text:
/**
 * @module EaselJS
 */

// namespace:
this.createjs = this.createjs||{};

(function() {
	"use strict";

/**
 * The MovieClip class associates a TweenJS Timeline with an EaselJS {{#crossLink "Container"}}{{/crossLink}}. It allows
 * you to create objects which encapsulate timeline animations, state changes, and synched actions. Due to the
 * complexities inherent in correctly setting up a MovieClip, it is largely intended for tool output and is not included
 * in the main EaselJS library.
 *
 * Currently MovieClip only works properly if it is tick based (as opposed to time based) though some concessions have
 * been made to support time-based timelines in the future.
 *
 *
Example

 * This example animates two shapes back and forth. The grey shape starts on the left, but we jump to a mid-point in
 * the animation using {{#crossLink "MovieClip/gotoAndPlay"}}{{/crossLink}}.
 *
 *      var stage = new createjs.Stage("canvas");
 *      createjs.Ticker.addEventListener("tick", stage);
 *
 *      var mc = new createjs.MovieClip(null, 0, true, {start:20});
 *      stage.addChild(mc);
 *
 *      var child1 = new createjs.Shape(
 *          new createjs.Graphics().beginFill("#999999")
 *              .drawCircle(30,30,30));
 *      var child2 = new createjs.Shape(
 *          new createjs.Graphics().beginFill("#5a9cfb")
 *              .drawCircle(30,30,30));
 *
 *      mc.timeline.addTween(
 *          createjs.Tween.get(child1)
 *              .to({x:0}).to({x:60}, 50).to({x:0}, 50));
 *      mc.timeline.addTween(
 *          createjs.Tween.get(child2)
 *              .to({x:60}).to({x:0}, 50).to({x:60}, 50));
 *
 *      mc.gotoAndPlay("start");
 *
 * It is recommended to use tween.to() to animate and set properties (use no duration to have it set
 * immediately), and the tween.wait() method to create delays between animations. Note that using the
 * tween.set() method to affect properties will likely not provide the desired result.
 *
 * @class MovieClip
 * @main MovieClip
 * @extends Container
 * @constructor
 * @param {String} [mode=independent] Initial value for the mode property. One of MovieClip.INDEPENDENT,
 * MovieClip.SINGLE_FRAME, or MovieClip.SYNCHED. The default is MovieClip.INDEPENDENT.
 * @param {Number} [startPosition=0] Initial value for the startPosition property.
 * @param {Boolean} [loop=true] Initial value for the loop property. The default is true.
 * @param {Object} [labels=null] A hash of labels to pass to the timeline instance associated with this MovieClip.
 * Labels only need to be passed if they need to be used.
 **/
var MovieClip = function(mode, startPosition, loop, labels) {
  this.initialize(mode, startPosition, loop, labels);
};
var p = MovieClip.prototype = new createjs.Container();

	/**
	 * The MovieClip will advance independently of its parent, even if its parent is paused.
	 * This is the default mode.
	 * @property INDEPENDENT
	 * @static
	 * @type String
	 * @default "independent"
	 * @readonly
	 **/
	MovieClip.INDEPENDENT = "independent";

	/**
	 * The MovieClip will only display a single frame (as determined by the startPosition property).
	 * @property SINGLE_FRAME
	 * @static
	 * @type String
	 * @default "single"
	 * @readonly
	 **/
	MovieClip.SINGLE_FRAME = "single";

	/**
	 * The MovieClip will be advanced only when its parent advances and will be synched to the position of
	 * the parent MovieClip.
	 * @property SYNCHED
	 * @static
	 * @type String
	 * @default "synched"
	 * @readonly
	 **/
	MovieClip.SYNCHED = "synched";

// public properties:

	/**
	 * Controls how this MovieClip advances its time. Must be one of 0 (INDEPENDENT), 1 (SINGLE_FRAME), or 2 (SYNCHED).
	 * See each constant for a description of the behaviour.
	 * @property mode
	 * @type String
	 * @default null
	 **/
	p.mode;

	/**
	 * Specifies what the first frame to play in this movieclip, or the only frame to display if mode is SINGLE_FRAME.
	 * @property startPosition
	 * @type Number
	 * @default 0
	 */
	p.startPosition = 0;

	/**
	 * Indicates whether this MovieClip should loop when it reaches the end of its timeline.
	 * @property loop
	 * @type Boolean
	 * @default true
	 */
	p.loop = true;

	/**
	 * The current frame of the movieclip.
	 * @property currentFrame
	 * @type Number
	 * @default 0
	 * @readonly
	 */
	p.currentFrame = 0;

	/**
	 * The TweenJS Timeline that is associated with this MovieClip. This is created automatically when the MovieClip
	 * instance is initialized. Animations are created by adding TweenJS Tween
	 * instances to the timeline.
	 *
	 *
Example

	 *      var tween = createjs.Tween.get(target).to({x:0}).to({x:100}, 30);
	 *      var mc = new createjs.MovieClip();
	 *      mc.timeline.addTween(tween);
	 *
	 * Elements can be added and removed from the timeline by toggling an "_off" property
	 * using the tweenInstance.to() method. Note that using Tween.set is not recommended to
	 * create MovieClip animations. The following example will toggle the target off on frame 0, and then back on for
	 * frame 1. You can use the "visible" property to achieve the same effect.
	 *
	 *      var tween = createjs.Tween.get(target).to({_off:false})
	 *          .wait(1).to({_off:true})
	 *          .wait(1).to({_off:false});
	 *
	 * @property timeline
	 * @type Timeline
	 * @default null
	 */
	p.timeline = null;

	/**
	 * If true, the MovieClip's position will not advance when ticked.
	 * @property paused
	 * @type Boolean
	 * @default false
	 */
	p.paused = false;

	/**
	 * If true, actions in this MovieClip's tweens will be run when the playhead advances.
	 * @property actionsEnabled
	 * @type Boolean
	 * @default true
	 */
	p.actionsEnabled = true;

	/**
	 * If true, the MovieClip will automatically be reset to its first frame whenever the timeline adds
	 * it back onto the display list. This only applies to MovieClip instances with mode=INDEPENDENT.
	 *

	 * For example, if you had a character animation with a "body" child MovieClip instance
	 * with different costumes on each frame, you could set body.autoReset = false, so that
	 * you can manually change the frame it is on, without worrying that it will be reset
	 * automatically.
	 * @property autoReset
	 * @type Boolean
	 * @default true
	 */
	p.autoReset = true;

	/**
	 * An array of bounds for each frame in the MovieClip. This is mainly intended for tool output.
	 * @property frameBounds
	 * @type Array
	 * @default null
	 */
	p.frameBounds = null;

// private properties:
	/**
	 * @property _synchOffset
	 * @type Number
	 * @default 0
	 * @private
	 */
	p._synchOffset = 0;

	/**
	 * @property _prevPos
	 * @type Number
	 * @default -1
	 * @private
	 */
	p._prevPos = -1; // TODO: evaluate using a ._reset Boolean prop instead of -1.

	/**
	 * @property _prevPosition
	 * @type Number
	 * @default 0
	 * @private
	 */
	p._prevPosition = 0;

	/**
	 * List of display objects that are actively being managed by the MovieClip.
	 * @property _managed
	 * @type Object
	 * @private
	 */
	p._managed;

// constructor:

	/**
	 * @property DisplayObject_initialize
	 * @type Function
    * @private
	 **/
	p.Container_initialize = p.initialize;

	/**
	 * Initialization method called by the constructor.
	 * @method initialize
	 * @param {String} [mode=independent] Initial value for the mode property. One of MovieClip.INDEPENDENT,
	 * MovieClip.SINGLE_FRAME, or MovieClip.SYNCHED. The default is MovieClip.INDEPENDENT.
	 * @param {Number} [startPosition=0] Initial value for the startPosition property.
	 * @param {Boolean} [loop=true] Initial value for the loop property. The default is true.
	 * @param {Object} [labels=null] A hash of labels to pass to the timeline instance associated with this MovieClip.
	 * Labels only need to be passed if they need to be used.
	 * @protected
	 **/
	p.initialize = function(mode, startPosition, loop, labels) {
		this.mode = mode||MovieClip.INDEPENDENT;
		this.startPosition = startPosition || 0;
		this.loop = loop;
		var props = {paused:true, position:startPosition, useTicks:true};
		this.Container_initialize();
		this.timeline = new createjs.Timeline(null, labels, props);
		this._managed = {};
	};

// public methods:
	/**
	 * Returns true or false indicating whether the display object would be visible if drawn to a canvas.
	 * This does not account for whether it would be visible within the boundaries of the stage.
	 * NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
	 * @method isVisible
	 * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas
	 **/
	p.isVisible = function() {
		// children are placed in draw, so we can't determine if we have content.
		return !!(this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0);
	};

	/**
	 * @property Container_draw
	 * @type Function
	 * @private
	 **/
	p.Container_draw = p.draw;

	/**
	 * Draws the display object into the specified context ignoring its visible, alpha, shadow, and transform.
	 * Returns true if the draw was handled (useful for overriding functionality).
	 * NOTE: This method is mainly for internal use, though it may be useful for advanced uses.
	 * @method draw
	 * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into.
	 * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache.
	 * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back
	 * into itself).
	 **/
	p.draw = function(ctx, ignoreCache) {
		// draw to cache first:
		if (this.DisplayObject_draw(ctx, ignoreCache)) { return true; }
		this._updateTimeline();
		this.Container_draw(ctx, ignoreCache);
		return true;
	};

	/**
	 * Sets paused to false.
	 * @method play
	 **/
	p.play = function() {
		this.paused = false;
	};

	/**
	 * Sets paused to true.
	 * @method stop
	 **/
	p.stop = function() {
		this.paused = true;
	};

	/**
	 * Advances this movie clip to the specified position or label and sets paused to false.
	 * @method gotoAndPlay
	 * @param {String|Number} positionOrLabel The animation name or frame number to go to.
	 **/
	p.gotoAndPlay = function(positionOrLabel) {
		this.paused = false;
		this._goto(positionOrLabel);
	};

	/**
	 * Advances this movie clip to the specified position or label and sets paused to true.
	 * @method gotoAndStop
	 * @param {String|Number} positionOrLabel The animation or frame name to go to.
	 **/
	p.gotoAndStop = function(positionOrLabel) {
		this.paused = true;
		this._goto(positionOrLabel);
	};

	/**
	 * Returns a sorted list of the labels defined on this MovieClip. Shortcut to TweenJS: Timeline.getLabels();
	 * @method getLabels
	 * @return {Array[Object]} A sorted array of objects with label and position (aka frame) properties.
	 **/
	p.getLabels = function() {
		return this.timeline.getLabels();
	};

	/**
	 * Returns the name of the label on or immediately before the current frame. See TweenJS: Timeline.getCurrentLabel()
	 * for more information.
	 * @method getCurrentLabel
	 * @return {String} The name of the current label or null if there is no label.
	 **/
	p.getCurrentLabel = function() {
		this._updateTimeline();
		return this.timeline.getCurrentLabel();
	};

	/**
	 * MovieClip instances cannot be cloned.
	 * @method clone
	 **/
	p.clone = function() {
		// TODO: add support for this? Need to clone the Timeline & retarget tweens - pretty complex.
		throw("MovieClip cannot be cloned.")
	};

	/**
	 * Returns a string representation of this object.
	 * @method toString
	 * @return {String} a string representation of the instance.
	 **/
	p.toString = function() {
		return "[MovieClip (name="+  this.name +")]";
	};

// private methods:

	/**
	 * @property Container__tick
	 * @type Function
	 * @protected
	 **/
	p.Container__tick = p._tick;

	/**
	 * @method _tick
	 * @param {Array} params Parameters to pass onto the DisplayObject {{#crossLink "DisplayObject/tick"}}{{/crossLink}}
	 * function.
	 * @protected
	 **/
	p._tick = function(params) {
		if (!this.paused && this.mode == MovieClip.INDEPENDENT) {
			this._prevPosition = (this._prevPos < 0) ? 0 : this._prevPosition+1;
			this._updateTimeline();
		}
		this.Container__tick(params);
	};

	/**
	 * @method _goto
	 * @param {String|Number} positionOrLabel The animation name or frame number to go to.
	 * @protected
	 **/
	p._goto = function(positionOrLabel) {
		var pos = this.timeline.resolve(positionOrLabel);
		if (pos == null) { return; }
		// prevent _updateTimeline from overwriting the new position because of a reset:
		if (this._prevPos == -1) { this._prevPos = NaN; }
		this._prevPosition = pos;
		this._updateTimeline();
	};

	/**
	 * @method _reset
	 * @private
	 **/
	p._reset = function() {
		this._prevPos = -1;
		this.currentFrame = 0;
	};

	/**
	 * @method _updateTimeline
	 * @protected
	 **/
	p._updateTimeline = function() {
		var tl = this.timeline;
		var synched = this.mode != MovieClip.INDEPENDENT;
		tl.loop = (this.loop==null) ? true : this.loop;

		// update timeline position, ignoring actions if this is a graphic.
		if (synched) {
			tl.setPosition(this.startPosition + (this.mode==MovieClip.SINGLE_FRAME?0:this._synchOffset), createjs.Tween.NONE);
		} else {
			tl.setPosition(this._prevPos < 0 ? 0 : this._prevPosition, this.actionsEnabled ? null : createjs.Tween.NONE);
		}

		this._prevPosition = tl._prevPosition;
		if (this._prevPos == tl._prevPos) { return; }
		this.currentFrame = this._prevPos = tl._prevPos;

		for (var n in this._managed) { this._managed[n] = 1; }

		var tweens = tl._tweens;
		for (var i=0, l=tweens.length; i<l; i++) {
			var tween = tweens[i];
			var target = tween._target;
			if (target == this || tween.passive) { continue; } // TODO: this assumes actions tween has this as the target. Valid?
			var offset = tween._stepPosition;

			if (target instanceof createjs.DisplayObject) {
				// motion tween.
				this._addManagedChild(target, offset);
			} else {
				// state tween.
				this._setState(target.state, offset);
			}
		}

		var kids = this.children;
		for (i=kids.length-1; i>=0; i--) {
			var id = kids[i].id;
			if (this._managed[id] == 1) {
				this.removeChildAt(i);
				delete(this._managed[id]);
			}
		}
	};

	/**
	 * @method _setState
	 * @param {Array} state
	 * @param {Number} offset
	 * @protected
	 **/
	p._setState = function(state, offset) {
		if (!state) { return; }
		for (var i=state.length-1;i>=0;i--) {
			var o = state[i];
			var target = o.t;
			var props = o.p;
			for (var n in props) { target[n] = props[n]; }
			this._addManagedChild(target, offset);
		}
	};

	/**
	 * Adds a child to the timeline, and sets it up as a managed child.
	 * @method _addManagedChild
	 * @param {MovieClip} child The child MovieClip to manage
	 * @param {Number} offset
	 * @private
	 **/
	p._addManagedChild = function(child, offset) {
		if (child._off) { return; }
		this.addChildAt(child,0);

		if (child instanceof MovieClip) {
			child._synchOffset = offset;
			// TODO: this does not precisely match Flash. Flash loses track of the clip if it is renamed or removed from the timeline, which causes it to reset.
			if (child.mode == MovieClip.INDEPENDENT && child.autoReset && !this._managed[child.id]) { child._reset(); }
		}
		this._managed[child.id] = 2;
	};

	/**
	 * @method Container__getBounds
	 * @param {Matrix2D} matrix
	 * @param {Boolean} ignoreTransform
	 * @return {Rectangle}
	 * @protected
	 **/
	p.Container__getBounds = p._getBounds;

	/**
	 * @method _getBounds
	 * @param {Matrix2D} matrix
	 * @param {Boolean} ignoreTransform
	 * @return {Rectangle}
	 * @protected
	 **/
	p._getBounds = function(matrix, ignoreTransform) {
		var bounds = this.DisplayObject_getBounds();
		if (!bounds) {
			this._updateTimeline();
			if (this.frameBounds) { bounds = this._rectangle.copy(this.frameBounds[this.currentFrame]); }
		}
		if (bounds) { return this._transformBounds(bounds, matrix, ignoreTransform); }
		return this.Container__getBounds(matrix, ignoreTransform);
	};

createjs.MovieClip = MovieClip;

	/**
	 * This plugin works with TweenJS to prevent the startPosition
	 * property from tweening.
	 * @private
	 * @class MovieClipPlugin
	 * @constructor
	 **/
	var MovieClipPlugin = function() {
	  throw("MovieClipPlugin cannot be instantiated.")
	};

	/**
	 * @method priority
	 * @private
	 **/
	MovieClipPlugin.priority = 100; // very high priority, should run first

	/**
	 * @method install
	 * @private
	 **/
	MovieClipPlugin.install = function() {
		createjs.Tween.installPlugin(MovieClipPlugin, ["startPosition"]);
	};

	/**
	 * @method init
	 * @param {Tween} tween
	 * @param {String} prop
	 * @param {String|Number|Boolean} value
	 * @private
	 **/
	MovieClipPlugin.init = function(tween, prop, value) {
		return value;
	};

	/**
	 * @method step
	 * @private
	 **/
	MovieClipPlugin.step = function() {
		// unused.
	};

	/**
	 * @method tween
	 * @param {Tween} tween
	 * @param {String} prop
	 * @param {String | Number | Boolean} value
	 * @param {Array} startValues
	 * @param {Array} endValues
	 * @param {Number} ratio
	 * @param {Object} wait
	 * @param {Object} end
	 * @return {*}
	 */
	MovieClipPlugin.tween = function(tween, prop, value, startValues, endValues, ratio, wait, end) {
		if (!(tween.target instanceof MovieClip)) { return value; }
		return (ratio == 1 ? endValues[prop] : startValues[prop]);
	};

	MovieClipPlugin.install();

}());


text:
<!doctype html>

<title>CodeMirror: Match Highlighter Demo</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../doc/docs.css">

<link rel="stylesheet" href="../lib/codemirror.css">

CodeMirror

Home

Manual

Code

Match Highlighter

Match Highlighter Demo

<form><textarea id="code" name="code">Select this text: hardToSpotVar
	And everywhere else in your code where hardToSpotVar appears will automatically illuminate.
Give it a try!  No more hardToSpotVars.</textarea></form>

Search and highlight occurences of the selected text.

redpajama_set_name: RedPajamaGithub


text:
"""Backend compiler related feature registration"""
# pylint: disable=invalid-name,unused-argument, len-as-condition, too-many-nested-blocks,
# pylint: disable=too-many-local-variables, too-many-arguments, no-else-return

from __future__ import absolute_import

import tvm
from tvm import te, topi
from tvm.runtime import convert
from tvm.te.hybrid import script
from tvm.topi.utils import get_const_int, get_const_tuple

from . import op as _reg
from . import strategy
from ._tensor import elemwise_shape_func
from .op import OpPattern

_reg.register_broadcast_schedule("broadcast_to")
_reg.register_broadcast_schedule("broadcast_to_like")
_reg.register_broadcast_schedule("expand_dims")
_reg.register_broadcast_schedule("repeat")
_reg.register_broadcast_schedule("tile")
_reg.register_broadcast_schedule("where")
_reg.register_injective_schedule("squeeze")
_reg.register_injective_schedule("reshape")
_reg.register_injective_schedule("reshape_like")
_reg.register_injective_schedule("full")
_reg.register_injective_schedule("full_like")
_reg.register_injective_schedule("arange")
_reg.register_injective_schedule("meshgrid")
_reg.register_injective_schedule("reverse")
_reg.register_injective_schedule("reverse_sequence")
_reg.register_injective_schedule("cast")
_reg.register_injective_schedule("cast_like")
_reg.register_injective_schedule("reinterpret")
_reg.register_injective_schedule("strided_slice")
_reg.register_injective_schedule("slice_like")
_reg.register_injective_schedule("split")
_reg.register_injective_schedule("take")
_reg.register_injective_schedule("stack")
_reg.register_injective_schedule("contrib_reverse_reshape")
_reg.register_injective_schedule("gather")
_reg.register_injective_schedule("gather_nd")
_reg.register_injective_schedule("sequence_mask")
_reg.register_injective_schedule("one_hot")
_reg.register_reduce_schedule("collapse_sum_like")
_reg.register_reduce_schedule("collapse_sum_to")
_reg.register_injective_schedule("unravel_index")
_reg.register_injective_schedule("sparse_to_dense")
_reg.register_injective_schedule("matrix_set_diag")
_reg.register_injective_schedule("adv_index")

# concatenate
_reg.register_schedule("concatenate", strategy.schedule_concatenate)

# strided_set
@_reg.register_compute("strided_set")
def compute_strided_set(attrs, inputs, output_type):
    """Compute definition of strided_set"""
    return [topi.strided_set(inputs[0], inputs[1], inputs[2], inputs[3], inputs[4])]

_reg.register_injective_schedule("strided_set")

# layout_transform
_reg.register_injective_schedule("layout_transform")
_reg.register_pattern("layout_transform", OpPattern.INJECTIVE)
_reg.register_injective_schedule("auto_scheduler_layout_transform")
_reg.register_pattern("auto_scheduler_layout_transform", OpPattern.INJECTIVE)

# argwhere
_reg.register_strategy("argwhere", strategy.argwhere_strategy)

# scatter
@_reg.register_compute("scatter")
def compute_scatter(attrs, inputs, output_type):
    """Compute definition of scatter"""
    return [topi.scatter(inputs[0], inputs[1], inputs[2], attrs.axis)]

_reg.register_strategy("scatter", strategy.scatter_strategy)

# sparse_fill_empty_rows
@_reg.register_compute("sparse_fill_empty_rows")
def compute_sparse_fill_empty_rows(attrs, inputs, output_type):
    """Compute definition of sparse_fill_empty_rows"""

    return topi.sparse_fill_empty_rows(
        inputs[0],
        inputs[1],
        inputs[2],
        inputs[3],
        output_type.fields[0].shape,
        output_type.fields[1].shape,
        output_type.fields[2].shape,
    )

_reg.register_strategy("sparse_fill_empty_rows", strategy.sparse_fill_empty_rows_strategy)

# sparse_reshape
@_reg.register_compute("sparse_reshape")
def compute_reshape(attrs, inputs, output_type):
    """Compute definition of sparse_reshape"""

    return topi.sparse_reshape(
        inputs[0],
        inputs[1],
        inputs[2],
        output_type.fields[0].shape,
        output_type.fields[1].shape,
    )

_reg.register_strategy("sparse_reshape", strategy.sparse_reshape_strategy)

# scatter_add
@_reg.register_compute("scatter_add")
def compute_scatter_add(attrs, inputs, output_type):
    """Compute definition of scatter_add"""
    return [topi.scatter_add(inputs[0], inputs[1], inputs[2], attrs.axis)]

_reg.register_strategy("scatter_add", strategy.scatter_add_strategy)

# scatter_nd
@_reg.register_compute("scatter_nd")
def compute_scatter_nd(attrs, inputs, output_type):
    """Compute definition of scatter_nd"""
    return [topi.scatter_nd(inputs[0], inputs[1], inputs[2], attrs.mode)]

_reg.register_strategy("scatter_nd", strategy.scatter_nd_strategy)

# cumsum
@_reg.register_compute("cumsum")
def compute_cumsum(attrs, inputs, output_type):
    """Compute definition of cumsum"""
    return [topi.cumsum(inputs[0], attrs.axis, attrs.dtype, attrs.exclusive)]

_reg.register_strategy("cumsum", strategy.cumsum_strategy)
_reg.register_shape_func("cumsum", False, elemwise_shape_func)

# cumprod
@_reg.register_compute("cumprod")
def compute_cumprod(attrs, inputs, output_type):
    """Compute definition of cumprod"""
    return [topi.cumprod(inputs[0], attrs.axis, attrs.dtype, attrs.exclusive)]

_reg.register_strategy("cumprod", strategy.cumprod_strategy)
_reg.register_shape_func("cumprod", False, elemwise_shape_func)

@_reg.register_compute("unique")
def compute_unique(attrs, inputs, output_type):
    """Compute definition of unique"""
    return topi.unique(inputs[0], attrs.sorted, attrs.return_counts)

_reg.register_strategy("unique", strategy.unique_strategy)

# invert_permutation
_reg.register_strategy("invert_permutation", strategy.invert_permutation_strategy)
_reg.register_shape_func("invert_permutation", False, elemwise_shape_func)

#####################
#  Shape functions  #
#####################

@script
def _arange_shape_func(start, stop, step):
    out = output_tensor((1,), "int64")
    if step[0] < 0:
        out[0] = int64(ceil_div((int64(start[0]) - int64(stop[0])), int64(-step[0])))
    else:
        out[0] = int64(ceil_div((int64(stop[0]) - int64(start[0])), int64(step[0])))
    return out

@_reg.register_shape_func("arange", True)
def arange_shape_func(attrs, inputs, _):
    """
    Shape func for arange
    """
    return [_arange_shape_func(*inputs)]

@script
def _strided_slice_shape_func_input_shape(data_shape, begin, end, strides, slice_mode):
    ndim = data_shape.shape[0]
    out = output_tensor((ndim,), "int64")
    for i in const_range(ndim):
        cbegin = int64(0)
        cend = int64(data_shape[i])
        cstride = int64(1)
        if len(strides) > i:
            cstride = int64(strides[i])
        if len(begin) > i:
            cbegin = int64(begin[i])
            if cbegin < 0:
                cbegin += int64(data_shape[i])
        if len(end) <= i:
            cend = int64(data_shape[i])
        elif slice_mode != 0:
            cstride = int64(1)
            if end[i] < 0:
                cend = int64(data_shape[i])
            else:
                cend = cbegin + int64(end[i])
        else:
            if end[i] > data_shape[i]:
                cend = int64(data_shape[i])
            elif end[i] < -data_shape[i]:
                cend = int64(-1)
            else:
                cend = int64(end[i])
                if cend < 0:
                    cend += int64(data_shape[i])
        assert cstride != 0, "Strides can't be zero."
        if cstride < 0:
            slice_range = cbegin - cend
            step = -cstride
        else:
            slice_range = cend - cbegin
            step = cstride

        out[i] = int64(ceil_div(slice_range, step))
    return out

@script
def _strided_slice_shape_func_with_axes(data_shape, begin, end, strides, slice_mode, axes):
    ndim = data_shape.shape[0]
    out = output_tensor((ndim,), "int64")
    for i in const_range(ndim):
        out[i] = data_shape[i]

    for i in const_range(len(axes)):
        cbegin = int64(0)
        cend = int64(data_shape[axes[i]])
        cstride = int64(1)
        if len(strides) > i:
            cstride = int64(strides[i])
        if len(begin) > i:
            cbegin = int64(begin[i])
            if cbegin < 0:
                cbegin += int64(data_shape[axes[i]])
        if len(end) <= i:
            cend = int64(data_shape[axes[i]])
        elif slice_mode != 0:
            cstride = int64(1)
            if end[i] < 0:
                cend = int64(data_shape[axes[i]])
            else:
                cend = cbegin + int64(end[i])
        else:
            if end[i] > data_shape[i]:
                cend = int64(data_shape[axes[i]])
            elif end[i] < -data_shape[i]:
                cend = int64(-1)
            else:
                cend = int64(end[i])
                if cend < 0:
                    cend += int64(data_shape[axes[i]])
        assert cstride != 0, "Strides can't be zero."
        if cstride < 0:
            slice_range = cbegin - cend
            step = -cstride
        else:
            slice_range = cend - cbegin
            step = cstride

        out[axes[i]] = int64(ceil_div(slice_range, step))
    return out

@_reg.register_shape_func("strided_slice", False)
def strided_slice_shape_func(attrs, inputs, _):
    """
    Shape func for strided_slice
    """
    slice_mode = convert(0 if attrs.slice_mode == "end" else 1)
    if attrs.axes is None:
        return [
            _strided_slice_shape_func_input_shape(
                inputs[0], attrs.begin, attrs.end, attrs.strides, slice_mode
            )
        ]
    return [
        _strided_slice_shape_func_with_axes(
            inputs[0], attrs.begin, attrs.end, attrs.strides, slice_mode, attrs.axes
        )
    ]

@script
def _one_hot_shape_func(indices_shape, depth, axis):
    in_ndim = indices_shape.shape[0]
    out_ndim = in_ndim + 1
    true_axis = in_ndim if axis == -1 else axis
    indices_i = 0
    out = output_tensor((out_ndim,), "int64")
    for i in range(out_ndim):
        if i == true_axis:
            out[i] = int64(depth)
        else:
            out[i] = int64(indices_shape[indices_i])
            indices_i += 1
    return out

@_reg.register_shape_func("one_hot", False)
def one_hot_shape_func(attrs, inputs, _):
    """
    Shape func for one_hot
    """
    shape_func = [_one_hot_shape_func(inputs[0], convert(attrs.depth), convert(attrs.axis))]
    return shape_func

@script
def _concatenate_shape_func(inputs, axis):
    ndim = inputs[0].shape[0]
    out = output_tensor((ndim,), "int64")
    for i in const_range(ndim):
        if i != axis:
            out[i] = inputs[0][i]
            for j in const_range(1, len(inputs)):
                assert out[i] == inputs[j][i], "Dims mismatch in the inputs of concatenate."
        else:
            out[i] = int64(0)
            for j in const_range(len(inputs)):
                out[i] += inputs[j][i]
    return out

@_reg.register_shape_func("concatenate", False)
def concatenate_shape_func(attrs, inputs, _):
    axis = get_const_int(attrs.axis)
    if axis < 0:
        axis += inputs[0].shape[0]
    return [_concatenate_shape_func(inputs, convert(axis))]

@script
def _reshape_shape_func_input_shape(data_shape, newshape, ndim):
    out = output_tensor((ndim,), "int64")
    src_idx = 0
    dst_idx = 0
    infer_idx = -1
    copy = False
    skip = 0
    for i in const_range(len(newshape)):
        if skip > 0:
            skip -= 1
        elif newshape[i] > 0:
            out[dst_idx] = int64(newshape[i])
            src_idx += 1
            dst_idx += 1
        elif newshape[i] == 0:
            out[dst_idx] = data_shape[src_idx]
            src_idx += 1
            dst_idx += 1
        elif newshape[i] == -1:
            assert infer_idx < 0, "One and only one dim can be inferred"
            out[dst_idx] = int64(1)
            infer_idx = i
            dst_idx += 1
        elif newshape[i] == -2:
            copy = True
        elif newshape[i] == -3:
            assert data_shape.shape[0] - src_idx > 1, "Not enough dims in input shape for -3"
            out[dst_idx] = data_shape[src_idx] * data_shape[src_idx + 1]
            src_idx += 2
            dst_idx += 1
        elif newshape[i] == -4:
            assert len(newshape) - i > 2, "Not enough dims in new shape for -4"
            if newshape[i + 1] == -1:
                assert newshape[i + 2] != -1, "Split dims cannot both be -1."
                out[dst_idx] = data_shape[src_idx] // int64(newshape[i + 2])
                out[dst_idx + 1] = int64(newshape[i + 2])
            else:
                out[dst_idx] = int64(newshape[i + 1])
                if newshape[i + 2] == -1:
                    out[dst_idx + 1] = data_shape[src_idx] // int64(newshape[i + 1])
                else:
                    out[dst_idx + 1] = int64(newshape[i + 2])
            assert (
                data_shape[src_idx] == out[dst_idx] * out[dst_idx + 1]
            ), "Product of split dims doesn't match to input dim"
            src_idx += 1
            dst_idx += 2
            skip = 2
        else:
            assert False, "Invalid special values in new shape"
    if len(data_shape.shape) > 0:
        # if data is not constant, we can then handle -1 and -2
        if copy:
            for i in range(src_idx, data_shape.shape[0]):
                out[dst_idx] = data_shape[i]
                dst_idx += 1
        if infer_idx >= 0:
            old_size = int64(1)
            for i in const_range(data_shape.shape[0]):
                old_size *= data_shape[i]
            new_size = int64(1)
            for i in const_range(out.shape[0]):
                new_size *= out[i]
            out[infer_idx] = old_size // new_size
    return out

@_reg.register_shape_func("reshape", False)
def reshape_shape_func(attrs, inputs, out_ndims):
    newshape = get_const_tuple(attrs.newshape)
    return [_reshape_shape_func_input_shape(inputs[0], convert(newshape), out_ndims[0])]

@script
def _take_no_axis_shape_func(indices_shape, out_ndim):
    out = output_tensor((out_ndim,), "int64")
    for i in const_range(out_ndim):
        out[i] = indices_shape[i]
    return out

@script
def _take_with_axis_shape_func(data_shape, indices_shape, axis, batch_dims, out_ndim):
    out = output_tensor((out_ndim,), "int64")
    for i in const_range(axis):
        out[i] = data_shape[i]
    if len(indices_shape.shape) == 0:
        # indices is constant
        for i in const_range(axis + 1, len(data_shape)):
            out[i - 1] = data_shape[i]
    else:
        for i in const_range(len(indices_shape) - batch_dims):
            out[axis + i] = indices_shape[i + batch_dims]
        for i in const_range(axis + 1, len(data_shape)):
            out[len(indices_shape) + i - 1 - batch_dims] = data_shape[i]
    return out

@_reg.register_shape_func("take", False)
def take_shape_func(attrs, inputs, out_ndims):
    """
    Shape function for take op.
    """
    if attrs.axis is None:
        return [_take_no_axis_shape_func(inputs[1], out_ndims[0])]
    axis = get_const_int(attrs.axis)
    batch_dims = get_const_int(attrs.batch_dims)
    data_ndim = int(inputs[0].shape[0])
    if inputs[1].shape:
        indicies_ndim = int(inputs[1].shape[0])
    if axis < 0:
        axis += data_ndim
    assert 0 <= axis < data_ndim
    if batch_dims < 0:
        batch_dims += indicies_ndim
    return [_take_with_axis_shape_func(*inputs, convert(axis), convert(batch_dims), out_ndims[0])]

@_reg.register_legalize("take")
def legalize_dyn_topk(attrs, inputs, types):
    """Legalize take op.
    Parameters
    ----------
    attrs : tvm.ir.Attrs
        Attributes of current op
    inputs : list of tvm.relay.Expr
        The args of the Relay expr to be legalized
    types : list of types
        List of input and output types
    Returns
    -------
    result : tvm.relay.Expr
        The legalized expr
    """
    return topi.take_legalize(attrs, inputs, types)

@script
def _argwhere_shape_func_1d(condition):
    out = output_tensor((2,), "int64")
    out[0] = int64(0)
    out[1] = int64(1)
    for i1 in range(condition.shape[0]):
        if condition[i1] != 0:
            out[0] += int64(1)
    return out

@script
def _argwhere_shape_func_2d(condition):
    out = output_tensor((2,), "int64")
    out[0] = int64(0)
    out[1] = int64(2)
    for i1 in range(condition.shape[0]):
        for i2 in range(condition.shape[1]):
            if condition[i1, i2] != 0:
                out[0] += int64(1)
    return out

@script
def _argwhere_shape_func_3d(condition):
    out = output_tensor((2,), "int64")
    out[0] = int64(0)
    out[1] = int64(3)
    for i1 in range(condition.shape[0]):
        for i2 in range(condition.shape[1]):
            for i3 in range(condition.shape[2]):
                if condition[i1, i2, i3] != 0:
                    out[0] += int64(1)
    return out

@script
def _argwhere_shape_func_4d(condition):
    out = output_tensor((2,), "int64")
    out[0] = int64(0)
    out[1] = int64(4)
    for i1 in range(condition.shape[0]):
        for i2 in range(condition.shape[1]):
            for i3 in range(condition.shape[2]):
                for i4 in range(condition.shape[3]):
                    if condition[i1, i2, i3, i4] != 0:
                        out[0] += int64(1)
    return out

@script
def _argwhere_shape_func_5d(condition):
    out = output_tensor((2,), "int64")
    out[0] = int64(0)
    out[1] = int64(5)
    for i1 in range(condition.shape[0]):
        for i2 in range(condition.shape[1]):
            for i3 in range(condition.shape[2]):
                for i4 in range(condition.shape[3]):
                    for i5 in range(condition.shape[4]):
                        if condition[i1, i2, i3, i4, i5] != 0:
                            out[0] += int64(1)
    return out

@_reg.register_shape_func("argwhere", True)
def argwhere_shape_func(attrs, inputs, out_ndims):
    """
    Shape function for argwhere.
    """
    if len(inputs[0].shape) == 1:
        return [_argwhere_shape_func_1d(inputs[0])]
    if len(inputs[0].shape) == 2:
        return [_argwhere_shape_func_2d(inputs[0])]
    if len(inputs[0].shape) == 3:
        return [_argwhere_shape_func_3d(inputs[0])]
    if len(inputs[0].shape) == 4:
        return [_argwhere_shape_func_4d(inputs[0])]
    if len(inputs[0].shape) == 5:
        return [_argwhere_shape_func_5d(inputs[0])]
    return ValueError("Does not support rank higher than 5 in argwhere")

_reg.register_shape_func("scatter", False, elemwise_shape_func)
_reg.register_shape_func("scatter_add", False, elemwise_shape_func)

@script
def _sparse_fill_empty_rows_shape_func(sparse_indices, dense_shape):

    new_sparse_indices_shape = output_tensor((2,), "int64")
    new_sparse_values_shape = output_tensor((1,), "int64")
    empty_row_indicator_shape = output_tensor((1,), "int64")
    num_dense_rows = int64(dense_shape[0])

    if int64(sparse_indices.shape[0]) == int64(0):  # Handle Empty Case
        #  Total rows will equal dense_shape[0]
        new_sparse_indices_shape[0] = num_dense_rows
        new_sparse_indices_shape[1] = int64(sparse_indices.shape[1])
        new_sparse_values_shape[0] = num_dense_rows
        empty_row_indicator_shape[0] = num_dense_rows
        return (new_sparse_indices_shape, new_sparse_values_shape, empty_row_indicator_shape)

    else:
        count = int64(sparse_indices.shape[0])  # Add count of all rows already in sparse_indices
        for i in range(1, int64(sparse_indices.shape[0])):
            index = int64(sparse_indices[i, 0])
            prev_index = int64(sparse_indices[i - 1, 0] + 1)

            if index > prev_index:
                count += index - prev_index  # Add count of all rows between two consecutive indices

        count += int64(sparse_indices[0, 0])  # Add count from 0 to first row id in sparse_indices
        count += int64(
            num_dense_rows - 1 - sparse_indices[sparse_indices.shape[0] - 1, 0]
        )  # Add count from last row id to dense_shape - 1
        new_sparse_indices_shape[0] = int64(count)
        new_sparse_indices_shape[1] = int64(sparse_indices.shape[1])
        new_sparse_values_shape[0] = int64(count)
        empty_row_indicator_shape[0] = num_dense_rows
        return (new_sparse_indices_shape, new_sparse_values_shape, empty_row_indicator_shape)

@_reg.register_shape_func("sparse_fill_empty_rows", True)
def sparse_fill_empty_rows_func(attrs, inputs, _):
    return _sparse_fill_empty_rows_shape_func(inputs[0], inputs[2])

@script
def _sparse_reshape_shape_func(sparse_indices_shape, prev_shape_shape, new_shape_shape):
    indices_shape = output_tensor((2,), "int64")
    indices_shape[0] = int64(sparse_indices_shape[0])
    indices_shape[1] = int64(new_shape_shape[0])
    shape_tensor = output_tensor((1,), "int64")
    shape_tensor[0] = int64(new_shape_shape[0])
    return (indices_shape, shape_tensor)

@_reg.register_shape_func("sparse_reshape", False)
def sparse_reshape_shape_func(attrs, inputs, _):
    """
    Shape func for sparse_reshape.
    """
    return _sparse_reshape_shape_func(inputs[0], inputs[1], inputs[2])

@script
def _layout_transform_shape_func(
    data_shape, out_layout_len, dst_equal_list, dst_mul_list, dst_div_list, dst_mix_list
):
    out = output_tensor((out_layout_len,), "int64")
    for i in const_range(len(dst_equal_list)):
        out[dst_equal_list[i][0]] = data_shape[dst_equal_list[i][1]]
    for i in const_range(len(dst_mul_list)):
        out[dst_mul_list[i][0]] = data_shape[dst_mul_list[i][1]] * data_shape[dst_mul_list[i][2]]
    for i in const_range(len(dst_div_list)):
        out[dst_div_list[i][0]] = data_shape[dst_div_list[i][1]] // dst_div_list[i][3]
        out[dst_div_list[i][2]] = int64(dst_div_list[i][3])
    for i in const_range(len(dst_mix_list)):
        out[dst_mix_list[i][0]] = (
            data_shape[dst_mix_list[i][1]] * dst_mix_list[i][2] // dst_mix_list[i][4]
        )
        out[dst_mix_list[i][3]] = int64(dst_mix_list[i][4])

    return out

@_reg.register_shape_func("layout_transform", False)
def layout_transform_shape_func(attrs, inputs, _):
    """
    Shape function for layout_transform op.
    """

    def _fetch_axis(layout):
        major_axes = []
        minor_axes = {}
        num_start = -1
        for i, item in enumerate(layout):
            if "A" <= item <= "Z":
                major_axes.append(item)
            elif "a" <= item <= "z":
                last_num = int(layout[num_start:i])
                minor_axes[item] = last_num
                num_start = -1
            elif num_start < 0:
                num_start = i
        return major_axes, minor_axes

    _, src_minor_axes = _fetch_axis(attrs.src_layout)
    dst_major_axes, dst_minor_axes = _fetch_axis(attrs.dst_layout)
    src_letter_list = []
    dst_letter_list = []
    for item in attrs.src_layout:
        if "A" <= item <= "Z" or "a" <= item <= "z":
            src_letter_list.append(item)
    for item in attrs.dst_layout:
        if "A" <= item <= "Z" or "a" <= item <= "z":
            dst_letter_list.append(item)
    out_layout_len = len(dst_major_axes) + len(dst_minor_axes)
    dst_equal_list = []
    dst_mul_list = []
    dst_div_list = []
    dst_mix_list = []

    for key in dst_major_axes:
        if key.lower() not in dst_minor_axes:
            if key.lower() not in src_minor_axes:
                dst_equal_list.append((dst_letter_list.index(key), src_letter_list.index(key)))
            else:
                dst_mul_list.append(
                    (
                        dst_letter_list.index(key),
                        src_letter_list.index(key),
                        src_letter_list.index(key.lower()),
                    )
                )
        else:
            if key.lower() not in src_minor_axes:
                dst_div_list.append(
                    (
                        dst_letter_list.index(key),
                        src_letter_list.index(key),
                        dst_letter_list.index(key.lower()),
                        dst_minor_axes[key.lower()],
                    )
                )
            else:
                dst_mix_list.append(
                    (
                        dst_letter_list.index(key),
                        src_letter_list.index(key),
                        src_minor_axes[key.lower()],
                        dst_letter_list.index(key.lower()),
                        dst_minor_axes[key.lower()],
                    )
                )

    return [
        _layout_transform_shape_func(
            inputs[0],
            convert(out_layout_len),
            convert(dst_equal_list),
            convert(dst_mul_list),
            convert(dst_div_list),
            convert(dst_mix_list),
        )
    ]

@script
def _expand_dim_shape_func(data_shape, ndim, axis, num_newaxis):
    out = output_tensor((ndim + num_newaxis,), "int64")
    for i in const_range(out.shape[0]):
        if i < axis:
            out[i] = data_shape[i]
        elif i < axis + num_newaxis:
            out[i] = int64(1)
        else:
            out[i] = data_shape[i - num_newaxis]

    return out

@_reg.register_shape_func("expand_dims", False)
def expand_dim_shape_func(attrs, inputs, _):
    """
    Shape function for expand_dim op.
    """
    axis = get_const_int(attrs.axis)
    num_newaxis = get_const_int(attrs.num_newaxis)
    if axis < 0:
        axis = inputs[0].shape[0] + axis + 1
    ndim = inputs[0].shape[0] if inputs[0].shape else 0
    return [_expand_dim_shape_func(inputs[0], convert(ndim), convert(axis), convert(num_newaxis))]

@script
def _transpose_shape_func(data_shape, axes):
    out = output_tensor((data_shape.shape[0],), "int64")
    for i in const_range(len(axes)):
        out[i] = data_shape[axes[i]]

    return out

@_reg.register_shape_func("transpose", False)
def transpose_shape_func(attrs, inputs, _):
    """
    Shape function for transpose op.
    """
    axes = attrs.axes if attrs.axes is None else get_const_tuple(attrs.axes)
    if axes is None:
        axes = list(range(inputs[0].shape[0].value))
        axes.reverse()
    axes = list(axes)
    for i, axis in enumerate(axes):
        if axis < 0:
            axes[i] = inputs[0].shape[0] + axis
    return [_transpose_shape_func(inputs[0], convert(axes))]

_reg.register_schedule("transpose", strategy.schedule_transpose)

@script
def _squeeze_shape_func(data_shape, keep_axes, remove_axes):
    out = output_tensor((len(keep_axes),), "int64")
    for i in const_range(len(keep_axes)):
        out[i] = data_shape[keep_axes[i]]

    for i in const_range(len(remove_axes)):
        assert data_shape[remove_axes[i]] == 1, "Removed dimension must have size 1"

    return out

@_reg.register_shape_func("squeeze", False)
def squeeze_shape_func(attrs, inputs, _):
    """
    Shape function for squeeze op.
    """
    axis = attrs.axis if attrs.axis is None else get_const_tuple(attrs.axis)
    keep_axes = []
    remove_axes = []
    if axis is not None:
        for i in range(inputs[0].shape[0].value):
            if i not in axis:
                keep_axes.append(i)
            else:
                remove_axes.append(i)

    # Due to current relay type system, it is possible even
    # a static kernel function needs shape function. To handle
    # this case, we allow axis to be None in squeeze shape func
    # for now.
    # TODO(kevinthesun): Enhance relay type system to avoid this.
    if keep_axes:
        out = _squeeze_shape_func(inputs[0], convert(keep_axes), convert(remove_axes))
    else:
        out = te.compute((), lambda *indices: 0)
    return [out]

@script
def _reshape_like_shape_func(target_shape):
    out = output_tensor((target_shape.shape[0],), "int64")
    for i in const_range(target_shape.shape[0]):
        out[i] = target_shape[i]

    return out

@_reg.register_shape_func("reshape_like", False)
def reshape_like_shape_func(attrs, inputs, _):
    """
    Shape function for reshape_like op.
    """
    return [_reshape_like_shape_func(inputs[1])]

@script
def _tile_shape_func(data, reps, ndim, tndim, rndim):
    out = output_tensor((tndim,), "int64")

    if ndim == rndim:
        for i in const_range(tndim):
            out[i] = data[i] * int64(reps[i])
    elif ndim > rndim:
        ngap = ndim - rndim
        for i in const_range(ndim):
            if i < ngap:
                out[i] = data[i]
            else:
                out[i] = data[i] * int64(reps[i - ngap])
    else:
        rgap = rndim - ndim
        for i in const_range(rndim):
            if i < rgap:
                out[i] = int64(reps[i])
            else:
                out[i] = int64(reps[i]) * data[i - rgap]
    return out

@_reg.register_shape_func("tile", False)
def tile_shape_func(attrs, inputs, _):
    """
    Shape function for tile op.
    """
    reps = get_const_tuple(attrs.reps)
    ndim = inputs[0].shape[0].value
    rndim = len(reps)
    tndim = ndim if ndim > rndim else rndim
    return [
        _tile_shape_func(inputs[0], convert(reps), convert(ndim), convert(tndim), convert(rndim))
    ]

@script
def _split_shape_func(data_shape, index, indices_or_sections, param_is_indices, axis):
    out = output_tensor((data_shape.shape[0],), "int64")
    if param_is_indices:
        for i in const_range(data_shape.shape[0]):
            if i == axis:
                assert (
                    data_shape[axis] % indices_or_sections[0] == 0
                ), "num_sections must be an integer factor of the size of axis"
                out[i] = ceil_div(data_shape[axis], indices_or_sections[0])
            else:
                out[i] = data_shape[i]
    else:
        start = int64(0)
        if index > 0:
            start = int64(indices_or_sections[index - 1])
        end = data_shape[axis]
        if index < len(indices_or_sections):
            end = int64(indices_or_sections[index])
        for i in const_range(data_shape.shape[0]):
            if i == axis:
                out[i] = end - start
            else:
                out[i] = data_shape[i]
    return out

@_reg.register_shape_func("split", False)
def split_shape_func(attrs, inputs, _):
    """
    Shape function for split op.
    """
    if isinstance(attrs.indices_or_sections, (int, tvm.tir.IntImm)):
        indices_or_sections = get_const_int(attrs.indices_or_sections)
        assert indices_or_sections > 0, "Slice count must be > 0"
    else:
        indices_or_sections = list(get_const_tuple(attrs.indices_or_sections))
        assert sorted(indices_or_sections)[0] > 0 and indices_or_sections == sorted(
            indices_or_sections
        ), "split_indices must be sorted"

    axis = get_const_int(attrs.axis)

    if axis < 0:
        axis += get_const_int(inputs[0].shape[0])

    num_out = (
        indices_or_sections
        if isinstance(indices_or_sections, int)
        else len(indices_or_sections) + 1
    )

    param_is_indices = isinstance(indices_or_sections, int)
    if param_is_indices:
        indices_or_sections = [indices_or_sections]
    return [
        _split_shape_func(
            inputs[0],
            convert(i),
            convert(indices_or_sections),
            convert(param_is_indices),
            convert(axis),
        )
        for i in range(num_out)
    ]

@script
def _adv_index_shape_func(inputs):
    index_rank = inputs[1].shape[0]
    data_rank = inputs[0].shape[0]
    out = output_tensor((data_rank + index_rank - len(inputs) + 1,), "int64")

    max_flatten_len = int64(1)
    for i in const_range(index_rank):
        max_flatten_len *= inputs[1][i]
        out[i] = inputs[1][i]
    for i in const_range(len(inputs) - 2):
        flatten_len = int64(1)
        for j in const_range(index_rank):
            flatten_len *= inputs[i + 2][j]
        if flatten_len > max_flatten_len:
            max_flatten_len = flatten_len
            for k in const_range(index_rank):
                out[k] = inputs[i + 2][k]

    for i in const_range(data_rank - len(inputs) + 1):
        out[i + index_rank] = inputs[0][i + len(inputs) - 1]

    return out

@_reg.register_shape_func("adv_index", False)
def adv_index_shape_func(attrs, inputs, _):
    """
    Shape func for adv_index.
    Only allow single index tensor.
    """
    return [_adv_index_shape_func(inputs)]

@script
def _repeat_shape_func(data_shape, repeats, axis):
    out = output_tensor((data_shape.shape[0],), "int64")

    for i in const_range(data_shape.shape[0]):
        if i == axis:
            out[i] = int64(data_shape[i] * repeats)
        else:
            out[i] = data_shape[i]

    return out

@_reg.register_shape_func("repeat", False)
def repeat_shape_func(attrs, inputs, _):
    """
    Shape func for repeat.
    """
    axis = get_const_int(attrs.axis)
    if axis < 0:
        axis = inputs[0].shape[0] + axis
    return [_repeat_shape_func(inputs[0], attrs.repeats, convert(axis))]

@_reg.register_shape_func("broadcast_to_like", False)
def broadcast_to_like_shape_func(attrs, inputs, _):
    """
    Shape func for broadcast_to_like.
    """
    return [topi.math.identity(inputs[1])]

@script
def _stack_shape_func(data_shape, axis, num_inputs):
    out = output_tensor((data_shape.shape[0] + 1,), "int64")

    for i in const_range(data_shape.shape[0] + 1):
        if i == axis:
            out[i] = int64(num_inputs)
        elif i < axis:
            out[i] = data_shape[i]
        else:
            out[i] = data_shape[i - 1]

    return out

@_reg.register_shape_func("stack", False)
def stack_shape_func(attrs, inputs, _):
    """
    Shape func for stack.
    """
    axis = get_const_int(attrs.axis)
    if axis < 0:
        axis += inputs[0].shape[0] + 1
    return [_stack_shape_func(inputs[0], convert(axis), convert(len(inputs)))]

@script
def _broadcast_shape_tensors(shape_tensor1, shape_tensor2):
    rank1 = shape_tensor1.shape[0]
    rank2 = shape_tensor2.shape[0]
    out_rank = max(rank1, rank2)
    bcast_shape_tensor = output_tensor((out_rank,), "int64")

    for index in const_range(out_rank):
        dim1 = int64(1)
        dim2 = int64(1)

        if rank1 == out_rank:
            dim1 = shape_tensor1[index]
        elif rank1 - (out_rank - index) >= 0:
            dim1 = shape_tensor1[rank1 - (out_rank - index)]

        if rank2 == out_rank:
            dim2 = shape_tensor2[index]
        elif rank2 - (out_rank - index) >= 0:
            dim2 = shape_tensor2[rank2 - (out_rank - index)]

        assert dim1 == dim2 or dim1 == 1 or dim2 == 1, "Invalid broadcast shapes"
        bcast_shape_tensor[index] = max(dim1, dim2)

    return bcast_shape_tensor

@_reg.register_shape_func("where", False)
def where_shape_func(attrs, inputs, _):
    """
    Shape func for where.
    """

    def ensure_tensor(tensor):
        if len(tensor.shape) == 0:
            return topi.full((1,), "int64", 1)
        return tensor

    cond_shape = ensure_tensor(inputs[0])
    x_shape = ensure_tensor(inputs[1])
    y_shape = ensure_tensor(inputs[2])

    bcast_shape = _broadcast_shape_tensors(x_shape, y_shape)
    out_shape = _broadcast_shape_tensors(bcast_shape, cond_shape)

    return [out_shape]

@script
def _unique_shape(data_shape):
    unique_shape = output_tensor((1,), "int64")
    indices_shape = output_tensor((1,), "int64")
    inverse_indices_shape = output_tensor((1,), "int64")
    num_unique_shape = output_tensor((1,), "int64")
    unique_shape[0] = data_shape[0]
    indices_shape[0] = data_shape[0]
    inverse_indices_shape[0] = data_shape[0]
    num_unique_shape[0] = int64(1)
    return (unique_shape, indices_shape, inverse_indices_shape, num_unique_shape)

@script
def _unique_with_counts_shape(data_shape):
    unique_shape = output_tensor((1,), "int64")
    indices_shape = output_tensor((1,), "int64")
    inverse_indices_shape = output_tensor((1,), "int64")
    num_unique_shape = output_tensor((1,), "int64")
    counts_shape = output_tensor((1,), "int64")
    unique_shape[0] = data_shape[0]
    indices_shape[0] = data_shape[0]
    inverse_indices_shape[0] = data_shape[0]
    num_unique_shape[0] = int64(1)
    counts_shape[0] = data_shape[0]
    return (unique_shape, indices_shape, inverse_indices_shape, num_unique_shape, counts_shape)

@_reg.register_shape_func("unique", False)
def unique_shape_func(attrs, inputs, _):
    """
    Shape func for unique operator.
    """
    if attrs.return_counts:
        return _unique_with_counts_shape(inputs[0])
    else:
        return _unique_shape(inputs[0])

@script
def _gather_nd_shape(data_shape, indices_shape, batch_dims, index_rank):
    ndim = data_shape.shape[0]
    # using mdim = indices_shape[0] wouldn't work because a rank cannot
    # depend on a runtime shape dimension of indices tensor, even if the
    # dimension is always a known, fixed value. As a workaround, we assume that
    # the fixed gather dimension (the size of an indexing tuple) is recorded
    # in gather_nd op attributes.
    mdim = index_rank
    kdim = indices_shape.shape[0] - 1
    out_shape = output_tensor((kdim + ndim - (mdim + batch_dims),), "int64")
    for i in range(1, kdim + 1):
        out_shape[i - 1] = indices_shape[i]
    for i in range(mdim + batch_dims, ndim):
        out_shape[kdim + i - (mdim + batch_dims)] = data_shape[i]
    return out_shape

@_reg.register_shape_func("gather_nd", False)
def gather_nd_shape_func(attrs, inputs, _):
    """
    Shape func for gather_nd operator.
    """
    batch_dims = get_const_int(attrs.batch_dims)
    index_rank = get_const_int(attrs.index_rank)

    assert index_rank > 0, "index_rank needs to be specified for dynamic gather_nd"

    return [_gather_nd_shape(inputs[0], inputs[1], convert(batch_dims), convert(index_rank))]

@script
def _gather_shape(data_shape, indices_shape, axis):
    out_shape = output_tensor((data_shape.shape[0],), "int64")
    for i in range(data_shape.shape[0]):
        if i != axis:
            assert (
                data_shape[i] == indices_shape[i]
            ), "data and indices size at non-gather axes must be the same"
        out_shape[i] = indices_shape[i]
    return out_shape

@_reg.register_shape_func("gather", False)
def gather_shape_func(attrs, inputs, _):
    """
    Shape func for gather operator.
    """
    return [_gather_shape(inputs[0], inputs[1], attrs.axis)]


text:
package com.senseidb.clue.commands;

import java.io.PrintStream;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;

import com.senseidb.clue.ClueContext;

public class GetUserCommitDataCommand extends ClueCommand {

	public GetUserCommitDataCommand(ClueContext ctx) {
		super(ctx);
	}

	@Override
	public String getName() {
		return "showcommitdata";
	}

	@Override
	public String help() {
		return "Shows user commit data";
	}

	@Override
	public void execute(String[] args, PrintStream out) throws Exception {
		IndexReader reader = ctx.getIndexReader();
		if (reader instanceof DirectoryReader) {
			DirectoryReader dirReader = (DirectoryReader) reader;
			Map<String, String> userData = dirReader.getIndexCommit().getUserData();
			if (userData == null || userData.size() == 0) {
				out.println("Empty user commit data");
			} else {
			  for (Entry<String, String> entry : userData.entrySet()) {
				  out.println("key: " + entry.getKey()+"\tvalue: " + entry.getValue());
			  }
			}
			out.flush();
		} else {
			throw new IllegalArgumentException("can only read user commit data from instances of " + DirectoryReader.class);
		}
	}
}


text:
var thumbnailviewer={
enableTitle: true, //Should "title" attribute of link be used as description?
enableAnimation: true, //Enable fading animation?
definefooter: '
CLOSE X
', //Define HTML for footer interface
defineLoading: ' Loading Image...', //Define HTML for "loading" div

/////////////No need to edit beyond here/////////////////////////

scrollbarwidth: 16,
opacitystring: 'filter:progid:DXImageTransform.Microsoft.alpha(opacity=10); -moz-opacity: 0.1; opacity: 0.1',
targetlinks:[], //Array to hold links with rel="thumbnail"

createthumbBox:function(){
//write out HTML for Image Thumbnail Viewer plus loading div
document.write('

'+this.definefooter+'
')
document.write('
'+this.defineLoading+'
')
this.thumbBox=document.getElementById("thumbBox")
this.thumbImage=document.getElementById("thumbImage") //Reference div that holds the shown image
this.thumbLoading=document.getElementById("thumbLoading") //Reference "loading" div that will be shown while image is fetched
this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
},

centerDiv:function(divobj){ //Centers a div element on the page
var ie=document.all && !window.opera
var dom=document.getElementById
var scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset
var scroll_left=(ie)? this.standardbody.scrollLeft : window.pageXOffset
var docwidth=(ie)? this.standardbody.clientWidth : window.innerWidth-this.scrollbarwidth
var docheight=(ie)? this.standardbody.clientHeight: window.innerHeight
var docheightcomplete=(this.standardbody.offsetHeight>this.standardbody.scrollHeight)? this.standardbody.offsetHeight : this.standardbody.scrollHeight //Full scroll height of document
var objwidth=divobj.offsetWidth //width of div element
var objheight=divobj.offsetHeight //height of div element
var topposition=(docheight>objheight)? scroll_top+docheight/2-objheight/2+"px" : scroll_top+10+"px" //Vertical position of div element: Either centered, or if element height larger than viewpoint height, 10px from top of viewpoint
divobj.style.left=docwidth/2-objwidth/2+"px" //Center div element horizontally
divobj.style.top=Math.floor(parseInt(topposition))+"px"
divobj.style.visibility="visible"
},

showthumbBox:function(){ //Show ThumbBox div
thumbnailviewer.thumbLoading.style.visibility="hidden" //Hide "loading" div
this.centerDiv(this.thumbBox)
if (this.enableAnimation){ //If fading animation enabled
this.currentopacity=0.1 //Starting opacity value
this.opacitytimer=setInterval("thumbnailviewer.opacityanimation()", 20)
}
},

loadimage:function(link){ //Load image function that gets attached to each link on the page with rel="thumbnail"
if (this.thumbBox.style.visibility=="visible") //if thumbox is visible on the page already
this.closeit() //Hide it first (not doing so causes triggers some positioning bug in Firefox
var imageHTML='' //Construct HTML for shown image
if (this.enableTitle && link.getAttribute("title")) //Use title attr of the link as description?
imageHTML+='
'+link.getAttribute("title")
this.centerDiv(this.thumbLoading) //Center and display "loading" div while we set up the image to be shown
this.thumbImage.innerHTML=imageHTML //Populate thumbImage div with shown image's HTML (while still hidden)
this.featureImage=this.thumbImage.getElementsByTagName("img")[0] //Reference shown image itself
if (this.featureImage.complete)
thumbnailviewer.showthumbBox()
else{
this.featureImage.onload=function(){ //When target image has completely loaded
thumbnailviewer.showthumbBox() //Display "thumbbox" div to the world!
}
}
if (document.all && !window.createPopup) //Target IE5.0 browsers only. Address IE image cache not firing onload bug: panoramio.com/blog/onload-event/
this.featureImage.src=link.getAttribute("href")
this.featureImage.onerror=function(){ //If an error has occurred while loading the image to show
thumbnailviewer.thumbLoading.style.visibility="hidden" //Hide "loading" div, game over
}
},

setimgopacity:function(value){ //Sets the opacity of "thumbimage" div per the passed in value setting (0 to 1 and in between)
var targetobject=this.featureImage
if (targetobject.filters && targetobject.filters[0]){ //IE syntax
if (typeof targetobject.filters[0].opacity=="number") //IE6
targetobject.filters[0].opacity=value*100
else //IE 5.5
targetobject.style.filter="alpha(opacity="+value*100+")"
}
else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
targetobject.style.MozOpacity=value
else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
targetobject.style.opacity=value
else //Non of the above, stop opacity animation
this.stopanimation()
},

opacityanimation:function(){ //Gradually increase opacity function
this.setimgopacity(this.currentopacity)
this.currentopacity+=0.1
if (this.currentopacity>1)
this.stopanimation()
},

stopanimation:function(){
if (typeof this.opacitytimer!="undefined")
clearInterval(this.opacitytimer)
},

closeit:function(){ //Close "thumbbox" div function
this.stopanimation()
this.thumbBox.style.visibility="hidden"
this.thumbImage.innerHTML=""
this.thumbBox.style.left="-2000px"
this.thumbBox.style.top="-2000px"
},

cleanup:function(){ //Clean up routine on page unload
this.thumbLoading=null
if (this.featureImage) this.featureImage.onload=null
this.featureImage=null
this.thumbImage=null
for (var i=0; i<this.targetlinks.length; i++)
this.targetlinks[i].onclick=null
this.thumbBox=null
},

dotask:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
if (target.addEventListener)
target.addEventListener(tasktype, functionref, false)
else if (target.attachEvent)
target.attachEvent(tasktype, functionref)
},

init:function(){ //Initialize thumbnail viewer script by scanning page and attaching appropriate function to links with rel="thumbnail"
if (!this.enableAnimation)
this.opacitystring=""
var pagelinks=document.getElementsByTagName("a")
for (var i=0; i<pagelinks.length; i++){ //BEGIN FOR LOOP
if (pagelinks[i].getAttribute("rel") && pagelinks[i].getAttribute("rel")=="thumbnail"){ //Begin if statement
pagelinks[i].onclick=function(){
thumbnailviewer.stopanimation() //Stop any currently running fade animation on "thumbbox" div before proceeding
thumbnailviewer.loadimage(this) //Load image
return false
}
this.targetlinks[this.targetlinks.length]=pagelinks[i] //store reference to target link
} //end if statement
} //END FOR LOOP
//Reposition "thumbbox" div when page is resized
this.dotask(window, function(){if (thumbnailviewer.thumbBox.style.visibility=="visible") thumbnailviewer.centerDiv(thumbnailviewer.thumbBox)}, "resize")

} //END init() function

}

thumbnailviewer.createthumbBox() //Output HTML for the image thumbnail viewer
thumbnailviewer.dotask(window, function(){thumbnailviewer.init()}, "load") //Initialize script on page load
thumbnailviewer.dotask(window, function(){thumbnailviewer.cleanup()}, "unload")


text:
var vows = require('vows'),
	assert = require('assert'),
	log4js = require('../lib/log4js'),
	sandbox = require('sandboxed-module');

function setupLogging(category, options) {
	var msgs = [];

	var fakeMailer = {
		send_mail: function (msg, callback) {
			msgs.push(msg);
			callback(null, true);
		}
	};

	var smtpModule = sandbox.require('../lib/appenders/smtp', {
		requires: {
			'nodemailer': fakeMailer
		}
	});

	log4js.addAppender(smtpModule.configure(options), category);

	return {
		logger: log4js.getLogger(category),
		mailer: fakeMailer,
		results: msgs
	};
}

function checkMessages (result, sender, subject) {
	for (var i = 0; i < result.results.length; ++i) {
		assert.equal(result.results[i].sender, sender ? sender : result.mailer.SMTP.user);
		assert.equal(result.results[i].to, 'recipient@domain.com');
		assert.equal(result.results[i].subject, subject ? subject : 'Log event #' + (i+1));
		assert.ok(new RegExp('.+Log event #' + (i+1) + '\n$').test(result.results[i].body));
	}
}

log4js.clearAppenders();
vows.describe('log4js smtpAppender').addBatch({
	'minimal config': {
		topic: function() {
			var setup = setupLogging('minimal config', {
				recipients: 'recipient@domain.com',
				smtp: {
					port: 25,
					user: 'user@domain.com'
				}
			});
			setup.logger.info('Log event #1');
			return setup;
		},
		'mailer should be configured properly': function (result) {
			assert.ok(result.mailer.SMTP);
			assert.equal(result.mailer.SMTP.port, 25);
			assert.equal(result.mailer.SMTP.user, 'user@domain.com');
		},
		'there should be one message only': function (result) {
			assert.equal(result.results.length, 1);
		},
		'message should contain proper data': function (result) {
			checkMessages(result);
		}
	},
	'fancy config': {
		topic: function() {
			var setup = setupLogging('fancy config', {
				recipients: 'recipient@domain.com',
				sender: 'sender@domain.com',
				subject: 'This is subject',
				smtp: {
					port: 25,
					user: 'user@domain.com'
				}
			});
			setup.logger.info('Log event #1');
			return setup;
		},
		'mailer should be configured properly': function (result) {
			assert.ok(result.mailer.SMTP);
			assert.equal(result.mailer.SMTP.port, 25);
			assert.equal(result.mailer.SMTP.user, 'user@domain.com');
		},
		'there should be one message only': function (result) {
			assert.equal(result.results.length, 1);
		},
		'message should contain proper data': function (result) {
			checkMessages(result, 'sender@domain.com', 'This is subject');
		}
	},
	'separate email for each event': {
		topic: function() {
			var self = this;
			var setup = setupLogging('separate email for each event', {
				recipients: 'recipient@domain.com',
				smtp: {
					port: 25,
					user: 'user@domain.com'
				}
			});
			setTimeout(function () {
				setup.logger.info('Log event #1');
			}, 0);
			setTimeout(function () {
				setup.logger.info('Log event #2');
			}, 500);
			setTimeout(function () {
				setup.logger.info('Log event #3');
			}, 1050);
			setTimeout(function () {
				self.callback(null, setup);
			}, 2100);
		},
		'there should be three messages': function (result) {
			assert.equal(result.results.length, 3);
		},
		'messages should contain proper data': function (result) {
			checkMessages(result);
		}
	},
	'multiple events in one email': {
		topic: function() {
			var self = this;
			var setup = setupLogging('multiple events in one email', {
				recipients: 'recipient@domain.com',
				sendInterval: 1,
				smtp: {
					port: 25,
					user: 'user@domain.com'
				}
			});
			setTimeout(function () {
				setup.logger.info('Log event #1');
			}, 0);
			setTimeout(function () {
				setup.logger.info('Log event #2');
			}, 500);
			setTimeout(function () {
				setup.logger.info('Log event #3');
			}, 1050);
			setTimeout(function () {
				self.callback(null, setup);
			}, 2100);
		},
		'there should be two messages': function (result) {
			assert.equal(result.results.length, 2);
		},
		'messages should contain proper data': function (result) {
			assert.equal(result.results[0].sender, result.mailer.SMTP.user);
			assert.equal(result.results[0].to, 'recipient@domain.com');
			assert.equal(result.results[0].subject, 'Log event #1');
			assert.equal(result.results[0].body.match(new RegExp('.+Log event #[1-2]$', 'gm')).length, 2);

			assert.equal(result.results[1].sender, result.mailer.SMTP.user);
			assert.equal(result.results[1].to, 'recipient@domain.com');
			assert.equal(result.results[1].subject, 'Log event #3');
			assert.ok(new RegExp('.+Log event #3\n$').test(result.results[1].body));
		}
	}

}).export(module);


text:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/acpi.h>
#include <linux/acpi_io.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/kref.h>
#include <linux/rculist.h>
#include <linux/interrupt.h>
#include <linux/debugfs.h>

#include "apei-internal.h"

#define APEI_PFX "APEI: "

/*
 * APEI ERST (Error Record Serialization Table) and EINJ (Error
 * INJection) interpreter framework.
 */

#define APEI_EXEC_PRESERVE_REGISTER	0x1

void apei_exec_ctx_init(struct apei_exec_context *ctx,
			struct apei_exec_ins_type *ins_table,
			u32 instructions,
			struct acpi_whea_header *action_table,
			u32 entries)
{
	ctx->ins_table = ins_table;
	ctx->instructions = instructions;
	ctx->action_table = action_table;
	ctx->entries = entries;
}
EXPORT_SYMBOL_GPL(apei_exec_ctx_init);

int __apei_exec_read_register(struct acpi_whea_header *entry, u64 *val)
{
	int rc;

	rc = apei_read(val, &entry->register_region);
	if (rc)
		return rc;
	*val >>= entry->register_region.bit_offset;
	*val &= entry->mask;

	return 0;
}

int apei_exec_read_register(struct apei_exec_context *ctx,
			    struct acpi_whea_header *entry)
{
	int rc;
	u64 val = 0;

	rc = __apei_exec_read_register(entry, &val);
	if (rc)
		return rc;
	ctx->value = val;

	return 0;
}
EXPORT_SYMBOL_GPL(apei_exec_read_register);

int apei_exec_read_register_value(struct apei_exec_context *ctx,
				  struct acpi_whea_header *entry)
{
	int rc;

	rc = apei_exec_read_register(ctx, entry);
	if (rc)
		return rc;
	ctx->value = (ctx->value == entry->value);

	return 0;
}
EXPORT_SYMBOL_GPL(apei_exec_read_register_value);

int __apei_exec_write_register(struct acpi_whea_header *entry, u64 val)
{
	int rc;

	val &= entry->mask;
	val <<= entry->register_region.bit_offset;
	if (entry->flags & APEI_EXEC_PRESERVE_REGISTER) {
		u64 valr = 0;
		rc = apei_read(&valr, &entry->register_region);
		if (rc)
			return rc;
		valr &= ~(entry->mask << entry->register_region.bit_offset);
		val |= valr;
	}
	rc = apei_write(val, &entry->register_region);

	return rc;
}

int apei_exec_write_register(struct apei_exec_context *ctx,
			     struct acpi_whea_header *entry)
{
	return __apei_exec_write_register(entry, ctx->value);
}
EXPORT_SYMBOL_GPL(apei_exec_write_register);

int apei_exec_write_register_value(struct apei_exec_context *ctx,
				   struct acpi_whea_header *entry)
{
	int rc;

	ctx->value = entry->value;
	rc = apei_exec_write_register(ctx, entry);

	return rc;
}
EXPORT_SYMBOL_GPL(apei_exec_write_register_value);

int apei_exec_noop(struct apei_exec_context *ctx,
		   struct acpi_whea_header *entry)
{
	return 0;
}
EXPORT_SYMBOL_GPL(apei_exec_noop);

/*
 * Interpret the specified action. Go through whole action table,
 * execute all instructions belong to the action.
 */
int __apei_exec_run(struct apei_exec_context *ctx, u8 action,
		    bool optional)
{
	int rc = -ENOENT;
	u32 i, ip;
	struct acpi_whea_header *entry;
	apei_exec_ins_func_t run;

	ctx->ip = 0;

	/*
	 * "ip" is the instruction pointer of current instruction,
	 * "ctx->ip" specifies the next instruction to executed,
	 * instruction "run" function may change the "ctx->ip" to
	 * implement "goto" semantics.
	 */
rewind:
	ip = 0;
	for (i = 0; i < ctx->entries; i++) {
		entry = &ctx->action_table[i];
		if (entry->action != action)
			continue;
		if (ip == ctx->ip) {
			if (entry->instruction >= ctx->instructions ||
			    !ctx->ins_table[entry->instruction].run) {
				pr_warning(FW_WARN APEI_PFX
			"Invalid action table, unknown instruction type: %d\n",
					   entry->instruction);
				return -EINVAL;
			}
			run = ctx->ins_table[entry->instruction].run;
			rc = run(ctx, entry);
			if (rc < 0)
				return rc;
			else if (rc != APEI_EXEC_SET_IP)
				ctx->ip++;
		}
		ip++;
		if (ctx->ip < ip)
			goto rewind;
	}

	return !optional && rc < 0 ? rc : 0;
}
EXPORT_SYMBOL_GPL(__apei_exec_run);

typedef int (*apei_exec_entry_func_t)(struct apei_exec_context *ctx,
				      struct acpi_whea_header *entry,
				      void *data);

static int apei_exec_for_each_entry(struct apei_exec_context *ctx,
				    apei_exec_entry_func_t func,
				    void *data,
				    int *end)
{
	u8 ins;
	int i, rc;
	struct acpi_whea_header *entry;
	struct apei_exec_ins_type *ins_table = ctx->ins_table;

	for (i = 0; i < ctx->entries; i++) {
		entry = ctx->action_table + i;
		ins = entry->instruction;
		if (end)
			*end = i;
		if (ins >= ctx->instructions || !ins_table[ins].run) {
			pr_warning(FW_WARN APEI_PFX
			"Invalid action table, unknown instruction type: %d\n",
				   ins);
			return -EINVAL;
		}
		rc = func(ctx, entry, data);
		if (rc)
			return rc;
	}

	return 0;
}

static int pre_map_gar_callback(struct apei_exec_context *ctx,
				struct acpi_whea_header *entry,
				void *data)
{
	u8 ins = entry->instruction;

	if (ctx->ins_table[ins].flags & APEI_EXEC_INS_ACCESS_REGISTER)
		return apei_map_generic_address(&entry->register_region);

	return 0;
}

/*
 * Pre-map all GARs in action table to make it possible to access them
 * in NMI handler.
 */
int apei_exec_pre_map_gars(struct apei_exec_context *ctx)
{
	int rc, end;

	rc = apei_exec_for_each_entry(ctx, pre_map_gar_callback,
				      NULL, &end);
	if (rc) {
		struct apei_exec_context ctx_unmap;
		memcpy(&ctx_unmap, ctx, sizeof(*ctx));
		ctx_unmap.entries = end;
		apei_exec_post_unmap_gars(&ctx_unmap);
	}

	return rc;
}
EXPORT_SYMBOL_GPL(apei_exec_pre_map_gars);

static int post_unmap_gar_callback(struct apei_exec_context *ctx,
				   struct acpi_whea_header *entry,
				   void *data)
{
	u8 ins = entry->instruction;

	if (ctx->ins_table[ins].flags & APEI_EXEC_INS_ACCESS_REGISTER)
		apei_unmap_generic_address(&entry->register_region);

	return 0;
}

/* Post-unmap all GAR in action table. */
int apei_exec_post_unmap_gars(struct apei_exec_context *ctx)
{
	return apei_exec_for_each_entry(ctx, post_unmap_gar_callback,
					NULL, NULL);
}
EXPORT_SYMBOL_GPL(apei_exec_post_unmap_gars);

/*
 * Resource management for GARs in APEI
 */
struct apei_res {
	struct list_head list;
	unsigned long start;
	unsigned long end;
};

/* Collect all resources requested, to avoid conflict */
struct apei_resources apei_resources_all = {
	.iomem = LIST_HEAD_INIT(apei_resources_all.iomem),
	.ioport = LIST_HEAD_INIT(apei_resources_all.ioport),
};

static int apei_res_add(struct list_head *res_list,
			unsigned long start, unsigned long size)
{
	struct apei_res *res, *resn, *res_ins = NULL;
	unsigned long end = start + size;

	if (end <= start)
		return 0;
repeat:
	list_for_each_entry_safe(res, resn, res_list, list) {
		if (res->start > end || res->end < start)
			continue;
		else if (end <= res->end && start >= res->start) {
			kfree(res_ins);
			return 0;
		}
		list_del(&res->list);
		res->start = start = min(res->start, start);
		res->end = end = max(res->end, end);
		kfree(res_ins);
		res_ins = res;
		goto repeat;
	}

	if (res_ins)
		list_add(&res_ins->list, res_list);
	else {
		res_ins = kmalloc(sizeof(*res), GFP_KERNEL);
		if (!res_ins)
			return -ENOMEM;
		res_ins->start = start;
		res_ins->end = end;
		list_add(&res_ins->list, res_list);
	}

	return 0;
}

static int apei_res_sub(struct list_head *res_list1,
			struct list_head *res_list2)
{
	struct apei_res *res1, *resn1, *res2, *res;
	res1 = list_entry(res_list1->next, struct apei_res, list);
	resn1 = list_entry(res1->list.next, struct apei_res, list);
	while (&res1->list != res_list1) {
		list_for_each_entry(res2, res_list2, list) {
			if (res1->start >= res2->end ||
			    res1->end <= res2->start)
				continue;
			else if (res1->end <= res2->end &&
				 res1->start >= res2->start) {
				list_del(&res1->list);
				kfree(res1);
				break;
			} else if (res1->end > res2->end &&
				   res1->start < res2->start) {
				res = kmalloc(sizeof(*res), GFP_KERNEL);
				if (!res)
					return -ENOMEM;
				res->start = res2->end;
				res->end = res1->end;
				res1->end = res2->start;
				list_add(&res->list, &res1->list);
				resn1 = res;
			} else {
				if (res1->start < res2->start)
					res1->end = res2->start;
				else
					res1->start = res2->end;
			}
		}
		res1 = resn1;
		resn1 = list_entry(resn1->list.next, struct apei_res, list);
	}

	return 0;
}

static void apei_res_clean(struct list_head *res_list)
{
	struct apei_res *res, *resn;

	list_for_each_entry_safe(res, resn, res_list, list) {
		list_del(&res->list);
		kfree(res);
	}
}

void apei_resources_fini(struct apei_resources *resources)
{
	apei_res_clean(&resources->iomem);
	apei_res_clean(&resources->ioport);
}
EXPORT_SYMBOL_GPL(apei_resources_fini);

static int apei_resources_merge(struct apei_resources *resources1,
				struct apei_resources *resources2)
{
	int rc;
	struct apei_res *res;

	list_for_each_entry(res, &resources2->iomem, list) {
		rc = apei_res_add(&resources1->iomem, res->start,
				  res->end - res->start);
		if (rc)
			return rc;
	}
	list_for_each_entry(res, &resources2->ioport, list) {
		rc = apei_res_add(&resources1->ioport, res->start,
				  res->end - res->start);
		if (rc)
			return rc;
	}

	return 0;
}

int apei_resources_add(struct apei_resources *resources,
		       unsigned long start, unsigned long size,
		       bool iomem)
{
	if (iomem)
		return apei_res_add(&resources->iomem, start, size);
	else
		return apei_res_add(&resources->ioport, start, size);
}
EXPORT_SYMBOL_GPL(apei_resources_add);

/*
 * EINJ has two groups of GARs (EINJ table entry and trigger table
 * entry), so common resources are subtracted from the trigger table
 * resources before the second requesting.
 */
int apei_resources_sub(struct apei_resources *resources1,
		       struct apei_resources *resources2)
{
	int rc;

	rc = apei_res_sub(&resources1->iomem, &resources2->iomem);
	if (rc)
		return rc;
	return apei_res_sub(&resources1->ioport, &resources2->ioport);
}
EXPORT_SYMBOL_GPL(apei_resources_sub);

static int apei_get_nvs_callback(__u64 start, __u64 size, void *data)
{
	struct apei_resources *resources = data;
	return apei_res_add(&resources->iomem, start, size);
}

static int apei_get_nvs_resources(struct apei_resources *resources)
{
	return acpi_nvs_for_each_region(apei_get_nvs_callback, resources);
}

/*
 * IO memory/port resource management mechanism is used to check
 * whether memory/port area used by GARs conflicts with normal memory
 * or IO memory/port of devices.
 */
int apei_resources_request(struct apei_resources *resources,
			   const char *desc)
{
	struct apei_res *res, *res_bak = NULL;
	struct resource *r;
	struct apei_resources nvs_resources;
	int rc;

	rc = apei_resources_sub(resources, &apei_resources_all);
	if (rc)
		return rc;

	/*
	 * Some firmware uses ACPI NVS region, that has been marked as
	 * busy, so exclude it from APEI resources to avoid false
	 * conflict.
	 */
	apei_resources_init(&nvs_resources);
	rc = apei_get_nvs_resources(&nvs_resources);
	if (rc)
		goto res_fini;
	rc = apei_resources_sub(resources, &nvs_resources);
	if (rc)
		goto res_fini;

	rc = -EINVAL;
	list_for_each_entry(res, &resources->iomem, list) {
		r = request_mem_region(res->start, res->end - res->start,
				       desc);
		if (!r) {
			pr_err(APEI_PFX
		"Can not request [mem %#010llx-%#010llx] for %s registers\n",
			       (unsigned long long)res->start,
			       (unsigned long long)res->end - 1, desc);
			res_bak = res;
			goto err_unmap_iomem;
		}
	}

	list_for_each_entry(res, &resources->ioport, list) {
		r = request_region(res->start, res->end - res->start, desc);
		if (!r) {
			pr_err(APEI_PFX
		"Can not request [io  %#06llx-%#06llx] for %s registers\n",
			       (unsigned long long)res->start,
			       (unsigned long long)res->end - 1, desc);
			res_bak = res;
			goto err_unmap_ioport;
		}
	}

	rc = apei_resources_merge(&apei_resources_all, resources);
	if (rc) {
		pr_err(APEI_PFX "Fail to merge resources!\n");
		goto err_unmap_ioport;
	}

	return 0;
err_unmap_ioport:
	list_for_each_entry(res, &resources->ioport, list) {
		if (res == res_bak)
			break;
		release_region(res->start, res->end - res->start);
	}
	res_bak = NULL;
err_unmap_iomem:
	list_for_each_entry(res, &resources->iomem, list) {
		if (res == res_bak)
			break;
		release_mem_region(res->start, res->end - res->start);
	}
res_fini:
	apei_resources_fini(&nvs_resources);
	return rc;
}
EXPORT_SYMBOL_GPL(apei_resources_request);

void apei_resources_release(struct apei_resources *resources)
{
	int rc;
	struct apei_res *res;

	list_for_each_entry(res, &resources->iomem, list)
		release_mem_region(res->start, res->end - res->start);
	list_for_each_entry(res, &resources->ioport, list)
		release_region(res->start, res->end - res->start);

	rc = apei_resources_sub(&apei_resources_all, resources);
	if (rc)
		pr_err(APEI_PFX "Fail to sub resources!\n");
}
EXPORT_SYMBOL_GPL(apei_resources_release);

static int apei_check_gar(struct acpi_generic_address *reg, u64 *paddr,
				u32 *access_bit_width)
{
	u32 bit_width, bit_offset, access_size_code, space_id;

	bit_width = reg->bit_width;
	bit_offset = reg->bit_offset;
	access_size_code = reg->access_width;
	space_id = reg->space_id;
	/* Handle possible alignment issues */
	memcpy(paddr, &reg->address, sizeof(*paddr));
	if (!*paddr) {
		pr_warning(FW_BUG APEI_PFX
			   "Invalid physical address in GAR [0x%llx/%u/%u/%u/%u]\n",
			   *paddr, bit_width, bit_offset, access_size_code,
			   space_id);
		return -EINVAL;
	}

	if (access_size_code < 1 || access_size_code > 4) {
		pr_warning(FW_BUG APEI_PFX
			   "Invalid access size code in GAR [0x%llx/%u/%u/%u/%u]\n",
			   *paddr, bit_width, bit_offset, access_size_code,
			   space_id);
		return -EINVAL;
	}
	*access_bit_width = 1UL << (access_size_code + 2);

	/* Fixup common BIOS bug */
	if (bit_width == 32 && bit_offset == 0 && (*paddr & 0x03) == 0 &&
	    *access_bit_width < 32)
		*access_bit_width = 32;
	else if (bit_width == 64 && bit_offset == 0 && (*paddr & 0x07) == 0 &&
	    *access_bit_width < 64)
		*access_bit_width = 64;

	if ((bit_width + bit_offset) > *access_bit_width) {
		pr_warning(FW_BUG APEI_PFX
			   "Invalid bit width + offset in GAR [0x%llx/%u/%u/%u/%u]\n",
			   *paddr, bit_width, bit_offset, access_size_code,
			   space_id);
		return -EINVAL;
	}

	if (space_id != ACPI_ADR_SPACE_SYSTEM_MEMORY &&
	    space_id != ACPI_ADR_SPACE_SYSTEM_IO) {
		pr_warning(FW_BUG APEI_PFX
			   "Invalid address space type in GAR [0x%llx/%u/%u/%u/%u]\n",
			   *paddr, bit_width, bit_offset, access_size_code,
			   space_id);
		return -EINVAL;
	}

	return 0;
}

int apei_map_generic_address(struct acpi_generic_address *reg)
{
	int rc;
	u32 access_bit_width;
	u64 address;

	rc = apei_check_gar(reg, &address, &access_bit_width);
	if (rc)
		return rc;
	return acpi_os_map_generic_address(reg);
}
EXPORT_SYMBOL_GPL(apei_map_generic_address);

/* read GAR in interrupt (including NMI) or process context */
int apei_read(u64 *val, struct acpi_generic_address *reg)
{
	int rc;
	u32 access_bit_width;
	u64 address;
	acpi_status status;

	rc = apei_check_gar(reg, &address, &access_bit_width);
	if (rc)
		return rc;

	*val = 0;
	switch(reg->space_id) {
	case ACPI_ADR_SPACE_SYSTEM_MEMORY:
		status = acpi_os_read_memory((acpi_physical_address) address,
					       val, access_bit_width);
		if (ACPI_FAILURE(status))
			return -EIO;
		break;
	case ACPI_ADR_SPACE_SYSTEM_IO:
		status = acpi_os_read_port(address, (u32 *)val,
					   access_bit_width);
		if (ACPI_FAILURE(status))
			return -EIO;
		break;
	default:
		return -EINVAL;
	}

	return 0;
}
EXPORT_SYMBOL_GPL(apei_read);

/* write GAR in interrupt (including NMI) or process context */
int apei_write(u64 val, struct acpi_generic_address *reg)
{
	int rc;
	u32 access_bit_width;
	u64 address;
	acpi_status status;

	rc = apei_check_gar(reg, &address, &access_bit_width);
	if (rc)
		return rc;

	switch (reg->space_id) {
	case ACPI_ADR_SPACE_SYSTEM_MEMORY:
		status = acpi_os_write_memory((acpi_physical_address) address,
						val, access_bit_width);
		if (ACPI_FAILURE(status))
			return -EIO;
		break;
	case ACPI_ADR_SPACE_SYSTEM_IO:
		status = acpi_os_write_port(address, val, access_bit_width);
		if (ACPI_FAILURE(status))
			return -EIO;
		break;
	default:
		return -EINVAL;
	}

	return 0;
}
EXPORT_SYMBOL_GPL(apei_write);

static int collect_res_callback(struct apei_exec_context *ctx,
				struct acpi_whea_header *entry,
				void *data)
{
	struct apei_resources *resources = data;
	struct acpi_generic_address *reg = &entry->register_region;
	u8 ins = entry->instruction;
	u32 access_bit_width;
	u64 paddr;
	int rc;

	if (!(ctx->ins_table[ins].flags & APEI_EXEC_INS_ACCESS_REGISTER))
		return 0;

	rc = apei_check_gar(reg, &paddr, &access_bit_width);
	if (rc)
		return rc;

	switch (reg->space_id) {
	case ACPI_ADR_SPACE_SYSTEM_MEMORY:
		return apei_res_add(&resources->iomem, paddr,
				    access_bit_width / 8);
	case ACPI_ADR_SPACE_SYSTEM_IO:
		return apei_res_add(&resources->ioport, paddr,
				    access_bit_width / 8);
	default:
		return -EINVAL;
	}
}

/*
 * Same register may be used by multiple instructions in GARs, so
 * resources are collected before requesting.
 */
int apei_exec_collect_resources(struct apei_exec_context *ctx,
				struct apei_resources *resources)
{
	return apei_exec_for_each_entry(ctx, collect_res_callback,
					resources, NULL);
}
EXPORT_SYMBOL_GPL(apei_exec_collect_resources);

struct dentry *apei_get_debugfs_dir(void)
{
	static struct dentry *dapei;

	if (!dapei)
		dapei = debugfs_create_dir("apei", NULL);

	return dapei;
}
EXPORT_SYMBOL_GPL(apei_get_debugfs_dir);

int apei_osc_setup(void)
{
	static u8 whea_uuid_str[] = "ed855e0c-6c90-47bf-a62a-26de0fc5ad5c";
	acpi_handle handle;
	u32 capbuf[3];
	struct acpi_osc_context context = {
		.uuid_str	= whea_uuid_str,
		.rev		= 1,
		.cap.length	= sizeof(capbuf),
		.cap.pointer	= capbuf,
	};

	capbuf[OSC_QUERY_TYPE] = OSC_QUERY_ENABLE;
	capbuf[OSC_SUPPORT_TYPE] = 1;
	capbuf[OSC_CONTROL_TYPE] = 0;

	if (ACPI_FAILURE(acpi_get_handle(NULL, "\\_SB", &handle))
	    || ACPI_FAILURE(acpi_run_osc(handle, &context)))
		return -EIO;
	else {
		kfree(context.ret.pointer);
		return 0;
	}
}
EXPORT_SYMBOL_GPL(apei_osc_setup);


text:
package org.apache.camel.support.resume;

import org.apache.camel.CamelContext;
import org.apache.camel.resume.ResumeAction;
import org.apache.camel.resume.ResumeActionAware;
import org.apache.camel.resume.ResumeAdapter;
import org.apache.camel.resume.ResumeStrategy;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Helper class for the resume strategy
 */
public final class ResumeStrategyHelper {
    private static final Logger LOG = LoggerFactory.getLogger(ResumeStrategyHelper.class);

    private ResumeStrategyHelper() {

    }

    /**
     * Executes the resume operation
     *
     * @param  context        a camel context on which the registry will be searched for the resume action
     * @param  on             the calling instance for the resume operation
     * @param  resumeStrategy the instance of the {@link ResumeStrategy} to perform the resume
     * @param  actionName     an action name that maps to a {@link ResumeAction} object in the registry
     * @throws Exception      if the strategy is unable to load the cache
     */
    public static void resume(
            CamelContext context, Object on, ResumeStrategy resumeStrategy,
            String actionName)
            throws Exception {
        resume(context, on, resumeStrategy, actionName, ResumeAdapter.class);
    }

    /**
     * Executes the resume operation
     *
     * @param  context        a camel context on which the registry will be searched for the resume action
     * @param  on             the calling instance for the resume operation
     * @param  resumeStrategy the instance of the {@link ResumeStrategy} to perform the resume
     * @param  actionName     an action name that maps to a {@link ResumeAction} object in the registry
     * @param  adapterClass   the class of the {@link ResumeAdapter} to look for in the registry
     * @throws Exception      if the strategy is unable to load the cache
     */
    public static <T extends ResumeAdapter> void resume(
            CamelContext context, Object on, ResumeStrategy resumeStrategy,
            String actionName, Class<T> adapterClass)
            throws Exception {
        if (resumeStrategy == null) {
            LOG.debug("Skipping resume operation because there's no resume strategy defined");

            return;
        }

        LOG.debug("Loading the resume cache");
        resumeStrategy.loadCache();

        T resumeAdapter = resumeStrategy.getAdapter(adapterClass);
        if (resumeAdapter == null) {
            LOG.warn("The resume cannot be executed because no resume adapter was provided");

            return;
        }

        if (resumeAdapter instanceof ResumeActionAware) {
            ResumeAction action = (ResumeAction) context.getRegistry().lookupByName(actionName);
            ObjectHelper.notNull(action, "The resume action cannot be null", on);

            ((ResumeActionAware) resumeAdapter).setResumeAction(action);
        }

        resumeAdapter.resume();
    }
}


text:
/****************************************************************************
** Resource object code
**
** Created by: The Resource Compiler for Qt version 5.2.1
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/

#include <QtCore/qglobal.h>

QT_BEGIN_NAMESPACE

QT_END_NAMESPACE

int QT_MANGLE_NAMESPACE(qInitResources_cvtoolwidget)()
{
    return 1;
}

Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qInitResources_cvtoolwidget))

int QT_MANGLE_NAMESPACE(qCleanupResources_cvtoolwidget)()
{
    return 1;
}

Q_DESTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qCleanupResources_cvtoolwidget))