code_text
stringlengths 604
999k
| repo_name
stringlengths 4
100
| file_path
stringlengths 4
873
| language
stringclasses 23
values | license
stringclasses 15
values | size
int32 1.02k
999k
|
---|---|---|---|---|---|
YUI.add('io-form', function (Y, NAME) {
/**
* Extends IO to enable HTML form data serialization, when specified
* in the transaction's configuration object.
* @module io
* @submodule io-form
* @for IO
*/
var eUC = encodeURIComponent;
/**
* Enumerate through an HTML form's elements collection
* and return a string comprised of key-value pairs.
*
* @method stringify
* @static
* @param {Node|String} form YUI form node or HTML form id
* @param {Object} [options] Configuration options.
* @param {Boolean} [options.useDisabled=false] Whether to include disabled fields.
* @param {Object|String} [options.extra] Extra values to include. May be a query string or an object with key/value pairs.
* @return {String}
*/
Y.IO.stringify = function(form, options) {
options = options || {};
var s = Y.IO.prototype._serialize({
id: form,
useDisabled: options.useDisabled
},
options.extra && typeof options.extra === 'object' ? Y.QueryString.stringify(options.extra) : options.extra);
return s;
};
Y.mix(Y.IO.prototype, {
/**
* Enumerate through an HTML form's elements collection
* and return a string comprised of key-value pairs.
*
* @method _serialize
* @private
* @param {Object} c
* @param {String|Element} c.id YUI form node or HTML form id
* @param {Boolean} c.useDisabled `true` to include disabled fields
* @param {String} s Key-value data defined in the configuration object.
* @return {String}
*/
_serialize: function(c, s) {
var data = [],
df = c.useDisabled || false,
item = 0,
id = (typeof c.id === 'string') ? c.id : c.id.getAttribute('id'),
e, f, n, v, d, i, il, j, jl, o;
if (!id) {
id = Y.guid('io:');
c.id.setAttribute('id', id);
}
f = Y.config.doc.getElementById(id);
if (!f || !f.elements) {
return s || '';
}
// Iterate over the form elements collection to construct the
// label-value pairs.
for (i = 0, il = f.elements.length; i < il; ++i) {
e = f.elements[i];
d = e.disabled;
n = e.name;
if (df ? n : n && !d) {
n = eUC(n) + '=';
v = eUC(e.value);
switch (e.type) {
// Safari, Opera, FF all default options.value from .text if
// value attribute not specified in markup
case 'select-one':
if (e.selectedIndex > -1) {
o = e.options[e.selectedIndex];
data[item++] = n + eUC(o.attributes.value && o.attributes.value.specified ? o.value : o.text);
}
break;
case 'select-multiple':
if (e.selectedIndex > -1) {
for (j = e.selectedIndex, jl = e.options.length; j < jl; ++j) {
o = e.options[j];
if (o.selected) {
data[item++] = n + eUC(o.attributes.value && o.attributes.value.specified ? o.value : o.text);
}
}
}
break;
case 'radio':
case 'checkbox':
if (e.checked) {
data[item++] = n + v;
}
break;
case 'file':
// stub case as XMLHttpRequest will only send the file path as a string.
case undefined:
// stub case for fieldset element which returns undefined.
case 'reset':
// stub case for input type reset button.
case 'button':
// stub case for input type button elements.
break;
case 'submit':
default:
data[item++] = n + v;
}
}
}
if (s) {
data[item++] = s;
}
return data.join('&');
}
}, true);
}, '@VERSION@', {"requires": ["io-base", "node-base"]});
| billybonz1/cdnjs | ajax/libs/yui/3.13.0/io-form/io-form.js | JavaScript | mit | 4,376 |
YUI.add('io-form', function (Y, NAME) {
/**
* Extends IO to enable HTML form data serialization, when specified
* in the transaction's configuration object.
* @module io
* @submodule io-form
* @for IO
*/
var eUC = encodeURIComponent;
/**
* Enumerate through an HTML form's elements collection
* and return a string comprised of key-value pairs.
*
* @method stringify
* @static
* @param {Node|String} form YUI form node or HTML form id
* @param {Object} [options] Configuration options.
* @param {Boolean} [options.useDisabled=false] Whether to include disabled fields.
* @param {Object|String} [options.extra] Extra values to include. May be a query string or an object with key/value pairs.
* @return {String}
*/
Y.IO.stringify = function(form, options) {
options = options || {};
var s = Y.IO.prototype._serialize({
id: form,
useDisabled: options.useDisabled
},
options.extra && typeof options.extra === 'object' ? Y.QueryString.stringify(options.extra) : options.extra);
return s;
};
Y.mix(Y.IO.prototype, {
/**
* Enumerate through an HTML form's elements collection
* and return a string comprised of key-value pairs.
*
* @method _serialize
* @private
* @param {Object} c
* @param {String|Element} c.id YUI form node or HTML form id
* @param {Boolean} c.useDisabled `true` to include disabled fields
* @param {String} s Key-value data defined in the configuration object.
* @return {String}
*/
_serialize: function(c, s) {
var data = [],
df = c.useDisabled || false,
item = 0,
id = (typeof c.id === 'string') ? c.id : c.id.getAttribute('id'),
e, f, n, v, d, i, il, j, jl, o;
if (!id) {
id = Y.guid('io:');
c.id.setAttribute('id', id);
}
f = Y.config.doc.getElementById(id);
if (!f || !f.elements) {
return s || '';
}
// Iterate over the form elements collection to construct the
// label-value pairs.
for (i = 0, il = f.elements.length; i < il; ++i) {
e = f.elements[i];
d = e.disabled;
n = e.name;
if (df ? n : n && !d) {
n = eUC(n) + '=';
v = eUC(e.value);
switch (e.type) {
// Safari, Opera, FF all default options.value from .text if
// value attribute not specified in markup
case 'select-one':
if (e.selectedIndex > -1) {
o = e.options[e.selectedIndex];
data[item++] = n + eUC(o.attributes.value && o.attributes.value.specified ? o.value : o.text);
}
break;
case 'select-multiple':
if (e.selectedIndex > -1) {
for (j = e.selectedIndex, jl = e.options.length; j < jl; ++j) {
o = e.options[j];
if (o.selected) {
data[item++] = n + eUC(o.attributes.value && o.attributes.value.specified ? o.value : o.text);
}
}
}
break;
case 'radio':
case 'checkbox':
if (e.checked) {
data[item++] = n + v;
}
break;
case 'file':
// stub case as XMLHttpRequest will only send the file path as a string.
case undefined:
// stub case for fieldset element which returns undefined.
case 'reset':
// stub case for input type reset button.
case 'button':
// stub case for input type button elements.
break;
case 'submit':
default:
data[item++] = n + v;
}
}
}
if (s) {
data[item++] = s;
}
return data.join('&');
}
}, true);
}, '@VERSION@', {"requires": ["io-base", "node-base"]});
| hanbyul-here/cdnjs | ajax/libs/yui/3.13.0/io-form/io-form.js | JavaScript | mit | 4,376 |
YUI.add('dd-ddm-drop', function(Y) {
/**
* Extends the dd-ddm Class to add support for the placement of Drop Target shims inside the viewport shim. It also handles all Drop Target related events and interactions.
* @module dd
* @submodule dd-ddm-drop
* @for DDM
* @namespace DD
*/
//TODO CSS class name for the bestMatch..
Y.mix(Y.DD.DDM, {
/**
* @private
* @property _noShim
* @description This flag turns off the use of the mouseover/mouseout shim. It should not be used unless you know what you are doing.
* @type {Boolean}
*/
_noShim: false,
/**
* @private
* @property _activeShims
* @description Placeholder for all active shims on the page
* @type {Array}
*/
_activeShims: [],
/**
* @private
* @method _hasActiveShim
* @description This method checks the _activeShims Object to see if there is a shim active.
* @return {Boolean}
*/
_hasActiveShim: function() {
if (this._noShim) {
return true;
}
return this._activeShims.length;
},
/**
* @private
* @method _addActiveShim
* @description Adds a Drop Target to the list of active shims
* @param {Object} d The Drop instance to add to the list.
*/
_addActiveShim: function(d) {
this._activeShims[this._activeShims.length] = d;
},
/**
* @private
* @method _removeActiveShim
* @description Removes a Drop Target to the list of active shims
* @param {Object} d The Drop instance to remove from the list.
*/
_removeActiveShim: function(d) {
var s = [];
Y.each(this._activeShims, function(v, k) {
if (v._yuid !== d._yuid) {
s[s.length] = v;
}
});
this._activeShims = s;
},
/**
* @method syncActiveShims
* @description This method will sync the position of the shims on the Drop Targets that are currently active.
* @param {Boolean} force Resize/sync all Targets.
*/
syncActiveShims: function(force) {
Y.later(0, this, function(force) {
var drops = ((force) ? this.targets : this._lookup());
Y.each(drops, function(v, k) {
v.sizeShim.call(v);
}, this);
}, force);
},
/**
* @private
* @property mode
* @description The mode that the drag operations will run in 0 for Point, 1 for Intersect, 2 for Strict
* @type Number
*/
mode: 0,
/**
* @private
* @property POINT
* @description In point mode, a Drop is targeted by the cursor being over the Target
* @type Number
*/
POINT: 0,
/**
* @private
* @property INTERSECT
* @description In intersect mode, a Drop is targeted by "part" of the drag node being over the Target
* @type Number
*/
INTERSECT: 1,
/**
* @private
* @property STRICT
* @description In strict mode, a Drop is targeted by the "entire" drag node being over the Target
* @type Number
*/
STRICT: 2,
/**
* @property useHash
* @description Should we only check targets that are in the viewport on drags (for performance), default: true
* @type {Boolean}
*/
useHash: true,
/**
* @property activeDrop
* @description A reference to the active Drop Target
* @type {Object}
*/
activeDrop: null,
/**
* @property validDrops
* @description An array of the valid Drop Targets for this interaction.
* @type {Array}
*/
//TODO Change array/object literals to be in sync..
validDrops: [],
/**
* @property otherDrops
* @description An object literal of Other Drop Targets that we encountered during this interaction (in the case of overlapping Drop Targets)
* @type {Object}
*/
otherDrops: {},
/**
* @property targets
* @description All of the Targets
* @type {Array}
*/
targets: [],
/**
* @private
* @method _addValid
* @description Add a Drop Target to the list of Valid Targets. This list get's regenerated on each new drag operation.
* @param {Object} drop
* @return {Self}
* @chainable
*/
_addValid: function(drop) {
this.validDrops[this.validDrops.length] = drop;
return this;
},
/**
* @private
* @method _removeValid
* @description Removes a Drop Target from the list of Valid Targets. This list get's regenerated on each new drag operation.
* @param {Object} drop
* @return {Self}
* @chainable
*/
_removeValid: function(drop) {
var drops = [];
Y.each(this.validDrops, function(v, k) {
if (v !== drop) {
drops[drops.length] = v;
}
});
this.validDrops = drops;
return this;
},
/**
* @method isOverTarget
* @description Check to see if the Drag element is over the target, method varies on current mode
* @param {Object} drop The drop to check against
* @return {Boolean}
*/
isOverTarget: function(drop) {
if (this.activeDrag && drop) {
var xy = this.activeDrag.mouseXY, r, dMode = this.activeDrag.get('dragMode'),
aRegion, node = drop.shim;
if (xy && this.activeDrag) {
aRegion = this.activeDrag.region;
if (dMode == this.STRICT) {
return this.activeDrag.get('dragNode').inRegion(drop.region, true, aRegion);
} else {
if (drop && drop.shim) {
if ((dMode == this.INTERSECT) && this._noShim) {
r = ((aRegion) ? aRegion : this.activeDrag.get('node'));
return drop.get('node').intersect(r, drop.region).inRegion;
} else {
if (this._noShim) {
node = drop.get('node');
}
return node.intersect({
top: xy[1],
bottom: xy[1],
left: xy[0],
right: xy[0]
}, drop.region).inRegion;
}
} else {
return false;
}
}
} else {
return false;
}
} else {
return false;
}
},
/**
* @method clearCache
* @description Clears the cache data used for this interaction.
*/
clearCache: function() {
this.validDrops = [];
this.otherDrops = {};
this._activeShims = [];
},
/**
* @private
* @method _activateTargets
* @description Clear the cache and activate the shims of all the targets
*/
_activateTargets: function() {
this._noShim = true;
this.clearCache();
Y.each(this.targets, function(v, k) {
v._activateShim([]);
if (v.get('noShim') == true) {
this._noShim = false;
}
}, this);
this._handleTargetOver();
},
/**
* @method getBestMatch
* @description This method will gather the area for all potential targets and see which has the hightest covered area and return it.
* @param {Array} drops An Array of drops to scan for the best match.
* @param {Boolean} all If present, it returns an Array. First item is best match, second is an Array of the other items in the original Array.
* @return {Object or Array}
*/
getBestMatch: function(drops, all) {
var biggest = null, area = 0, out;
Y.each(drops, function(v, k) {
var inter = this.activeDrag.get('dragNode').intersect(v.get('node'));
v.region.area = inter.area;
if (inter.inRegion) {
if (inter.area > area) {
area = inter.area;
biggest = v;
}
}
}, this);
if (all) {
out = [];
//TODO Sort the others in numeric order by area covered..
Y.each(drops, function(v, k) {
if (v !== biggest) {
out[out.length] = v;
}
}, this);
return [biggest, out];
} else {
return biggest;
}
},
/**
* @private
* @method _deactivateTargets
* @description This method fires the drop:hit, drag:drophit, drag:dropmiss methods and deactivates the shims..
*/
_deactivateTargets: function() {
var other = [], tmp,
activeDrag = this.activeDrag,
activeDrop = this.activeDrop;
//TODO why is this check so hard??
if (activeDrag && activeDrop && this.otherDrops[activeDrop]) {
if (!activeDrag.get('dragMode')) {
//TODO otherDrops -- private..
other = this.otherDrops;
delete other[activeDrop];
} else {
tmp = this.getBestMatch(this.otherDrops, true);
activeDrop = tmp[0];
other = tmp[1];
}
activeDrag.get('node').removeClass(this.CSS_PREFIX + '-drag-over');
if (activeDrop) {
activeDrop.fire('drop:hit', { drag: activeDrag, drop: activeDrop, others: other });
activeDrag.fire('drag:drophit', { drag: activeDrag, drop: activeDrop, others: other });
}
} else if (activeDrag && activeDrag.get('dragging')) {
activeDrag.get('node').removeClass(this.CSS_PREFIX + '-drag-over');
activeDrag.fire('drag:dropmiss', { pageX: activeDrag.lastXY[0], pageY: activeDrag.lastXY[1] });
} else {
}
this.activeDrop = null;
Y.each(this.targets, function(v, k) {
v._deactivateShim([]);
}, this);
},
/**
* @private
* @method _dropMove
* @description This method is called when the move method is called on the Drag Object.
*/
_dropMove: function() {
if (this._hasActiveShim()) {
this._handleTargetOver();
} else {
Y.each(this.otherDrops, function(v, k) {
v._handleOut.apply(v, []);
});
}
},
/**
* @private
* @method _lookup
* @description Filters the list of Drops down to those in the viewport.
* @return {Array} The valid Drop Targets that are in the viewport.
*/
_lookup: function() {
if (!this.useHash || this._noShim) {
return this.validDrops;
}
var drops = [];
//Only scan drop shims that are in the Viewport
Y.each(this.validDrops, function(v, k) {
if (v.shim && v.shim.inViewportRegion(false, v.region)) {
drops[drops.length] = v;
}
});
return drops;
},
/**
* @private
* @method _handleTargetOver
* @description This method execs _handleTargetOver on all valid Drop Targets
*/
_handleTargetOver: function() {
var drops = this._lookup();
Y.each(drops, function(v, k) {
v._handleTargetOver.call(v);
}, this);
},
/**
* @private
* @method _regTarget
* @description Add the passed in Target to the targets collection
* @param {Object} t The Target to add to the targets collection
*/
_regTarget: function(t) {
this.targets[this.targets.length] = t;
},
/**
* @private
* @method _unregTarget
* @description Remove the passed in Target from the targets collection
* @param {Object} drop The Target to remove from the targets collection
*/
_unregTarget: function(drop) {
var targets = [], vdrops;
Y.each(this.targets, function(v, k) {
if (v != drop) {
targets[targets.length] = v;
}
}, this);
this.targets = targets;
vdrops = [];
Y.each(this.validDrops, function(v, k) {
if (v !== drop) {
vdrops[vdrops.length] = v;
}
});
this.validDrops = vdrops;
},
/**
* @method getDrop
* @description Get a valid Drop instance back from a Node or a selector string, false otherwise
* @param {String/Object} node The Node instance or Selector string to check for a valid Drop Object
* @return {Object}
*/
getDrop: function(node) {
var drop = false,
n = Y.one(node);
if (n instanceof Y.Node) {
Y.each(this.targets, function(v, k) {
if (n.compareTo(v.get('node'))) {
drop = v;
}
});
}
return drop;
}
}, true);
}, '@VERSION@' ,{skinnable:false, requires:['dd-ddm']});
| potomak/cdnjs | ajax/libs/yui/3.6.0/dd-ddm-drop/dd-ddm-drop-debug.js | JavaScript | mit | 14,548 |
YUI.add("io-xdr",function(e,t){function a(e,t,n){var r='<object id="io_swf" type="application/x-shockwave-flash" data="'+e+'" width="0" height="0">'+'<param name="movie" value="'+e+'">'+'<param name="FlashVars" value="yid='+t+"&uid="+n+'">'+'<param name="allowScriptAccess" value="always">'+"</object>",i=s.createElement("div");s.body.appendChild(i),i.innerHTML=r}function f(t,n,r){return n==="flash"&&(t.c.responseText=decodeURI(t.c.responseText)),r==="xml"&&(t.c.responseXML=e.DataType.XML.parse(t.c.responseText)),t}function l(e,t){return e.c.abort(e.id,t)}function c(e){return u?i[e.id]!==4:e.c.isInProgress(e.id)}var n=e.publish("io:xdrReady",{fireOnce:!0}),r={},i={},s=e.config.doc,o=e.config.win,u=o&&o.XDomainRequest;e.mix(e.IO.prototype,{_transport:{},_ieEvt:function(e,t){var n=this,r=e.id,s="timeout";e.c.onprogress=function(){i[r]=3},e.c.onload=function(){i[r]=4,n.xdrResponse("success",e,t)},e.c.onerror=function(){i[r]=4,n.xdrResponse("failure",e,t)},e.c.ontimeout=function(){i[r]=4,n.xdrResponse(s,e,t)},e.c[s]=t[s]||0},xdr:function(t,n,i){var s=this;return i.xdr.use==="flash"?(r[n.id]=i,o.setTimeout(function(){try{n.c.send(t,{id:n.id,uid:n.uid,method:i.method,data:i.data,headers:i.headers})}catch(e){s.xdrResponse("transport error",n,i),delete r[n.id]}},e.io.xdr.delay)):u?(s._ieEvt(n,i),n.c.open(i.method||"GET",t),setTimeout(function(){n.c.send(i.data)},0)):n.c.send(t,n,i),{id:n.id,abort:function(){return n.c?l(n,i):!1},isInProgress:function(){return n.c?c(n.id):!1},io:s}},xdrResponse:function(e,t,n){n=r[t.id]?r[t.id]:n;var s=this,o=u?i:r,a=n.xdr.use,l=n.xdr.dataType;switch(e){case"start":s.start(t,n);break;case"success":s.success(f(t,a,l),n),delete o[t.id];break;case"timeout":case"abort":case"transport error":t.c={status:0,statusText:e};case"failure":s.failure(f(t,a,l),n),delete o[t.id]}},_xdrReady:function(t,r){e.fire(n,t,r)},transport:function(t){t.id==="flash"&&(a(e.UA.ie?t.src+"?d="+(new Date).valueOf().toString():t.src,e.id,t.uid),e.IO.transports.flash=function(){return s.getElementById("io_swf")})}}),e.io.xdrReady=function(t,n){var r=e.io._map[n];e.io.xdr.delay=0,r._xdrReady.apply(r,[t,n])},e.io.xdrResponse=function(t,n,r){var i=e.io._map[n.uid];i.xdrResponse.apply(i,[t,n,r])},e.io.transport=function(t){var n=e.io._map["io:0"]||new e.IO;t.uid=n._uid,n.transport.apply(n,[t])},e.io.xdr={delay:100}},"@VERSION@",{requires:["io-base","datatype-xml-parse"]});
| mariorez/cdnjs | ajax/libs/yui/3.11.0/io-xdr/io-xdr-min.js | JavaScript | mit | 2,402 |
YUI.add('async-queue', function (Y, NAME) {
/**
* <p>AsyncQueue allows you create a chain of function callbacks executed
* via setTimeout (or synchronously) that are guaranteed to run in order.
* Items in the queue can be promoted or removed. Start or resume the
* execution chain with run(). pause() to temporarily delay execution, or
* stop() to halt and clear the queue.</p>
*
* @module async-queue
*/
/**
* <p>A specialized queue class that supports scheduling callbacks to execute
* sequentially, iteratively, even asynchronously.</p>
*
* <p>Callbacks can be function refs or objects with the following keys. Only
* the <code>fn</code> key is required.</p>
*
* <ul>
* <li><code>fn</code> -- The callback function</li>
* <li><code>context</code> -- The execution context for the callbackFn.</li>
* <li><code>args</code> -- Arguments to pass to callbackFn.</li>
* <li><code>timeout</code> -- Millisecond delay before executing callbackFn.
* (Applies to each iterative execution of callback)</li>
* <li><code>iterations</code> -- Number of times to repeat the callback.
* <li><code>until</code> -- Repeat the callback until this function returns
* true. This setting trumps iterations.</li>
* <li><code>autoContinue</code> -- Set to false to prevent the AsyncQueue from
* executing the next callback in the Queue after
* the callback completes.</li>
* <li><code>id</code> -- Name that can be used to get, promote, get the
* indexOf, or delete this callback.</li>
* </ul>
*
* @class AsyncQueue
* @extends EventTarget
* @constructor
* @param callback* {Function|Object} 0..n callbacks to seed the queue
*/
Y.AsyncQueue = function() {
this._init();
this.add.apply(this, arguments);
};
var Queue = Y.AsyncQueue,
EXECUTE = 'execute',
SHIFT = 'shift',
PROMOTE = 'promote',
REMOVE = 'remove',
isObject = Y.Lang.isObject,
isFunction = Y.Lang.isFunction;
/**
* <p>Static default values used to populate callback configuration properties.
* Preconfigured defaults include:</p>
*
* <ul>
* <li><code>autoContinue</code>: <code>true</code></li>
* <li><code>iterations</code>: 1</li>
* <li><code>timeout</code>: 10 (10ms between callbacks)</li>
* <li><code>until</code>: (function to run until iterations <= 0)</li>
* </ul>
*
* @property defaults
* @type {Object}
* @static
*/
Queue.defaults = Y.mix({
autoContinue : true,
iterations : 1,
timeout : 10,
until : function () {
this.iterations |= 0;
return this.iterations <= 0;
}
}, Y.config.queueDefaults || {});
Y.extend(Queue, Y.EventTarget, {
/**
* Used to indicate the queue is currently executing a callback.
*
* @property _running
* @type {Boolean|Object} true for synchronous callback execution, the
* return handle from Y.later for async callbacks.
* Otherwise false.
* @protected
*/
_running : false,
/**
* Initializes the AsyncQueue instance properties and events.
*
* @method _init
* @protected
*/
_init : function () {
Y.EventTarget.call(this, { prefix: 'queue', emitFacade: true });
this._q = [];
/**
* Callback defaults for this instance. Static defaults that are not
* overridden are also included.
*
* @property defaults
* @type {Object}
*/
this.defaults = {};
this._initEvents();
},
/**
* Initializes the instance events.
*
* @method _initEvents
* @protected
*/
_initEvents : function () {
this.publish({
'execute' : { defaultFn : this._defExecFn, emitFacade: true },
'shift' : { defaultFn : this._defShiftFn, emitFacade: true },
'add' : { defaultFn : this._defAddFn, emitFacade: true },
'promote' : { defaultFn : this._defPromoteFn, emitFacade: true },
'remove' : { defaultFn : this._defRemoveFn, emitFacade: true }
});
},
/**
* Returns the next callback needing execution. If a callback is
* configured to repeat via iterations or until, it will be returned until
* the completion criteria is met.
*
* When the queue is empty, null is returned.
*
* @method next
* @return {Function} the callback to execute
*/
next : function () {
var callback;
while (this._q.length) {
callback = this._q[0] = this._prepare(this._q[0]);
if (callback && callback.until()) {
this.fire(SHIFT, { callback: callback });
callback = null;
} else {
break;
}
}
return callback || null;
},
/**
* Default functionality for the "shift" event. Shifts the
* callback stored in the event object's <em>callback</em> property from
* the queue if it is the first item.
*
* @method _defShiftFn
* @param e {Event} The event object
* @protected
*/
_defShiftFn : function (e) {
if (this.indexOf(e.callback) === 0) {
this._q.shift();
}
},
/**
* Creates a wrapper function to execute the callback using the aggregated
* configuration generated by combining the static AsyncQueue.defaults, the
* instance defaults, and the specified callback settings.
*
* The wrapper function is decorated with the callback configuration as
* properties for runtime modification.
*
* @method _prepare
* @param callback {Object|Function} the raw callback
* @return {Function} a decorated function wrapper to execute the callback
* @protected
*/
_prepare: function (callback) {
if (isFunction(callback) && callback._prepared) {
return callback;
}
var config = Y.merge(
Queue.defaults,
{ context : this, args: [], _prepared: true },
this.defaults,
(isFunction(callback) ? { fn: callback } : callback)),
wrapper = Y.bind(function () {
if (!wrapper._running) {
wrapper.iterations--;
}
if (isFunction(wrapper.fn)) {
wrapper.fn.apply(wrapper.context || Y,
Y.Array(wrapper.args));
}
}, this);
return Y.mix(wrapper, config);
},
/**
* Sets the queue in motion. All queued callbacks will be executed in
* order unless pause() or stop() is called or if one of the callbacks is
* configured with autoContinue: false.
*
* @method run
* @return {AsyncQueue} the AsyncQueue instance
* @chainable
*/
run : function () {
var callback,
cont = true;
for (callback = this.next();
cont && callback && !this.isRunning();
callback = this.next())
{
cont = (callback.timeout < 0) ?
this._execute(callback) :
this._schedule(callback);
}
if (!callback) {
/**
* Event fired after the last queued callback is executed.
* @event complete
*/
this.fire('complete');
}
return this;
},
/**
* Handles the execution of callbacks. Returns a boolean indicating
* whether it is appropriate to continue running.
*
* @method _execute
* @param callback {Object} the callback object to execute
* @return {Boolean} whether the run loop should continue
* @protected
*/
_execute : function (callback) {
this._running = callback._running = true;
callback.iterations--;
this.fire(EXECUTE, { callback: callback });
var cont = this._running && callback.autoContinue;
this._running = callback._running = false;
return cont;
},
/**
* Schedules the execution of asynchronous callbacks.
*
* @method _schedule
* @param callback {Object} the callback object to execute
* @return {Boolean} whether the run loop should continue
* @protected
*/
_schedule : function (callback) {
this._running = Y.later(callback.timeout, this, function () {
if (this._execute(callback)) {
this.run();
}
});
return false;
},
/**
* Determines if the queue is waiting for a callback to complete execution.
*
* @method isRunning
* @return {Boolean} true if queue is waiting for a
* from any initiated transactions
*/
isRunning : function () {
return !!this._running;
},
/**
* Default functionality for the "execute" event. Executes the
* callback function
*
* @method _defExecFn
* @param e {Event} the event object
* @protected
*/
_defExecFn : function (e) {
e.callback();
},
/**
* Add any number of callbacks to the end of the queue. Callbacks may be
* provided as functions or objects.
*
* @method add
* @param callback* {Function|Object} 0..n callbacks
* @return {AsyncQueue} the AsyncQueue instance
* @chainable
*/
add : function () {
this.fire('add', { callbacks: Y.Array(arguments,0,true) });
return this;
},
/**
* Default functionality for the "add" event. Adds the callbacks
* in the event facade to the queue. Callbacks successfully added to the
* queue are present in the event's <code>added</code> property in the
* after phase.
*
* @method _defAddFn
* @param e {Event} the event object
* @protected
*/
_defAddFn : function(e) {
var _q = this._q,
added = [];
Y.Array.each(e.callbacks, function (c) {
if (isObject(c)) {
_q.push(c);
added.push(c);
}
});
e.added = added;
},
/**
* Pause the execution of the queue after the execution of the current
* callback completes. If called from code outside of a queued callback,
* clears the timeout for the pending callback. Paused queue can be
* restarted with q.run()
*
* @method pause
* @return {AsyncQueue} the AsyncQueue instance
* @chainable
*/
pause: function () {
if (isObject(this._running)) {
this._running.cancel();
}
this._running = false;
return this;
},
/**
* Stop and clear the queue after the current execution of the
* current callback completes.
*
* @method stop
* @return {AsyncQueue} the AsyncQueue instance
* @chainable
*/
stop : function () {
this._q = [];
return this.pause();
},
/**
* Returns the current index of a callback. Pass in either the id or
* callback function from getCallback.
*
* @method indexOf
* @param callback {String|Function} the callback or its specified id
* @return {Number} index of the callback or -1 if not found
*/
indexOf : function (callback) {
var i = 0, len = this._q.length, c;
for (; i < len; ++i) {
c = this._q[i];
if (c === callback || c.id === callback) {
return i;
}
}
return -1;
},
/**
* Retrieve a callback by its id. Useful to modify the configuration
* while the queue is running.
*
* @method getCallback
* @param id {String} the id assigned to the callback
* @return {Object} the callback object
*/
getCallback : function (id) {
var i = this.indexOf(id);
return (i > -1) ? this._q[i] : null;
},
/**
* Promotes the named callback to the top of the queue. If a callback is
* currently executing or looping (via until or iterations), the promotion
* is scheduled to occur after the current callback has completed.
*
* @method promote
* @param callback {String|Object} the callback object or a callback's id
* @return {AsyncQueue} the AsyncQueue instance
* @chainable
*/
promote : function (callback) {
var payload = { callback : callback },e;
if (this.isRunning()) {
e = this.after(SHIFT, function () {
this.fire(PROMOTE, payload);
e.detach();
}, this);
} else {
this.fire(PROMOTE, payload);
}
return this;
},
/**
* <p>Default functionality for the "promote" event. Promotes the
* named callback to the head of the queue.</p>
*
* <p>The event object will contain a property "callback", which
* holds the id of a callback or the callback object itself.</p>
*
* @method _defPromoteFn
* @param e {Event} the custom event
* @protected
*/
_defPromoteFn : function (e) {
var i = this.indexOf(e.callback),
promoted = (i > -1) ? this._q.splice(i,1)[0] : null;
e.promoted = promoted;
if (promoted) {
this._q.unshift(promoted);
}
},
/**
* Removes the callback from the queue. If the queue is active, the
* removal is scheduled to occur after the current callback has completed.
*
* @method remove
* @param callback {String|Object} the callback object or a callback's id
* @return {AsyncQueue} the AsyncQueue instance
* @chainable
*/
remove : function (callback) {
var payload = { callback : callback },e;
// Can't return the removed callback because of the deferral until
// current callback is complete
if (this.isRunning()) {
e = this.after(SHIFT, function () {
this.fire(REMOVE, payload);
e.detach();
},this);
} else {
this.fire(REMOVE, payload);
}
return this;
},
/**
* <p>Default functionality for the "remove" event. Removes the
* callback from the queue.</p>
*
* <p>The event object will contain a property "callback", which
* holds the id of a callback or the callback object itself.</p>
*
* @method _defRemoveFn
* @param e {Event} the custom event
* @protected
*/
_defRemoveFn : function (e) {
var i = this.indexOf(e.callback);
e.removed = (i > -1) ? this._q.splice(i,1)[0] : null;
},
/**
* Returns the number of callbacks in the queue.
*
* @method size
* @return {Number}
*/
size : function () {
// next() flushes callbacks that have met their until() criteria and
// therefore shouldn't count since they wouldn't execute anyway.
if (!this.isRunning()) {
this.next();
}
return this._q.length;
}
});
}, '@VERSION@', {"requires": ["event-custom"]});
| froala/cdnjs | ajax/libs/yui/3.10.1/async-queue/async-queue.js | JavaScript | mit | 15,382 |
YUI.add('dom-deprecated', function (Y, NAME) {
Y.mix(Y.DOM, {
// @deprecated
children: function(node, tag) {
var ret = [];
if (node) {
tag = tag || '*';
ret = Y.Selector.query('> ' + tag, node);
}
return ret;
},
// @deprecated
firstByTag: function(tag, root) {
var ret;
root = root || Y.config.doc;
if (tag && root.getElementsByTagName) {
ret = root.getElementsByTagName(tag)[0];
}
return ret || null;
},
/*
* Finds the previous sibling of the element.
* @method previous
* @deprecated Use elementByAxis
* @param {HTMLElement} element The html element.
* @param {Function} fn optional An optional boolean test to apply.
* The optional function is passed the current DOM node being tested as its only argument.
* If no function is given, the first sibling is returned.
* @param {Boolean} all optional Whether all node types should be scanned, or just element nodes.
* @return {HTMLElement | null} The matching DOM node or null if none found.
*/
previous: function(element, fn, all) {
return Y.DOM.elementByAxis(element, 'previousSibling', fn, all);
},
/*
* Finds the next sibling of the element.
* @method next
* @deprecated Use elementByAxis
* @param {HTMLElement} element The html element.
* @param {Function} fn optional An optional boolean test to apply.
* The optional function is passed the current DOM node being tested as its only argument.
* If no function is given, the first sibling is returned.
* @param {Boolean} all optional Whether all node types should be scanned, or just element nodes.
* @return {HTMLElement | null} The matching DOM node or null if none found.
*/
next: function(element, fn, all) {
return Y.DOM.elementByAxis(element, 'nextSibling', fn, all);
}
});
}, '@VERSION@', {"requires": ["dom-base"]});
| xubowenjx/cdnjs | ajax/libs/yui/3.9.0/dom-deprecated/dom-deprecated-debug.js | JavaScript | mit | 2,015 |
YUI.add('color-hsv', function (Y, NAME) {
/**
Color provides static methods for color conversion hsv values.
Y.Color.toHSV('f00'); // hsv(0, 100%, 100%)
Y.Color.toHSVA('rgb(255, 255, 0'); // hsva(60, 100%, 100%, 1)
@module color
@submodule color-hsv
@class HSV
@namespace Color
@since 3.8.0
**/
Color = {
/**
@static
@property REGEX_HSV
@type RegExp
@default /hsva?\(([.\d]*), ?([.\d]*)%, ?([.\d]*)%,? ?([.\d]*)?\)/
@since 3.8.0
**/
REGEX_HSV: /hsva?\(([.\d]*), ?([.\d]*)%, ?([.\d]*)%,? ?([.\d]*)?\)/,
/**
@static
@property STR_HSV
@type String
@default hsv({*}, {*}%, {*}%)
@since 3.8.0
**/
STR_HSV: 'hsv({*}, {*}%, {*}%)',
/**
@static
@property STR_HSVA
@type String
@default hsva({*}, {*}%, {*}%, {*})
@since 3.8.0
**/
STR_HSVA: 'hsva({*}, {*}%, {*}%, {*})',
/**
Converts provided color value to an HSV string.
@public
@method toHSV
@param {String} str
@return {String}
@since 3.8.0
**/
toHSV: function (str) {
var clr = Y.Color._convertTo(str, 'hsv');
return clr.toLowerCase();
},
/**
Converts provided color value to an HSVA string.
@public
@method toHSVA
@param {String} str
@return {String}
@since 3.8.0
**/
toHSVA: function (str) {
var clr = Y.Color._convertTo(str, 'hsva');
return clr.toLowerCase();
},
/**
Parses the RGB string into h, s, v values. Will return an Array
of values or an HSV string.
@protected
@method _rgbToHsv
@param {String} str
@param {Boolean} [toArray]
@return {String|Array}
@since 3.8.0
**/
_rgbToHsv: function (str, toArray) {
var h, s, v,
rgb = Y.Color.REGEX_RGB.exec(str),
r = rgb[1] / 255,
g = rgb[2] / 255,
b = rgb[3] / 255,
max = Math.max(r, g, b),
min = Math.min(r, g, b),
delta = max - min;
if (max === min) {
h = 0;
} else if (max === r) {
h = 60 * (g - b) / delta;
} else if (max === g) {
h = (60 * (b - r) / delta) + 120;
} else { // max === b
h = (60 * (r - g) / delta) + 240;
}
s = (max === 0) ? 0 : 1 - (min / max);
// ensure h is between 0 and 360
while (h < 0) {
h += 360;
}
h %= 360;
h = Math.round(h);
// saturation is percentage
s = Math.round(s * 100);
// value is percentage
v = Math.round(max * 100);
if (toArray) {
return [h, s, v];
}
return Y.Color.fromArray([h, s, v], Y.Color.TYPES.HSV);
},
/**
Parses the HSV string into r, b, g values. Will return an Array
of values or an RGB string.
@protected
@method _hsvToRgb
@param {String} str
@param {Boolean} [toArray]
@return {String|Array}
@since 3.8.0
**/
_hsvToRgb: function (str, toArray) {
var hsv = Y.Color.REGEX_HSV.exec(str),
h = parseInt(hsv[1], 10),
s = parseInt(hsv[2], 10) / 100, // 0 - 1
v = parseInt(hsv[3], 10) / 100, // 0 - 1
r,
g,
b,
i = Math.floor(h / 60) % 6,
f = (h / 60) - i,
p = v * (1 - s),
q = v * (1 - (s * f)),
t = v * (1 - (s * (1 - f)));
if (s === 0) {
r = v;
g = v;
b = v;
} else {
switch (i) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
}
r = Math.min(255, Math.round(r * 256));
g = Math.min(255, Math.round(g * 256));
b = Math.min(255, Math.round(b * 256));
if (toArray) {
return [r, g, b];
}
return Y.Color.fromArray([r, g, b], Y.Color.TYPES.RGB);
}
};
Y.Color = Y.mix(Color, Y.Color);
Y.Color.TYPES = Y.mix(Y.Color.TYPES, {'HSV':'hsv', 'HSVA':'hsva'});
Y.Color.CONVERTS = Y.mix(Y.Color.CONVERTS, {'hsv': 'toHSV', 'hsva': 'toHSVA'});
}, '@VERSION@', {"requires": ["color-base"]});
| amoyeh/cdnjs | ajax/libs/yui/3.18.1/color-hsv/color-hsv.js | JavaScript | mit | 4,428 |
package vun_TZ
import (
"math"
"strconv"
"time"
"github.com/go-playground/locales"
"github.com/go-playground/locales/currency"
)
type vun_TZ struct {
locale string
pluralsCardinal []locales.PluralRule
pluralsOrdinal []locales.PluralRule
pluralsRange []locales.PluralRule
decimal string
group string
minus string
percent string
perMille string
timeSeparator string
inifinity string
currencies []string // idx = enum of currency code
monthsAbbreviated []string
monthsNarrow []string
monthsWide []string
daysAbbreviated []string
daysNarrow []string
daysShort []string
daysWide []string
periodsAbbreviated []string
periodsNarrow []string
periodsShort []string
periodsWide []string
erasAbbreviated []string
erasNarrow []string
erasWide []string
timezones map[string]string
}
// New returns a new instance of translator for the 'vun_TZ' locale
func New() locales.Translator {
return &vun_TZ{
locale: "vun_TZ",
pluralsCardinal: []locales.PluralRule{2, 6},
pluralsOrdinal: nil,
pluralsRange: nil,
timeSeparator: ":",
currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UZS", "VEB", "VEF", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"},
monthsAbbreviated: []string{"", "Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ago", "Sep", "Okt", "Nov", "Des"},
monthsNarrow: []string{"", "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"},
monthsWide: []string{"", "Januari", "Februari", "Machi", "Aprilyi", "Mei", "Junyi", "Julyai", "Agusti", "Septemba", "Oktoba", "Novemba", "Desemba"},
daysAbbreviated: []string{"Jpi", "Jtt", "Jnn", "Jtn", "Alh", "Iju", "Jmo"},
daysNarrow: []string{"J", "J", "J", "J", "A", "I", "J"},
daysWide: []string{"Jumapilyi", "Jumatatuu", "Jumanne", "Jumatanu", "Alhamisi", "Ijumaa", "Jumamosi"},
periodsAbbreviated: []string{"utuko", "kyiukonyi"},
periodsWide: []string{"utuko", "kyiukonyi"},
erasAbbreviated: []string{"KK", "BK"},
erasNarrow: []string{"", ""},
erasWide: []string{"Kabla ya Kristu", "Baada ya Kristu"},
timezones: map[string]string{"WESZ": "WESZ", "CLT": "CLT", "ACST": "ACST", "COT": "COT", "WITA": "WITA", "CDT": "CDT", "CAT": "CAT", "AKST": "AKST", "EAT": "EAT", "HECU": "HECU", "HKST": "HKST", "HNPM": "HNPM", "ACWST": "ACWST", "ACWDT": "ACWDT", "JDT": "JDT", "OEZ": "OEZ", "HNCU": "HNCU", "CST": "CST", "HADT": "HADT", "HNOG": "HNOG", "ART": "ART", "WAST": "WAST", "BT": "BT", "SAST": "SAST", "HNPMX": "HNPMX", "WIB": "WIB", "NZDT": "NZDT", "HKT": "HKT", "COST": "COST", "HNEG": "HNEG", "NZST": "NZST", "VET": "VET", "AST": "AST", "GMT": "GMT", "GYT": "GYT", "PDT": "PDT", "ECT": "ECT", "JST": "JST", "HENOMX": "HENOMX", "HEEG": "HEEG", "ChST": "ChST", "AWST": "AWST", "SGT": "SGT", "MDT": "MDT", "HAT": "HAT", "AEDT": "AEDT", "UYST": "UYST", "AWDT": "AWDT", "IST": "IST", "ADT": "ADT", "CLST": "CLST", "TMST": "TMST", "LHDT": "LHDT", "CHAST": "CHAST", "HEOG": "HEOG", "WARST": "WARST", "ACDT": "ACDT", "HEPMX": "HEPMX", "HAST": "HAST", "TMT": "TMT", "MST": "MST", "HNT": "HNT", "GFT": "GFT", "BOT": "BOT", "MYT": "MYT", "WART": "WART", "ARST": "ARST", "EST": "EST", "HEPM": "HEPM", "LHST": "LHST", "SRT": "SRT", "WEZ": "WEZ", "EDT": "EDT", "HNNOMX": "HNNOMX", "∅∅∅": "∅∅∅", "WAT": "WAT", "AKDT": "AKDT", "AEST": "AEST", "UYT": "UYT", "WIT": "WIT", "PST": "PST", "OESZ": "OESZ", "CHADT": "CHADT", "MEZ": "MEZ", "MESZ": "MESZ"},
}
}
// Locale returns the current translators string locale
func (vun *vun_TZ) Locale() string {
return vun.locale
}
// PluralsCardinal returns the list of cardinal plural rules associated with 'vun_TZ'
func (vun *vun_TZ) PluralsCardinal() []locales.PluralRule {
return vun.pluralsCardinal
}
// PluralsOrdinal returns the list of ordinal plural rules associated with 'vun_TZ'
func (vun *vun_TZ) PluralsOrdinal() []locales.PluralRule {
return vun.pluralsOrdinal
}
// PluralsRange returns the list of range plural rules associated with 'vun_TZ'
func (vun *vun_TZ) PluralsRange() []locales.PluralRule {
return vun.pluralsRange
}
// CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'vun_TZ'
func (vun *vun_TZ) CardinalPluralRule(num float64, v uint64) locales.PluralRule {
n := math.Abs(num)
if n == 1 {
return locales.PluralRuleOne
}
return locales.PluralRuleOther
}
// OrdinalPluralRule returns the ordinal PluralRule given 'num' and digits/precision of 'v' for 'vun_TZ'
func (vun *vun_TZ) OrdinalPluralRule(num float64, v uint64) locales.PluralRule {
return locales.PluralRuleUnknown
}
// RangePluralRule returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for 'vun_TZ'
func (vun *vun_TZ) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule {
return locales.PluralRuleUnknown
}
// MonthAbbreviated returns the locales abbreviated month given the 'month' provided
func (vun *vun_TZ) MonthAbbreviated(month time.Month) string {
return vun.monthsAbbreviated[month]
}
// MonthsAbbreviated returns the locales abbreviated months
func (vun *vun_TZ) MonthsAbbreviated() []string {
return vun.monthsAbbreviated[1:]
}
// MonthNarrow returns the locales narrow month given the 'month' provided
func (vun *vun_TZ) MonthNarrow(month time.Month) string {
return vun.monthsNarrow[month]
}
// MonthsNarrow returns the locales narrow months
func (vun *vun_TZ) MonthsNarrow() []string {
return vun.monthsNarrow[1:]
}
// MonthWide returns the locales wide month given the 'month' provided
func (vun *vun_TZ) MonthWide(month time.Month) string {
return vun.monthsWide[month]
}
// MonthsWide returns the locales wide months
func (vun *vun_TZ) MonthsWide() []string {
return vun.monthsWide[1:]
}
// WeekdayAbbreviated returns the locales abbreviated weekday given the 'weekday' provided
func (vun *vun_TZ) WeekdayAbbreviated(weekday time.Weekday) string {
return vun.daysAbbreviated[weekday]
}
// WeekdaysAbbreviated returns the locales abbreviated weekdays
func (vun *vun_TZ) WeekdaysAbbreviated() []string {
return vun.daysAbbreviated
}
// WeekdayNarrow returns the locales narrow weekday given the 'weekday' provided
func (vun *vun_TZ) WeekdayNarrow(weekday time.Weekday) string {
return vun.daysNarrow[weekday]
}
// WeekdaysNarrow returns the locales narrow weekdays
func (vun *vun_TZ) WeekdaysNarrow() []string {
return vun.daysNarrow
}
// WeekdayShort returns the locales short weekday given the 'weekday' provided
func (vun *vun_TZ) WeekdayShort(weekday time.Weekday) string {
return vun.daysShort[weekday]
}
// WeekdaysShort returns the locales short weekdays
func (vun *vun_TZ) WeekdaysShort() []string {
return vun.daysShort
}
// WeekdayWide returns the locales wide weekday given the 'weekday' provided
func (vun *vun_TZ) WeekdayWide(weekday time.Weekday) string {
return vun.daysWide[weekday]
}
// WeekdaysWide returns the locales wide weekdays
func (vun *vun_TZ) WeekdaysWide() []string {
return vun.daysWide
}
// FmtNumber returns 'num' with digits/precision of 'v' for 'vun_TZ' and handles both Whole and Real numbers based on 'v'
func (vun *vun_TZ) FmtNumber(num float64, v uint64) string {
return strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
}
// FmtPercent returns 'num' with digits/precision of 'v' for 'vun_TZ' and handles both Whole and Real numbers based on 'v'
// NOTE: 'num' passed into FmtPercent is assumed to be in percent already
func (vun *vun_TZ) FmtPercent(num float64, v uint64) string {
return strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
}
// FmtCurrency returns the currency representation of 'num' with digits/precision of 'v' for 'vun_TZ'
func (vun *vun_TZ) FmtCurrency(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := vun.currencies[currency]
l := len(s) + len(symbol) + 0 + 0*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, vun.decimal[0])
inWhole = true
continue
}
if inWhole {
if count == 3 {
b = append(b, vun.group[0])
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
for j := len(symbol) - 1; j >= 0; j-- {
b = append(b, symbol[j])
}
if num < 0 {
b = append(b, vun.minus[0])
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, vun.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
return string(b)
}
// FmtAccounting returns the currency representation of 'num' with digits/precision of 'v' for 'vun_TZ'
// in accounting notation.
func (vun *vun_TZ) FmtAccounting(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := vun.currencies[currency]
l := len(s) + len(symbol) + 0 + 0*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, vun.decimal[0])
inWhole = true
continue
}
if inWhole {
if count == 3 {
b = append(b, vun.group[0])
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
for j := len(symbol) - 1; j >= 0; j-- {
b = append(b, symbol[j])
}
b = append(b, vun.minus[0])
} else {
for j := len(symbol) - 1; j >= 0; j-- {
b = append(b, symbol[j])
}
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, vun.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
return string(b)
}
// FmtDateShort returns the short date representation of 't' for 'vun_TZ'
func (vun *vun_TZ) FmtDateShort(t time.Time) string {
b := make([]byte, 0, 32)
if t.Day() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x2f}...)
if t.Month() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Month()), 10)
b = append(b, []byte{0x2f}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(t.Year()*-1), 10)
}
return string(b)
}
// FmtDateMedium returns the medium date representation of 't' for 'vun_TZ'
func (vun *vun_TZ) FmtDateMedium(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, vun.monthsAbbreviated[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(t.Year()*-1), 10)
}
return string(b)
}
// FmtDateLong returns the long date representation of 't' for 'vun_TZ'
func (vun *vun_TZ) FmtDateLong(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, vun.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(t.Year()*-1), 10)
}
return string(b)
}
// FmtDateFull returns the full date representation of 't' for 'vun_TZ'
func (vun *vun_TZ) FmtDateFull(t time.Time) string {
b := make([]byte, 0, 32)
b = append(b, vun.daysWide[t.Weekday()]...)
b = append(b, []byte{0x2c, 0x20}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, vun.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(t.Year()*-1), 10)
}
return string(b)
}
// FmtTimeShort returns the short time representation of 't' for 'vun_TZ'
func (vun *vun_TZ) FmtTimeShort(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, vun.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
return string(b)
}
// FmtTimeMedium returns the medium time representation of 't' for 'vun_TZ'
func (vun *vun_TZ) FmtTimeMedium(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, vun.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, vun.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
return string(b)
}
// FmtTimeLong returns the long time representation of 't' for 'vun_TZ'
func (vun *vun_TZ) FmtTimeLong(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, vun.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, vun.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
tz, _ := t.Zone()
b = append(b, tz...)
return string(b)
}
// FmtTimeFull returns the full time representation of 't' for 'vun_TZ'
func (vun *vun_TZ) FmtTimeFull(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, vun.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, vun.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
tz, _ := t.Zone()
if btz, ok := vun.timezones[tz]; ok {
b = append(b, btz...)
} else {
b = append(b, tz...)
}
return string(b)
}
| RobBagby/acs-engine | vendor/github.com/go-playground/locales/vun_TZ/vun_TZ.go | GO | mit | 16,269 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {
MatCommonModule,
MatLineModule,
MatPseudoCheckboxModule,
MatRippleModule,
} from '@angular/material/core';
import {
MatList,
MatNavList,
MatListAvatarCssMatStyler,
MatListIconCssMatStyler,
MatListItem,
MatListSubheaderCssMatStyler,
} from './list';
import {MatListOption, MatSelectionList} from './selection-list';
import {MatDividerModule} from '@angular/material/divider';
@NgModule({
imports: [MatLineModule, MatRippleModule, MatCommonModule, MatPseudoCheckboxModule, CommonModule],
exports: [
MatList,
MatNavList,
MatListItem,
MatListAvatarCssMatStyler,
MatLineModule,
MatCommonModule,
MatListIconCssMatStyler,
MatListSubheaderCssMatStyler,
MatPseudoCheckboxModule,
MatSelectionList,
MatListOption,
MatDividerModule
],
declarations: [
MatList,
MatNavList,
MatListItem,
MatListAvatarCssMatStyler,
MatListIconCssMatStyler,
MatListSubheaderCssMatStyler,
MatSelectionList,
MatListOption
],
})
export class MatListModule {}
| willshowell/material2 | src/lib/list/list-module.ts | TypeScript | mit | 1,333 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace AutoMapper.UnitTests.Bug
{
public class IgnoreShouldBeInheritedIfConventionCannotMap
{
public class BaseDomain
{
}
public class StandardDomain : BaseDomain
{
}
public class SpecificDomain : StandardDomain
{
}
public class MoreSpecificDomain : SpecificDomain
{
}
public class Dto
{
public string SpecificProperty { get; set; }
}
[Fact]
public void inhertited_ignore_should_be_overridden_passes_validation()
{
Mapper.CreateMap<BaseDomain, Dto>()
.ForMember(d => d.SpecificProperty, m => m.Ignore())
.Include<StandardDomain, Dto>();
Mapper.CreateMap<StandardDomain, Dto>()
.Include<SpecificDomain, Dto>();
Mapper.CreateMap<SpecificDomain, Dto>()
.Include<MoreSpecificDomain, Dto>();
Mapper.CreateMap<MoreSpecificDomain, Dto>();
Mapper.AssertConfigurationIsValid();
}
}
}
| peterchase/AutoMapper | src/UnitTests/MappingInheritance/IgnoreShouldBeInheritedIfConventionCannotMap.cs | C# | mit | 1,217 |
# frozen_string_literal: true
require "abstract_unit"
require "active_support/json"
class ErbUtilTest < ActiveSupport::TestCase
include ERB::Util
ERB::Util::HTML_ESCAPE.each do |given, expected|
define_method "test_html_escape_#{expected.gsub(/\W/, '')}" do
assert_equal expected, html_escape(given)
end
end
ERB::Util::JSON_ESCAPE.each do |given, expected|
define_method "test_json_escape_#{expected.gsub(/\W/, '')}" do
assert_equal ERB::Util::JSON_ESCAPE[given], json_escape(given)
end
end
HTML_ESCAPE_TEST_CASES = [
["<br>", "<br>"],
["a & b", "a & b"],
['"quoted" string', ""quoted" string"],
["'quoted' string", "'quoted' string"],
[
'<script type="application/javascript">alert("You are \'pwned\'!")</script>',
"<script type="application/javascript">alert("You are 'pwned'!")</script>"
]
]
JSON_ESCAPE_TEST_CASES = [
["1", "1"],
["null", "null"],
['"&"', '"\u0026"'],
['"</script>"', '"\u003c/script\u003e"'],
['["</script>"]', '["\u003c/script\u003e"]'],
['{"name":"</script>"}', '{"name":"\u003c/script\u003e"}'],
[%({"name":"d\u2028h\u2029h"}), '{"name":"d\u2028h\u2029h"}']
]
def test_html_escape
HTML_ESCAPE_TEST_CASES.each do |(raw, expected)|
assert_equal expected, html_escape(raw)
end
end
def test_json_escape
JSON_ESCAPE_TEST_CASES.each do |(raw, expected)|
assert_equal expected, json_escape(raw)
end
end
def test_json_escape_does_not_alter_json_string_meaning
JSON_ESCAPE_TEST_CASES.each do |(raw, _)|
expected = ActiveSupport::JSON.decode(raw)
if expected.nil?
assert_nil ActiveSupport::JSON.decode(json_escape(raw))
else
assert_equal expected, ActiveSupport::JSON.decode(json_escape(raw))
end
end
end
def test_json_escape_is_idempotent
JSON_ESCAPE_TEST_CASES.each do |(raw, _)|
assert_equal json_escape(raw), json_escape(json_escape(raw))
end
end
def test_json_escape_returns_unsafe_strings_when_passed_unsafe_strings
value = json_escape("asdf")
assert !value.html_safe?
end
def test_json_escape_returns_safe_strings_when_passed_safe_strings
value = json_escape("asdf".html_safe)
assert value.html_safe?
end
def test_html_escape_is_html_safe
escaped = h("<p>")
assert_equal "<p>", escaped
assert escaped.html_safe?
end
def test_html_escape_passes_html_escape_unmodified
escaped = h("<p>".html_safe)
assert_equal "<p>", escaped
assert escaped.html_safe?
end
def test_rest_in_ascii
(0..127).to_a.map(&:chr).each do |chr|
next if %('"&<>).include?(chr)
assert_equal chr, html_escape(chr)
end
end
def test_html_escape_once
assert_equal "1 <>&"' 2 & 3", html_escape_once('1 <>&"\' 2 & 3')
assert_equal " ' ' λ λ " ' < > ", html_escape_once(" ' ' λ λ \" ' < > ")
end
def test_html_escape_once_returns_unsafe_strings_when_passed_unsafe_strings
value = html_escape_once("1 < 2 & 3")
assert !value.html_safe?
end
def test_html_escape_once_returns_safe_strings_when_passed_safe_strings
value = html_escape_once("1 < 2 & 3".html_safe)
assert value.html_safe?
end
end
| felipecvo/rails | actionview/test/template/erb_util_test.rb | Ruby | mit | 3,397 |
package ps_AF
import (
"math"
"strconv"
"time"
"github.com/go-playground/locales"
"github.com/go-playground/locales/currency"
)
type ps_AF struct {
locale string
pluralsCardinal []locales.PluralRule
pluralsOrdinal []locales.PluralRule
pluralsRange []locales.PluralRule
decimal string
group string
minus string
percent string
perMille string
timeSeparator string
inifinity string
currencies []string // idx = enum of currency code
currencyPositiveSuffix string
currencyNegativeSuffix string
monthsAbbreviated []string
monthsNarrow []string
monthsWide []string
daysAbbreviated []string
daysNarrow []string
daysShort []string
daysWide []string
periodsAbbreviated []string
periodsNarrow []string
periodsShort []string
periodsWide []string
erasAbbreviated []string
erasNarrow []string
erasWide []string
timezones map[string]string
}
// New returns a new instance of translator for the 'ps_AF' locale
func New() locales.Translator {
return &ps_AF{
locale: "ps_AF",
pluralsCardinal: []locales.PluralRule{2, 6},
pluralsOrdinal: nil,
pluralsRange: nil,
decimal: "٫",
group: "٬",
minus: "-",
percent: "٪",
perMille: "؉",
timeSeparator: ":",
inifinity: "∞",
currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UZS", "VEB", "VEF", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"},
currencyPositiveSuffix: " ",
currencyNegativeSuffix: " ",
monthsAbbreviated: []string{"", "جنوري", "فبروري", "مارچ", "اپریل", "مۍ", "جون", "جولای", "اګست", "سپتمبر", "اکتوبر", "نومبر", "دسمبر"},
monthsNarrow: []string{"", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"},
monthsWide: []string{"", "جنوري", "فبروري", "مارچ", "اپریل", "مۍ", "جون", "جولای", "اګست", "سپتمبر", "اکتوبر", "نومبر", "دسمبر"},
daysAbbreviated: []string{"یکشنبه", "دوشنبه", "سه\u200cشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه"},
daysShort: []string{"یکشنبه", "دوشنبه", "سه\u200cشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه"},
daysWide: []string{"یکشنبه", "دوشنبه", "سه\u200cشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه"},
periodsAbbreviated: []string{"غ.م.", "غ.و."},
periodsNarrow: []string{"غ.م.", "غ.و."},
periodsWide: []string{"غ.م.", "غ.و."},
erasAbbreviated: []string{"له میلاد وړاندې", "م."},
erasNarrow: []string{"", ""},
erasWide: []string{"له میلاد څخه وړاندې", "له میلاد څخه وروسته"},
timezones: map[string]string{"SAST": "SAST", "MYT": "MYT", "CLST": "CLST", "AST": "AST", "TMST": "TMST", "HNPMX": "HNPMX", "VET": "VET", "WAST": "WAST", "EST": "EST", "HEEG": "HEEG", "SRT": "SRT", "WIT": "WIT", "CHAST": "CHAST", "NZST": "NZST", "HEOG": "HEOG", "HNEG": "HNEG", "BT": "BT", "HNPM": "HNPM", "EAT": "EAT", "BOT": "BOT", "CLT": "CLT", "OESZ": "OESZ", "MST": "MST", "GYT": "GYT", "CHADT": "CHADT", "PST": "PST", "MEZ": "MEZ", "ARST": "ARST", "HNT": "HNT", "HAT": "HAT", "WITA": "WITA", "∅∅∅": "∅∅∅", "LHDT": "LHDT", "WIB": "WIB", "ECT": "ECT", "CAT": "CAT", "WARST": "WARST", "AKDT": "AKDT", "ChST": "ChST", "UYT": "UYT", "LHST": "LHST", "PDT": "PDT", "NZDT": "NZDT", "WEZ": "د لودیځې اروپا معیاري وخت", "GMT": "گرينويچ وخت", "MDT": "MDT", "ACST": "ACST", "AWST": "AWST", "AWDT": "AWDT", "ACWDT": "ACWDT", "ADT": "ADT", "TMT": "TMT", "COST": "COST", "AEDT": "AEDT", "HEPM": "HEPM", "HECU": "HECU", "SGT": "SGT", "HAST": "HAST", "WESZ": "د لودیځې اورپا د اوړي وخت", "ART": "ART", "HEPMX": "HEPMX", "IST": "IST", "HNOG": "HNOG", "HENOMX": "HENOMX", "AKST": "AKST", "HKST": "HKST", "HNNOMX": "HNNOMX", "GFT": "GFT", "HNCU": "HNCU", "CDT": "CDT", "HADT": "HADT", "JDT": "JDT", "WART": "WART", "MESZ": "MESZ", "OEZ": "OEZ", "EDT": "EDT", "ACDT": "ACDT", "COT": "COT", "UYST": "UYST", "CST": "CST", "ACWST": "ACWST", "HKT": "HKT", "WAT": "WAT", "AEST": "AEST", "JST": "JST"},
}
}
// Locale returns the current translators string locale
func (ps *ps_AF) Locale() string {
return ps.locale
}
// PluralsCardinal returns the list of cardinal plural rules associated with 'ps_AF'
func (ps *ps_AF) PluralsCardinal() []locales.PluralRule {
return ps.pluralsCardinal
}
// PluralsOrdinal returns the list of ordinal plural rules associated with 'ps_AF'
func (ps *ps_AF) PluralsOrdinal() []locales.PluralRule {
return ps.pluralsOrdinal
}
// PluralsRange returns the list of range plural rules associated with 'ps_AF'
func (ps *ps_AF) PluralsRange() []locales.PluralRule {
return ps.pluralsRange
}
// CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'ps_AF'
func (ps *ps_AF) CardinalPluralRule(num float64, v uint64) locales.PluralRule {
n := math.Abs(num)
if n == 1 {
return locales.PluralRuleOne
}
return locales.PluralRuleOther
}
// OrdinalPluralRule returns the ordinal PluralRule given 'num' and digits/precision of 'v' for 'ps_AF'
func (ps *ps_AF) OrdinalPluralRule(num float64, v uint64) locales.PluralRule {
return locales.PluralRuleUnknown
}
// RangePluralRule returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for 'ps_AF'
func (ps *ps_AF) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule {
return locales.PluralRuleUnknown
}
// MonthAbbreviated returns the locales abbreviated month given the 'month' provided
func (ps *ps_AF) MonthAbbreviated(month time.Month) string {
return ps.monthsAbbreviated[month]
}
// MonthsAbbreviated returns the locales abbreviated months
func (ps *ps_AF) MonthsAbbreviated() []string {
return ps.monthsAbbreviated[1:]
}
// MonthNarrow returns the locales narrow month given the 'month' provided
func (ps *ps_AF) MonthNarrow(month time.Month) string {
return ps.monthsNarrow[month]
}
// MonthsNarrow returns the locales narrow months
func (ps *ps_AF) MonthsNarrow() []string {
return ps.monthsNarrow[1:]
}
// MonthWide returns the locales wide month given the 'month' provided
func (ps *ps_AF) MonthWide(month time.Month) string {
return ps.monthsWide[month]
}
// MonthsWide returns the locales wide months
func (ps *ps_AF) MonthsWide() []string {
return ps.monthsWide[1:]
}
// WeekdayAbbreviated returns the locales abbreviated weekday given the 'weekday' provided
func (ps *ps_AF) WeekdayAbbreviated(weekday time.Weekday) string {
return ps.daysAbbreviated[weekday]
}
// WeekdaysAbbreviated returns the locales abbreviated weekdays
func (ps *ps_AF) WeekdaysAbbreviated() []string {
return ps.daysAbbreviated
}
// WeekdayNarrow returns the locales narrow weekday given the 'weekday' provided
func (ps *ps_AF) WeekdayNarrow(weekday time.Weekday) string {
return ps.daysNarrow[weekday]
}
// WeekdaysNarrow returns the locales narrow weekdays
func (ps *ps_AF) WeekdaysNarrow() []string {
return ps.daysNarrow
}
// WeekdayShort returns the locales short weekday given the 'weekday' provided
func (ps *ps_AF) WeekdayShort(weekday time.Weekday) string {
return ps.daysShort[weekday]
}
// WeekdaysShort returns the locales short weekdays
func (ps *ps_AF) WeekdaysShort() []string {
return ps.daysShort
}
// WeekdayWide returns the locales wide weekday given the 'weekday' provided
func (ps *ps_AF) WeekdayWide(weekday time.Weekday) string {
return ps.daysWide[weekday]
}
// WeekdaysWide returns the locales wide weekdays
func (ps *ps_AF) WeekdaysWide() []string {
return ps.daysWide
}
// FmtNumber returns 'num' with digits/precision of 'v' for 'ps_AF' and handles both Whole and Real numbers based on 'v'
func (ps *ps_AF) FmtNumber(num float64, v uint64) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
l := len(s) + 9 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
for j := len(ps.decimal) - 1; j >= 0; j-- {
b = append(b, ps.decimal[j])
}
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(ps.group) - 1; j >= 0; j-- {
b = append(b, ps.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
for j := len(ps.minus) - 1; j >= 0; j-- {
b = append(b, ps.minus[j])
}
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
// FmtPercent returns 'num' with digits/precision of 'v' for 'ps_AF' and handles both Whole and Real numbers based on 'v'
// NOTE: 'num' passed into FmtPercent is assumed to be in percent already
func (ps *ps_AF) FmtPercent(num float64, v uint64) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
l := len(s) + 11
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
for j := len(ps.decimal) - 1; j >= 0; j-- {
b = append(b, ps.decimal[j])
}
continue
}
b = append(b, s[i])
}
if num < 0 {
for j := len(ps.minus) - 1; j >= 0; j-- {
b = append(b, ps.minus[j])
}
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
b = append(b, ps.percent...)
return string(b)
}
// FmtCurrency returns the currency representation of 'num' with digits/precision of 'v' for 'ps_AF'
func (ps *ps_AF) FmtCurrency(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := ps.currencies[currency]
l := len(s) + len(symbol) + 11 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
for j := len(ps.decimal) - 1; j >= 0; j-- {
b = append(b, ps.decimal[j])
}
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(ps.group) - 1; j >= 0; j-- {
b = append(b, ps.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
for j := len(ps.minus) - 1; j >= 0; j-- {
b = append(b, ps.minus[j])
}
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, ps.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
b = append(b, ps.currencyPositiveSuffix...)
b = append(b, symbol...)
return string(b)
}
// FmtAccounting returns the currency representation of 'num' with digits/precision of 'v' for 'ps_AF'
// in accounting notation.
func (ps *ps_AF) FmtAccounting(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := ps.currencies[currency]
l := len(s) + len(symbol) + 11 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
for j := len(ps.decimal) - 1; j >= 0; j-- {
b = append(b, ps.decimal[j])
}
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(ps.group) - 1; j >= 0; j-- {
b = append(b, ps.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
for j := len(ps.minus) - 1; j >= 0; j-- {
b = append(b, ps.minus[j])
}
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, ps.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
if num < 0 {
b = append(b, ps.currencyNegativeSuffix...)
b = append(b, symbol...)
} else {
b = append(b, ps.currencyPositiveSuffix...)
b = append(b, symbol...)
}
return string(b)
}
// FmtDateShort returns the short date representation of 't' for 'ps_AF'
func (ps *ps_AF) FmtDateShort(t time.Time) string {
b := make([]byte, 0, 32)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(t.Year()*-1), 10)
}
b = append(b, []byte{0x2f}...)
b = strconv.AppendInt(b, int64(t.Month()), 10)
b = append(b, []byte{0x2f}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
return string(b)
}
// FmtDateMedium returns the medium date representation of 't' for 'ps_AF'
func (ps *ps_AF) FmtDateMedium(t time.Time) string {
b := make([]byte, 0, 32)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(t.Year()*-1), 10)
}
b = append(b, []byte{0x20}...)
b = append(b, ps.monthsAbbreviated[t.Month()]...)
b = append(b, []byte{0x20}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
return string(b)
}
// FmtDateLong returns the long date representation of 't' for 'ps_AF'
func (ps *ps_AF) FmtDateLong(t time.Time) string {
b := make([]byte, 0, 32)
b = append(b, []byte{0xd8, 0xaf, 0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(t.Year()*-1), 10)
}
b = append(b, []byte{0x20, 0xd8, 0xaf, 0x20}...)
b = append(b, ps.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
return string(b)
}
// FmtDateFull returns the full date representation of 't' for 'ps_AF'
func (ps *ps_AF) FmtDateFull(t time.Time) string {
b := make([]byte, 0, 32)
b = append(b, ps.daysWide[t.Weekday()]...)
b = append(b, []byte{0x20, 0xd8, 0xaf, 0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(t.Year()*-1), 10)
}
b = append(b, []byte{0x20, 0xd8, 0xaf, 0x20}...)
b = append(b, ps.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
return string(b)
}
// FmtTimeShort returns the short time representation of 't' for 'ps_AF'
func (ps *ps_AF) FmtTimeShort(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, ps.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
return string(b)
}
// FmtTimeMedium returns the medium time representation of 't' for 'ps_AF'
func (ps *ps_AF) FmtTimeMedium(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, ps.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, ps.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
return string(b)
}
// FmtTimeLong returns the long time representation of 't' for 'ps_AF'
func (ps *ps_AF) FmtTimeLong(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, ps.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, ps.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20, 0x28}...)
tz, _ := t.Zone()
b = append(b, tz...)
b = append(b, []byte{0x29}...)
return string(b)
}
// FmtTimeFull returns the full time representation of 't' for 'ps_AF'
func (ps *ps_AF) FmtTimeFull(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, ps.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, ps.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20, 0x28}...)
tz, _ := t.Zone()
if btz, ok := ps.timezones[tz]; ok {
b = append(b, btz...)
} else {
b = append(b, tz...)
}
b = append(b, []byte{0x29}...)
return string(b)
}
| nicholasjackson/building-microservices-in-go | vendor/github.com/go-playground/locales/ps_AF/ps_AF.go | GO | mit | 18,531 |
require 'date'
require 'sass/util'
module Sass
# Handles Sass version-reporting.
# Sass not only reports the standard three version numbers,
# but its Git revision hash as well,
# if it was installed from Git.
module Version
# Returns a hash representing the version of Sass.
# The `:major`, `:minor`, and `:teeny` keys have their respective numbers as Fixnums.
# The `:name` key has the name of the version.
# The `:string` key contains a human-readable string representation of the version.
# The `:number` key is the major, minor, and teeny keys separated by periods.
# The `:date` key, which is not guaranteed to be defined, is the `DateTime`
# at which this release was cut.
# If Sass is checked out from Git, the `:rev` key will have the revision hash.
# For example:
#
# {
# :string => "2.1.0.9616393",
# :rev => "9616393b8924ef36639c7e82aa88a51a24d16949",
# :number => "2.1.0",
# :date => DateTime.parse("Apr 30 13:52:01 2009 -0700"),
# :major => 2, :minor => 1, :teeny => 0
# }
#
# If a prerelease version of Sass is being used,
# the `:string` and `:number` fields will reflect the full version
# (e.g. `"2.2.beta.1"`), and the `:teeny` field will be `-1`.
# A `:prerelease` key will contain the name of the prerelease (e.g. `"beta"`),
# and a `:prerelease_number` key will contain the rerelease number.
# For example:
#
# {
# :string => "3.0.beta.1",
# :number => "3.0.beta.1",
# :date => DateTime.parse("Mar 31 00:38:04 2010 -0700"),
# :major => 3, :minor => 0, :teeny => -1,
# :prerelease => "beta",
# :prerelease_number => 1
# }
#
# @return [{Symbol => String/Fixnum}] The version hash
# @comment
# rubocop:disable ClassVars
def version
return @@version if defined?(@@version)
numbers = File.read(Sass::Util.scope('VERSION')).strip.split('.').
map {|n| n =~ /^[0-9]+$/ ? n.to_i : n}
name = File.read(Sass::Util.scope('VERSION_NAME')).strip
@@version = {
:major => numbers[0],
:minor => numbers[1],
:teeny => numbers[2],
:name => name
}
if (date = version_date)
@@version[:date] = date
end
if numbers[3].is_a?(String)
@@version[:teeny] = -1
@@version[:prerelease] = numbers[3]
@@version[:prerelease_number] = numbers[4]
end
@@version[:number] = numbers.join('.')
@@version[:string] = @@version[:number].dup
if (rev = revision_number)
@@version[:rev] = rev
unless rev[0] == ?(
@@version[:string] << "." << rev[0...7]
end
end
@@version[:string] << " (#{name})"
@@version
end
# rubocop:enable ClassVars
private
def revision_number
if File.exists?(Sass::Util.scope('REVISION'))
rev = File.read(Sass::Util.scope('REVISION')).strip
return rev unless rev =~ /^([a-f0-9]+|\(.*\))$/ || rev == '(unknown)'
end
return unless File.exists?(Sass::Util.scope('.git/HEAD'))
rev = File.read(Sass::Util.scope('.git/HEAD')).strip
return rev unless rev =~ /^ref: (.*)$/
ref_name = $1
ref_file = Sass::Util.scope(".git/#{ref_name}")
info_file = Sass::Util.scope(".git/info/refs")
return File.read(ref_file).strip if File.exists?(ref_file)
return unless File.exists?(info_file)
File.open(info_file) do |f|
f.each do |l|
sha, ref = l.strip.split("\t", 2)
next unless ref == ref_name
return sha
end
end
nil
end
def version_date
return unless File.exists?(Sass::Util.scope('VERSION_DATE'))
DateTime.parse(File.read(Sass::Util.scope('VERSION_DATE')).strip)
end
end
extend Sass::Version
# A string representing the version of Sass.
# A more fine-grained representation is available from Sass.version.
# @api public
VERSION = version[:string] unless defined?(Sass::VERSION)
end
| codal/sass | lib/sass/version.rb | Ruby | mit | 4,121 |
/**
* Core JavaScript file for the s2Member plugin.
*
* This is the development version of the code.
* Which ultimately produces s2member-min.js.
*
* Copyright: © 2009-2011
* {@link http://www.websharks-inc.com/ WebSharks, Inc.}
* (coded in the USA)
*
* Released under the terms of the GNU General Public License.
* You should have received a copy of the GNU General Public License,
* along with this software. In the main directory, see: /licensing/
* If not, see: {@link http://www.gnu.org/licenses/}.
*
* @package s2Member
* @since 3.0
*/
jQuery(document)
.ready(function($)
{
window.ws_plugin__s2member_skip_all_file_confirmations = window.ws_plugin__s2member_skip_all_file_confirmations || false;
var runningBuddyPress = '<?php echo c_ws_plugin__s2member_utils_conds::bp_is_installed("query-active-plugins") ? "1" : ""; ?>',
filesBaseDir = '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(c_ws_plugin__s2member_utils_dirs::basename_dir_app_data($GLOBALS["WS_PLUGIN__"]["s2member"]["c"]["files_dir"])); ?>',
skipAllFileConfirmations = ws_plugin__s2member_skip_all_file_confirmations ? true : false,
uniqueFilesDownloadedInPage = [/* Real-time counts in a single page/instance. */];
if(!skipAllFileConfirmations && S2MEMBER_CURRENT_USER_IS_LOGGED_IN && S2MEMBER_CURRENT_USER_DOWNLOADS_CURRENTLY < S2MEMBER_CURRENT_USER_DOWNLOADS_ALLOWED)
{
$('a[href*="s2member_file_download="], a[href*="/s2member-files/"], a[href^="s2member-files/"], a[href*="/' + filesBaseDir.replace(/([\:\.\[\]])/g, '\\$1') + '/"], a[href^="' + filesBaseDir.replace(/([\:\.\[\]])/g, '\\$1') + '/"]')
.click(function()
{
if(!/s2member[_\-]file[_\-]download[_\-]key[\=\-].+/i.test(this.href)/* Do NOT prompt on downloads issued with a Key. */)
{
var c = '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Confirm File Download —", "s2member-front", "s2member")); ?>' + '\n\n';
c += $.sprintf('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("You`ve downloaded %s protected %s in the last %s.", "s2member-front", "s2member")); ?>', S2MEMBER_CURRENT_USER_DOWNLOADS_CURRENTLY, ((S2MEMBER_CURRENT_USER_DOWNLOADS_CURRENTLY === 1) ? '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("file", "s2member-front", "s2member")); ?>' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("files", "s2member-front", "s2member")); ?>'), ((S2MEMBER_CURRENT_USER_DOWNLOADS_ALLOWED_DAYS === 1) ? '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("24 hours", "s2member-front", "s2member")); ?>' : $.sprintf('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("%s days", "s2member-front", "s2member")); ?>', S2MEMBER_CURRENT_USER_DOWNLOADS_ALLOWED_DAYS))) + '\n\n';
c += (S2MEMBER_CURRENT_USER_DOWNLOADS_ALLOWED_IS_UNLIMITED) ? '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("You`re entitled to UNLIMITED downloads though (so, no worries).", "s2member-front", "s2member")); ?>' : $.sprintf('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("You`re entitled to %s unique %s %s.", "s2member-front", "s2member")); ?>', S2MEMBER_CURRENT_USER_DOWNLOADS_ALLOWED, ((S2MEMBER_CURRENT_USER_DOWNLOADS_ALLOWED === 1) ? '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("download", "s2member-front", "s2member")); ?>' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("downloads", "s2member-front", "s2member")); ?>'), ((S2MEMBER_CURRENT_USER_DOWNLOADS_ALLOWED_DAYS === 1) ? '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("each day", "s2member-front", "s2member")); ?>' : $.sprintf('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("every %s-day period", "s2member-front", "s2member")); ?>', S2MEMBER_CURRENT_USER_DOWNLOADS_ALLOWED_DAYS)));
if((/s2member[_\-]skip[_\-]confirmation/i.test(this.href) && !/s2member[_\-]skip[_\-]confirmation[\=\-](0|no|false)/i.test(this.href)) || confirm(c))
{
if($.inArray(this.href, uniqueFilesDownloadedInPage) === -1)
S2MEMBER_CURRENT_USER_DOWNLOADS_CURRENTLY++, uniqueFilesDownloadedInPage.push(this.href);
return true;
}
return false;
}
return true;
});
}
if(!/\/wp-admin([\/?#]|$)/i.test(location.href))
{
$('input#ws-plugin--s2member-profile-password1, input#ws-plugin--s2member-profile-password2')
.keyup(function()
{
ws_plugin__s2member_passwordStrength(
$('input#ws-plugin--s2member-profile-login'),
$('input#ws-plugin--s2member-profile-password1'),
$('input#ws-plugin--s2member-profile-password2'),
$('div#ws-plugin--s2member-profile-password-strength')
);
});
$('form#ws-plugin--s2member-profile')
.submit(function(/* Validate Profile. */)
{
var context = this, label = '', error = '', errors = '',
$password1 = $('input#ws-plugin--s2member-profile-password1', context),
$password2 = $('input#ws-plugin--s2member-profile-password2', context);
var $submissionButton = $('input#ws-plugin--s2member-profile-submit', context);
$(':input', context)
.each(function(/* Go through them all together. */)
{
var id = /* Remove numeric suffixes. */ $.trim($(this).attr('id')).replace(/---[0-9]+$/g, '');
if(id && (label = $.trim($('label[for="' + id + '"]', context).first().children('strong').first().text().replace(/[\r\n\t]+/g, ' '))))
{
if(error = ws_plugin__s2member_validationErrors(label, this, context))
errors += /* Collect errors. */ error + '\n\n';
}
});
if(errors = $.trim(errors))
{
alert('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Oops, you missed something: —", "s2member-front", "s2member")); ?>' + '\n\n' + errors);
return false;
}
else if($.trim($password1.val()) && $.trim($password1.val()) !== $.trim($password2.val()))
{
alert('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Oops, you missed something: —", "s2member-front", "s2member")); ?>' + '\n\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Passwords do not match up. Please try again.", "s2member-front", "s2member")); ?>');
return false;
}
else if($.trim($password1.val()) && /* Enforce minimum length requirement here. */ $.trim($password1.val()).length < 6)
{
alert('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Oops, you missed something: —", "s2member-front", "s2member")); ?>' + '\n\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Password MUST be at least 6 characters. Please try again.", "s2member-front", "s2member")); ?>');
return false;
}
ws_plugin__s2member_animateProcessing($submissionButton);
return true;
});
}
if(/\/wp-signup\.php/i.test(location.href))
{
$('div#content > div.mu_register > form#setupform')
.submit(function()
{
var context = this, label = '', error = '', errors = '',
$submissionButton = $('p.submit input[type="submit"]', context);
$('input#user_email', context).attr('data-expected', 'email');
$('input#user_name, input#user_email, input#blogname, input#blog_title, input#captcha_code', context).attr({'aria-required': 'true'});
$(':input', context)
.each(function(/* Go through them all together. */)
{
var id = $.trim($(this).attr('id')).replace(/---[0-9]+$/g, ''/* Remove numeric suffixes. */);
if(id && (label = $.trim($('label[for="' + id + '"]', context).first().text().replace(/[\r\n\t]+/g, ' '))))
{
if(error = ws_plugin__s2member_validationErrors(label, this, context))
errors += error + '\n\n'/* Collect errors. */;
}
});
if(errors = $.trim(errors))
{
alert('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Oops, you missed something: —", "s2member-front", "s2member")); ?>' + '\n\n' + errors);
return false;
}
ws_plugin__s2member_animateProcessing($submissionButton);
return true;
});
}
if(/\/wp-login\.php/i.test(location.href))
{
$('div#login > form#registerform input#user_login').attr('tabindex', '10');
$('div#login > form#registerform input#user_email').attr('tabindex', '20');
$('div#login > form#registerform input#wp-submit').attr('tabindex', '1000');
$('input#ws-plugin--s2member-custom-reg-field-user-pass1, input#ws-plugin--s2member-custom-reg-field-user-pass2')
.keyup(function()
{
ws_plugin__s2member_passwordStrength(
$('input#user_login'),
$('input#ws-plugin--s2member-custom-reg-field-user-pass1'),
$('input#ws-plugin--s2member-custom-reg-field-user-pass2'),
$('div#ws-plugin--s2member-custom-reg-field-user-pass-strength')
);
});
$('div#login > form#registerform')
.submit(function()
{
var context = this, label = '', error = '', errors = '',
$pass1 = $('input#ws-plugin--s2member-custom-reg-field-user-pass1[aria-required="true"]', context),
$pass2 = $('input#ws-plugin--s2member-custom-reg-field-user-pass2', context),
$submissionButton = $('input#wp-submit', context/* Registration submission button. */);
$('input#user_email', context).attr('data-expected', 'email');
$('input#user_login, input#user_email, input#captcha_code', context).attr({'aria-required': 'true'});
$(':input', context)
.each(function(/* Go through them all together. */)
{
var id = $.trim($(this).attr('id')).replace(/---[0-9]+$/g, ''/* Remove numeric suffixes. */);
if($.inArray(id, ['user_login', 'user_email', 'captcha_code']) !== -1/* No for="" attribute on these fields. */)
{
if((label = $.trim($(this).parent('label').text().replace(/[\r\n\t]+/g, ' '))))
{
if(error = ws_plugin__s2member_validationErrors(label, this, context))
errors += error + '\n\n'/* Collect errors. */;
}
}
else if(id && (label = $.trim($('label[for="' + id + '"]', context).first().children('span').first().text().replace(/[\r\n\t]+/g, ' '))))
{
if(error = ws_plugin__s2member_validationErrors(label, this, context))
errors += error + '\n\n'/* Collect errors. */;
}
});
if(errors = $.trim(errors))
{
alert('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Oops, you missed something: —", "s2member-front", "s2member")); ?>' + '\n\n' + errors);
return false;
}
else if($pass1.length && $.trim($pass1.val()) !== $.trim($pass2.val()))
{
alert('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Oops, you missed something: —", "s2member-front", "s2member")); ?>' + '\n\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Passwords do not match up. Please try again.", "s2member-front", "s2member")); ?>');
return false;
}
else if($pass1.length && $.trim($pass1.val()).length < 6/* Enforce minimum length requirement here. */)
{
alert('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Oops, you missed something: —", "s2member-front", "s2member")); ?>' + '\n\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Password MUST be at least 6 characters. Please try again.", "s2member-front", "s2member")); ?>');
return false;
}
ws_plugin__s2member_animateProcessing($submissionButton);
return true;
});
}
if(/\/wp-admin\/(?:user\/)?profile\.php/i.test(location.href))
{
$('form#your-profile')
.submit(function(/* Validation. */)
{
var context = this, label = '', error = '', errors = '';
$('input#email', context).attr('data-expected', 'email');
$(':input[id^="ws-plugin--s2member-profile-"]', context)
.each(function(/* Go through them all together. */)
{
var id = /* Remove numeric suffixes. */ $.trim($(this).attr('id')).replace(/---[0-9]+$/g, '');
if(id && (label = $.trim($('label[for="' + id + '"]', context).first().text().replace(/[\r\n\t]+/g, ' '))))
{
if(error = ws_plugin__s2member_validationErrors(label, this, context))
errors += error + '\n\n'/* Collect errors. */;
}
});
if(errors = $.trim(errors))
{
alert('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Oops, you missed something: —", "s2member-front", "s2member")); ?>' + '\n\n' + errors);
return false;
}
return true;
});
}
if(runningBuddyPress/* Attach form submission handler to `/register` for BuddyPress. */)
{
$('body.registration form div#ws-plugin--s2member-custom-reg-fields-4bp-section').closest('form')
.submit(function()
{
var context = this, label = '', error = '', errors = '';
$('input#signup_email', context).attr('data-expected', 'email');
$('input#signup_username, input#signup_email, input#signup_password, input#field_1', context).attr({'aria-required': 'true'});
$(':input', context)
.each(function(/* Go through them all together. */)
{
var id = $.trim($(this).attr('id')).replace(/---[0-9]+$/g, ''/* Remove numeric suffixes. */);
if(id && (label = $.trim($('label[for="' + id + '"]', context).first().text().replace(/[\r\n\t]+/g, ' '))))
{
if(error = ws_plugin__s2member_validationErrors(label, this, context))
errors += error + '\n\n'/* Collect errors. */;
}
});
if(errors = $.trim(errors))
{
alert('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Oops, you missed something: —", "s2member-front", "s2member")); ?>' + '\n\n' + errors);
return false;
}
return true;
});
$('body.logged-in.profile.profile-edit :input.ws-plugin--s2member-profile-field-4bp').closest('form')
.submit(function()
{
var context = this, label = '', error = '', errors = '';
$('input#field_1', context).attr({'aria-required': 'true'});
$(':input', context)
.each(function(/* Go through them all together. */)
{
var id = $.trim($(this).attr('id')).replace(/---[0-9]+$/g, ''/* Remove numeric suffixes. */);
if(id && (label = $.trim($('label[for="' + id + '"]', context).first().text().replace(/[\r\n\t]+/g, ' '))))
{
if(error = ws_plugin__s2member_validationErrors(label, this, context))
errors += error + '\n\n'/* Collect errors. */;
}
});
if(errors = $.trim(errors))
{
alert('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("— Oops, you missed something: —", "s2member-front", "s2member")); ?>' + '\n\n' + errors);
return false;
}
return true;
});
}
window.ws_plugin__s2member_passwordStrengthMeter = function(password1, password2)
{
var score = 0; // Initialize score.
if((password1 != password2) && password2.length > 0)
return 'mismatch';
else if(password1.length < 1)
return 'empty';
else if(password1.length < 6)
return 'short';
if(password1.match(/[0-9]/))
score += 10;
if(password1.match(/[a-z]/))
score += 10;
if(password1.match(/[A-Z]/))
score += 10;
if(password1.match(/[^0-9a-zA-Z]/))
score = (score === 30) ? score + 20 : score + 10;
if(score < 30) return 'bad';
if(score < 50) return 'good';
return 'strong'; // Default return value.
};
window.ws_plugin__s2member_passwordStrength = function($username, $pass1, $pass2, $result)
{
if($username instanceof jQuery && $pass1 instanceof jQuery && $pass2 instanceof jQuery && $result instanceof jQuery)
{
var pwsL10n = { // Password strength meter translations.
'empty' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Strength indicator", "s2member-front", "s2member")); ?>',
'short' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Very weak", "s2member-front", "s2member")); ?>',
'bad' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Weak", "s2member-front", "s2member")); ?>',
'good' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Medium", "s2member-front", "s2member")); ?>',
'strong' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Strong", "s2member-front", "s2member")); ?>',
'mismatch': '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Mismatch", "s2member-front", "s2member")); ?>'
};
$result.removeClass('ws-plugin--s2member-password-strength-short');
$result.removeClass('ws-plugin--s2member-password-strength-bad');
$result.removeClass('ws-plugin--s2member-password-strength-good');
$result.removeClass('ws-plugin--s2member-password-strength-strong');
$result.removeClass('ws-plugin--s2member-password-strength-mismatch');
$result.removeClass('ws-plugin--s2member-password-strength-empty');
var meterSays = ws_plugin__s2member_passwordStrengthMeter($pass1.val(), $pass2.val());
$result.addClass('ws-plugin--s2member-password-strength-' + meterSays).html(pwsL10n[meterSays]);
}
};
window.ws_plugin__s2member_validationErrors = function(label, field, context, required, expected)
{
if(typeof label === 'string' && label && typeof field === 'object' && typeof context === 'object')
if(typeof field.tagName === 'string' && /^(input|textarea|select)$/i.test(field.tagName) && !field.disabled)
{
var tag = field.tagName.toLowerCase(), $field = $(field), type = $.trim($field.attr('type')).toLowerCase(), name = $.trim($field.attr('name')), value = $field.val();
required = ( typeof required === 'boolean') ? required : ($field.attr('aria-required') === 'true'), expected = ( typeof expected === 'string') ? expected : $.trim($field.attr('data-expected'));
var forcePersonalEmails = ('<?php echo strlen($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["custom_reg_force_personal_emails"]); ?>' > 0);
var nonPersonalEmailUsers = new RegExp('^(<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq (implode ("|", preg_split ("/[\r\n\t ;,]+/", preg_quote ($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["custom_reg_force_personal_emails"], "/")))); ?>)@', 'i');
if(tag === 'input' && type === 'checkbox' && /\[\]$/.test(name))
{
if(typeof field.id === 'string' && /-0$/.test(field.id))
if(required && !$('input[name="' + ws_plugin__s2member_escjQAttr(name) + '"]:checked', context).length)
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Please check at least one of the boxes.", "s2member-front", "s2member")); ?>';
}
else if(tag === 'input' && type === 'checkbox')
{
if(required && !field.checked)
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Required. This box must be checked.", "s2member-front", "s2member")); ?>';
}
else if(tag === 'input' && type === 'radio')
{
if(typeof field.id === 'string' && /-0$/.test(field.id))
if(required && !$('input[name="' + ws_plugin__s2member_escjQAttr(name) + '"]:checked', context).length)
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Please select one of the options.", "s2member-front", "s2member")); ?>';
}
else if(tag === 'select' && $field.attr('multiple'))
{
if(required && (!(value instanceof Array) || !value.length))
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Please select at least one of the options.", "s2member-front", "s2member")); ?>';
}
else if(typeof value !== 'string' || (required && !(value = $.trim(value)).length))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("This is a required field, please try again.", "s2member-front", "s2member")); ?>';
}
else if((value = $.trim(value)).length && ((tag === 'input' && /^(text|password)$/i.test(type)) || tag === 'textarea') && typeof expected === 'string' && expected.length)
{
if(expected === 'numeric-wp-commas' && (!/^[0-9\.,]+$/.test(value) || isNaN(value.replace(/,/g, ''))))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be numeric (with or without decimals, commas allowed).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'numeric' && (!/^[0-9\.]+$/.test(value) || isNaN(value)))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be numeric (with or without decimals, no commas).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'integer' && (!/^[0-9]+$/.test(value) || isNaN(value)))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be an integer (a whole number, without any decimals).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'integer-gt-0' && (!/^[0-9]+$/.test(value) || isNaN(value) || value <= 0))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be an integer > 0 (whole number, no decimals, greater than 0).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'float' && (!/^[0-9\.]+$/.test(value) || !/[0-9]/.test(value) || !/\./.test(value) || isNaN(value)))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be a float (floating point number, decimals required).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'float-gt-0' && (!/^[0-9\.]+$/.test(value) || !/[0-9]/.test(value) || !/\./.test(value) || isNaN(value) || value <= 0))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be a float > 0 (floating point number, decimals required, greater than 0).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'date' && !/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be a date (required date format: dd/mm/yyyy).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'email' && !/^[a-zA-Z0-9_!#$%&*+=?`{}~|\/\^\'\-]+(?:\.?[a-zA-Z0-9_!#$%&*+=?`{}~|\/\^\'\-]+)*@[a-zA-Z0-9]+(?:\-*[a-zA-Z0-9]+)*(?:\.[a-zA-Z0-9]+(?:\-*[a-zA-Z0-9]+)*)*(?:\.[a-zA-Z][a-zA-Z0-9]+)?$/.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be a valid email address.", "s2member-front", "s2member")); ?>';
}
else if(expected === 'email' && forcePersonalEmails && nonPersonalEmailUsers.test(value))
{
return label + '\n' + $.sprintf('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Please use a personal email address.\nAddresses like <%s@> are problematic.", "s2member-front", "s2member")); ?>', value.split('@')[0]);
}
else if(expected === 'url' && !/^https?\:\/\/.+$/i.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be a full URL (starting with http or https).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'domain' && !/^[a-zA-Z0-9]+(?:\-*[a-zA-Z0-9]+)*(?:\.[a-zA-Z0-9]+(?:\-*[a-zA-Z0-9]+)*)*(?:\.[a-zA-Z][a-zA-Z0-9]+)?$/.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be a domain name (domain name only, without http).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'phone' && (!/^[0-9 ()\-]+$/.test(value) || value.replace(/[^0-9]+/g, '').length !== 10))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be a phone # (10 digits w/possible hyphens, spaces, brackets).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'uszip' && !/^[0-9]{5}(?:\-[0-9]{4})?$/.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be a US zipcode (5-9 digits w/ possible hyphen).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'cazip' && !/^[0-9A-Z]{3} ?[0-9A-Z]{3}$/i.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be a Canadian zipcode (6 alpha-numerics w/possible space).", "s2member-front", "s2member")); ?>';
}
else if(expected === 'uczip' && !/^[0-9]{5}(?:\-[0-9]{4})?$/.test(value) && !/^[0-9A-Z]{3} ?[0-9A-Z]{3}$/i.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be a zipcode (either a US or Canadian zipcode).", "s2member-front", "s2member")); ?>';
}
else if(/^alphanumerics\-spaces\-punctuation\-[0-9]+(?:\-e)?$/.test(expected) && !/^[a-z 0-9\/\\\\,.?:;"\'{}[\]\^|+=_()*&%$#@!`~\-]+$/i.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Please use alphanumerics, spaces & punctuation only.", "s2member-front", "s2member")); ?>';
}
else if(/^alphanumerics\-spaces\-[0-9]+(?:\-e)?$/.test(expected) && !/^[a-z 0-9]+$/i.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Please use alphanumerics & spaces only.", "s2member-front", "s2member")); ?>';
}
else if(/^alphanumerics\-punctuation\-[0-9]+(?:\-e)?$/.test(expected) && !/^[a-z0-9\/\\\\,.?:;"\'{}[\]\^|+=_()*&%$#@!`~\-]+$/i.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Please use alphanumerics & punctuation only (no spaces).", "s2member-front", "s2member")); ?>';
}
else if(/^alphanumerics\-[0-9]+(?:\-e)?$/.test(expected) && !/^[a-z0-9]+$/i.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Please use alphanumerics only (no spaces/punctuation).", "s2member-front", "s2member")); ?>';
}
else if(/^alphabetics\-[0-9]+(?:\-e)?$/.test(expected) && !/^[a-z]+$/i.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Please use alphabetics only (no digits/spaces/punctuation).", "s2member-front", "s2member")); ?>';
}
else if(/^numerics\-[0-9]+(?:\-e)?$/.test(expected) && !/^[0-9]+$/i.test(value))
{
return label + '\n' + '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Please use numeric digits only.", "s2member-front", "s2member")); ?>';
}
else if(/^(?:any|alphanumerics\-spaces\-punctuation|alphanumerics\-spaces|alphanumerics\-punctuation|alphanumerics|alphabetics|numerics)\-[0-9]+(?:\-e)?$/.test(expected))
{
var split = expected.split('-'), length = Number(split[1]), exactLength = (split.length > 2 && split[2] === 'e');
if(exactLength && value.length !== length/* An exact length is required? */)
return label + '\n' + $.sprintf('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be exactly %s %s.", "s2member-front", "s2member")); ?>', length, ((split[0] === 'numerics') ? ((length === 1) ? '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("digit", "s2member-front", "s2member")); ?>' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("digits", "s2member-front", "s2member")); ?>') : ((length === 1) ? '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("character", "s2member-front", "s2member")); ?>' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("characters", "s2member-front", "s2member")); ?>')));
else if(value.length < length/* Otherwise, we interpret as the minimum length. */)
return label + '\n' + $.sprintf('<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("Must be at least %s %s.", "s2member-front", "s2member")); ?>', length, ((split[0] === 'numerics') ? ((length === 1) ? '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("digit", "s2member-front", "s2member")); ?>' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("digits", "s2member-front", "s2member")); ?>') : ((length === 1) ? '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("character", "s2member-front", "s2member")); ?>' : '<?php echo c_ws_plugin__s2member_utils_strings::esc_js_sq(_x("characters", "s2member-front", "s2member")); ?>')));
}
}
}
return ''; // No errors in this case.
};
window.ws_plugin__s2member_animateProcessing = function($obj, reset)
{
if(reset)
$($obj).removeClass('ws-plugin--s2member-animate-processing');
else $($obj).addClass('ws-plugin--s2member-animate-processing');
};
window.ws_plugin__s2member_escAttr = window.ws_plugin__s2member_escHtml = function(string)
{
if(/[&\<\>"']/.test(string = String(string)))
string = string.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'),
string = string.replace(/"/g, '"').replace(/'/g, ''');
return string;
};
window.ws_plugin__s2member_escjQAttr = function(string)
{
return String(string).replace(/([.:\[\]])/g, '\\$1');
};
}); | creative2020/downtownop | wp-content/plugins/s2member/includes/s2member.js | JavaScript | mit | 34,298 |
using System;
using System.Net;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using NSubstitute;
using Octokit.Internal;
using Xunit;
namespace Octokit.Tests.Http
{
public class ApiConnectionTests
{
public class TheGetMethod
{
[Fact]
public async Task MakesGetRequestForItem()
{
var getUri = new Uri("anything", UriKind.Relative);
IApiResponse<object> response = new ApiResponse<object>(new Response());
var connection = Substitute.For<IConnection>();
connection.Get<object>(Args.Uri, null, null).Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var data = await apiConnection.Get<object>(getUri);
Assert.Same(response.Body, data);
connection.Received().GetResponse<object>(getUri);
}
[Fact]
public async Task MakesGetRequestForItemWithAcceptsOverride()
{
var getUri = new Uri("anything", UriKind.Relative);
const string accepts = "custom/accepts";
IApiResponse<object> response = new ApiResponse<object>(new Response());
var connection = Substitute.For<IConnection>();
connection.Get<object>(Args.Uri, null, Args.String).Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var data = await apiConnection.Get<object>(getUri, null, accepts);
Assert.Same(response.Body, data);
connection.Received().Get<object>(getUri, null, accepts);
}
[Fact]
public async Task EnsuresArgumentNotNull()
{
var getUri = new Uri("anything", UriKind.Relative);
var client = new ApiConnection(Substitute.For<IConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get<object>(null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get<object>(getUri, new Dictionary<string, string>(), null));
}
}
public class TheGetHtmlMethod
{
[Fact]
public async Task MakesHtmlRequest()
{
var getUri = new Uri("anything", UriKind.Relative);
IApiResponse<string> response = new ApiResponse<string>(new Response(), "<html />");
var connection = Substitute.For<IConnection>();
connection.GetHtml(Args.Uri, null).Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var data = await apiConnection.GetHtml(getUri);
Assert.Equal("<html />", data);
connection.Received().GetHtml(getUri);
}
[Fact]
public async Task EnsuresArgumentNotNull()
{
var client = new ApiConnection(Substitute.For<IConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetHtml(null));
}
}
public class TheGetAllMethod
{
[Fact]
public async Task MakesGetRequestForAllItems()
{
var getAllUri = new Uri("anything", UriKind.Relative);
IApiResponse<List<object>> response = new ApiResponse<List<object>>(
new Response(),
new List<object> { new object(), new object() });
var connection = Substitute.For<IConnection>();
connection.Get<List<object>>(Args.Uri, null, null).Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var data = await apiConnection.GetAll<object>(getAllUri);
Assert.Equal(2, data.Count);
connection.Received().Get<List<object>>(getAllUri, null, null);
}
[Fact]
public async Task EnsuresArgumentNotNull()
{
var client = new ApiConnection(Substitute.For<IConnection>());
// One argument
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll<object>(null));
// Two argument
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
await client.GetAll<object>(null, new Dictionary<string, string>()));
// Three arguments
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
await client.GetAll<object>(null, new Dictionary<string, string>(), "accepts"));
}
}
public class ThePatchMethod
{
[Fact]
public async Task MakesPatchRequestWithSuppliedData()
{
var patchUri = new Uri("anything", UriKind.Relative);
var sentData = new object();
IApiResponse<object> response = new ApiResponse<object>(new Response(), new object());
var connection = Substitute.For<IConnection>();
connection.Patch<object>(Args.Uri, Args.Object).Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var data = await apiConnection.Patch<object>(patchUri, sentData);
Assert.Same(data, response.Body);
connection.Received().Patch<object>(patchUri, sentData);
}
[Fact]
public async Task MakesPatchRequestWithAcceptsOverride()
{
var patchUri = new Uri("anything", UriKind.Relative);
var sentData = new object();
var accepts = "custom/accepts";
IApiResponse<object> response = new ApiResponse<object>(new Response());
var connection = Substitute.For<IConnection>();
connection.Patch<object>(Args.Uri, Args.Object, Args.String).Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var data = await apiConnection.Patch<object>(patchUri, sentData, accepts);
Assert.Same(data, response.Body);
connection.Received().Patch<object>(patchUri, sentData, accepts);
}
[Fact]
public async Task EnsuresArgumentNotNull()
{
var connection = new ApiConnection(Substitute.For<IConnection>());
var patchUri = new Uri("", UriKind.Relative);
await Assert.ThrowsAsync<ArgumentNullException>(() => connection.Patch<object>(null, new object()));
await Assert.ThrowsAsync<ArgumentNullException>(() => connection.Patch<object>(patchUri, null));
await Assert.ThrowsAsync<ArgumentNullException>(() => connection.Patch<object>(patchUri, new object(), null));
}
}
public class ThePostMethod
{
[Fact]
public async Task MakesPostRequestWithoutData()
{
var postUri = new Uri("anything", UriKind.Relative);
var statusCode = HttpStatusCode.Accepted;
var connection = Substitute.For<IConnection>();
connection.Post(Args.Uri).Returns(Task.FromResult(statusCode));
var apiConnection = new ApiConnection(connection);
await apiConnection.Post(postUri);
connection.Received().Post(postUri);
}
[Fact]
public async Task MakesPostRequestWithSuppliedData()
{
var postUri = new Uri("anything", UriKind.Relative);
var sentData = new object();
IApiResponse<object> response = new ApiResponse<object>(new Response(), new object());
var connection = Substitute.For<IConnection>();
connection.Post<object>(Args.Uri, Args.Object, null, null).Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var data = await apiConnection.Post<object>(postUri, sentData);
Assert.Same(data, response.Body);
connection.Received().Post<object>(postUri, sentData, null, null);
}
[Fact]
public async Task MakesUploadRequest()
{
var uploadUrl = new Uri("anything", UriKind.Relative);
IApiResponse<string> response = new ApiResponse<string>(new Response(), "the response");
var connection = Substitute.For<IConnection>();
connection.Post<string>(Args.Uri, Arg.Any<Stream>(), Args.String, Args.String)
.Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var rawData = new MemoryStream();
await apiConnection.Post<string>(uploadUrl, rawData, "accepts", "content-type");
connection.Received().Post<string>(uploadUrl, rawData, "accepts", "content-type");
}
[Fact]
public async Task EnsuresArgumentsNotNull()
{
var postUri = new Uri("", UriKind.Relative);
var connection = new ApiConnection(Substitute.For<IConnection>());
// 1 parameter overload
await Assert.ThrowsAsync<ArgumentNullException>(() => connection.Post(null));
// 2 parameter overload
await Assert.ThrowsAsync<ArgumentNullException>(() => connection.Post<object>(null, new object()));
await Assert.ThrowsAsync<ArgumentNullException>(() => connection.Post<object>(postUri, null));
// 3 parameters
await Assert.ThrowsAsync<ArgumentNullException>(() => connection.Post<object>(null, new MemoryStream(), "anAccept", "some-content-type"));
await Assert.ThrowsAsync<ArgumentNullException>(() => connection.Post<object>(postUri, null, "anAccept", "some-content-type"));
}
}
public class ThePutMethod
{
[Fact]
public async Task MakesPutRequestWithSuppliedData()
{
var putUri = new Uri("anything", UriKind.Relative);
var sentData = new object();
IApiResponse<object> response = new ApiResponse<object>(new Response());
var connection = Substitute.For<IConnection>();
connection.Put<object>(Args.Uri, Args.Object).Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var data = await apiConnection.Put<object>(putUri, sentData);
Assert.Same(data, response.Body);
connection.Received().Put<object>(putUri, sentData);
}
[Fact]
public async Task MakesPutRequestWithSuppliedDataAndTwoFactorCode()
{
var putUri = new Uri("anything", UriKind.Relative);
var sentData = new object();
IApiResponse<object> response = new ApiResponse<object>(new Response());
var connection = Substitute.For<IConnection>();
connection.Put<object>(Args.Uri, Args.Object, "two-factor").Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var data = await apiConnection.Put<object>(putUri, sentData, "two-factor");
Assert.Same(data, response.Body);
connection.Received().Put<object>(putUri, sentData, "two-factor");
}
[Fact]
public async Task EnsuresArgumentsNotNull()
{
var putUri = new Uri("", UriKind.Relative);
var connection = new ApiConnection(Substitute.For<IConnection>());
// 2 parameter overload
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
await connection.Put<object>(null, new object()));
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
await connection.Put<object>(putUri, null));
// 3 parameters
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
await connection.Put<object>(null, new MemoryStream(), "two-factor"));
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
await connection.Put<object>(putUri, null, "two-factor"));
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
await connection.Put<object>(putUri, new MemoryStream(), null));
await Assert.ThrowsAsync<ArgumentException>(async () =>
await connection.Put<object>(putUri, new MemoryStream(), ""));
}
}
public class TheDeleteMethod
{
[Fact]
public async Task MakesDeleteRequest()
{
var deleteUri = new Uri("anything", UriKind.Relative);
HttpStatusCode statusCode = HttpStatusCode.NoContent;
var connection = Substitute.For<IConnection>();
connection.Delete(Args.Uri).Returns(Task.FromResult(statusCode));
var apiConnection = new ApiConnection(connection);
await apiConnection.Delete(deleteUri);
connection.Received().Delete(deleteUri);
}
[Fact]
public async Task EnsuresArgumentNotNull()
{
var connection = new ApiConnection(Substitute.For<IConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => connection.Delete(null));
}
}
public class TheGetQueuedOperationMethod
{
[Fact]
public async Task WhenGetReturnsNotOkOrAcceptedApiExceptionIsThrown()
{
var queuedOperationUrl = new Uri("anything", UriKind.Relative);
const HttpStatusCode statusCode = HttpStatusCode.PartialContent;
IApiResponse<object> response = new ApiResponse<object>(new Response(statusCode, null, new Dictionary<string, string>(), "application/json"), new object());
var connection = Substitute.For<IConnection>();
connection.GetResponse<object>(queuedOperationUrl, Args.CancellationToken).Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
await Assert.ThrowsAsync<ApiException>(() => apiConnection.GetQueuedOperation<object>(queuedOperationUrl, Args.CancellationToken));
}
[Fact]
public async Task WhenGetReturnsOkThenBodyAsObjectIsReturned()
{
var queuedOperationUrl = new Uri("anything", UriKind.Relative);
var result = new[] { new object() };
const HttpStatusCode statusCode = HttpStatusCode.OK;
var httpResponse = new Response(statusCode, null, new Dictionary<string, string>(), "application/json");
IApiResponse<IReadOnlyList<object>> response = new ApiResponse<IReadOnlyList<object>>(httpResponse, result);
var connection = Substitute.For<IConnection>();
connection.GetResponse<IReadOnlyList<object>>(queuedOperationUrl, Args.CancellationToken)
.Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var actualResult = await apiConnection.GetQueuedOperation<object>(queuedOperationUrl, Args.CancellationToken);
Assert.Same(actualResult, result);
}
[Fact]
public async Task WhenGetReturnsNoContentThenReturnsEmptyCollection()
{
var queuedOperationUrl = new Uri("anything", UriKind.Relative);
var result = new [] { new object() };
const HttpStatusCode statusCode = HttpStatusCode.NoContent;
var httpResponse = new Response(statusCode, null, new Dictionary<string, string>(), "application/json");
IApiResponse<IReadOnlyList<object>> response = new ApiResponse<IReadOnlyList<object>>(
httpResponse, result);
var connection = Substitute.For<IConnection>();
connection.GetResponse<IReadOnlyList<object>>(queuedOperationUrl, Args.CancellationToken)
.Returns(Task.FromResult(response));
var apiConnection = new ApiConnection(connection);
var actualResult = await apiConnection.GetQueuedOperation<object>(queuedOperationUrl, Args.CancellationToken);
Assert.Empty(actualResult);
}
[Fact]
public async Task GetIsRepeatedUntilHttpStatusCodeOkIsReturned()
{
var queuedOperationUrl = new Uri("anything", UriKind.Relative);
var result = new [] { new object() };
IApiResponse<IReadOnlyList<object>> firstResponse = new ApiResponse<IReadOnlyList<object>>(
new Response(HttpStatusCode.Accepted, null, new Dictionary<string, string>(), "application/json"), result);
IApiResponse<IReadOnlyList<object>> completedResponse = new ApiResponse<IReadOnlyList<object>>(
new Response(HttpStatusCode.OK, null, new Dictionary<string, string>(), "application/json"), result);
var connection = Substitute.For<IConnection>();
connection.GetResponse<IReadOnlyList<object>>(queuedOperationUrl, Args.CancellationToken)
.Returns(x => Task.FromResult(firstResponse),
x => Task.FromResult(firstResponse),
x => Task.FromResult(completedResponse));
var apiConnection = new ApiConnection(connection);
await apiConnection.GetQueuedOperation<object>(queuedOperationUrl, CancellationToken.None);
connection.Received(3).GetResponse<IReadOnlyList<object>>(queuedOperationUrl, Args.CancellationToken);
}
public async Task CanCancelQueuedOperation()
{
var queuedOperationUrl = new Uri("anything", UriKind.Relative);
var result = new [] { new object() };
IApiResponse<IReadOnlyList<object>> accepted = new ApiResponse<IReadOnlyList<object>>(
new Response(HttpStatusCode.Accepted, null, new Dictionary<string, string>(), "application/json"), result);
var connection = Substitute.For<IConnection>();
connection.GetResponse<IReadOnlyList<object>>(queuedOperationUrl, Args.CancellationToken)
.Returns(x => Task.FromResult(accepted));
var apiConnection = new ApiConnection(connection);
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(100);
var canceled = false;
var operationResult = await apiConnection.GetQueuedOperation<object>(queuedOperationUrl, cancellationTokenSource.Token)
.ContinueWith(task =>
{
canceled = task.IsCanceled;
return task;
}, TaskContinuationOptions.OnlyOnCanceled)
.ContinueWith(task => task, TaskContinuationOptions.OnlyOnFaulted);
Assert.True(canceled);
Assert.Null(operationResult);
}
[Fact]
public async Task EnsuresArgumentNotNull()
{
var connection = new ApiConnection(Substitute.For<IConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => connection.GetQueuedOperation<object>(null, CancellationToken.None));
}
}
public class TheCtor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new ApiConnection(null));
}
}
}
}
| cH40z-Lord/octokit.net | Octokit.Tests/Http/ApiConnectionTests.cs | C# | mit | 20,551 |
<?php
namespace Bolt\Composer\EventListener;
class PackageEventListener
{
/**
* Event handler for composer package events
*
* @param \Composer\EventDispatcher\Event $event
*/
public static function handle($event)
{
try {
$operation = $event->getOperation();
if (method_exists($operation, 'getPackage')) {
$installedPackage = $operation->getPackage();
} elseif (method_exists($operation, 'getTargetPackage')) {
$installedPackage = $operation->getTargetPackage();
} else {
return;
}
} catch (\Exception $e) {
return;
}
$rootExtra = $event->getComposer()->getPackage()->getExtra();
$extra = $installedPackage->getExtra();
if (isset($extra['bolt-assets'])) {
$type = $installedPackage->getType();
$pathToPublic = $rootExtra['bolt-web-path'];
// Get the path from extensions base through to public
$destParts = [getcwd(), $pathToPublic, 'extensions', 'vendor', $installedPackage->getName(), $extra['bolt-assets']];
$dest = realpath(join(DIRECTORY_SEPARATOR, $destParts));
if ($type === 'bolt-extension' && isset($extra['bolt-assets'])) {
$sourceParts = [getcwd(), 'vendor', $installedPackage->getName(),$extra['bolt-assets']];
$source = join(DIRECTORY_SEPARATOR, $sourceParts);
self::mirror($source, $dest);
}
}
}
/**
* Mirror a directory if the two directories don't match
*
* @param string $source
* @param string $dest
*/
public static function mirror($source, $dest)
{
@mkdir($dest, 0755, true);
if (realpath($source) === realpath($dest)) {
return;
}
/** @var $iterator \RecursiveIteratorIterator|\RecursiveDirectoryIterator */
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $item) {
/** @var $item \SplFileInfo */
if ($item->isDir()) {
$new = $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName();
if (!is_dir($new)) {
mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
} else {
copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
}
}
}
| tekjava/bolt | src/Composer/EventListener/PackageEventListener.php | PHP | mit | 2,646 |
<?php
namespace Gedmo\Timestampable\Traits;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Timestampable Trait, usable with PHP >= 5.4
*
* @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
trait TimestampableEntity
{
/**
* @var \DateTime
* @Gedmo\Timestampable(on="create")
* @ORM\Column(type="datetime")
*/
protected $createdAt;
/**
* @var \DateTime
* @Gedmo\Timestampable(on="update")
* @ORM\Column(type="datetime")
*/
protected $updatedAt;
/**
* Sets createdAt.
*
* @param \DateTime $createdAt
* @return $this
*/
public function setCreatedAt(\DateTime $createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Returns createdAt.
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Sets updatedAt.
*
* @param \DateTime $updatedAt
* @return $this
*/
public function setUpdatedAt(\DateTime $updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Returns updatedAt.
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
}
| 175009/movie_store | vendor/gedmo/doctrine-extensions/lib/Gedmo/Timestampable/Traits/TimestampableEntity.php | PHP | mit | 1,377 |
//>>built
define("dojox/charting/plot2d/Candlesticks",["dojo/_base/lang","dojo/_base/declare","dojo/_base/array","dojo/has","./CartesianBase","./_PlotEvents","./common","dojox/lang/functional","dojox/lang/functional/reversed","dojox/lang/utils","dojox/gfx/fx"],function(_1,_2,_3,_4,_5,_6,dc,df,_7,du,fx){
var _8=_7.lambda("item.purgeGroup()");
return _2("dojox.charting.plot2d.Candlesticks",[_5,_6],{defaultParams:{gap:2,animate:null},optionalParams:{minBarSize:1,maxBarSize:1,stroke:{},outline:{},shadow:{},fill:{},font:"",fontColor:""},constructor:function(_9,_a){
this.opt=_1.clone(this.defaultParams);
du.updateWithObject(this.opt,_a);
du.updateWithPattern(this.opt,_a,this.optionalParams);
this.animate=this.opt.animate;
},collectStats:function(_b){
var _c=_1.delegate(dc.defaultStats);
for(var i=0;i<_b.length;i++){
var _d=_b[i];
if(!_d.data.length){
continue;
}
var _e=_c.vmin,_f=_c.vmax;
if(!("ymin" in _d)||!("ymax" in _d)){
_3.forEach(_d.data,function(val,idx){
if(val!==null){
var x=val.x||idx+1;
_c.hmin=Math.min(_c.hmin,x);
_c.hmax=Math.max(_c.hmax,x);
_c.vmin=Math.min(_c.vmin,val.open,val.close,val.high,val.low);
_c.vmax=Math.max(_c.vmax,val.open,val.close,val.high,val.low);
}
});
}
if("ymin" in _d){
_c.vmin=Math.min(_e,_d.ymin);
}
if("ymax" in _d){
_c.vmax=Math.max(_f,_d.ymax);
}
}
return _c;
},getSeriesStats:function(){
var _10=this.collectStats(this.series);
_10.hmin-=0.5;
_10.hmax+=0.5;
return _10;
},render:function(dim,_11){
if(this.zoom&&!this.isDataDirty()){
return this.performZoom(dim,_11);
}
this.resetEvents();
this.dirty=this.isDirty();
var s;
if(this.dirty){
_3.forEach(this.series,_8);
this._eventSeries={};
this.cleanGroup();
s=this.getGroup();
df.forEachRev(this.series,function(_12){
_12.cleanGroup(s);
});
}
var t=this.chart.theme,f,gap,_13,ht=this._hScaler.scaler.getTransformerFromModel(this._hScaler),vt=this._vScaler.scaler.getTransformerFromModel(this._vScaler),_14=this.events();
f=dc.calculateBarSize(this._hScaler.bounds.scale,this.opt);
gap=f.gap;
_13=f.size;
for(var i=this.series.length-1;i>=0;--i){
var run=this.series[i];
if(!this.dirty&&!run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
var _15=t.next("candlestick",[this.opt,run]),_16=new Array(run.data.length);
if(run.hidden){
run.dyn.fill=_15.series.fill;
run.dyn.stroke=_15.series.stroke;
continue;
}
s=run.group;
for(var j=0;j<run.data.length;++j){
var v=run.data[j];
if(v!==null){
var _17=t.addMixin(_15,"candlestick",v,true);
var x=ht(v.x||(j+0.5))+_11.l+gap,y=dim.height-_11.b,_18=vt(v.open),_19=vt(v.close),_1a=vt(v.high),low=vt(v.low);
if("mid" in v){
var mid=vt(v.mid);
}
if(low>_1a){
var tmp=_1a;
_1a=low;
low=tmp;
}
if(_13>=1){
var _1b=_18>_19;
var _1c={x1:_13/2,x2:_13/2,y1:y-_1a,y2:y-low},_1d={x:0,y:y-Math.max(_18,_19),width:_13,height:Math.max(_1b?_18-_19:_19-_18,1)};
var _1e=s.createGroup();
_1e.setTransform({dx:x,dy:0});
var _1f=_1e.createGroup();
_1f.createLine(_1c).setStroke(_17.series.stroke);
_1f.createRect(_1d).setStroke(_17.series.stroke).setFill(_1b?_17.series.fill:"white");
if("mid" in v){
_1f.createLine({x1:(_17.series.stroke.width||1),x2:_13-(_17.series.stroke.width||1),y1:y-mid,y2:y-mid}).setStroke(_1b?"white":_17.series.stroke);
}
run.dyn.fill=_17.series.fill;
run.dyn.stroke=_17.series.stroke;
if(_14){
var o={element:"candlestick",index:j,run:run,shape:_1f,x:x,y:y-Math.max(_18,_19),cx:_13/2,cy:(y-Math.max(_18,_19))+(Math.max(_1b?_18-_19:_19-_18,1)/2),width:_13,height:Math.max(_1b?_18-_19:_19-_18,1),data:v};
this._connectEvents(o);
_16[j]=o;
}
}
if(this.animate){
this._animateCandlesticks(_1e,y-low,_1a-low);
}
}
}
this._eventSeries[run.name]=_16;
run.dirty=false;
}
this.dirty=false;
if(_4("dojo-bidi")){
this._checkOrientation(this.group,dim,_11);
}
return this;
},tooltipFunc:function(o){
return "<table cellpadding=\"1\" cellspacing=\"0\" border=\"0\" style=\"font-size:0.9em;\">"+"<tr><td>Open:</td><td align=\"right\"><strong>"+o.data.open+"</strong></td></tr>"+"<tr><td>High:</td><td align=\"right\"><strong>"+o.data.high+"</strong></td></tr>"+"<tr><td>Low:</td><td align=\"right\"><strong>"+o.data.low+"</strong></td></tr>"+"<tr><td>Close:</td><td align=\"right\"><strong>"+o.data.close+"</strong></td></tr>"+(o.data.mid!==undefined?"<tr><td>Mid:</td><td align=\"right\"><strong>"+o.data.mid+"</strong></td></tr>":"")+"</table>";
},_animateCandlesticks:function(_20,_21,_22){
fx.animateTransform(_1.delegate({shape:_20,duration:1200,transform:[{name:"translate",start:[0,_21-(_21/_22)],end:[0,0]},{name:"scale",start:[1,1/_22],end:[1,1]},{name:"original"}]},this.animate)).play();
}});
});
| brandon-bailey/osdms | assets/webodf/editor/dojox/charting/plot2d/Candlesticks.js | JavaScript | mit | 4,584 |
/*! jQuery UI - v1.10.2 - 2013-03-14
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.slider.js, jquery.ui.sortable.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js
* Copyright 2013 jQuery Foundation and other contributors Licensed MIT */
(function( $, undefined ) {
var uuid = 0,
runiqueId = /^ui-id-\d+$/;
// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};
$.extend( $.ui, {
version: "1.10.2",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
});
// plugins
$.fn.extend({
focus: (function( orig ) {
return function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
orig.apply( this, arguments );
};
})( $.fn.focus ),
scrollParent: function() {
var scrollParent;
if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x"));
}).eq(0);
}
return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent;
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
},
uniqueId: function() {
return this.each(function() {
if ( !this.id ) {
this.id = "ui-id-" + (++uuid);
}
});
},
removeUniqueId: function() {
return this.each(function() {
if ( runiqueId.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
});
}
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var map, mapName, img,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap=#" + mapName + "]" )[0];
return !!img && visible( img );
}
return ( /input|select|textarea|button|object/.test( nodeName ) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible( element );
}
function visible( element ) {
return $.expr.filters.visible( element ) &&
!$( element ).parents().addBack().filter(function() {
return $.css( this, "visibility" ) === "hidden";
}).length;
}
$.extend( $.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function( dataName ) {
return function( elem ) {
return !!$.data( elem, dataName );
};
}) :
// support: jQuery <1.8
function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
if ( border ) {
size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
}
// support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
$.fn.removeData = (function( removeData ) {
return function( key ) {
if ( arguments.length ) {
return removeData.call( this, $.camelCase( key ) );
} else {
return removeData.call( this );
}
};
})( $.fn.removeData );
}
// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
$.support.selectstart = "onselectstart" in document.createElement( "div" );
$.fn.extend({
disableSelection: function() {
return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
".ui-disableSelection", function( event ) {
event.preventDefault();
});
},
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
}
});
$.extend( $.ui, {
// $.ui.plugin is deprecated. Use the proxy pattern instead.
plugin: {
add: function( module, option, set ) {
var i,
proto = $.ui[ module ].prototype;
for ( i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args ) {
var i,
set = instance.plugins[ name ];
if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
return;
}
for ( i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
},
// only used by resizable
hasScroll: function( el, a ) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ( $( el ).css( "overflow" ) === "hidden") {
return false;
}
var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
has = false;
if ( el[ scroll ] > 0 ) {
return true;
}
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[ scroll ] = 1;
has = ( el[ scroll ] > 0 );
el[ scroll ] = 0;
return has;
}
});
})( jQuery );
(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
// proxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
proxiedPrototype = {},
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
})( jQuery );
(function( $, undefined ) {
var mouseHandled = false;
$( document ).mouseup( function() {
mouseHandled = false;
});
$.widget("ui.mouse", {
version: "1.10.2",
options: {
cancel: "input,textarea,button,select,option",
distance: 1,
delay: 0
},
_mouseInit: function() {
var that = this;
this.element
.bind("mousedown."+this.widgetName, function(event) {
return that._mouseDown(event);
})
.bind("click."+this.widgetName, function(event) {
if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
$.removeData(event.target, that.widgetName + ".preventClickEvent");
event.stopImmediatePropagation();
return false;
}
});
this.started = false;
},
// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.unbind("."+this.widgetName);
if ( this._mouseMoveDelegate ) {
$(document)
.unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
}
},
_mouseDown: function(event) {
// don't let more than one widget handle mouseStart
if( mouseHandled ) { return; }
// we may have missed mouseup (out of window)
(this._mouseStarted && this._mouseUp(event));
this._mouseDownEvent = event;
var that = this,
btnIsLeft = (event.which === 1),
// event.target.nodeName works around a bug in IE 8 with
// disabled inputs (#7620)
elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
return true;
}
this.mouseDelayMet = !this.options.delay;
if (!this.mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
that.mouseDelayMet = true;
}, this.options.delay);
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted = (this._mouseStart(event) !== false);
if (!this._mouseStarted) {
event.preventDefault();
return true;
}
}
// Click event may never have fired (Gecko & Opera)
if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
$.removeData(event.target, this.widgetName + ".preventClickEvent");
}
// these delegates are required to keep context
this._mouseMoveDelegate = function(event) {
return that._mouseMove(event);
};
this._mouseUpDelegate = function(event) {
return that._mouseUp(event);
};
$(document)
.bind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.bind("mouseup."+this.widgetName, this._mouseUpDelegate);
event.preventDefault();
mouseHandled = true;
return true;
},
_mouseMove: function(event) {
// IE mouseup check - mouseup happened when mouse was out of window
if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
return this._mouseUp(event);
}
if (this._mouseStarted) {
this._mouseDrag(event);
return event.preventDefault();
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted =
(this._mouseStart(this._mouseDownEvent, event) !== false);
(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
}
return !this._mouseStarted;
},
_mouseUp: function(event) {
$(document)
.unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
.unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
if (this._mouseStarted) {
this._mouseStarted = false;
if (event.target === this._mouseDownEvent.target) {
$.data(event.target, this.widgetName + ".preventClickEvent", true);
}
this._mouseStop(event);
}
return false;
},
_mouseDistanceMet: function(event) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - event.pageX),
Math.abs(this._mouseDownEvent.pageY - event.pageY)
) >= this.options.distance
);
},
_mouseDelayMet: function(/* event */) {
return this.mouseDelayMet;
},
// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function(/* event */) {},
_mouseDrag: function(/* event */) {},
_mouseStop: function(/* event */) {},
_mouseCapture: function(/* event */) { return true; }
});
})(jQuery);
(function( $, undefined ) {
$.ui = $.ui || {};
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
round = Math.round,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[0];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[0];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[0].clientWidth;
}
div.remove();
return (cachedScrollbarWidth = w1 - w2);
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ),
overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[0].scrollHeight );
return {
width: hasOverflowY ? $.position.scrollbarWidth() : 0,
height: hasOverflowX ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[0] );
return {
element: withinElement,
isWindow: isWindow,
offset: withinElement.offset() || { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: isWindow ? withinElement.width() : withinElement.outerWidth(),
height: isWindow ? withinElement.height() : withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[0].preventDefault ) {
// force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
});
// normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each(function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
// if the browser doesn't support fractions, then round for consistent results
if ( !$.support.offsetFractions ) {
position.left = round( position.left );
position.top = round( position.top );
}
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem : elem
});
}
});
if ( options.using ) {
// adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
});
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// element is wider than within
if ( data.collisionWidth > outerWidth ) {
// element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
position.left += overLeft - newOverRight;
// element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// element is taller than within
if ( data.collisionHeight > outerHeight ) {
// element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
position.top += overTop - newOverBottom;
// element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
}
else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
position.top += myOffset + atOffset + offset;
}
}
else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
// fraction support test
(function () {
var testElement, testElementParent, testElementStyle, offsetLeft, i,
body = document.getElementsByTagName( "body" )[ 0 ],
div = document.createElement( "div" );
//Create a "fake body" for testing based on method used in jQuery.support
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
};
if ( body ) {
$.extend( testElementStyle, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || document.documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
div.style.cssText = "position: absolute; left: 10.7432222px;";
offsetLeft = $( div ).offset().left;
$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
})();
}( jQuery ) );
(function( $, undefined ) {
var uid = 0,
hideProps = {},
showProps = {};
hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
showProps.height = showProps.paddingTop = showProps.paddingBottom =
showProps.borderTopWidth = showProps.borderBottomWidth = "show";
$.widget( "ui.accordion", {
version: "1.10.2",
options: {
active: 0,
animate: {},
collapsible: false,
event: "click",
header: "> li > :first-child,> :not(li):even",
heightStyle: "auto",
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
},
// callbacks
activate: null,
beforeActivate: null
},
_create: function() {
var options = this.options;
this.prevShow = this.prevHide = $();
this.element.addClass( "ui-accordion ui-widget ui-helper-reset" )
// ARIA
.attr( "role", "tablist" );
// don't allow collapsible: false and active: false / null
if ( !options.collapsible && (options.active === false || options.active == null) ) {
options.active = 0;
}
this._processPanels();
// handle negative values
if ( options.active < 0 ) {
options.active += this.headers.length;
}
this._refresh();
},
_getCreateEventData: function() {
return {
header: this.active,
panel: !this.active.length ? $() : this.active.next(),
content: !this.active.length ? $() : this.active.next()
};
},
_createIcons: function() {
var icons = this.options.icons;
if ( icons ) {
$( "<span>" )
.addClass( "ui-accordion-header-icon ui-icon " + icons.header )
.prependTo( this.headers );
this.active.children( ".ui-accordion-header-icon" )
.removeClass( icons.header )
.addClass( icons.activeHeader );
this.headers.addClass( "ui-accordion-icons" );
}
},
_destroyIcons: function() {
this.headers
.removeClass( "ui-accordion-icons" )
.children( ".ui-accordion-header-icon" )
.remove();
},
_destroy: function() {
var contents;
// clean up main element
this.element
.removeClass( "ui-accordion ui-widget ui-helper-reset" )
.removeAttr( "role" );
// clean up headers
this.headers
.removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
.removeAttr( "role" )
.removeAttr( "aria-selected" )
.removeAttr( "aria-controls" )
.removeAttr( "tabIndex" )
.each(function() {
if ( /^ui-accordion/.test( this.id ) ) {
this.removeAttribute( "id" );
}
});
this._destroyIcons();
// clean up content panels
contents = this.headers.next()
.css( "display", "" )
.removeAttr( "role" )
.removeAttr( "aria-expanded" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-labelledby" )
.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" )
.each(function() {
if ( /^ui-accordion/.test( this.id ) ) {
this.removeAttribute( "id" );
}
});
if ( this.options.heightStyle !== "content" ) {
contents.css( "height", "" );
}
},
_setOption: function( key, value ) {
if ( key === "active" ) {
// _activate() will handle invalid values and update this.options
this._activate( value );
return;
}
if ( key === "event" ) {
if ( this.options.event ) {
this._off( this.headers, this.options.event );
}
this._setupEvents( value );
}
this._super( key, value );
// setting collapsible: false while collapsed; open first panel
if ( key === "collapsible" && !value && this.options.active === false ) {
this._activate( 0 );
}
if ( key === "icons" ) {
this._destroyIcons();
if ( value ) {
this._createIcons();
}
}
// #5332 - opacity doesn't cascade to positioned elements in IE
// so we need to add the disabled class to the headers and panels
if ( key === "disabled" ) {
this.headers.add( this.headers.next() )
.toggleClass( "ui-state-disabled", !!value );
}
},
_keydown: function( event ) {
/*jshint maxcomplexity:15*/
if ( event.altKey || event.ctrlKey ) {
return;
}
var keyCode = $.ui.keyCode,
length = this.headers.length,
currentIndex = this.headers.index( event.target ),
toFocus = false;
switch ( event.keyCode ) {
case keyCode.RIGHT:
case keyCode.DOWN:
toFocus = this.headers[ ( currentIndex + 1 ) % length ];
break;
case keyCode.LEFT:
case keyCode.UP:
toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
break;
case keyCode.SPACE:
case keyCode.ENTER:
this._eventHandler( event );
break;
case keyCode.HOME:
toFocus = this.headers[ 0 ];
break;
case keyCode.END:
toFocus = this.headers[ length - 1 ];
break;
}
if ( toFocus ) {
$( event.target ).attr( "tabIndex", -1 );
$( toFocus ).attr( "tabIndex", 0 );
toFocus.focus();
event.preventDefault();
}
},
_panelKeyDown : function( event ) {
if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
$( event.currentTarget ).prev().focus();
}
},
refresh: function() {
var options = this.options;
this._processPanels();
// was collapsed or no panel
if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) {
options.active = false;
this.active = $();
// active false only when collapsible is true
} if ( options.active === false ) {
this._activate( 0 );
// was active, but active panel is gone
} else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
// all remaining panel are disabled
if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) {
options.active = false;
this.active = $();
// activate previous panel
} else {
this._activate( Math.max( 0, options.active - 1 ) );
}
// was active, active panel still exists
} else {
// make sure active index is correct
options.active = this.headers.index( this.active );
}
this._destroyIcons();
this._refresh();
},
_processPanels: function() {
this.headers = this.element.find( this.options.header )
.addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" );
this.headers.next()
.addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
.filter(":not(.ui-accordion-content-active)")
.hide();
},
_refresh: function() {
var maxHeight,
options = this.options,
heightStyle = options.heightStyle,
parent = this.element.parent(),
accordionId = this.accordionId = "ui-accordion-" +
(this.element.attr( "id" ) || ++uid);
this.active = this._findActive( options.active )
.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" )
.removeClass( "ui-corner-all" );
this.active.next()
.addClass( "ui-accordion-content-active" )
.show();
this.headers
.attr( "role", "tab" )
.each(function( i ) {
var header = $( this ),
headerId = header.attr( "id" ),
panel = header.next(),
panelId = panel.attr( "id" );
if ( !headerId ) {
headerId = accordionId + "-header-" + i;
header.attr( "id", headerId );
}
if ( !panelId ) {
panelId = accordionId + "-panel-" + i;
panel.attr( "id", panelId );
}
header.attr( "aria-controls", panelId );
panel.attr( "aria-labelledby", headerId );
})
.next()
.attr( "role", "tabpanel" );
this.headers
.not( this.active )
.attr({
"aria-selected": "false",
tabIndex: -1
})
.next()
.attr({
"aria-expanded": "false",
"aria-hidden": "true"
})
.hide();
// make sure at least one header is in the tab order
if ( !this.active.length ) {
this.headers.eq( 0 ).attr( "tabIndex", 0 );
} else {
this.active.attr({
"aria-selected": "true",
tabIndex: 0
})
.next()
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
}
this._createIcons();
this._setupEvents( options.event );
if ( heightStyle === "fill" ) {
maxHeight = parent.height();
this.element.siblings( ":visible" ).each(function() {
var elem = $( this ),
position = elem.css( "position" );
if ( position === "absolute" || position === "fixed" ) {
return;
}
maxHeight -= elem.outerHeight( true );
});
this.headers.each(function() {
maxHeight -= $( this ).outerHeight( true );
});
this.headers.next()
.each(function() {
$( this ).height( Math.max( 0, maxHeight -
$( this ).innerHeight() + $( this ).height() ) );
})
.css( "overflow", "auto" );
} else if ( heightStyle === "auto" ) {
maxHeight = 0;
this.headers.next()
.each(function() {
maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
})
.height( maxHeight );
}
},
_activate: function( index ) {
var active = this._findActive( index )[ 0 ];
// trying to activate the already active panel
if ( active === this.active[ 0 ] ) {
return;
}
// trying to collapse, simulate a click on the currently active header
active = active || this.active[ 0 ];
this._eventHandler({
target: active,
currentTarget: active,
preventDefault: $.noop
});
},
_findActive: function( selector ) {
return typeof selector === "number" ? this.headers.eq( selector ) : $();
},
_setupEvents: function( event ) {
var events = {
keydown: "_keydown"
};
if ( event ) {
$.each( event.split(" "), function( index, eventName ) {
events[ eventName ] = "_eventHandler";
});
}
this._off( this.headers.add( this.headers.next() ) );
this._on( this.headers, events );
this._on( this.headers.next(), { keydown: "_panelKeyDown" });
this._hoverable( this.headers );
this._focusable( this.headers );
},
_eventHandler: function( event ) {
var options = this.options,
active = this.active,
clicked = $( event.currentTarget ),
clickedIsActive = clicked[ 0 ] === active[ 0 ],
collapsing = clickedIsActive && options.collapsible,
toShow = collapsing ? $() : clicked.next(),
toHide = active.next(),
eventData = {
oldHeader: active,
oldPanel: toHide,
newHeader: collapsing ? $() : clicked,
newPanel: toShow
};
event.preventDefault();
if (
// click on active header, but not collapsible
( clickedIsActive && !options.collapsible ) ||
// allow canceling activation
( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
return;
}
options.active = collapsing ? false : this.headers.index( clicked );
// when the call to ._toggle() comes after the class changes
// it causes a very odd bug in IE 8 (see #6720)
this.active = clickedIsActive ? $() : clicked;
this._toggle( eventData );
// switch classes
// corner classes on the previously active header stay after the animation
active.removeClass( "ui-accordion-header-active ui-state-active" );
if ( options.icons ) {
active.children( ".ui-accordion-header-icon" )
.removeClass( options.icons.activeHeader )
.addClass( options.icons.header );
}
if ( !clickedIsActive ) {
clicked
.removeClass( "ui-corner-all" )
.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
if ( options.icons ) {
clicked.children( ".ui-accordion-header-icon" )
.removeClass( options.icons.header )
.addClass( options.icons.activeHeader );
}
clicked
.next()
.addClass( "ui-accordion-content-active" );
}
},
_toggle: function( data ) {
var toShow = data.newPanel,
toHide = this.prevShow.length ? this.prevShow : data.oldPanel;
// handle activating a panel during the animation for another activation
this.prevShow.add( this.prevHide ).stop( true, true );
this.prevShow = toShow;
this.prevHide = toHide;
if ( this.options.animate ) {
this._animate( toShow, toHide, data );
} else {
toHide.hide();
toShow.show();
this._toggleComplete( data );
}
toHide.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
toHide.prev().attr( "aria-selected", "false" );
// if we're switching panels, remove the old header from the tab order
// if we're opening from collapsed state, remove the previous header from the tab order
// if we're collapsing, then keep the collapsing header in the tab order
if ( toShow.length && toHide.length ) {
toHide.prev().attr( "tabIndex", -1 );
} else if ( toShow.length ) {
this.headers.filter(function() {
return $( this ).attr( "tabIndex" ) === 0;
})
.attr( "tabIndex", -1 );
}
toShow
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
})
.prev()
.attr({
"aria-selected": "true",
tabIndex: 0
});
},
_animate: function( toShow, toHide, data ) {
var total, easing, duration,
that = this,
adjust = 0,
down = toShow.length &&
( !toHide.length || ( toShow.index() < toHide.index() ) ),
animate = this.options.animate || {},
options = down && animate.down || animate,
complete = function() {
that._toggleComplete( data );
};
if ( typeof options === "number" ) {
duration = options;
}
if ( typeof options === "string" ) {
easing = options;
}
// fall back from options to animation in case of partial down settings
easing = easing || options.easing || animate.easing;
duration = duration || options.duration || animate.duration;
if ( !toHide.length ) {
return toShow.animate( showProps, duration, easing, complete );
}
if ( !toShow.length ) {
return toHide.animate( hideProps, duration, easing, complete );
}
total = toShow.show().outerHeight();
toHide.animate( hideProps, {
duration: duration,
easing: easing,
step: function( now, fx ) {
fx.now = Math.round( now );
}
});
toShow
.hide()
.animate( showProps, {
duration: duration,
easing: easing,
complete: complete,
step: function( now, fx ) {
fx.now = Math.round( now );
if ( fx.prop !== "height" ) {
adjust += fx.now;
} else if ( that.options.heightStyle !== "content" ) {
fx.now = Math.round( total - toHide.outerHeight() - adjust );
adjust = 0;
}
}
});
},
_toggleComplete: function( data ) {
var toHide = data.oldPanel;
toHide
.removeClass( "ui-accordion-content-active" )
.prev()
.removeClass( "ui-corner-top" )
.addClass( "ui-corner-all" );
// Work around for rendering bug in IE (#5421)
if ( toHide.length ) {
toHide.parent()[0].className = toHide.parent()[0].className;
}
this._trigger( "activate", null, data );
}
});
})( jQuery );
(function( $, undefined ) {
// used to prevent race conditions with remote data sources
var requestIndex = 0;
$.widget( "ui.autocomplete", {
version: "1.10.2",
defaultElement: "<input>",
options: {
appendTo: null,
autoFocus: false,
delay: 300,
minLength: 1,
position: {
my: "left top",
at: "left bottom",
collision: "none"
},
source: null,
// callbacks
change: null,
close: null,
focus: null,
open: null,
response: null,
search: null,
select: null
},
pending: 0,
_create: function() {
// Some browsers only repeat keydown events, not keypress events,
// so we use the suppressKeyPress flag to determine if we've already
// handled the keydown event. #7269
// Unfortunately the code for & in keypress is the same as the up arrow,
// so we use the suppressKeyPressRepeat flag to avoid handling keypress
// events when we know the keydown event was used to modify the
// search term. #7799
var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
nodeName = this.element[0].nodeName.toLowerCase(),
isTextarea = nodeName === "textarea",
isInput = nodeName === "input";
this.isMultiLine =
// Textareas are always multi-line
isTextarea ? true :
// Inputs are always single-line, even if inside a contentEditable element
// IE also treats inputs as contentEditable
isInput ? false :
// All other element types are determined by whether or not they're contentEditable
this.element.prop( "isContentEditable" );
this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
this.isNewMenu = true;
this.element
.addClass( "ui-autocomplete-input" )
.attr( "autocomplete", "off" );
this._on( this.element, {
keydown: function( event ) {
/*jshint maxcomplexity:15*/
if ( this.element.prop( "readOnly" ) ) {
suppressKeyPress = true;
suppressInput = true;
suppressKeyPressRepeat = true;
return;
}
suppressKeyPress = false;
suppressInput = false;
suppressKeyPressRepeat = false;
var keyCode = $.ui.keyCode;
switch( event.keyCode ) {
case keyCode.PAGE_UP:
suppressKeyPress = true;
this._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
suppressKeyPress = true;
this._move( "nextPage", event );
break;
case keyCode.UP:
suppressKeyPress = true;
this._keyEvent( "previous", event );
break;
case keyCode.DOWN:
suppressKeyPress = true;
this._keyEvent( "next", event );
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open and has focus
if ( this.menu.active ) {
// #6055 - Opera still allows the keypress to occur
// which causes forms to submit
suppressKeyPress = true;
event.preventDefault();
this.menu.select( event );
}
break;
case keyCode.TAB:
if ( this.menu.active ) {
this.menu.select( event );
}
break;
case keyCode.ESCAPE:
if ( this.menu.element.is( ":visible" ) ) {
this._value( this.term );
this.close( event );
// Different browsers have different default behavior for escape
// Single press can mean undo or clear
// Double press in IE means clear the whole form
event.preventDefault();
}
break;
default:
suppressKeyPressRepeat = true;
// search timeout should be triggered before the input value is changed
this._searchTimeout( event );
break;
}
},
keypress: function( event ) {
if ( suppressKeyPress ) {
suppressKeyPress = false;
event.preventDefault();
return;
}
if ( suppressKeyPressRepeat ) {
return;
}
// replicate some key handlers to allow them to repeat in Firefox and Opera
var keyCode = $.ui.keyCode;
switch( event.keyCode ) {
case keyCode.PAGE_UP:
this._move( "previousPage", event );
break;
case keyCode.PAGE_DOWN:
this._move( "nextPage", event );
break;
case keyCode.UP:
this._keyEvent( "previous", event );
break;
case keyCode.DOWN:
this._keyEvent( "next", event );
break;
}
},
input: function( event ) {
if ( suppressInput ) {
suppressInput = false;
event.preventDefault();
return;
}
this._searchTimeout( event );
},
focus: function() {
this.selectedItem = null;
this.previous = this._value();
},
blur: function( event ) {
if ( this.cancelBlur ) {
delete this.cancelBlur;
return;
}
clearTimeout( this.searching );
this.close( event );
this._change( event );
}
});
this._initSource();
this.menu = $( "<ul>" )
.addClass( "ui-autocomplete ui-front" )
.appendTo( this._appendTo() )
.menu({
// custom key handling for now
input: $(),
// disable ARIA support, the live region takes care of that
role: null
})
.hide()
.data( "ui-menu" );
this._on( this.menu.element, {
mousedown: function( event ) {
// prevent moving focus out of the text field
event.preventDefault();
// IE doesn't prevent moving focus even with event.preventDefault()
// so we set a flag to know when we should ignore the blur event
this.cancelBlur = true;
this._delay(function() {
delete this.cancelBlur;
});
// clicking on the scrollbar causes focus to shift to the body
// but we can't detect a mouseup or a click immediately afterward
// so we have to track the next mousedown and close the menu if
// the user clicks somewhere outside of the autocomplete
var menuElement = this.menu.element[ 0 ];
if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
this._delay(function() {
var that = this;
this.document.one( "mousedown", function( event ) {
if ( event.target !== that.element[ 0 ] &&
event.target !== menuElement &&
!$.contains( menuElement, event.target ) ) {
that.close();
}
});
});
}
},
menufocus: function( event, ui ) {
// support: Firefox
// Prevent accidental activation of menu items in Firefox (#7024 #9118)
if ( this.isNewMenu ) {
this.isNewMenu = false;
if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
this.menu.blur();
this.document.one( "mousemove", function() {
$( event.target ).trigger( event.originalEvent );
});
return;
}
}
var item = ui.item.data( "ui-autocomplete-item" );
if ( false !== this._trigger( "focus", event, { item: item } ) ) {
// use value to match what will end up in the input, if it was a key event
if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
this._value( item.value );
}
} else {
// Normally the input is populated with the item's value as the
// menu is navigated, causing screen readers to notice a change and
// announce the item. Since the focus event was canceled, this doesn't
// happen, so we update the live region so that screen readers can
// still notice the change and announce it.
this.liveRegion.text( item.value );
}
},
menuselect: function( event, ui ) {
var item = ui.item.data( "ui-autocomplete-item" ),
previous = this.previous;
// only trigger when focus was lost (click on menu)
if ( this.element[0] !== this.document[0].activeElement ) {
this.element.focus();
this.previous = previous;
// #6109 - IE triggers two focus events and the second
// is asynchronous, so we need to reset the previous
// term synchronously and asynchronously :-(
this._delay(function() {
this.previous = previous;
this.selectedItem = item;
});
}
if ( false !== this._trigger( "select", event, { item: item } ) ) {
this._value( item.value );
}
// reset the term after the select event
// this allows custom select handling to work properly
this.term = this._value();
this.close( event );
this.selectedItem = item;
}
});
this.liveRegion = $( "<span>", {
role: "status",
"aria-live": "polite"
})
.addClass( "ui-helper-hidden-accessible" )
.insertAfter( this.element );
// turning off autocomplete prevents the browser from remembering the
// value when navigating through history, so we re-enable autocomplete
// if the page is unloaded before the widget is destroyed. #7790
this._on( this.window, {
beforeunload: function() {
this.element.removeAttr( "autocomplete" );
}
});
},
_destroy: function() {
clearTimeout( this.searching );
this.element
.removeClass( "ui-autocomplete-input" )
.removeAttr( "autocomplete" );
this.menu.element.remove();
this.liveRegion.remove();
},
_setOption: function( key, value ) {
this._super( key, value );
if ( key === "source" ) {
this._initSource();
}
if ( key === "appendTo" ) {
this.menu.element.appendTo( this._appendTo() );
}
if ( key === "disabled" && value && this.xhr ) {
this.xhr.abort();
}
},
_appendTo: function() {
var element = this.options.appendTo;
if ( element ) {
element = element.jquery || element.nodeType ?
$( element ) :
this.document.find( element ).eq( 0 );
}
if ( !element ) {
element = this.element.closest( ".ui-front" );
}
if ( !element.length ) {
element = this.document[0].body;
}
return element;
},
_initSource: function() {
var array, url,
that = this;
if ( $.isArray(this.options.source) ) {
array = this.options.source;
this.source = function( request, response ) {
response( $.ui.autocomplete.filter( array, request.term ) );
};
} else if ( typeof this.options.source === "string" ) {
url = this.options.source;
this.source = function( request, response ) {
if ( that.xhr ) {
that.xhr.abort();
}
that.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
success: function( data ) {
response( data );
},
error: function() {
response( [] );
}
});
};
} else {
this.source = this.options.source;
}
},
_searchTimeout: function( event ) {
clearTimeout( this.searching );
this.searching = this._delay(function() {
// only search if the value has changed
if ( this.term !== this._value() ) {
this.selectedItem = null;
this.search( null, event );
}
}, this.options.delay );
},
search: function( value, event ) {
value = value != null ? value : this._value();
// always save the actual value, not the one passed as an argument
this.term = this._value();
if ( value.length < this.options.minLength ) {
return this.close( event );
}
if ( this._trigger( "search", event ) === false ) {
return;
}
return this._search( value );
},
_search: function( value ) {
this.pending++;
this.element.addClass( "ui-autocomplete-loading" );
this.cancelSearch = false;
this.source( { term: value }, this._response() );
},
_response: function() {
var that = this,
index = ++requestIndex;
return function( content ) {
if ( index === requestIndex ) {
that.__response( content );
}
that.pending--;
if ( !that.pending ) {
that.element.removeClass( "ui-autocomplete-loading" );
}
};
},
__response: function( content ) {
if ( content ) {
content = this._normalize( content );
}
this._trigger( "response", null, { content: content } );
if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
this._suggest( content );
this._trigger( "open" );
} else {
// use ._close() instead of .close() so we don't cancel future searches
this._close();
}
},
close: function( event ) {
this.cancelSearch = true;
this._close( event );
},
_close: function( event ) {
if ( this.menu.element.is( ":visible" ) ) {
this.menu.element.hide();
this.menu.blur();
this.isNewMenu = true;
this._trigger( "close", event );
}
},
_change: function( event ) {
if ( this.previous !== this._value() ) {
this._trigger( "change", event, { item: this.selectedItem } );
}
},
_normalize: function( items ) {
// assume all items have the right format when the first item is complete
if ( items.length && items[0].label && items[0].value ) {
return items;
}
return $.map( items, function( item ) {
if ( typeof item === "string" ) {
return {
label: item,
value: item
};
}
return $.extend({
label: item.label || item.value,
value: item.value || item.label
}, item );
});
},
_suggest: function( items ) {
var ul = this.menu.element.empty();
this._renderMenu( ul, items );
this.isNewMenu = true;
this.menu.refresh();
// size and position menu
ul.show();
this._resizeMenu();
ul.position( $.extend({
of: this.element
}, this.options.position ));
if ( this.options.autoFocus ) {
this.menu.next();
}
},
_resizeMenu: function() {
var ul = this.menu.element;
ul.outerWidth( Math.max(
// Firefox wraps long text (possibly a rounding bug)
// so we add 1px to avoid the wrapping (#7513)
ul.width( "" ).outerWidth() + 1,
this.element.outerWidth()
) );
},
_renderMenu: function( ul, items ) {
var that = this;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
},
_renderItemData: function( ul, item ) {
return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
},
_renderItem: function( ul, item ) {
return $( "<li>" )
.append( $( "<a>" ).text( item.label ) )
.appendTo( ul );
},
_move: function( direction, event ) {
if ( !this.menu.element.is( ":visible" ) ) {
this.search( null, event );
return;
}
if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
this.menu.isLastItem() && /^next/.test( direction ) ) {
this._value( this.term );
this.menu.blur();
return;
}
this.menu[ direction ]( event );
},
widget: function() {
return this.menu.element;
},
_value: function() {
return this.valueMethod.apply( this.element, arguments );
},
_keyEvent: function( keyEvent, event ) {
if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
this._move( keyEvent, event );
// prevents moving cursor to beginning/end of the text field in some browsers
event.preventDefault();
}
}
});
$.extend( $.ui.autocomplete, {
escapeRegex: function( value ) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
},
filter: function(array, term) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
return $.grep( array, function(value) {
return matcher.test( value.label || value.value || value );
});
}
});
// live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
options: {
messages: {
noResults: "No search results.",
results: function( amount ) {
return amount + ( amount > 1 ? " results are" : " result is" ) +
" available, use up and down arrow keys to navigate.";
}
}
},
__response: function( content ) {
var message;
this._superApply( arguments );
if ( this.options.disabled || this.cancelSearch ) {
return;
}
if ( content && content.length ) {
message = this.options.messages.results( content.length );
} else {
message = this.options.messages.noResults;
}
this.liveRegion.text( message );
}
});
}( jQuery ));
(function( $, undefined ) {
var lastActive, startXPos, startYPos, clickDragged,
baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
stateClasses = "ui-state-hover ui-state-active ",
typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
formResetHandler = function() {
var buttons = $( this ).find( ":ui-button" );
setTimeout(function() {
buttons.button( "refresh" );
}, 1 );
},
radioGroup = function( radio ) {
var name = radio.name,
form = radio.form,
radios = $( [] );
if ( name ) {
name = name.replace( /'/g, "\\'" );
if ( form ) {
radios = $( form ).find( "[name='" + name + "']" );
} else {
radios = $( "[name='" + name + "']", radio.ownerDocument )
.filter(function() {
return !this.form;
});
}
}
return radios;
};
$.widget( "ui.button", {
version: "1.10.2",
defaultElement: "<button>",
options: {
disabled: null,
text: true,
label: null,
icons: {
primary: null,
secondary: null
}
},
_create: function() {
this.element.closest( "form" )
.unbind( "reset" + this.eventNamespace )
.bind( "reset" + this.eventNamespace, formResetHandler );
if ( typeof this.options.disabled !== "boolean" ) {
this.options.disabled = !!this.element.prop( "disabled" );
} else {
this.element.prop( "disabled", this.options.disabled );
}
this._determineButtonType();
this.hasTitle = !!this.buttonElement.attr( "title" );
var that = this,
options = this.options,
toggleButton = this.type === "checkbox" || this.type === "radio",
activeClass = !toggleButton ? "ui-state-active" : "",
focusClass = "ui-state-focus";
if ( options.label === null ) {
options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
}
this._hoverable( this.buttonElement );
this.buttonElement
.addClass( baseClasses )
.attr( "role", "button" )
.bind( "mouseenter" + this.eventNamespace, function() {
if ( options.disabled ) {
return;
}
if ( this === lastActive ) {
$( this ).addClass( "ui-state-active" );
}
})
.bind( "mouseleave" + this.eventNamespace, function() {
if ( options.disabled ) {
return;
}
$( this ).removeClass( activeClass );
})
.bind( "click" + this.eventNamespace, function( event ) {
if ( options.disabled ) {
event.preventDefault();
event.stopImmediatePropagation();
}
});
this.element
.bind( "focus" + this.eventNamespace, function() {
// no need to check disabled, focus won't be triggered anyway
that.buttonElement.addClass( focusClass );
})
.bind( "blur" + this.eventNamespace, function() {
that.buttonElement.removeClass( focusClass );
});
if ( toggleButton ) {
this.element.bind( "change" + this.eventNamespace, function() {
if ( clickDragged ) {
return;
}
that.refresh();
});
// if mouse moves between mousedown and mouseup (drag) set clickDragged flag
// prevents issue where button state changes but checkbox/radio checked state
// does not in Firefox (see ticket #6970)
this.buttonElement
.bind( "mousedown" + this.eventNamespace, function( event ) {
if ( options.disabled ) {
return;
}
clickDragged = false;
startXPos = event.pageX;
startYPos = event.pageY;
})
.bind( "mouseup" + this.eventNamespace, function( event ) {
if ( options.disabled ) {
return;
}
if ( startXPos !== event.pageX || startYPos !== event.pageY ) {
clickDragged = true;
}
});
}
if ( this.type === "checkbox" ) {
this.buttonElement.bind( "click" + this.eventNamespace, function() {
if ( options.disabled || clickDragged ) {
return false;
}
});
} else if ( this.type === "radio" ) {
this.buttonElement.bind( "click" + this.eventNamespace, function() {
if ( options.disabled || clickDragged ) {
return false;
}
$( this ).addClass( "ui-state-active" );
that.buttonElement.attr( "aria-pressed", "true" );
var radio = that.element[ 0 ];
radioGroup( radio )
.not( radio )
.map(function() {
return $( this ).button( "widget" )[ 0 ];
})
.removeClass( "ui-state-active" )
.attr( "aria-pressed", "false" );
});
} else {
this.buttonElement
.bind( "mousedown" + this.eventNamespace, function() {
if ( options.disabled ) {
return false;
}
$( this ).addClass( "ui-state-active" );
lastActive = this;
that.document.one( "mouseup", function() {
lastActive = null;
});
})
.bind( "mouseup" + this.eventNamespace, function() {
if ( options.disabled ) {
return false;
}
$( this ).removeClass( "ui-state-active" );
})
.bind( "keydown" + this.eventNamespace, function(event) {
if ( options.disabled ) {
return false;
}
if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
$( this ).addClass( "ui-state-active" );
}
})
// see #8559, we bind to blur here in case the button element loses
// focus between keydown and keyup, it would be left in an "active" state
.bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
$( this ).removeClass( "ui-state-active" );
});
if ( this.buttonElement.is("a") ) {
this.buttonElement.keyup(function(event) {
if ( event.keyCode === $.ui.keyCode.SPACE ) {
// TODO pass through original event correctly (just as 2nd argument doesn't work)
$( this ).click();
}
});
}
}
// TODO: pull out $.Widget's handling for the disabled option into
// $.Widget.prototype._setOptionDisabled so it's easy to proxy and can
// be overridden by individual plugins
this._setOption( "disabled", options.disabled );
this._resetButton();
},
_determineButtonType: function() {
var ancestor, labelSelector, checked;
if ( this.element.is("[type=checkbox]") ) {
this.type = "checkbox";
} else if ( this.element.is("[type=radio]") ) {
this.type = "radio";
} else if ( this.element.is("input") ) {
this.type = "input";
} else {
this.type = "button";
}
if ( this.type === "checkbox" || this.type === "radio" ) {
// we don't search against the document in case the element
// is disconnected from the DOM
ancestor = this.element.parents().last();
labelSelector = "label[for='" + this.element.attr("id") + "']";
this.buttonElement = ancestor.find( labelSelector );
if ( !this.buttonElement.length ) {
ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
this.buttonElement = ancestor.filter( labelSelector );
if ( !this.buttonElement.length ) {
this.buttonElement = ancestor.find( labelSelector );
}
}
this.element.addClass( "ui-helper-hidden-accessible" );
checked = this.element.is( ":checked" );
if ( checked ) {
this.buttonElement.addClass( "ui-state-active" );
}
this.buttonElement.prop( "aria-pressed", checked );
} else {
this.buttonElement = this.element;
}
},
widget: function() {
return this.buttonElement;
},
_destroy: function() {
this.element
.removeClass( "ui-helper-hidden-accessible" );
this.buttonElement
.removeClass( baseClasses + " " + stateClasses + " " + typeClasses )
.removeAttr( "role" )
.removeAttr( "aria-pressed" )
.html( this.buttonElement.find(".ui-button-text").html() );
if ( !this.hasTitle ) {
this.buttonElement.removeAttr( "title" );
}
},
_setOption: function( key, value ) {
this._super( key, value );
if ( key === "disabled" ) {
if ( value ) {
this.element.prop( "disabled", true );
} else {
this.element.prop( "disabled", false );
}
return;
}
this._resetButton();
},
refresh: function() {
//See #8237 & #8828
var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" );
if ( isDisabled !== this.options.disabled ) {
this._setOption( "disabled", isDisabled );
}
if ( this.type === "radio" ) {
radioGroup( this.element[0] ).each(function() {
if ( $( this ).is( ":checked" ) ) {
$( this ).button( "widget" )
.addClass( "ui-state-active" )
.attr( "aria-pressed", "true" );
} else {
$( this ).button( "widget" )
.removeClass( "ui-state-active" )
.attr( "aria-pressed", "false" );
}
});
} else if ( this.type === "checkbox" ) {
if ( this.element.is( ":checked" ) ) {
this.buttonElement
.addClass( "ui-state-active" )
.attr( "aria-pressed", "true" );
} else {
this.buttonElement
.removeClass( "ui-state-active" )
.attr( "aria-pressed", "false" );
}
}
},
_resetButton: function() {
if ( this.type === "input" ) {
if ( this.options.label ) {
this.element.val( this.options.label );
}
return;
}
var buttonElement = this.buttonElement.removeClass( typeClasses ),
buttonText = $( "<span></span>", this.document[0] )
.addClass( "ui-button-text" )
.html( this.options.label )
.appendTo( buttonElement.empty() )
.text(),
icons = this.options.icons,
multipleIcons = icons.primary && icons.secondary,
buttonClasses = [];
if ( icons.primary || icons.secondary ) {
if ( this.options.text ) {
buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
}
if ( icons.primary ) {
buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
}
if ( icons.secondary ) {
buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
}
if ( !this.options.text ) {
buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );
if ( !this.hasTitle ) {
buttonElement.attr( "title", $.trim( buttonText ) );
}
}
} else {
buttonClasses.push( "ui-button-text-only" );
}
buttonElement.addClass( buttonClasses.join( " " ) );
}
});
$.widget( "ui.buttonset", {
version: "1.10.2",
options: {
items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"
},
_create: function() {
this.element.addClass( "ui-buttonset" );
},
_init: function() {
this.refresh();
},
_setOption: function( key, value ) {
if ( key === "disabled" ) {
this.buttons.button( "option", key, value );
}
this._super( key, value );
},
refresh: function() {
var rtl = this.element.css( "direction" ) === "rtl";
this.buttons = this.element.find( this.options.items )
.filter( ":ui-button" )
.button( "refresh" )
.end()
.not( ":ui-button" )
.button()
.end()
.map(function() {
return $( this ).button( "widget" )[ 0 ];
})
.removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
.filter( ":first" )
.addClass( rtl ? "ui-corner-right" : "ui-corner-left" )
.end()
.filter( ":last" )
.addClass( rtl ? "ui-corner-left" : "ui-corner-right" )
.end()
.end();
},
_destroy: function() {
this.element.removeClass( "ui-buttonset" );
this.buttons
.map(function() {
return $( this ).button( "widget" )[ 0 ];
})
.removeClass( "ui-corner-left ui-corner-right" )
.end()
.button( "destroy" );
}
});
}( jQuery ) );
(function( $, undefined ) {
$.extend($.ui, { datepicker: { version: "1.10.2" } });
var PROP_NAME = "datepicker",
dpuuid = new Date().getTime(),
instActive;
/* Date picker manager.
Use the singleton instance of this class, $.datepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Datepicker() {
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
this._appendClass = "ui-datepicker-append"; // The name of the append marker class
this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[""] = { // Default regional settings
closeText: "Done", // Display text for close link
prevText: "Prev", // Display text for previous month link
nextText: "Next", // Display text for next month link
currentText: "Today", // Display text for current month link
monthNames: ["January","February","March","April","May","June",
"July","August","September","October","November","December"], // Names of months for drop-down and formatting
monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
weekHeader: "Wk", // Column header for week of the year
dateFormat: "mm/dd/yy", // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: "" // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: "focus", // "focus" for popup on focus,
// "button" for trigger button, or "both" for either
showAnim: "fadeIn", // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: "", // Display text following the input box, e.g. showing the format
buttonText: "...", // Text for trigger button
buttonImage: "", // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: "c-10:c+10", // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: "+10", // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with "+" for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: "fast", // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: "", // Selector for an alternate field to store selected dates into
altFormat: "", // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false, // True to size the input for the date format, false to leave as is
disabled: false // The initial disabled state
};
$.extend(this._defaults, this.regional[""]);
this.dpDiv = bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
}
$.extend(Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: "hasDatepicker",
//Keep track of the maximum number of rows displayed (see #7043)
maxRows: 4,
// TODO rename to "widget" when switching to widget factory
_widgetDatepicker: function() {
return this.dpDiv;
},
/* Override the default settings for all instances of the date picker.
* @param settings object - the new settings to use as defaults (anonymous object)
* @return the manager object
*/
setDefaults: function(settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the date picker to a jQuery selection.
* @param target element - the target input field or division or span
* @param settings object - the new settings to use for this date picker instance (anonymous)
*/
_attachDatepicker: function(target, settings) {
var nodeName, inline, inst;
nodeName = target.nodeName.toLowerCase();
inline = (nodeName === "div" || nodeName === "span");
if (!target.id) {
this.uuid += 1;
target.id = "dp" + this.uuid;
}
inst = this._newInst($(target), inline);
inst.settings = $.extend({}, settings || {});
if (nodeName === "input") {
this._connectDatepicker(target, inst);
} else if (inline) {
this._inlineDatepicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function(target, inline) {
var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
return {id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
inline: inline, // is datepicker inline or not
dpDiv: (!inline ? this.dpDiv : // presentation div
bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
},
/* Attach the date picker to an input field. */
_connectDatepicker: function(target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName)) {
return;
}
this._attachments(input, inst);
input.addClass(this.markerClassName).keydown(this._doKeyDown).
keypress(this._doKeyPress).keyup(this._doKeyUp);
this._autoSize(inst);
$.data(target, PROP_NAME, inst);
//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
},
/* Make attachments based on settings. */
_attachments: function(input, inst) {
var showOn, buttonText, buttonImage,
appendText = this._get(inst, "appendText"),
isRTL = this._get(inst, "isRTL");
if (inst.append) {
inst.append.remove();
}
if (appendText) {
inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
input[isRTL ? "before" : "after"](inst.append);
}
input.unbind("focus", this._showDatepicker);
if (inst.trigger) {
inst.trigger.remove();
}
showOn = this._get(inst, "showOn");
if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
input.focus(this._showDatepicker);
}
if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
buttonText = this._get(inst, "buttonText");
buttonImage = this._get(inst, "buttonImage");
inst.trigger = $(this._get(inst, "buttonImageOnly") ?
$("<img/>").addClass(this._triggerClass).
attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
$("<button type='button'></button>").addClass(this._triggerClass).
html(!buttonImage ? buttonText : $("<img/>").attr(
{ src:buttonImage, alt:buttonText, title:buttonText })));
input[isRTL ? "before" : "after"](inst.trigger);
inst.trigger.click(function() {
if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
$.datepicker._hideDatepicker();
} else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
$.datepicker._hideDatepicker();
$.datepicker._showDatepicker(input[0]);
} else {
$.datepicker._showDatepicker(input[0]);
}
return false;
});
}
},
/* Apply the maximum length for the date format. */
_autoSize: function(inst) {
if (this._get(inst, "autoSize") && !inst.inline) {
var findMax, max, maxI, i,
date = new Date(2009, 12 - 1, 20), // Ensure double digits
dateFormat = this._get(inst, "dateFormat");
if (dateFormat.match(/[DM]/)) {
findMax = function(names) {
max = 0;
maxI = 0;
for (i = 0; i < names.length; i++) {
if (names[i].length > max) {
max = names[i].length;
maxI = i;
}
}
return maxI;
};
date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
"monthNames" : "monthNamesShort"))));
date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
"dayNames" : "dayNamesShort"))) + 20 - date.getDay());
}
inst.input.attr("size", this._formatDate(inst, date).length);
}
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function(target, inst) {
var divSpan = $(target);
if (divSpan.hasClass(this.markerClassName)) {
return;
}
divSpan.addClass(this.markerClassName).append(inst.dpDiv);
$.data(target, PROP_NAME, inst);
this._setDate(inst, this._getDefaultDate(inst), true);
this._updateDatepicker(inst);
this._updateAlternate(inst);
//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
inst.dpDiv.css( "display", "block" );
},
/* Pop-up the date picker in a "dialog" box.
* @param input element - ignored
* @param date string or Date - the initial date to display
* @param onSelect function - the function to call when a date is selected
* @param settings object - update the dialog date picker instance's settings (anonymous object)
* @param pos int[2] - coordinates for the dialog's position within the screen or
* event - with x/y coordinates or
* leave empty for default (screen centre)
* @return the manager object
*/
_dialogDatepicker: function(input, date, onSelect, settings, pos) {
var id, browserWidth, browserHeight, scrollX, scrollY,
inst = this._dialogInst; // internal instance
if (!inst) {
this.uuid += 1;
id = "dp" + this.uuid;
this._dialogInput = $("<input type='text' id='" + id +
"' style='position: absolute; top: -100px; width: 0px;'/>");
this._dialogInput.keydown(this._doKeyDown);
$("body").append(this._dialogInput);
inst = this._dialogInst = this._newInst(this._dialogInput, false);
inst.settings = {};
$.data(this._dialogInput[0], PROP_NAME, inst);
}
extendRemove(inst.settings, settings || {});
date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
this._dialogInput.val(date);
this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
if (!this._pos) {
browserWidth = document.documentElement.clientWidth;
browserHeight = document.documentElement.clientHeight;
scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
}
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
inst.settings.onSelect = onSelect;
this._inDialog = true;
this.dpDiv.addClass(this._dialogClass);
this._showDatepicker(this._dialogInput[0]);
if ($.blockUI) {
$.blockUI(this.dpDiv);
}
$.data(this._dialogInput[0], PROP_NAME, inst);
return this;
},
/* Detach a datepicker from its control.
* @param target element - the target input field or division or span
*/
_destroyDatepicker: function(target) {
var nodeName,
$target = $(target),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
$.removeData(target, PROP_NAME);
if (nodeName === "input") {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).
unbind("focus", this._showDatepicker).
unbind("keydown", this._doKeyDown).
unbind("keypress", this._doKeyPress).
unbind("keyup", this._doKeyUp);
} else if (nodeName === "div" || nodeName === "span") {
$target.removeClass(this.markerClassName).empty();
}
},
/* Enable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_enableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = false;
inst.trigger.filter("button").
each(function() { this.disabled = false; }).end().
filter("img").css({opacity: "1.0", cursor: ""});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().removeClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", false);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value === target ? null : value); }); // delete entry
},
/* Disable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_disableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = true;
inst.trigger.filter("button").
each(function() { this.disabled = true; }).end().
filter("img").css({opacity: "0.5", cursor: "default"});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().addClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", true);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value === target ? null : value); }); // delete entry
this._disabledInputs[this._disabledInputs.length] = target;
},
/* Is the first field in a jQuery collection disabled as a datepicker?
* @param target element - the target input field or division or span
* @return boolean - true if disabled, false if enabled
*/
_isDisabledDatepicker: function(target) {
if (!target) {
return false;
}
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] === target) {
return true;
}
}
return false;
},
/* Retrieve the instance data for the target control.
* @param target element - the target input field or division or span
* @return object - the associated instance data
* @throws error if a jQuery problem getting data
*/
_getInst: function(target) {
try {
return $.data(target, PROP_NAME);
}
catch (err) {
throw "Missing instance data for this datepicker";
}
},
/* Update or retrieve the settings for a date picker attached to an input field or division.
* @param target element - the target input field or division or span
* @param name object - the new settings to update or
* string - the name of the setting to change or retrieve,
* when retrieving also "all" for all instance settings or
* "defaults" for all global defaults
* @param value any - the new value for the setting
* (omit if above is an object or to retrieve a value)
*/
_optionDatepicker: function(target, name, value) {
var settings, date, minDate, maxDate,
inst = this._getInst(target);
if (arguments.length === 2 && typeof name === "string") {
return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
(inst ? (name === "all" ? $.extend({}, inst.settings) :
this._get(inst, name)) : null));
}
settings = name || {};
if (typeof name === "string") {
settings = {};
settings[name] = value;
}
if (inst) {
if (this._curInst === inst) {
this._hideDatepicker();
}
date = this._getDateDatepicker(target, true);
minDate = this._getMinMaxDate(inst, "min");
maxDate = this._getMinMaxDate(inst, "max");
extendRemove(inst.settings, settings);
// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
inst.settings.minDate = this._formatDate(inst, minDate);
}
if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
inst.settings.maxDate = this._formatDate(inst, maxDate);
}
if ( "disabled" in settings ) {
if ( settings.disabled ) {
this._disableDatepicker(target);
} else {
this._enableDatepicker(target);
}
}
this._attachments($(target), inst);
this._autoSize(inst);
this._setDate(inst, date);
this._updateAlternate(inst);
this._updateDatepicker(inst);
}
},
// change method deprecated
_changeDatepicker: function(target, name, value) {
this._optionDatepicker(target, name, value);
},
/* Redraw the date picker attached to an input field or division.
* @param target element - the target input field or division or span
*/
_refreshDatepicker: function(target) {
var inst = this._getInst(target);
if (inst) {
this._updateDatepicker(inst);
}
},
/* Set the dates for a jQuery selection.
* @param target element - the target input field or division or span
* @param date Date - the new date
*/
_setDateDatepicker: function(target, date) {
var inst = this._getInst(target);
if (inst) {
this._setDate(inst, date);
this._updateDatepicker(inst);
this._updateAlternate(inst);
}
},
/* Get the date(s) for the first entry in a jQuery selection.
* @param target element - the target input field or division or span
* @param noDefault boolean - true if no default date is to be used
* @return Date - the current date
*/
_getDateDatepicker: function(target, noDefault) {
var inst = this._getInst(target);
if (inst && !inst.inline) {
this._setDateFromField(inst, noDefault);
}
return (inst ? this._getDate(inst) : null);
},
/* Handle keystrokes. */
_doKeyDown: function(event) {
var onSelect, dateStr, sel,
inst = $.datepicker._getInst(event.target),
handled = true,
isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
inst._keyEvent = true;
if ($.datepicker._datepickerShowing) {
switch (event.keyCode) {
case 9: $.datepicker._hideDatepicker();
handled = false;
break; // hide on tab out
case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
$.datepicker._currentClass + ")", inst.dpDiv);
if (sel[0]) {
$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
}
onSelect = $.datepicker._get(inst, "onSelect");
if (onSelect) {
dateStr = $.datepicker._formatDate(inst);
// trigger custom callback
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
} else {
$.datepicker._hideDatepicker();
}
return false; // don't submit the form
case 27: $.datepicker._hideDatepicker();
break; // hide on escape
case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
break; // previous month/year on page up/+ ctrl
case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
break; // next month/year on page down/+ ctrl
case 35: if (event.ctrlKey || event.metaKey) {
$.datepicker._clearDate(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36: if (event.ctrlKey || event.metaKey) {
$.datepicker._gotoToday(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
}
handled = event.ctrlKey || event.metaKey;
// -1 day on ctrl or command +left
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +left on Mac
break;
case 38: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, -7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // -1 week on ctrl or command +up
case 39: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
}
handled = event.ctrlKey || event.metaKey;
// +1 day on ctrl or command +right
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +right
break;
case 40: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, +7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // +1 week on ctrl or command +down
default: handled = false;
}
} else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
$.datepicker._showDatepicker(this);
} else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Filter entered characters - based on date format. */
_doKeyPress: function(event) {
var chars, chr,
inst = $.datepicker._getInst(event.target);
if ($.datepicker._get(inst, "constrainInput")) {
chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
}
},
/* Synchronise manual entry and field/alternate field. */
_doKeyUp: function(event) {
var date,
inst = $.datepicker._getInst(event.target);
if (inst.input.val() !== inst.lastVal) {
try {
date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
(inst.input ? inst.input.val() : null),
$.datepicker._getFormatConfig(inst));
if (date) { // only if valid
$.datepicker._setDateFromField(inst);
$.datepicker._updateAlternate(inst);
$.datepicker._updateDatepicker(inst);
}
}
catch (err) {
}
}
return true;
},
/* Pop-up the date picker for a given input field.
* If false returned from beforeShow event handler do not show.
* @param input element - the input field attached to the date picker or
* event - if triggered by focus
*/
_showDatepicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
input = $("input", input.parentNode)[0];
}
if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
return;
}
var inst, beforeShow, beforeShowSettings, isFixed,
offset, showAnim, duration;
inst = $.datepicker._getInst(input);
if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
$.datepicker._curInst.dpDiv.stop(true, true);
if ( inst && $.datepicker._datepickerShowing ) {
$.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
}
}
beforeShow = $.datepicker._get(inst, "beforeShow");
beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
if(beforeShowSettings === false){
return;
}
extendRemove(inst.settings, beforeShowSettings);
inst.lastVal = null;
$.datepicker._lastInput = input;
$.datepicker._setDateFromField(inst);
if ($.datepicker._inDialog) { // hide cursor
input.value = "";
}
if (!$.datepicker._pos) { // position below input
$.datepicker._pos = $.datepicker._findPos(input);
$.datepicker._pos[1] += input.offsetHeight; // add the height
}
isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css("position") === "fixed";
return !isFixed;
});
offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
$.datepicker._pos = null;
//to avoid flashes on Firefox
inst.dpDiv.empty();
// determine sizing offscreen
inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
$.datepicker._updateDatepicker(inst);
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.datepicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
"static" : (isFixed ? "fixed" : "absolute")), display: "none",
left: offset.left + "px", top: offset.top + "px"});
if (!inst.inline) {
showAnim = $.datepicker._get(inst, "showAnim");
duration = $.datepicker._get(inst, "duration");
inst.dpDiv.zIndex($(input).zIndex()+1);
$.datepicker._datepickerShowing = true;
if ( $.effects && $.effects.effect[ showAnim ] ) {
inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
} else {
inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
}
if (inst.input.is(":visible") && !inst.input.is(":disabled")) {
inst.input.focus();
}
$.datepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function(inst) {
this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
instActive = inst; // for delegate hover events
inst.dpDiv.empty().append(this._generateHTML(inst));
this._attachHandlers(inst);
inst.dpDiv.find("." + this._dayOverClass + " a").mouseover();
var origyearshtml,
numMonths = this._getNumberOfMonths(inst),
cols = numMonths[1],
width = 17;
inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
if (cols > 1) {
inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
}
inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
"Class"]("ui-datepicker-multi");
inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
"Class"]("ui-datepicker-rtl");
// #6694 - don't focus the input if it's already focused
// this breaks the change event in IE
if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input &&
inst.input.is(":visible") && !inst.input.is(":disabled") && inst.input[0] !== document.activeElement) {
inst.input.focus();
}
// deffered render of the years select (to avoid flashes on Firefox)
if( inst.yearshtml ){
origyearshtml = inst.yearshtml;
setTimeout(function(){
//assure that inst.yearshtml didn't change.
if( origyearshtml === inst.yearshtml && inst.yearshtml ){
inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
}
origyearshtml = inst.yearshtml = null;
}, 0);
}
},
/* Retrieve the size of left and top borders for an element.
* @param elem (jQuery object) the element of interest
* @return (number[2]) the left and top borders
*/
_getBorders: function(elem) {
var convert = function(value) {
return {thin: 1, medium: 2, thick: 3}[value] || value;
};
return [parseFloat(convert(elem.css("border-left-width"))),
parseFloat(convert(elem.css("border-top-width")))];
},
/* Check positioning to remain on screen. */
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth(),
dpHeight = inst.dpDiv.outerHeight(),
inputWidth = inst.input ? inst.input.outerWidth() : 0,
inputHeight = inst.input ? inst.input.outerHeight() : 0,
viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight) : 0);
return offset;
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
var position,
inst = this._getInst(obj),
isRTL = this._get(inst, "isRTL");
while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
obj = obj[isRTL ? "previousSibling" : "nextSibling"];
}
position = $(obj).offset();
return [position.left, position.top];
},
/* Hide the date picker from view.
* @param input element - the input field attached to the date picker
*/
_hideDatepicker: function(input) {
var showAnim, duration, postProcess, onClose,
inst = this._curInst;
if (!inst || (input && inst !== $.data(input, PROP_NAME))) {
return;
}
if (this._datepickerShowing) {
showAnim = this._get(inst, "showAnim");
duration = this._get(inst, "duration");
postProcess = function() {
$.datepicker._tidyDialog(inst);
};
// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
} else {
inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
(showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
}
if (!showAnim) {
postProcess();
}
this._datepickerShowing = false;
onClose = this._get(inst, "onClose");
if (onClose) {
onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
}
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
if ($.blockUI) {
$.unblockUI();
$("body").append(this.dpDiv);
}
}
this._inDialog = false;
}
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.datepicker._curInst) {
return;
}
var $target = $(event.target),
inst = $.datepicker._getInst($target[0]);
if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
$target.parents("#" + $.datepicker._mainDivId).length === 0 &&
!$target.hasClass($.datepicker.markerClassName) &&
!$target.closest("." + $.datepicker._triggerClass).length &&
$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
$.datepicker._hideDatepicker();
}
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var target = $(id),
inst = this._getInst(target[0]);
if (this._isDisabledDatepicker(target[0])) {
return;
}
this._adjustInstDate(inst, offset +
(period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
period);
this._updateDatepicker(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var date,
target = $(id),
inst = this._getInst(target[0]);
if (this._get(inst, "gotoCurrent") && inst.currentDay) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
} else {
date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
}
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var target = $(id),
inst = this._getInst(target[0]);
inst["selected" + (period === "M" ? "Month" : "Year")] =
inst["draw" + (period === "M" ? "Month" : "Year")] =
parseInt(select.options[select.selectedIndex].value,10);
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a day. */
_selectDay: function(id, month, year, td) {
var inst,
target = $(id);
if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
return;
}
inst = this._getInst(target[0]);
inst.selectedDay = inst.currentDay = $("a", td).html();
inst.selectedMonth = inst.currentMonth = month;
inst.selectedYear = inst.currentYear = year;
this._selectDate(id, this._formatDate(inst,
inst.currentDay, inst.currentMonth, inst.currentYear));
},
/* Erase the input field and hide the date picker. */
_clearDate: function(id) {
var target = $(id);
this._selectDate(target, "");
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var onSelect,
target = $(id),
inst = this._getInst(target[0]);
dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
if (inst.input) {
inst.input.val(dateStr);
}
this._updateAlternate(inst);
onSelect = this._get(inst, "onSelect");
if (onSelect) {
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
} else if (inst.input) {
inst.input.trigger("change"); // fire the change event
}
if (inst.inline){
this._updateDatepicker(inst);
} else {
this._hideDatepicker();
this._lastInput = inst.input[0];
if (typeof(inst.input[0]) !== "object") {
inst.input.focus(); // restore focus
}
this._lastInput = null;
}
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function(inst) {
var altFormat, date, dateStr,
altField = this._get(inst, "altField");
if (altField) { // update alternate field too
altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
date = this._getDate(inst);
dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
$(altField).each(function() { $(this).val(dateStr); });
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
* @param date Date - the date to customise
* @return [boolean, string] - is this date selectable?, what is its CSS class?
*/
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ""];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* @param date Date - the date to get the week for
* @return number - the number of the week within the year that contains this date
*/
iso8601Week: function(date) {
var time,
checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
},
/* Parse a string value into a date object.
* See formatDate below for the possible formats.
*
* @param format string - the expected format of the date
* @param value string - the date in the above format
* @param settings Object - attributes include:
* shortYearCutoff number - the cutoff year for determining the century (optional)
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return Date - the extracted date value or null if value is blank
*/
parseDate: function (format, value, settings) {
if (format == null || value == null) {
throw "Invalid arguments";
}
value = (typeof value === "object" ? value.toString() : value + "");
if (value === "") {
return null;
}
var iFormat, dim, extra,
iValue = 0,
shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
year = -1,
month = -1,
day = -1,
doy = -1,
literal = false,
date,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Extract a number from the string value
getNumber = function(match) {
var isDoubled = lookAhead(match),
size = (match === "@" ? 14 : (match === "!" ? 20 :
(match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
digits = new RegExp("^\\d{1," + size + "}"),
num = value.substring(iValue).match(digits);
if (!num) {
throw "Missing number at position " + iValue;
}
iValue += num[0].length;
return parseInt(num[0], 10);
},
// Extract a name from the string value and convert to an index
getName = function(match, shortNames, longNames) {
var index = -1,
names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
return [ [k, v] ];
}).sort(function (a, b) {
return -(a[1].length - b[1].length);
});
$.each(names, function (i, pair) {
var name = pair[1];
if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
index = pair[0];
iValue += name.length;
return false;
}
});
if (index !== -1) {
return index + 1;
} else {
throw "Unknown name at position " + iValue;
}
},
// Confirm that a literal character matches the string value
checkLiteral = function() {
if (value.charAt(iValue) !== format.charAt(iFormat)) {
throw "Unexpected literal at position " + iValue;
}
iValue++;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
checkLiteral();
}
} else {
switch (format.charAt(iFormat)) {
case "d":
day = getNumber("d");
break;
case "D":
getName("D", dayNamesShort, dayNames);
break;
case "o":
doy = getNumber("o");
break;
case "m":
month = getNumber("m");
break;
case "M":
month = getName("M", monthNamesShort, monthNames);
break;
case "y":
year = getNumber("y");
break;
case "@":
date = new Date(getNumber("@"));
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "!":
date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "'":
if (lookAhead("'")){
checkLiteral();
} else {
literal = true;
}
break;
default:
checkLiteral();
}
}
}
if (iValue < value.length){
extra = value.substr(iValue);
if (!/^\s+/.test(extra)) {
throw "Extra/unparsed characters found in date: " + extra;
}
}
if (year === -1) {
year = new Date().getFullYear();
} else if (year < 100) {
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
(year <= shortYearCutoff ? 0 : -100);
}
if (doy > -1) {
month = 1;
day = doy;
do {
dim = this._getDaysInMonth(year, month - 1);
if (day <= dim) {
break;
}
month++;
day -= dim;
} while (true);
}
date = this._daylightSavingAdjust(new Date(year, month - 1, day));
if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
throw "Invalid date"; // E.g. 31/02/00
}
return date;
},
/* Standard date formats. */
ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
COOKIE: "D, dd M yy",
ISO_8601: "yy-mm-dd",
RFC_822: "D, d M y",
RFC_850: "DD, dd-M-y",
RFC_1036: "D, d M y",
RFC_1123: "D, d M yy",
RFC_2822: "D, d M yy",
RSS: "D, d M y", // RFC 822
TICKS: "!",
TIMESTAMP: "@",
W3C: "yy-mm-dd", // ISO 8601
_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
/* Format a date object into a string value.
* The format can be combinations of the following:
* d - day of month (no leading zero)
* dd - day of month (two digit)
* o - day of year (no leading zeros)
* oo - day of year (three digit)
* D - day name short
* DD - day name long
* m - month of year (no leading zero)
* mm - month of year (two digit)
* M - month name short
* MM - month name long
* y - year (two digit)
* yy - year (four digit)
* @ - Unix timestamp (ms since 01/01/1970)
* ! - Windows ticks (100ns since 01/01/0001)
* "..." - literal text
* '' - single quote
*
* @param format string - the desired format of the date
* @param date Date - the date value to format
* @param settings Object - attributes include:
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return string - the date in the above format
*/
formatDate: function (format, date, settings) {
if (!date) {
return "";
}
var iFormat,
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Format a number, with leading zero if necessary
formatNumber = function(match, value, len) {
var num = "" + value;
if (lookAhead(match)) {
while (num.length < len) {
num = "0" + num;
}
}
return num;
},
// Format a name, short or long as requested
formatName = function(match, value, shortNames, longNames) {
return (lookAhead(match) ? longNames[value] : shortNames[value]);
},
output = "",
literal = false;
if (date) {
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
output += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d":
output += formatNumber("d", date.getDate(), 2);
break;
case "D":
output += formatName("D", date.getDay(), dayNamesShort, dayNames);
break;
case "o":
output += formatNumber("o",
Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
break;
case "m":
output += formatNumber("m", date.getMonth() + 1, 2);
break;
case "M":
output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
break;
case "y":
output += (lookAhead("y") ? date.getFullYear() :
(date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
break;
case "@":
output += date.getTime();
break;
case "!":
output += date.getTime() * 10000 + this._ticksTo1970;
break;
case "'":
if (lookAhead("'")) {
output += "'";
} else {
literal = true;
}
break;
default:
output += format.charAt(iFormat);
}
}
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function (format) {
var iFormat,
chars = "",
literal = false,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
chars += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d": case "m": case "y": case "@":
chars += "0123456789";
break;
case "D": case "M":
return null; // Accept anything
case "'":
if (lookAhead("'")) {
chars += "'";
} else {
literal = true;
}
break;
default:
chars += format.charAt(iFormat);
}
}
}
return chars;
},
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst, noDefault) {
if (inst.input.val() === inst.lastVal) {
return;
}
var dateFormat = this._get(inst, "dateFormat"),
dates = inst.lastVal = inst.input ? inst.input.val() : null,
defaultDate = this._getDefaultDate(inst),
date = defaultDate,
settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
dates = (noDefault ? "" : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
return this._restrictMinMax(inst,
this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(inst, date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
},
offsetString = function(offset) {
try {
return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
offset, $.datepicker._getFormatConfig(inst));
}
catch (e) {
// Ignore
}
var date = (offset.toLowerCase().match(/^c/) ?
$.datepicker._getDate(inst) : null) || new Date(),
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || "d") {
case "d" : case "D" :
day += parseInt(matches[1],10); break;
case "w" : case "W" :
day += parseInt(matches[1],10) * 7; break;
case "m" : case "M" :
month += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
case "y": case "Y" :
year += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
},
newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
(typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
if (newDate) {
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return this._daylightSavingAdjust(newDate);
},
/* Handle switch to/from daylight saving.
* Hours may be non-zero on daylight saving cut-over:
* > 12 when midnight changeover, but then cannot generate
* midnight datetime, so jump to 1AM, otherwise reset.
* @param date (Date) the date to check
* @return (Date) the corrected date
*/
_daylightSavingAdjust: function(date) {
if (!date) {
return null;
}
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return date;
},
/* Set the date(s) directly. */
_setDate: function(inst, date, noChange) {
var clear = !date,
origMonth = inst.selectedMonth,
origYear = inst.selectedYear,
newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
inst.selectedDay = inst.currentDay = newDate.getDate();
inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
this._notifyChange(inst);
}
this._adjustInstDate(inst);
if (inst.input) {
inst.input.val(clear ? "" : this._formatDate(inst));
}
},
/* Retrieve the date(s) directly. */
_getDate: function(inst) {
var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
this._daylightSavingAdjust(new Date(
inst.currentYear, inst.currentMonth, inst.currentDay)));
return startDate;
},
/* Attach the onxxx handlers. These are declared statically so
* they work with static code transformers like Caja.
*/
_attachHandlers: function(inst) {
var stepMonths = this._get(inst, "stepMonths"),
id = "#" + inst.id.replace( /\\\\/g, "\\" );
inst.dpDiv.find("[data-handler]").map(function () {
var handler = {
prev: function () {
window["DP_jQuery_" + dpuuid].datepicker._adjustDate(id, -stepMonths, "M");
},
next: function () {
window["DP_jQuery_" + dpuuid].datepicker._adjustDate(id, +stepMonths, "M");
},
hide: function () {
window["DP_jQuery_" + dpuuid].datepicker._hideDatepicker();
},
today: function () {
window["DP_jQuery_" + dpuuid].datepicker._gotoToday(id);
},
selectDay: function () {
window["DP_jQuery_" + dpuuid].datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
return false;
},
selectMonth: function () {
window["DP_jQuery_" + dpuuid].datepicker._selectMonthYear(id, this, "M");
return false;
},
selectYear: function () {
window["DP_jQuery_" + dpuuid].datepicker._selectMonthYear(id, this, "Y");
return false;
}
};
$(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
});
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function(inst) {
var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
printDate, dRow, tbody, daySettings, otherMonth, unselectable,
tempDate = new Date(),
today = this._daylightSavingAdjust(
new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
isRTL = this._get(inst, "isRTL"),
showButtonPanel = this._get(inst, "showButtonPanel"),
hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
numMonths = this._getNumberOfMonths(inst),
showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
stepMonths = this._get(inst, "stepMonths"),
isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
drawMonth = inst.drawMonth - showCurrentAtPos,
drawYear = inst.drawYear;
if (drawMonth < 0) {
drawMonth += 12;
drawYear--;
}
if (maxDate) {
maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
drawMonth--;
if (drawMonth < 0) {
drawMonth = 11;
drawYear--;
}
}
}
inst.drawMonth = drawMonth;
inst.drawYear = drawYear;
prevText = this._get(inst, "prevText");
prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
this._getFormatConfig(inst)));
prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));
nextText = this._get(inst, "nextText");
nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
this._getFormatConfig(inst)));
next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));
currentText = this._get(inst, "currentText");
gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
currentText = (!navigationAsDateFormat ? currentText :
this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
this._get(inst, "closeText") + "</button>" : "");
buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
(this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";
firstDay = parseInt(this._get(inst, "firstDay"),10);
firstDay = (isNaN(firstDay) ? 0 : firstDay);
showWeek = this._get(inst, "showWeek");
dayNames = this._get(inst, "dayNames");
dayNamesMin = this._get(inst, "dayNamesMin");
monthNames = this._get(inst, "monthNames");
monthNamesShort = this._get(inst, "monthNamesShort");
beforeShowDay = this._get(inst, "beforeShowDay");
showOtherMonths = this._get(inst, "showOtherMonths");
selectOtherMonths = this._get(inst, "selectOtherMonths");
defaultDate = this._getDefaultDate(inst);
html = "";
dow;
for (row = 0; row < numMonths[0]; row++) {
group = "";
this.maxRows = 4;
for (col = 0; col < numMonths[1]; col++) {
selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
cornerClass = " ui-corner-all";
calender = "";
if (isMultiMonth) {
calender += "<div class='ui-datepicker-group";
if (numMonths[1] > 1) {
switch (col) {
case 0: calender += " ui-datepicker-group-first";
cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break;
case numMonths[1]-1: calender += " ui-datepicker-group-last";
cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break;
default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
}
}
calender += "'>";
}
calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
(/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
(/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
"</div><table class='ui-datepicker-calendar'><thead>" +
"<tr>";
thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
for (dow = 0; dow < 7; dow++) { // days of the week
day = (dow + firstDay) % 7;
thead += "<th" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
"<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
}
calender += thead + "</tr></thead><tbody>";
daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
}
leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
this.maxRows = numRows;
printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
calender += "<tr>";
tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
this._get(inst, "calculateWeek")(printDate) + "</td>");
for (dow = 0; dow < 7; dow++) { // create date picker days
daySettings = (beforeShowDay ?
beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
otherMonth = (printDate.getMonth() !== drawMonth);
unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
tbody += "<td class='" +
((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
(otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
(defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
" " + this._dayOverClass : "") + // highlight selected day
(unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days
(otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
(printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
(printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "'") + "'" : "") + // cell title
(unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
(otherMonth && !showOtherMonths ? " " : // display for other months
(unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
(printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
(printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
(otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
"' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
printDate.setDate(printDate.getDate() + 1);
printDate = this._daylightSavingAdjust(printDate);
}
calender += tbody + "</tr>";
}
drawMonth++;
if (drawMonth > 11) {
drawMonth = 0;
drawYear++;
}
calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
group += calender;
}
html += group;
}
html += buttonPanel;
inst._keyEvent = false;
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
changeMonth = this._get(inst, "changeMonth"),
changeYear = this._get(inst, "changeYear"),
showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
html = "<div class='ui-datepicker-title'>",
monthHtml = "";
// month selection
if (secondary || !changeMonth) {
monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
} else {
inMinYear = (minDate && minDate.getFullYear() === drawYear);
inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
for ( month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
monthHtml += "<option value='" + month + "'" +
(month === drawMonth ? " selected='selected'" : "") +
">" + monthNamesShort[month] + "</option>";
}
}
monthHtml += "</select>";
}
if (!showMonthAfterYear) {
html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : "");
}
// year selection
if ( !inst.yearshtml ) {
inst.yearshtml = "";
if (secondary || !changeYear) {
html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
} else {
// determine range of years to display
years = this._get(inst, "yearRange").split(":");
thisYear = new Date().getFullYear();
determineYear = function(value) {
var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
year = determineYear(years[0]);
endYear = Math.max(year, determineYear(years[1] || ""));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
for (; year <= endYear; year++) {
inst.yearshtml += "<option value='" + year + "'" +
(year === drawYear ? " selected='selected'" : "") +
">" + year + "</option>";
}
inst.yearshtml += "</select>";
html += inst.yearshtml;
inst.yearshtml = null;
}
}
html += this._get(inst, "yearSuffix");
if (showMonthAfterYear) {
html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml;
}
html += "</div>"; // Close datepicker_header
return html;
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function(inst, offset, period) {
var year = inst.drawYear + (period === "Y" ? offset : 0),
month = inst.drawMonth + (period === "M" ? offset : 0),
day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
if (period === "M" || period === "Y") {
this._notifyChange(inst);
}
},
/* Ensure a date is within any min/max bounds. */
_restrictMinMax: function(inst, date) {
var minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
newDate = (minDate && date < minDate ? minDate : date);
return (maxDate && newDate > maxDate ? maxDate : newDate);
},
/* Notify change of month/year. */
_notifyChange: function(inst) {
var onChange = this._get(inst, "onChangeMonthYear");
if (onChange) {
onChange.apply((inst.input ? inst.input[0] : null),
[inst.selectedYear, inst.selectedMonth + 1, inst]);
}
},
/* Determine the number of months to show. */
_getNumberOfMonths: function(inst) {
var numMonths = this._get(inst, "numberOfMonths");
return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
},
/* Determine the current maximum date - ensure no time components are set. */
_getMinMaxDate: function(inst, minMax) {
return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(inst, offset, curYear, curMonth) {
var numMonths = this._getNumberOfMonths(inst),
date = this._daylightSavingAdjust(new Date(curYear,
curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
if (offset < 0) {
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
}
return this._isInRange(inst, date);
},
/* Is the given date in the accepted range? */
_isInRange: function(inst, date) {
var yearSplit, currentYear,
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
minYear = null,
maxYear = null,
years = this._get(inst, "yearRange");
if (years){
yearSplit = years.split(":");
currentYear = new Date().getFullYear();
minYear = parseInt(yearSplit[0], 10);
maxYear = parseInt(yearSplit[1], 10);
if ( yearSplit[0].match(/[+\-].*/) ) {
minYear += currentYear;
}
if ( yearSplit[1].match(/[+\-].*/) ) {
maxYear += currentYear;
}
}
return ((!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()) &&
(!minYear || date.getFullYear() >= minYear) &&
(!maxYear || date.getFullYear() <= maxYear));
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function(inst) {
var shortYearCutoff = this._get(inst, "shortYearCutoff");
shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
},
/* Format the given date for display. */
_formatDate: function(inst, day, month, year) {
if (!day) {
inst.currentDay = inst.selectedDay;
inst.currentMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
}
var date = (day ? (typeof day === "object" ? day :
this._daylightSavingAdjust(new Date(year, month, day))) :
this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
}
});
/*
* Bind hover events for datepicker elements.
* Done via delegate so the binding only occurs once in the lifetime of the parent div.
* Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
*/
function bindHover(dpDiv) {
var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
return dpDiv.delegate(selector, "mouseout", function() {
$(this).removeClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).removeClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).removeClass("ui-datepicker-next-hover");
}
})
.delegate(selector, "mouseover", function(){
if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) {
$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
$(this).addClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).addClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).addClass("ui-datepicker-next-hover");
}
}
});
}
/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
$.extend(target, props);
for (var name in props) {
if (props[name] == null) {
target[name] = props[name];
}
}
return target;
}
/* Invoke the datepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new datepicker functionality
@return jQuery object */
$.fn.datepicker = function(options){
/* Verify an empty collection wasn't passed - Fixes #6976 */
if ( !this.length ) {
return this;
}
/* Initialise the date picker. */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick);
$.datepicker.initialized = true;
}
/* Append datepicker main container to body if not exist. */
if ($("#"+$.datepicker._mainDivId).length === 0) {
$("body").append($.datepicker.dpDiv);
}
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
return this.each(function() {
typeof options === "string" ?
$.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this].concat(otherArgs)) :
$.datepicker._attachDatepicker(this, options);
});
};
$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.10.2";
// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window["DP_jQuery_" + dpuuid] = $;
})(jQuery);
(function( $, undefined ) {
var sizeRelatedOptions = {
buttons: true,
height: true,
maxHeight: true,
maxWidth: true,
minHeight: true,
minWidth: true,
width: true
},
resizableRelatedOptions = {
maxHeight: true,
maxWidth: true,
minHeight: true,
minWidth: true
};
$.widget( "ui.dialog", {
version: "1.10.2",
options: {
appendTo: "body",
autoOpen: true,
buttons: [],
closeOnEscape: true,
closeText: "close",
dialogClass: "",
draggable: true,
hide: null,
height: "auto",
maxHeight: null,
maxWidth: null,
minHeight: 150,
minWidth: 150,
modal: false,
position: {
my: "center",
at: "center",
of: window,
collision: "fit",
// Ensure the titlebar is always visible
using: function( pos ) {
var topOffset = $( this ).css( pos ).offset().top;
if ( topOffset < 0 ) {
$( this ).css( "top", pos.top - topOffset );
}
}
},
resizable: true,
show: null,
title: null,
width: 300,
// callbacks
beforeClose: null,
close: null,
drag: null,
dragStart: null,
dragStop: null,
focus: null,
open: null,
resize: null,
resizeStart: null,
resizeStop: null
},
_create: function() {
this.originalCss = {
display: this.element[0].style.display,
width: this.element[0].style.width,
minHeight: this.element[0].style.minHeight,
maxHeight: this.element[0].style.maxHeight,
height: this.element[0].style.height
};
this.originalPosition = {
parent: this.element.parent(),
index: this.element.parent().children().index( this.element )
};
this.originalTitle = this.element.attr("title");
this.options.title = this.options.title || this.originalTitle;
this._createWrapper();
this.element
.show()
.removeAttr("title")
.addClass("ui-dialog-content ui-widget-content")
.appendTo( this.uiDialog );
this._createTitlebar();
this._createButtonPane();
if ( this.options.draggable && $.fn.draggable ) {
this._makeDraggable();
}
if ( this.options.resizable && $.fn.resizable ) {
this._makeResizable();
}
this._isOpen = false;
},
_init: function() {
if ( this.options.autoOpen ) {
this.open();
}
},
_appendTo: function() {
var element = this.options.appendTo;
if ( element && (element.jquery || element.nodeType) ) {
return $( element );
}
return this.document.find( element || "body" ).eq( 0 );
},
_destroy: function() {
var next,
originalPosition = this.originalPosition;
this._destroyOverlay();
this.element
.removeUniqueId()
.removeClass("ui-dialog-content ui-widget-content")
.css( this.originalCss )
// Without detaching first, the following becomes really slow
.detach();
this.uiDialog.stop( true, true ).remove();
if ( this.originalTitle ) {
this.element.attr( "title", this.originalTitle );
}
next = originalPosition.parent.children().eq( originalPosition.index );
// Don't try to place the dialog next to itself (#8613)
if ( next.length && next[0] !== this.element[0] ) {
next.before( this.element );
} else {
originalPosition.parent.append( this.element );
}
},
widget: function() {
return this.uiDialog;
},
disable: $.noop,
enable: $.noop,
close: function( event ) {
var that = this;
if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
return;
}
this._isOpen = false;
this._destroyOverlay();
if ( !this.opener.filter(":focusable").focus().length ) {
// Hiding a focused element doesn't trigger blur in WebKit
// so in case we have nothing to focus on, explicitly blur the active element
// https://bugs.webkit.org/show_bug.cgi?id=47182
$( this.document[0].activeElement ).blur();
}
this._hide( this.uiDialog, this.options.hide, function() {
that._trigger( "close", event );
});
},
isOpen: function() {
return this._isOpen;
},
moveToTop: function() {
this._moveToTop();
},
_moveToTop: function( event, silent ) {
var moved = !!this.uiDialog.nextAll(":visible").insertBefore( this.uiDialog ).length;
if ( moved && !silent ) {
this._trigger( "focus", event );
}
return moved;
},
open: function() {
var that = this;
if ( this._isOpen ) {
if ( this._moveToTop() ) {
this._focusTabbable();
}
return;
}
this._isOpen = true;
this.opener = $( this.document[0].activeElement );
this._size();
this._position();
this._createOverlay();
this._moveToTop( null, true );
this._show( this.uiDialog, this.options.show, function() {
that._focusTabbable();
that._trigger("focus");
});
this._trigger("open");
},
_focusTabbable: function() {
// Set focus to the first match:
// 1. First element inside the dialog matching [autofocus]
// 2. Tabbable element inside the content element
// 3. Tabbable element inside the buttonpane
// 4. The close button
// 5. The dialog itself
var hasFocus = this.element.find("[autofocus]");
if ( !hasFocus.length ) {
hasFocus = this.element.find(":tabbable");
}
if ( !hasFocus.length ) {
hasFocus = this.uiDialogButtonPane.find(":tabbable");
}
if ( !hasFocus.length ) {
hasFocus = this.uiDialogTitlebarClose.filter(":tabbable");
}
if ( !hasFocus.length ) {
hasFocus = this.uiDialog;
}
hasFocus.eq( 0 ).focus();
},
_keepFocus: function( event ) {
function checkFocus() {
var activeElement = this.document[0].activeElement,
isActive = this.uiDialog[0] === activeElement ||
$.contains( this.uiDialog[0], activeElement );
if ( !isActive ) {
this._focusTabbable();
}
}
event.preventDefault();
checkFocus.call( this );
// support: IE
// IE <= 8 doesn't prevent moving focus even with event.preventDefault()
// so we check again later
this._delay( checkFocus );
},
_createWrapper: function() {
this.uiDialog = $("<div>")
.addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " +
this.options.dialogClass )
.hide()
.attr({
// Setting tabIndex makes the div focusable
tabIndex: -1,
role: "dialog"
})
.appendTo( this._appendTo() );
this._on( this.uiDialog, {
keydown: function( event ) {
if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
event.keyCode === $.ui.keyCode.ESCAPE ) {
event.preventDefault();
this.close( event );
return;
}
// prevent tabbing out of dialogs
if ( event.keyCode !== $.ui.keyCode.TAB ) {
return;
}
var tabbables = this.uiDialog.find(":tabbable"),
first = tabbables.filter(":first"),
last = tabbables.filter(":last");
if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) {
first.focus( 1 );
event.preventDefault();
} else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) {
last.focus( 1 );
event.preventDefault();
}
},
mousedown: function( event ) {
if ( this._moveToTop( event ) ) {
this._focusTabbable();
}
}
});
// We assume that any existing aria-describedby attribute means
// that the dialog content is marked up properly
// otherwise we brute force the content as the description
if ( !this.element.find("[aria-describedby]").length ) {
this.uiDialog.attr({
"aria-describedby": this.element.uniqueId().attr("id")
});
}
},
_createTitlebar: function() {
var uiDialogTitle;
this.uiDialogTitlebar = $("<div>")
.addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix")
.prependTo( this.uiDialog );
this._on( this.uiDialogTitlebar, {
mousedown: function( event ) {
// Don't prevent click on close button (#8838)
// Focusing a dialog that is partially scrolled out of view
// causes the browser to scroll it into view, preventing the click event
if ( !$( event.target ).closest(".ui-dialog-titlebar-close") ) {
// Dialog isn't getting focus when dragging (#8063)
this.uiDialog.focus();
}
}
});
this.uiDialogTitlebarClose = $("<button></button>")
.button({
label: this.options.closeText,
icons: {
primary: "ui-icon-closethick"
},
text: false
})
.addClass("ui-dialog-titlebar-close")
.appendTo( this.uiDialogTitlebar );
this._on( this.uiDialogTitlebarClose, {
click: function( event ) {
event.preventDefault();
this.close( event );
}
});
uiDialogTitle = $("<span>")
.uniqueId()
.addClass("ui-dialog-title")
.prependTo( this.uiDialogTitlebar );
this._title( uiDialogTitle );
this.uiDialog.attr({
"aria-labelledby": uiDialogTitle.attr("id")
});
},
_title: function( title ) {
if ( !this.options.title ) {
title.html(" ");
}
title.text( this.options.title );
},
_createButtonPane: function() {
this.uiDialogButtonPane = $("<div>")
.addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");
this.uiButtonSet = $("<div>")
.addClass("ui-dialog-buttonset")
.appendTo( this.uiDialogButtonPane );
this._createButtons();
},
_createButtons: function() {
var that = this,
buttons = this.options.buttons;
// if we already have a button pane, remove it
this.uiDialogButtonPane.remove();
this.uiButtonSet.empty();
if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) {
this.uiDialog.removeClass("ui-dialog-buttons");
return;
}
$.each( buttons, function( name, props ) {
var click, buttonOptions;
props = $.isFunction( props ) ?
{ click: props, text: name } :
props;
// Default to a non-submitting button
props = $.extend( { type: "button" }, props );
// Change the context for the click callback to be the main element
click = props.click;
props.click = function() {
click.apply( that.element[0], arguments );
};
buttonOptions = {
icons: props.icons,
text: props.showText
};
delete props.icons;
delete props.showText;
$( "<button></button>", props )
.button( buttonOptions )
.appendTo( that.uiButtonSet );
});
this.uiDialog.addClass("ui-dialog-buttons");
this.uiDialogButtonPane.appendTo( this.uiDialog );
},
_makeDraggable: function() {
var that = this,
options = this.options;
function filteredUi( ui ) {
return {
position: ui.position,
offset: ui.offset
};
}
this.uiDialog.draggable({
cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
handle: ".ui-dialog-titlebar",
containment: "document",
start: function( event, ui ) {
$( this ).addClass("ui-dialog-dragging");
that._blockFrames();
that._trigger( "dragStart", event, filteredUi( ui ) );
},
drag: function( event, ui ) {
that._trigger( "drag", event, filteredUi( ui ) );
},
stop: function( event, ui ) {
options.position = [
ui.position.left - that.document.scrollLeft(),
ui.position.top - that.document.scrollTop()
];
$( this ).removeClass("ui-dialog-dragging");
that._unblockFrames();
that._trigger( "dragStop", event, filteredUi( ui ) );
}
});
},
_makeResizable: function() {
var that = this,
options = this.options,
handles = options.resizable,
// .ui-resizable has position: relative defined in the stylesheet
// but dialogs have to use absolute or fixed positioning
position = this.uiDialog.css("position"),
resizeHandles = typeof handles === "string" ?
handles :
"n,e,s,w,se,sw,ne,nw";
function filteredUi( ui ) {
return {
originalPosition: ui.originalPosition,
originalSize: ui.originalSize,
position: ui.position,
size: ui.size
};
}
this.uiDialog.resizable({
cancel: ".ui-dialog-content",
containment: "document",
alsoResize: this.element,
maxWidth: options.maxWidth,
maxHeight: options.maxHeight,
minWidth: options.minWidth,
minHeight: this._minHeight(),
handles: resizeHandles,
start: function( event, ui ) {
$( this ).addClass("ui-dialog-resizing");
that._blockFrames();
that._trigger( "resizeStart", event, filteredUi( ui ) );
},
resize: function( event, ui ) {
that._trigger( "resize", event, filteredUi( ui ) );
},
stop: function( event, ui ) {
options.height = $( this ).height();
options.width = $( this ).width();
$( this ).removeClass("ui-dialog-resizing");
that._unblockFrames();
that._trigger( "resizeStop", event, filteredUi( ui ) );
}
})
.css( "position", position );
},
_minHeight: function() {
var options = this.options;
return options.height === "auto" ?
options.minHeight :
Math.min( options.minHeight, options.height );
},
_position: function() {
// Need to show the dialog to get the actual offset in the position plugin
var isVisible = this.uiDialog.is(":visible");
if ( !isVisible ) {
this.uiDialog.show();
}
this.uiDialog.position( this.options.position );
if ( !isVisible ) {
this.uiDialog.hide();
}
},
_setOptions: function( options ) {
var that = this,
resize = false,
resizableOptions = {};
$.each( options, function( key, value ) {
that._setOption( key, value );
if ( key in sizeRelatedOptions ) {
resize = true;
}
if ( key in resizableRelatedOptions ) {
resizableOptions[ key ] = value;
}
});
if ( resize ) {
this._size();
this._position();
}
if ( this.uiDialog.is(":data(ui-resizable)") ) {
this.uiDialog.resizable( "option", resizableOptions );
}
},
_setOption: function( key, value ) {
/*jshint maxcomplexity:15*/
var isDraggable, isResizable,
uiDialog = this.uiDialog;
if ( key === "dialogClass" ) {
uiDialog
.removeClass( this.options.dialogClass )
.addClass( value );
}
if ( key === "disabled" ) {
return;
}
this._super( key, value );
if ( key === "appendTo" ) {
this.uiDialog.appendTo( this._appendTo() );
}
if ( key === "buttons" ) {
this._createButtons();
}
if ( key === "closeText" ) {
this.uiDialogTitlebarClose.button({
// Ensure that we always pass a string
label: "" + value
});
}
if ( key === "draggable" ) {
isDraggable = uiDialog.is(":data(ui-draggable)");
if ( isDraggable && !value ) {
uiDialog.draggable("destroy");
}
if ( !isDraggable && value ) {
this._makeDraggable();
}
}
if ( key === "position" ) {
this._position();
}
if ( key === "resizable" ) {
// currently resizable, becoming non-resizable
isResizable = uiDialog.is(":data(ui-resizable)");
if ( isResizable && !value ) {
uiDialog.resizable("destroy");
}
// currently resizable, changing handles
if ( isResizable && typeof value === "string" ) {
uiDialog.resizable( "option", "handles", value );
}
// currently non-resizable, becoming resizable
if ( !isResizable && value !== false ) {
this._makeResizable();
}
}
if ( key === "title" ) {
this._title( this.uiDialogTitlebar.find(".ui-dialog-title") );
}
},
_size: function() {
// If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
// divs will both have width and height set, so we need to reset them
var nonContentHeight, minContentHeight, maxContentHeight,
options = this.options;
// Reset content sizing
this.element.show().css({
width: "auto",
minHeight: 0,
maxHeight: "none",
height: 0
});
if ( options.minWidth > options.width ) {
options.width = options.minWidth;
}
// reset wrapper sizing
// determine the height of all the non-content elements
nonContentHeight = this.uiDialog.css({
height: "auto",
width: options.width
})
.outerHeight();
minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
maxContentHeight = typeof options.maxHeight === "number" ?
Math.max( 0, options.maxHeight - nonContentHeight ) :
"none";
if ( options.height === "auto" ) {
this.element.css({
minHeight: minContentHeight,
maxHeight: maxContentHeight,
height: "auto"
});
} else {
this.element.height( Math.max( 0, options.height - nonContentHeight ) );
}
if (this.uiDialog.is(":data(ui-resizable)") ) {
this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
}
},
_blockFrames: function() {
this.iframeBlocks = this.document.find( "iframe" ).map(function() {
var iframe = $( this );
return $( "<div>" )
.css({
position: "absolute",
width: iframe.outerWidth(),
height: iframe.outerHeight()
})
.appendTo( iframe.parent() )
.offset( iframe.offset() )[0];
});
},
_unblockFrames: function() {
if ( this.iframeBlocks ) {
this.iframeBlocks.remove();
delete this.iframeBlocks;
}
},
_allowInteraction: function( event ) {
if ( $( event.target ).closest(".ui-dialog").length ) {
return true;
}
// TODO: Remove hack when datepicker implements
// the .ui-front logic (#8989)
return !!$( event.target ).closest(".ui-datepicker").length;
},
_createOverlay: function() {
if ( !this.options.modal ) {
return;
}
var that = this,
widgetFullName = this.widgetFullName;
if ( !$.ui.dialog.overlayInstances ) {
// Prevent use of anchors and inputs.
// We use a delay in case the overlay is created from an
// event that we're going to be cancelling. (#2804)
this._delay(function() {
// Handle .dialog().dialog("close") (#4065)
if ( $.ui.dialog.overlayInstances ) {
this.document.bind( "focusin.dialog", function( event ) {
if ( !that._allowInteraction( event ) ) {
event.preventDefault();
$(".ui-dialog:visible:last .ui-dialog-content")
.data( widgetFullName )._focusTabbable();
}
});
}
});
}
this.overlay = $("<div>")
.addClass("ui-widget-overlay ui-front")
.appendTo( this._appendTo() );
this._on( this.overlay, {
mousedown: "_keepFocus"
});
$.ui.dialog.overlayInstances++;
},
_destroyOverlay: function() {
if ( !this.options.modal ) {
return;
}
if ( this.overlay ) {
$.ui.dialog.overlayInstances--;
if ( !$.ui.dialog.overlayInstances ) {
this.document.unbind( "focusin.dialog" );
}
this.overlay.remove();
this.overlay = null;
}
}
});
$.ui.dialog.overlayInstances = 0;
// DEPRECATED
if ( $.uiBackCompat !== false ) {
// position option with array notation
// just override with old implementation
$.widget( "ui.dialog", $.ui.dialog, {
_position: function() {
var position = this.options.position,
myAt = [],
offset = [ 0, 0 ],
isVisible;
if ( position ) {
if ( typeof position === "string" || (typeof position === "object" && "0" in position ) ) {
myAt = position.split ? position.split(" ") : [ position[0], position[1] ];
if ( myAt.length === 1 ) {
myAt[1] = myAt[0];
}
$.each( [ "left", "top" ], function( i, offsetPosition ) {
if ( +myAt[ i ] === myAt[ i ] ) {
offset[ i ] = myAt[ i ];
myAt[ i ] = offsetPosition;
}
});
position = {
my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " +
myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]),
at: myAt.join(" ")
};
}
position = $.extend( {}, $.ui.dialog.prototype.options.position, position );
} else {
position = $.ui.dialog.prototype.options.position;
}
// need to show the dialog to get the actual offset in the position plugin
isVisible = this.uiDialog.is(":visible");
if ( !isVisible ) {
this.uiDialog.show();
}
this.uiDialog.position( position );
if ( !isVisible ) {
this.uiDialog.hide();
}
}
});
}
}( jQuery ) );
(function( $, undefined ) {
$.widget("ui.draggable", $.ui.mouse, {
version: "1.10.2",
widgetEventPrefix: "drag",
options: {
addClasses: true,
appendTo: "parent",
axis: false,
connectToSortable: false,
containment: false,
cursor: "auto",
cursorAt: false,
grid: false,
handle: false,
helper: "original",
iframeFix: false,
opacity: false,
refreshPositions: false,
revert: false,
revertDuration: 500,
scope: "default",
scroll: true,
scrollSensitivity: 20,
scrollSpeed: 20,
snap: false,
snapMode: "both",
snapTolerance: 20,
stack: false,
zIndex: false,
// callbacks
drag: null,
start: null,
stop: null
},
_create: function() {
if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) {
this.element[0].style.position = "relative";
}
if (this.options.addClasses){
this.element.addClass("ui-draggable");
}
if (this.options.disabled){
this.element.addClass("ui-draggable-disabled");
}
this._mouseInit();
},
_destroy: function() {
this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
this._mouseDestroy();
},
_mouseCapture: function(event) {
var o = this.options;
// among others, prevent a drag on a resizable-handle
if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
return false;
}
//Quit if we're not on a valid handle
this.handle = this._getHandle(event);
if (!this.handle) {
return false;
}
$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
$("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>")
.css({
width: this.offsetWidth+"px", height: this.offsetHeight+"px",
position: "absolute", opacity: "0.001", zIndex: 1000
})
.css($(this).offset())
.appendTo("body");
});
return true;
},
_mouseStart: function(event) {
var o = this.options;
//Create and append the visible helper
this.helper = this._createHelper(event);
this.helper.addClass("ui-draggable-dragging");
//Cache the helper size
this._cacheHelperProportions();
//If ddmanager is used for droppables, set the global draggable
if($.ui.ddmanager) {
$.ui.ddmanager.current = this;
}
/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/
//Cache the margins of the original element
this._cacheMargins();
//Store the helper's css position
this.cssPosition = this.helper.css("position");
this.scrollParent = this.helper.scrollParent();
//The element's absolute position on the page minus margins
this.offset = this.positionAbs = this.element.offset();
this.offset = {
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};
$.extend(this.offset, {
click: { //Where the click happened, relative to the element
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
},
parent: this._getParentOffset(),
relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
});
//Generate the original position
this.originalPosition = this.position = this._generatePosition(event);
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;
//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
//Set a containment if given in the options
if(o.containment) {
this._setContainment();
}
//Trigger event + callbacks
if(this._trigger("start", event) === false) {
this._clear();
return false;
}
//Recache the helper size
this._cacheHelperProportions();
//Prepare the droppable offsets
if ($.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(this, event);
}
this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
//If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
if ( $.ui.ddmanager ) {
$.ui.ddmanager.dragStart(this, event);
}
return true;
},
_mouseDrag: function(event, noPropagation) {
//Compute the helpers position
this.position = this._generatePosition(event);
this.positionAbs = this._convertPositionTo("absolute");
//Call plugins and callbacks and use the resulting position if something is returned
if (!noPropagation) {
var ui = this._uiHash();
if(this._trigger("drag", event, ui) === false) {
this._mouseUp({});
return false;
}
this.position = ui.position;
}
if(!this.options.axis || this.options.axis !== "y") {
this.helper[0].style.left = this.position.left+"px";
}
if(!this.options.axis || this.options.axis !== "x") {
this.helper[0].style.top = this.position.top+"px";
}
if($.ui.ddmanager) {
$.ui.ddmanager.drag(this, event);
}
return false;
},
_mouseStop: function(event) {
//If we are using droppables, inform the manager about the drop
var element,
that = this,
elementInDom = false,
dropped = false;
if ($.ui.ddmanager && !this.options.dropBehaviour) {
dropped = $.ui.ddmanager.drop(this, event);
}
//if a drop comes from outside (a sortable)
if(this.dropped) {
dropped = this.dropped;
this.dropped = false;
}
//if the original element is no longer in the DOM don't bother to continue (see #8269)
element = this.element[0];
while ( element && (element = element.parentNode) ) {
if (element === document ) {
elementInDom = true;
}
}
if ( !elementInDom && this.options.helper === "original" ) {
return false;
}
if((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
if(that._trigger("stop", event) !== false) {
that._clear();
}
});
} else {
if(this._trigger("stop", event) !== false) {
this._clear();
}
}
return false;
},
_mouseUp: function(event) {
//Remove frame helpers
$("div.ui-draggable-iframeFix").each(function() {
this.parentNode.removeChild(this);
});
//If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
if( $.ui.ddmanager ) {
$.ui.ddmanager.dragStop(this, event);
}
return $.ui.mouse.prototype._mouseUp.call(this, event);
},
cancel: function() {
if(this.helper.is(".ui-draggable-dragging")) {
this._mouseUp({});
} else {
this._clear();
}
return this;
},
_getHandle: function(event) {
return this.options.handle ?
!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
true;
},
_createHelper: function(event) {
var o = this.options,
helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element);
if(!helper.parents("body").length) {
helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
}
if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
helper.css("position", "absolute");
}
return helper;
},
_adjustOffsetFromHelper: function(obj) {
if (typeof obj === "string") {
obj = obj.split(" ");
}
if ($.isArray(obj)) {
obj = {left: +obj[0], top: +obj[1] || 0};
}
if ("left" in obj) {
this.offset.click.left = obj.left + this.margins.left;
}
if ("right" in obj) {
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
}
if ("top" in obj) {
this.offset.click.top = obj.top + this.margins.top;
}
if ("bottom" in obj) {
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
}
},
_getParentOffset: function() {
//Get the offsetParent and cache its position
this.offsetParent = this.helper.offsetParent();
var po = this.offsetParent.offset();
// This is a special case where we need to modify a offset calculated on start, since the following happened:
// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
// the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
po.left += this.scrollParent.scrollLeft();
po.top += this.scrollParent.scrollTop();
}
//This needs to be actually done for all browsers, since pageX/pageY includes this information
//Ugly IE fix
if((this.offsetParent[0] === document.body) ||
(this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
po = { top: 0, left: 0 };
}
return {
top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
};
},
_getRelativeOffset: function() {
if(this.cssPosition === "relative") {
var p = this.element.position();
return {
top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
};
} else {
return { top: 0, left: 0 };
}
},
_cacheMargins: function() {
this.margins = {
left: (parseInt(this.element.css("marginLeft"),10) || 0),
top: (parseInt(this.element.css("marginTop"),10) || 0),
right: (parseInt(this.element.css("marginRight"),10) || 0),
bottom: (parseInt(this.element.css("marginBottom"),10) || 0)
};
},
_cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},
_setContainment: function() {
var over, c, ce,
o = this.options;
if(o.containment === "parent") {
o.containment = this.helper[0].parentNode;
}
if(o.containment === "document" || o.containment === "window") {
this.containment = [
o.containment === "document" ? 0 : $(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
o.containment === "document" ? 0 : $(window).scrollTop() - this.offset.relative.top - this.offset.parent.top,
(o.containment === "document" ? 0 : $(window).scrollLeft()) + $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
(o.containment === "document" ? 0 : $(window).scrollTop()) + ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
];
}
if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor !== Array) {
c = $(o.containment);
ce = c[0];
if(!ce) {
return;
}
over = ($(ce).css("overflow") !== "hidden");
this.containment = [
(parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0),
(parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0),
(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderRightWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left - this.margins.right,
(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderBottomWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top - this.margins.bottom
];
this.relative_container = c;
} else if(o.containment.constructor === Array) {
this.containment = o.containment;
}
},
_convertPositionTo: function(d, pos) {
if(!pos) {
pos = this.position;
}
var mod = d === "absolute" ? 1 : -1,
scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
return {
top: (
pos.top + // The absolute mouse position
this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
),
left: (
pos.left + // The absolute mouse position
this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
)
};
},
_generatePosition: function(event) {
var containment, co, top, left,
o = this.options,
scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName),
pageX = event.pageX,
pageY = event.pageY;
/*
* - Position constraining -
* Constrain the position to a mix of grid, containment.
*/
if(this.originalPosition) { //If we are not dragging yet, we won't check for options
if(this.containment) {
if (this.relative_container){
co = this.relative_container.offset();
containment = [ this.containment[0] + co.left,
this.containment[1] + co.top,
this.containment[2] + co.left,
this.containment[3] + co.top ];
}
else {
containment = this.containment;
}
if(event.pageX - this.offset.click.left < containment[0]) {
pageX = containment[0] + this.offset.click.left;
}
if(event.pageY - this.offset.click.top < containment[1]) {
pageY = containment[1] + this.offset.click.top;
}
if(event.pageX - this.offset.click.left > containment[2]) {
pageX = containment[2] + this.offset.click.left;
}
if(event.pageY - this.offset.click.top > containment[3]) {
pageY = containment[3] + this.offset.click.top;
}
}
if(o.grid) {
//Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
}
}
return {
top: (
pageY - // The absolute mouse position
this.offset.click.top - // Click offset (relative to the element)
this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
),
left: (
pageX - // The absolute mouse position
this.offset.click.left - // Click offset (relative to the element)
this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
)
};
},
_clear: function() {
this.helper.removeClass("ui-draggable-dragging");
if(this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
this.helper.remove();
}
this.helper = null;
this.cancelHelperRemoval = false;
},
// From now on bulk stuff - mainly helpers
_trigger: function(type, event, ui) {
ui = ui || this._uiHash();
$.ui.plugin.call(this, type, [event, ui]);
//The absolute position has to be recalculated after plugins
if(type === "drag") {
this.positionAbs = this._convertPositionTo("absolute");
}
return $.Widget.prototype._trigger.call(this, type, event, ui);
},
plugins: {},
_uiHash: function() {
return {
helper: this.helper,
position: this.position,
originalPosition: this.originalPosition,
offset: this.positionAbs
};
}
});
$.ui.plugin.add("draggable", "connectToSortable", {
start: function(event, ui) {
var inst = $(this).data("ui-draggable"), o = inst.options,
uiSortable = $.extend({}, ui, { item: inst.element });
inst.sortables = [];
$(o.connectToSortable).each(function() {
var sortable = $.data(this, "ui-sortable");
if (sortable && !sortable.options.disabled) {
inst.sortables.push({
instance: sortable,
shouldRevert: sortable.options.revert
});
sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
sortable._trigger("activate", event, uiSortable);
}
});
},
stop: function(event, ui) {
//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
var inst = $(this).data("ui-draggable"),
uiSortable = $.extend({}, ui, { item: inst.element });
$.each(inst.sortables, function() {
if(this.instance.isOver) {
this.instance.isOver = 0;
inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid"
if(this.shouldRevert) {
this.instance.options.revert = this.shouldRevert;
}
//Trigger the stop of the sortable
this.instance._mouseStop(event);
this.instance.options.helper = this.instance.options._helper;
//If the helper has been the original item, restore properties in the sortable
if(inst.options.helper === "original") {
this.instance.currentItem.css({ top: "auto", left: "auto" });
}
} else {
this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
this.instance._trigger("deactivate", event, uiSortable);
}
});
},
drag: function(event, ui) {
var inst = $(this).data("ui-draggable"), that = this;
$.each(inst.sortables, function() {
var innermostIntersecting = false,
thisSortable = this;
//Copy over some variables to allow calling the sortable's native _intersectsWith
this.instance.positionAbs = inst.positionAbs;
this.instance.helperProportions = inst.helperProportions;
this.instance.offset.click = inst.offset.click;
if(this.instance._intersectsWith(this.instance.containerCache)) {
innermostIntersecting = true;
$.each(inst.sortables, function () {
this.instance.positionAbs = inst.positionAbs;
this.instance.helperProportions = inst.helperProportions;
this.instance.offset.click = inst.offset.click;
if (this !== thisSortable &&
this.instance._intersectsWith(this.instance.containerCache) &&
$.contains(thisSortable.instance.element[0], this.instance.element[0])
) {
innermostIntersecting = false;
}
return innermostIntersecting;
});
}
if(innermostIntersecting) {
//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
if(!this.instance.isOver) {
this.instance.isOver = 1;
//Now we fake the start of dragging for the sortable instance,
//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true);
this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
this.instance.options.helper = function() { return ui.helper[0]; };
event.target = this.instance.currentItem[0];
this.instance._mouseCapture(event, true);
this.instance._mouseStart(event, true, true);
//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
this.instance.offset.click.top = inst.offset.click.top;
this.instance.offset.click.left = inst.offset.click.left;
this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
inst._trigger("toSortable", event);
inst.dropped = this.instance.element; //draggable revert needs that
//hack so receive/update callbacks work (mostly)
inst.currentItem = inst.element;
this.instance.fromOutside = inst;
}
//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
if(this.instance.currentItem) {
this.instance._mouseDrag(event);
}
} else {
//If it doesn't intersect with the sortable, and it intersected before,
//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
if(this.instance.isOver) {
this.instance.isOver = 0;
this.instance.cancelHelperRemoval = true;
//Prevent reverting on this forced stop
this.instance.options.revert = false;
// The out event needs to be triggered independently
this.instance._trigger("out", event, this.instance._uiHash(this.instance));
this.instance._mouseStop(event, true);
this.instance.options.helper = this.instance.options._helper;
//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
this.instance.currentItem.remove();
if(this.instance.placeholder) {
this.instance.placeholder.remove();
}
inst._trigger("fromSortable", event);
inst.dropped = false; //draggable revert needs that
}
}
});
}
});
$.ui.plugin.add("draggable", "cursor", {
start: function() {
var t = $("body"), o = $(this).data("ui-draggable").options;
if (t.css("cursor")) {
o._cursor = t.css("cursor");
}
t.css("cursor", o.cursor);
},
stop: function() {
var o = $(this).data("ui-draggable").options;
if (o._cursor) {
$("body").css("cursor", o._cursor);
}
}
});
$.ui.plugin.add("draggable", "opacity", {
start: function(event, ui) {
var t = $(ui.helper), o = $(this).data("ui-draggable").options;
if(t.css("opacity")) {
o._opacity = t.css("opacity");
}
t.css("opacity", o.opacity);
},
stop: function(event, ui) {
var o = $(this).data("ui-draggable").options;
if(o._opacity) {
$(ui.helper).css("opacity", o._opacity);
}
}
});
$.ui.plugin.add("draggable", "scroll", {
start: function() {
var i = $(this).data("ui-draggable");
if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
i.overflowOffset = i.scrollParent.offset();
}
},
drag: function( event ) {
var i = $(this).data("ui-draggable"), o = i.options, scrolled = false;
if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
if(!o.axis || o.axis !== "x") {
if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
} else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) {
i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
}
}
if(!o.axis || o.axis !== "y") {
if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
} else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) {
i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
}
}
} else {
if(!o.axis || o.axis !== "x") {
if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
} else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
}
}
if(!o.axis || o.axis !== "y") {
if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
} else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
}
}
}
if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(i, event);
}
}
});
$.ui.plugin.add("draggable", "snap", {
start: function() {
var i = $(this).data("ui-draggable"),
o = i.options;
i.snapElements = [];
$(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() {
var $t = $(this),
$o = $t.offset();
if(this !== i.element[0]) {
i.snapElements.push({
item: this,
width: $t.outerWidth(), height: $t.outerHeight(),
top: $o.top, left: $o.left
});
}
});
},
drag: function(event, ui) {
var ts, bs, ls, rs, l, r, t, b, i, first,
inst = $(this).data("ui-draggable"),
o = inst.options,
d = o.snapTolerance,
x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
for (i = inst.snapElements.length - 1; i >= 0; i--){
l = inst.snapElements[i].left;
r = l + inst.snapElements[i].width;
t = inst.snapElements[i].top;
b = t + inst.snapElements[i].height;
//Yes, I know, this is insane ;)
if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
if(inst.snapElements[i].snapping) {
(inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
}
inst.snapElements[i].snapping = false;
continue;
}
if(o.snapMode !== "inner") {
ts = Math.abs(t - y2) <= d;
bs = Math.abs(b - y1) <= d;
ls = Math.abs(l - x2) <= d;
rs = Math.abs(r - x1) <= d;
if(ts) {
ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
}
if(bs) {
ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
}
if(ls) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
}
if(rs) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
}
}
first = (ts || bs || ls || rs);
if(o.snapMode !== "outer") {
ts = Math.abs(t - y1) <= d;
bs = Math.abs(b - y2) <= d;
ls = Math.abs(l - x1) <= d;
rs = Math.abs(r - x2) <= d;
if(ts) {
ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
}
if(bs) {
ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
}
if(ls) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
}
if(rs) {
ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
}
}
if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
}
inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
}
}
});
$.ui.plugin.add("draggable", "stack", {
start: function() {
var min,
o = this.data("ui-draggable").options,
group = $.makeArray($(o.stack)).sort(function(a,b) {
return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0);
});
if (!group.length) { return; }
min = parseInt($(group[0]).css("zIndex"), 10) || 0;
$(group).each(function(i) {
$(this).css("zIndex", min + i);
});
this.css("zIndex", (min + group.length));
}
});
$.ui.plugin.add("draggable", "zIndex", {
start: function(event, ui) {
var t = $(ui.helper), o = $(this).data("ui-draggable").options;
if(t.css("zIndex")) {
o._zIndex = t.css("zIndex");
}
t.css("zIndex", o.zIndex);
},
stop: function(event, ui) {
var o = $(this).data("ui-draggable").options;
if(o._zIndex) {
$(ui.helper).css("zIndex", o._zIndex);
}
}
});
})(jQuery);
(function( $, undefined ) {
function isOverAxis( x, reference, size ) {
return ( x > reference ) && ( x < ( reference + size ) );
}
$.widget("ui.droppable", {
version: "1.10.2",
widgetEventPrefix: "drop",
options: {
accept: "*",
activeClass: false,
addClasses: true,
greedy: false,
hoverClass: false,
scope: "default",
tolerance: "intersect",
// callbacks
activate: null,
deactivate: null,
drop: null,
out: null,
over: null
},
_create: function() {
var o = this.options,
accept = o.accept;
this.isover = false;
this.isout = true;
this.accept = $.isFunction(accept) ? accept : function(d) {
return d.is(accept);
};
//Store the droppable's proportions
this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };
// Add the reference and positions to the manager
$.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || [];
$.ui.ddmanager.droppables[o.scope].push(this);
(o.addClasses && this.element.addClass("ui-droppable"));
},
_destroy: function() {
var i = 0,
drop = $.ui.ddmanager.droppables[this.options.scope];
for ( ; i < drop.length; i++ ) {
if ( drop[i] === this ) {
drop.splice(i, 1);
}
}
this.element.removeClass("ui-droppable ui-droppable-disabled");
},
_setOption: function(key, value) {
if(key === "accept") {
this.accept = $.isFunction(value) ? value : function(d) {
return d.is(value);
};
}
$.Widget.prototype._setOption.apply(this, arguments);
},
_activate: function(event) {
var draggable = $.ui.ddmanager.current;
if(this.options.activeClass) {
this.element.addClass(this.options.activeClass);
}
if(draggable){
this._trigger("activate", event, this.ui(draggable));
}
},
_deactivate: function(event) {
var draggable = $.ui.ddmanager.current;
if(this.options.activeClass) {
this.element.removeClass(this.options.activeClass);
}
if(draggable){
this._trigger("deactivate", event, this.ui(draggable));
}
},
_over: function(event) {
var draggable = $.ui.ddmanager.current;
// Bail if draggable and droppable are same element
if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
return;
}
if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
if(this.options.hoverClass) {
this.element.addClass(this.options.hoverClass);
}
this._trigger("over", event, this.ui(draggable));
}
},
_out: function(event) {
var draggable = $.ui.ddmanager.current;
// Bail if draggable and droppable are same element
if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
return;
}
if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
if(this.options.hoverClass) {
this.element.removeClass(this.options.hoverClass);
}
this._trigger("out", event, this.ui(draggable));
}
},
_drop: function(event,custom) {
var draggable = custom || $.ui.ddmanager.current,
childrenIntersection = false;
// Bail if draggable and droppable are same element
if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
return false;
}
this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function() {
var inst = $.data(this, "ui-droppable");
if(
inst.options.greedy &&
!inst.options.disabled &&
inst.options.scope === draggable.options.scope &&
inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) &&
$.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)
) { childrenIntersection = true; return false; }
});
if(childrenIntersection) {
return false;
}
if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
if(this.options.activeClass) {
this.element.removeClass(this.options.activeClass);
}
if(this.options.hoverClass) {
this.element.removeClass(this.options.hoverClass);
}
this._trigger("drop", event, this.ui(draggable));
return this.element;
}
return false;
},
ui: function(c) {
return {
draggable: (c.currentItem || c.element),
helper: c.helper,
position: c.position,
offset: c.positionAbs
};
}
});
$.ui.intersect = function(draggable, droppable, toleranceMode) {
if (!droppable.offset) {
return false;
}
var draggableLeft, draggableTop,
x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height,
l = droppable.offset.left, r = l + droppable.proportions.width,
t = droppable.offset.top, b = t + droppable.proportions.height;
switch (toleranceMode) {
case "fit":
return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
case "intersect":
return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
x2 - (draggable.helperProportions.width / 2) < r && // Left Half
t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half
y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
case "pointer":
draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left);
draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top);
return isOverAxis( draggableTop, t, droppable.proportions.height ) && isOverAxis( draggableLeft, l, droppable.proportions.width );
case "touch":
return (
(y1 >= t && y1 <= b) || // Top edge touching
(y2 >= t && y2 <= b) || // Bottom edge touching
(y1 < t && y2 > b) // Surrounded vertically
) && (
(x1 >= l && x1 <= r) || // Left edge touching
(x2 >= l && x2 <= r) || // Right edge touching
(x1 < l && x2 > r) // Surrounded horizontally
);
default:
return false;
}
};
/*
This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
current: null,
droppables: { "default": [] },
prepareOffsets: function(t, event) {
var i, j,
m = $.ui.ddmanager.droppables[t.options.scope] || [],
type = event ? event.type : null, // workaround for #2317
list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack();
droppablesLoop: for (i = 0; i < m.length; i++) {
//No disabled and non-accepted
if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) {
continue;
}
// Filter out elements in the current dragged item
for (j=0; j < list.length; j++) {
if(list[j] === m[i].element[0]) {
m[i].proportions.height = 0;
continue droppablesLoop;
}
}
m[i].visible = m[i].element.css("display") !== "none";
if(!m[i].visible) {
continue;
}
//Activate the droppable if used directly from draggables
if(type === "mousedown") {
m[i]._activate.call(m[i], event);
}
m[i].offset = m[i].element.offset();
m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight };
}
},
drop: function(draggable, event) {
var dropped = false;
// Create a copy of the droppables in case the list changes during the drop (#9116)
$.each(($.ui.ddmanager.droppables[draggable.options.scope] || []).slice(), function() {
if(!this.options) {
return;
}
if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) {
dropped = this._drop.call(this, event) || dropped;
}
if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
this.isout = true;
this.isover = false;
this._deactivate.call(this, event);
}
});
return dropped;
},
dragStart: function( draggable, event ) {
//Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() {
if( !draggable.options.refreshPositions ) {
$.ui.ddmanager.prepareOffsets( draggable, event );
}
});
},
drag: function(draggable, event) {
//If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
if(draggable.options.refreshPositions) {
$.ui.ddmanager.prepareOffsets(draggable, event);
}
//Run through all droppables and check their positions based on specific tolerance options
$.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {
if(this.options.disabled || this.greedyChild || !this.visible) {
return;
}
var parentInstance, scope, parent,
intersects = $.ui.intersect(draggable, this, this.options.tolerance),
c = !intersects && this.isover ? "isout" : (intersects && !this.isover ? "isover" : null);
if(!c) {
return;
}
if (this.options.greedy) {
// find droppable parents with same scope
scope = this.options.scope;
parent = this.element.parents(":data(ui-droppable)").filter(function () {
return $.data(this, "ui-droppable").options.scope === scope;
});
if (parent.length) {
parentInstance = $.data(parent[0], "ui-droppable");
parentInstance.greedyChild = (c === "isover");
}
}
// we just moved into a greedy child
if (parentInstance && c === "isover") {
parentInstance.isover = false;
parentInstance.isout = true;
parentInstance._out.call(parentInstance, event);
}
this[c] = true;
this[c === "isout" ? "isover" : "isout"] = false;
this[c === "isover" ? "_over" : "_out"].call(this, event);
// we just moved out of a greedy child
if (parentInstance && c === "isout") {
parentInstance.isout = false;
parentInstance.isover = true;
parentInstance._over.call(parentInstance, event);
}
});
},
dragStop: function( draggable, event ) {
draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" );
//Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
if( !draggable.options.refreshPositions ) {
$.ui.ddmanager.prepareOffsets( draggable, event );
}
}
};
})(jQuery);
(function($, undefined) {
var dataSpace = "ui-effects-";
$.effects = {
effect: {}
};
/*!
* jQuery Color Animations v2.1.2
* https://github.com/jquery/jquery-color
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* Date: Wed Jan 16 08:47:09 2013 -0600
*/
(function( jQuery, undefined ) {
var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",
// plusequals test for += 100 -= 100
rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
// a set of RE's that can match strings and generate color tuples.
stringParsers = [{
re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
parse: function( execResult ) {
return [
execResult[ 1 ],
execResult[ 2 ],
execResult[ 3 ],
execResult[ 4 ]
];
}
}, {
re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
parse: function( execResult ) {
return [
execResult[ 1 ] * 2.55,
execResult[ 2 ] * 2.55,
execResult[ 3 ] * 2.55,
execResult[ 4 ]
];
}
}, {
// this regex ignores A-F because it's compared against an already lowercased string
re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
parse: function( execResult ) {
return [
parseInt( execResult[ 1 ], 16 ),
parseInt( execResult[ 2 ], 16 ),
parseInt( execResult[ 3 ], 16 )
];
}
}, {
// this regex ignores A-F because it's compared against an already lowercased string
re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
parse: function( execResult ) {
return [
parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
];
}
}, {
re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
space: "hsla",
parse: function( execResult ) {
return [
execResult[ 1 ],
execResult[ 2 ] / 100,
execResult[ 3 ] / 100,
execResult[ 4 ]
];
}
}],
// jQuery.Color( )
color = jQuery.Color = function( color, green, blue, alpha ) {
return new jQuery.Color.fn.parse( color, green, blue, alpha );
},
spaces = {
rgba: {
props: {
red: {
idx: 0,
type: "byte"
},
green: {
idx: 1,
type: "byte"
},
blue: {
idx: 2,
type: "byte"
}
}
},
hsla: {
props: {
hue: {
idx: 0,
type: "degrees"
},
saturation: {
idx: 1,
type: "percent"
},
lightness: {
idx: 2,
type: "percent"
}
}
}
},
propTypes = {
"byte": {
floor: true,
max: 255
},
"percent": {
max: 1
},
"degrees": {
mod: 360,
floor: true
}
},
support = color.support = {},
// element for support tests
supportElem = jQuery( "<p>" )[ 0 ],
// colors = jQuery.Color.names
colors,
// local aliases of functions called often
each = jQuery.each;
// determine rgba support immediately
supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;
// define cache name and alpha properties
// for rgba and hsla spaces
each( spaces, function( spaceName, space ) {
space.cache = "_" + spaceName;
space.props.alpha = {
idx: 3,
type: "percent",
def: 1
};
});
function clamp( value, prop, allowEmpty ) {
var type = propTypes[ prop.type ] || {};
if ( value == null ) {
return (allowEmpty || !prop.def) ? null : prop.def;
}
// ~~ is an short way of doing floor for positive numbers
value = type.floor ? ~~value : parseFloat( value );
// IE will pass in empty strings as value for alpha,
// which will hit this case
if ( isNaN( value ) ) {
return prop.def;
}
if ( type.mod ) {
// we add mod before modding to make sure that negatives values
// get converted properly: -10 -> 350
return (value + type.mod) % type.mod;
}
// for now all property types without mod have min and max
return 0 > value ? 0 : type.max < value ? type.max : value;
}
function stringParse( string ) {
var inst = color(),
rgba = inst._rgba = [];
string = string.toLowerCase();
each( stringParsers, function( i, parser ) {
var parsed,
match = parser.re.exec( string ),
values = match && parser.parse( match ),
spaceName = parser.space || "rgba";
if ( values ) {
parsed = inst[ spaceName ]( values );
// if this was an rgba parse the assignment might happen twice
// oh well....
inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
rgba = inst._rgba = parsed._rgba;
// exit each( stringParsers ) here because we matched
return false;
}
});
// Found a stringParser that handled it
if ( rgba.length ) {
// if this came from a parsed string, force "transparent" when alpha is 0
// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
if ( rgba.join() === "0,0,0,0" ) {
jQuery.extend( rgba, colors.transparent );
}
return inst;
}
// named colors
return colors[ string ];
}
color.fn = jQuery.extend( color.prototype, {
parse: function( red, green, blue, alpha ) {
if ( red === undefined ) {
this._rgba = [ null, null, null, null ];
return this;
}
if ( red.jquery || red.nodeType ) {
red = jQuery( red ).css( green );
green = undefined;
}
var inst = this,
type = jQuery.type( red ),
rgba = this._rgba = [];
// more than 1 argument specified - assume ( red, green, blue, alpha )
if ( green !== undefined ) {
red = [ red, green, blue, alpha ];
type = "array";
}
if ( type === "string" ) {
return this.parse( stringParse( red ) || colors._default );
}
if ( type === "array" ) {
each( spaces.rgba.props, function( key, prop ) {
rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
});
return this;
}
if ( type === "object" ) {
if ( red instanceof color ) {
each( spaces, function( spaceName, space ) {
if ( red[ space.cache ] ) {
inst[ space.cache ] = red[ space.cache ].slice();
}
});
} else {
each( spaces, function( spaceName, space ) {
var cache = space.cache;
each( space.props, function( key, prop ) {
// if the cache doesn't exist, and we know how to convert
if ( !inst[ cache ] && space.to ) {
// if the value was null, we don't need to copy it
// if the key was alpha, we don't need to copy it either
if ( key === "alpha" || red[ key ] == null ) {
return;
}
inst[ cache ] = space.to( inst._rgba );
}
// this is the only case where we allow nulls for ALL properties.
// call clamp with alwaysAllowEmpty
inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
});
// everything defined but alpha?
if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
// use the default of 1
inst[ cache ][ 3 ] = 1;
if ( space.from ) {
inst._rgba = space.from( inst[ cache ] );
}
}
});
}
return this;
}
},
is: function( compare ) {
var is = color( compare ),
same = true,
inst = this;
each( spaces, function( _, space ) {
var localCache,
isCache = is[ space.cache ];
if (isCache) {
localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
each( space.props, function( _, prop ) {
if ( isCache[ prop.idx ] != null ) {
same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
return same;
}
});
}
return same;
});
return same;
},
_space: function() {
var used = [],
inst = this;
each( spaces, function( spaceName, space ) {
if ( inst[ space.cache ] ) {
used.push( spaceName );
}
});
return used.pop();
},
transition: function( other, distance ) {
var end = color( other ),
spaceName = end._space(),
space = spaces[ spaceName ],
startColor = this.alpha() === 0 ? color( "transparent" ) : this,
start = startColor[ space.cache ] || space.to( startColor._rgba ),
result = start.slice();
end = end[ space.cache ];
each( space.props, function( key, prop ) {
var index = prop.idx,
startValue = start[ index ],
endValue = end[ index ],
type = propTypes[ prop.type ] || {};
// if null, don't override start value
if ( endValue === null ) {
return;
}
// if null - use end
if ( startValue === null ) {
result[ index ] = endValue;
} else {
if ( type.mod ) {
if ( endValue - startValue > type.mod / 2 ) {
startValue += type.mod;
} else if ( startValue - endValue > type.mod / 2 ) {
startValue -= type.mod;
}
}
result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
}
});
return this[ spaceName ]( result );
},
blend: function( opaque ) {
// if we are already opaque - return ourself
if ( this._rgba[ 3 ] === 1 ) {
return this;
}
var rgb = this._rgba.slice(),
a = rgb.pop(),
blend = color( opaque )._rgba;
return color( jQuery.map( rgb, function( v, i ) {
return ( 1 - a ) * blend[ i ] + a * v;
}));
},
toRgbaString: function() {
var prefix = "rgba(",
rgba = jQuery.map( this._rgba, function( v, i ) {
return v == null ? ( i > 2 ? 1 : 0 ) : v;
});
if ( rgba[ 3 ] === 1 ) {
rgba.pop();
prefix = "rgb(";
}
return prefix + rgba.join() + ")";
},
toHslaString: function() {
var prefix = "hsla(",
hsla = jQuery.map( this.hsla(), function( v, i ) {
if ( v == null ) {
v = i > 2 ? 1 : 0;
}
// catch 1 and 2
if ( i && i < 3 ) {
v = Math.round( v * 100 ) + "%";
}
return v;
});
if ( hsla[ 3 ] === 1 ) {
hsla.pop();
prefix = "hsl(";
}
return prefix + hsla.join() + ")";
},
toHexString: function( includeAlpha ) {
var rgba = this._rgba.slice(),
alpha = rgba.pop();
if ( includeAlpha ) {
rgba.push( ~~( alpha * 255 ) );
}
return "#" + jQuery.map( rgba, function( v ) {
// default to 0 when nulls exist
v = ( v || 0 ).toString( 16 );
return v.length === 1 ? "0" + v : v;
}).join("");
},
toString: function() {
return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
}
});
color.fn.parse.prototype = color.fn;
// hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021
function hue2rgb( p, q, h ) {
h = ( h + 1 ) % 1;
if ( h * 6 < 1 ) {
return p + (q - p) * h * 6;
}
if ( h * 2 < 1) {
return q;
}
if ( h * 3 < 2 ) {
return p + (q - p) * ((2/3) - h) * 6;
}
return p;
}
spaces.hsla.to = function ( rgba ) {
if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
return [ null, null, null, rgba[ 3 ] ];
}
var r = rgba[ 0 ] / 255,
g = rgba[ 1 ] / 255,
b = rgba[ 2 ] / 255,
a = rgba[ 3 ],
max = Math.max( r, g, b ),
min = Math.min( r, g, b ),
diff = max - min,
add = max + min,
l = add * 0.5,
h, s;
if ( min === max ) {
h = 0;
} else if ( r === max ) {
h = ( 60 * ( g - b ) / diff ) + 360;
} else if ( g === max ) {
h = ( 60 * ( b - r ) / diff ) + 120;
} else {
h = ( 60 * ( r - g ) / diff ) + 240;
}
// chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
if ( diff === 0 ) {
s = 0;
} else if ( l <= 0.5 ) {
s = diff / add;
} else {
s = diff / ( 2 - add );
}
return [ Math.round(h) % 360, s, l, a == null ? 1 : a ];
};
spaces.hsla.from = function ( hsla ) {
if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
return [ null, null, null, hsla[ 3 ] ];
}
var h = hsla[ 0 ] / 360,
s = hsla[ 1 ],
l = hsla[ 2 ],
a = hsla[ 3 ],
q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
p = 2 * l - q;
return [
Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
Math.round( hue2rgb( p, q, h ) * 255 ),
Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
a
];
};
each( spaces, function( spaceName, space ) {
var props = space.props,
cache = space.cache,
to = space.to,
from = space.from;
// makes rgba() and hsla()
color.fn[ spaceName ] = function( value ) {
// generate a cache for this space if it doesn't exist
if ( to && !this[ cache ] ) {
this[ cache ] = to( this._rgba );
}
if ( value === undefined ) {
return this[ cache ].slice();
}
var ret,
type = jQuery.type( value ),
arr = ( type === "array" || type === "object" ) ? value : arguments,
local = this[ cache ].slice();
each( props, function( key, prop ) {
var val = arr[ type === "object" ? key : prop.idx ];
if ( val == null ) {
val = local[ prop.idx ];
}
local[ prop.idx ] = clamp( val, prop );
});
if ( from ) {
ret = color( from( local ) );
ret[ cache ] = local;
return ret;
} else {
return color( local );
}
};
// makes red() green() blue() alpha() hue() saturation() lightness()
each( props, function( key, prop ) {
// alpha is included in more than one space
if ( color.fn[ key ] ) {
return;
}
color.fn[ key ] = function( value ) {
var vtype = jQuery.type( value ),
fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
local = this[ fn ](),
cur = local[ prop.idx ],
match;
if ( vtype === "undefined" ) {
return cur;
}
if ( vtype === "function" ) {
value = value.call( this, cur );
vtype = jQuery.type( value );
}
if ( value == null && prop.empty ) {
return this;
}
if ( vtype === "string" ) {
match = rplusequals.exec( value );
if ( match ) {
value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
}
}
local[ prop.idx ] = value;
return this[ fn ]( local );
};
});
});
// add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
var hooks = hook.split( " " );
each( hooks, function( i, hook ) {
jQuery.cssHooks[ hook ] = {
set: function( elem, value ) {
var parsed, curElem,
backgroundColor = "";
if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) {
value = color( parsed || value );
if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
curElem = hook === "backgroundColor" ? elem.parentNode : elem;
while (
(backgroundColor === "" || backgroundColor === "transparent") &&
curElem && curElem.style
) {
try {
backgroundColor = jQuery.css( curElem, "backgroundColor" );
curElem = curElem.parentNode;
} catch ( e ) {
}
}
value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
backgroundColor :
"_default" );
}
value = value.toRgbaString();
}
try {
elem.style[ hook ] = value;
} catch( e ) {
// wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
}
}
};
jQuery.fx.step[ hook ] = function( fx ) {
if ( !fx.colorInit ) {
fx.start = color( fx.elem, hook );
fx.end = color( fx.end );
fx.colorInit = true;
}
jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
};
});
};
color.hook( stepHooks );
jQuery.cssHooks.borderColor = {
expand: function( value ) {
var expanded = {};
each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
expanded[ "border" + part + "Color" ] = value;
});
return expanded;
}
};
// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {
// 4.1. Basic color keywords
aqua: "#00ffff",
black: "#000000",
blue: "#0000ff",
fuchsia: "#ff00ff",
gray: "#808080",
green: "#008000",
lime: "#00ff00",
maroon: "#800000",
navy: "#000080",
olive: "#808000",
purple: "#800080",
red: "#ff0000",
silver: "#c0c0c0",
teal: "#008080",
white: "#ffffff",
yellow: "#ffff00",
// 4.2.3. "transparent" color keyword
transparent: [ null, null, null, 0 ],
_default: "#ffffff"
};
})( jQuery );
/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
(function() {
var classAnimationActions = [ "add", "remove", "toggle" ],
shorthandStyles = {
border: 1,
borderBottom: 1,
borderColor: 1,
borderLeft: 1,
borderRight: 1,
borderTop: 1,
borderWidth: 1,
margin: 1,
padding: 1
};
$.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) {
$.fx.step[ prop ] = function( fx ) {
if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
jQuery.style( fx.elem, prop, fx.end );
fx.setAttr = true;
}
};
});
function getElementStyles( elem ) {
var key, len,
style = elem.ownerDocument.defaultView ?
elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
elem.currentStyle,
styles = {};
if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
len = style.length;
while ( len-- ) {
key = style[ len ];
if ( typeof style[ key ] === "string" ) {
styles[ $.camelCase( key ) ] = style[ key ];
}
}
// support: Opera, IE <9
} else {
for ( key in style ) {
if ( typeof style[ key ] === "string" ) {
styles[ key ] = style[ key ];
}
}
}
return styles;
}
function styleDifference( oldStyle, newStyle ) {
var diff = {},
name, value;
for ( name in newStyle ) {
value = newStyle[ name ];
if ( oldStyle[ name ] !== value ) {
if ( !shorthandStyles[ name ] ) {
if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
diff[ name ] = value;
}
}
}
}
return diff;
}
// support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
$.effects.animateClass = function( value, duration, easing, callback ) {
var o = $.speed( duration, easing, callback );
return this.queue( function() {
var animated = $( this ),
baseClass = animated.attr( "class" ) || "",
applyClassChange,
allAnimations = o.children ? animated.find( "*" ).addBack() : animated;
// map the animated objects to store the original styles.
allAnimations = allAnimations.map(function() {
var el = $( this );
return {
el: el,
start: getElementStyles( this )
};
});
// apply class change
applyClassChange = function() {
$.each( classAnimationActions, function(i, action) {
if ( value[ action ] ) {
animated[ action + "Class" ]( value[ action ] );
}
});
};
applyClassChange();
// map all animated objects again - calculate new styles and diff
allAnimations = allAnimations.map(function() {
this.end = getElementStyles( this.el[ 0 ] );
this.diff = styleDifference( this.start, this.end );
return this;
});
// apply original class
animated.attr( "class", baseClass );
// map all animated objects again - this time collecting a promise
allAnimations = allAnimations.map(function() {
var styleInfo = this,
dfd = $.Deferred(),
opts = $.extend({}, o, {
queue: false,
complete: function() {
dfd.resolve( styleInfo );
}
});
this.el.animate( this.diff, opts );
return dfd.promise();
});
// once all animations have completed:
$.when.apply( $, allAnimations.get() ).done(function() {
// set the final class
applyClassChange();
// for each animated element,
// clear all css properties that were animated
$.each( arguments, function() {
var el = this.el;
$.each( this.diff, function(key) {
el.css( key, "" );
});
});
// this is guarnteed to be there if you use jQuery.speed()
// it also handles dequeuing the next anim...
o.complete.call( animated[ 0 ] );
});
});
};
$.fn.extend({
addClass: (function( orig ) {
return function( classNames, speed, easing, callback ) {
return speed ?
$.effects.animateClass.call( this,
{ add: classNames }, speed, easing, callback ) :
orig.apply( this, arguments );
};
})( $.fn.addClass ),
removeClass: (function( orig ) {
return function( classNames, speed, easing, callback ) {
return arguments.length > 1 ?
$.effects.animateClass.call( this,
{ remove: classNames }, speed, easing, callback ) :
orig.apply( this, arguments );
};
})( $.fn.removeClass ),
toggleClass: (function( orig ) {
return function( classNames, force, speed, easing, callback ) {
if ( typeof force === "boolean" || force === undefined ) {
if ( !speed ) {
// without speed parameter
return orig.apply( this, arguments );
} else {
return $.effects.animateClass.call( this,
(force ? { add: classNames } : { remove: classNames }),
speed, easing, callback );
}
} else {
// without force parameter
return $.effects.animateClass.call( this,
{ toggle: classNames }, force, speed, easing );
}
};
})( $.fn.toggleClass ),
switchClass: function( remove, add, speed, easing, callback) {
return $.effects.animateClass.call( this, {
add: add,
remove: remove
}, speed, easing, callback );
}
});
})();
/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/
(function() {
$.extend( $.effects, {
version: "1.10.2",
// Saves a set of properties in a data storage
save: function( element, set ) {
for( var i=0; i < set.length; i++ ) {
if ( set[ i ] !== null ) {
element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
}
}
},
// Restores a set of previously saved properties from a data storage
restore: function( element, set ) {
var val, i;
for( i=0; i < set.length; i++ ) {
if ( set[ i ] !== null ) {
val = element.data( dataSpace + set[ i ] );
// support: jQuery 1.6.2
// http://bugs.jquery.com/ticket/9917
// jQuery 1.6.2 incorrectly returns undefined for any falsy value.
// We can't differentiate between "" and 0 here, so we just assume
// empty string since it's likely to be a more common value...
if ( val === undefined ) {
val = "";
}
element.css( set[ i ], val );
}
}
},
setMode: function( el, mode ) {
if (mode === "toggle") {
mode = el.is( ":hidden" ) ? "show" : "hide";
}
return mode;
},
// Translates a [top,left] array into a baseline value
// this should be a little more flexible in the future to handle a string & hash
getBaseline: function( origin, original ) {
var y, x;
switch ( origin[ 0 ] ) {
case "top": y = 0; break;
case "middle": y = 0.5; break;
case "bottom": y = 1; break;
default: y = origin[ 0 ] / original.height;
}
switch ( origin[ 1 ] ) {
case "left": x = 0; break;
case "center": x = 0.5; break;
case "right": x = 1; break;
default: x = origin[ 1 ] / original.width;
}
return {
x: x,
y: y
};
},
// Wraps the element around a wrapper that copies position properties
createWrapper: function( element ) {
// if the element is already wrapped, return it
if ( element.parent().is( ".ui-effects-wrapper" )) {
return element.parent();
}
// wrap the element
var props = {
width: element.outerWidth(true),
height: element.outerHeight(true),
"float": element.css( "float" )
},
wrapper = $( "<div></div>" )
.addClass( "ui-effects-wrapper" )
.css({
fontSize: "100%",
background: "transparent",
border: "none",
margin: 0,
padding: 0
}),
// Store the size in case width/height are defined in % - Fixes #5245
size = {
width: element.width(),
height: element.height()
},
active = document.activeElement;
// support: Firefox
// Firefox incorrectly exposes anonymous content
// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
try {
active.id;
} catch( e ) {
active = document.body;
}
element.wrap( wrapper );
// Fixes #7595 - Elements lose focus when wrapped.
if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
$( active ).focus();
}
wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element
// transfer positioning properties to the wrapper
if ( element.css( "position" ) === "static" ) {
wrapper.css({ position: "relative" });
element.css({ position: "relative" });
} else {
$.extend( props, {
position: element.css( "position" ),
zIndex: element.css( "z-index" )
});
$.each([ "top", "left", "bottom", "right" ], function(i, pos) {
props[ pos ] = element.css( pos );
if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
props[ pos ] = "auto";
}
});
element.css({
position: "relative",
top: 0,
left: 0,
right: "auto",
bottom: "auto"
});
}
element.css(size);
return wrapper.css( props ).show();
},
removeWrapper: function( element ) {
var active = document.activeElement;
if ( element.parent().is( ".ui-effects-wrapper" ) ) {
element.parent().replaceWith( element );
// Fixes #7595 - Elements lose focus when wrapped.
if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
$( active ).focus();
}
}
return element;
},
setTransition: function( element, list, factor, value ) {
value = value || {};
$.each( list, function( i, x ) {
var unit = element.cssUnit( x );
if ( unit[ 0 ] > 0 ) {
value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
}
});
return value;
}
});
// return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {
// allow passing all options as the first parameter
if ( $.isPlainObject( effect ) ) {
options = effect;
effect = effect.effect;
}
// convert to an object
effect = { effect: effect };
// catch (effect, null, ...)
if ( options == null ) {
options = {};
}
// catch (effect, callback)
if ( $.isFunction( options ) ) {
callback = options;
speed = null;
options = {};
}
// catch (effect, speed, ?)
if ( typeof options === "number" || $.fx.speeds[ options ] ) {
callback = speed;
speed = options;
options = {};
}
// catch (effect, options, callback)
if ( $.isFunction( speed ) ) {
callback = speed;
speed = null;
}
// add options to effect
if ( options ) {
$.extend( effect, options );
}
speed = speed || options.duration;
effect.duration = $.fx.off ? 0 :
typeof speed === "number" ? speed :
speed in $.fx.speeds ? $.fx.speeds[ speed ] :
$.fx.speeds._default;
effect.complete = callback || options.complete;
return effect;
}
function standardAnimationOption( option ) {
// Valid standard speeds (nothing, number, named speed)
if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
return true;
}
// Invalid strings - treat as "normal" speed
if ( typeof option === "string" && !$.effects.effect[ option ] ) {
return true;
}
// Complete callback
if ( $.isFunction( option ) ) {
return true;
}
// Options hash (but not naming an effect)
if ( typeof option === "object" && !option.effect ) {
return true;
}
// Didn't match any standard API
return false;
}
$.fn.extend({
effect: function( /* effect, options, speed, callback */ ) {
var args = _normalizeArguments.apply( this, arguments ),
mode = args.mode,
queue = args.queue,
effectMethod = $.effects.effect[ args.effect ];
if ( $.fx.off || !effectMethod ) {
// delegate to the original method (e.g., .show()) if possible
if ( mode ) {
return this[ mode ]( args.duration, args.complete );
} else {
return this.each( function() {
if ( args.complete ) {
args.complete.call( this );
}
});
}
}
function run( next ) {
var elem = $( this ),
complete = args.complete,
mode = args.mode;
function done() {
if ( $.isFunction( complete ) ) {
complete.call( elem[0] );
}
if ( $.isFunction( next ) ) {
next();
}
}
// If the element already has the correct final state, delegate to
// the core methods so the internal tracking of "olddisplay" works.
if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
elem[ mode ]();
done();
} else {
effectMethod.call( elem[0], args, done );
}
}
return queue === false ? this.each( run ) : this.queue( queue || "fx", run );
},
show: (function( orig ) {
return function( option ) {
if ( standardAnimationOption( option ) ) {
return orig.apply( this, arguments );
} else {
var args = _normalizeArguments.apply( this, arguments );
args.mode = "show";
return this.effect.call( this, args );
}
};
})( $.fn.show ),
hide: (function( orig ) {
return function( option ) {
if ( standardAnimationOption( option ) ) {
return orig.apply( this, arguments );
} else {
var args = _normalizeArguments.apply( this, arguments );
args.mode = "hide";
return this.effect.call( this, args );
}
};
})( $.fn.hide ),
toggle: (function( orig ) {
return function( option ) {
if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
return orig.apply( this, arguments );
} else {
var args = _normalizeArguments.apply( this, arguments );
args.mode = "toggle";
return this.effect.call( this, args );
}
};
})( $.fn.toggle ),
// helper functions
cssUnit: function(key) {
var style = this.css( key ),
val = [];
$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
if ( style.indexOf( unit ) > 0 ) {
val = [ parseFloat( style ), unit ];
}
});
return val;
}
});
})();
/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/
(function() {
// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)
var baseEasings = {};
$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
baseEasings[ name ] = function( p ) {
return Math.pow( p, i + 2 );
};
});
$.extend( baseEasings, {
Sine: function ( p ) {
return 1 - Math.cos( p * Math.PI / 2 );
},
Circ: function ( p ) {
return 1 - Math.sqrt( 1 - p * p );
},
Elastic: function( p ) {
return p === 0 || p === 1 ? p :
-Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
},
Back: function( p ) {
return p * p * ( 3 * p - 2 );
},
Bounce: function ( p ) {
var pow2,
bounce = 4;
while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
}
});
$.each( baseEasings, function( name, easeIn ) {
$.easing[ "easeIn" + name ] = easeIn;
$.easing[ "easeOut" + name ] = function( p ) {
return 1 - easeIn( 1 - p );
};
$.easing[ "easeInOut" + name ] = function( p ) {
return p < 0.5 ?
easeIn( p * 2 ) / 2 :
1 - easeIn( p * -2 + 2 ) / 2;
};
});
})();
})(jQuery);
(function( $, undefined ) {
var rvertical = /up|down|vertical/,
rpositivemotion = /up|left|vertical|horizontal/;
$.effects.effect.blind = function( o, done ) {
// Create element
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "hide" ),
direction = o.direction || "up",
vertical = rvertical.test( direction ),
ref = vertical ? "height" : "width",
ref2 = vertical ? "top" : "left",
motion = rpositivemotion.test( direction ),
animation = {},
show = mode === "show",
wrapper, distance, margin;
// if already wrapped, the wrapper's properties are my property. #6245
if ( el.parent().is( ".ui-effects-wrapper" ) ) {
$.effects.save( el.parent(), props );
} else {
$.effects.save( el, props );
}
el.show();
wrapper = $.effects.createWrapper( el ).css({
overflow: "hidden"
});
distance = wrapper[ ref ]();
margin = parseFloat( wrapper.css( ref2 ) ) || 0;
animation[ ref ] = show ? distance : 0;
if ( !motion ) {
el
.css( vertical ? "bottom" : "right", 0 )
.css( vertical ? "top" : "left", "auto" )
.css({ position: "absolute" });
animation[ ref2 ] = show ? margin : distance + margin;
}
// start at 0 if we are showing
if ( show ) {
wrapper.css( ref, 0 );
if ( ! motion ) {
wrapper.css( ref2, margin + distance );
}
}
// Animate
wrapper.animate( animation, {
duration: o.duration,
easing: o.easing,
queue: false,
complete: function() {
if ( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.bounce = function( o, done ) {
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
// defaults:
mode = $.effects.setMode( el, o.mode || "effect" ),
hide = mode === "hide",
show = mode === "show",
direction = o.direction || "up",
distance = o.distance,
times = o.times || 5,
// number of internal animations
anims = times * 2 + ( show || hide ? 1 : 0 ),
speed = o.duration / anims,
easing = o.easing,
// utility:
ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
motion = ( direction === "up" || direction === "left" ),
i,
upAnim,
downAnim,
// we will need to re-assemble the queue to stack our animations in place
queue = el.queue(),
queuelen = queue.length;
// Avoid touching opacity to prevent clearType and PNG issues in IE
if ( show || hide ) {
props.push( "opacity" );
}
$.effects.save( el, props );
el.show();
$.effects.createWrapper( el ); // Create Wrapper
// default distance for the BIGGEST bounce is the outer Distance / 3
if ( !distance ) {
distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
}
if ( show ) {
downAnim = { opacity: 1 };
downAnim[ ref ] = 0;
// if we are showing, force opacity 0 and set the initial position
// then do the "first" animation
el.css( "opacity", 0 )
.css( ref, motion ? -distance * 2 : distance * 2 )
.animate( downAnim, speed, easing );
}
// start at the smallest distance if we are hiding
if ( hide ) {
distance = distance / Math.pow( 2, times - 1 );
}
downAnim = {};
downAnim[ ref ] = 0;
// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
for ( i = 0; i < times; i++ ) {
upAnim = {};
upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
el.animate( upAnim, speed, easing )
.animate( downAnim, speed, easing );
distance = hide ? distance * 2 : distance / 2;
}
// Last Bounce when Hiding
if ( hide ) {
upAnim = { opacity: 0 };
upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
el.animate( upAnim, speed, easing );
}
el.queue(function() {
if ( hide ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
});
// inject all the animations we just queued to be first in line (after "inprogress")
if ( queuelen > 1) {
queue.splice.apply( queue,
[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
}
el.dequeue();
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.clip = function( o, done ) {
// Create element
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "hide" ),
show = mode === "show",
direction = o.direction || "vertical",
vert = direction === "vertical",
size = vert ? "height" : "width",
position = vert ? "top" : "left",
animation = {},
wrapper, animate, distance;
// Save & Show
$.effects.save( el, props );
el.show();
// Create Wrapper
wrapper = $.effects.createWrapper( el ).css({
overflow: "hidden"
});
animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
distance = animate[ size ]();
// Shift
if ( show ) {
animate.css( size, 0 );
animate.css( position, distance / 2 );
}
// Create Animation Object:
animation[ size ] = show ? distance : 0;
animation[ position ] = show ? 0 : distance / 2;
// Animate
animate.animate( animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( !show ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.drop = function( o, done ) {
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "hide" ),
show = mode === "show",
direction = o.direction || "left",
ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg",
animation = {
opacity: show ? 1 : 0
},
distance;
// Adjust
$.effects.save( el, props );
el.show();
$.effects.createWrapper( el );
distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2;
if ( show ) {
el
.css( "opacity", 0 )
.css( ref, motion === "pos" ? -distance : distance );
}
// Animation
animation[ ref ] = ( show ?
( motion === "pos" ? "+=" : "-=" ) :
( motion === "pos" ? "-=" : "+=" ) ) +
distance;
// Animate
el.animate( animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.explode = function( o, done ) {
var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3,
cells = rows,
el = $( this ),
mode = $.effects.setMode( el, o.mode || "hide" ),
show = mode === "show",
// show and then visibility:hidden the element before calculating offset
offset = el.show().css( "visibility", "hidden" ).offset(),
// width and height of a piece
width = Math.ceil( el.outerWidth() / cells ),
height = Math.ceil( el.outerHeight() / rows ),
pieces = [],
// loop
i, j, left, top, mx, my;
// children animate complete:
function childComplete() {
pieces.push( this );
if ( pieces.length === rows * cells ) {
animComplete();
}
}
// clone the element for each row and cell.
for( i = 0; i < rows ; i++ ) { // ===>
top = offset.top + i * height;
my = i - ( rows - 1 ) / 2 ;
for( j = 0; j < cells ; j++ ) { // |||
left = offset.left + j * width;
mx = j - ( cells - 1 ) / 2 ;
// Create a clone of the now hidden main element that will be absolute positioned
// within a wrapper div off the -left and -top equal to size of our pieces
el
.clone()
.appendTo( "body" )
.wrap( "<div></div>" )
.css({
position: "absolute",
visibility: "visible",
left: -j * width,
top: -i * height
})
// select the wrapper - make it overflow: hidden and absolute positioned based on
// where the original was located +left and +top equal to the size of pieces
.parent()
.addClass( "ui-effects-explode" )
.css({
position: "absolute",
overflow: "hidden",
width: width,
height: height,
left: left + ( show ? mx * width : 0 ),
top: top + ( show ? my * height : 0 ),
opacity: show ? 0 : 1
}).animate({
left: left + ( show ? 0 : mx * width ),
top: top + ( show ? 0 : my * height ),
opacity: show ? 1 : 0
}, o.duration || 500, o.easing, childComplete );
}
}
function animComplete() {
el.css({
visibility: "visible"
});
$( pieces ).remove();
if ( !show ) {
el.hide();
}
done();
}
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.fade = function( o, done ) {
var el = $( this ),
mode = $.effects.setMode( el, o.mode || "toggle" );
el.animate({
opacity: mode
}, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: done
});
};
})( jQuery );
(function( $, undefined ) {
$.effects.effect.fold = function( o, done ) {
// Create element
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "hide" ),
show = mode === "show",
hide = mode === "hide",
size = o.size || 15,
percent = /([0-9]+)%/.exec( size ),
horizFirst = !!o.horizFirst,
widthFirst = show !== horizFirst,
ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ],
duration = o.duration / 2,
wrapper, distance,
animation1 = {},
animation2 = {};
$.effects.save( el, props );
el.show();
// Create Wrapper
wrapper = $.effects.createWrapper( el ).css({
overflow: "hidden"
});
distance = widthFirst ?
[ wrapper.width(), wrapper.height() ] :
[ wrapper.height(), wrapper.width() ];
if ( percent ) {
size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
}
if ( show ) {
wrapper.css( horizFirst ? {
height: 0,
width: size
} : {
height: size,
width: 0
});
}
// Animation
animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;
// Animate
wrapper
.animate( animation1, duration, o.easing )
.animate( animation2, duration, o.easing, function() {
if ( hide ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.highlight = function( o, done ) {
var elem = $( this ),
props = [ "backgroundImage", "backgroundColor", "opacity" ],
mode = $.effects.setMode( elem, o.mode || "show" ),
animation = {
backgroundColor: elem.css( "backgroundColor" )
};
if (mode === "hide") {
animation.opacity = 0;
}
$.effects.save( elem, props );
elem
.show()
.css({
backgroundImage: "none",
backgroundColor: o.color || "#ffff99"
})
.animate( animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( mode === "hide" ) {
elem.hide();
}
$.effects.restore( elem, props );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.pulsate = function( o, done ) {
var elem = $( this ),
mode = $.effects.setMode( elem, o.mode || "show" ),
show = mode === "show",
hide = mode === "hide",
showhide = ( show || mode === "hide" ),
// showing or hiding leaves of the "last" animation
anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
duration = o.duration / anims,
animateTo = 0,
queue = elem.queue(),
queuelen = queue.length,
i;
if ( show || !elem.is(":visible")) {
elem.css( "opacity", 0 ).show();
animateTo = 1;
}
// anims - 1 opacity "toggles"
for ( i = 1; i < anims; i++ ) {
elem.animate({
opacity: animateTo
}, duration, o.easing );
animateTo = 1 - animateTo;
}
elem.animate({
opacity: animateTo
}, duration, o.easing);
elem.queue(function() {
if ( hide ) {
elem.hide();
}
done();
});
// We just queued up "anims" animations, we need to put them next in the queue
if ( queuelen > 1 ) {
queue.splice.apply( queue,
[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
}
elem.dequeue();
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.puff = function( o, done ) {
var elem = $( this ),
mode = $.effects.setMode( elem, o.mode || "hide" ),
hide = mode === "hide",
percent = parseInt( o.percent, 10 ) || 150,
factor = percent / 100,
original = {
height: elem.height(),
width: elem.width(),
outerHeight: elem.outerHeight(),
outerWidth: elem.outerWidth()
};
$.extend( o, {
effect: "scale",
queue: false,
fade: true,
mode: mode,
complete: done,
percent: hide ? percent : 100,
from: hide ?
original :
{
height: original.height * factor,
width: original.width * factor,
outerHeight: original.outerHeight * factor,
outerWidth: original.outerWidth * factor
}
});
elem.effect( o );
};
$.effects.effect.scale = function( o, done ) {
// Create element
var el = $( this ),
options = $.extend( true, {}, o ),
mode = $.effects.setMode( el, o.mode || "effect" ),
percent = parseInt( o.percent, 10 ) ||
( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ),
direction = o.direction || "both",
origin = o.origin,
original = {
height: el.height(),
width: el.width(),
outerHeight: el.outerHeight(),
outerWidth: el.outerWidth()
},
factor = {
y: direction !== "horizontal" ? (percent / 100) : 1,
x: direction !== "vertical" ? (percent / 100) : 1
};
// We are going to pass this effect to the size effect:
options.effect = "size";
options.queue = false;
options.complete = done;
// Set default origin and restore for show/hide
if ( mode !== "effect" ) {
options.origin = origin || ["middle","center"];
options.restore = true;
}
options.from = o.from || ( mode === "show" ? {
height: 0,
width: 0,
outerHeight: 0,
outerWidth: 0
} : original );
options.to = {
height: original.height * factor.y,
width: original.width * factor.x,
outerHeight: original.outerHeight * factor.y,
outerWidth: original.outerWidth * factor.x
};
// Fade option to support puff
if ( options.fade ) {
if ( mode === "show" ) {
options.from.opacity = 0;
options.to.opacity = 1;
}
if ( mode === "hide" ) {
options.from.opacity = 1;
options.to.opacity = 0;
}
}
// Animate
el.effect( options );
};
$.effects.effect.size = function( o, done ) {
// Create element
var original, baseline, factor,
el = $( this ),
props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ],
// Always restore
props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ],
// Copy for children
props2 = [ "width", "height", "overflow" ],
cProps = [ "fontSize" ],
vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],
// Set options
mode = $.effects.setMode( el, o.mode || "effect" ),
restore = o.restore || mode !== "effect",
scale = o.scale || "both",
origin = o.origin || [ "middle", "center" ],
position = el.css( "position" ),
props = restore ? props0 : props1,
zero = {
height: 0,
width: 0,
outerHeight: 0,
outerWidth: 0
};
if ( mode === "show" ) {
el.show();
}
original = {
height: el.height(),
width: el.width(),
outerHeight: el.outerHeight(),
outerWidth: el.outerWidth()
};
if ( o.mode === "toggle" && mode === "show" ) {
el.from = o.to || zero;
el.to = o.from || original;
} else {
el.from = o.from || ( mode === "show" ? zero : original );
el.to = o.to || ( mode === "hide" ? zero : original );
}
// Set scaling factor
factor = {
from: {
y: el.from.height / original.height,
x: el.from.width / original.width
},
to: {
y: el.to.height / original.height,
x: el.to.width / original.width
}
};
// Scale the css box
if ( scale === "box" || scale === "both" ) {
// Vertical props scaling
if ( factor.from.y !== factor.to.y ) {
props = props.concat( vProps );
el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from );
el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to );
}
// Horizontal props scaling
if ( factor.from.x !== factor.to.x ) {
props = props.concat( hProps );
el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from );
el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to );
}
}
// Scale the content
if ( scale === "content" || scale === "both" ) {
// Vertical props scaling
if ( factor.from.y !== factor.to.y ) {
props = props.concat( cProps ).concat( props2 );
el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from );
el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to );
}
}
$.effects.save( el, props );
el.show();
$.effects.createWrapper( el );
el.css( "overflow", "hidden" ).css( el.from );
// Adjust
if (origin) { // Calculate baseline shifts
baseline = $.effects.getBaseline( origin, original );
el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y;
el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x;
el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y;
el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x;
}
el.css( el.from ); // set top & left
// Animate
if ( scale === "content" || scale === "both" ) { // Scale the children
// Add margins/font-size
vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps);
hProps = hProps.concat([ "marginLeft", "marginRight" ]);
props2 = props0.concat(vProps).concat(hProps);
el.find( "*[width]" ).each( function(){
var child = $( this ),
c_original = {
height: child.height(),
width: child.width(),
outerHeight: child.outerHeight(),
outerWidth: child.outerWidth()
};
if (restore) {
$.effects.save(child, props2);
}
child.from = {
height: c_original.height * factor.from.y,
width: c_original.width * factor.from.x,
outerHeight: c_original.outerHeight * factor.from.y,
outerWidth: c_original.outerWidth * factor.from.x
};
child.to = {
height: c_original.height * factor.to.y,
width: c_original.width * factor.to.x,
outerHeight: c_original.height * factor.to.y,
outerWidth: c_original.width * factor.to.x
};
// Vertical props scaling
if ( factor.from.y !== factor.to.y ) {
child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from );
child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to );
}
// Horizontal props scaling
if ( factor.from.x !== factor.to.x ) {
child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from );
child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to );
}
// Animate children
child.css( child.from );
child.animate( child.to, o.duration, o.easing, function() {
// Restore children
if ( restore ) {
$.effects.restore( child, props2 );
}
});
});
}
// Animate
el.animate( el.to, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( el.to.opacity === 0 ) {
el.css( "opacity", el.from.opacity );
}
if( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
if ( !restore ) {
// we need to calculate our new positioning based on the scaling
if ( position === "static" ) {
el.css({
position: "relative",
top: el.to.top,
left: el.to.left
});
} else {
$.each([ "top", "left" ], function( idx, pos ) {
el.css( pos, function( _, str ) {
var val = parseInt( str, 10 ),
toRef = idx ? el.to.left : el.to.top;
// if original was "auto", recalculate the new value from wrapper
if ( str === "auto" ) {
return toRef + "px";
}
return val + toRef + "px";
});
});
}
}
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.shake = function( o, done ) {
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "effect" ),
direction = o.direction || "left",
distance = o.distance || 20,
times = o.times || 3,
anims = times * 2 + 1,
speed = Math.round(o.duration/anims),
ref = (direction === "up" || direction === "down") ? "top" : "left",
positiveMotion = (direction === "up" || direction === "left"),
animation = {},
animation1 = {},
animation2 = {},
i,
// we will need to re-assemble the queue to stack our animations in place
queue = el.queue(),
queuelen = queue.length;
$.effects.save( el, props );
el.show();
$.effects.createWrapper( el );
// Animation
animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;
// Animate
el.animate( animation, speed, o.easing );
// Shakes
for ( i = 1; i < times; i++ ) {
el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
}
el
.animate( animation1, speed, o.easing )
.animate( animation, speed / 2, o.easing )
.queue(function() {
if ( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
});
// inject all the animations we just queued to be first in line (after "inprogress")
if ( queuelen > 1) {
queue.splice.apply( queue,
[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
}
el.dequeue();
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.slide = function( o, done ) {
// Create element
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "width", "height" ],
mode = $.effects.setMode( el, o.mode || "show" ),
show = mode === "show",
direction = o.direction || "left",
ref = (direction === "up" || direction === "down") ? "top" : "left",
positiveMotion = (direction === "up" || direction === "left"),
distance,
animation = {};
// Adjust
$.effects.save( el, props );
el.show();
distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true );
$.effects.createWrapper( el ).css({
overflow: "hidden"
});
if ( show ) {
el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance );
}
// Animation
animation[ ref ] = ( show ?
( positiveMotion ? "+=" : "-=") :
( positiveMotion ? "-=" : "+=")) +
distance;
// Animate
el.animate( animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( mode === "hide" ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
}
});
};
})(jQuery);
(function( $, undefined ) {
$.effects.effect.transfer = function( o, done ) {
var elem = $( this ),
target = $( o.to ),
targetFixed = target.css( "position" ) === "fixed",
body = $("body"),
fixTop = targetFixed ? body.scrollTop() : 0,
fixLeft = targetFixed ? body.scrollLeft() : 0,
endPosition = target.offset(),
animation = {
top: endPosition.top - fixTop ,
left: endPosition.left - fixLeft ,
height: target.innerHeight(),
width: target.innerWidth()
},
startPosition = elem.offset(),
transfer = $( "<div class='ui-effects-transfer'></div>" )
.appendTo( document.body )
.addClass( o.className )
.css({
top: startPosition.top - fixTop ,
left: startPosition.left - fixLeft ,
height: elem.innerHeight(),
width: elem.innerWidth(),
position: targetFixed ? "fixed" : "absolute"
})
.animate( animation, o.duration, o.easing, function() {
transfer.remove();
done();
});
};
})(jQuery);
(function( $, undefined ) {
$.widget( "ui.menu", {
version: "1.10.2",
defaultElement: "<ul>",
delay: 300,
options: {
icons: {
submenu: "ui-icon-carat-1-e"
},
menus: "ul",
position: {
my: "left top",
at: "right top"
},
role: "menu",
// callbacks
blur: null,
focus: null,
select: null
},
_create: function() {
this.activeMenu = this.element;
// flag used to prevent firing of the click handler
// as the event bubbles up through nested menus
this.mouseHandled = false;
this.element
.uniqueId()
.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
.attr({
role: this.options.role,
tabIndex: 0
})
// need to catch all clicks on disabled menu
// not possible through _on
.bind( "click" + this.eventNamespace, $.proxy(function( event ) {
if ( this.options.disabled ) {
event.preventDefault();
}
}, this ));
if ( this.options.disabled ) {
this.element
.addClass( "ui-state-disabled" )
.attr( "aria-disabled", "true" );
}
this._on({
// Prevent focus from sticking to links inside menu after clicking
// them (focus should always stay on UL during navigation).
"mousedown .ui-menu-item > a": function( event ) {
event.preventDefault();
},
"click .ui-state-disabled > a": function( event ) {
event.preventDefault();
},
"click .ui-menu-item:has(a)": function( event ) {
var target = $( event.target ).closest( ".ui-menu-item" );
if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
this.mouseHandled = true;
this.select( event );
// Open submenu on click
if ( target.has( ".ui-menu" ).length ) {
this.expand( event );
} else if ( !this.element.is( ":focus" ) ) {
// Redirect focus to the menu
this.element.trigger( "focus", [ true ] );
// If the active item is on the top level, let it stay active.
// Otherwise, blur the active item since it is no longer visible.
if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
clearTimeout( this.timer );
}
}
}
},
"mouseenter .ui-menu-item": function( event ) {
var target = $( event.currentTarget );
// Remove ui-state-active class from siblings of the newly focused menu item
// to avoid a jump caused by adjacent elements both having a class with a border
target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
this.focus( event, target );
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function( event, keepActiveItem ) {
// If there's already an active item, keep it active
// If not, activate the first item
var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 );
if ( !keepActiveItem ) {
this.focus( event, item );
}
},
blur: function( event ) {
this._delay(function() {
if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
this.collapseAll( event );
}
});
},
keydown: "_keydown"
});
this.refresh();
// Clicks outside of a menu collapse any open menus
this._on( this.document, {
click: function( event ) {
if ( !$( event.target ).closest( ".ui-menu" ).length ) {
this.collapseAll( event );
}
// Reset the mouseHandled flag
this.mouseHandled = false;
}
});
},
_destroy: function() {
// Destroy (sub)menus
this.element
.removeAttr( "aria-activedescendant" )
.find( ".ui-menu" ).addBack()
.removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" )
.removeAttr( "role" )
.removeAttr( "tabIndex" )
.removeAttr( "aria-labelledby" )
.removeAttr( "aria-expanded" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-disabled" )
.removeUniqueId()
.show();
// Destroy menu items
this.element.find( ".ui-menu-item" )
.removeClass( "ui-menu-item" )
.removeAttr( "role" )
.removeAttr( "aria-disabled" )
.children( "a" )
.removeUniqueId()
.removeClass( "ui-corner-all ui-state-hover" )
.removeAttr( "tabIndex" )
.removeAttr( "role" )
.removeAttr( "aria-haspopup" )
.children().each( function() {
var elem = $( this );
if ( elem.data( "ui-menu-submenu-carat" ) ) {
elem.remove();
}
});
// Destroy menu dividers
this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
},
_keydown: function( event ) {
/*jshint maxcomplexity:20*/
var match, prev, character, skip, regex,
preventDefault = true;
function escape( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}
switch ( event.keyCode ) {
case $.ui.keyCode.PAGE_UP:
this.previousPage( event );
break;
case $.ui.keyCode.PAGE_DOWN:
this.nextPage( event );
break;
case $.ui.keyCode.HOME:
this._move( "first", "first", event );
break;
case $.ui.keyCode.END:
this._move( "last", "last", event );
break;
case $.ui.keyCode.UP:
this.previous( event );
break;
case $.ui.keyCode.DOWN:
this.next( event );
break;
case $.ui.keyCode.LEFT:
this.collapse( event );
break;
case $.ui.keyCode.RIGHT:
if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
this.expand( event );
}
break;
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
this._activate( event );
break;
case $.ui.keyCode.ESCAPE:
this.collapse( event );
break;
default:
preventDefault = false;
prev = this.previousFilter || "";
character = String.fromCharCode( event.keyCode );
skip = false;
clearTimeout( this.filterTimer );
if ( character === prev ) {
skip = true;
} else {
character = prev + character;
}
regex = new RegExp( "^" + escape( character ), "i" );
match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
return regex.test( $( this ).children( "a" ).text() );
});
match = skip && match.index( this.active.next() ) !== -1 ?
this.active.nextAll( ".ui-menu-item" ) :
match;
// If no matches on the current filter, reset to the last character pressed
// to move down the menu to the first item that starts with that character
if ( !match.length ) {
character = String.fromCharCode( event.keyCode );
regex = new RegExp( "^" + escape( character ), "i" );
match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
return regex.test( $( this ).children( "a" ).text() );
});
}
if ( match.length ) {
this.focus( event, match );
if ( match.length > 1 ) {
this.previousFilter = character;
this.filterTimer = this._delay(function() {
delete this.previousFilter;
}, 1000 );
} else {
delete this.previousFilter;
}
} else {
delete this.previousFilter;
}
}
if ( preventDefault ) {
event.preventDefault();
}
},
_activate: function( event ) {
if ( !this.active.is( ".ui-state-disabled" ) ) {
if ( this.active.children( "a[aria-haspopup='true']" ).length ) {
this.expand( event );
} else {
this.select( event );
}
}
},
refresh: function() {
var menus,
icon = this.options.icons.submenu,
submenus = this.element.find( this.options.menus );
// Initialize nested menus
submenus.filter( ":not(.ui-menu)" )
.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
.hide()
.attr({
role: this.options.role,
"aria-hidden": "true",
"aria-expanded": "false"
})
.each(function() {
var menu = $( this ),
item = menu.prev( "a" ),
submenuCarat = $( "<span>" )
.addClass( "ui-menu-icon ui-icon " + icon )
.data( "ui-menu-submenu-carat", true );
item
.attr( "aria-haspopup", "true" )
.prepend( submenuCarat );
menu.attr( "aria-labelledby", item.attr( "id" ) );
});
menus = submenus.add( this.element );
// Don't refresh list items that are already adapted
menus.children( ":not(.ui-menu-item):has(a)" )
.addClass( "ui-menu-item" )
.attr( "role", "presentation" )
.children( "a" )
.uniqueId()
.addClass( "ui-corner-all" )
.attr({
tabIndex: -1,
role: this._itemRole()
});
// Initialize unlinked menu-items containing spaces and/or dashes only as dividers
menus.children( ":not(.ui-menu-item)" ).each(function() {
var item = $( this );
// hyphen, em dash, en dash
if ( !/[^\-\u2014\u2013\s]/.test( item.text() ) ) {
item.addClass( "ui-widget-content ui-menu-divider" );
}
});
// Add aria-disabled attribute to any disabled menu item
menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" );
// If the active item has been removed, blur the menu
if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
this.blur();
}
},
_itemRole: function() {
return {
menu: "menuitem",
listbox: "option"
}[ this.options.role ];
},
_setOption: function( key, value ) {
if ( key === "icons" ) {
this.element.find( ".ui-menu-icon" )
.removeClass( this.options.icons.submenu )
.addClass( value.submenu );
}
this._super( key, value );
},
focus: function( event, item ) {
var nested, focused;
this.blur( event, event && event.type === "focus" );
this._scrollIntoView( item );
this.active = item.first();
focused = this.active.children( "a" ).addClass( "ui-state-focus" );
// Only update aria-activedescendant if there's a role
// otherwise we assume focus is managed elsewhere
if ( this.options.role ) {
this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
}
// Highlight active parent menu item, if any
this.active
.parent()
.closest( ".ui-menu-item" )
.children( "a:first" )
.addClass( "ui-state-active" );
if ( event && event.type === "keydown" ) {
this._close();
} else {
this.timer = this._delay(function() {
this._close();
}, this.delay );
}
nested = item.children( ".ui-menu" );
if ( nested.length && ( /^mouse/.test( event.type ) ) ) {
this._startOpening(nested);
}
this.activeMenu = item.parent();
this._trigger( "focus", event, { item: item } );
},
_scrollIntoView: function( item ) {
var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
if ( this._hasScroll() ) {
borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
scroll = this.activeMenu.scrollTop();
elementHeight = this.activeMenu.height();
itemHeight = item.height();
if ( offset < 0 ) {
this.activeMenu.scrollTop( scroll + offset );
} else if ( offset + itemHeight > elementHeight ) {
this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
}
}
},
blur: function( event, fromFocus ) {
if ( !fromFocus ) {
clearTimeout( this.timer );
}
if ( !this.active ) {
return;
}
this.active.children( "a" ).removeClass( "ui-state-focus" );
this.active = null;
this._trigger( "blur", event, { item: this.active } );
},
_startOpening: function( submenu ) {
clearTimeout( this.timer );
// Don't open if already open fixes a Firefox bug that caused a .5 pixel
// shift in the submenu position when mousing over the carat icon
if ( submenu.attr( "aria-hidden" ) !== "true" ) {
return;
}
this.timer = this._delay(function() {
this._close();
this._open( submenu );
}, this.delay );
},
_open: function( submenu ) {
var position = $.extend({
of: this.active
}, this.options.position );
clearTimeout( this.timer );
this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
.hide()
.attr( "aria-hidden", "true" );
submenu
.show()
.removeAttr( "aria-hidden" )
.attr( "aria-expanded", "true" )
.position( position );
},
collapseAll: function( event, all ) {
clearTimeout( this.timer );
this.timer = this._delay(function() {
// If we were passed an event, look for the submenu that contains the event
var currentMenu = all ? this.element :
$( event && event.target ).closest( this.element.find( ".ui-menu" ) );
// If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
if ( !currentMenu.length ) {
currentMenu = this.element;
}
this._close( currentMenu );
this.blur( event );
this.activeMenu = currentMenu;
}, this.delay );
},
// With no arguments, closes the currently active menu - if nothing is active
// it closes all menus. If passed an argument, it will search for menus BELOW
_close: function( startMenu ) {
if ( !startMenu ) {
startMenu = this.active ? this.active.parent() : this.element;
}
startMenu
.find( ".ui-menu" )
.hide()
.attr( "aria-hidden", "true" )
.attr( "aria-expanded", "false" )
.end()
.find( "a.ui-state-active" )
.removeClass( "ui-state-active" );
},
collapse: function( event ) {
var newItem = this.active &&
this.active.parent().closest( ".ui-menu-item", this.element );
if ( newItem && newItem.length ) {
this._close();
this.focus( event, newItem );
}
},
expand: function( event ) {
var newItem = this.active &&
this.active
.children( ".ui-menu " )
.children( ".ui-menu-item" )
.first();
if ( newItem && newItem.length ) {
this._open( newItem.parent() );
// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
this._delay(function() {
this.focus( event, newItem );
});
}
},
next: function( event ) {
this._move( "next", "first", event );
},
previous: function( event ) {
this._move( "prev", "last", event );
},
isFirstItem: function() {
return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
},
isLastItem: function() {
return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
},
_move: function( direction, filter, event ) {
var next;
if ( this.active ) {
if ( direction === "first" || direction === "last" ) {
next = this.active
[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
.eq( -1 );
} else {
next = this.active
[ direction + "All" ]( ".ui-menu-item" )
.eq( 0 );
}
}
if ( !next || !next.length || !this.active ) {
next = this.activeMenu.children( ".ui-menu-item" )[ filter ]();
}
this.focus( event, next );
},
nextPage: function( event ) {
var item, base, height;
if ( !this.active ) {
this.next( event );
return;
}
if ( this.isLastItem() ) {
return;
}
if ( this._hasScroll() ) {
base = this.active.offset().top;
height = this.element.height();
this.active.nextAll( ".ui-menu-item" ).each(function() {
item = $( this );
return item.offset().top - base - height < 0;
});
this.focus( event, item );
} else {
this.focus( event, this.activeMenu.children( ".ui-menu-item" )
[ !this.active ? "first" : "last" ]() );
}
},
previousPage: function( event ) {
var item, base, height;
if ( !this.active ) {
this.next( event );
return;
}
if ( this.isFirstItem() ) {
return;
}
if ( this._hasScroll() ) {
base = this.active.offset().top;
height = this.element.height();
this.active.prevAll( ".ui-menu-item" ).each(function() {
item = $( this );
return item.offset().top - base + height > 0;
});
this.focus( event, item );
} else {
this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
}
},
_hasScroll: function() {
return this.element.outerHeight() < this.element.prop( "scrollHeight" );
},
select: function( event ) {
// TODO: It should never be possible to not have an active item at this
// point, but the tests don't trigger mouseenter before click.
this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
var ui = { item: this.active };
if ( !this.active.has( ".ui-menu" ).length ) {
this.collapseAll( event, true );
}
this._trigger( "select", event, ui );
}
});
}( jQuery ));
(function( $, undefined ) {
$.widget( "ui.progressbar", {
version: "1.10.2",
options: {
max: 100,
value: 0,
change: null,
complete: null
},
min: 0,
_create: function() {
// Constrain initial value
this.oldValue = this.options.value = this._constrainedValue();
this.element
.addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
.attr({
// Only set static values, aria-valuenow and aria-valuemax are
// set inside _refreshValue()
role: "progressbar",
"aria-valuemin": this.min
});
this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
.appendTo( this.element );
this._refreshValue();
},
_destroy: function() {
this.element
.removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
.removeAttr( "role" )
.removeAttr( "aria-valuemin" )
.removeAttr( "aria-valuemax" )
.removeAttr( "aria-valuenow" );
this.valueDiv.remove();
},
value: function( newValue ) {
if ( newValue === undefined ) {
return this.options.value;
}
this.options.value = this._constrainedValue( newValue );
this._refreshValue();
},
_constrainedValue: function( newValue ) {
if ( newValue === undefined ) {
newValue = this.options.value;
}
this.indeterminate = newValue === false;
// sanitize value
if ( typeof newValue !== "number" ) {
newValue = 0;
}
return this.indeterminate ? false :
Math.min( this.options.max, Math.max( this.min, newValue ) );
},
_setOptions: function( options ) {
// Ensure "value" option is set after other values (like max)
var value = options.value;
delete options.value;
this._super( options );
this.options.value = this._constrainedValue( value );
this._refreshValue();
},
_setOption: function( key, value ) {
if ( key === "max" ) {
// Don't allow a max less than min
value = Math.max( this.min, value );
}
this._super( key, value );
},
_percentage: function() {
return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
},
_refreshValue: function() {
var value = this.options.value,
percentage = this._percentage();
this.valueDiv
.toggle( this.indeterminate || value > this.min )
.toggleClass( "ui-corner-right", value === this.options.max )
.width( percentage.toFixed(0) + "%" );
this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate );
if ( this.indeterminate ) {
this.element.removeAttr( "aria-valuenow" );
if ( !this.overlayDiv ) {
this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv );
}
} else {
this.element.attr({
"aria-valuemax": this.options.max,
"aria-valuenow": value
});
if ( this.overlayDiv ) {
this.overlayDiv.remove();
this.overlayDiv = null;
}
}
if ( this.oldValue !== value ) {
this.oldValue = value;
this._trigger( "change" );
}
if ( value === this.options.max ) {
this._trigger( "complete" );
}
}
});
})( jQuery );
(function( $, undefined ) {
function num(v) {
return parseInt(v, 10) || 0;
}
function isNumber(value) {
return !isNaN(parseInt(value, 10));
}
$.widget("ui.resizable", $.ui.mouse, {
version: "1.10.2",
widgetEventPrefix: "resize",
options: {
alsoResize: false,
animate: false,
animateDuration: "slow",
animateEasing: "swing",
aspectRatio: false,
autoHide: false,
containment: false,
ghost: false,
grid: false,
handles: "e,s,se",
helper: false,
maxHeight: null,
maxWidth: null,
minHeight: 10,
minWidth: 10,
// See #7960
zIndex: 90,
// callbacks
resize: null,
start: null,
stop: null
},
_create: function() {
var n, i, handle, axis, hname,
that = this,
o = this.options;
this.element.addClass("ui-resizable");
$.extend(this, {
_aspectRatio: !!(o.aspectRatio),
aspectRatio: o.aspectRatio,
originalElement: this.element,
_proportionallyResizeElements: [],
_helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
});
//Wrap the element if it cannot hold child nodes
if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {
//Create a wrapper element and set the wrapper to the new current internal element
this.element.wrap(
$("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({
position: this.element.css("position"),
width: this.element.outerWidth(),
height: this.element.outerHeight(),
top: this.element.css("top"),
left: this.element.css("left")
})
);
//Overwrite the original this.element
this.element = this.element.parent().data(
"ui-resizable", this.element.data("ui-resizable")
);
this.elementIsWrapper = true;
//Move margins to the wrapper
this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") });
this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});
//Prevent Safari textarea resize
this.originalResizeStyle = this.originalElement.css("resize");
this.originalElement.css("resize", "none");
//Push the actual element to our proportionallyResize internal array
this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" }));
// avoid IE jump (hard set the margin)
this.originalElement.css({ margin: this.originalElement.css("margin") });
// fix handlers offset
this._proportionallyResize();
}
this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" });
if(this.handles.constructor === String) {
if ( this.handles === "all") {
this.handles = "n,e,s,w,se,sw,ne,nw";
}
n = this.handles.split(",");
this.handles = {};
for(i = 0; i < n.length; i++) {
handle = $.trim(n[i]);
hname = "ui-resizable-"+handle;
axis = $("<div class='ui-resizable-handle " + hname + "'></div>");
// Apply zIndex to all handles - see #7960
axis.css({ zIndex: o.zIndex });
//TODO : What's going on here?
if ("se" === handle) {
axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se");
}
//Insert into internal handles object and append to element
this.handles[handle] = ".ui-resizable-"+handle;
this.element.append(axis);
}
}
this._renderAxis = function(target) {
var i, axis, padPos, padWrapper;
target = target || this.element;
for(i in this.handles) {
if(this.handles[i].constructor === String) {
this.handles[i] = $(this.handles[i], this.element).show();
}
//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
axis = $(this.handles[i], this.element);
//Checking the correct pad and border
padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();
//The padding type i have to apply...
padPos = [ "padding",
/ne|nw|n/.test(i) ? "Top" :
/se|sw|s/.test(i) ? "Bottom" :
/^e$/.test(i) ? "Right" : "Left" ].join("");
target.css(padPos, padWrapper);
this._proportionallyResize();
}
//TODO: What's that good for? There's not anything to be executed left
if(!$(this.handles[i]).length) {
continue;
}
}
};
//TODO: make renderAxis a prototype function
this._renderAxis(this.element);
this._handles = $(".ui-resizable-handle", this.element)
.disableSelection();
//Matching axis name
this._handles.mouseover(function() {
if (!that.resizing) {
if (this.className) {
axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
}
//Axis, default = se
that.axis = axis && axis[1] ? axis[1] : "se";
}
});
//If we want to auto hide the elements
if (o.autoHide) {
this._handles.hide();
$(this.element)
.addClass("ui-resizable-autohide")
.mouseenter(function() {
if (o.disabled) {
return;
}
$(this).removeClass("ui-resizable-autohide");
that._handles.show();
})
.mouseleave(function(){
if (o.disabled) {
return;
}
if (!that.resizing) {
$(this).addClass("ui-resizable-autohide");
that._handles.hide();
}
});
}
//Initialize the mouse interaction
this._mouseInit();
},
_destroy: function() {
this._mouseDestroy();
var wrapper,
_destroy = function(exp) {
$(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
.removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove();
};
//TODO: Unwrap at same DOM position
if (this.elementIsWrapper) {
_destroy(this.element);
wrapper = this.element;
this.originalElement.css({
position: wrapper.css("position"),
width: wrapper.outerWidth(),
height: wrapper.outerHeight(),
top: wrapper.css("top"),
left: wrapper.css("left")
}).insertAfter( wrapper );
wrapper.remove();
}
this.originalElement.css("resize", this.originalResizeStyle);
_destroy(this.originalElement);
return this;
},
_mouseCapture: function(event) {
var i, handle,
capture = false;
for (i in this.handles) {
handle = $(this.handles[i])[0];
if (handle === event.target || $.contains(handle, event.target)) {
capture = true;
}
}
return !this.options.disabled && capture;
},
_mouseStart: function(event) {
var curleft, curtop, cursor,
o = this.options,
iniPos = this.element.position(),
el = this.element;
this.resizing = true;
// bugfix for http://dev.jquery.com/ticket/1749
if ( (/absolute/).test( el.css("position") ) ) {
el.css({ position: "absolute", top: el.css("top"), left: el.css("left") });
} else if (el.is(".ui-draggable")) {
el.css({ position: "absolute", top: iniPos.top, left: iniPos.left });
}
this._renderProxy();
curleft = num(this.helper.css("left"));
curtop = num(this.helper.css("top"));
if (o.containment) {
curleft += $(o.containment).scrollLeft() || 0;
curtop += $(o.containment).scrollTop() || 0;
}
//Store needed variables
this.offset = this.helper.offset();
this.position = { left: curleft, top: curtop };
this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
this.originalPosition = { left: curleft, top: curtop };
this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
this.originalMousePosition = { left: event.pageX, top: event.pageY };
//Aspect Ratio
this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);
cursor = $(".ui-resizable-" + this.axis).css("cursor");
$("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor);
el.addClass("ui-resizable-resizing");
this._propagate("start", event);
return true;
},
_mouseDrag: function(event) {
//Increase performance, avoid regex
var data,
el = this.helper, props = {},
smp = this.originalMousePosition,
a = this.axis,
prevTop = this.position.top,
prevLeft = this.position.left,
prevWidth = this.size.width,
prevHeight = this.size.height,
dx = (event.pageX-smp.left)||0,
dy = (event.pageY-smp.top)||0,
trigger = this._change[a];
if (!trigger) {
return false;
}
// Calculate the attrs that will be change
data = trigger.apply(this, [event, dx, dy]);
// Put this in the mouseDrag handler since the user can start pressing shift while resizing
this._updateVirtualBoundaries(event.shiftKey);
if (this._aspectRatio || event.shiftKey) {
data = this._updateRatio(data, event);
}
data = this._respectSize(data, event);
this._updateCache(data);
// plugins callbacks need to be called first
this._propagate("resize", event);
if (this.position.top !== prevTop) {
props.top = this.position.top + "px";
}
if (this.position.left !== prevLeft) {
props.left = this.position.left + "px";
}
if (this.size.width !== prevWidth) {
props.width = this.size.width + "px";
}
if (this.size.height !== prevHeight) {
props.height = this.size.height + "px";
}
el.css(props);
if (!this._helper && this._proportionallyResizeElements.length) {
this._proportionallyResize();
}
// Call the user callback if the element was resized
if ( ! $.isEmptyObject(props) ) {
this._trigger("resize", event, this.ui());
}
return false;
},
_mouseStop: function(event) {
this.resizing = false;
var pr, ista, soffseth, soffsetw, s, left, top,
o = this.options, that = this;
if(this._helper) {
pr = this._proportionallyResizeElements;
ista = pr.length && (/textarea/i).test(pr[0].nodeName);
soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height;
soffsetw = ista ? 0 : that.sizeDiff.width;
s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) };
left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null;
top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
if (!o.animate) {
this.element.css($.extend(s, { top: top, left: left }));
}
that.helper.height(that.size.height);
that.helper.width(that.size.width);
if (this._helper && !o.animate) {
this._proportionallyResize();
}
}
$("body").css("cursor", "auto");
this.element.removeClass("ui-resizable-resizing");
this._propagate("stop", event);
if (this._helper) {
this.helper.remove();
}
return false;
},
_updateVirtualBoundaries: function(forceAspectRatio) {
var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
o = this.options;
b = {
minWidth: isNumber(o.minWidth) ? o.minWidth : 0,
maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity,
minHeight: isNumber(o.minHeight) ? o.minHeight : 0,
maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity
};
if(this._aspectRatio || forceAspectRatio) {
// We want to create an enclosing box whose aspect ration is the requested one
// First, compute the "projected" size for each dimension based on the aspect ratio and other dimension
pMinWidth = b.minHeight * this.aspectRatio;
pMinHeight = b.minWidth / this.aspectRatio;
pMaxWidth = b.maxHeight * this.aspectRatio;
pMaxHeight = b.maxWidth / this.aspectRatio;
if(pMinWidth > b.minWidth) {
b.minWidth = pMinWidth;
}
if(pMinHeight > b.minHeight) {
b.minHeight = pMinHeight;
}
if(pMaxWidth < b.maxWidth) {
b.maxWidth = pMaxWidth;
}
if(pMaxHeight < b.maxHeight) {
b.maxHeight = pMaxHeight;
}
}
this._vBoundaries = b;
},
_updateCache: function(data) {
this.offset = this.helper.offset();
if (isNumber(data.left)) {
this.position.left = data.left;
}
if (isNumber(data.top)) {
this.position.top = data.top;
}
if (isNumber(data.height)) {
this.size.height = data.height;
}
if (isNumber(data.width)) {
this.size.width = data.width;
}
},
_updateRatio: function( data ) {
var cpos = this.position,
csize = this.size,
a = this.axis;
if (isNumber(data.height)) {
data.width = (data.height * this.aspectRatio);
} else if (isNumber(data.width)) {
data.height = (data.width / this.aspectRatio);
}
if (a === "sw") {
data.left = cpos.left + (csize.width - data.width);
data.top = null;
}
if (a === "nw") {
data.top = cpos.top + (csize.height - data.height);
data.left = cpos.left + (csize.width - data.width);
}
return data;
},
_respectSize: function( data ) {
var o = this._vBoundaries,
a = this.axis,
ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height),
dw = this.originalPosition.left + this.originalSize.width,
dh = this.position.top + this.size.height,
cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
if (isminw) {
data.width = o.minWidth;
}
if (isminh) {
data.height = o.minHeight;
}
if (ismaxw) {
data.width = o.maxWidth;
}
if (ismaxh) {
data.height = o.maxHeight;
}
if (isminw && cw) {
data.left = dw - o.minWidth;
}
if (ismaxw && cw) {
data.left = dw - o.maxWidth;
}
if (isminh && ch) {
data.top = dh - o.minHeight;
}
if (ismaxh && ch) {
data.top = dh - o.maxHeight;
}
// fixing jump error on top/left - bug #2330
if (!data.width && !data.height && !data.left && data.top) {
data.top = null;
} else if (!data.width && !data.height && !data.top && data.left) {
data.left = null;
}
return data;
},
_proportionallyResize: function() {
if (!this._proportionallyResizeElements.length) {
return;
}
var i, j, borders, paddings, prel,
element = this.helper || this.element;
for ( i=0; i < this._proportionallyResizeElements.length; i++) {
prel = this._proportionallyResizeElements[i];
if (!this.borderDif) {
this.borderDif = [];
borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")];
paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")];
for ( j = 0; j < borders.length; j++ ) {
this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 );
}
}
prel.css({
height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
});
}
},
_renderProxy: function() {
var el = this.element, o = this.options;
this.elementOffset = el.offset();
if(this._helper) {
this.helper = this.helper || $("<div style='overflow:hidden;'></div>");
this.helper.addClass(this._helper).css({
width: this.element.outerWidth() - 1,
height: this.element.outerHeight() - 1,
position: "absolute",
left: this.elementOffset.left +"px",
top: this.elementOffset.top +"px",
zIndex: ++o.zIndex //TODO: Don't modify option
});
this.helper
.appendTo("body")
.disableSelection();
} else {
this.helper = this.element;
}
},
_change: {
e: function(event, dx) {
return { width: this.originalSize.width + dx };
},
w: function(event, dx) {
var cs = this.originalSize, sp = this.originalPosition;
return { left: sp.left + dx, width: cs.width - dx };
},
n: function(event, dx, dy) {
var cs = this.originalSize, sp = this.originalPosition;
return { top: sp.top + dy, height: cs.height - dy };
},
s: function(event, dx, dy) {
return { height: this.originalSize.height + dy };
},
se: function(event, dx, dy) {
return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
},
sw: function(event, dx, dy) {
return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
},
ne: function(event, dx, dy) {
return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
},
nw: function(event, dx, dy) {
return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
}
},
_propagate: function(n, event) {
$.ui.plugin.call(this, n, [event, this.ui()]);
(n !== "resize" && this._trigger(n, event, this.ui()));
},
plugins: {},
ui: function() {
return {
originalElement: this.originalElement,
element: this.element,
helper: this.helper,
position: this.position,
size: this.size,
originalSize: this.originalSize,
originalPosition: this.originalPosition
};
}
});
/*
* Resizable Extensions
*/
$.ui.plugin.add("resizable", "animate", {
stop: function( event ) {
var that = $(this).data("ui-resizable"),
o = that.options,
pr = that._proportionallyResizeElements,
ista = pr.length && (/textarea/i).test(pr[0].nodeName),
soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height,
soffsetw = ista ? 0 : that.sizeDiff.width,
style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) },
left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null,
top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null;
that.element.animate(
$.extend(style, top && left ? { top: top, left: left } : {}), {
duration: o.animateDuration,
easing: o.animateEasing,
step: function() {
var data = {
width: parseInt(that.element.css("width"), 10),
height: parseInt(that.element.css("height"), 10),
top: parseInt(that.element.css("top"), 10),
left: parseInt(that.element.css("left"), 10)
};
if (pr && pr.length) {
$(pr[0]).css({ width: data.width, height: data.height });
}
// propagating resize, and updating values for each animation step
that._updateCache(data);
that._propagate("resize", event);
}
}
);
}
});
$.ui.plugin.add("resizable", "containment", {
start: function() {
var element, p, co, ch, cw, width, height,
that = $(this).data("ui-resizable"),
o = that.options,
el = that.element,
oc = o.containment,
ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
if (!ce) {
return;
}
that.containerElement = $(ce);
if (/document/.test(oc) || oc === document) {
that.containerOffset = { left: 0, top: 0 };
that.containerPosition = { left: 0, top: 0 };
that.parentData = {
element: $(document), left: 0, top: 0,
width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
};
}
// i'm a node, so compute top, left, right, bottom
else {
element = $(ce);
p = [];
$([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });
that.containerOffset = element.offset();
that.containerPosition = element.position();
that.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };
co = that.containerOffset;
ch = that.containerSize.height;
cw = that.containerSize.width;
width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw );
height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);
that.parentData = {
element: ce, left: co.left, top: co.top, width: width, height: height
};
}
},
resize: function( event ) {
var woset, hoset, isParent, isOffsetRelative,
that = $(this).data("ui-resizable"),
o = that.options,
co = that.containerOffset, cp = that.position,
pRatio = that._aspectRatio || event.shiftKey,
cop = { top:0, left:0 }, ce = that.containerElement;
if (ce[0] !== document && (/static/).test(ce.css("position"))) {
cop = co;
}
if (cp.left < (that._helper ? co.left : 0)) {
that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left));
if (pRatio) {
that.size.height = that.size.width / that.aspectRatio;
}
that.position.left = o.helper ? co.left : 0;
}
if (cp.top < (that._helper ? co.top : 0)) {
that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top);
if (pRatio) {
that.size.width = that.size.height * that.aspectRatio;
}
that.position.top = that._helper ? co.top : 0;
}
that.offset.left = that.parentData.left+that.position.left;
that.offset.top = that.parentData.top+that.position.top;
woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width );
hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height );
isParent = that.containerElement.get(0) === that.element.parent().get(0);
isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position"));
if(isParent && isOffsetRelative) {
woset -= that.parentData.left;
}
if (woset + that.size.width >= that.parentData.width) {
that.size.width = that.parentData.width - woset;
if (pRatio) {
that.size.height = that.size.width / that.aspectRatio;
}
}
if (hoset + that.size.height >= that.parentData.height) {
that.size.height = that.parentData.height - hoset;
if (pRatio) {
that.size.width = that.size.height * that.aspectRatio;
}
}
},
stop: function(){
var that = $(this).data("ui-resizable"),
o = that.options,
co = that.containerOffset,
cop = that.containerPosition,
ce = that.containerElement,
helper = $(that.helper),
ho = helper.offset(),
w = helper.outerWidth() - that.sizeDiff.width,
h = helper.outerHeight() - that.sizeDiff.height;
if (that._helper && !o.animate && (/relative/).test(ce.css("position"))) {
$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
}
if (that._helper && !o.animate && (/static/).test(ce.css("position"))) {
$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
}
}
});
$.ui.plugin.add("resizable", "alsoResize", {
start: function () {
var that = $(this).data("ui-resizable"),
o = that.options,
_store = function (exp) {
$(exp).each(function() {
var el = $(this);
el.data("ui-resizable-alsoresize", {
width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10)
});
});
};
if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) {
if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); }
else { $.each(o.alsoResize, function (exp) { _store(exp); }); }
}else{
_store(o.alsoResize);
}
},
resize: function (event, ui) {
var that = $(this).data("ui-resizable"),
o = that.options,
os = that.originalSize,
op = that.originalPosition,
delta = {
height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0,
top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0
},
_alsoResize = function (exp, c) {
$(exp).each(function() {
var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {},
css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"];
$.each(css, function (i, prop) {
var sum = (start[prop]||0) + (delta[prop]||0);
if (sum && sum >= 0) {
style[prop] = sum || null;
}
});
el.css(style);
});
};
if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) {
$.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); });
}else{
_alsoResize(o.alsoResize);
}
},
stop: function () {
$(this).removeData("resizable-alsoresize");
}
});
$.ui.plugin.add("resizable", "ghost", {
start: function() {
var that = $(this).data("ui-resizable"), o = that.options, cs = that.size;
that.ghost = that.originalElement.clone();
that.ghost
.css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 })
.addClass("ui-resizable-ghost")
.addClass(typeof o.ghost === "string" ? o.ghost : "");
that.ghost.appendTo(that.helper);
},
resize: function(){
var that = $(this).data("ui-resizable");
if (that.ghost) {
that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width });
}
},
stop: function() {
var that = $(this).data("ui-resizable");
if (that.ghost && that.helper) {
that.helper.get(0).removeChild(that.ghost.get(0));
}
}
});
$.ui.plugin.add("resizable", "grid", {
resize: function() {
var that = $(this).data("ui-resizable"),
o = that.options,
cs = that.size,
os = that.originalSize,
op = that.originalPosition,
a = that.axis,
grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid,
gridX = (grid[0]||1),
gridY = (grid[1]||1),
ox = Math.round((cs.width - os.width) / gridX) * gridX,
oy = Math.round((cs.height - os.height) / gridY) * gridY,
newWidth = os.width + ox,
newHeight = os.height + oy,
isMaxWidth = o.maxWidth && (o.maxWidth < newWidth),
isMaxHeight = o.maxHeight && (o.maxHeight < newHeight),
isMinWidth = o.minWidth && (o.minWidth > newWidth),
isMinHeight = o.minHeight && (o.minHeight > newHeight);
o.grid = grid;
if (isMinWidth) {
newWidth = newWidth + gridX;
}
if (isMinHeight) {
newHeight = newHeight + gridY;
}
if (isMaxWidth) {
newWidth = newWidth - gridX;
}
if (isMaxHeight) {
newHeight = newHeight - gridY;
}
if (/^(se|s|e)$/.test(a)) {
that.size.width = newWidth;
that.size.height = newHeight;
} else if (/^(ne)$/.test(a)) {
that.size.width = newWidth;
that.size.height = newHeight;
that.position.top = op.top - oy;
} else if (/^(sw)$/.test(a)) {
that.size.width = newWidth;
that.size.height = newHeight;
that.position.left = op.left - ox;
} else {
that.size.width = newWidth;
that.size.height = newHeight;
that.position.top = op.top - oy;
that.position.left = op.left - ox;
}
}
});
})(jQuery);
(function( $, undefined ) {
$.widget("ui.selectable", $.ui.mouse, {
version: "1.10.2",
options: {
appendTo: "body",
autoRefresh: true,
distance: 0,
filter: "*",
tolerance: "touch",
// callbacks
selected: null,
selecting: null,
start: null,
stop: null,
unselected: null,
unselecting: null
},
_create: function() {
var selectees,
that = this;
this.element.addClass("ui-selectable");
this.dragged = false;
// cache selectee children based on filter
this.refresh = function() {
selectees = $(that.options.filter, that.element[0]);
selectees.addClass("ui-selectee");
selectees.each(function() {
var $this = $(this),
pos = $this.offset();
$.data(this, "selectable-item", {
element: this,
$element: $this,
left: pos.left,
top: pos.top,
right: pos.left + $this.outerWidth(),
bottom: pos.top + $this.outerHeight(),
startselected: false,
selected: $this.hasClass("ui-selected"),
selecting: $this.hasClass("ui-selecting"),
unselecting: $this.hasClass("ui-unselecting")
});
});
};
this.refresh();
this.selectees = selectees.addClass("ui-selectee");
this._mouseInit();
this.helper = $("<div class='ui-selectable-helper'></div>");
},
_destroy: function() {
this.selectees
.removeClass("ui-selectee")
.removeData("selectable-item");
this.element
.removeClass("ui-selectable ui-selectable-disabled");
this._mouseDestroy();
},
_mouseStart: function(event) {
var that = this,
options = this.options;
this.opos = [event.pageX, event.pageY];
if (this.options.disabled) {
return;
}
this.selectees = $(options.filter, this.element[0]);
this._trigger("start", event);
$(options.appendTo).append(this.helper);
// position helper (lasso)
this.helper.css({
"left": event.pageX,
"top": event.pageY,
"width": 0,
"height": 0
});
if (options.autoRefresh) {
this.refresh();
}
this.selectees.filter(".ui-selected").each(function() {
var selectee = $.data(this, "selectable-item");
selectee.startselected = true;
if (!event.metaKey && !event.ctrlKey) {
selectee.$element.removeClass("ui-selected");
selectee.selected = false;
selectee.$element.addClass("ui-unselecting");
selectee.unselecting = true;
// selectable UNSELECTING callback
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
});
$(event.target).parents().addBack().each(function() {
var doSelect,
selectee = $.data(this, "selectable-item");
if (selectee) {
doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected");
selectee.$element
.removeClass(doSelect ? "ui-unselecting" : "ui-selected")
.addClass(doSelect ? "ui-selecting" : "ui-unselecting");
selectee.unselecting = !doSelect;
selectee.selecting = doSelect;
selectee.selected = doSelect;
// selectable (UN)SELECTING callback
if (doSelect) {
that._trigger("selecting", event, {
selecting: selectee.element
});
} else {
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
return false;
}
});
},
_mouseDrag: function(event) {
this.dragged = true;
if (this.options.disabled) {
return;
}
var tmp,
that = this,
options = this.options,
x1 = this.opos[0],
y1 = this.opos[1],
x2 = event.pageX,
y2 = event.pageY;
if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; }
if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; }
this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1});
this.selectees.each(function() {
var selectee = $.data(this, "selectable-item"),
hit = false;
//prevent helper from being selected if appendTo: selectable
if (!selectee || selectee.element === that.element[0]) {
return;
}
if (options.tolerance === "touch") {
hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
} else if (options.tolerance === "fit") {
hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
}
if (hit) {
// SELECT
if (selectee.selected) {
selectee.$element.removeClass("ui-selected");
selectee.selected = false;
}
if (selectee.unselecting) {
selectee.$element.removeClass("ui-unselecting");
selectee.unselecting = false;
}
if (!selectee.selecting) {
selectee.$element.addClass("ui-selecting");
selectee.selecting = true;
// selectable SELECTING callback
that._trigger("selecting", event, {
selecting: selectee.element
});
}
} else {
// UNSELECT
if (selectee.selecting) {
if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
selectee.$element.removeClass("ui-selecting");
selectee.selecting = false;
selectee.$element.addClass("ui-selected");
selectee.selected = true;
} else {
selectee.$element.removeClass("ui-selecting");
selectee.selecting = false;
if (selectee.startselected) {
selectee.$element.addClass("ui-unselecting");
selectee.unselecting = true;
}
// selectable UNSELECTING callback
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
}
if (selectee.selected) {
if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
selectee.$element.removeClass("ui-selected");
selectee.selected = false;
selectee.$element.addClass("ui-unselecting");
selectee.unselecting = true;
// selectable UNSELECTING callback
that._trigger("unselecting", event, {
unselecting: selectee.element
});
}
}
}
});
return false;
},
_mouseStop: function(event) {
var that = this;
this.dragged = false;
$(".ui-unselecting", this.element[0]).each(function() {
var selectee = $.data(this, "selectable-item");
selectee.$element.removeClass("ui-unselecting");
selectee.unselecting = false;
selectee.startselected = false;
that._trigger("unselected", event, {
unselected: selectee.element
});
});
$(".ui-selecting", this.element[0]).each(function() {
var selectee = $.data(this, "selectable-item");
selectee.$element.removeClass("ui-selecting").addClass("ui-selected");
selectee.selecting = false;
selectee.selected = true;
selectee.startselected = true;
that._trigger("selected", event, {
selected: selectee.element
});
});
this._trigger("stop", event);
this.helper.remove();
return false;
}
});
})(jQuery);
(function( $, undefined ) {
// number of pages in a slider
// (how many times can you page up/down to go through the whole range)
var numPages = 5;
$.widget( "ui.slider", $.ui.mouse, {
version: "1.10.2",
widgetEventPrefix: "slide",
options: {
animate: false,
distance: 0,
max: 100,
min: 0,
orientation: "horizontal",
range: false,
step: 1,
value: 0,
values: null,
// callbacks
change: null,
slide: null,
start: null,
stop: null
},
_create: function() {
this._keySliding = false;
this._mouseSliding = false;
this._animateOff = true;
this._handleIndex = null;
this._detectOrientation();
this._mouseInit();
this.element
.addClass( "ui-slider" +
" ui-slider-" + this.orientation +
" ui-widget" +
" ui-widget-content" +
" ui-corner-all");
this._refresh();
this._setOption( "disabled", this.options.disabled );
this._animateOff = false;
},
_refresh: function() {
this._createRange();
this._createHandles();
this._setupEvents();
this._refreshValue();
},
_createHandles: function() {
var i, handleCount,
options = this.options,
existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
handles = [];
handleCount = ( options.values && options.values.length ) || 1;
if ( existingHandles.length > handleCount ) {
existingHandles.slice( handleCount ).remove();
existingHandles = existingHandles.slice( 0, handleCount );
}
for ( i = existingHandles.length; i < handleCount; i++ ) {
handles.push( handle );
}
this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );
this.handle = this.handles.eq( 0 );
this.handles.each(function( i ) {
$( this ).data( "ui-slider-handle-index", i );
});
},
_createRange: function() {
var options = this.options,
classes = "";
if ( options.range ) {
if ( options.range === true ) {
if ( !options.values ) {
options.values = [ this._valueMin(), this._valueMin() ];
} else if ( options.values.length && options.values.length !== 2 ) {
options.values = [ options.values[0], options.values[0] ];
} else if ( $.isArray( options.values ) ) {
options.values = options.values.slice(0);
}
}
if ( !this.range || !this.range.length ) {
this.range = $( "<div></div>" )
.appendTo( this.element );
classes = "ui-slider-range" +
// note: this isn't the most fittingly semantic framework class for this element,
// but worked best visually with a variety of themes
" ui-widget-header ui-corner-all";
} else {
this.range.removeClass( "ui-slider-range-min ui-slider-range-max" )
// Handle range switching from true to min/max
.css({
"left": "",
"bottom": ""
});
}
this.range.addClass( classes +
( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) );
} else {
this.range = $([]);
}
},
_setupEvents: function() {
var elements = this.handles.add( this.range ).filter( "a" );
this._off( elements );
this._on( elements, this._handleEvents );
this._hoverable( elements );
this._focusable( elements );
},
_destroy: function() {
this.handles.remove();
this.range.remove();
this.element
.removeClass( "ui-slider" +
" ui-slider-horizontal" +
" ui-slider-vertical" +
" ui-widget" +
" ui-widget-content" +
" ui-corner-all" );
this._mouseDestroy();
},
_mouseCapture: function( event ) {
var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
that = this,
o = this.options;
if ( o.disabled ) {
return false;
}
this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
};
this.elementOffset = this.element.offset();
position = { x: event.pageX, y: event.pageY };
normValue = this._normValueFromMouse( position );
distance = this._valueMax() - this._valueMin() + 1;
this.handles.each(function( i ) {
var thisDistance = Math.abs( normValue - that.values(i) );
if (( distance > thisDistance ) ||
( distance === thisDistance &&
(i === that._lastChangedValue || that.values(i) === o.min ))) {
distance = thisDistance;
closestHandle = $( this );
index = i;
}
});
allowed = this._start( event, index );
if ( allowed === false ) {
return false;
}
this._mouseSliding = true;
this._handleIndex = index;
closestHandle
.addClass( "ui-state-active" )
.focus();
offset = closestHandle.offset();
mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
top: event.pageY - offset.top -
( closestHandle.height() / 2 ) -
( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
};
if ( !this.handles.hasClass( "ui-state-hover" ) ) {
this._slide( event, index, normValue );
}
this._animateOff = true;
return true;
},
_mouseStart: function() {
return true;
},
_mouseDrag: function( event ) {
var position = { x: event.pageX, y: event.pageY },
normValue = this._normValueFromMouse( position );
this._slide( event, this._handleIndex, normValue );
return false;
},
_mouseStop: function( event ) {
this.handles.removeClass( "ui-state-active" );
this._mouseSliding = false;
this._stop( event, this._handleIndex );
this._change( event, this._handleIndex );
this._handleIndex = null;
this._clickOffset = null;
this._animateOff = false;
return false;
},
_detectOrientation: function() {
this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
},
_normValueFromMouse: function( position ) {
var pixelTotal,
pixelMouse,
percentMouse,
valueTotal,
valueMouse;
if ( this.orientation === "horizontal" ) {
pixelTotal = this.elementSize.width;
pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
} else {
pixelTotal = this.elementSize.height;
pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
}
percentMouse = ( pixelMouse / pixelTotal );
if ( percentMouse > 1 ) {
percentMouse = 1;
}
if ( percentMouse < 0 ) {
percentMouse = 0;
}
if ( this.orientation === "vertical" ) {
percentMouse = 1 - percentMouse;
}
valueTotal = this._valueMax() - this._valueMin();
valueMouse = this._valueMin() + percentMouse * valueTotal;
return this._trimAlignValue( valueMouse );
},
_start: function( event, index ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
return this._trigger( "start", event, uiHash );
},
_slide: function( event, index, newVal ) {
var otherVal,
newValues,
allowed;
if ( this.options.values && this.options.values.length ) {
otherVal = this.values( index ? 0 : 1 );
if ( ( this.options.values.length === 2 && this.options.range === true ) &&
( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
) {
newVal = otherVal;
}
if ( newVal !== this.values( index ) ) {
newValues = this.values();
newValues[ index ] = newVal;
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger( "slide", event, {
handle: this.handles[ index ],
value: newVal,
values: newValues
} );
otherVal = this.values( index ? 0 : 1 );
if ( allowed !== false ) {
this.values( index, newVal, true );
}
}
} else {
if ( newVal !== this.value() ) {
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger( "slide", event, {
handle: this.handles[ index ],
value: newVal
} );
if ( allowed !== false ) {
this.value( newVal );
}
}
}
},
_stop: function( event, index ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
this._trigger( "stop", event, uiHash );
},
_change: function( event, index ) {
if ( !this._keySliding && !this._mouseSliding ) {
var uiHash = {
handle: this.handles[ index ],
value: this.value()
};
if ( this.options.values && this.options.values.length ) {
uiHash.value = this.values( index );
uiHash.values = this.values();
}
//store the last changed value index for reference when handles overlap
this._lastChangedValue = index;
this._trigger( "change", event, uiHash );
}
},
value: function( newValue ) {
if ( arguments.length ) {
this.options.value = this._trimAlignValue( newValue );
this._refreshValue();
this._change( null, 0 );
return;
}
return this._value();
},
values: function( index, newValue ) {
var vals,
newValues,
i;
if ( arguments.length > 1 ) {
this.options.values[ index ] = this._trimAlignValue( newValue );
this._refreshValue();
this._change( null, index );
return;
}
if ( arguments.length ) {
if ( $.isArray( arguments[ 0 ] ) ) {
vals = this.options.values;
newValues = arguments[ 0 ];
for ( i = 0; i < vals.length; i += 1 ) {
vals[ i ] = this._trimAlignValue( newValues[ i ] );
this._change( null, i );
}
this._refreshValue();
} else {
if ( this.options.values && this.options.values.length ) {
return this._values( index );
} else {
return this.value();
}
}
} else {
return this._values();
}
},
_setOption: function( key, value ) {
var i,
valsLength = 0;
if ( key === "range" && this.options.range === true ) {
if ( value === "min" ) {
this.options.value = this._values( 0 );
this.options.values = null;
} else if ( value === "max" ) {
this.options.value = this._values( this.options.values.length-1 );
this.options.values = null;
}
}
if ( $.isArray( this.options.values ) ) {
valsLength = this.options.values.length;
}
$.Widget.prototype._setOption.apply( this, arguments );
switch ( key ) {
case "orientation":
this._detectOrientation();
this.element
.removeClass( "ui-slider-horizontal ui-slider-vertical" )
.addClass( "ui-slider-" + this.orientation );
this._refreshValue();
break;
case "value":
this._animateOff = true;
this._refreshValue();
this._change( null, 0 );
this._animateOff = false;
break;
case "values":
this._animateOff = true;
this._refreshValue();
for ( i = 0; i < valsLength; i += 1 ) {
this._change( null, i );
}
this._animateOff = false;
break;
case "min":
case "max":
this._animateOff = true;
this._refreshValue();
this._animateOff = false;
break;
case "range":
this._animateOff = true;
this._refresh();
this._animateOff = false;
break;
}
},
//internal value getter
// _value() returns value trimmed by min and max, aligned by step
_value: function() {
var val = this.options.value;
val = this._trimAlignValue( val );
return val;
},
//internal values getter
// _values() returns array of values trimmed by min and max, aligned by step
// _values( index ) returns single value trimmed by min and max, aligned by step
_values: function( index ) {
var val,
vals,
i;
if ( arguments.length ) {
val = this.options.values[ index ];
val = this._trimAlignValue( val );
return val;
} else if ( this.options.values && this.options.values.length ) {
// .slice() creates a copy of the array
// this copy gets trimmed by min and max and then returned
vals = this.options.values.slice();
for ( i = 0; i < vals.length; i+= 1) {
vals[ i ] = this._trimAlignValue( vals[ i ] );
}
return vals;
} else {
return [];
}
},
// returns the step-aligned value that val is closest to, between (inclusive) min and max
_trimAlignValue: function( val ) {
if ( val <= this._valueMin() ) {
return this._valueMin();
}
if ( val >= this._valueMax() ) {
return this._valueMax();
}
var step = ( this.options.step > 0 ) ? this.options.step : 1,
valModStep = (val - this._valueMin()) % step,
alignValue = val - valModStep;
if ( Math.abs(valModStep) * 2 >= step ) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
// Since JavaScript has problems with large floats, round
// the final value to 5 digits after the decimal point (see #4124)
return parseFloat( alignValue.toFixed(5) );
},
_valueMin: function() {
return this.options.min;
},
_valueMax: function() {
return this.options.max;
},
_refreshValue: function() {
var lastValPercent, valPercent, value, valueMin, valueMax,
oRange = this.options.range,
o = this.options,
that = this,
animate = ( !this._animateOff ) ? o.animate : false,
_set = {};
if ( this.options.values && this.options.values.length ) {
this.handles.each(function( i ) {
valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100;
_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
if ( that.options.range === true ) {
if ( that.orientation === "horizontal" ) {
if ( i === 0 ) {
that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
}
if ( i === 1 ) {
that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
}
} else {
if ( i === 0 ) {
that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
}
if ( i === 1 ) {
that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
}
}
}
lastValPercent = valPercent;
});
} else {
value = this.value();
valueMin = this._valueMin();
valueMax = this._valueMax();
valPercent = ( valueMax !== valueMin ) ?
( value - valueMin ) / ( valueMax - valueMin ) * 100 :
0;
_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
if ( oRange === "min" && this.orientation === "horizontal" ) {
this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
}
if ( oRange === "max" && this.orientation === "horizontal" ) {
this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
}
if ( oRange === "min" && this.orientation === "vertical" ) {
this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
}
if ( oRange === "max" && this.orientation === "vertical" ) {
this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
}
}
},
_handleEvents: {
keydown: function( event ) {
/*jshint maxcomplexity:25*/
var allowed, curVal, newVal, step,
index = $( event.target ).data( "ui-slider-handle-index" );
switch ( event.keyCode ) {
case $.ui.keyCode.HOME:
case $.ui.keyCode.END:
case $.ui.keyCode.PAGE_UP:
case $.ui.keyCode.PAGE_DOWN:
case $.ui.keyCode.UP:
case $.ui.keyCode.RIGHT:
case $.ui.keyCode.DOWN:
case $.ui.keyCode.LEFT:
event.preventDefault();
if ( !this._keySliding ) {
this._keySliding = true;
$( event.target ).addClass( "ui-state-active" );
allowed = this._start( event, index );
if ( allowed === false ) {
return;
}
}
break;
}
step = this.options.step;
if ( this.options.values && this.options.values.length ) {
curVal = newVal = this.values( index );
} else {
curVal = newVal = this.value();
}
switch ( event.keyCode ) {
case $.ui.keyCode.HOME:
newVal = this._valueMin();
break;
case $.ui.keyCode.END:
newVal = this._valueMax();
break;
case $.ui.keyCode.PAGE_UP:
newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) );
break;
case $.ui.keyCode.PAGE_DOWN:
newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) );
break;
case $.ui.keyCode.UP:
case $.ui.keyCode.RIGHT:
if ( curVal === this._valueMax() ) {
return;
}
newVal = this._trimAlignValue( curVal + step );
break;
case $.ui.keyCode.DOWN:
case $.ui.keyCode.LEFT:
if ( curVal === this._valueMin() ) {
return;
}
newVal = this._trimAlignValue( curVal - step );
break;
}
this._slide( event, index, newVal );
},
click: function( event ) {
event.preventDefault();
},
keyup: function( event ) {
var index = $( event.target ).data( "ui-slider-handle-index" );
if ( this._keySliding ) {
this._keySliding = false;
this._stop( event, index );
this._change( event, index );
$( event.target ).removeClass( "ui-state-active" );
}
}
}
});
}(jQuery));
(function( $, undefined ) {
/*jshint loopfunc: true */
function isOverAxis( x, reference, size ) {
return ( x > reference ) && ( x < ( reference + size ) );
}
function isFloating(item) {
return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
}
$.widget("ui.sortable", $.ui.mouse, {
version: "1.10.2",
widgetEventPrefix: "sort",
ready: false,
options: {
appendTo: "parent",
axis: false,
connectWith: false,
containment: false,
cursor: "auto",
cursorAt: false,
dropOnEmpty: true,
forcePlaceholderSize: false,
forceHelperSize: false,
grid: false,
handle: false,
helper: "original",
items: "> *",
opacity: false,
placeholder: false,
revert: false,
scroll: true,
scrollSensitivity: 20,
scrollSpeed: 20,
scope: "default",
tolerance: "intersect",
zIndex: 1000,
// callbacks
activate: null,
beforeStop: null,
change: null,
deactivate: null,
out: null,
over: null,
receive: null,
remove: null,
sort: null,
start: null,
stop: null,
update: null
},
_create: function() {
var o = this.options;
this.containerCache = {};
this.element.addClass("ui-sortable");
//Get the items
this.refresh();
//Let's determine if the items are being displayed horizontally
this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false;
//Let's determine the parent's offset
this.offset = this.element.offset();
//Initialize mouse events for interaction
this._mouseInit();
//We're ready to go
this.ready = true;
},
_destroy: function() {
this.element
.removeClass("ui-sortable ui-sortable-disabled");
this._mouseDestroy();
for ( var i = this.items.length - 1; i >= 0; i-- ) {
this.items[i].item.removeData(this.widgetName + "-item");
}
return this;
},
_setOption: function(key, value){
if ( key === "disabled" ) {
this.options[ key ] = value;
this.widget().toggleClass( "ui-sortable-disabled", !!value );
} else {
// Don't call widget base _setOption for disable as it adds ui-state-disabled class
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_mouseCapture: function(event, overrideHandle) {
var currentItem = null,
validHandle = false,
that = this;
if (this.reverting) {
return false;
}
if(this.options.disabled || this.options.type === "static") {
return false;
}
//We have to refresh the items data once first
this._refreshItems(event);
//Find out if the clicked node (or one of its parents) is a actual item in this.items
$(event.target).parents().each(function() {
if($.data(this, that.widgetName + "-item") === that) {
currentItem = $(this);
return false;
}
});
if($.data(event.target, that.widgetName + "-item") === that) {
currentItem = $(event.target);
}
if(!currentItem) {
return false;
}
if(this.options.handle && !overrideHandle) {
$(this.options.handle, currentItem).find("*").addBack().each(function() {
if(this === event.target) {
validHandle = true;
}
});
if(!validHandle) {
return false;
}
}
this.currentItem = currentItem;
this._removeCurrentsFromItems();
return true;
},
_mouseStart: function(event, overrideHandle, noActivation) {
var i, body,
o = this.options;
this.currentContainer = this;
//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
this.refreshPositions();
//Create and append the visible helper
this.helper = this._createHelper(event);
//Cache the helper size
this._cacheHelperProportions();
/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/
//Cache the margins of the original element
this._cacheMargins();
//Get the next scrolling parent
this.scrollParent = this.helper.scrollParent();
//The element's absolute position on the page minus margins
this.offset = this.currentItem.offset();
this.offset = {
top: this.offset.top - this.margins.top,
left: this.offset.left - this.margins.left
};
$.extend(this.offset, {
click: { //Where the click happened, relative to the element
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
},
parent: this._getParentOffset(),
relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
});
// Only after we got the offset, we can change the helper's position to absolute
// TODO: Still need to figure out a way to make relative sorting possible
this.helper.css("position", "absolute");
this.cssPosition = this.helper.css("position");
//Generate the original position
this.originalPosition = this._generatePosition(event);
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;
//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
//Cache the former DOM position
this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
if(this.helper[0] !== this.currentItem[0]) {
this.currentItem.hide();
}
//Create the placeholder
this._createPlaceholder();
//Set a containment if given in the options
if(o.containment) {
this._setContainment();
}
if( o.cursor && o.cursor !== "auto" ) { // cursor option
body = this.document.find( "body" );
// support: IE
this.storedCursor = body.css( "cursor" );
body.css( "cursor", o.cursor );
this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
}
if(o.opacity) { // opacity option
if (this.helper.css("opacity")) {
this._storedOpacity = this.helper.css("opacity");
}
this.helper.css("opacity", o.opacity);
}
if(o.zIndex) { // zIndex option
if (this.helper.css("zIndex")) {
this._storedZIndex = this.helper.css("zIndex");
}
this.helper.css("zIndex", o.zIndex);
}
//Prepare scrolling
if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
this.overflowOffset = this.scrollParent.offset();
}
//Call callbacks
this._trigger("start", event, this._uiHash());
//Recache the helper size
if(!this._preserveHelperProportions) {
this._cacheHelperProportions();
}
//Post "activate" events to possible containers
if( !noActivation ) {
for ( i = this.containers.length - 1; i >= 0; i-- ) {
this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
}
}
//Prepare possible droppables
if($.ui.ddmanager) {
$.ui.ddmanager.current = this;
}
if ($.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(this, event);
}
this.dragging = true;
this.helper.addClass("ui-sortable-helper");
this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
return true;
},
_mouseDrag: function(event) {
var i, item, itemElement, intersection,
o = this.options,
scrolled = false;
//Compute the helpers position
this.position = this._generatePosition(event);
this.positionAbs = this._convertPositionTo("absolute");
if (!this.lastPositionAbs) {
this.lastPositionAbs = this.positionAbs;
}
//Do scrolling
if(this.options.scroll) {
if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
} else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
}
if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
} else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
}
} else {
if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
} else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
}
if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
} else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
}
}
if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
$.ui.ddmanager.prepareOffsets(this, event);
}
}
//Regenerate the absolute position used for position checks
this.positionAbs = this._convertPositionTo("absolute");
//Set the helper position
if(!this.options.axis || this.options.axis !== "y") {
this.helper[0].style.left = this.position.left+"px";
}
if(!this.options.axis || this.options.axis !== "x") {
this.helper[0].style.top = this.position.top+"px";
}
//Rearrange
for (i = this.items.length - 1; i >= 0; i--) {
//Cache variables and intersection, continue if no intersection
item = this.items[i];
itemElement = item.item[0];
intersection = this._intersectsWithPointer(item);
if (!intersection) {
continue;
}
// Only put the placeholder inside the current Container, skip all
// items form other containers. This works because when moving
// an item from one container to another the
// currentContainer is switched before the placeholder is moved.
//
// Without this moving items in "sub-sortables" can cause the placeholder to jitter
// beetween the outer and inner container.
if (item.instance !== this.currentContainer) {
continue;
}
// cannot intersect with itself
// no useless actions that have been done before
// no action if the item moved is the parent of the item checked
if (itemElement !== this.currentItem[0] &&
this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
!$.contains(this.placeholder[0], itemElement) &&
(this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
) {
this.direction = intersection === 1 ? "down" : "up";
if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
this._rearrange(event, item);
} else {
break;
}
this._trigger("change", event, this._uiHash());
break;
}
}
//Post events to containers
this._contactContainers(event);
//Interconnect with droppables
if($.ui.ddmanager) {
$.ui.ddmanager.drag(this, event);
}
//Call callbacks
this._trigger("sort", event, this._uiHash());
this.lastPositionAbs = this.positionAbs;
return false;
},
_mouseStop: function(event, noPropagation) {
if(!event) {
return;
}
//If we are using droppables, inform the manager about the drop
if ($.ui.ddmanager && !this.options.dropBehaviour) {
$.ui.ddmanager.drop(this, event);
}
if(this.options.revert) {
var that = this,
cur = this.placeholder.offset(),
axis = this.options.axis,
animation = {};
if ( !axis || axis === "x" ) {
animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft);
}
if ( !axis || axis === "y" ) {
animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop);
}
this.reverting = true;
$(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
that._clear(event);
});
} else {
this._clear(event, noPropagation);
}
return false;
},
cancel: function() {
if(this.dragging) {
this._mouseUp({ target: null });
if(this.options.helper === "original") {
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
} else {
this.currentItem.show();
}
//Post deactivating events to containers
for (var i = this.containers.length - 1; i >= 0; i--){
this.containers[i]._trigger("deactivate", null, this._uiHash(this));
if(this.containers[i].containerCache.over) {
this.containers[i]._trigger("out", null, this._uiHash(this));
this.containers[i].containerCache.over = 0;
}
}
}
if (this.placeholder) {
//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
if(this.placeholder[0].parentNode) {
this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
}
if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
this.helper.remove();
}
$.extend(this, {
helper: null,
dragging: false,
reverting: false,
_noFinalSort: null
});
if(this.domPosition.prev) {
$(this.domPosition.prev).after(this.currentItem);
} else {
$(this.domPosition.parent).prepend(this.currentItem);
}
}
return this;
},
serialize: function(o) {
var items = this._getItemsAsjQuery(o && o.connected),
str = [];
o = o || {};
$(items).each(function() {
var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
if (res) {
str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
}
});
if(!str.length && o.key) {
str.push(o.key + "=");
}
return str.join("&");
},
toArray: function(o) {
var items = this._getItemsAsjQuery(o && o.connected),
ret = [];
o = o || {};
items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
return ret;
},
/* Be careful with the following core functions */
_intersectsWith: function(item) {
var x1 = this.positionAbs.left,
x2 = x1 + this.helperProportions.width,
y1 = this.positionAbs.top,
y2 = y1 + this.helperProportions.height,
l = item.left,
r = l + item.width,
t = item.top,
b = t + item.height,
dyClick = this.offset.click.top,
dxClick = this.offset.click.left,
isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;
if ( this.options.tolerance === "pointer" ||
this.options.forcePointerForContainers ||
(this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
) {
return isOverElement;
} else {
return (l < x1 + (this.helperProportions.width / 2) && // Right Half
x2 - (this.helperProportions.width / 2) < r && // Left Half
t < y1 + (this.helperProportions.height / 2) && // Bottom Half
y2 - (this.helperProportions.height / 2) < b ); // Top Half
}
},
_intersectsWithPointer: function(item) {
var isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
isOverElement = isOverElementHeight && isOverElementWidth,
verticalDirection = this._getDragVerticalDirection(),
horizontalDirection = this._getDragHorizontalDirection();
if (!isOverElement) {
return false;
}
return this.floating ?
( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
: ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );
},
_intersectsWithSides: function(item) {
var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
verticalDirection = this._getDragVerticalDirection(),
horizontalDirection = this._getDragHorizontalDirection();
if (this.floating && horizontalDirection) {
return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
} else {
return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
}
},
_getDragVerticalDirection: function() {
var delta = this.positionAbs.top - this.lastPositionAbs.top;
return delta !== 0 && (delta > 0 ? "down" : "up");
},
_getDragHorizontalDirection: function() {
var delta = this.positionAbs.left - this.lastPositionAbs.left;
return delta !== 0 && (delta > 0 ? "right" : "left");
},
refresh: function(event) {
this._refreshItems(event);
this.refreshPositions();
return this;
},
_connectWith: function() {
var options = this.options;
return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
},
_getItemsAsjQuery: function(connected) {
var i, j, cur, inst,
items = [],
queries = [],
connectWith = this._connectWith();
if(connectWith && connected) {
for (i = connectWith.length - 1; i >= 0; i--){
cur = $(connectWith[i]);
for ( j = cur.length - 1; j >= 0; j--){
inst = $.data(cur[j], this.widgetFullName);
if(inst && inst !== this && !inst.options.disabled) {
queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
}
}
}
}
queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);
for (i = queries.length - 1; i >= 0; i--){
queries[i][0].each(function() {
items.push(this);
});
}
return $(items);
},
_removeCurrentsFromItems: function() {
var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
this.items = $.grep(this.items, function (item) {
for (var j=0; j < list.length; j++) {
if(list[j] === item.item[0]) {
return false;
}
}
return true;
});
},
_refreshItems: function(event) {
this.items = [];
this.containers = [this];
var i, j, cur, inst, targetData, _queries, item, queriesLength,
items = this.items,
queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
connectWith = this._connectWith();
if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
for (i = connectWith.length - 1; i >= 0; i--){
cur = $(connectWith[i]);
for (j = cur.length - 1; j >= 0; j--){
inst = $.data(cur[j], this.widgetFullName);
if(inst && inst !== this && !inst.options.disabled) {
queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
this.containers.push(inst);
}
}
}
}
for (i = queries.length - 1; i >= 0; i--) {
targetData = queries[i][1];
_queries = queries[i][0];
for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
item = $(_queries[j]);
item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)
items.push({
item: item,
instance: targetData,
width: 0, height: 0,
left: 0, top: 0
});
}
}
},
refreshPositions: function(fast) {
//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
if(this.offsetParent && this.helper) {
this.offset.parent = this._getParentOffset();
}
var i, item, t, p;
for (i = this.items.length - 1; i >= 0; i--){
item = this.items[i];
//We ignore calculating positions of all connected containers when we're not over them
if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
continue;
}
t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
if (!fast) {
item.width = t.outerWidth();
item.height = t.outerHeight();
}
p = t.offset();
item.left = p.left;
item.top = p.top;
}
if(this.options.custom && this.options.custom.refreshContainers) {
this.options.custom.refreshContainers.call(this);
} else {
for (i = this.containers.length - 1; i >= 0; i--){
p = this.containers[i].element.offset();
this.containers[i].containerCache.left = p.left;
this.containers[i].containerCache.top = p.top;
this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
}
}
return this;
},
_createPlaceholder: function(that) {
that = that || this;
var className,
o = that.options;
if(!o.placeholder || o.placeholder.constructor === String) {
className = o.placeholder;
o.placeholder = {
element: function() {
var nodeName = that.currentItem[0].nodeName.toLowerCase(),
element = $( that.document[0].createElement( nodeName ) )
.addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
.removeClass("ui-sortable-helper");
if ( nodeName === "tr" ) {
// Use a high colspan to force the td to expand the full
// width of the table (browsers are smart enough to
// handle this properly)
element.append( "<td colspan='99'> </td>" );
} else if ( nodeName === "img" ) {
element.attr( "src", that.currentItem.attr( "src" ) );
}
if ( !className ) {
element.css( "visibility", "hidden" );
}
return element;
},
update: function(container, p) {
// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
if(className && !o.forcePlaceholderSize) {
return;
}
//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
}
};
}
//Create the placeholder
that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
//Append it after the actual current item
that.currentItem.after(that.placeholder);
//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
o.placeholder.update(that, that.placeholder);
},
_contactContainers: function(event) {
var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating,
innermostContainer = null,
innermostIndex = null;
// get innermost container that intersects with item
for (i = this.containers.length - 1; i >= 0; i--) {
// never consider a container that's located within the item itself
if($.contains(this.currentItem[0], this.containers[i].element[0])) {
continue;
}
if(this._intersectsWith(this.containers[i].containerCache)) {
// if we've already found a container and it's more "inner" than this, then continue
if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
continue;
}
innermostContainer = this.containers[i];
innermostIndex = i;
} else {
// container doesn't intersect. trigger "out" event if necessary
if(this.containers[i].containerCache.over) {
this.containers[i]._trigger("out", event, this._uiHash(this));
this.containers[i].containerCache.over = 0;
}
}
}
// if no intersecting containers found, return
if(!innermostContainer) {
return;
}
// move the item into the container if it's not there already
if(this.containers.length === 1) {
if (!this.containers[innermostIndex].containerCache.over) {
this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
this.containers[innermostIndex].containerCache.over = 1;
}
} else {
//When entering a new container, we will find the item with the least distance and append our item near it
dist = 10000;
itemWithLeastDistance = null;
floating = innermostContainer.floating || isFloating(this.currentItem);
posProperty = floating ? "left" : "top";
sizeProperty = floating ? "width" : "height";
base = this.positionAbs[posProperty] + this.offset.click[posProperty];
for (j = this.items.length - 1; j >= 0; j--) {
if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
continue;
}
if(this.items[j].item[0] === this.currentItem[0]) {
continue;
}
if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) {
continue;
}
cur = this.items[j].item.offset()[posProperty];
nearBottom = false;
if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){
nearBottom = true;
cur += this.items[j][sizeProperty];
}
if(Math.abs(cur - base) < dist) {
dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
this.direction = nearBottom ? "up": "down";
}
}
//Check if dropOnEmpty is enabled
if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
return;
}
if(this.currentContainer === this.containers[innermostIndex]) {
return;
}
itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
this._trigger("change", event, this._uiHash());
this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
this.currentContainer = this.containers[innermostIndex];
//Update the placeholder
this.options.placeholder.update(this.currentContainer, this.placeholder);
this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
this.containers[innermostIndex].containerCache.over = 1;
}
},
_createHelper: function(event) {
var o = this.options,
helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);
//Add the helper to the DOM if that didn't happen already
if(!helper.parents("body").length) {
$(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
}
if(helper[0] === this.currentItem[0]) {
this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
}
if(!helper[0].style.width || o.forceHelperSize) {
helper.width(this.currentItem.width());
}
if(!helper[0].style.height || o.forceHelperSize) {
helper.height(this.currentItem.height());
}
return helper;
},
_adjustOffsetFromHelper: function(obj) {
if (typeof obj === "string") {
obj = obj.split(" ");
}
if ($.isArray(obj)) {
obj = {left: +obj[0], top: +obj[1] || 0};
}
if ("left" in obj) {
this.offset.click.left = obj.left + this.margins.left;
}
if ("right" in obj) {
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
}
if ("top" in obj) {
this.offset.click.top = obj.top + this.margins.top;
}
if ("bottom" in obj) {
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
}
},
_getParentOffset: function() {
//Get the offsetParent and cache its position
this.offsetParent = this.helper.offsetParent();
var po = this.offsetParent.offset();
// This is a special case where we need to modify a offset calculated on start, since the following happened:
// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
// the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
po.left += this.scrollParent.scrollLeft();
po.top += this.scrollParent.scrollTop();
}
// This needs to be actually done for all browsers, since pageX/pageY includes this information
// with an ugly IE fix
if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
po = { top: 0, left: 0 };
}
return {
top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
};
},
_getRelativeOffset: function() {
if(this.cssPosition === "relative") {
var p = this.currentItem.position();
return {
top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
};
} else {
return { top: 0, left: 0 };
}
},
_cacheMargins: function() {
this.margins = {
left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
};
},
_cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},
_setContainment: function() {
var ce, co, over,
o = this.options;
if(o.containment === "parent") {
o.containment = this.helper[0].parentNode;
}
if(o.containment === "document" || o.containment === "window") {
this.containment = [
0 - this.offset.relative.left - this.offset.parent.left,
0 - this.offset.relative.top - this.offset.parent.top,
$(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
];
}
if(!(/^(document|window|parent)$/).test(o.containment)) {
ce = $(o.containment)[0];
co = $(o.containment).offset();
over = ($(ce).css("overflow") !== "hidden");
this.containment = [
co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
];
}
},
_convertPositionTo: function(d, pos) {
if(!pos) {
pos = this.position;
}
var mod = d === "absolute" ? 1 : -1,
scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
return {
top: (
pos.top + // The absolute mouse position
this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
),
left: (
pos.left + // The absolute mouse position
this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
)
};
},
_generatePosition: function(event) {
var top, left,
o = this.options,
pageX = event.pageX,
pageY = event.pageY,
scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
// This is another very weird special case that only happens for relative elements:
// 1. If the css position is relative
// 2. and the scroll parent is the document or similar to the offset parent
// we have to refresh the relative offset during the scroll so there are no jumps
if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) {
this.offset.relative = this._getRelativeOffset();
}
/*
* - Position constraining -
* Constrain the position to a mix of grid, containment.
*/
if(this.originalPosition) { //If we are not dragging yet, we won't check for options
if(this.containment) {
if(event.pageX - this.offset.click.left < this.containment[0]) {
pageX = this.containment[0] + this.offset.click.left;
}
if(event.pageY - this.offset.click.top < this.containment[1]) {
pageY = this.containment[1] + this.offset.click.top;
}
if(event.pageX - this.offset.click.left > this.containment[2]) {
pageX = this.containment[2] + this.offset.click.left;
}
if(event.pageY - this.offset.click.top > this.containment[3]) {
pageY = this.containment[3] + this.offset.click.top;
}
}
if(o.grid) {
top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
}
}
return {
top: (
pageY - // The absolute mouse position
this.offset.click.top - // Click offset (relative to the element)
this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
),
left: (
pageX - // The absolute mouse position
this.offset.click.left - // Click offset (relative to the element)
this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
)
};
},
_rearrange: function(event, i, a, hardRefresh) {
a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));
//Various things done here to improve the performance:
// 1. we create a setTimeout, that calls refreshPositions
// 2. on the instance, we have a counter variable, that get's higher after every append
// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
// 4. this lets only the last addition to the timeout stack through
this.counter = this.counter ? ++this.counter : 1;
var counter = this.counter;
this._delay(function() {
if(counter === this.counter) {
this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
}
});
},
_clear: function(event, noPropagation) {
this.reverting = false;
// We delay all events that have to be triggered to after the point where the placeholder has been removed and
// everything else normalized again
var i,
delayedTriggers = [];
// We first have to update the dom position of the actual currentItem
// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
if(!this._noFinalSort && this.currentItem.parent().length) {
this.placeholder.before(this.currentItem);
}
this._noFinalSort = null;
if(this.helper[0] === this.currentItem[0]) {
for(i in this._storedCSS) {
if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
this._storedCSS[i] = "";
}
}
this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
} else {
this.currentItem.show();
}
if(this.fromOutside && !noPropagation) {
delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
}
if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
}
// Check if the items Container has Changed and trigger appropriate
// events.
if (this !== this.currentContainer) {
if(!noPropagation) {
delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
}
}
//Post events to containers
for (i = this.containers.length - 1; i >= 0; i--){
if(!noPropagation) {
delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i]));
}
if(this.containers[i].containerCache.over) {
delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i]));
this.containers[i].containerCache.over = 0;
}
}
//Do what was originally in plugins
if ( this.storedCursor ) {
this.document.find( "body" ).css( "cursor", this.storedCursor );
this.storedStylesheet.remove();
}
if(this._storedOpacity) {
this.helper.css("opacity", this._storedOpacity);
}
if(this._storedZIndex) {
this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
}
this.dragging = false;
if(this.cancelHelperRemoval) {
if(!noPropagation) {
this._trigger("beforeStop", event, this._uiHash());
for (i=0; i < delayedTriggers.length; i++) {
delayedTriggers[i].call(this, event);
} //Trigger all delayed events
this._trigger("stop", event, this._uiHash());
}
this.fromOutside = false;
return false;
}
if(!noPropagation) {
this._trigger("beforeStop", event, this._uiHash());
}
//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
if(this.helper[0] !== this.currentItem[0]) {
this.helper.remove();
}
this.helper = null;
if(!noPropagation) {
for (i=0; i < delayedTriggers.length; i++) {
delayedTriggers[i].call(this, event);
} //Trigger all delayed events
this._trigger("stop", event, this._uiHash());
}
this.fromOutside = false;
return true;
},
_trigger: function() {
if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
this.cancel();
}
},
_uiHash: function(_inst) {
var inst = _inst || this;
return {
helper: inst.helper,
placeholder: inst.placeholder || $([]),
position: inst.position,
originalPosition: inst.originalPosition,
offset: inst.positionAbs,
item: inst.currentItem,
sender: _inst ? _inst.element : null
};
}
});
})(jQuery);
(function( $ ) {
function modifier( fn ) {
return function() {
var previous = this.element.val();
fn.apply( this, arguments );
this._refresh();
if ( previous !== this.element.val() ) {
this._trigger( "change" );
}
};
}
$.widget( "ui.spinner", {
version: "1.10.2",
defaultElement: "<input>",
widgetEventPrefix: "spin",
options: {
culture: null,
icons: {
down: "ui-icon-triangle-1-s",
up: "ui-icon-triangle-1-n"
},
incremental: true,
max: null,
min: null,
numberFormat: null,
page: 10,
step: 1,
change: null,
spin: null,
start: null,
stop: null
},
_create: function() {
// handle string values that need to be parsed
this._setOption( "max", this.options.max );
this._setOption( "min", this.options.min );
this._setOption( "step", this.options.step );
// format the value, but don't constrain
this._value( this.element.val(), true );
this._draw();
this._on( this._events );
this._refresh();
// turning off autocomplete prevents the browser from remembering the
// value when navigating through history, so we re-enable autocomplete
// if the page is unloaded before the widget is destroyed. #7790
this._on( this.window, {
beforeunload: function() {
this.element.removeAttr( "autocomplete" );
}
});
},
_getCreateOptions: function() {
var options = {},
element = this.element;
$.each( [ "min", "max", "step" ], function( i, option ) {
var value = element.attr( option );
if ( value !== undefined && value.length ) {
options[ option ] = value;
}
});
return options;
},
_events: {
keydown: function( event ) {
if ( this._start( event ) && this._keydown( event ) ) {
event.preventDefault();
}
},
keyup: "_stop",
focus: function() {
this.previous = this.element.val();
},
blur: function( event ) {
if ( this.cancelBlur ) {
delete this.cancelBlur;
return;
}
this._stop();
this._refresh();
if ( this.previous !== this.element.val() ) {
this._trigger( "change", event );
}
},
mousewheel: function( event, delta ) {
if ( !delta ) {
return;
}
if ( !this.spinning && !this._start( event ) ) {
return false;
}
this._spin( (delta > 0 ? 1 : -1) * this.options.step, event );
clearTimeout( this.mousewheelTimer );
this.mousewheelTimer = this._delay(function() {
if ( this.spinning ) {
this._stop( event );
}
}, 100 );
event.preventDefault();
},
"mousedown .ui-spinner-button": function( event ) {
var previous;
// We never want the buttons to have focus; whenever the user is
// interacting with the spinner, the focus should be on the input.
// If the input is focused then this.previous is properly set from
// when the input first received focus. If the input is not focused
// then we need to set this.previous based on the value before spinning.
previous = this.element[0] === this.document[0].activeElement ?
this.previous : this.element.val();
function checkFocus() {
var isActive = this.element[0] === this.document[0].activeElement;
if ( !isActive ) {
this.element.focus();
this.previous = previous;
// support: IE
// IE sets focus asynchronously, so we need to check if focus
// moved off of the input because the user clicked on the button.
this._delay(function() {
this.previous = previous;
});
}
}
// ensure focus is on (or stays on) the text field
event.preventDefault();
checkFocus.call( this );
// support: IE
// IE doesn't prevent moving focus even with event.preventDefault()
// so we set a flag to know when we should ignore the blur event
// and check (again) if focus moved off of the input.
this.cancelBlur = true;
this._delay(function() {
delete this.cancelBlur;
checkFocus.call( this );
});
if ( this._start( event ) === false ) {
return;
}
this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
},
"mouseup .ui-spinner-button": "_stop",
"mouseenter .ui-spinner-button": function( event ) {
// button will add ui-state-active if mouse was down while mouseleave and kept down
if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) {
return;
}
if ( this._start( event ) === false ) {
return false;
}
this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
},
// TODO: do we really want to consider this a stop?
// shouldn't we just stop the repeater and wait until mouseup before
// we trigger the stop event?
"mouseleave .ui-spinner-button": "_stop"
},
_draw: function() {
var uiSpinner = this.uiSpinner = this.element
.addClass( "ui-spinner-input" )
.attr( "autocomplete", "off" )
.wrap( this._uiSpinnerHtml() )
.parent()
// add buttons
.append( this._buttonHtml() );
this.element.attr( "role", "spinbutton" );
// button bindings
this.buttons = uiSpinner.find( ".ui-spinner-button" )
.attr( "tabIndex", -1 )
.button()
.removeClass( "ui-corner-all" );
// IE 6 doesn't understand height: 50% for the buttons
// unless the wrapper has an explicit height
if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) &&
uiSpinner.height() > 0 ) {
uiSpinner.height( uiSpinner.height() );
}
// disable spinner if element was already disabled
if ( this.options.disabled ) {
this.disable();
}
},
_keydown: function( event ) {
var options = this.options,
keyCode = $.ui.keyCode;
switch ( event.keyCode ) {
case keyCode.UP:
this._repeat( null, 1, event );
return true;
case keyCode.DOWN:
this._repeat( null, -1, event );
return true;
case keyCode.PAGE_UP:
this._repeat( null, options.page, event );
return true;
case keyCode.PAGE_DOWN:
this._repeat( null, -options.page, event );
return true;
}
return false;
},
_uiSpinnerHtml: function() {
return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>";
},
_buttonHtml: function() {
return "" +
"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" +
"<span class='ui-icon " + this.options.icons.up + "'>▲</span>" +
"</a>" +
"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" +
"<span class='ui-icon " + this.options.icons.down + "'>▼</span>" +
"</a>";
},
_start: function( event ) {
if ( !this.spinning && this._trigger( "start", event ) === false ) {
return false;
}
if ( !this.counter ) {
this.counter = 1;
}
this.spinning = true;
return true;
},
_repeat: function( i, steps, event ) {
i = i || 500;
clearTimeout( this.timer );
this.timer = this._delay(function() {
this._repeat( 40, steps, event );
}, i );
this._spin( steps * this.options.step, event );
},
_spin: function( step, event ) {
var value = this.value() || 0;
if ( !this.counter ) {
this.counter = 1;
}
value = this._adjustValue( value + step * this._increment( this.counter ) );
if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) {
this._value( value );
this.counter++;
}
},
_increment: function( i ) {
var incremental = this.options.incremental;
if ( incremental ) {
return $.isFunction( incremental ) ?
incremental( i ) :
Math.floor( i*i*i/50000 - i*i/500 + 17*i/200 + 1 );
}
return 1;
},
_precision: function() {
var precision = this._precisionOf( this.options.step );
if ( this.options.min !== null ) {
precision = Math.max( precision, this._precisionOf( this.options.min ) );
}
return precision;
},
_precisionOf: function( num ) {
var str = num.toString(),
decimal = str.indexOf( "." );
return decimal === -1 ? 0 : str.length - decimal - 1;
},
_adjustValue: function( value ) {
var base, aboveMin,
options = this.options;
// make sure we're at a valid step
// - find out where we are relative to the base (min or 0)
base = options.min !== null ? options.min : 0;
aboveMin = value - base;
// - round to the nearest step
aboveMin = Math.round(aboveMin / options.step) * options.step;
// - rounding is based on 0, so adjust back to our base
value = base + aboveMin;
// fix precision from bad JS floating point math
value = parseFloat( value.toFixed( this._precision() ) );
// clamp the value
if ( options.max !== null && value > options.max) {
return options.max;
}
if ( options.min !== null && value < options.min ) {
return options.min;
}
return value;
},
_stop: function( event ) {
if ( !this.spinning ) {
return;
}
clearTimeout( this.timer );
clearTimeout( this.mousewheelTimer );
this.counter = 0;
this.spinning = false;
this._trigger( "stop", event );
},
_setOption: function( key, value ) {
if ( key === "culture" || key === "numberFormat" ) {
var prevValue = this._parse( this.element.val() );
this.options[ key ] = value;
this.element.val( this._format( prevValue ) );
return;
}
if ( key === "max" || key === "min" || key === "step" ) {
if ( typeof value === "string" ) {
value = this._parse( value );
}
}
if ( key === "icons" ) {
this.buttons.first().find( ".ui-icon" )
.removeClass( this.options.icons.up )
.addClass( value.up );
this.buttons.last().find( ".ui-icon" )
.removeClass( this.options.icons.down )
.addClass( value.down );
}
this._super( key, value );
if ( key === "disabled" ) {
if ( value ) {
this.element.prop( "disabled", true );
this.buttons.button( "disable" );
} else {
this.element.prop( "disabled", false );
this.buttons.button( "enable" );
}
}
},
_setOptions: modifier(function( options ) {
this._super( options );
this._value( this.element.val() );
}),
_parse: function( val ) {
if ( typeof val === "string" && val !== "" ) {
val = window.Globalize && this.options.numberFormat ?
Globalize.parseFloat( val, 10, this.options.culture ) : +val;
}
return val === "" || isNaN( val ) ? null : val;
},
_format: function( value ) {
if ( value === "" ) {
return "";
}
return window.Globalize && this.options.numberFormat ?
Globalize.format( value, this.options.numberFormat, this.options.culture ) :
value;
},
_refresh: function() {
this.element.attr({
"aria-valuemin": this.options.min,
"aria-valuemax": this.options.max,
// TODO: what should we do with values that can't be parsed?
"aria-valuenow": this._parse( this.element.val() )
});
},
// update the value without triggering change
_value: function( value, allowAny ) {
var parsed;
if ( value !== "" ) {
parsed = this._parse( value );
if ( parsed !== null ) {
if ( !allowAny ) {
parsed = this._adjustValue( parsed );
}
value = this._format( parsed );
}
}
this.element.val( value );
this._refresh();
},
_destroy: function() {
this.element
.removeClass( "ui-spinner-input" )
.prop( "disabled", false )
.removeAttr( "autocomplete" )
.removeAttr( "role" )
.removeAttr( "aria-valuemin" )
.removeAttr( "aria-valuemax" )
.removeAttr( "aria-valuenow" );
this.uiSpinner.replaceWith( this.element );
},
stepUp: modifier(function( steps ) {
this._stepUp( steps );
}),
_stepUp: function( steps ) {
if ( this._start() ) {
this._spin( (steps || 1) * this.options.step );
this._stop();
}
},
stepDown: modifier(function( steps ) {
this._stepDown( steps );
}),
_stepDown: function( steps ) {
if ( this._start() ) {
this._spin( (steps || 1) * -this.options.step );
this._stop();
}
},
pageUp: modifier(function( pages ) {
this._stepUp( (pages || 1) * this.options.page );
}),
pageDown: modifier(function( pages ) {
this._stepDown( (pages || 1) * this.options.page );
}),
value: function( newVal ) {
if ( !arguments.length ) {
return this._parse( this.element.val() );
}
modifier( this._value ).call( this, newVal );
},
widget: function() {
return this.uiSpinner;
}
});
}( jQuery ) );
(function( $, undefined ) {
var tabId = 0,
rhash = /#.*$/;
function getNextTabId() {
return ++tabId;
}
function isLocal( anchor ) {
return anchor.hash.length > 1 &&
decodeURIComponent( anchor.href.replace( rhash, "" ) ) ===
decodeURIComponent( location.href.replace( rhash, "" ) );
}
$.widget( "ui.tabs", {
version: "1.10.2",
delay: 300,
options: {
active: null,
collapsible: false,
event: "click",
heightStyle: "content",
hide: null,
show: null,
// callbacks
activate: null,
beforeActivate: null,
beforeLoad: null,
load: null
},
_create: function() {
var that = this,
options = this.options;
this.running = false;
this.element
.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" )
.toggleClass( "ui-tabs-collapsible", options.collapsible )
// Prevent users from focusing disabled tabs via click
.delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) {
if ( $( this ).is( ".ui-state-disabled" ) ) {
event.preventDefault();
}
})
// support: IE <9
// Preventing the default action in mousedown doesn't prevent IE
// from focusing the element, so if the anchor gets focused, blur.
// We don't have to worry about focusing the previously focused
// element since clicking on a non-focusable element should focus
// the body anyway.
.delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() {
if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) {
this.blur();
}
});
this._processTabs();
options.active = this._initialActive();
// Take disabling tabs via class attribute from HTML
// into account and update option properly.
if ( $.isArray( options.disabled ) ) {
options.disabled = $.unique( options.disabled.concat(
$.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) {
return that.tabs.index( li );
})
) ).sort();
}
// check for length avoids error when initializing empty list
if ( this.options.active !== false && this.anchors.length ) {
this.active = this._findActive( options.active );
} else {
this.active = $();
}
this._refresh();
if ( this.active.length ) {
this.load( options.active );
}
},
_initialActive: function() {
var active = this.options.active,
collapsible = this.options.collapsible,
locationHash = location.hash.substring( 1 );
if ( active === null ) {
// check the fragment identifier in the URL
if ( locationHash ) {
this.tabs.each(function( i, tab ) {
if ( $( tab ).attr( "aria-controls" ) === locationHash ) {
active = i;
return false;
}
});
}
// check for a tab marked active via a class
if ( active === null ) {
active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) );
}
// no active tab, set to false
if ( active === null || active === -1 ) {
active = this.tabs.length ? 0 : false;
}
}
// handle numbers: negative, out of range
if ( active !== false ) {
active = this.tabs.index( this.tabs.eq( active ) );
if ( active === -1 ) {
active = collapsible ? false : 0;
}
}
// don't allow collapsible: false and active: false
if ( !collapsible && active === false && this.anchors.length ) {
active = 0;
}
return active;
},
_getCreateEventData: function() {
return {
tab: this.active,
panel: !this.active.length ? $() : this._getPanelForTab( this.active )
};
},
_tabKeydown: function( event ) {
/*jshint maxcomplexity:15*/
var focusedTab = $( this.document[0].activeElement ).closest( "li" ),
selectedIndex = this.tabs.index( focusedTab ),
goingForward = true;
if ( this._handlePageNav( event ) ) {
return;
}
switch ( event.keyCode ) {
case $.ui.keyCode.RIGHT:
case $.ui.keyCode.DOWN:
selectedIndex++;
break;
case $.ui.keyCode.UP:
case $.ui.keyCode.LEFT:
goingForward = false;
selectedIndex--;
break;
case $.ui.keyCode.END:
selectedIndex = this.anchors.length - 1;
break;
case $.ui.keyCode.HOME:
selectedIndex = 0;
break;
case $.ui.keyCode.SPACE:
// Activate only, no collapsing
event.preventDefault();
clearTimeout( this.activating );
this._activate( selectedIndex );
return;
case $.ui.keyCode.ENTER:
// Toggle (cancel delayed activation, allow collapsing)
event.preventDefault();
clearTimeout( this.activating );
// Determine if we should collapse or activate
this._activate( selectedIndex === this.options.active ? false : selectedIndex );
return;
default:
return;
}
// Focus the appropriate tab, based on which key was pressed
event.preventDefault();
clearTimeout( this.activating );
selectedIndex = this._focusNextTab( selectedIndex, goingForward );
// Navigating with control key will prevent automatic activation
if ( !event.ctrlKey ) {
// Update aria-selected immediately so that AT think the tab is already selected.
// Otherwise AT may confuse the user by stating that they need to activate the tab,
// but the tab will already be activated by the time the announcement finishes.
focusedTab.attr( "aria-selected", "false" );
this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" );
this.activating = this._delay(function() {
this.option( "active", selectedIndex );
}, this.delay );
}
},
_panelKeydown: function( event ) {
if ( this._handlePageNav( event ) ) {
return;
}
// Ctrl+up moves focus to the current tab
if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) {
event.preventDefault();
this.active.focus();
}
},
// Alt+page up/down moves focus to the previous/next tab (and activates)
_handlePageNav: function( event ) {
if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) {
this._activate( this._focusNextTab( this.options.active - 1, false ) );
return true;
}
if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) {
this._activate( this._focusNextTab( this.options.active + 1, true ) );
return true;
}
},
_findNextTab: function( index, goingForward ) {
var lastTabIndex = this.tabs.length - 1;
function constrain() {
if ( index > lastTabIndex ) {
index = 0;
}
if ( index < 0 ) {
index = lastTabIndex;
}
return index;
}
while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) {
index = goingForward ? index + 1 : index - 1;
}
return index;
},
_focusNextTab: function( index, goingForward ) {
index = this._findNextTab( index, goingForward );
this.tabs.eq( index ).focus();
return index;
},
_setOption: function( key, value ) {
if ( key === "active" ) {
// _activate() will handle invalid values and update this.options
this._activate( value );
return;
}
if ( key === "disabled" ) {
// don't use the widget factory's disabled handling
this._setupDisabled( value );
return;
}
this._super( key, value);
if ( key === "collapsible" ) {
this.element.toggleClass( "ui-tabs-collapsible", value );
// Setting collapsible: false while collapsed; open first panel
if ( !value && this.options.active === false ) {
this._activate( 0 );
}
}
if ( key === "event" ) {
this._setupEvents( value );
}
if ( key === "heightStyle" ) {
this._setupHeightStyle( value );
}
},
_tabId: function( tab ) {
return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId();
},
_sanitizeSelector: function( hash ) {
return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : "";
},
refresh: function() {
var options = this.options,
lis = this.tablist.children( ":has(a[href])" );
// get disabled tabs from class attribute from HTML
// this will get converted to a boolean if needed in _refresh()
options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) {
return lis.index( tab );
});
this._processTabs();
// was collapsed or no tabs
if ( options.active === false || !this.anchors.length ) {
options.active = false;
this.active = $();
// was active, but active tab is gone
} else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) {
// all remaining tabs are disabled
if ( this.tabs.length === options.disabled.length ) {
options.active = false;
this.active = $();
// activate previous tab
} else {
this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) );
}
// was active, active tab still exists
} else {
// make sure active index is correct
options.active = this.tabs.index( this.active );
}
this._refresh();
},
_refresh: function() {
this._setupDisabled( this.options.disabled );
this._setupEvents( this.options.event );
this._setupHeightStyle( this.options.heightStyle );
this.tabs.not( this.active ).attr({
"aria-selected": "false",
tabIndex: -1
});
this.panels.not( this._getPanelForTab( this.active ) )
.hide()
.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
// Make sure one tab is in the tab order
if ( !this.active.length ) {
this.tabs.eq( 0 ).attr( "tabIndex", 0 );
} else {
this.active
.addClass( "ui-tabs-active ui-state-active" )
.attr({
"aria-selected": "true",
tabIndex: 0
});
this._getPanelForTab( this.active )
.show()
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
}
},
_processTabs: function() {
var that = this;
this.tablist = this._getList()
.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
.attr( "role", "tablist" );
this.tabs = this.tablist.find( "> li:has(a[href])" )
.addClass( "ui-state-default ui-corner-top" )
.attr({
role: "tab",
tabIndex: -1
});
this.anchors = this.tabs.map(function() {
return $( "a", this )[ 0 ];
})
.addClass( "ui-tabs-anchor" )
.attr({
role: "presentation",
tabIndex: -1
});
this.panels = $();
this.anchors.each(function( i, anchor ) {
var selector, panel, panelId,
anchorId = $( anchor ).uniqueId().attr( "id" ),
tab = $( anchor ).closest( "li" ),
originalAriaControls = tab.attr( "aria-controls" );
// inline tab
if ( isLocal( anchor ) ) {
selector = anchor.hash;
panel = that.element.find( that._sanitizeSelector( selector ) );
// remote tab
} else {
panelId = that._tabId( tab );
selector = "#" + panelId;
panel = that.element.find( selector );
if ( !panel.length ) {
panel = that._createPanel( panelId );
panel.insertAfter( that.panels[ i - 1 ] || that.tablist );
}
panel.attr( "aria-live", "polite" );
}
if ( panel.length) {
that.panels = that.panels.add( panel );
}
if ( originalAriaControls ) {
tab.data( "ui-tabs-aria-controls", originalAriaControls );
}
tab.attr({
"aria-controls": selector.substring( 1 ),
"aria-labelledby": anchorId
});
panel.attr( "aria-labelledby", anchorId );
});
this.panels
.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
.attr( "role", "tabpanel" );
},
// allow overriding how to find the list for rare usage scenarios (#7715)
_getList: function() {
return this.element.find( "ol,ul" ).eq( 0 );
},
_createPanel: function( id ) {
return $( "<div>" )
.attr( "id", id )
.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
.data( "ui-tabs-destroy", true );
},
_setupDisabled: function( disabled ) {
if ( $.isArray( disabled ) ) {
if ( !disabled.length ) {
disabled = false;
} else if ( disabled.length === this.anchors.length ) {
disabled = true;
}
}
// disable tabs
for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) {
if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
$( li )
.addClass( "ui-state-disabled" )
.attr( "aria-disabled", "true" );
} else {
$( li )
.removeClass( "ui-state-disabled" )
.removeAttr( "aria-disabled" );
}
}
this.options.disabled = disabled;
},
_setupEvents: function( event ) {
var events = {
click: function( event ) {
event.preventDefault();
}
};
if ( event ) {
$.each( event.split(" "), function( index, eventName ) {
events[ eventName ] = "_eventHandler";
});
}
this._off( this.anchors.add( this.tabs ).add( this.panels ) );
this._on( this.anchors, events );
this._on( this.tabs, { keydown: "_tabKeydown" } );
this._on( this.panels, { keydown: "_panelKeydown" } );
this._focusable( this.tabs );
this._hoverable( this.tabs );
},
_setupHeightStyle: function( heightStyle ) {
var maxHeight,
parent = this.element.parent();
if ( heightStyle === "fill" ) {
maxHeight = parent.height();
maxHeight -= this.element.outerHeight() - this.element.height();
this.element.siblings( ":visible" ).each(function() {
var elem = $( this ),
position = elem.css( "position" );
if ( position === "absolute" || position === "fixed" ) {
return;
}
maxHeight -= elem.outerHeight( true );
});
this.element.children().not( this.panels ).each(function() {
maxHeight -= $( this ).outerHeight( true );
});
this.panels.each(function() {
$( this ).height( Math.max( 0, maxHeight -
$( this ).innerHeight() + $( this ).height() ) );
})
.css( "overflow", "auto" );
} else if ( heightStyle === "auto" ) {
maxHeight = 0;
this.panels.each(function() {
maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
}).height( maxHeight );
}
},
_eventHandler: function( event ) {
var options = this.options,
active = this.active,
anchor = $( event.currentTarget ),
tab = anchor.closest( "li" ),
clickedIsActive = tab[ 0 ] === active[ 0 ],
collapsing = clickedIsActive && options.collapsible,
toShow = collapsing ? $() : this._getPanelForTab( tab ),
toHide = !active.length ? $() : this._getPanelForTab( active ),
eventData = {
oldTab: active,
oldPanel: toHide,
newTab: collapsing ? $() : tab,
newPanel: toShow
};
event.preventDefault();
if ( tab.hasClass( "ui-state-disabled" ) ||
// tab is already loading
tab.hasClass( "ui-tabs-loading" ) ||
// can't switch durning an animation
this.running ||
// click on active header, but not collapsible
( clickedIsActive && !options.collapsible ) ||
// allow canceling activation
( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
return;
}
options.active = collapsing ? false : this.tabs.index( tab );
this.active = clickedIsActive ? $() : tab;
if ( this.xhr ) {
this.xhr.abort();
}
if ( !toHide.length && !toShow.length ) {
$.error( "jQuery UI Tabs: Mismatching fragment identifier." );
}
if ( toShow.length ) {
this.load( this.tabs.index( tab ), event );
}
this._toggle( event, eventData );
},
// handles show/hide for selecting tabs
_toggle: function( event, eventData ) {
var that = this,
toShow = eventData.newPanel,
toHide = eventData.oldPanel;
this.running = true;
function complete() {
that.running = false;
that._trigger( "activate", event, eventData );
}
function show() {
eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );
if ( toShow.length && that.options.show ) {
that._show( toShow, that.options.show, complete );
} else {
toShow.show();
complete();
}
}
// start out by hiding, then showing, then completing
if ( toHide.length && this.options.hide ) {
this._hide( toHide, this.options.hide, function() {
eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
show();
});
} else {
eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
toHide.hide();
show();
}
toHide.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
eventData.oldTab.attr( "aria-selected", "false" );
// If we're switching tabs, remove the old tab from the tab order.
// If we're opening from collapsed state, remove the previous tab from the tab order.
// If we're collapsing, then keep the collapsing tab in the tab order.
if ( toShow.length && toHide.length ) {
eventData.oldTab.attr( "tabIndex", -1 );
} else if ( toShow.length ) {
this.tabs.filter(function() {
return $( this ).attr( "tabIndex" ) === 0;
})
.attr( "tabIndex", -1 );
}
toShow.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
eventData.newTab.attr({
"aria-selected": "true",
tabIndex: 0
});
},
_activate: function( index ) {
var anchor,
active = this._findActive( index );
// trying to activate the already active panel
if ( active[ 0 ] === this.active[ 0 ] ) {
return;
}
// trying to collapse, simulate a click on the current active header
if ( !active.length ) {
active = this.active;
}
anchor = active.find( ".ui-tabs-anchor" )[ 0 ];
this._eventHandler({
target: anchor,
currentTarget: anchor,
preventDefault: $.noop
});
},
_findActive: function( index ) {
return index === false ? $() : this.tabs.eq( index );
},
_getIndex: function( index ) {
// meta-function to give users option to provide a href string instead of a numerical index.
if ( typeof index === "string" ) {
index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) );
}
return index;
},
_destroy: function() {
if ( this.xhr ) {
this.xhr.abort();
}
this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );
this.tablist
.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
.removeAttr( "role" );
this.anchors
.removeClass( "ui-tabs-anchor" )
.removeAttr( "role" )
.removeAttr( "tabIndex" )
.removeUniqueId();
this.tabs.add( this.panels ).each(function() {
if ( $.data( this, "ui-tabs-destroy" ) ) {
$( this ).remove();
} else {
$( this )
.removeClass( "ui-state-default ui-state-active ui-state-disabled " +
"ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" )
.removeAttr( "tabIndex" )
.removeAttr( "aria-live" )
.removeAttr( "aria-busy" )
.removeAttr( "aria-selected" )
.removeAttr( "aria-labelledby" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-expanded" )
.removeAttr( "role" );
}
});
this.tabs.each(function() {
var li = $( this ),
prev = li.data( "ui-tabs-aria-controls" );
if ( prev ) {
li
.attr( "aria-controls", prev )
.removeData( "ui-tabs-aria-controls" );
} else {
li.removeAttr( "aria-controls" );
}
});
this.panels.show();
if ( this.options.heightStyle !== "content" ) {
this.panels.css( "height", "" );
}
},
enable: function( index ) {
var disabled = this.options.disabled;
if ( disabled === false ) {
return;
}
if ( index === undefined ) {
disabled = false;
} else {
index = this._getIndex( index );
if ( $.isArray( disabled ) ) {
disabled = $.map( disabled, function( num ) {
return num !== index ? num : null;
});
} else {
disabled = $.map( this.tabs, function( li, num ) {
return num !== index ? num : null;
});
}
}
this._setupDisabled( disabled );
},
disable: function( index ) {
var disabled = this.options.disabled;
if ( disabled === true ) {
return;
}
if ( index === undefined ) {
disabled = true;
} else {
index = this._getIndex( index );
if ( $.inArray( index, disabled ) !== -1 ) {
return;
}
if ( $.isArray( disabled ) ) {
disabled = $.merge( [ index ], disabled ).sort();
} else {
disabled = [ index ];
}
}
this._setupDisabled( disabled );
},
load: function( index, event ) {
index = this._getIndex( index );
var that = this,
tab = this.tabs.eq( index ),
anchor = tab.find( ".ui-tabs-anchor" ),
panel = this._getPanelForTab( tab ),
eventData = {
tab: tab,
panel: panel
};
// not remote
if ( isLocal( anchor[ 0 ] ) ) {
return;
}
this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );
// support: jQuery <1.8
// jQuery <1.8 returns false if the request is canceled in beforeSend,
// but as of 1.8, $.ajax() always returns a jqXHR object.
if ( this.xhr && this.xhr.statusText !== "canceled" ) {
tab.addClass( "ui-tabs-loading" );
panel.attr( "aria-busy", "true" );
this.xhr
.success(function( response ) {
// support: jQuery <1.8
// http://bugs.jquery.com/ticket/11778
setTimeout(function() {
panel.html( response );
that._trigger( "load", event, eventData );
}, 1 );
})
.complete(function( jqXHR, status ) {
// support: jQuery <1.8
// http://bugs.jquery.com/ticket/11778
setTimeout(function() {
if ( status === "abort" ) {
that.panels.stop( false, true );
}
tab.removeClass( "ui-tabs-loading" );
panel.removeAttr( "aria-busy" );
if ( jqXHR === that.xhr ) {
delete that.xhr;
}
}, 1 );
});
}
},
_ajaxSettings: function( anchor, event, eventData ) {
var that = this;
return {
url: anchor.attr( "href" ),
beforeSend: function( jqXHR, settings ) {
return that._trigger( "beforeLoad", event,
$.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) );
}
};
},
_getPanelForTab: function( tab ) {
var id = $( tab ).attr( "aria-controls" );
return this.element.find( this._sanitizeSelector( "#" + id ) );
}
});
})( jQuery );
(function( $ ) {
var increments = 0;
function addDescribedBy( elem, id ) {
var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ );
describedby.push( id );
elem
.data( "ui-tooltip-id", id )
.attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
}
function removeDescribedBy( elem ) {
var id = elem.data( "ui-tooltip-id" ),
describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ),
index = $.inArray( id, describedby );
if ( index !== -1 ) {
describedby.splice( index, 1 );
}
elem.removeData( "ui-tooltip-id" );
describedby = $.trim( describedby.join( " " ) );
if ( describedby ) {
elem.attr( "aria-describedby", describedby );
} else {
elem.removeAttr( "aria-describedby" );
}
}
$.widget( "ui.tooltip", {
version: "1.10.2",
options: {
content: function() {
// support: IE<9, Opera in jQuery <1.7
// .text() can't accept undefined, so coerce to a string
var title = $( this ).attr( "title" ) || "";
// Escape title, since we're going from an attribute to raw HTML
return $( "<a>" ).text( title ).html();
},
hide: true,
// Disabled elements have inconsistent behavior across browsers (#8661)
items: "[title]:not([disabled])",
position: {
my: "left top+15",
at: "left bottom",
collision: "flipfit flip"
},
show: true,
tooltipClass: null,
track: false,
// callbacks
close: null,
open: null
},
_create: function() {
this._on({
mouseover: "open",
focusin: "open"
});
// IDs of generated tooltips, needed for destroy
this.tooltips = {};
// IDs of parent tooltips where we removed the title attribute
this.parents = {};
if ( this.options.disabled ) {
this._disable();
}
},
_setOption: function( key, value ) {
var that = this;
if ( key === "disabled" ) {
this[ value ? "_disable" : "_enable" ]();
this.options[ key ] = value;
// disable element style changes
return;
}
this._super( key, value );
if ( key === "content" ) {
$.each( this.tooltips, function( id, element ) {
that._updateContent( element );
});
}
},
_disable: function() {
var that = this;
// close open tooltips
$.each( this.tooltips, function( id, element ) {
var event = $.Event( "blur" );
event.target = event.currentTarget = element[0];
that.close( event, true );
});
// remove title attributes to prevent native tooltips
this.element.find( this.options.items ).addBack().each(function() {
var element = $( this );
if ( element.is( "[title]" ) ) {
element
.data( "ui-tooltip-title", element.attr( "title" ) )
.attr( "title", "" );
}
});
},
_enable: function() {
// restore title attributes
this.element.find( this.options.items ).addBack().each(function() {
var element = $( this );
if ( element.data( "ui-tooltip-title" ) ) {
element.attr( "title", element.data( "ui-tooltip-title" ) );
}
});
},
open: function( event ) {
var that = this,
target = $( event ? event.target : this.element )
// we need closest here due to mouseover bubbling,
// but always pointing at the same event target
.closest( this.options.items );
// No element to show a tooltip for or the tooltip is already open
if ( !target.length || target.data( "ui-tooltip-id" ) ) {
return;
}
if ( target.attr( "title" ) ) {
target.data( "ui-tooltip-title", target.attr( "title" ) );
}
target.data( "ui-tooltip-open", true );
// kill parent tooltips, custom or native, for hover
if ( event && event.type === "mouseover" ) {
target.parents().each(function() {
var parent = $( this ),
blurEvent;
if ( parent.data( "ui-tooltip-open" ) ) {
blurEvent = $.Event( "blur" );
blurEvent.target = blurEvent.currentTarget = this;
that.close( blurEvent, true );
}
if ( parent.attr( "title" ) ) {
parent.uniqueId();
that.parents[ this.id ] = {
element: this,
title: parent.attr( "title" )
};
parent.attr( "title", "" );
}
});
}
this._updateContent( target, event );
},
_updateContent: function( target, event ) {
var content,
contentOption = this.options.content,
that = this,
eventType = event ? event.type : null;
if ( typeof contentOption === "string" ) {
return this._open( event, target, contentOption );
}
content = contentOption.call( target[0], function( response ) {
// ignore async response if tooltip was closed already
if ( !target.data( "ui-tooltip-open" ) ) {
return;
}
// IE may instantly serve a cached response for ajax requests
// delay this call to _open so the other call to _open runs first
that._delay(function() {
// jQuery creates a special event for focusin when it doesn't
// exist natively. To improve performance, the native event
// object is reused and the type is changed. Therefore, we can't
// rely on the type being correct after the event finished
// bubbling, so we set it back to the previous value. (#8740)
if ( event ) {
event.type = eventType;
}
this._open( event, target, response );
});
});
if ( content ) {
this._open( event, target, content );
}
},
_open: function( event, target, content ) {
var tooltip, events, delayedShow,
positionOption = $.extend( {}, this.options.position );
if ( !content ) {
return;
}
// Content can be updated multiple times. If the tooltip already
// exists, then just update the content and bail.
tooltip = this._find( target );
if ( tooltip.length ) {
tooltip.find( ".ui-tooltip-content" ).html( content );
return;
}
// if we have a title, clear it to prevent the native tooltip
// we have to check first to avoid defining a title if none exists
// (we don't want to cause an element to start matching [title])
//
// We use removeAttr only for key events, to allow IE to export the correct
// accessible attributes. For mouse events, set to empty string to avoid
// native tooltip showing up (happens only when removing inside mouseover).
if ( target.is( "[title]" ) ) {
if ( event && event.type === "mouseover" ) {
target.attr( "title", "" );
} else {
target.removeAttr( "title" );
}
}
tooltip = this._tooltip( target );
addDescribedBy( target, tooltip.attr( "id" ) );
tooltip.find( ".ui-tooltip-content" ).html( content );
function position( event ) {
positionOption.of = event;
if ( tooltip.is( ":hidden" ) ) {
return;
}
tooltip.position( positionOption );
}
if ( this.options.track && event && /^mouse/.test( event.type ) ) {
this._on( this.document, {
mousemove: position
});
// trigger once to override element-relative positioning
position( event );
} else {
tooltip.position( $.extend({
of: target
}, this.options.position ) );
}
tooltip.hide();
this._show( tooltip, this.options.show );
// Handle tracking tooltips that are shown with a delay (#8644). As soon
// as the tooltip is visible, position the tooltip using the most recent
// event.
if ( this.options.show && this.options.show.delay ) {
delayedShow = this.delayedShow = setInterval(function() {
if ( tooltip.is( ":visible" ) ) {
position( positionOption.of );
clearInterval( delayedShow );
}
}, $.fx.interval );
}
this._trigger( "open", event, { tooltip: tooltip } );
events = {
keyup: function( event ) {
if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
var fakeEvent = $.Event(event);
fakeEvent.currentTarget = target[0];
this.close( fakeEvent, true );
}
},
remove: function() {
this._removeTooltip( tooltip );
}
};
if ( !event || event.type === "mouseover" ) {
events.mouseleave = "close";
}
if ( !event || event.type === "focusin" ) {
events.focusout = "close";
}
this._on( true, target, events );
},
close: function( event ) {
var that = this,
target = $( event ? event.currentTarget : this.element ),
tooltip = this._find( target );
// disabling closes the tooltip, so we need to track when we're closing
// to avoid an infinite loop in case the tooltip becomes disabled on close
if ( this.closing ) {
return;
}
// Clear the interval for delayed tracking tooltips
clearInterval( this.delayedShow );
// only set title if we had one before (see comment in _open())
if ( target.data( "ui-tooltip-title" ) ) {
target.attr( "title", target.data( "ui-tooltip-title" ) );
}
removeDescribedBy( target );
tooltip.stop( true );
this._hide( tooltip, this.options.hide, function() {
that._removeTooltip( $( this ) );
});
target.removeData( "ui-tooltip-open" );
this._off( target, "mouseleave focusout keyup" );
// Remove 'remove' binding only on delegated targets
if ( target[0] !== this.element[0] ) {
this._off( target, "remove" );
}
this._off( this.document, "mousemove" );
if ( event && event.type === "mouseleave" ) {
$.each( this.parents, function( id, parent ) {
$( parent.element ).attr( "title", parent.title );
delete that.parents[ id ];
});
}
this.closing = true;
this._trigger( "close", event, { tooltip: tooltip } );
this.closing = false;
},
_tooltip: function( element ) {
var id = "ui-tooltip-" + increments++,
tooltip = $( "<div>" )
.attr({
id: id,
role: "tooltip"
})
.addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " +
( this.options.tooltipClass || "" ) );
$( "<div>" )
.addClass( "ui-tooltip-content" )
.appendTo( tooltip );
tooltip.appendTo( this.document[0].body );
this.tooltips[ id ] = element;
return tooltip;
},
_find: function( target ) {
var id = target.data( "ui-tooltip-id" );
return id ? $( "#" + id ) : $();
},
_removeTooltip: function( tooltip ) {
tooltip.remove();
delete this.tooltips[ tooltip.attr( "id" ) ];
},
_destroy: function() {
var that = this;
// close open tooltips
$.each( this.tooltips, function( id, element ) {
// Delegate to close method to handle common cleanup
var event = $.Event( "blur" );
event.target = event.currentTarget = element[0];
that.close( event, true );
// Remove immediately; destroying an open tooltip doesn't use the
// hide animation
$( "#" + id ).remove();
// Restore the title
if ( element.data( "ui-tooltip-title" ) ) {
element.attr( "title", element.data( "ui-tooltip-title" ) );
element.removeData( "ui-tooltip-title" );
}
});
}
});
}( jQuery ) );
| arkaindas/cdnjs | ajax/libs/jqueryui/1.10.2/jquery-ui.js | JavaScript | mit | 436,089 |
/*! normalize.css v7.0.0 | MIT License | github.com/necolas/normalize.css */
/* Document
========================================================================== */
/**
* 1. Correct the line height in all browsers.
* 2. Prevent adjustments of font size after orientation changes in
* IE on Windows Phone and in iOS.
*/
html {
line-height: 1.15; /* 1 */
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/* Sections
========================================================================== */
/**
* Remove the margin in all browsers (opinionated).
*/
body {
margin: 0;
}
/**
* Add the correct display in IE 9-.
*/
article,
aside,
footer,
header,
nav,
section {
display: block;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/* Grouping content
========================================================================== */
/**
* Add the correct display in IE 9-.
* 1. Add the correct display in IE.
*/
figcaption,
figure,
main { /* 1 */
display: block;
}
/**
* Add the correct margin in IE 8.
*/
figure {
margin: 1em 40px;
}
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box; /* 1 */
height: 0; /* 1 */
overflow: visible; /* 2 */
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
pre {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/* Text-level semantics
========================================================================== */
/**
* 1. Remove the gray background on active links in IE 10.
* 2. Remove gaps in links underline in iOS 8+ and Safari 8+.
*/
a {
background-color: transparent; /* 1 */
-webkit-text-decoration-skip: objects; /* 2 */
}
/**
* 1. Remove the bottom border in Chrome 57- and Firefox 39-.
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none; /* 1 */
text-decoration: underline; /* 2 */
text-decoration: underline dotted; /* 2 */
}
/**
* Prevent the duplicate application of `bolder` by the next rule in Safari 6.
*/
b,
strong {
font-weight: inherit;
}
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/**
* Add the correct font style in Android 4.3-.
*/
dfn {
font-style: italic;
}
/**
* Add the correct background and color in IE 9-.
*/
mark {
background-color: #ff0;
color: #000;
}
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/* Embedded content
========================================================================== */
/**
* Add the correct display in IE 9-.
*/
audio,
video {
display: inline-block;
}
/**
* Add the correct display in iOS 4-7.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Remove the border on images inside links in IE 10-.
*/
img {
border-style: none;
}
/**
* Hide the overflow in IE.
*/
svg:not(:root) {
overflow: hidden;
}
/* Forms
========================================================================== */
/**
* 1. Change the font styles in all browsers (opinionated).
* 2. Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
font-family: sans-serif; /* 1 */
font-size: 100%; /* 1 */
line-height: 1.15; /* 1 */
margin: 0; /* 2 */
}
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input { /* 1 */
overflow: visible;
}
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select { /* 1 */
text-transform: none;
}
/**
* 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`
* controls in Android 4.
* 2. Correct the inability to style clickable types in iOS and Safari.
*/
button,
html [type="button"], /* 1 */
[type="reset"],
[type="submit"] {
-webkit-appearance: button; /* 2 */
}
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
* Correct the padding in Firefox.
*/
fieldset {
padding: 0.35em 0.75em 0.625em;
}
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box; /* 1 */
color: inherit; /* 2 */
display: table; /* 1 */
max-width: 100%; /* 1 */
padding: 0; /* 3 */
white-space: normal; /* 1 */
}
/**
* 1. Add the correct display in IE 9-.
* 2. Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
/**
* Remove the default vertical scrollbar in IE.
*/
textarea {
overflow: auto;
}
/**
* 1. Add the correct box sizing in IE 10-.
* 2. Remove the padding in IE 10-.
*/
[type="checkbox"],
[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/**
* Remove the inner padding and cancel buttons in Chrome and Safari on macOS.
*/
[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/* Interactive
========================================================================== */
/*
* Add the correct display in IE 9-.
* 1. Add the correct display in Edge, IE, and Firefox.
*/
details, /* 1 */
menu {
display: block;
}
/*
* Add the correct display in all browsers.
*/
summary {
display: list-item;
}
/* Scripting
========================================================================== */
/**
* Add the correct display in IE 9-.
*/
canvas {
display: inline-block;
}
/**
* Add the correct display in IE.
*/
template {
display: none;
}
/* Hidden
========================================================================== */
/**
* Add the correct display in IE 10-.
*/
[hidden] {
display: none;
}
| nfletton/bvspca | bvspca/static/sass/normalize.css | CSS | mit | 7,719 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\BrowserKit;
/**
* Response object.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Response
{
protected $content;
protected $status;
protected $headers;
/**
* Constructor.
*
* The headers array is a set of key/value pairs. If a header is present multiple times
* then the value is an array of all the values.
*
* @param string $content The content of the response
* @param int $status The response status code
* @param array $headers An array of headers
*/
public function __construct($content = '', $status = 200, array $headers = array())
{
$this->content = $content;
$this->status = $status;
$this->headers = $headers;
}
/**
* Converts the response object to string containing all headers and the response content.
*
* @return string The response with headers and content
*/
public function __toString()
{
$headers = '';
foreach ($this->headers as $name => $value) {
if (is_string($value)) {
$headers .= $this->buildHeader($name, $value);
} else {
foreach ($value as $headerValue) {
$headers .= $this->buildHeader($name, $headerValue);
}
}
}
return $headers."\n".$this->content;
}
/**
* Returns the build header line.
*
* @param string $name The header name
* @param string $value The header value
*
* @return string The built header line
*/
protected function buildHeader($name, $value)
{
return sprintf("%s: %s\n", $name, $value);
}
/**
* Gets the response content.
*
* @return string The response content
*/
public function getContent()
{
return $this->content;
}
/**
* Gets the response status code.
*
* @return int The response status code
*/
public function getStatus()
{
return $this->status;
}
/**
* Gets the response headers.
*
* @return array The response headers
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Gets a response header.
*
* @param string $header The header name
* @param bool $first Whether to return the first value or all header values
*
* @return string|array The first header value if $first is true, an array of values otherwise
*/
public function getHeader($header, $first = true)
{
$normalizedHeader = str_replace('-', '_', strtolower($header));
foreach ($this->headers as $key => $value) {
if (str_replace('-', '_', strtolower($key)) === $normalizedHeader) {
if ($first) {
return is_array($value) ? (count($value) ? $value[0] : '') : $value;
}
return is_array($value) ? $value : array($value);
}
}
return $first ? null : array();
}
}
| dosten/symfony | src/Symfony/Component/BrowserKit/Response.php | PHP | mit | 3,324 |
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles Quoted Printable (QP) Transfer Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder implements Swift_Mime_ContentEncoder
{
protected $_dotEscape;
/**
* Creates a new QpContentEncoder for the given CharacterStream.
*
* @param Swift_CharacterStream $charStream to use for reading characters
* @param Swift_StreamFilter $filter if canonicalization should occur
* @param bool $dotEscape if dot stuffing workaround must be enabled
*/
public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null, $dotEscape = false)
{
$this->_dotEscape = $dotEscape;
parent::__construct($charStream, $filter);
}
public function __sleep()
{
return array('_charStream', '_filter', '_dotEscape');
}
protected function getSafeMapShareId()
{
return get_class($this).($this->_dotEscape ? '.dotEscape' : '');
}
protected function initSafeMap()
{
parent::initSafeMap();
if ($this->_dotEscape) {
/* Encode . as =2e for buggy remote servers */
unset($this->_safeMap[0x2e]);
}
}
/**
* Encode stream $in to stream $out.
*
* QP encoded strings have a maximum line length of 76 characters.
* If the first line needs to be shorter, indicate the difference with
* $firstLineOffset.
*
* @param Swift_OutputByteStream $os output stream
* @param Swift_InputByteStream $is input stream
* @param int $firstLineOffset
* @param int $maxLineLength
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{
if ($maxLineLength > 76 || $maxLineLength <= 0) {
$maxLineLength = 76;
}
$thisLineLength = $maxLineLength - $firstLineOffset;
$this->_charStream->flushContents();
$this->_charStream->importByteStream($os);
$currentLine = '';
$prepend = '';
$size = $lineLen = 0;
while (false !== $bytes = $this->_nextSequence()) {
// If we're filtering the input
if (isset($this->_filter)) {
// If we can't filter because we need more bytes
while ($this->_filter->shouldBuffer($bytes)) {
// Then collect bytes into the buffer
if (false === $moreBytes = $this->_nextSequence(1)) {
break;
}
foreach ($moreBytes as $b) {
$bytes[] = $b;
}
}
// And filter them
$bytes = $this->_filter->filter($bytes);
}
$enc = $this->_encodeByteSequence($bytes, $size);
$i = strpos($enc, '=0D=0A');
$newLineLength = $lineLen + ($i === false ? $size : $i);
if ($currentLine && $newLineLength >= $thisLineLength) {
$is->write($prepend.$this->_standardize($currentLine));
$currentLine = '';
$prepend = "=\r\n";
$thisLineLength = $maxLineLength;
$lineLen = 0;
}
$currentLine .= $enc;
if ($i === false) {
$lineLen += $size;
} else {
// 6 is the length of '=0D=0A'.
$lineLen = $size - strrpos($enc, '=0D=0A') - 6;
}
}
if (strlen($currentLine)) {
$is->write($prepend.$this->_standardize($currentLine));
}
}
/**
* Get the name of this encoding scheme.
* Returns the string 'quoted-printable'.
*
* @return string
*/
public function getName()
{
return 'quoted-printable';
}
}
| GingfreeX/E-Randopi | vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php | PHP | mit | 4,225 |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CodeMirror: Properties files mode</title>
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="properties.js"></script>
<style>.CodeMirror {border-top: 1px solid #ddd; border-bottom: 1px solid #ddd;}</style>
<link rel="stylesheet" href="../../doc/docs.css">
</head>
<body>
<h1>CodeMirror: Properties files mode</h1>
<form><textarea id="code" name="code">
# This is a properties file
a.key = A value
another.key = http://example.com
! Exclamation mark as comment
but.not=Within ! A value # indeed
# Spaces at the beginning of a line
spaces.before.key=value
backslash=Used for multi\
line entries,\
that's convenient.
# Unicode sequences
unicode.key=This is \u0020 Unicode
no.multiline=here
# Colons
colons : can be used too
# Spaces
spaces\ in\ keys=Not very common...
</textarea></form>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-properties</code>,
<code>text/x-ini</code>.</p>
</body>
</html>
| MenZil/jsdelivr | files/codemirror/3.14.0/mode/properties/index.html | HTML | mit | 1,216 |
var baseSetData = require('./baseSetData'),
createBindWrapper = require('./createBindWrapper'),
createHybridWrapper = require('./createHybridWrapper'),
createPartialWrapper = require('./createPartialWrapper'),
getData = require('./getData'),
mergeData = require('./mergeData'),
setData = require('./setData');
/** Used to compose bitmasks for wrapper metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
PARTIAL_FLAG = 32,
PARTIAL_RIGHT_FLAG = 64;
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to reference.
* @param {number} bitmask The bitmask of flags.
* The bitmask may be composed of the following flags:
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
length -= (holders ? holders.length : 0);
if (bitmask & PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func),
newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
if (data) {
mergeData(newData, data);
bitmask = newData[1];
arity = newData[9];
}
newData[9] = arity == null
? (isBindKey ? 0 : func.length)
: (nativeMax(arity - length, 0) || 0);
if (bitmask == BIND_FLAG) {
var result = createBindWrapper(newData[0], newData[2]);
} else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
result = createPartialWrapper.apply(undefined, newData);
} else {
result = createHybridWrapper.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setter(result, newData);
}
module.exports = createWrapper;
| puaykai/noodles | grails-app/assets/javascripts/dependencies/node_modules/babel-traverse/node_modules/lodash/internal/createWrapper.js | JavaScript | mit | 3,075 |
var baseSetData = require('./baseSetData'),
createBindWrapper = require('./createBindWrapper'),
createHybridWrapper = require('./createHybridWrapper'),
createPartialWrapper = require('./createPartialWrapper'),
getData = require('./getData'),
mergeData = require('./mergeData'),
setData = require('./setData');
/** Used to compose bitmasks for wrapper metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
PARTIAL_FLAG = 32,
PARTIAL_RIGHT_FLAG = 64;
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to reference.
* @param {number} bitmask The bitmask of flags.
* The bitmask may be composed of the following flags:
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
length -= (holders ? holders.length : 0);
if (bitmask & PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func),
newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
if (data) {
mergeData(newData, data);
bitmask = newData[1];
arity = newData[9];
}
newData[9] = arity == null
? (isBindKey ? 0 : func.length)
: (nativeMax(arity - length, 0) || 0);
if (bitmask == BIND_FLAG) {
var result = createBindWrapper(newData[0], newData[2]);
} else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
result = createPartialWrapper.apply(undefined, newData);
} else {
result = createHybridWrapper.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setter(result, newData);
}
module.exports = createWrapper;
| lvduit/islab-portfolio-by-ghost | node_modules/testem/node_modules/js-yaml/node_modules/argparse/node_modules/lodash/internal/createWrapper.js | JavaScript | mit | 3,075 |
import { APIGatewayProxyEvent, Context, APIGatewayProxyResult } from 'aws-lambda';
import * as express from 'express';
export type HttpMethods = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
/* eslint-disable @typescript-eslint/no-explicit-any */
export type SessionData = Record<string, any>;
export type JsonBody = any;
export type HtmlBody = string;
export type RequestBody = any;
/* eslint-enable @typescript-eslint/no-explicit-any */
/**
* An incoming Architect Request.
* https://arc.codes/docs/en/reference/runtime/node#request
*/
export interface HttpRequest {
httpMethod: HttpMethods;
/**
* The absolute path of the request
*/
path: string;
/**
* The absolute path of the request, with resources substituted for actual path parts (e.g. /{foo}/bar)
*/
resource: string;
/**
* Any URL params, if defined in your HTTP Function's path (e.g. foo in GET /:foo/bar)
*/
pathParameters: Record<string, string>;
/**
* Any query params if present in the client request
*/
queryStringParameters: Record<string, string>;
/**
* All client request headers
*/
headers: Record<string, string>;
/**
* The request body in a base64-encoded buffer. You'll need to parse request.body before you can use it, but Architect provides tools to do this - see parsing request bodies.
*/
body: RequestBody;
/**
* Indicates whether body is base64-encoded binary payload (will always be true if body has not null)
*/
isBase64Encoded: boolean;
/**
* When the request/response is run through arc.http.async (https://arc.codes/docs/en/reference/runtime/node#arc.http.async) then it will have session added.
*/
session?: SessionData | undefined;
}
/**
* https://arc.codes/primitives/http#res
*/
export interface HttpResponse {
/**
* Sets the HTTP status code
*/
statusCode?: number | undefined;
/**
* Alias for @see statusCode
*/
status?: number | undefined;
/**
* All response headers
*/
headers?: Record<string, string> | undefined;
/**
* Contains request body, either as a plain string (no encoding or serialization required) or, if binary, base64-encoded buffer
* Note: The maximum body payload size is 6MB
*/
body?: string | undefined;
/**
* Indicates whether body is base64-encoded binary payload
* Required to be set to true if emitting a binary payload
*/
isBase64Encoded?: boolean | undefined;
/**
* When the request/response is run through arc.http.async (https://arc.codes/docs/en/reference/runtime/node#arc.http.async) then it will have session added.
*/
session?: SessionData | undefined;
/**
* When used with https://arc.codes/docs/en/reference/runtime/node#arc.http.async
* json sets the Content-Type header to application/json
*/
json?: JsonBody | undefined;
/**
* When used with https://arc.codes/docs/en/reference/runtime/node#arc.http.async
* json sets the Content-Type header to application/json
*/
html?: HtmlBody | undefined;
}
/**
* Defines an HttpHandler that works with architect.
*/
export interface HttpHandler {
(req: HttpRequest): Promise<HttpResponse | undefined>;
}
export type LambdaHandler = (event: APIGatewayProxyEvent, context: Context) => Promise<APIGatewayProxyResult>;
export type HttpAsync = (...fns: HttpHandler[]) => LambdaHandler;
export type HttpExpress = (app: express.Application) => LambdaHandler;
export interface HttpSession {
read(req: HttpRequest): Promise<SessionData>;
write(sess: SessionData): Promise<string>;
}
export interface HttpProxyOptions {
spa: boolean;
alias: Record<string, string>;
}
export type HttpProxy = (options: HttpProxyOptions) => HttpHandler;
export interface StaticOptions {
stagePath: string;
}
export interface Helpers {
bodyParser: (req: HttpRequest) => Record<string, any>;
interpolate: (req: HttpRequest) => HttpRequest;
static: (asset: string, options?: StaticOptions) => string;
url: (url: string) => string;
}
export interface ArcHttp {
/**
* https://arc.codes/docs/en/reference/runtime/node#arc.http.async
*/
async: HttpAsync;
/**
* https://arc.codes/docs/en/reference/runtime/node#arc.http.express
*/
express: HttpExpress;
/**
* https://github.com/architect/functions/blob/3f11406b651f2854371906ad5f9eb9c300433032/src/http/index.js#L21-L26
*/
helpers: Helpers;
/**
* https://arc.codes/docs/en/reference/runtime/node#arc.http.proxy
*/
proxy: HttpProxy;
/**
* https://arc.codes/docs/en/reference/runtime/node#arc.http.session
*/
session: HttpSession;
}
| markogresak/DefinitelyTyped | types/architect__functions/http.d.ts | TypeScript | mit | 4,781 |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Redis.Models
{
using System.Linq;
/// <summary>
/// The resource model definition for a ARM proxy resource. It will have
/// everything other than required location and tags
/// </summary>
public partial class ProxyResource : Resource
{
/// <summary>
/// Initializes a new instance of the ProxyResource class.
/// </summary>
public ProxyResource()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ProxyResource class.
/// </summary>
/// <param name="id">Resource ID.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type.</param>
public ProxyResource(string id = default(string), string name = default(string), string type = default(string))
: base(id, name, type)
{
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
}
}
| jackmagic313/azure-sdk-for-net | sdk/redis/Microsoft.Azure.Management.RedisCache/src/Generated/Models/ProxyResource.cs | C# | mit | 1,498 |
# frozen_string_literal: true
require "active_support/number_helper/number_converter"
module ActiveSupport
module NumberHelper
class NumberToRoundedConverter < NumberConverter # :nodoc:
self.namespace = :precision
self.validate_float = true
def convert
helper = RoundingHelper.new(options)
rounded_number = helper.round(number)
if precision = options[:precision]
if options[:significant] && precision > 0
digits = helper.digit_count(rounded_number)
precision -= digits
precision = 0 if precision < 0 # don't let it be negative
end
formatted_string =
if rounded_number.finite?
s = rounded_number.to_s("F")
a, b = s.split(".", 2)
if precision != 0
b << "0" * precision
a << "."
a << b[0, precision]
end
a
else
# Infinity/NaN
"%f" % rounded_number
end
else
formatted_string = rounded_number
end
delimited_number = NumberToDelimitedConverter.convert(formatted_string, options)
format_number(delimited_number)
end
private
def strip_insignificant_zeros
options[:strip_insignificant_zeros]
end
def format_number(number)
if strip_insignificant_zeros
escaped_separator = Regexp.escape(options[:separator])
number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, "")
else
number
end
end
end
end
end
| Ladvien/ladvien.github.io | vendor/cache/ruby/3.0.0/gems/activesupport-6.1.4.1/lib/active_support/number_helper/number_to_rounded_converter.rb | Ruby | mit | 1,700 |
var test = require("tap").test
var npm = require.resolve("../../bin/npm-cli.js")
var osenv = require("osenv")
var path = require("path")
var fs = require("fs")
var rimraf = require("rimraf")
var mkdirp = require("mkdirp")
var mr = require("npm-registry-mock")
var child
var spawn = require("child_process").spawn
var node = process.execPath
var pkg = process.env.npm_config_tmp || "/tmp"
pkg += path.sep + "noargs-install-config-save"
function writePackageJson() {
rimraf.sync(pkg)
mkdirp.sync(pkg)
fs.writeFileSync(pkg + "/package.json", JSON.stringify({
"author": "Rocko Artischocko",
"name": "noargs",
"version": "0.0.0",
"devDependencies": {
"underscore": "1.3.1"
}
}), 'utf8')
}
function createChild (args) {
var env = {
npm_config_save: true,
npm_config_registry: "http://localhost:1337",
HOME: process.env.HOME,
Path: process.env.PATH,
PATH: process.env.PATH
}
if (process.platform === "win32")
env.npm_config_cache = "%APPDATA%\\npm-cache"
return spawn(node, args, {
cwd: pkg,
stdio: "inherit",
env: env
})
}
test("does not update the package.json with empty arguments", function (t) {
writePackageJson()
t.plan(1)
mr(1337, function (s) {
var child = createChild([npm, "install"])
child.on("close", function (m) {
var text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8"))
t.ok(text.indexOf('"dependencies') === -1)
s.close()
t.end()
})
})
})
test("updates the package.json (adds dependencies) with an argument", function (t) {
writePackageJson()
t.plan(1)
mr(1337, function (s) {
var child = createChild([npm, "install", "underscore"])
child.on("close", function (m) {
var text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8"))
t.ok(text.indexOf('"dependencies') !== -1)
s.close()
t.end()
})
})
}) | vito16/express2 | node_modules/cordova/node_modules/npm/test/tap/noargs-install-config-save.js | JavaScript | mit | 1,916 |
class LatePoliciesAddColumns < ActiveRecord::Migration
def self.up
change_column :late_policies, :penalty_per_unit, :float
add_column :late_policies, :times_used, :integer, :null => false, :default => 0
add_column :late_policies, :instructor_id, :integer, :null => false
add_column :late_policies, :policy_name, :string, :null => false
index = 1
LatePolicy.find_each do |f|
f.update_attribute :instructor_id, 2
f.update_attribute :policy_name, 'Default Policy ' + index.to_s
index += 1
end
execute "ALTER TABLE late_policies ADD CONSTRAINT `fk_instructor_id` FOREIGN KEY (instructor_id) REFERENCES users(id);"
remove_index "late_policies", :name => "penalty_period_length_unit"
remove_column :late_policies, :expressed_as_percentage
remove_column :late_policies, :penalty_period_in_minutes
end
def self.down
add_column :late_policies, :expressed_as_percentage, :boolean
add_column :late_policies, :penalty_period_in_minutes, :integer
add_index "late_policies", ["penalty_period_in_minutes"], :name => "penalty_period_length_unit"
execute "ALTER TABLE late_policies DROP FOREIGN KEY `fk_instructor_id`;"
remove_column :late_policies, :times_used
remove_column :late_policies, :instructor_id
remove_column :late_policies, :policy_name
change_column :late_policies, :penalty_per_unit, :integer
end
end
| rmmaily/expertiza | db/migrate/20131201172400_late_policies_add_columns.rb | Ruby | mit | 1,416 |
/// <reference path="object-assign.d.ts" />
import * as objectAssign from 'object-assign';
interface Target {
hellow: string;
}
interface Source1 {
source1: string;
}
interface Result extends Target, Source1 {
}
interface Source2 {
source2: string;
}
interface Result2 extends Result, Source2 {
}
interface Source3 {
source3: string;
}
interface Result3 extends Result2, Source3 {
}
interface Source4 {
source4: string;
}
interface Result4 extends Result3, Source4 {
}
interface Source5 {
source5: string;
}
interface Result5 extends Result4, Source5 {
}
function assign1(): Result {
return objectAssign({hellow: "world"}, {source1: "U"});
}
function assign2(): Result2 {
return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"});
}
function assign3(): Result3 {
return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"});
}
function assign4(): Result4 {
return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"});
}
function assign5(): Result5 {
return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"});
}
function assign() {
return objectAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}, {
hellow: "hellow",
source1: "source1",
source2: "source2",
source3: "source3",
source4: "source4",
source5: "source5",
generic: "any"
});
}
| tkrugg/DefinitelyTyped | object-assign/object-assign-tests.ts | TypeScript | mit | 1,511 |
var should = require("should");
var path = require("path");
var webpack = require("../lib/webpack");
describe("NodeTemplatePlugin", function() {
it("should compile and run a simple module", function(done) {
webpack({
context: path.join(__dirname, "fixtures", "nodetest"),
target: "node",
output: {
path: path.join(__dirname, "js"),
filename: "result.js",
chunkFilename: "[hash].result.[id].js",
library: "abc",
libraryTarget: "commonjs",
},
entry: "./entry",
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
}, function(err, stats) {
if(err) return err;
stats.hasErrors().should.be.not.ok;
stats.hasWarnings().should.be.not.ok;
var result = require("./js/result").abc;
result.nextTick.should.be.equal(process.nextTick);
result.fs.should.be.equal(require("fs"));
result.loadChunk(456, function(chunk) {
chunk.should.be.eql(123);
result.loadChunk(567, function(chunk) {
chunk.should.be.eql({a: 1});
done();
});
});
});
});
it("should compile and run a simple module in single mode", function(done) {
webpack({
context: path.join(__dirname, "fixtures", "nodetest"),
target: "node",
output: {
path: path.join(__dirname, "js"),
filename: "result2.js",
chunkFilename: "[hash].result2.[id].js",
library: "def",
libraryTarget: "umd",
},
entry: "./entry",
plugins: [
new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
new webpack.optimize.UglifyJsPlugin()
]
}, function(err, stats) {
if(err) return err;
stats.hasErrors().should.be.not.ok;
var result = require("./js/result2");
result.nextTick.should.be.equal(process.nextTick);
result.fs.should.be.equal(require("fs"));
var sameTick = true;
result.loadChunk(456, function(chunk) {
chunk.should.be.eql(123);
sameTick.should.be.eql(true);
result.loadChunk(567, function(chunk) {
chunk.should.be.eql({a: 1});
done();
});
});
});
});
});
| mvayngrib/webpack | test/NodeTemplatePlugin.test.js | JavaScript | mit | 1,998 |
/* unzip.c -- IO for uncompress .zip files using zlib
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
Read unzip.h for more info
*/
/* Decryption code comes from crypt.c by Info-ZIP but has been greatly reduced in terms of
compatibility with older software. The following is from the original crypt.c. Code
woven in by Terry Thorsen 1/2003.
*/
/*
Copyright (c) 1990-2000 Info-ZIP. All rights reserved.
See the accompanying file LICENSE, version 2000-Apr-09 or later
(the contents of which are also included in zip.h) for terms of use.
If, for some reason, all these files are missing, the Info-ZIP license
also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html
*/
/*
crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h]
The encryption/decryption parts of this source code (as opposed to the
non-echoing password parts) were originally written in Europe. The
whole source package can be freely distributed, including from the USA.
(Prior to January 2000, re-export from the US was a violation of US law.)
*/
/*
This encryption code is a direct transcription of the algorithm from
Roger Schlafly, described by Phil Katz in the file appnote.txt. This
file (appnote.txt) is distributed with the PKZIP program (even in the
version without encryption capabilities).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(USE_SYSTEM_ZLIB)
#include <zlib.h>
#else
#include "zlib.h"
#endif
#include "unzip.h"
#ifdef STDC
# include <stddef.h>
# include <string.h>
# include <stdlib.h>
#endif
#ifdef NO_ERRNO_H
extern int errno;
#else
# include <errno.h>
#endif
#ifndef local
# define local static
#endif
/* compile with -Dlocal if your debugger can't find static symbols */
#ifndef CASESENSITIVITYDEFAULT_NO
# if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES)
# define CASESENSITIVITYDEFAULT_NO
# endif
#endif
#ifndef UNZ_BUFSIZE
#define UNZ_BUFSIZE (16384)
#endif
#ifndef UNZ_MAXFILENAMEINZIP
#define UNZ_MAXFILENAMEINZIP (256)
#endif
#ifndef ALLOC
# define ALLOC(size) (malloc(size))
#endif
#ifndef TRYFREE
# define TRYFREE(p) {if (p) free(p);}
#endif
#define SIZECENTRALDIRITEM (0x2e)
#define SIZEZIPLOCALHEADER (0x1e)
const char unz_copyright[] =
" unzip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll";
/* unz_file_info_interntal contain internal info about a file in zipfile*/
typedef struct unz_file_info_internal_s
{
uLong offset_curfile;/* relative offset of local header 4 bytes */
} unz_file_info_internal;
/* file_in_zip_read_info_s contain internal information about a file in zipfile,
when reading and decompress it */
typedef struct
{
char *read_buffer; /* internal buffer for compressed data */
z_stream stream; /* zLib stream structure for inflate */
uLong pos_in_zipfile; /* position in byte on the zipfile, for fseek*/
uLong stream_initialised; /* flag set if stream structure is initialised*/
uLong offset_local_extrafield;/* offset of the local extra field */
uInt size_local_extrafield;/* size of the local extra field */
uLong pos_local_extrafield; /* position in the local extra field in read*/
uLong crc32; /* crc32 of all data uncompressed */
uLong crc32_wait; /* crc32 we must obtain after decompress all */
uLong rest_read_compressed; /* number of byte to be decompressed */
uLong rest_read_uncompressed;/*number of byte to be obtained after decomp*/
zlib_filefunc_def z_filefunc;
voidpf filestream; /* io structore of the zipfile */
uLong compression_method; /* compression method (0==store) */
uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
int raw;
} file_in_zip_read_info_s;
/* unz_s contain internal information about the zipfile
*/
typedef struct
{
zlib_filefunc_def z_filefunc;
voidpf filestream; /* io structore of the zipfile */
unz_global_info gi; /* public global information */
uLong byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
uLong num_file; /* number of the current file in the zipfile*/
uLong pos_in_central_dir; /* pos of the current file in the central dir*/
uLong current_file_ok; /* flag about the usability of the current file*/
uLong central_pos; /* position of the beginning of the central dir*/
uLong size_central_dir; /* size of the central directory */
uLong offset_central_dir; /* offset of start of central directory with
respect to the starting disk number */
unz_file_info cur_file_info; /* public info about the current file in zip*/
unz_file_info_internal cur_file_info_internal; /* private info about it*/
file_in_zip_read_info_s* pfile_in_zip_read; /* structure about the current
file if we are decompressing it */
int encrypted;
# ifndef NOUNCRYPT
unsigned long keys[3]; /* keys defining the pseudo-random sequence */
const unsigned long* pcrc_32_tab;
# endif
} unz_s;
#ifndef NOUNCRYPT
#include "crypt.h"
#endif
/* ===========================================================================
Read a byte from a gz_stream; update next_in and avail_in. Return EOF
for end of file.
IN assertion: the stream s has been sucessfully opened for reading.
*/
local int unzlocal_getByte OF((
const zlib_filefunc_def* pzlib_filefunc_def,
voidpf filestream,
int *pi));
local int unzlocal_getByte(pzlib_filefunc_def,filestream,pi)
const zlib_filefunc_def* pzlib_filefunc_def;
voidpf filestream;
int *pi;
{
unsigned char c;
int err = (int)ZREAD(*pzlib_filefunc_def,filestream,&c,1);
if (err==1)
{
*pi = (int)c;
return UNZ_OK;
}
else
{
if (ZERROR(*pzlib_filefunc_def,filestream))
return UNZ_ERRNO;
else
return UNZ_EOF;
}
}
/* ===========================================================================
Reads a long in LSB order from the given gz_stream. Sets
*/
local int unzlocal_getShort OF((
const zlib_filefunc_def* pzlib_filefunc_def,
voidpf filestream,
uLong *pX));
local int unzlocal_getShort (pzlib_filefunc_def,filestream,pX)
const zlib_filefunc_def* pzlib_filefunc_def;
voidpf filestream;
uLong *pX;
{
uLong x ;
int i;
int err;
err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i);
x = (uLong)i;
if (err==UNZ_OK)
err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i);
x += ((uLong)i)<<8;
if (err==UNZ_OK)
*pX = x;
else
*pX = 0;
return err;
}
local int unzlocal_getLong OF((
const zlib_filefunc_def* pzlib_filefunc_def,
voidpf filestream,
uLong *pX));
local int unzlocal_getLong (pzlib_filefunc_def,filestream,pX)
const zlib_filefunc_def* pzlib_filefunc_def;
voidpf filestream;
uLong *pX;
{
uLong x ;
int i;
int err;
err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i);
x = (uLong)i;
if (err==UNZ_OK)
err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i);
x += ((uLong)i)<<8;
if (err==UNZ_OK)
err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i);
x += ((uLong)i)<<16;
if (err==UNZ_OK)
err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i);
x += ((uLong)i)<<24;
if (err==UNZ_OK)
*pX = x;
else
*pX = 0;
return err;
}
/* My own strcmpi / strcasecmp */
local int strcmpcasenosensitive_internal (fileName1,fileName2)
const char* fileName1;
const char* fileName2;
{
for (;;)
{
char c1=*(fileName1++);
char c2=*(fileName2++);
if ((c1>='a') && (c1<='z'))
c1 -= 0x20;
if ((c2>='a') && (c2<='z'))
c2 -= 0x20;
if (c1=='\0')
return ((c2=='\0') ? 0 : -1);
if (c2=='\0')
return 1;
if (c1<c2)
return -1;
if (c1>c2)
return 1;
}
}
#ifdef CASESENSITIVITYDEFAULT_NO
#define CASESENSITIVITYDEFAULTVALUE 2
#else
#define CASESENSITIVITYDEFAULTVALUE 1
#endif
#ifndef STRCMPCASENOSENTIVEFUNCTION
#define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal
#endif
/*
Compare two filename (fileName1,fileName2).
If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
or strcasecmp)
If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
(like 1 on Unix, 2 on Windows)
*/
extern int ZEXPORT unzStringFileNameCompare (fileName1,fileName2,iCaseSensitivity)
const char* fileName1;
const char* fileName2;
int iCaseSensitivity;
{
if (iCaseSensitivity==0)
iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE;
if (iCaseSensitivity==1)
return strcmp(fileName1,fileName2);
return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2);
}
#ifndef BUFREADCOMMENT
#define BUFREADCOMMENT (0x400)
#endif
/*
Locate the Central directory of a zipfile (at the end, just before
the global comment)
*/
local uLong unzlocal_SearchCentralDir OF((
const zlib_filefunc_def* pzlib_filefunc_def,
voidpf filestream));
local uLong unzlocal_SearchCentralDir(pzlib_filefunc_def,filestream)
const zlib_filefunc_def* pzlib_filefunc_def;
voidpf filestream;
{
unsigned char* buf;
uLong uSizeFile;
uLong uBackRead;
uLong uMaxBack=0xffff; /* maximum size of global comment */
uLong uPosFound=0;
if (ZSEEK(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
return 0;
uSizeFile = ZTELL(*pzlib_filefunc_def,filestream);
if (uMaxBack>uSizeFile)
uMaxBack = uSizeFile;
buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
if (buf==NULL)
return 0;
uBackRead = 4;
while (uBackRead<uMaxBack)
{
uLong uReadSize,uReadPos ;
int i;
if (uBackRead+BUFREADCOMMENT>uMaxBack)
uBackRead = uMaxBack;
else
uBackRead+=BUFREADCOMMENT;
uReadPos = uSizeFile-uBackRead ;
uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
(BUFREADCOMMENT+4) : (uSizeFile-uReadPos);
if (ZSEEK(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
break;
if (ZREAD(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
break;
for (i=(int)uReadSize-3; (i--)>0;)
if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
{
uPosFound = uReadPos+i;
break;
}
if (uPosFound!=0)
break;
}
TRYFREE(buf);
return uPosFound;
}
/*
Open a Zip file. path contain the full pathname (by example,
on a Windows NT computer "c:\\test\\zlib114.zip" or on an Unix computer
"zlib/zlib114.zip".
If the zipfile cannot be opened (file doesn't exist or in not valid), the
return value is NULL.
Else, the return value is a unzFile Handle, usable with other function
of this unzip package.
*/
extern unzFile ZEXPORT unzOpen2 (path, pzlib_filefunc_def)
const char *path;
zlib_filefunc_def* pzlib_filefunc_def;
{
unz_s us;
unz_s *s;
uLong central_pos,uL;
uLong number_disk; /* number of the current dist, used for
spaning ZIP, unsupported, always 0*/
uLong number_disk_with_CD; /* number the the disk with central dir, used
for spaning ZIP, unsupported, always 0*/
uLong number_entry_CD; /* total number of entries in
the central dir
(same than number_entry on nospan) */
int err=UNZ_OK;
if (unz_copyright[0]!=' ')
return NULL;
if (pzlib_filefunc_def==NULL)
fill_fopen_filefunc(&us.z_filefunc);
else
us.z_filefunc = *pzlib_filefunc_def;
us.filestream= (*(us.z_filefunc.zopen_file))(us.z_filefunc.opaque,
path,
ZLIB_FILEFUNC_MODE_READ |
ZLIB_FILEFUNC_MODE_EXISTING);
if (us.filestream==NULL)
return NULL;
central_pos = unzlocal_SearchCentralDir(&us.z_filefunc,us.filestream);
if (central_pos==0)
err=UNZ_ERRNO;
if (ZSEEK(us.z_filefunc, us.filestream,
central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
err=UNZ_ERRNO;
/* the signature, already checked */
if (unzlocal_getLong(&us.z_filefunc, us.filestream,&uL)!=UNZ_OK)
err=UNZ_ERRNO;
/* number of this disk */
if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_disk)!=UNZ_OK)
err=UNZ_ERRNO;
/* number of the disk with the start of the central directory */
if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_disk_with_CD)!=UNZ_OK)
err=UNZ_ERRNO;
/* total number of entries in the central dir on this disk */
if (unzlocal_getShort(&us.z_filefunc, us.filestream,&us.gi.number_entry)!=UNZ_OK)
err=UNZ_ERRNO;
/* total number of entries in the central dir */
if (unzlocal_getShort(&us.z_filefunc, us.filestream,&number_entry_CD)!=UNZ_OK)
err=UNZ_ERRNO;
if ((number_entry_CD!=us.gi.number_entry) ||
(number_disk_with_CD!=0) ||
(number_disk!=0))
err=UNZ_BADZIPFILE;
/* size of the central directory */
if (unzlocal_getLong(&us.z_filefunc, us.filestream,&us.size_central_dir)!=UNZ_OK)
err=UNZ_ERRNO;
/* offset of start of central directory with respect to the
starting disk number */
if (unzlocal_getLong(&us.z_filefunc, us.filestream,&us.offset_central_dir)!=UNZ_OK)
err=UNZ_ERRNO;
/* zipfile comment length */
if (unzlocal_getShort(&us.z_filefunc, us.filestream,&us.gi.size_comment)!=UNZ_OK)
err=UNZ_ERRNO;
if ((central_pos<us.offset_central_dir+us.size_central_dir) &&
(err==UNZ_OK))
err=UNZ_BADZIPFILE;
if (err!=UNZ_OK)
{
ZCLOSE(us.z_filefunc, us.filestream);
return NULL;
}
us.byte_before_the_zipfile = central_pos -
(us.offset_central_dir+us.size_central_dir);
us.central_pos = central_pos;
us.pfile_in_zip_read = NULL;
us.encrypted = 0;
s=(unz_s*)ALLOC(sizeof(unz_s));
*s=us;
unzGoToFirstFile((unzFile)s);
return (unzFile)s;
}
extern unzFile ZEXPORT unzOpen (path)
const char *path;
{
return unzOpen2(path, NULL);
}
/*
Close a ZipFile opened with unzipOpen.
If there is files inside the .Zip opened with unzipOpenCurrentFile (see later),
these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
return UNZ_OK if there is no problem. */
extern int ZEXPORT unzClose (file)
unzFile file;
{
unz_s* s;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (s->pfile_in_zip_read!=NULL)
unzCloseCurrentFile(file);
ZCLOSE(s->z_filefunc, s->filestream);
TRYFREE(s);
return UNZ_OK;
}
/*
Write info about the ZipFile in the *pglobal_info structure.
No preparation of the structure is needed
return UNZ_OK if there is no problem. */
extern int ZEXPORT unzGetGlobalInfo (file,pglobal_info)
unzFile file;
unz_global_info *pglobal_info;
{
unz_s* s;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
*pglobal_info=s->gi;
return UNZ_OK;
}
/*
Translate date/time from Dos format to tm_unz (readable more easilty)
*/
local void unzlocal_DosDateToTmuDate (ulDosDate, ptm)
uLong ulDosDate;
tm_unz* ptm;
{
uLong uDate;
uDate = (uLong)(ulDosDate>>16);
ptm->tm_mday = (uInt)(uDate&0x1f) ;
ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ;
ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ;
ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800);
ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ;
ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ;
}
/*
Get Info about the current file in the zipfile, with internal only info
*/
local int unzlocal_GetCurrentFileInfoInternal OF((unzFile file,
unz_file_info *pfile_info,
unz_file_info_internal
*pfile_info_internal,
char *szFileName,
uLong fileNameBufferSize,
void *extraField,
uLong extraFieldBufferSize,
char *szComment,
uLong commentBufferSize));
local int unzlocal_GetCurrentFileInfoInternal (file,
pfile_info,
pfile_info_internal,
szFileName, fileNameBufferSize,
extraField, extraFieldBufferSize,
szComment, commentBufferSize)
unzFile file;
unz_file_info *pfile_info;
unz_file_info_internal *pfile_info_internal;
char *szFileName;
uLong fileNameBufferSize;
void *extraField;
uLong extraFieldBufferSize;
char *szComment;
uLong commentBufferSize;
{
unz_s* s;
unz_file_info file_info;
unz_file_info_internal file_info_internal;
int err=UNZ_OK;
uLong uMagic;
long lSeek=0;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (ZSEEK(s->z_filefunc, s->filestream,
s->pos_in_central_dir+s->byte_before_the_zipfile,
ZLIB_FILEFUNC_SEEK_SET)!=0)
err=UNZ_ERRNO;
/* we check the magic */
if (err==UNZ_OK) {
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK)
err=UNZ_ERRNO;
else if (uMagic!=0x02014b50)
err=UNZ_BADZIPFILE;
}
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.version) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.version_needed) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.flag) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.compression_method) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.dosDate) != UNZ_OK)
err=UNZ_ERRNO;
unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date);
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.crc) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.compressed_size) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.uncompressed_size) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_filename) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_extra) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.size_file_comment) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.disk_num_start) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&file_info.internal_fa) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info.external_fa) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&file_info_internal.offset_curfile) != UNZ_OK)
err=UNZ_ERRNO;
lSeek+=file_info.size_filename;
if ((err==UNZ_OK) && (szFileName!=NULL))
{
uLong uSizeRead ;
if (file_info.size_filename<fileNameBufferSize)
{
*(szFileName+file_info.size_filename)='\0';
uSizeRead = file_info.size_filename;
}
else
uSizeRead = fileNameBufferSize;
if ((file_info.size_filename>0) && (fileNameBufferSize>0))
if (ZREAD(s->z_filefunc, s->filestream,szFileName,uSizeRead)!=uSizeRead)
err=UNZ_ERRNO;
lSeek -= uSizeRead;
}
if ((err==UNZ_OK) && (extraField!=NULL))
{
uLong uSizeRead ;
if (file_info.size_file_extra<extraFieldBufferSize)
uSizeRead = file_info.size_file_extra;
else
uSizeRead = extraFieldBufferSize;
if (lSeek!=0) {
if (ZSEEK(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0)
lSeek=0;
else
err=UNZ_ERRNO;
}
if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0))
if (ZREAD(s->z_filefunc, s->filestream,extraField,uSizeRead)!=uSizeRead)
err=UNZ_ERRNO;
lSeek += file_info.size_file_extra - uSizeRead;
}
else
lSeek+=file_info.size_file_extra;
if ((err==UNZ_OK) && (szComment!=NULL))
{
uLong uSizeRead ;
if (file_info.size_file_comment<commentBufferSize)
{
*(szComment+file_info.size_file_comment)='\0';
uSizeRead = file_info.size_file_comment;
}
else
uSizeRead = commentBufferSize;
if (lSeek!=0) {
if (ZSEEK(s->z_filefunc, s->filestream,lSeek,ZLIB_FILEFUNC_SEEK_CUR)==0)
lSeek=0;
else
err=UNZ_ERRNO;
}
if ((file_info.size_file_comment>0) && (commentBufferSize>0))
if (ZREAD(s->z_filefunc, s->filestream,szComment,uSizeRead)!=uSizeRead)
err=UNZ_ERRNO;
lSeek+=file_info.size_file_comment - uSizeRead;
}
else
lSeek+=file_info.size_file_comment;
if ((err==UNZ_OK) && (pfile_info!=NULL))
*pfile_info=file_info;
if ((err==UNZ_OK) && (pfile_info_internal!=NULL))
*pfile_info_internal=file_info_internal;
return err;
}
/*
Write info about the ZipFile in the *pglobal_info structure.
No preparation of the structure is needed
return UNZ_OK if there is no problem.
*/
extern int ZEXPORT unzGetCurrentFileInfo (file,
pfile_info,
szFileName, fileNameBufferSize,
extraField, extraFieldBufferSize,
szComment, commentBufferSize)
unzFile file;
unz_file_info *pfile_info;
char *szFileName;
uLong fileNameBufferSize;
void *extraField;
uLong extraFieldBufferSize;
char *szComment;
uLong commentBufferSize;
{
return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL,
szFileName,fileNameBufferSize,
extraField,extraFieldBufferSize,
szComment,commentBufferSize);
}
/*
Set the current file of the zipfile to the first file.
return UNZ_OK if there is no problem
*/
extern int ZEXPORT unzGoToFirstFile (file)
unzFile file;
{
int err=UNZ_OK;
unz_s* s;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
s->pos_in_central_dir=s->offset_central_dir;
s->num_file=0;
err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
&s->cur_file_info_internal,
NULL,0,NULL,0,NULL,0);
s->current_file_ok = (err == UNZ_OK);
return err;
}
/*
Set the current file of the zipfile to the next file.
return UNZ_OK if there is no problem
return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
*/
extern int ZEXPORT unzGoToNextFile (file)
unzFile file;
{
unz_s* s;
int err;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return UNZ_END_OF_LIST_OF_FILE;
if (s->gi.number_entry != 0xffff) /* 2^16 files overflow hack */
if (s->num_file+1==s->gi.number_entry)
return UNZ_END_OF_LIST_OF_FILE;
s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ;
s->num_file++;
err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
&s->cur_file_info_internal,
NULL,0,NULL,0,NULL,0);
s->current_file_ok = (err == UNZ_OK);
return err;
}
/*
Try locate the file szFileName in the zipfile.
For the iCaseSensitivity signification, see unzipStringFileNameCompare
return value :
UNZ_OK if the file is found. It becomes the current file.
UNZ_END_OF_LIST_OF_FILE if the file is not found
*/
extern int ZEXPORT unzLocateFile (file, szFileName, iCaseSensitivity)
unzFile file;
const char *szFileName;
int iCaseSensitivity;
{
unz_s* s;
int err;
/* We remember the 'current' position in the file so that we can jump
* back there if we fail.
*/
unz_file_info cur_file_infoSaved;
unz_file_info_internal cur_file_info_internalSaved;
uLong num_fileSaved;
uLong pos_in_central_dirSaved;
if (file==NULL)
return UNZ_PARAMERROR;
if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return UNZ_END_OF_LIST_OF_FILE;
/* Save the current state */
num_fileSaved = s->num_file;
pos_in_central_dirSaved = s->pos_in_central_dir;
cur_file_infoSaved = s->cur_file_info;
cur_file_info_internalSaved = s->cur_file_info_internal;
err = unzGoToFirstFile(file);
while (err == UNZ_OK)
{
char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1];
err = unzGetCurrentFileInfo(file,NULL,
szCurrentFileName,sizeof(szCurrentFileName)-1,
NULL,0,NULL,0);
if (err == UNZ_OK)
{
if (unzStringFileNameCompare(szCurrentFileName,
szFileName,iCaseSensitivity)==0)
return UNZ_OK;
err = unzGoToNextFile(file);
}
}
/* We failed, so restore the state of the 'current file' to where we
* were.
*/
s->num_file = num_fileSaved ;
s->pos_in_central_dir = pos_in_central_dirSaved ;
s->cur_file_info = cur_file_infoSaved;
s->cur_file_info_internal = cur_file_info_internalSaved;
return err;
}
/*
///////////////////////////////////////////
// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net)
// I need random access
//
// Further optimization could be realized by adding an ability
// to cache the directory in memory. The goal being a single
// comprehensive file read to put the file I need in a memory.
*/
/*
typedef struct unz_file_pos_s
{
uLong pos_in_zip_directory; // offset in file
uLong num_of_file; // # of file
} unz_file_pos;
*/
extern int ZEXPORT unzGetFilePos(file, file_pos)
unzFile file;
unz_file_pos* file_pos;
{
unz_s* s;
if (file==NULL || file_pos==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return UNZ_END_OF_LIST_OF_FILE;
file_pos->pos_in_zip_directory = s->pos_in_central_dir;
file_pos->num_of_file = s->num_file;
return UNZ_OK;
}
extern int ZEXPORT unzGoToFilePos(file, file_pos)
unzFile file;
unz_file_pos* file_pos;
{
unz_s* s;
int err;
if (file==NULL || file_pos==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
/* jump to the right spot */
s->pos_in_central_dir = file_pos->pos_in_zip_directory;
s->num_file = file_pos->num_of_file;
/* set the current file */
err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
&s->cur_file_info_internal,
NULL,0,NULL,0,NULL,0);
/* return results */
s->current_file_ok = (err == UNZ_OK);
return err;
}
/*
// Unzip Helper Functions - should be here?
///////////////////////////////////////////
*/
/*
Read the local header of the current zipfile
Check the coherency of the local header and info in the end of central
directory about this file
store in *piSizeVar the size of extra info in local header
(filename and size of extra field data)
*/
local int unzlocal_CheckCurrentFileCoherencyHeader (s,piSizeVar,
poffset_local_extrafield,
psize_local_extrafield)
unz_s* s;
uInt* piSizeVar;
uLong *poffset_local_extrafield;
uInt *psize_local_extrafield;
{
uLong uMagic,uData,uFlags;
uLong size_filename;
uLong size_extra_field;
int err=UNZ_OK;
*piSizeVar = 0;
*poffset_local_extrafield = 0;
*psize_local_extrafield = 0;
if (ZSEEK(s->z_filefunc, s->filestream,s->cur_file_info_internal.offset_curfile +
s->byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET)!=0)
return UNZ_ERRNO;
if (err==UNZ_OK) {
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uMagic) != UNZ_OK)
err=UNZ_ERRNO;
else if (uMagic!=0x04034b50)
err=UNZ_BADZIPFILE;
}
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK)
err=UNZ_ERRNO;
/*
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion))
err=UNZ_BADZIPFILE;
*/
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&uData) != UNZ_OK)
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method))
err=UNZ_BADZIPFILE;
if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) &&
(s->cur_file_info.compression_method!=Z_DEFLATED))
err=UNZ_BADZIPFILE;
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* date/time */
err=UNZ_ERRNO;
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* crc */
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) &&
((uFlags & 8)==0))
err=UNZ_BADZIPFILE;
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size compr */
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) &&
((uFlags & 8)==0))
err=UNZ_BADZIPFILE;
if (unzlocal_getLong(&s->z_filefunc, s->filestream,&uData) != UNZ_OK) /* size uncompr */
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) &&
((uFlags & 8)==0))
err=UNZ_BADZIPFILE;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&size_filename) != UNZ_OK)
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename))
err=UNZ_BADZIPFILE;
*piSizeVar += (uInt)size_filename;
if (unzlocal_getShort(&s->z_filefunc, s->filestream,&size_extra_field) != UNZ_OK)
err=UNZ_ERRNO;
*poffset_local_extrafield= s->cur_file_info_internal.offset_curfile +
SIZEZIPLOCALHEADER + size_filename;
*psize_local_extrafield = (uInt)size_extra_field;
*piSizeVar += (uInt)size_extra_field;
return err;
}
/*
Open for reading data the current file in the zipfile.
If there is no error and the file is opened, the return value is UNZ_OK.
*/
extern int ZEXPORT unzOpenCurrentFile3 (file, method, level, raw, password)
unzFile file;
int* method;
int* level;
int raw;
const char* password;
{
int err=UNZ_OK;
uInt iSizeVar;
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
uLong offset_local_extrafield; /* offset of the local extra field */
uInt size_local_extrafield; /* size of the local extra field */
# ifndef NOUNCRYPT
char source[12];
# else
if (password != NULL)
return UNZ_PARAMERROR;
# endif
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return UNZ_PARAMERROR;
if (s->pfile_in_zip_read != NULL)
unzCloseCurrentFile(file);
if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar,
&offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
return UNZ_BADZIPFILE;
pfile_in_zip_read_info = (file_in_zip_read_info_s*)
ALLOC(sizeof(file_in_zip_read_info_s));
if (pfile_in_zip_read_info==NULL)
return UNZ_INTERNALERROR;
pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE);
pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
pfile_in_zip_read_info->pos_local_extrafield=0;
pfile_in_zip_read_info->raw=raw;
if (pfile_in_zip_read_info->read_buffer==NULL)
{
TRYFREE(pfile_in_zip_read_info);
return UNZ_INTERNALERROR;
}
pfile_in_zip_read_info->stream_initialised=0;
if (method!=NULL)
*method = (int)s->cur_file_info.compression_method;
if (level!=NULL)
{
*level = 6;
switch (s->cur_file_info.flag & 0x06)
{
case 6 : *level = 1; break;
case 4 : *level = 2; break;
case 2 : *level = 9; break;
}
}
if ((s->cur_file_info.compression_method!=0) &&
(s->cur_file_info.compression_method!=Z_DEFLATED))
err=UNZ_BADZIPFILE;
pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc;
pfile_in_zip_read_info->crc32=0;
pfile_in_zip_read_info->compression_method =
s->cur_file_info.compression_method;
pfile_in_zip_read_info->filestream=s->filestream;
pfile_in_zip_read_info->z_filefunc=s->z_filefunc;
pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile;
pfile_in_zip_read_info->stream.total_out = 0;
if ((s->cur_file_info.compression_method==Z_DEFLATED) &&
(!raw))
{
pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
pfile_in_zip_read_info->stream.zfree = (free_func)0;
pfile_in_zip_read_info->stream.opaque = (voidpf)0;
pfile_in_zip_read_info->stream.next_in = (voidpf)0;
pfile_in_zip_read_info->stream.avail_in = 0;
err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS);
if (err == Z_OK)
pfile_in_zip_read_info->stream_initialised=1;
else
{
TRYFREE(pfile_in_zip_read_info);
return err;
}
/* windowBits is passed < 0 to tell that there is no zlib header.
* Note that in this case inflate *requires* an extra "dummy" byte
* after the compressed stream in order to complete decompression and
* return Z_STREAM_END.
* In unzip, i don't wait absolutely Z_STREAM_END because I known the
* size of both compressed and uncompressed data
*/
}
pfile_in_zip_read_info->rest_read_compressed =
s->cur_file_info.compressed_size ;
pfile_in_zip_read_info->rest_read_uncompressed =
s->cur_file_info.uncompressed_size ;
pfile_in_zip_read_info->pos_in_zipfile =
s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER +
iSizeVar;
pfile_in_zip_read_info->stream.avail_in = (uInt)0;
s->pfile_in_zip_read = pfile_in_zip_read_info;
# ifndef NOUNCRYPT
if (password != NULL)
{
int i;
s->pcrc_32_tab = get_crc_table();
init_keys(password,s->keys,s->pcrc_32_tab);
if (ZSEEK(s->z_filefunc, s->filestream,
s->pfile_in_zip_read->pos_in_zipfile +
s->pfile_in_zip_read->byte_before_the_zipfile,
SEEK_SET)!=0)
return UNZ_INTERNALERROR;
if(ZREAD(s->z_filefunc, s->filestream,source, 12)<12)
return UNZ_INTERNALERROR;
for (i = 0; i<12; i++)
zdecode(s->keys,s->pcrc_32_tab,source[i]);
s->pfile_in_zip_read->pos_in_zipfile+=12;
s->encrypted=1;
}
# endif
return UNZ_OK;
}
extern int ZEXPORT unzOpenCurrentFile (file)
unzFile file;
{
return unzOpenCurrentFile3(file, NULL, NULL, 0, NULL);
}
extern int ZEXPORT unzOpenCurrentFilePassword (file, password)
unzFile file;
const char* password;
{
return unzOpenCurrentFile3(file, NULL, NULL, 0, password);
}
extern int ZEXPORT unzOpenCurrentFile2 (file,method,level,raw)
unzFile file;
int* method;
int* level;
int raw;
{
return unzOpenCurrentFile3(file, method, level, raw, NULL);
}
/*
Read bytes from the current file.
buf contain buffer where data must be copied
len the size of buf.
return the number of byte copied if somes bytes are copied
return 0 if the end of file was reached
return <0 with error code if there is an error
(UNZ_ERRNO for IO error, or zLib error for uncompress error)
*/
extern int ZEXPORT unzReadCurrentFile (file, buf, len)
unzFile file;
voidp buf;
unsigned len;
{
int err=UNZ_OK;
uInt iRead = 0;
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
if ((pfile_in_zip_read_info->read_buffer == NULL))
return UNZ_END_OF_LIST_OF_FILE;
if (len==0)
return 0;
pfile_in_zip_read_info->stream.next_out = (Bytef*)buf;
pfile_in_zip_read_info->stream.avail_out = (uInt)len;
if ((len>pfile_in_zip_read_info->rest_read_uncompressed) &&
(!(pfile_in_zip_read_info->raw)))
pfile_in_zip_read_info->stream.avail_out =
(uInt)pfile_in_zip_read_info->rest_read_uncompressed;
if ((len>pfile_in_zip_read_info->rest_read_compressed+
pfile_in_zip_read_info->stream.avail_in) &&
(pfile_in_zip_read_info->raw))
pfile_in_zip_read_info->stream.avail_out =
(uInt)pfile_in_zip_read_info->rest_read_compressed+
pfile_in_zip_read_info->stream.avail_in;
while (pfile_in_zip_read_info->stream.avail_out>0)
{
if ((pfile_in_zip_read_info->stream.avail_in==0) &&
(pfile_in_zip_read_info->rest_read_compressed>0))
{
uInt uReadThis = UNZ_BUFSIZE;
if (pfile_in_zip_read_info->rest_read_compressed<uReadThis)
uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
if (uReadThis == 0)
return UNZ_EOF;
if (ZSEEK(pfile_in_zip_read_info->z_filefunc,
pfile_in_zip_read_info->filestream,
pfile_in_zip_read_info->pos_in_zipfile +
pfile_in_zip_read_info->byte_before_the_zipfile,
ZLIB_FILEFUNC_SEEK_SET)!=0)
return UNZ_ERRNO;
if (ZREAD(pfile_in_zip_read_info->z_filefunc,
pfile_in_zip_read_info->filestream,
pfile_in_zip_read_info->read_buffer,
uReadThis)!=uReadThis)
return UNZ_ERRNO;
# ifndef NOUNCRYPT
if(s->encrypted)
{
uInt i;
for(i=0;i<uReadThis;i++)
pfile_in_zip_read_info->read_buffer[i] =
zdecode(s->keys,s->pcrc_32_tab,
pfile_in_zip_read_info->read_buffer[i]);
}
# endif
pfile_in_zip_read_info->pos_in_zipfile += uReadThis;
pfile_in_zip_read_info->rest_read_compressed-=uReadThis;
pfile_in_zip_read_info->stream.next_in =
(Bytef*)pfile_in_zip_read_info->read_buffer;
pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
}
if ((pfile_in_zip_read_info->compression_method==0) || (pfile_in_zip_read_info->raw))
{
uInt uDoCopy,i ;
if ((pfile_in_zip_read_info->stream.avail_in == 0) &&
(pfile_in_zip_read_info->rest_read_compressed == 0))
return (iRead==0) ? UNZ_EOF : iRead;
if (pfile_in_zip_read_info->stream.avail_out <
pfile_in_zip_read_info->stream.avail_in)
uDoCopy = pfile_in_zip_read_info->stream.avail_out ;
else
uDoCopy = pfile_in_zip_read_info->stream.avail_in ;
for (i=0;i<uDoCopy;i++)
*(pfile_in_zip_read_info->stream.next_out+i) =
*(pfile_in_zip_read_info->stream.next_in+i);
pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,
pfile_in_zip_read_info->stream.next_out,
uDoCopy);
pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy;
pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
pfile_in_zip_read_info->stream.next_out += uDoCopy;
pfile_in_zip_read_info->stream.next_in += uDoCopy;
pfile_in_zip_read_info->stream.total_out += uDoCopy;
iRead += uDoCopy;
}
else
{
uLong uTotalOutBefore,uTotalOutAfter;
const Bytef *bufBefore;
uLong uOutThis;
int flush=Z_SYNC_FLUSH;
uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
bufBefore = pfile_in_zip_read_info->stream.next_out;
/*
if ((pfile_in_zip_read_info->rest_read_uncompressed ==
pfile_in_zip_read_info->stream.avail_out) &&
(pfile_in_zip_read_info->rest_read_compressed == 0))
flush = Z_FINISH;
*/
err=inflate(&pfile_in_zip_read_info->stream,flush);
if ((err>=0) && (pfile_in_zip_read_info->stream.msg!=NULL))
err = Z_DATA_ERROR;
uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
uOutThis = uTotalOutAfter-uTotalOutBefore;
pfile_in_zip_read_info->crc32 =
crc32(pfile_in_zip_read_info->crc32,bufBefore,
(uInt)(uOutThis));
pfile_in_zip_read_info->rest_read_uncompressed -=
uOutThis;
iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
if (err==Z_STREAM_END)
return (iRead==0) ? UNZ_EOF : iRead;
if (err!=Z_OK)
break;
}
}
if (err==Z_OK)
return iRead;
return err;
}
/*
Give the current position in uncompressed data
*/
extern z_off_t ZEXPORT unztell (file)
unzFile file;
{
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
return (z_off_t)pfile_in_zip_read_info->stream.total_out;
}
/*
return 1 if the end of file was reached, 0 elsewhere
*/
extern int ZEXPORT unzeof (file)
unzFile file;
{
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
return 1;
else
return 0;
}
/*
Read extra field from the current file (opened by unzOpenCurrentFile)
This is the local-header version of the extra field (sometimes, there is
more info in the local-header version than in the central-header)
if buf==NULL, it return the size of the local extra field that can be read
if buf!=NULL, len is the size of the buffer, the extra header is copied in
buf.
the return value is the number of bytes copied in buf, or (if <0)
the error code
*/
extern int ZEXPORT unzGetLocalExtrafield (file,buf,len)
unzFile file;
voidp buf;
unsigned len;
{
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
uInt read_now;
uLong size_to_read;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
size_to_read = (pfile_in_zip_read_info->size_local_extrafield -
pfile_in_zip_read_info->pos_local_extrafield);
if (buf==NULL)
return (int)size_to_read;
if (len>size_to_read)
read_now = (uInt)size_to_read;
else
read_now = (uInt)len ;
if (read_now==0)
return 0;
if (ZSEEK(pfile_in_zip_read_info->z_filefunc,
pfile_in_zip_read_info->filestream,
pfile_in_zip_read_info->offset_local_extrafield +
pfile_in_zip_read_info->pos_local_extrafield,
ZLIB_FILEFUNC_SEEK_SET)!=0)
return UNZ_ERRNO;
if (ZREAD(pfile_in_zip_read_info->z_filefunc,
pfile_in_zip_read_info->filestream,
buf,read_now)!=read_now)
return UNZ_ERRNO;
return (int)read_now;
}
/*
Close the file in zip opened with unzipOpenCurrentFile
Return UNZ_CRCERROR if all the file was read but the CRC is not good
*/
extern int ZEXPORT unzCloseCurrentFile (file)
unzFile file;
{
int err=UNZ_OK;
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
if ((pfile_in_zip_read_info->rest_read_uncompressed == 0) &&
(!pfile_in_zip_read_info->raw))
{
if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait)
err=UNZ_CRCERROR;
}
TRYFREE(pfile_in_zip_read_info->read_buffer);
pfile_in_zip_read_info->read_buffer = NULL;
if (pfile_in_zip_read_info->stream_initialised)
inflateEnd(&pfile_in_zip_read_info->stream);
pfile_in_zip_read_info->stream_initialised = 0;
TRYFREE(pfile_in_zip_read_info);
s->pfile_in_zip_read=NULL;
return err;
}
/*
Get the global comment string of the ZipFile, in the szComment buffer.
uSizeBuf is the size of the szComment buffer.
return the number of byte copied or an error code <0
*/
extern int ZEXPORT unzGetGlobalComment (file, szComment, uSizeBuf)
unzFile file;
char *szComment;
uLong uSizeBuf;
{
//int err=UNZ_OK;
unz_s* s;
uLong uReadThis ;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
uReadThis = uSizeBuf;
if (uReadThis>s->gi.size_comment)
uReadThis = s->gi.size_comment;
if (ZSEEK(s->z_filefunc,s->filestream,s->central_pos+22,ZLIB_FILEFUNC_SEEK_SET)!=0)
return UNZ_ERRNO;
if (uReadThis>0)
{
*szComment='\0';
if (ZREAD(s->z_filefunc,s->filestream,szComment,uReadThis)!=uReadThis)
return UNZ_ERRNO;
}
if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment))
*(szComment+s->gi.size_comment)='\0';
return (int)uReadThis;
}
/* Additions by RX '2004 */
extern uLong ZEXPORT unzGetOffset (file)
unzFile file;
{
unz_s* s;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return 0;
if (s->gi.number_entry != 0 && s->gi.number_entry != 0xffff)
if (s->num_file==s->gi.number_entry)
return 0;
return s->pos_in_central_dir;
}
extern int ZEXPORT unzSetOffset (file, pos)
unzFile file;
uLong pos;
{
unz_s* s;
int err;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
s->pos_in_central_dir = pos;
s->num_file = s->gi.number_entry; /* hack */
err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
&s->cur_file_info_internal,
NULL,0,NULL,0,NULL,0);
s->current_file_ok = (err == UNZ_OK);
return err;
}
| WhiteVell/Amber | node-v0.10.20/deps/zlib/contrib/minizip/unzip.c | C | mit | 49,394 |
import moment from 'moment';
import UAParser from 'ua-parser-js';
Template.visitorInfo.helpers({
user() {
const user = Template.instance().user.get();
if (user && user.userAgent) {
const ua = new UAParser();
ua.setUA(user.userAgent);
user.os = `${ ua.getOS().name } ${ ua.getOS().version }`;
if (['Mac OS', 'iOS'].indexOf(ua.getOS().name) !== -1) {
user.osIcon = 'icon-apple';
} else {
user.osIcon = `icon-${ ua.getOS().name.toLowerCase() }`;
}
user.browser = `${ ua.getBrowser().name } ${ ua.getBrowser().version }`;
user.browserIcon = `icon-${ ua.getBrowser().name.toLowerCase() }`;
}
return user;
},
room() {
return ChatRoom.findOne({ _id: this.rid });
},
joinTags() {
return this.tags && this.tags.join(', ');
},
customFields() {
const fields = [];
let livechatData = {};
const user = Template.instance().user.get();
if (user) {
livechatData = _.extend(livechatData, user.livechatData);
}
const data = Template.currentData();
if (data && data.rid) {
const room = RocketChat.models.Rooms.findOne(data.rid);
if (room) {
livechatData = _.extend(livechatData, room.livechatData);
}
}
if (!_.isEmpty(livechatData)) {
for (const _id in livechatData) {
if (livechatData.hasOwnProperty(_id)) {
const customFields = Template.instance().customFields.get();
if (customFields) {
const field = _.findWhere(customFields, { _id });
if (field && field.visibility !== 'hidden') {
fields.push({ label: field.label, value: livechatData[_id] });
}
}
}
}
return fields;
}
},
createdAt() {
if (!this.createdAt) {
return '';
}
return moment(this.createdAt).format('L LTS');
},
lastLogin() {
if (!this.lastLogin) {
return '';
}
return moment(this.lastLogin).format('L LTS');
},
editing() {
return Template.instance().action.get() === 'edit';
},
forwarding() {
return Template.instance().action.get() === 'forward';
},
editDetails() {
const instance = Template.instance();
const user = instance.user.get();
return {
visitorId: user ? user._id : null,
roomId: this.rid,
save() {
instance.action.set();
},
cancel() {
instance.action.set();
}
};
},
forwardDetails() {
const instance = Template.instance();
const user = instance.user.get();
return {
visitorId: user ? user._id : null,
roomId: this.rid,
save() {
instance.action.set();
},
cancel() {
instance.action.set();
}
};
},
roomOpen() {
const room = ChatRoom.findOne({ _id: this.rid });
return room.open;
},
guestPool() {
return RocketChat.settings.get('Livechat_Routing_Method') === 'Guest_Pool';
},
showDetail() {
if (Template.instance().action.get()) {
return 'hidden';
}
},
canSeeButtons() {
if (RocketChat.authz.hasRole(Meteor.userId(), 'livechat-manager')) {
return true;
}
const data = Template.currentData();
if (data && data.rid) {
const subscription = RocketChat.models.Subscriptions.findOne({ rid: data.rid });
return subscription !== undefined;
}
return false;
}
});
Template.visitorInfo.events({
'click .edit-livechat'(event, instance) {
event.preventDefault();
instance.action.set('edit');
},
'click .close-livechat'(event) {
event.preventDefault();
swal({
title: t('Closing_chat'),
type: 'input',
inputPlaceholder: t('Please_add_a_comment'),
showCancelButton: true,
closeOnConfirm: false
}, (inputValue) => {
if (!inputValue) {
swal.showInputError(t('Please_add_a_comment_to_close_the_room'));
return false;
}
if (s.trim(inputValue) === '') {
swal.showInputError(t('Please_add_a_comment_to_close_the_room'));
return false;
}
Meteor.call('livechat:closeRoom', this.rid, inputValue, function(error/*, result*/) {
if (error) {
return handleError(error);
}
swal({
title: t('Chat_closed'),
text: t('Chat_closed_successfully'),
type: 'success',
timer: 1000,
showConfirmButton: false
});
});
});
},
'click .return-inquiry'(event) {
event.preventDefault();
swal({
title: t('Would_you_like_to_return_the_inquiry'),
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: t('Yes')
}, () => {
Meteor.call('livechat:returnAsInquiry', this.rid, function(error/*, result*/) {
if (error) {
console.log(error);
} else {
Session.set('openedRoom');
FlowRouter.go('/home');
}
});
});
},
'click .forward-livechat'(event, instance) {
event.preventDefault();
instance.action.set('forward');
}
});
Template.visitorInfo.onCreated(function() {
this.visitorId = new ReactiveVar(null);
this.customFields = new ReactiveVar([]);
this.action = new ReactiveVar();
this.user = new ReactiveVar();
Meteor.call('livechat:getCustomFields', (err, customFields) => {
if (customFields) {
this.customFields.set(customFields);
}
});
const currentData = Template.currentData();
if (currentData && currentData.rid) {
this.autorun(() => {
const room = ChatRoom.findOne(currentData.rid);
if (room && room.v && room.v._id) {
this.visitorId.set(room.v._id);
} else {
this.visitorId.set();
}
});
this.subscribe('livechat:visitorInfo', { rid: currentData.rid });
}
this.autorun(() => {
this.user.set(Meteor.users.findOne({ '_id': this.visitorId.get() }));
});
});
| Achaikos/Rocket.Chat | packages/rocketchat-livechat/client/views/app/tabbar/visitorInfo.js | JavaScript | mit | 5,471 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
File Name: 15.9.5.3-2.js
ECMA Section: 15.9.5.3-2 Date.prototype.valueOf
Description:
The valueOf function returns a number, which is this time value.
The valueOf function is not generic; it generates a runtime error if
its this value is not a Date object. Therefore it cannot be transferred
to other kinds of objects for use as a method.
Author: christine@netscape.com
Date: 12 november 1997
*/
var SECTION = "15.9.5.3-2";
var VERSION = "ECMA_1";
startTest();
var TITLE = "Date.prototype.valueOf";
writeHeaderToLog( SECTION + " "+ TITLE);
addTestCase( TIME_NOW );
addTestCase( TIME_1970 );
addTestCase( TIME_1900 );
addTestCase( TIME_2000 );
addTestCase( UTC_FEB_29_2000 );
addTestCase( UTC_JAN_1_2005 );
test();
function addTestCase( t ) {
new TestCase( SECTION,
"(new Date("+t+").valueOf()",
t,
(new Date(t)).valueOf() );
new TestCase( SECTION,
"(new Date("+(t+1)+").valueOf()",
t+1,
(new Date(t+1)).valueOf() );
new TestCase( SECTION,
"(new Date("+(t-1)+").valueOf()",
t-1,
(new Date(t-1)).valueOf() );
new TestCase( SECTION,
"(new Date("+(t-TZ_ADJUST)+").valueOf()",
t-TZ_ADJUST,
(new Date(t-TZ_ADJUST)).valueOf() );
new TestCase( SECTION,
"(new Date("+(t+TZ_ADJUST)+").valueOf()",
t+TZ_ADJUST,
(new Date(t+TZ_ADJUST)).valueOf() );
}
function MyObject( value ) {
this.value = value;
this.valueOf = Date.prototype.valueOf;
this.toString = new Function( "return this+\"\";");
return this;
}
| havocp/hwf | deps/spidermonkey/tests/ecma/Date/15.9.5.3-2.js | JavaScript | mit | 3,355 |
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var Compiler = require("./Compiler");
var MultiCompiler = require("./MultiCompiler");
var NodeEnvironmentPlugin = require("./node/NodeEnvironmentPlugin");
var WebpackOptionsApply = require("./WebpackOptionsApply");
var WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter");
var validateWebpackOptions = require("./validateWebpackOptions");
var WebpackOptionsValidationError = require("./WebpackOptionsValidationError");
function webpack(options, callback) {
var webpackOptionsValidationErrors = validateWebpackOptions(options);
if(webpackOptionsValidationErrors.length) {
throw new WebpackOptionsValidationError(webpackOptionsValidationErrors);
}
var compiler;
if(Array.isArray(options)) {
compiler = new MultiCompiler(options.map(function(options) {
return webpack(options);
}));
} else if(typeof options === "object") {
new WebpackOptionsDefaulter().process(options);
compiler = new Compiler();
compiler.options = options;
compiler.options = new WebpackOptionsApply().process(options, compiler);
new NodeEnvironmentPlugin().apply(compiler);
compiler.applyPlugins("environment");
compiler.applyPlugins("after-environment");
} else {
throw new Error("Invalid argument: options");
}
if(callback) {
if(typeof callback !== "function") throw new Error("Invalid argument: callback");
if(options.watch === true || (Array.isArray(options) &&
options.some(function(o) {
return o.watch;
}))) {
var watchOptions = (!Array.isArray(options) ? options : options[0]).watchOptions || {};
return compiler.watch(watchOptions, callback);
}
compiler.run(callback);
}
return compiler;
}
exports = module.exports = webpack;
webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter;
webpack.WebpackOptionsApply = WebpackOptionsApply;
webpack.Compiler = Compiler;
webpack.MultiCompiler = MultiCompiler;
webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin;
webpack.validate = validateWebpackOptions;
function exportPlugins(exports, path, plugins) {
plugins.forEach(function(name) {
Object.defineProperty(exports, name, {
configurable: false,
enumerable: true,
get: function() {
return require(path + "/" + name);
}
});
});
}
exportPlugins(exports, ".", [
"DefinePlugin",
"NormalModuleReplacementPlugin",
"ContextReplacementPlugin",
"IgnorePlugin",
"WatchIgnorePlugin",
"BannerPlugin",
"PrefetchPlugin",
"AutomaticPrefetchPlugin",
"ProvidePlugin",
"HotModuleReplacementPlugin",
"SourceMapDevToolPlugin",
"EvalSourceMapDevToolPlugin",
"EvalDevToolModulePlugin",
"CachePlugin",
"ExtendedAPIPlugin",
"ExternalsPlugin",
"JsonpTemplatePlugin",
"LibraryTemplatePlugin",
"LoaderTargetPlugin",
"MemoryOutputFileSystem",
"ProgressPlugin",
"SetVarMainTemplatePlugin",
"UmdMainTemplatePlugin",
"NoErrorsPlugin",
"NewWatchingPlugin",
"EnvironmentPlugin",
"DllPlugin",
"DllReferencePlugin",
"LoaderOptionsPlugin",
"NamedModulesPlugin",
"HashedModuleIdsPlugin",
"ModuleFilenameHelpers"
]);
exportPlugins(exports.optimize = {}, "./optimize", [
"AggressiveMergingPlugin",
"AggressiveSplittingPlugin",
"CommonsChunkPlugin",
"ChunkModuleIdRangePlugin",
"DedupePlugin",
"LimitChunkCountPlugin",
"MinChunkSizePlugin",
"OccurrenceOrderPlugin",
"UglifyJsPlugin"
]);
exportPlugins(exports.dependencies = {}, "./dependencies", []);
| Asamaha/React-Side-Project-Netflix | node_modules/webpack/lib/webpack.js | JavaScript | mit | 3,540 |
# sqlalchemy/exc.py
# Copyright (C) 2005-2011 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Exceptions used with SQLAlchemy.
The base exception class is :class:`.SQLAlchemyError`. Exceptions which are raised as a
result of DBAPI exceptions are all subclasses of
:class:`.DBAPIError`.
"""
import traceback
class SQLAlchemyError(Exception):
"""Generic error class."""
class ArgumentError(SQLAlchemyError):
"""Raised when an invalid or conflicting function argument is supplied.
This error generally corresponds to construction time state errors.
"""
class CircularDependencyError(SQLAlchemyError):
"""Raised by topological sorts when a circular dependency is detected.
There are two scenarios where this error occurs:
* In a Session flush operation, if two objects are mutually dependent
on each other, they can not be inserted or deleted via INSERT or
DELETE statements alone; an UPDATE will be needed to post-associate
or pre-deassociate one of the foreign key constrained values.
The ``post_update`` flag described at :ref:`post_update` can resolve
this cycle.
* In a :meth:`.MetaData.create_all`, :meth:`.MetaData.drop_all`,
:attr:`.MetaData.sorted_tables` operation, two :class:`.ForeignKey`
or :class:`.ForeignKeyConstraint` objects mutually refer to each
other. Apply the ``use_alter=True`` flag to one or both,
see :ref:`use_alter`.
"""
def __init__(self, message, cycles, edges):
message += " Cycles: %r all edges: %r" % (cycles, edges)
SQLAlchemyError.__init__(self, message)
self.cycles = cycles
self.edges = edges
class CompileError(SQLAlchemyError):
"""Raised when an error occurs during SQL compilation"""
class IdentifierError(SQLAlchemyError):
"""Raised when a schema name is beyond the max character limit"""
# Moved to orm.exc; compatibility definition installed by orm import until 0.6
ConcurrentModificationError = None
class DisconnectionError(SQLAlchemyError):
"""A disconnect is detected on a raw DB-API connection.
This error is raised and consumed internally by a connection pool. It can
be raised by the :meth:`.PoolEvents.checkout` event
so that the host pool forces a retry; the exception will be caught
three times in a row before the pool gives up and raises
:class:`~sqlalchemy.exc.InvalidRequestError` regarding the connection attempt.
"""
# Moved to orm.exc; compatibility definition installed by orm import until 0.6
FlushError = None
class TimeoutError(SQLAlchemyError):
"""Raised when a connection pool times out on getting a connection."""
class InvalidRequestError(SQLAlchemyError):
"""SQLAlchemy was asked to do something it can't do.
This error generally corresponds to runtime state errors.
"""
class ResourceClosedError(InvalidRequestError):
"""An operation was requested from a connection, cursor, or other
object that's in a closed state."""
class NoSuchColumnError(KeyError, InvalidRequestError):
"""A nonexistent column is requested from a ``RowProxy``."""
class NoReferenceError(InvalidRequestError):
"""Raised by ``ForeignKey`` to indicate a reference cannot be resolved."""
class NoReferencedTableError(NoReferenceError):
"""Raised by ``ForeignKey`` when the referred ``Table`` cannot be located."""
def __init__(self, message, tname):
NoReferenceError.__init__(self, message)
self.table_name = tname
class NoReferencedColumnError(NoReferenceError):
"""Raised by ``ForeignKey`` when the referred ``Column`` cannot be located."""
def __init__(self, message, tname, cname):
NoReferenceError.__init__(self, message)
self.table_name = tname
self.column_name = cname
class NoSuchTableError(InvalidRequestError):
"""Table does not exist or is not visible to a connection."""
class UnboundExecutionError(InvalidRequestError):
"""SQL was attempted without a database connection to execute it on."""
class DontWrapMixin(object):
"""A mixin class which, when applied to a user-defined Exception class,
will not be wrapped inside of :class:`.StatementError` if the error is
emitted within the process of executing a statement.
E.g.::
from sqlalchemy.exc import DontWrapMixin
class MyCustomException(Exception, DontWrapMixin):
pass
class MySpecialType(TypeDecorator):
impl = String
def process_bind_param(self, value, dialect):
if value == 'invalid':
raise MyCustomException("invalid!")
"""
import sys
if sys.version_info < (2, 5):
class DontWrapMixin:
pass
# Moved to orm.exc; compatibility definition installed by orm import until 0.6
UnmappedColumnError = None
class StatementError(SQLAlchemyError):
"""An error occurred during execution of a SQL statement.
:class:`.StatementError` wraps the exception raised
during execution, and features :attr:`.statement`
and :attr:`.params` attributes which supply context regarding
the specifics of the statement which had an issue.
The wrapped exception object is available in
the :attr:`.orig` attribute.
"""
def __init__(self, message, statement, params, orig):
SQLAlchemyError.__init__(self, message)
self.statement = statement
self.params = params
self.orig = orig
def __str__(self):
from sqlalchemy.sql import util
params_repr = util._repr_params(self.params, 10)
return ' '.join((SQLAlchemyError.__str__(self),
repr(self.statement), repr(params_repr)))
class DBAPIError(StatementError):
"""Raised when the execution of a database operation fails.
``DBAPIError`` wraps exceptions raised by the DB-API underlying the
database operation. Driver-specific implementations of the standard
DB-API exception types are wrapped by matching sub-types of SQLAlchemy's
``DBAPIError`` when possible. DB-API's ``Error`` type maps to
``DBAPIError`` in SQLAlchemy, otherwise the names are identical. Note
that there is no guarantee that different DB-API implementations will
raise the same exception type for any given error condition.
:class:`.DBAPIError` features :attr:`.statement`
and :attr:`.params` attributes which supply context regarding
the specifics of the statement which had an issue, for the
typical case when the error was raised within the context of
emitting a SQL statement.
The wrapped exception object is available in the :attr:`.orig` attribute.
Its type and properties are DB-API implementation specific.
"""
@classmethod
def instance(cls, statement, params,
orig,
dbapi_base_err,
connection_invalidated=False):
# Don't ever wrap these, just return them directly as if
# DBAPIError didn't exist.
if isinstance(orig, (KeyboardInterrupt, SystemExit, DontWrapMixin)):
return orig
if orig is not None:
# not a DBAPI error, statement is present.
# raise a StatementError
if not isinstance(orig, dbapi_base_err) and statement:
return StatementError(
"%s (original cause: %s)" % (
str(orig),
traceback.format_exception_only(orig.__class__, orig)[-1].strip()
), statement, params, orig)
name, glob = orig.__class__.__name__, globals()
if name in glob and issubclass(glob[name], DBAPIError):
cls = glob[name]
return cls(statement, params, orig, connection_invalidated)
def __init__(self, statement, params, orig, connection_invalidated=False):
try:
text = str(orig)
except (KeyboardInterrupt, SystemExit):
raise
except Exception, e:
text = 'Error in str() of DB-API-generated exception: ' + str(e)
StatementError.__init__(
self,
'(%s) %s' % (orig.__class__.__name__, text),
statement,
params,
orig
)
self.connection_invalidated = connection_invalidated
class InterfaceError(DBAPIError):
"""Wraps a DB-API InterfaceError."""
class DatabaseError(DBAPIError):
"""Wraps a DB-API DatabaseError."""
class DataError(DatabaseError):
"""Wraps a DB-API DataError."""
class OperationalError(DatabaseError):
"""Wraps a DB-API OperationalError."""
class IntegrityError(DatabaseError):
"""Wraps a DB-API IntegrityError."""
class InternalError(DatabaseError):
"""Wraps a DB-API InternalError."""
class ProgrammingError(DatabaseError):
"""Wraps a DB-API ProgrammingError."""
class NotSupportedError(DatabaseError):
"""Wraps a DB-API NotSupportedError."""
# Warnings
class SADeprecationWarning(DeprecationWarning):
"""Issued once per usage of a deprecated API."""
class SAPendingDeprecationWarning(PendingDeprecationWarning):
"""Issued once per usage of a deprecated API."""
class SAWarning(RuntimeWarning):
"""Issued at runtime."""
| Sir-Henry-Curtis/Ironworks | lib/sqlalchemy/exc.py | Python | mit | 9,537 |
// This file has been autogenerated.
exports.setEnvironment = function() {
process.env['AZURE_SUBSCRIPTION_ID'] = 'dummy';
};
exports.scopes = [[function (nock) {
var result =
nock('http://management.azure.com:443')
.get('/providers/Microsoft.Intune/locations/fef.msua06/flaggedUsers?api-version=2015-01-14-preview')
.reply(200, "{\"value\":[{\"id\":\"/providers/Microsoft.Intune/locations/fef.msua06/flaggedUsers/d8aeb100-6e17-4cf7-bbda-169000d03c1e\",\"name\":\"d8aeb100-6e17-4cf7-bbda-169000d03c1e\",\"type\":\"Microsoft.Intune/locations/flaggedUsers\",\"properties\":{\"friendlyName\":\"Joe Admin\",\"errorCount\":1}}]}", { 'cache-control': 'no-cache',
pragma: 'no-cache',
'content-length': '271',
'content-type': 'application/json;odata=minimalmetadata;streaming=true;charset=utf-8,application/json;odata=minimalmetadata;streaming=true;charset=utf-8',
expires: '-1',
'x-ms-ratelimit-remaining-tenant-reads': '14997',
'elapsed-time-milliseconds': '525',
'service-name': 'AdminExperienceService',
'client-request-id': '73f53fcc-3ffc-4490-ba47-17437af7ae73',
'unique-request-id': '13c5f5fe-4211-4316-ae14-38ddd13060ef',
'x-ms-request-id': '13c5f5fe-4211-4316-ae14-38ddd13060ef',
'related-activity-id': '13c5f5fe-4211-4316-ae14-38ddd13060ef',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
dataserviceversion: '3.0;',
server: 'Microsoft-HTTPAPI/2.0',
'x-ms-correlation-request-id': 'be0b6772-1b84-4c11-95d1-c5d8a6aec295',
'x-ms-routing-request-id': 'WESTUS:20151204T223626Z:be0b6772-1b84-4c11-95d1-c5d8a6aec295',
date: 'Fri, 04 Dec 2015 22:36:26 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('https://management.azure.com:443')
.get('/providers/Microsoft.Intune/locations/fef.msua06/flaggedUsers?api-version=2015-01-14-preview')
.reply(200, "{\"value\":[{\"id\":\"/providers/Microsoft.Intune/locations/fef.msua06/flaggedUsers/d8aeb100-6e17-4cf7-bbda-169000d03c1e\",\"name\":\"d8aeb100-6e17-4cf7-bbda-169000d03c1e\",\"type\":\"Microsoft.Intune/locations/flaggedUsers\",\"properties\":{\"friendlyName\":\"Joe Admin\",\"errorCount\":1}}]}", { 'cache-control': 'no-cache',
pragma: 'no-cache',
'content-length': '271',
'content-type': 'application/json;odata=minimalmetadata;streaming=true;charset=utf-8,application/json;odata=minimalmetadata;streaming=true;charset=utf-8',
expires: '-1',
'x-ms-ratelimit-remaining-tenant-reads': '14997',
'elapsed-time-milliseconds': '525',
'service-name': 'AdminExperienceService',
'client-request-id': '73f53fcc-3ffc-4490-ba47-17437af7ae73',
'unique-request-id': '13c5f5fe-4211-4316-ae14-38ddd13060ef',
'x-ms-request-id': '13c5f5fe-4211-4316-ae14-38ddd13060ef',
'related-activity-id': '13c5f5fe-4211-4316-ae14-38ddd13060ef',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
dataserviceversion: '3.0;',
server: 'Microsoft-HTTPAPI/2.0',
'x-ms-correlation-request-id': 'be0b6772-1b84-4c11-95d1-c5d8a6aec295',
'x-ms-routing-request-id': 'WESTUS:20151204T223626Z:be0b6772-1b84-4c11-95d1-c5d8a6aec295',
date: 'Fri, 04 Dec 2015 22:36:26 GMT',
connection: 'close' });
return result; }]]; | lmazuel/azure-sdk-for-node | test/recordings/intune-tests/Intune_Resource_Management_-_FlaggedUsers_-_GetMAMFlaggedUsers.nock.js | JavaScript | mit | 3,179 |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Search.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Divides text using language-specific rules.
/// </summary>
[Newtonsoft.Json.JsonObject("#Microsoft.Azure.Search.MicrosoftLanguageTokenizer")]
public partial class MicrosoftLanguageTokenizer : Tokenizer
{
/// <summary>
/// Initializes a new instance of the MicrosoftLanguageTokenizer class.
/// </summary>
public MicrosoftLanguageTokenizer()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the MicrosoftLanguageTokenizer class.
/// </summary>
/// <param name="name">The name of the tokenizer. It must only contain
/// letters, digits, spaces, dashes or underscores, can only start and
/// end with alphanumeric characters, and is limited to 128
/// characters.</param>
/// <param name="maxTokenLength">The maximum token length. Tokens
/// longer than the maximum length are split. Maximum token length that
/// can be used is 300 characters. Tokens longer than 300 characters
/// are first split into tokens of length 300 and then each of those
/// tokens is split based on the max token length set. Default is
/// 255.</param>
/// <param name="isSearchTokenizer">A value indicating how the
/// tokenizer is used. Set to true if used as the search tokenizer, set
/// to false if used as the indexing tokenizer. Default is
/// false.</param>
/// <param name="language">The language to use. The default is English.
/// Possible values include: 'bangla', 'bulgarian', 'catalan',
/// 'chineseSimplified', 'chineseTraditional', 'croatian', 'czech',
/// 'danish', 'dutch', 'english', 'french', 'german', 'greek',
/// 'gujarati', 'hindi', 'icelandic', 'indonesian', 'italian',
/// 'japanese', 'kannada', 'korean', 'malay', 'malayalam', 'marathi',
/// 'norwegianBokmaal', 'polish', 'portuguese', 'portugueseBrazilian',
/// 'punjabi', 'romanian', 'russian', 'serbianCyrillic',
/// 'serbianLatin', 'slovenian', 'spanish', 'swedish', 'tamil',
/// 'telugu', 'thai', 'ukrainian', 'urdu', 'vietnamese'</param>
public MicrosoftLanguageTokenizer(string name, int? maxTokenLength = default(int?), bool? isSearchTokenizer = default(bool?), MicrosoftTokenizerLanguage? language = default(MicrosoftTokenizerLanguage?))
: base(name)
{
MaxTokenLength = maxTokenLength;
IsSearchTokenizer = isSearchTokenizer;
Language = language;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the maximum token length. Tokens longer than the
/// maximum length are split. Maximum token length that can be used is
/// 300 characters. Tokens longer than 300 characters are first split
/// into tokens of length 300 and then each of those tokens is split
/// based on the max token length set. Default is 255.
/// </summary>
[JsonProperty(PropertyName = "maxTokenLength")]
public int? MaxTokenLength { get; set; }
/// <summary>
/// Gets or sets a value indicating how the tokenizer is used. Set to
/// true if used as the search tokenizer, set to false if used as the
/// indexing tokenizer. Default is false.
/// </summary>
[JsonProperty(PropertyName = "isSearchTokenizer")]
public bool? IsSearchTokenizer { get; set; }
/// <summary>
/// Gets or sets the language to use. The default is English. Possible
/// values include: 'bangla', 'bulgarian', 'catalan',
/// 'chineseSimplified', 'chineseTraditional', 'croatian', 'czech',
/// 'danish', 'dutch', 'english', 'french', 'german', 'greek',
/// 'gujarati', 'hindi', 'icelandic', 'indonesian', 'italian',
/// 'japanese', 'kannada', 'korean', 'malay', 'malayalam', 'marathi',
/// 'norwegianBokmaal', 'polish', 'portuguese', 'portugueseBrazilian',
/// 'punjabi', 'romanian', 'russian', 'serbianCyrillic',
/// 'serbianLatin', 'slovenian', 'spanish', 'swedish', 'tamil',
/// 'telugu', 'thai', 'ukrainian', 'urdu', 'vietnamese'
/// </summary>
[JsonProperty(PropertyName = "language")]
public MicrosoftTokenizerLanguage? Language { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
if (MaxTokenLength > 300)
{
throw new ValidationException(ValidationRules.InclusiveMaximum, "MaxTokenLength", 300);
}
}
}
}
| brjohnstmsft/azure-sdk-for-net | sdk/search/Microsoft.Azure.Search.Service/src/Generated/Models/MicrosoftLanguageTokenizer.cs | C# | mit | 5,513 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
public class TestClass
{
public static int m_TestInt = 1;
~TestClass()
{
m_TestInt--;
}
}
/// <summary>
/// KeepAlive(System.Object)
/// </summary>
public class GCKeepAlive
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call KeepAlive to prevent an object to be GCed");
try
{
TestClass tc = new TestClass();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
if (TestClass.m_TestInt != 1)
{
TestLibrary.TestFramework.LogError("001.1", "Calling KeepAlive can not prevent an object to be GCed");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] TestClass.m_TestInt = " + TestClass.m_TestInt);
retVal = false;
}
GC.KeepAlive(tc);
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
GCKeepAlive test = new GCKeepAlive();
TestLibrary.TestFramework.BeginTestCase("GCKeepAlive");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| ruben-ayrapetyan/coreclr | tests/src/CoreMangLib/cti/system/gc/gckeepalive.cs | C# | mit | 2,206 |
/* ========================================================================
* Bootstrap: carousel.js v3.0.0
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function ($) { "use strict";
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused =
this.sliding =
this.interval =
this.$active =
this.$items = null
this.options.pause == 'hover' && this.$element
.on('mouseenter', $.proxy(this.pause, this))
.on('mouseleave', $.proxy(this.cycle, this))
}
Carousel.DEFAULTS = {
interval: 5000
, pause: 'hover'
, wrap: true
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getActiveIndex = function () {
this.$active = this.$element.find('.item.active')
this.$items = this.$active.parent().children()
return this.$items.index(this.$active)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getActiveIndex()
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid', function () { that.to(pos) })
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition.end) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || $active[type]()
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var fallback = type == 'next' ? 'first' : 'last'
var that = this
if (!$next.length) {
if (!this.options.wrap) return
$next = this.$element.find('.item')[fallback]()
}
this.sliding = true
isCycling && this.pause()
var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction })
if ($next.hasClass('active')) return
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
this.$element.one('slid', function () {
var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()])
$nextIndicator && $nextIndicator.addClass('active')
})
}
if ($.support.transition && this.$element.hasClass('slide')) {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one($.support.transition.end, function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () { that.$element.trigger('slid') }, 0)
})
.emulateTransitionEnd(600)
} else {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger('slid')
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
var old = $.fn.carousel
$.fn.carousel = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
$(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
var $this = $(this), href
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
$target.carousel(options)
if (slideIndex = $this.attr('data-slide-to')) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
})
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
$carousel.carousel($carousel.data())
})
})
}(window.jQuery);
| billybonz1/cdnjs | ajax/libs/twitter-bootstrap/3.0.1/js/carousel.js | JavaScript | mit | 6,452 |
/*
* /MathJax/localization/en/en.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation("en",null,{menuTitle:"English",version:"2.3",isLoaded:true,domains:{_:{version:"2.3",isLoaded:true,strings:{CookieConfig:"MathJax has found a user-configuration cookie that includes code to be run. Do you want to run it?\n\n(You should press Cancel unless you set up the cookie yourself.)",MathProcessingError:"Math Processing Error",MathError:"Math Error",LoadFile:"Loading %1",Loading:"Loading",LoadFailed:"File failed to load: %1",ProcessMath:"Processing Math: %1%%",Processing:"Processing",TypesetMath:"Typesetting Math: %1%%",Typesetting:"Typesetting",MathJaxNotSupported:"Your browser does not support MathJax"}},FontWarnings:{},"HTML-CSS":{},HelpDialog:{},MathML:{},MathMenu:{},TeX:{}},plural:function(a){if(a===1){return 1}return 2},number:function(a){return a}});MathJax.Ajax.loadComplete("[MathJax]/localization/en/en.js");
| sinkcup/cdnjs | ajax/libs/mathjax/2.3/localization/en/en.js | JavaScript | mit | 1,534 |
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
function InsertionText(text, consumeBlanks) {
this.text = text;
this.origLength = text.length;
this.offsets = [];
this.consumeBlanks = consumeBlanks;
this.startPos = this.findFirstNonBlank();
this.endPos = this.findLastNonBlank();
}
var WHITE_RE = /[ \f\n\r\t\v\u00A0\u2028\u2029]/;
InsertionText.prototype = {
findFirstNonBlank: function () {
var pos = -1,
text = this.text,
len = text.length,
i;
for (i = 0; i < len; i += 1) {
if (!text.charAt(i).match(WHITE_RE)) {
pos = i;
break;
}
}
return pos;
},
findLastNonBlank: function () {
var text = this.text,
len = text.length,
pos = text.length + 1,
i;
for (i = len - 1; i >= 0; i -= 1) {
if (!text.charAt(i).match(WHITE_RE)) {
pos = i;
break;
}
}
return pos;
},
originalLength: function () {
return this.origLength;
},
insertAt: function (col, str, insertBefore, consumeBlanks) {
consumeBlanks = typeof consumeBlanks === 'undefined' ? this.consumeBlanks : consumeBlanks;
col = col > this.originalLength() ? this.originalLength() : col;
col = col < 0 ? 0 : col;
if (consumeBlanks) {
if (col <= this.startPos) {
col = 0;
}
if (col > this.endPos) {
col = this.origLength;
}
}
var len = str.length,
offset = this.findOffset(col, len, insertBefore),
realPos = col + offset,
text = this.text;
this.text = text.substring(0, realPos) + str + text.substring(realPos);
return this;
},
findOffset: function (pos, len, insertBefore) {
var offsets = this.offsets,
offsetObj,
cumulativeOffset = 0,
i;
for (i = 0; i < offsets.length; i += 1) {
offsetObj = offsets[i];
if (offsetObj.pos < pos || (offsetObj.pos === pos && !insertBefore)) {
cumulativeOffset += offsetObj.len;
}
if (offsetObj.pos >= pos) {
break;
}
}
if (offsetObj && offsetObj.pos === pos) {
offsetObj.len += len;
} else {
offsets.splice(i, 0, { pos: pos, len: len });
}
return cumulativeOffset;
},
wrap: function (startPos, startText, endPos, endText, consumeBlanks) {
this.insertAt(startPos, startText, true, consumeBlanks);
this.insertAt(endPos, endText, false, consumeBlanks);
return this;
},
wrapLine: function (startText, endText) {
this.wrap(0, startText, this.originalLength(), endText);
},
toString: function () {
return this.text;
}
};
module.exports = InsertionText; | ZhenghuiMa/Demo | node_modules/istanbul-threshold-checker/node_modules/istanbul/lib/util/insertion-text.js | JavaScript | mit | 3,117 |
if (require.register) {
var qs = require('querystring');
} else {
var qs = require('../')
, expect = require('expect.js');
}
describe('qs.parse()', function(){
it('should support the basics', function(){
expect(qs.parse('0=foo')).to.eql({ '0': 'foo' });
expect(qs.parse('foo=c++'))
.to.eql({ foo: 'c ' });
expect(qs.parse('a[>=]=23'))
.to.eql({ a: { '>=': '23' }});
expect(qs.parse('a[<=>]==23'))
.to.eql({ a: { '<=>': '=23' }});
expect(qs.parse('a[==]=23'))
.to.eql({ a: { '==': '23' }});
expect(qs.parse('foo'))
.to.eql({ foo: '' });
expect(qs.parse('foo=bar'))
.to.eql({ foo: 'bar' });
expect(qs.parse(' foo = bar = baz '))
.to.eql({ ' foo ': ' bar = baz ' });
expect(qs.parse('foo=bar=baz'))
.to.eql({ foo: 'bar=baz' });
expect(qs.parse('foo=bar&bar=baz'))
.to.eql({ foo: 'bar', bar: 'baz' });
expect(qs.parse('foo=bar&baz'))
.to.eql({ foo: 'bar', baz: '' });
expect(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'))
.to.eql({
cht: 'p3'
, chd: 't:60,40'
, chs: '250x100'
, chl: 'Hello|World'
});
})
it('should support encoded = signs', function(){
expect(qs.parse('he%3Dllo=th%3Dere'))
.to.eql({ 'he=llo': 'th=ere' });
})
it('should support nesting', function(){
expect(qs.parse('ops[>=]=25'))
.to.eql({ ops: { '>=': '25' }});
expect(qs.parse('user[name]=tj'))
.to.eql({ user: { name: 'tj' }});
expect(qs.parse('user[name][first]=tj&user[name][last]=holowaychuk'))
.to.eql({ user: { name: { first: 'tj', last: 'holowaychuk' }}});
})
it('should support array notation', function(){
expect(qs.parse('images[]'))
.to.eql({ images: [] });
expect(qs.parse('user[]=tj'))
.to.eql({ user: ['tj'] });
expect(qs.parse('user[]=tj&user[]=tobi&user[]=jane'))
.to.eql({ user: ['tj', 'tobi', 'jane'] });
expect(qs.parse('user[names][]=tj&user[names][]=tyler'))
.to.eql({ user: { names: ['tj', 'tyler'] }});
expect(qs.parse('user[names][]=tj&user[names][]=tyler&user[email]=tj@vision-media.ca'))
.to.eql({ user: { names: ['tj', 'tyler'], email: 'tj@vision-media.ca' }});
expect(qs.parse('items=a&items=b'))
.to.eql({ items: ['a', 'b'] });
expect(qs.parse('user[names]=tj&user[names]=holowaychuk&user[names]=TJ'))
.to.eql({ user: { names: ['tj', 'holowaychuk', 'TJ'] }});
expect(qs.parse('user[name][first]=tj&user[name][first]=TJ'))
.to.eql({ user: { name: { first: ['tj', 'TJ'] }}});
var o = qs.parse('existing[fcbaebfecc][name][last]=tj')
expect(o).to.eql({ existing: { 'fcbaebfecc': { name: { last: 'tj' }}}})
expect(Array.isArray(o.existing)).to.equal(false);
})
it('should support arrays with indexes', function(){
expect(qs.parse('foo[0]=bar&foo[1]=baz')).to.eql({ foo: ['bar', 'baz'] });
expect(qs.parse('foo[1]=bar&foo[0]=baz')).to.eql({ foo: ['baz', 'bar'] });
expect(qs.parse('foo[base64]=RAWR')).to.eql({ foo: { base64: 'RAWR' }});
expect(qs.parse('foo[64base]=RAWR')).to.eql({ foo: { '64base': 'RAWR' }});
})
it('should expand to an array when dupliate keys are present', function(){
expect(qs.parse('items=bar&items=baz&items=raz'))
.to.eql({ items: ['bar', 'baz', 'raz'] });
})
it('should support right-hand side brackets', function(){
expect(qs.parse('pets=["tobi"]'))
.to.eql({ pets: '["tobi"]' });
expect(qs.parse('operators=[">=", "<="]'))
.to.eql({ operators: '[">=", "<="]' });
expect(qs.parse('op[>=]=[1,2,3]'))
.to.eql({ op: { '>=': '[1,2,3]' }});
expect(qs.parse('op[>=]=[1,2,3]&op[=]=[[[[1]]]]'))
.to.eql({ op: { '>=': '[1,2,3]', '=': '[[[[1]]]]' }});
})
it('should support empty values', function(){
expect(qs.parse('')).to.eql({});
expect(qs.parse(undefined)).to.eql({});
expect(qs.parse(null)).to.eql({});
})
it('should transform arrays to objects', function(){
expect(qs.parse('foo[0]=bar&foo[bad]=baz')).to.eql({ foo: { 0: "bar", bad: "baz" }});
expect(qs.parse('foo[bad]=baz&foo[0]=bar')).to.eql({ foo: { 0: "bar", bad: "baz" }});
})
it('should support malformed uri chars', function(){
expect(qs.parse('{%:%}')).to.eql({ '{%:%}': '' });
expect(qs.parse('foo=%:%}')).to.eql({ 'foo': '%:%}' });
})
it('should support semi-parsed strings', function(){
expect(qs.parse({ 'user[name]': 'tobi' }))
.to.eql({ user: { name: 'tobi' }});
expect(qs.parse({ 'user[name]': 'tobi', 'user[email][main]': 'tobi@lb.com' }))
.to.eql({ user: { name: 'tobi', email: { main: 'tobi@lb.com' } }});
})
it('should not produce empty keys', function(){
expect(qs.parse('_r=1&'))
.to.eql({ _r: '1' })
})
})
| vwolfley/NC-Google.Map | node_modules/grunt-contrib-watch/node_modules/tiny-lr-fork/node_modules/qs/test/parse.js | JavaScript | mit | 4,817 |
/*!
* jQuery UI Position 1.10.3
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/position/
*/
!function(a,b){function c(a,b,c){return[parseFloat(a[0])*(n.test(a[0])?b/100:1),parseFloat(a[1])*(n.test(a[1])?c/100:1)]}function d(b,c){return parseInt(a.css(b,c),10)||0}function e(b){var c=b[0];return 9===c.nodeType?{width:b.width(),height:b.height(),offset:{top:0,left:0}}:a.isWindow(c)?{width:b.width(),height:b.height(),offset:{top:b.scrollTop(),left:b.scrollLeft()}}:c.preventDefault?{width:0,height:0,offset:{top:c.pageY,left:c.pageX}}:{width:b.outerWidth(),height:b.outerHeight(),offset:b.offset()}}a.ui=a.ui||{};var f,g=Math.max,h=Math.abs,i=Math.round,j=/left|center|right/,k=/top|center|bottom/,l=/[\+\-]\d+(\.[\d]+)?%?/,m=/^\w+/,n=/%$/,o=a.fn.position;a.position={scrollbarWidth:function(){if(f!==b)return f;var c,d,e=a("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),g=e.children()[0];return a("body").append(e),c=g.offsetWidth,e.css("overflow","scroll"),d=g.offsetWidth,c===d&&(d=e[0].clientWidth),e.remove(),f=c-d},getScrollInfo:function(b){var c=b.isWindow?"":b.element.css("overflow-x"),d=b.isWindow?"":b.element.css("overflow-y"),e="scroll"===c||"auto"===c&&b.width<b.element[0].scrollWidth,f="scroll"===d||"auto"===d&&b.height<b.element[0].scrollHeight;return{width:f?a.position.scrollbarWidth():0,height:e?a.position.scrollbarWidth():0}},getWithinInfo:function(b){var c=a(b||window),d=a.isWindow(c[0]);return{element:c,isWindow:d,offset:c.offset()||{left:0,top:0},scrollLeft:c.scrollLeft(),scrollTop:c.scrollTop(),width:d?c.width():c.outerWidth(),height:d?c.height():c.outerHeight()}}},a.fn.position=function(b){if(!b||!b.of)return o.apply(this,arguments);b=a.extend({},b);var f,n,p,q,r,s,t=a(b.of),u=a.position.getWithinInfo(b.within),v=a.position.getScrollInfo(u),w=(b.collision||"flip").split(" "),x={};return s=e(t),t[0].preventDefault&&(b.at="left top"),n=s.width,p=s.height,q=s.offset,r=a.extend({},q),a.each(["my","at"],function(){var a,c,d=(b[this]||"").split(" ");1===d.length&&(d=j.test(d[0])?d.concat(["center"]):k.test(d[0])?["center"].concat(d):["center","center"]),d[0]=j.test(d[0])?d[0]:"center",d[1]=k.test(d[1])?d[1]:"center",a=l.exec(d[0]),c=l.exec(d[1]),x[this]=[a?a[0]:0,c?c[0]:0],b[this]=[m.exec(d[0])[0],m.exec(d[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===b.at[0]?r.left+=n:"center"===b.at[0]&&(r.left+=n/2),"bottom"===b.at[1]?r.top+=p:"center"===b.at[1]&&(r.top+=p/2),f=c(x.at,n,p),r.left+=f[0],r.top+=f[1],this.each(function(){var e,j,k=a(this),l=k.outerWidth(),m=k.outerHeight(),o=d(this,"marginLeft"),s=d(this,"marginTop"),y=l+o+d(this,"marginRight")+v.width,z=m+s+d(this,"marginBottom")+v.height,A=a.extend({},r),B=c(x.my,k.outerWidth(),k.outerHeight());"right"===b.my[0]?A.left-=l:"center"===b.my[0]&&(A.left-=l/2),"bottom"===b.my[1]?A.top-=m:"center"===b.my[1]&&(A.top-=m/2),A.left+=B[0],A.top+=B[1],a.support.offsetFractions||(A.left=i(A.left),A.top=i(A.top)),e={marginLeft:o,marginTop:s},a.each(["left","top"],function(c,d){a.ui.position[w[c]]&&a.ui.position[w[c]][d](A,{targetWidth:n,targetHeight:p,elemWidth:l,elemHeight:m,collisionPosition:e,collisionWidth:y,collisionHeight:z,offset:[f[0]+B[0],f[1]+B[1]],my:b.my,at:b.at,within:u,elem:k})}),b.using&&(j=function(a){var c=q.left-A.left,d=c+n-l,e=q.top-A.top,f=e+p-m,i={target:{element:t,left:q.left,top:q.top,width:n,height:p},element:{element:k,left:A.left,top:A.top,width:l,height:m},horizontal:0>d?"left":c>0?"right":"center",vertical:0>f?"top":e>0?"bottom":"middle"};l>n&&h(c+d)<n&&(i.horizontal="center"),m>p&&h(e+f)<p&&(i.vertical="middle"),i.important=g(h(c),h(d))>g(h(e),h(f))?"horizontal":"vertical",b.using.call(this,a,i)}),k.offset(a.extend(A,{using:j}))})},a.ui.position={fit:{left:function(a,b){var c,d=b.within,e=d.isWindow?d.scrollLeft:d.offset.left,f=d.width,h=a.left-b.collisionPosition.marginLeft,i=e-h,j=h+b.collisionWidth-f-e;b.collisionWidth>f?i>0&&0>=j?(c=a.left+i+b.collisionWidth-f-e,a.left+=i-c):a.left=j>0&&0>=i?e:i>j?e+f-b.collisionWidth:e:i>0?a.left+=i:j>0?a.left-=j:a.left=g(a.left-h,a.left)},top:function(a,b){var c,d=b.within,e=d.isWindow?d.scrollTop:d.offset.top,f=b.within.height,h=a.top-b.collisionPosition.marginTop,i=e-h,j=h+b.collisionHeight-f-e;b.collisionHeight>f?i>0&&0>=j?(c=a.top+i+b.collisionHeight-f-e,a.top+=i-c):a.top=j>0&&0>=i?e:i>j?e+f-b.collisionHeight:e:i>0?a.top+=i:j>0?a.top-=j:a.top=g(a.top-h,a.top)}},flip:{left:function(a,b){var c,d,e=b.within,f=e.offset.left+e.scrollLeft,g=e.width,i=e.isWindow?e.scrollLeft:e.offset.left,j=a.left-b.collisionPosition.marginLeft,k=j-i,l=j+b.collisionWidth-g-i,m="left"===b.my[0]?-b.elemWidth:"right"===b.my[0]?b.elemWidth:0,n="left"===b.at[0]?b.targetWidth:"right"===b.at[0]?-b.targetWidth:0,o=-2*b.offset[0];0>k?(c=a.left+m+n+o+b.collisionWidth-g-f,(0>c||c<h(k))&&(a.left+=m+n+o)):l>0&&(d=a.left-b.collisionPosition.marginLeft+m+n+o-i,(d>0||h(d)<l)&&(a.left+=m+n+o))},top:function(a,b){var c,d,e=b.within,f=e.offset.top+e.scrollTop,g=e.height,i=e.isWindow?e.scrollTop:e.offset.top,j=a.top-b.collisionPosition.marginTop,k=j-i,l=j+b.collisionHeight-g-i,m="top"===b.my[1],n=m?-b.elemHeight:"bottom"===b.my[1]?b.elemHeight:0,o="top"===b.at[1]?b.targetHeight:"bottom"===b.at[1]?-b.targetHeight:0,p=-2*b.offset[1];0>k?(d=a.top+n+o+p+b.collisionHeight-g-f,a.top+n+o+p>k&&(0>d||d<h(k))&&(a.top+=n+o+p)):l>0&&(c=a.top-b.collisionPosition.marginTop+n+o+p-i,a.top+n+o+p>l&&(c>0||h(c)<l)&&(a.top+=n+o+p))}},flipfit:{left:function(){a.ui.position.flip.left.apply(this,arguments),a.ui.position.fit.left.apply(this,arguments)},top:function(){a.ui.position.flip.top.apply(this,arguments),a.ui.position.fit.top.apply(this,arguments)}}},function(){var b,c,d,e,f,g=document.getElementsByTagName("body")[0],h=document.createElement("div");b=document.createElement(g?"div":"body"),d={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},g&&a.extend(d,{position:"absolute",left:"-1000px",top:"-1000px"});for(f in d)b.style[f]=d[f];b.appendChild(h),c=g||document.documentElement,c.insertBefore(b,c.firstChild),h.style.cssText="position: absolute; left: 10.7432222px;",e=a(h).offset().left,a.support.offsetFractions=e>10&&11>e,b.innerHTML="",c.removeChild(b)}()}(window.webshims&&window.webshims.$||jQuery); | shallaa/cdnjs | ajax/libs/webshim/1.12.1/minified/shims/plugins/jquery.ui.position.js | JavaScript | mit | 6,400 |
YUI.add('series-stacked', function (Y, NAME) {
/**
* Provides functionality for creating stacked series.
*
* @module charts
* @submodule series-stacked
*/
var Y_Lang = Y.Lang;
/**
* Utility class used for creating stacked series.
*
* @module charts
* @class StackingUtil
* @constructor
* @submodule series-stacked
*/
function StackingUtil(){}
StackingUtil.prototype = {
/**
* Indicates whether the series is stacked.
*
* @property _stacked
* @private
*/
_stacked: true,
/**
* @protected
*
* Adjusts coordinate values for stacked series.
*
* @method _stackCoordinates
*/
_stackCoordinates: function()
{
if(this.get("direction") === "vertical")
{
this._stackXCoords();
}
else
{
this._stackYCoords();
}
},
/**
* Stacks coordinates for a stacked vertical series.
*
* @method _stackXCoords
* @protected
*/
_stackXCoords: function()
{
var order = this.get("order"),
seriesCollection = this.get("seriesTypeCollection"),
i = 0,
xcoords = this.get("xcoords"),
ycoords = this.get("ycoords"),
len,
coord,
prevCoord,
prevOrder,
stackedXCoords = xcoords.concat(),
prevXCoords,
prevYCoords,
nullIndices = [],
nullIndex;
if(order > 0)
{
prevXCoords = seriesCollection[order - 1].get("stackedXCoords");
prevYCoords = seriesCollection[order - 1].get("stackedYCoords");
len = prevXCoords.length;
}
else
{
len = xcoords.length;
}
for(; i < len; i = i + 1)
{
if(Y_Lang.isNumber(xcoords[i]))
{
if(order > 0)
{
prevCoord = prevXCoords[i];
if(!Y_Lang.isNumber(prevCoord))
{
prevOrder = order;
while(prevOrder > - 1 && !Y_Lang.isNumber(prevCoord))
{
prevOrder = prevOrder - 1;
if(prevOrder > -1)
{
prevCoord = seriesCollection[prevOrder].get("stackedXCoords")[i];
}
else
{
prevCoord = this._leftOrigin;
}
}
}
xcoords[i] = xcoords[i] + prevCoord;
}
stackedXCoords[i] = xcoords[i];
}
else
{
nullIndices.push(i);
}
}
this._cleanXNaN(stackedXCoords, ycoords);
len = nullIndices.length;
if(len > 0)
{
for(i = 0; i < len; i = i + 1)
{
nullIndex = nullIndices[i];
coord = order > 0 ? prevXCoords[nullIndex] : this._leftOrigin;
stackedXCoords[nullIndex] = Math.max(stackedXCoords[nullIndex], coord);
}
}
this.set("stackedXCoords", stackedXCoords);
this.set("stackedYCoords", ycoords);
},
/**
* Stacks coordinates for a stacked horizontal series.
*
* @method _stackYCoords
* @protected
*/
_stackYCoords: function()
{
var order = this.get("order"),
graphic = this.get("graphic"),
h = graphic.get("height"),
seriesCollection = this.get("seriesTypeCollection"),
i = 0,
xcoords = this.get("xcoords"),
ycoords = this.get("ycoords"),
len,
coord,
prevCoord,
prevOrder,
stackedYCoords = ycoords.concat(),
prevXCoords,
prevYCoords,
nullIndices = [],
nullIndex;
if(order > 0)
{
prevXCoords = seriesCollection[order - 1].get("stackedXCoords");
prevYCoords = seriesCollection[order - 1].get("stackedYCoords");
len = prevYCoords.length;
}
else
{
len = ycoords.length;
}
for(; i < len; i = i + 1)
{
if(Y_Lang.isNumber(ycoords[i]))
{
if(order > 0)
{
prevCoord = prevYCoords[i];
if(!Y_Lang.isNumber(prevCoord))
{
prevOrder = order;
while(prevOrder > - 1 && !Y_Lang.isNumber(prevCoord))
{
prevOrder = prevOrder - 1;
if(prevOrder > -1)
{
prevCoord = seriesCollection[prevOrder].get("stackedYCoords")[i];
}
else
{
prevCoord = this._bottomOrigin;
}
}
}
ycoords[i] = prevCoord - (h - ycoords[i]);
}
stackedYCoords[i] = ycoords[i];
}
else
{
nullIndices.push(i);
}
}
this._cleanYNaN(xcoords, stackedYCoords);
len = nullIndices.length;
if(len > 0)
{
for(i = 0; i < len; i = i + 1)
{
nullIndex = nullIndices[i];
coord = order > 0 ? prevYCoords[nullIndex] : h;
stackedYCoords[nullIndex] = Math.min(stackedYCoords[nullIndex], coord);
}
}
this.set("stackedXCoords", xcoords);
this.set("stackedYCoords", stackedYCoords);
},
/**
* Cleans invalid x-coordinates by calculating their value based on the corresponding y-coordinate, the
* previous valid x-coordinate with its corresponding y-coordinate and the next valid x-coordinate with
* its corresponding y-coordinate. If there is no previous or next valid x-coordinate, the value will not
* be altered.
*
* @method _cleanXNaN
* @param {Array} xcoords An array of x-coordinate values
* @param {Array} ycoords An arry of y-coordinate values
* @private
*/
_cleanXNaN: function(xcoords, ycoords)
{
var previousValidIndex,
nextValidIndex,
previousValidX,
previousValidY,
x,
y,
nextValidX,
nextValidY,
isNumber = Y_Lang.isNumber,
m,
i = 0,
len = ycoords.length;
for(; i < len; ++i)
{
x = xcoords[i];
y = ycoords[i];
//if x is invalid, calculate where it should be
if(!isNumber(x) && i > 0 && i < len - 1)
{
previousValidY = ycoords[i - 1];
//check to see if the previous value is valid
previousValidX = this._getPreviousValidCoordValue(xcoords, i);
nextValidY = ycoords[i + 1];
nextValidX = this._getNextValidCoordValue(xcoords, i);
//check to see if the next value is valid
if(isNumber(previousValidX) && isNumber(nextValidX))
{
//calculate slope and solve for x
m = (nextValidY - previousValidY) / (nextValidX - previousValidX);
xcoords[i] = (y + (m * previousValidX) - previousValidY)/m;
}
previousValidIndex = NaN;
nextValidIndex = NaN;
}
}
},
/**
* Returns the previous valid (numeric) value in an array if available.
*
* @method _getPreviousValidCoordValue
* @param {Array} coords Array of values
* @param {Number} index The index in the array in which to begin searching.
* @return Number
* @private
*/
_getPreviousValidCoordValue: function(coords, index)
{
var coord,
isNumber = Y_Lang.isNumber,
limit = -1;
while(!isNumber(coord) && index > limit)
{
index = index - 1;
coord = coords[index];
}
return coord;
},
/**
* Returns the next valid (numeric) value in an array if available.
*
* @method _getNextValidCoordValue
* @param {Array} coords Array of values
* @param {Number} index The index in the array in which to begin searching.
* @return Number
* @private
*/
_getNextValidCoordValue: function(coords, index)
{
var coord,
isNumber = Y_Lang.isNumber,
limit = coords.length;
while(!isNumber(coord) && index < limit)
{
index = index + 1;
coord = coords[index];
}
return coord;
},
/**
* Cleans invalid y-coordinates by calculating their value based on the corresponding x-coordinate, the
* previous valid y-coordinate with its corresponding x-coordinate and the next valid y-coordinate with
* its corresponding x-coordinate. If there is no previous or next valid y-coordinate, the value will not
* be altered.
*
* @method _cleanYNaN
* @param {Array} xcoords An array of x-coordinate values
* @param {Array} ycoords An arry of y-coordinate values
* @private
*/
_cleanYNaN: function(xcoords, ycoords)
{
var previousValidIndex,
nextValidIndex,
previousValidX,
previousValidY,
x,
y,
nextValidX,
nextValidY,
isNumber = Y_Lang.isNumber,
m,
i = 0,
len = xcoords.length;
for(; i < len; ++i)
{
x = xcoords[i];
y = ycoords[i];
//if y is invalid, calculate where it should be
if(!isNumber(y) && i > 0 && i < len - 1)
{
//check to see if the previous value is valid
previousValidX = xcoords[i - 1];
previousValidY = this._getPreviousValidCoordValue(ycoords, i);
//check to see if the next value is valid
nextValidX = xcoords[i + 1];
nextValidY = this._getNextValidCoordValue(ycoords, i);
if(isNumber(previousValidY) && isNumber(nextValidY))
{
//calculate slope and solve for y
m = (nextValidY - previousValidY) / (nextValidX - previousValidX);
ycoords[i] = previousValidY + ((m * x) - (m * previousValidX));
}
previousValidIndex = NaN;
nextValidIndex = NaN;
}
}
}
};
Y.StackingUtil = StackingUtil;
}, '@VERSION@', {"requires": ["axis-stacked"]});
| gionkunz/cdnjs | ajax/libs/yui/3.10.3/series-stacked/series-stacked.js | JavaScript | mit | 11,140 |
YUI.add('tree-selectable', function (Y, NAME) {
/*jshint expr:true, onevar:false */
/**
Extension for `Tree` that adds the concept of selection state for nodes.
@module tree
@submodule tree-selectable
@main tree-selectable
**/
var Do = Y.Do;
/**
Extension for `Tree` that adds the concept of selection state for nodes.
@class Tree.Selectable
@constructor
@extensionfor Tree
**/
/**
Fired when a node is selected.
@event select
@param {Tree.Node} node Node being selected.
@preventable _defSelectFn
**/
var EVT_SELECT = 'select';
/**
Fired when a node is unselected.
@event unselect
@param {Tree.Node} node Node being unselected.
@preventable _defUnselectFn
**/
var EVT_UNSELECT = 'unselect';
function Selectable() {}
Selectable.prototype = {
// -- Protected Properties -------------------------------------------------
/**
Mapping of node ids to node instances for nodes in this tree that are
currently selected.
@property {Object} _selectedMap
@protected
**/
// -- Lifecycle ------------------------------------------------------------
initializer: function () {
this.nodeExtensions = this.nodeExtensions.concat(Y.Tree.Node.Selectable);
this._selectedMap = {};
Do.after(this._selectableAfterDefAddFn, this, '_defAddFn');
Do.after(this._selectableAfterDefClearFn, this, '_defClearFn');
Do.after(this._selectableAfterDefRemoveFn, this, '_defRemoveFn');
this._selectableEvents = [
this.after('multiSelectChange', this._afterMultiSelectChange)
];
},
destructor: function () {
(new Y.EventHandle(this._selectableEvents)).detach();
this._selectableEvents = null;
this._selectedMap = null;
},
// -- Public Methods -------------------------------------------------------
/**
Returns an array of nodes that are currently selected.
@method getSelectedNodes
@return {Tree.Node.Selectable[]} Array of selected nodes.
**/
getSelectedNodes: function () {
return Y.Object.values(this._selectedMap);
},
/**
Selects the specified node.
@method selectNode
@param {Tree.Node.Selectable} node Node to select.
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `select` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
selectNode: function (node, options) {
// Instead of calling node.isSelected(), we look for the node in this
// tree's selectedMap, which ensures that the `select` event will fire
// in cases such as a node being added to this tree with its selected
// state already set to true.
if (!this._selectedMap[node.id]) {
this._fireTreeEvent(EVT_SELECT, {
node: node,
src : options && options.src
}, {
defaultFn: this._defSelectFn,
silent : options && options.silent
});
}
return this;
},
/**
Unselects all selected nodes.
@method unselect
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `unselect` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
unselect: function (options) {
for (var id in this._selectedMap) {
if (this._selectedMap.hasOwnProperty(id)) {
this.unselectNode(this._selectedMap[id], options);
}
}
return this;
},
/**
Unselects the specified node.
@method unselectNode
@param {Tree.Node.Selectable} node Node to unselect.
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `unselect` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
unselectNode: function (node, options) {
if (node.isSelected() || this._selectedMap[node.id]) {
this._fireTreeEvent(EVT_UNSELECT, {
node: node,
src : options && options.src
}, {
defaultFn: this._defUnselectFn,
silent : options && options.silent
});
}
return this;
},
// -- Protected Methods ----------------------------------------------------
_selectableAfterDefAddFn: function (e) {
// If the node is marked as selected, we need go through the select
// flow.
if (e.node.isSelected()) {
this.selectNode(e.node);
}
},
_selectableAfterDefClearFn: function () {
this._selectedMap = {};
},
_selectableAfterDefRemoveFn: function (e) {
delete e.node.state.selected;
delete this._selectedMap[e.node.id];
},
// -- Protected Event Handlers ---------------------------------------------
_afterMultiSelectChange: function () {
this.unselect();
},
_defSelectFn: function (e) {
if (!this.get('multiSelect')) {
this.unselect();
}
e.node.state.selected = true;
this._selectedMap[e.node.id] = e.node;
},
_defUnselectFn: function (e) {
delete e.node.state.selected;
delete this._selectedMap[e.node.id];
}
};
Selectable.ATTRS = {
/**
Whether or not to allow multiple nodes to be selected at once.
@attribute {Boolean} multiSelect
@default false
**/
multiSelect: {
value: false
}
};
Y.Tree.Selectable = Selectable;
/**
@module tree
@submodule tree-selectable
**/
/**
`Tree.Node` extension that adds methods useful for nodes in trees that use the
`Tree.Selectable` extension.
@class Tree.Node.Selectable
@constructor
@extensionfor Tree.Node
**/
function NodeSelectable() {}
NodeSelectable.prototype = {
/**
Returns `true` if this node is currently selected.
@method isSelected
@return {Boolean} `true` if this node is currently selected, `false`
otherwise.
**/
isSelected: function () {
return !!this.state.selected;
},
/**
Selects this node.
@method select
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `select` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
select: function (options) {
this.tree.selectNode(this, options);
return this;
},
/**
Unselects this node.
@method unselect
@param {Object} [options] Options.
@param {Boolean} [options.silent=false] If `true`, the `unselect` event
will be suppressed.
@param {String} [options.src] Source of the change, to be passed along
to the event facade of the resulting event. This can be used to
distinguish between changes triggered by a user and changes
triggered programmatically, for example.
@chainable
**/
unselect: function (options) {
this.tree.unselectNode(this, options);
return this;
}
};
Y.Tree.Node.Selectable = NodeSelectable;
}, '@VERSION@', {"requires": ["tree"]});
| ruslanas/cdnjs | ajax/libs/yui/3.10.0/tree-selectable/tree-selectable-debug.js | JavaScript | mit | 8,213 |
@charset "utf-8";
body {
margin:0;
}
#mocha {
font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: 60px 50px;
}
#mocha ul,
#mocha li {
margin: 0;
padding: 0;
}
#mocha ul {
list-style: none;
}
#mocha h1,
#mocha h2 {
margin: 0;
}
#mocha h1 {
margin-top: 15px;
font-size: 1em;
font-weight: 200;
}
#mocha h1 a {
text-decoration: none;
color: inherit;
}
#mocha h1 a:hover {
text-decoration: underline;
}
#mocha .suite .suite h1 {
margin-top: 0;
font-size: .8em;
}
#mocha .hidden {
display: none;
}
#mocha h2 {
font-size: 12px;
font-weight: normal;
cursor: pointer;
}
#mocha .suite {
margin-left: 15px;
}
#mocha .test {
margin-left: 15px;
overflow: hidden;
}
#mocha .test.pending:hover h2::after {
content: '(pending)';
font-family: arial, sans-serif;
}
#mocha .test.pass.medium .duration {
background: #c09853;
}
#mocha .test.pass.slow .duration {
background: #b94a48;
}
#mocha .test.pass::before {
content: '✓';
font-size: 12px;
display: block;
float: left;
margin-right: 5px;
color: #00d6b2;
}
#mocha .test.pass .duration {
font-size: 9px;
margin-left: 5px;
padding: 2px 5px;
color: #fff;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
}
#mocha .test.pass.fast .duration {
display: none;
}
#mocha .test.pending {
color: #0b97c4;
}
#mocha .test.pending::before {
content: '◦';
color: #0b97c4;
}
#mocha .test.fail {
color: #c00;
}
#mocha .test.fail pre {
color: black;
}
#mocha .test.fail::before {
content: '✖';
font-size: 12px;
display: block;
float: left;
margin-right: 5px;
color: #c00;
}
#mocha .test pre.error {
color: #c00;
max-height: 300px;
overflow: auto;
}
/**
* (1): approximate for browsers not supporting calc
* (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border)
* ^^ seriously
*/
#mocha .test pre {
display: block;
float: left;
clear: left;
font: 12px/1.5 monaco, monospace;
margin: 5px;
padding: 15px;
border: 1px solid #eee;
max-width: 85%; /*(1)*/
max-width: calc(100% - 42px); /*(2)*/
word-wrap: break-word;
border-bottom-color: #ddd;
-webkit-border-radius: 3px;
-webkit-box-shadow: 0 1px 3px #eee;
-moz-border-radius: 3px;
-moz-box-shadow: 0 1px 3px #eee;
border-radius: 3px;
}
#mocha .test h2 {
position: relative;
}
#mocha .test a.replay {
position: absolute;
top: 3px;
right: 0;
text-decoration: none;
vertical-align: middle;
display: block;
width: 15px;
height: 15px;
line-height: 15px;
text-align: center;
background: #eee;
font-size: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
-webkit-transition: opacity 200ms;
-moz-transition: opacity 200ms;
transition: opacity 200ms;
opacity: 0.3;
color: #888;
}
#mocha .test:hover a.replay {
opacity: 1;
}
#mocha-report.pass .test.fail {
display: none;
}
#mocha-report.fail .test.pass {
display: none;
}
#mocha-report.pending .test.pass,
#mocha-report.pending .test.fail {
display: none;
}
#mocha-report.pending .test.pass.pending {
display: block;
}
#mocha-error {
color: #c00;
font-size: 1.5em;
font-weight: 100;
letter-spacing: 1px;
}
#mocha-stats {
position: fixed;
top: 15px;
right: 10px;
font-size: 12px;
margin: 0;
color: #888;
z-index: 1;
}
#mocha-stats .progress {
float: right;
padding-top: 0;
}
#mocha-stats em {
color: black;
}
#mocha-stats a {
text-decoration: none;
color: inherit;
}
#mocha-stats a:hover {
border-bottom: 1px solid #eee;
}
#mocha-stats li {
display: inline-block;
margin: 0 5px;
list-style: none;
padding-top: 11px;
}
#mocha-stats canvas {
width: 40px;
height: 40px;
}
#mocha code .comment { color: #ddd; }
#mocha code .init { color: #2f6fad; }
#mocha code .string { color: #5890ad; }
#mocha code .keyword { color: #8a6343; }
#mocha code .number { color: #2f6fad; }
@media screen and (max-device-width: 480px) {
#mocha {
margin: 60px 0px;
}
#mocha #stats {
position: absolute;
}
}
| carlsednaoui/cdnjs | ajax/libs/mocha/1.16.0/mocha.css | CSS | mit | 4,242 |
//------------------------------------------------------------------------------
// <copyright file="XmlEnumAttribute.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization {
using System;
/// <include file='doc\XmlEnumAttribute.uex' path='docs/doc[@for="XmlEnumAttribute"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[AttributeUsage(AttributeTargets.Field)]
public class XmlEnumAttribute : System.Attribute {
string name;
/// <include file='doc\XmlEnumAttribute.uex' path='docs/doc[@for="XmlEnumAttribute.XmlEnumAttribute"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlEnumAttribute() {
}
/// <include file='doc\XmlEnumAttribute.uex' path='docs/doc[@for="XmlEnumAttribute.XmlEnumAttribute1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlEnumAttribute(string name) {
this.name = name;
}
/// <include file='doc\XmlEnumAttribute.uex' path='docs/doc[@for="XmlEnumAttribute.Name"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string Name {
get { return name; }
set { name = value; }
}
}
}
| wparad/referencesource | System.Xml/System/Xml/Serialization/XmlEnumAttribute.cs | C# | mit | 1,636 |
# encoding: utf-8
require 'spec_helper'
describe Github, 'options' do
let(:default_adapter) { :net_http }
let(:adapter) { :patron }
let(:token) { '123' }
let(:options) { { :adapter => adapter } }
context 'when different instances of the same class' do
it 'instantiates the same api classes with different options' do
repos = Github::Client::Repos.new
repos2 = Github::Client::Repos.new options
expect(repos.object_id).to_not eql(repos2.object_id)
expect(repos.adapter).to eql default_adapter
expect(repos2.adapter).to eql adapter
repos.adapter = adapter
repos2.adapter = default_adapter
expect(repos.adapter).to eql adapter
expect(repos2.adapter).to eql default_adapter
end
it 'instantiates the same clients with different options' do
client = Github.new :oauth_token => 'client'
client2 = Github.new :oauth_token => 'client2'
expect(client.object_id).to_not eql(client2.object_id)
expect(client.oauth_token).to eql 'client'
expect(client2.oauth_token).to eql 'client2'
end
end
context 'when different instances of the same chain' do
it "inherits properties from client and doesn't pass them up the tree" do
client = Github.new options
repos = client.repos
expect(client.adapter).to eql(adapter)
expect(repos.adapter).to eql(adapter)
repos.adapter = default_adapter
expect(client.adapter).to eql(adapter)
expect(repos.adapter).to eql(default_adapter)
client.oauth_token = token
expect(client.oauth_token).to eql(token)
expect(repos.oauth_token).to be_nil
end
it "inherits properties from api and doesn't pass them up the tree" do
repos = Github::Client::Repos.new options
comments = repos.comments
expect(repos.adapter).to eql(adapter)
expect(comments.adapter).to eql(adapter)
comments.adapter = default_adapter
expect(repos.adapter).to eql(adapter)
expect(comments.adapter).to eql(default_adapter)
repos.oauth_token = token
expect(repos.oauth_token).to eql(token)
expect(comments.oauth_token).to be_nil
end
end
context 'when setting attributes through accessors' do
let(:default_endpoint) { 'https://api.github.com'}
let(:endpoint) { 'https://my-company/api/v3' }
let(:login) { 'Piotr' }
it 'sets login on correct instance' do
client = Github.new :login => login
expect(Github.login).to be_nil
expect(client.login).to eql login
end
it 'sets attribute' do
client = Github.new options
client.endpoint = endpoint
expect(Github.endpoint).to eql default_endpoint
expect(client.endpoint).to eql endpoint
end
it 'sets attribute through dsl' do
client = Github.new do |config|
config.endpoint = endpoint
end
expect(client.endpoint).to eql endpoint
repos = client.repos do |config|
config.adapter = adapter
end
expect(repos.endpoint).to eql endpoint
expect(repos.adapter).to eql adapter
end
it 'updates current_options through api setters' do
client = Github.new :endpoint => endpoint
expect(client.repos.current_options[:endpoint]).to eql endpoint
expect(client.repos.endpoint).to eql endpoint
repos = client.repos
repos.endpoint = default_endpoint
expect(repos.endpoint).to eql default_endpoint
expect(repos.current_options[:endpoint]).to eql default_endpoint
end
end
end # options
| ahmetabdi/github | spec/integration/options_spec.rb | Ruby | mit | 3,551 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using FileHelpers.Events;
using Microsoft.Office.Interop.Excel;
namespace FileHelpers.DataLink
{
/// <summary><para>This class implements <see cref="DataStorage"/> for Microsoft Excel Files.</para>
/// <para><b>WARNING you need to have installed Microsoft Excel 2000 or newer to use this feature.</b></para>
/// <para><b>To use this class you need to reference the FileHelpers.ExcelStorage.dll file.</b></para>
/// </summary>
/// <remarks><b>This class is contained in the FileHelpers.ExcelStorage.dll and need the Interop.Office.dll and Interop.Excel.dll to work correctly.</b></remarks>
public sealed class ExcelStorage : ExcelStorageBase
{
#region " Constructors "
/// <summary>Create a new ExcelStorage to work with the specified type</summary>
/// <param name="recordType">The type of records.</param>
public ExcelStorage(Type recordType):base(recordType)
{
// Temporary
// if (RecordHasDateFields())
// throw new NotImplementedException("For now the ExcelStorage don�t work with DateTime fields, sorry for the problems.");
}
/// <summary>Create a new ExcelStorage to work with the specified type</summary>
/// <param name="recordType">The type of records.</param>
/// <param name="startRow">The row of the first data cell. Begining in 1.</param>
/// <param name="startCol">The column of the first data cell. Begining in 1.</param>
public ExcelStorage(Type recordType, int startRow, int startCol) : base(recordType, startRow, startCol)
{
}
/// <summary>Create a new ExcelStorage to work with the specified type</summary>
/// <param name="recordType">The type of records.</param>
/// <param name="startRow">The row of the first data cell. Begining in 1.</param>
/// <param name="startCol">The column of the first data cell. Begining in 1.</param>
/// <param name="fileName">The file path to work with.</param>
public ExcelStorage(Type recordType, string fileName, int startRow, int startCol)
: base(recordType, fileName, startRow, startCol)
{
}
#endregion
#region " Private Fields "
private ApplicationClass mApp;
private Workbook mBook;
private Worksheet mSheet;
private List<string> mSheets;
//private RecordInfo mRecordInfo;
#endregion
#region " Public Properties "
/// <summary>Returns the names of the worksheets.</summary>
public List<string> Sheets
{
get
{
if(mSheets == null)
{
try
{
ReadAndStoreSheetNames();
}
finally
{
CloseAndCleanUp();
}
}
return mSheets;
}
}
#endregion
#region " InitExcel "
private void InitExcel()
{
try
{
this.mApp = new ApplicationClass();
}
catch (System.Runtime.InteropServices.COMException ex)
{
if (ex.Message.IndexOf("00024500-0000-0000-C000-000000000046") >= 0)
throw new ExcelBadUsageException("Excel 2000 or newer is not installed in this system.");
else
throw;
}
this.mBook = null;
this.mSheet = null;
this.mApp.Visible = false;
this.mApp.AlertBeforeOverwriting = false;
this.mApp.ScreenUpdating = false;
this.mApp.DisplayAlerts = false;
this.mApp.EnableAnimations = false;
this.mApp.Interactive = false;
}
#endregion
#region " CloseAndCleanUp "
private void CloseAndCleanUp()
{
if (this.mSheet != null)
{
DisposeCOMObject(mSheet);
mSheet = null;
}
if (this.mBook != null)
{
this.mBook.Close(false, mv, mv);
DisposeCOMObject(mBook);
this.mBook = null;
}
//Thread.Sleep(100);
if (this.mApp != null)
{
//this.mApp.Interactive = true;
this.mApp.Quit();
DisposeCOMObject(mApp);
this.mApp = null;
}
}
private void DisposeCOMObject(object comObject)
{
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(comObject) > 1)
{}
}
#endregion
private readonly Missing mv = Missing.Value;
#region " OpenWorkbook "
private void OpenWorkbook(string filename)
{
FileInfo info = new FileInfo(filename);
if (info.Exists == false)
throw new FileNotFoundException("Excel File '" + filename + "' not found.", filename);
this.mBook = this.mApp.Workbooks.Open(info.FullName, (int) UpdateLinks,
mv, mv, mv, mv, mv, mv, mv, mv, mv, mv, mv);
if (SheetName == null || SheetName == string.Empty)
this.mSheet = (Worksheet) this.mBook.ActiveSheet;
else
{
try
{
this.mSheet = (Worksheet) this.mBook.Sheets[SheetName];
}
catch
{
throw new ExcelBadUsageException("The sheet '" + SheetName + "' was not found in the workbook.");
}
}
}
#endregion
#region " CreateWorkbook methods "
private void OpenOrCreateWorkbook(string filename)
{
if (File.Exists(filename))
OpenWorkbook(filename);
else
CreateWorkbook();
}
private void CreateWorkbook()
{
this.mBook = this.mApp.Workbooks.Add(mv);
this.mSheet = (Worksheet) this.mBook.ActiveSheet;
}
#endregion
#region " SaveWorkbook "
private void SaveWorkbook(string filename)
{
if (this.mBook == null)
return;
if (File.Exists(filename))
{
this.mBook.Save();
}
else
{
this.mBook.SaveAs(filename, mv, mv, mv, mv, mv, XlSaveAsAccessMode.xlNoChange, mv, mv, mv, mv);
}
}
#endregion
#region " CellAsString "
/// <summary>
/// Determine if a given cell is empty.
/// </summary>
/// <param name="row">Row index (1-based)</param>
/// <param name="col">Column index (1-based)</param>
protected override string CellAsString(object row, object col)
{
if (this.mSheet == null)
{
return null;
}
Range r;
r = (Range) this.mSheet.Cells[row, col];
object res = r.Value;
DisposeCOMObject(r);
return Convert.ToString(res);
}
#endregion
#region " ColLeter "
string _ColLetter(int col /* 0 origin */)
{
// col = [0...25]
if (col >= 0 && col <= 25)
return ((char)('A' + col)).ToString();
return "";
}
string ColLetter(int col /* 1 Origin */)
{
if (col < 1 || col > 256)
throw new ExcelBadUsageException("Column out of range; must be between 1 and 256"); // Excel limits
col--; // make 0 origin
// good up to col ZZ
int col2 = (col / 26)-1;
int col1 = (col % 26);
return _ColLetter(col2) + _ColLetter(col1);
}
#endregion
#region " RowValues "
private object[] RowValues(int row, int startCol, int numberOfCols)
{
if (this.mSheet == null)
{
return null;
}
object[] res;
Range r;
if (numberOfCols == 1)
{
r = mSheet.get_Range(ColLetter(startCol) + row.ToString(), ColLetter(startCol + numberOfCols - 1) + row.ToString());
res = new object[] {r.Value};
//DisposeCOMObject(r);
}
else
{
r = mSheet.get_Range(ColLetter(startCol) + row.ToString(), ColLetter(startCol + numberOfCols - 1) + row.ToString());
//object[,] resTemp = (object[,]) r.Value2;
//TODO Eandis team check if correct
object[,] resTemp = (object[,])r.Value;
//DisposeCOMObject(r);
res = new object[numberOfCols];
for (int i = 1; i <= numberOfCols; i++)
{
res[i - 1] = resTemp[1, i];
}
}
return res;
}
private void WriteRowValues(object[] values, int row, int startCol)
{
if (this.mSheet == null)
return;
Range r = this.mSheet.get_Range(ColLetter(startCol) + row.ToString(), ColLetter(startCol + values.Length - 1) + row.ToString());
r.Value = values;
}
#endregion
#region " InsertRecords "
/// <summary>Insert all the records in the specified Excel File.</summary>
/// <param name="records">The records to insert.</param>
public override void InsertRecords(object[] records)
{
if (records == null || records.Length == 0)
return;
System.Globalization.CultureInfo oldCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
try
{
int recordNumber = 0;
OnProgress(new ProgressEventArgs(0, records.Length));
this.InitExcel();
if (OverrideFile && File.Exists(FileName))
File.Delete(FileName);
if (TemplateFile != string.Empty)
{
if (File.Exists(TemplateFile) == false)
throw new ExcelBadUsageException("Template file not found: '" + TemplateFile + "'");
if (TemplateFile != FileName)
File.Copy(TemplateFile, FileName, true);
}
this.OpenOrCreateWorkbook(FileName);
for (int i = 0; i < records.Length; i++)
{
recordNumber++;
OnProgress(new ProgressEventArgs(recordNumber, records.Length));
WriteRowValues(RecordToValues(records[i]), StartRow + i, StartColumn);
}
SaveWorkbook(FileName);
}
catch
{
throw;
}
finally
{
CloseAndCleanUp();
Thread.CurrentThread.CurrentCulture = oldCulture;
}
}
#endregion
#region " ExtractRecords "
/// <summary>Returns the records extracted from Excel file.</summary>
/// <returns>The extracted records.</returns>
public override object[] ExtractRecords()
{
if (FileName == String.Empty)
throw new ExcelBadUsageException("You need to specify the WorkBookFile of the ExcelDataLink.");
ArrayList res = new ArrayList();
System.Globalization.CultureInfo oldCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
try
{
int cRow = StartRow;
int recordNumber = 0;
OnProgress(new ProgressEventArgs(0, -1));
object[] colValues = new object[RecordFieldCount];
this.InitExcel();
this.OpenWorkbook(this.FileName);
while (ShouldStopOnRow(cRow) == false)
{
try
{
if (ShouldReadRowData(cRow))
{
recordNumber++;
OnProgress(new ProgressEventArgs(recordNumber, -1));
colValues = RowValues(cRow, StartColumn, RecordFieldCount);
object record = ValuesToRecord(colValues);
res.Add(record);
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
AddError(cRow, ex, ColumnsToValues(colValues));
break;
}
}
finally
{
cRow++;
}
}
}
catch
{
throw;
}
finally
{
CloseAndCleanUp();
Thread.CurrentThread.CurrentCulture = oldCulture;
}
return (object[]) res.ToArray(this.RecordType);
}
#endregion
private void ReadAndStoreSheetNames()
{
mSheets = new List<string>();
InitExcel();
OpenWorkbook(FileName);
foreach (Worksheet sheet in this.mBook.Worksheets)
mSheets.Add(sheet.Name);
}
private string ColumnsToValues(object[] values)
{
if (values == null || values.Length == 0)
return string.Empty;
string res = string.Empty;
if (values[0] != null)
res = values[0].ToString();
for(int i = 1; i < values.Length; i++)
{
if (values[i] == null)
res += ",";
else
res += "," + values[i].ToString();
}
return res;
}
}
} | senthilmsv/FileHelpers | FileHelpers.ExcelStorage/ExcelStorage.cs | C# | mit | 13,225 |
Clazz.declarePackage ("J.shape");
Clazz.load (["J.shape.AtomShape"], "J.shape.Balls", ["JU.BS", "J.c.PAL", "JU.C"], function () {
c$ = Clazz.declareType (J.shape, "Balls", J.shape.AtomShape);
Clazz.overrideMethod (c$, "setSize",
function (size, bsSelected) {
if (size == 2147483647) {
this.isActive = true;
if (this.bsSizeSet == null) this.bsSizeSet = new JU.BS ();
this.bsSizeSet.or (bsSelected);
return;
}this.setSize2 (size, bsSelected);
}, "~N,JU.BS");
Clazz.overrideMethod (c$, "setSizeRD",
function (rd, bsSelected) {
this.isActive = true;
if (this.bsSizeSet == null) this.bsSizeSet = new JU.BS ();
var bsLength = Math.min (this.atoms.length, bsSelected.length ());
for (var i = bsSelected.nextSetBit (0); i >= 0 && i < bsLength; i = bsSelected.nextSetBit (i + 1)) {
var atom = this.atoms[i];
atom.setMadAtom (this.vwr, rd);
this.bsSizeSet.set (i);
}
}, "J.atomdata.RadiusData,JU.BS");
Clazz.overrideMethod (c$, "setProperty",
function (propertyName, value, bs) {
if ("color" === propertyName) {
var colix = JU.C.getColixO (value);
if (colix == 0) colix = 2;
if (this.bsColixSet == null) this.bsColixSet = new JU.BS ();
var pid = J.c.PAL.pidOf (value);
for (var i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1)) {
var atom = this.atoms[i];
atom.colixAtom = this.getColixA (colix, pid, atom);
this.bsColixSet.setBitTo (i, colix != 2 || pid != J.c.PAL.NONE.id);
atom.paletteID = pid;
}
return;
}if ("colorValues" === propertyName) {
var values = value;
if (values.length == 0) return;
if (this.bsColixSet == null) this.bsColixSet = new JU.BS ();
var n = 0;
var color = null;
for (var i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1)) {
if (n >= values.length) return;
color = Integer.$valueOf (values[n++]);
var colix = JU.C.getColixO (color);
if (colix == 0) colix = 2;
var pid = J.c.PAL.pidOf (color);
var atom = this.atoms[i];
atom.colixAtom = this.getColixA (colix, pid, atom);
this.bsColixSet.setBitTo (i, colix != 2 || pid != J.c.PAL.NONE.id);
atom.paletteID = pid;
}
return;
}if ("colors" === propertyName) {
var data = value;
var colixes = data[0];
if (this.bsColixSet == null) this.bsColixSet = new JU.BS ();
var c;
for (var i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1)) {
if (i >= colixes.length || (c = colixes[i]) == 0) continue;
this.atoms[i].colixAtom = c;
this.atoms[i].paletteID = J.c.PAL.UNKNOWN.id;
this.bsColixSet.set (i);
}
return;
}if ("translucency" === propertyName) {
var isTranslucent = ((value).equals ("translucent"));
if (this.bsColixSet == null) this.bsColixSet = new JU.BS ();
for (var i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1)) {
this.atoms[i].setTranslucent (isTranslucent, this.translucentLevel);
if (isTranslucent) this.bsColixSet.set (i);
}
return;
}if (propertyName.startsWith ("ball")) {
propertyName = propertyName.substring (4).intern ();
}this.setPropAS (propertyName, value, bs);
}, "~S,~O,JU.BS");
Clazz.overrideMethod (c$, "setAtomClickability",
function () {
var bsDeleted = this.vwr.slm.bsDeleted;
for (var i = this.ac; --i >= 0; ) {
var atom = this.atoms[i];
atom.setClickable (0);
if (bsDeleted != null && bsDeleted.get (i) || (atom.shapeVisibilityFlags & this.vf) == 0 || this.ms.isAtomHidden (i)) continue;
atom.setClickable (this.vf);
}
});
});
| sxhexe/reaction-route-search | reactionroute_web/reaction/static/j2s/J/shape/Balls.js | JavaScript | mit | 3,342 |
require 'tc_helper.rb'
class TestRelationships < Test::Unit::TestCase
def test_for
source_obj_1, source_obj_2 = Object.new, Object.new
rel_1 = Axlsx::Relationship.new(source_obj_1, Axlsx::WORKSHEET_R, "bar")
rel_2 = Axlsx::Relationship.new(source_obj_2, Axlsx::WORKSHEET_R, "bar")
rels = Axlsx::Relationships.new
rels << rel_1
rels << rel_2
assert_equal rel_1, rels.for(source_obj_1)
assert_equal rel_2, rels.for(source_obj_2)
end
def test_valid_document
@rels = Axlsx::Relationships.new
schema = Nokogiri::XML::Schema(File.open(Axlsx::RELS_XSD))
doc = Nokogiri::XML(@rels.to_xml_string)
errors = []
schema.validate(doc).each do |error|
puts error.message
errors << error
end
@rels << Axlsx::Relationship.new(nil, Axlsx::WORKSHEET_R, "bar")
doc = Nokogiri::XML(@rels.to_xml_string)
errors = []
schema.validate(doc).each do |error|
puts error.message
errors << error
end
assert(errors.size == 0)
end
end
| Debiancc/axlsx | test/rels/tc_relationships.rb | Ruby | mit | 1,024 |
module ChefSpec::API
# @since 3.0.0
module EasyInstallPackageMatchers
ChefSpec.define_matcher :easy_install_package
#
# Assert that an +easy_install_package+ resource exists in the Chef run
# with the action +:install+. Given a Chef Recipe that installs "pygments" as a
# +easy_install_package+:
#
# easy_install_package 'pygments' do
# action :install
# end
#
# The Examples section demonstrates the different ways to test a
# +easy_install_package+ resource with ChefSpec.
#
# @example Assert that an +easy_install_package+ was installed
# expect(chef_run).to install_easy_install_package('pygments')
#
# @example Assert that an +easy_install_package+ was installed with predicate matchers
# expect(chef_run).to install_easy_install_package('pygments').with_version('1.2.3')
#
# @example Assert that an +easy_install_package+ was installed with attributes
# expect(chef_run).to install_easy_install_package('pygments').with(version: '1.2.3')
#
# @example Assert that an +easy_install_package+ was installed using a regex
# expect(chef_run).to install_easy_install_package('pygments').with(version: /(\d+\.){2}\.\d+/)
#
# @example Assert that an +easy_install_package+ was _not_ installed
# expect(chef_run).to_not install_easy_install_package('pygments')
#
#
# @param [String, Regex] resource_name
# the name of the resource to match
#
# @return [ChefSpec::Matchers::ResourceMatcher]
#
def install_easy_install_package(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:easy_install_package, :install, resource_name)
end
#
# Assert that an +easy_install_package+ resource exists in the Chef run
# with the action +:purge+. Given a Chef Recipe that purges "pygments" as a
# +easy_install_package+:
#
# easy_install_package 'pygments' do
# action :purge
# end
#
# The Examples section demonstrates the different ways to test a
# +easy_install_package+ resource with ChefSpec.
#
# @example Assert that an +easy_install_package+ was purged
# expect(chef_run).to purge_easy_install_package('pygments')
#
# @example Assert that an +easy_install_package+ was purged with predicate matchers
# expect(chef_run).to purge_easy_install_package('pygments').with_version('1.2.3')
#
# @example Assert that an +easy_install_package+ was purged with attributes
# expect(chef_run).to purge_easy_install_package('pygments').with(version: '1.2.3')
#
# @example Assert that an +easy_install_package+ was purged using a regex
# expect(chef_run).to purge_easy_install_package('pygments').with(version: /(\d+\.){2}\.\d+/)
#
# @example Assert that an +easy_install_package+ was _not_ purged
# expect(chef_run).to_not purge_easy_install_package('pygments')
#
#
# @param [String, Regex] resource_name
# the name of the resource to match
#
# @return [ChefSpec::Matchers::ResourceMatcher]
#
def purge_easy_install_package(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:easy_install_package, :purge, resource_name)
end
#
# Assert that an +easy_install_package+ resource exists in the Chef run
# with the action +:remove+. Given a Chef Recipe that removes "pygments" as a
# +easy_install_package+:
#
# easy_install_package 'pygments' do
# action :remove
# end
#
# The Examples section demonstrates the different ways to test a
# +easy_install_package+ resource with ChefSpec.
#
# @example Assert that an +easy_install_package+ was removed
# expect(chef_run).to remove_easy_install_package('pygments')
#
# @example Assert that an +easy_install_package+ was removed with predicate matchers
# expect(chef_run).to remove_easy_install_package('pygments').with_version('1.2.3')
#
# @example Assert that an +easy_install_package+ was removed with attributes
# expect(chef_run).to remove_easy_install_package('pygments').with(version: '1.2.3')
#
# @example Assert that an +easy_install_package+ was removed using a regex
# expect(chef_run).to remove_easy_install_package('pygments').with(version: /(\d+\.){2}\.\d+/)
#
# @example Assert that an +easy_install_package+ was _not_ removed
# expect(chef_run).to_not remove_easy_install_package('pygments')
#
#
# @param [String, Regex] resource_name
# the name of the resource to match
#
# @return [ChefSpec::Matchers::ResourceMatcher]
#
def remove_easy_install_package(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:easy_install_package, :remove, resource_name)
end
#
# Assert that an +easy_install_package+ resource exists in the Chef run
# with the action +:upgrade+. Given a Chef Recipe that upgrades "pygments" as a
# +easy_install_package+:
#
# easy_install_package 'pygments' do
# action :upgrade
# end
#
# The Examples section demonstrates the different ways to test a
# +easy_install_package+ resource with ChefSpec.
#
# @example Assert that an +easy_install_package+ was upgraded
# expect(chef_run).to upgrade_easy_install_package('pygments')
#
# @example Assert that an +easy_install_package+ was upgraded with predicate matchers
# expect(chef_run).to upgrade_easy_install_package('pygments').with_version('1.2.3')
#
# @example Assert that an +easy_install_package+ was upgraded with attributes
# expect(chef_run).to upgrade_easy_install_package('pygments').with(version: '1.2.3')
#
# @example Assert that an +easy_install_package+ was upgraded using a regex
# expect(chef_run).to upgrade_easy_install_package('pygments').with(version: /(\d+\.){2}\.\d+/)
#
# @example Assert that an +easy_install_package+ was _not_ upgraded
# expect(chef_run).to_not upgrade_easy_install_package('pygments')
#
#
# @param [String, Regex] resource_name
# the name of the resource to match
#
# @return [ChefSpec::Matchers::ResourceMatcher]
#
def upgrade_easy_install_package(resource_name)
ChefSpec::Matchers::ResourceMatcher.new(:easy_install_package, :upgrade, resource_name)
end
end
end
| oldirty/chefspec | lib/chefspec/api/easy_install_package.rb | Ruby | mit | 6,414 |
using ContosoCookbook.Common;
using ContosoCookbook.DataModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace ContosoCookbook
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
/// <summary>
/// NavigationHelper is used on each page to aid in navigation and
/// process lifetime management
/// </summary>
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
/// <summary>
/// This can be changed to a strongly typed view model.
/// </summary>
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
public MainPage()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
var recipeDataGroups = await RecipeDataSource.GetGroupsAsync((String)e.NavigationParameter);
this.DefaultViewModel["AllGroups"] = recipeDataGroups;
groupListView.SelectedItem = null;
}
#region NavigationHelper registration
/// The methods provided in this section are simply used to allow
/// NavigationHelper to respond to the page's navigation methods.
///
/// Page specific logic should be placed in event handlers for the
/// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
/// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
/// The navigation parameter is available in the LoadState method
/// in addition to page state preserved during an earlier session.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
#endregion
private void About_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(AboutPage));
}
private void lstGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.Frame.Navigate(typeof(GroupDetailPage), (groupListView.SelectedItem as RecipeDataGroup).UniqueId);
}
}
}
| Windows-Readiness/WinDevCamp | Presentation/17. Porting 8.1 Apps to Win 10/Demos/MigrationDemo/Begin/ContosoCookbook/ContosoCookbook/MainPage.xaml.cs | C# | mit | 3,870 |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../SDL_internal.h"
#include "SDL_syshaptic.h"
#include "SDL_haptic_c.h"
#include "../joystick/SDL_joystick_c.h" /* For SDL_PrivateJoystickValid */
#include "SDL_assert.h"
/* Global for SDL_windowshaptic.c */
#if (defined(SDL_HAPTIC_DINPUT) && SDL_HAPTIC_DINPUT) || (defined(SDL_HAPTIC_XINPUT) && SDL_HAPTIC_XINPUT)
SDL_Haptic *SDL_haptics = NULL;
#else
static SDL_Haptic *SDL_haptics = NULL;
#endif
/*
* Initializes the Haptic devices.
*/
int
SDL_HapticInit(void)
{
int status;
status = SDL_SYS_HapticInit();
if (status >= 0) {
status = 0;
}
return status;
}
/*
* Checks to see if the haptic device is valid
*/
static int
ValidHaptic(SDL_Haptic * haptic)
{
int valid;
SDL_Haptic *hapticlist;
valid = 0;
if (haptic != NULL) {
hapticlist = SDL_haptics;
while ( hapticlist )
{
if (hapticlist == haptic) {
valid = 1;
break;
}
hapticlist = hapticlist->next;
}
}
/* Create the error here. */
if (valid == 0) {
SDL_SetError("Haptic: Invalid haptic device identifier");
}
return valid;
}
/*
* Returns the number of available devices.
*/
int
SDL_NumHaptics(void)
{
return SDL_SYS_NumHaptics();
}
/*
* Gets the name of a Haptic device by index.
*/
const char *
SDL_HapticName(int device_index)
{
if ((device_index < 0) || (device_index >= SDL_NumHaptics())) {
SDL_SetError("Haptic: There are %d haptic devices available",
SDL_NumHaptics());
return NULL;
}
return SDL_SYS_HapticName(device_index);
}
/*
* Opens a Haptic device.
*/
SDL_Haptic *
SDL_HapticOpen(int device_index)
{
SDL_Haptic *haptic;
SDL_Haptic *hapticlist;
if ((device_index < 0) || (device_index >= SDL_NumHaptics())) {
SDL_SetError("Haptic: There are %d haptic devices available",
SDL_NumHaptics());
return NULL;
}
hapticlist = SDL_haptics;
/* If the haptic is already open, return it
* TODO: Should we create haptic instance IDs like the Joystick API?
*/
while ( hapticlist )
{
if (device_index == hapticlist->index) {
haptic = hapticlist;
++haptic->ref_count;
return haptic;
}
hapticlist = hapticlist->next;
}
/* Create the haptic device */
haptic = (SDL_Haptic *) SDL_malloc((sizeof *haptic));
if (haptic == NULL) {
SDL_OutOfMemory();
return NULL;
}
/* Initialize the haptic device */
SDL_memset(haptic, 0, (sizeof *haptic));
haptic->rumble_id = -1;
haptic->index = device_index;
if (SDL_SYS_HapticOpen(haptic) < 0) {
SDL_free(haptic);
return NULL;
}
/* Add haptic to list */
++haptic->ref_count;
/* Link the haptic in the list */
haptic->next = SDL_haptics;
SDL_haptics = haptic;
/* Disable autocenter and set gain to max. */
if (haptic->supported & SDL_HAPTIC_GAIN)
SDL_HapticSetGain(haptic, 100);
if (haptic->supported & SDL_HAPTIC_AUTOCENTER)
SDL_HapticSetAutocenter(haptic, 0);
return haptic;
}
/*
* Returns 1 if the device has been opened.
*/
int
SDL_HapticOpened(int device_index)
{
int opened;
SDL_Haptic *hapticlist;
/* Make sure it's valid. */
if ((device_index < 0) || (device_index >= SDL_NumHaptics())) {
SDL_SetError("Haptic: There are %d haptic devices available",
SDL_NumHaptics());
return 0;
}
opened = 0;
hapticlist = SDL_haptics;
/* TODO Should this use an instance ID? */
while ( hapticlist )
{
if (hapticlist->index == (Uint8) device_index) {
opened = 1;
break;
}
hapticlist = hapticlist->next;
}
return opened;
}
/*
* Returns the index to a haptic device.
*/
int
SDL_HapticIndex(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return -1;
}
return haptic->index;
}
/*
* Returns SDL_TRUE if mouse is haptic, SDL_FALSE if it isn't.
*/
int
SDL_MouseIsHaptic(void)
{
if (SDL_SYS_HapticMouse() < 0)
return SDL_FALSE;
return SDL_TRUE;
}
/*
* Returns the haptic device if mouse is haptic or NULL elsewise.
*/
SDL_Haptic *
SDL_HapticOpenFromMouse(void)
{
int device_index;
device_index = SDL_SYS_HapticMouse();
if (device_index < 0) {
SDL_SetError("Haptic: Mouse isn't a haptic device.");
return NULL;
}
return SDL_HapticOpen(device_index);
}
/*
* Returns SDL_TRUE if joystick has haptic features.
*/
int
SDL_JoystickIsHaptic(SDL_Joystick * joystick)
{
int ret;
/* Must be a valid joystick */
if (!SDL_PrivateJoystickValid(joystick)) {
return -1;
}
ret = SDL_SYS_JoystickIsHaptic(joystick);
if (ret > 0)
return SDL_TRUE;
else if (ret == 0)
return SDL_FALSE;
else
return -1;
}
/*
* Opens a haptic device from a joystick.
*/
SDL_Haptic *
SDL_HapticOpenFromJoystick(SDL_Joystick * joystick)
{
SDL_Haptic *haptic;
SDL_Haptic *hapticlist;
/* Make sure there is room. */
if (SDL_NumHaptics() <= 0) {
SDL_SetError("Haptic: There are %d haptic devices available",
SDL_NumHaptics());
return NULL;
}
/* Must be a valid joystick */
if (!SDL_PrivateJoystickValid(joystick)) {
SDL_SetError("Haptic: Joystick isn't valid.");
return NULL;
}
/* Joystick must be haptic */
if (SDL_SYS_JoystickIsHaptic(joystick) <= 0) {
SDL_SetError("Haptic: Joystick isn't a haptic device.");
return NULL;
}
hapticlist = SDL_haptics;
/* Check to see if joystick's haptic is already open */
while ( hapticlist )
{
if (SDL_SYS_JoystickSameHaptic(hapticlist, joystick)) {
haptic = hapticlist;
++haptic->ref_count;
return haptic;
}
hapticlist = hapticlist->next;
}
/* Create the haptic device */
haptic = (SDL_Haptic *) SDL_malloc((sizeof *haptic));
if (haptic == NULL) {
SDL_OutOfMemory();
return NULL;
}
/* Initialize the haptic device */
SDL_memset(haptic, 0, sizeof(SDL_Haptic));
haptic->rumble_id = -1;
if (SDL_SYS_HapticOpenFromJoystick(haptic, joystick) < 0) {
SDL_SetError("Haptic: SDL_SYS_HapticOpenFromJoystick failed.");
SDL_free(haptic);
return NULL;
}
/* Add haptic to list */
++haptic->ref_count;
/* Link the haptic in the list */
haptic->next = SDL_haptics;
SDL_haptics = haptic;
return haptic;
}
/*
* Closes a SDL_Haptic device.
*/
void
SDL_HapticClose(SDL_Haptic * haptic)
{
int i;
SDL_Haptic *hapticlist;
SDL_Haptic *hapticlistprev;
/* Must be valid */
if (!ValidHaptic(haptic)) {
return;
}
/* Check if it's still in use */
if (--haptic->ref_count > 0) {
return;
}
/* Close it, properly removing effects if needed */
for (i = 0; i < haptic->neffects; i++) {
if (haptic->effects[i].hweffect != NULL) {
SDL_HapticDestroyEffect(haptic, i);
}
}
SDL_SYS_HapticClose(haptic);
/* Remove from the list */
hapticlist = SDL_haptics;
hapticlistprev = NULL;
while ( hapticlist )
{
if (haptic == hapticlist)
{
if ( hapticlistprev )
{
/* unlink this entry */
hapticlistprev->next = hapticlist->next;
}
else
{
SDL_haptics = haptic->next;
}
break;
}
hapticlistprev = hapticlist;
hapticlist = hapticlist->next;
}
/* Free */
SDL_free(haptic);
}
/*
* Cleans up after the subsystem.
*/
void
SDL_HapticQuit(void)
{
while (SDL_haptics) {
SDL_HapticClose(SDL_haptics);
}
SDL_SYS_HapticQuit();
}
/*
* Returns the number of effects a haptic device has.
*/
int
SDL_HapticNumEffects(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return -1;
}
return haptic->neffects;
}
/*
* Returns the number of effects a haptic device can play.
*/
int
SDL_HapticNumEffectsPlaying(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return -1;
}
return haptic->nplaying;
}
/*
* Returns supported effects by the device.
*/
unsigned int
SDL_HapticQuery(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return 0; /* same as if no effects were supported */
}
return haptic->supported;
}
/*
* Returns the number of axis on the device.
*/
int
SDL_HapticNumAxes(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return -1;
}
return haptic->naxes;
}
/*
* Checks to see if the device can support the effect.
*/
int
SDL_HapticEffectSupported(SDL_Haptic * haptic, SDL_HapticEffect * effect)
{
if (!ValidHaptic(haptic)) {
return -1;
}
if ((haptic->supported & effect->type) != 0)
return SDL_TRUE;
return SDL_FALSE;
}
/*
* Creates a new haptic effect.
*/
int
SDL_HapticNewEffect(SDL_Haptic * haptic, SDL_HapticEffect * effect)
{
int i;
/* Check for device validity. */
if (!ValidHaptic(haptic)) {
return -1;
}
/* Check to see if effect is supported */
if (SDL_HapticEffectSupported(haptic, effect) == SDL_FALSE) {
return SDL_SetError("Haptic: Effect not supported by haptic device.");
}
/* See if there's a free slot */
for (i = 0; i < haptic->neffects; i++) {
if (haptic->effects[i].hweffect == NULL) {
/* Now let the backend create the real effect */
if (SDL_SYS_HapticNewEffect(haptic, &haptic->effects[i], effect)
!= 0) {
return -1; /* Backend failed to create effect */
}
SDL_memcpy(&haptic->effects[i].effect, effect,
sizeof(SDL_HapticEffect));
return i;
}
}
return SDL_SetError("Haptic: Device has no free space left.");
}
/*
* Checks to see if an effect is valid.
*/
static int
ValidEffect(SDL_Haptic * haptic, int effect)
{
if ((effect < 0) || (effect >= haptic->neffects)) {
SDL_SetError("Haptic: Invalid effect identifier.");
return 0;
}
return 1;
}
/*
* Updates an effect.
*/
int
SDL_HapticUpdateEffect(SDL_Haptic * haptic, int effect,
SDL_HapticEffect * data)
{
if (!ValidHaptic(haptic) || !ValidEffect(haptic, effect)) {
return -1;
}
/* Can't change type dynamically. */
if (data->type != haptic->effects[effect].effect.type) {
return SDL_SetError("Haptic: Updating effect type is illegal.");
}
/* Updates the effect */
if (SDL_SYS_HapticUpdateEffect(haptic, &haptic->effects[effect], data) <
0) {
return -1;
}
SDL_memcpy(&haptic->effects[effect].effect, data,
sizeof(SDL_HapticEffect));
return 0;
}
/*
* Runs the haptic effect on the device.
*/
int
SDL_HapticRunEffect(SDL_Haptic * haptic, int effect, Uint32 iterations)
{
if (!ValidHaptic(haptic) || !ValidEffect(haptic, effect)) {
return -1;
}
/* Run the effect */
if (SDL_SYS_HapticRunEffect(haptic, &haptic->effects[effect], iterations)
< 0) {
return -1;
}
return 0;
}
/*
* Stops the haptic effect on the device.
*/
int
SDL_HapticStopEffect(SDL_Haptic * haptic, int effect)
{
if (!ValidHaptic(haptic) || !ValidEffect(haptic, effect)) {
return -1;
}
/* Stop the effect */
if (SDL_SYS_HapticStopEffect(haptic, &haptic->effects[effect]) < 0) {
return -1;
}
return 0;
}
/*
* Gets rid of a haptic effect.
*/
void
SDL_HapticDestroyEffect(SDL_Haptic * haptic, int effect)
{
if (!ValidHaptic(haptic) || !ValidEffect(haptic, effect)) {
return;
}
/* Not allocated */
if (haptic->effects[effect].hweffect == NULL) {
return;
}
SDL_SYS_HapticDestroyEffect(haptic, &haptic->effects[effect]);
}
/*
* Gets the status of a haptic effect.
*/
int
SDL_HapticGetEffectStatus(SDL_Haptic * haptic, int effect)
{
if (!ValidHaptic(haptic) || !ValidEffect(haptic, effect)) {
return -1;
}
if ((haptic->supported & SDL_HAPTIC_STATUS) == 0) {
return SDL_SetError("Haptic: Device does not support status queries.");
}
return SDL_SYS_HapticGetEffectStatus(haptic, &haptic->effects[effect]);
}
/*
* Sets the global gain of the device.
*/
int
SDL_HapticSetGain(SDL_Haptic * haptic, int gain)
{
const char *env;
int real_gain, max_gain;
if (!ValidHaptic(haptic)) {
return -1;
}
if ((haptic->supported & SDL_HAPTIC_GAIN) == 0) {
return SDL_SetError("Haptic: Device does not support setting gain.");
}
if ((gain < 0) || (gain > 100)) {
return SDL_SetError("Haptic: Gain must be between 0 and 100.");
}
/* We use the envvar to get the maximum gain. */
env = SDL_getenv("SDL_HAPTIC_GAIN_MAX");
if (env != NULL) {
max_gain = SDL_atoi(env);
/* Check for sanity. */
if (max_gain < 0)
max_gain = 0;
else if (max_gain > 100)
max_gain = 100;
/* We'll scale it linearly with SDL_HAPTIC_GAIN_MAX */
real_gain = (gain * max_gain) / 100;
} else {
real_gain = gain;
}
if (SDL_SYS_HapticSetGain(haptic, real_gain) < 0) {
return -1;
}
return 0;
}
/*
* Makes the device autocenter, 0 disables.
*/
int
SDL_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter)
{
if (!ValidHaptic(haptic)) {
return -1;
}
if ((haptic->supported & SDL_HAPTIC_AUTOCENTER) == 0) {
return SDL_SetError("Haptic: Device does not support setting autocenter.");
}
if ((autocenter < 0) || (autocenter > 100)) {
return SDL_SetError("Haptic: Autocenter must be between 0 and 100.");
}
if (SDL_SYS_HapticSetAutocenter(haptic, autocenter) < 0) {
return -1;
}
return 0;
}
/*
* Pauses the haptic device.
*/
int
SDL_HapticPause(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return -1;
}
if ((haptic->supported & SDL_HAPTIC_PAUSE) == 0) {
return SDL_SetError("Haptic: Device does not support setting pausing.");
}
return SDL_SYS_HapticPause(haptic);
}
/*
* Unpauses the haptic device.
*/
int
SDL_HapticUnpause(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return -1;
}
if ((haptic->supported & SDL_HAPTIC_PAUSE) == 0) {
return 0; /* Not going to be paused, so we pretend it's unpaused. */
}
return SDL_SYS_HapticUnpause(haptic);
}
/*
* Stops all the currently playing effects.
*/
int
SDL_HapticStopAll(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return -1;
}
return SDL_SYS_HapticStopAll(haptic);
}
/*
* Checks to see if rumble is supported.
*/
int
SDL_HapticRumbleSupported(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return -1;
}
/* Most things can use SINE, but XInput only has LEFTRIGHT. */
return ((haptic->supported & (SDL_HAPTIC_SINE|SDL_HAPTIC_LEFTRIGHT)) != 0);
}
/*
* Initializes the haptic device for simple rumble playback.
*/
int
SDL_HapticRumbleInit(SDL_Haptic * haptic)
{
SDL_HapticEffect *efx = &haptic->rumble_effect;
if (!ValidHaptic(haptic)) {
return -1;
}
/* Already allocated. */
if (haptic->rumble_id >= 0) {
return 0;
}
SDL_zerop(efx);
if (haptic->supported & SDL_HAPTIC_SINE) {
efx->type = SDL_HAPTIC_SINE;
efx->periodic.direction.type = SDL_HAPTIC_CARTESIAN;
efx->periodic.period = 1000;
efx->periodic.magnitude = 0x4000;
efx->periodic.length = 5000;
efx->periodic.attack_length = 0;
efx->periodic.fade_length = 0;
} else if (haptic->supported & SDL_HAPTIC_LEFTRIGHT) { /* XInput? */
efx->type = SDL_HAPTIC_LEFTRIGHT;
efx->leftright.length = 5000;
efx->leftright.large_magnitude = 0x4000;
efx->leftright.small_magnitude = 0x4000;
} else {
return SDL_SetError("Device doesn't support rumble");
}
haptic->rumble_id = SDL_HapticNewEffect(haptic, &haptic->rumble_effect);
if (haptic->rumble_id >= 0) {
return 0;
}
return -1;
}
/*
* Runs simple rumble on a haptic device
*/
int
SDL_HapticRumblePlay(SDL_Haptic * haptic, float strength, Uint32 length)
{
SDL_HapticEffect *efx;
Sint16 magnitude;
if (!ValidHaptic(haptic)) {
return -1;
}
if (haptic->rumble_id < 0) {
return SDL_SetError("Haptic: Rumble effect not initialized on haptic device");
}
/* Clamp strength. */
if (strength > 1.0f) {
strength = 1.0f;
} else if (strength < 0.0f) {
strength = 0.0f;
}
magnitude = (Sint16)(32767.0f*strength);
efx = &haptic->rumble_effect;
if (efx->type == SDL_HAPTIC_SINE) {
efx->periodic.magnitude = magnitude;
efx->periodic.length = length;
} else if (efx->type == SDL_HAPTIC_LEFTRIGHT) {
efx->leftright.small_magnitude = efx->leftright.large_magnitude = magnitude;
efx->leftright.length = length;
} else {
SDL_assert(0 && "This should have been caught elsewhere");
}
if (SDL_HapticUpdateEffect(haptic, haptic->rumble_id, &haptic->rumble_effect) < 0) {
return -1;
}
return SDL_HapticRunEffect(haptic, haptic->rumble_id, 1);
}
/*
* Stops the simple rumble on a haptic device.
*/
int
SDL_HapticRumbleStop(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return -1;
}
if (haptic->rumble_id < 0) {
return SDL_SetError("Haptic: Rumble effect not initialized on haptic device");
}
return SDL_HapticStopEffect(haptic, haptic->rumble_id);
}
/* vi: set ts=4 sw=4 expandtab: */
| henu/Urho3D | Source/ThirdParty/SDL/src/haptic/SDL_haptic.c | C | mit | 18,982 |
<?php
/**
* A class for logging to the default php error log.
*
* @author Lasse Birnbaum Jensen, SDU.
* @author Andreas Åkre Solberg, UNINETT AS. <andreas.solberg@uninett.no>
* @author Olav Morken, UNINETT AS.
* @package SimpleSAMLphp
* @version $ID$
*/
class SimpleSAML_Logger_LoggingHandlerErrorLog implements SimpleSAML_Logger_LoggingHandler
{
/**
* This array contains the mappings from syslog loglevel to names.
*/
private static $levelNames = array(
SimpleSAML_Logger::EMERG => 'EMERG',
SimpleSAML_Logger::ALERT => 'ALERT',
SimpleSAML_Logger::CRIT => 'CRIT',
SimpleSAML_Logger::ERR => 'ERR',
SimpleSAML_Logger::WARNING => 'WARNING',
SimpleSAML_Logger::NOTICE => 'NOTICE',
SimpleSAML_Logger::INFO => 'INFO',
SimpleSAML_Logger::DEBUG => 'DEBUG',
);
private $format;
/**
* Set the format desired for the logs.
*
* @param string $format The format used for logs.
*/
public function setLogFormat($format)
{
$this->format = $format;
}
/**
* Log a message to syslog.
*
* @param int $level The log level.
* @param string $string The formatted message to log.
*/
public function log($level, $string)
{
$config = SimpleSAML_Configuration::getInstance();
assert($config instanceof SimpleSAML_Configuration);
$processname = $config->getString('logging.processname', 'SimpleSAMLphp');
if (array_key_exists($level, self::$levelNames)) {
$levelName = self::$levelNames[$level];
} else {
$levelName = sprintf('UNKNOWN%d', $level);
}
$formats = array('%process', '%level');
$replacements = array($processname, $levelName);
$string = str_replace($formats, $replacements, $string);
$string = preg_replace('/%\w+(\{[^\}]+\})?/', '', $string);
$string = trim($string);
error_log($string);
}
}
| sk-unikent/docker-moodle | shared/simplesamlphp/lib/SimpleSAML/Logger/LoggingHandlerErrorLog.php | PHP | mit | 2,008 |
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Web.DynamicData.Util;
using System.Web.Resources;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace System.Web.DynamicData {
/// <summary>
/// The base class for all field template user controls
/// </summary>
public class FieldTemplateUserControl : UserControl, IBindableControl, IFieldTemplate {
private static RequiredAttribute s_defaultRequiredAttribute = new RequiredAttribute();
private Dictionary<Type, bool> _ignoredModelValidationAttributes;
private object _fieldValue;
private DefaultValueMapping _defaultValueMapping;
private bool _pageDataItemSet;
private object _pageDataItem;
public FieldTemplateUserControl() {
}
internal FieldTemplateUserControl(DefaultValueMapping defaultValueMapping) {
_defaultValueMapping = defaultValueMapping;
}
/// <summary>
/// The host that provides context to this field template
/// </summary>
[Browsable(false)]
public IFieldTemplateHost Host { get; private set; }
/// <summary>
/// The formatting options that need to be applied to this field template
/// </summary>
[Browsable(false)]
public IFieldFormattingOptions FormattingOptions { get; private set; }
/// <summary>
/// The MetaColumn that this field template is working with
/// </summary>
[Browsable(false)]
public MetaColumn Column {
get {
return Host.Column;
}
}
/// <summary>
/// The ContainerType in which this
/// </summary>
[Browsable(false)]
public virtual ContainerType ContainerType {
get {
return Misc.FindContainerType(this);
}
}
/// <summary>
/// The MetaTable that this field's column belongs to
/// </summary>
[Browsable(false)]
public MetaTable Table {
get {
return Column.Table;
}
}
/// <summary>
/// Casts the MetaColumn to a MetaForeignKeyColumn. Throws if it is not an FK column.
/// </summary>
[Browsable(false)]
public MetaForeignKeyColumn ForeignKeyColumn {
get {
var foreignKeyColumn = Column as MetaForeignKeyColumn;
if (foreignKeyColumn == null) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
DynamicDataResources.FieldTemplateUserControl_ColumnIsNotFK, Column.Name));
}
return foreignKeyColumn;
}
}
/// <summary>
/// Casts the MetaColumn to a MetaChildrenColumn. Throws if it is not an Children column.
/// </summary>
[Browsable(false)]
public MetaChildrenColumn ChildrenColumn {
get {
var childrenColumn = Column as MetaChildrenColumn;
if (childrenColumn == null) {
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
DynamicDataResources.FieldTemplateUserControl_ColumnIsNotChildren, Column.Name));
}
return childrenColumn;
}
}
/// <summary>
/// The mode (readonly, edit, insert) that the field template should use
/// </summary>
[Browsable(false)]
public DataBoundControlMode Mode {
get {
return Host.Mode;
}
}
/// <summary>
/// The collection of metadata attributes that apply to this column
/// </summary>
[Browsable(false)]
public System.ComponentModel.AttributeCollection MetadataAttributes {
get {
return Column.Attributes;
}
}
/// <summary>
/// Returns the data control that handles the field inside the field template
/// </summary>
[Browsable(false)]
public virtual Control DataControl {
get {
return null;
}
}
/// <summary>
/// The current data object. Equivalent to Page.GetDataItem()
/// </summary>
[Browsable(false)]
public virtual object Row {
get {
// The DataItem is normally null in insert mode, we're going to surface the DictionaryCustomTypeDescriptor if there is a
// a default value was specified for this column.
if (Mode == DataBoundControlMode.Insert && DefaultValueMapping != null && DefaultValueMapping.Contains(Column)) {
return DefaultValueMapping.Instance;
}
// Used for unit testing. We can't use null since thats a valid value.
if (_pageDataItemSet) {
return _pageDataItem;
}
return Page.GetDataItem();
}
internal set {
// Only set in unit tests.
_pageDataItem = value;
_pageDataItemSet = true;
}
}
/// <summary>
/// The value of the Column in the current Row
/// </summary>
[Browsable(false)]
public virtual object FieldValue {
get {
// If a field value was explicitly set, use it instead of the usual logic.
if (_fieldValue != null)
return _fieldValue;
return GetColumnValue(Column);
}
set {
_fieldValue = value;
}
}
/// <summary>
/// Get the value of a specific column in the current row
/// </summary>
/// <param name="column"></param>
/// <returns></returns>
protected virtual object GetColumnValue(MetaColumn column) {
object row = Row;
if (row != null) {
return DataBinder.GetPropertyValue(row, column.Name);
}
// Fallback on old behavior
if (Mode == DataBoundControlMode.Insert) {
return column.DefaultValue;
}
return null;
}
/// <summary>
/// Return the field value as a formatted string
/// </summary>
[Browsable(false)]
public virtual string FieldValueString {
get {
// Get the string and preprocess it
return FormatFieldValue(FieldValue);
}
}
/// <summary>
/// Similar to FieldValueString, but the string is to be used when the field is in edit mode
/// </summary>
[Browsable(false)]
public virtual string FieldValueEditString {
get {
return FormattingOptions.FormatEditValue(FieldValue);
}
}
/// <summary>
/// Only applies to FK columns. Returns a URL that links to the page that displays the details
/// of the foreign key entity. e.g. In the Product table's Category column, this produces a link
/// that goes to the details of the category that the product is in
/// </summary>
protected string ForeignKeyPath {
get {
return ForeignKeyColumn.GetForeignKeyPath(PageAction.Details, Row);
}
}
internal DefaultValueMapping DefaultValueMapping {
get {
if (_defaultValueMapping == null) {
// Ensure this only gets accessed in insert mode
Debug.Assert(Mode == DataBoundControlMode.Insert);
_defaultValueMapping = MetaTableHelper.GetDefaultValueMapping(this, Context.ToWrapper());
}
return _defaultValueMapping;
}
}
/// <summary>
/// Same as ForeignKeyPath, except that it allows the path part of the URL to be overriden. This is
/// used when using pages that don't live under DynamicData/CustomPages.
/// </summary>
/// <param name="path">The path override</param>
/// <returns></returns>
protected string BuildForeignKeyPath(string path) {
// If a path was passed in, resolved it relative to the containing page
if (!String.IsNullOrEmpty(path)) {
path = ResolveParentRelativePath(path);
}
return ForeignKeyColumn.GetForeignKeyPath(PageAction.Details, Row, path);
}
/// <summary>
/// Only applies to Children columns. Returns a URL that links to the page that displays the list
/// of children entities. e.g. In the Category table's Products column, this produces a link
/// that goes to the list of Products that are in this Category.
/// </summary>
protected string ChildrenPath {
get {
return ChildrenColumn.GetChildrenPath(PageAction.List, Row);
}
}
/// <summary>
/// Same as ChildrenPath, except that it allows the path part of the URL to be overriden. This is
/// used when using pages that don't live under DynamicData/CustomPages.
/// </summary>
/// <param name="path">The path override</param>
/// <returns></returns>
protected string BuildChildrenPath(string path) {
// If a path was passed in, resolved it relative to the containing page
if (!String.IsNullOrEmpty(path)) {
path = ResolveParentRelativePath(path);
}
return ChildrenColumn.GetChildrenPath(PageAction.List, Row, path);
}
// Resolve a relative path based on the containing page
private string ResolveParentRelativePath(string path) {
if (path == null || TemplateControl == null)
return path;
Control parentControl = TemplateControl.Parent;
if (parentControl == null)
return path;
return parentControl.ResolveUrl(path);
}
/// <summary>
/// Return the field template for another column
/// </summary>
protected FieldTemplateUserControl FindOtherFieldTemplate(string columnName) {
return Parent.FindFieldTemplate(columnName) as FieldTemplateUserControl;
}
/// <summary>
/// Only applies to FK columns. Populate the list control with all the values from the parent table
/// </summary>
/// <param name="listControl">The control to be populated</param>
protected void PopulateListControl(ListControl listControl) {
Type enumType;
if (Column is MetaForeignKeyColumn) {
Misc.FillListItemCollection(ForeignKeyColumn.ParentTable, listControl.Items);
} else if (Column.IsEnumType(out enumType)) {
Debug.Assert(enumType != null);
FillEnumListControl(listControl, enumType);
}
}
private void FillEnumListControl(ListControl list, Type enumType) {
foreach (DictionaryEntry entry in Misc.GetEnumNamesAndValues(enumType)) {
list.Items.Add(new ListItem((string)entry.Key, (string)entry.Value));
}
}
/// <summary>
/// Gets a string representation of the column's value so that it can be matched with
/// values populated in a dropdown. This currently works for FK and Enum columns only.
/// The method returns null for other column types.
/// </summary>
/// <returns></returns>
protected string GetSelectedValueString() {
Type enumType;
if (Column is MetaForeignKeyColumn) {
return ForeignKeyColumn.GetForeignKeyString(Row);
} else if(Column.IsEnumType(out enumType)) {
return Misc.GetUnderlyingTypeValueString(enumType, FieldValue);
}
return null;
}
/// <summary>
/// Only applies to FK columns. This is used when saving the value of a foreign key, typically selected
/// from a drop down.
/// </summary>
/// <param name="dictionary">The dictionary that contains all the new values</param>
/// <param name="selectedValue">The value to be saved. Typically, this comes from DropDownList.SelectedValue</param>
protected virtual void ExtractForeignKey(IDictionary dictionary, string selectedValue) {
ForeignKeyColumn.ExtractForeignKey(dictionary, selectedValue);
}
/// <summary>
/// Apply potential HTML encoding and formatting to a string that needs to be displayed
/// </summary>
/// <param name="fieldValue">The value that should be formatted</param>
/// <returns>the formatted value</returns>
public virtual string FormatFieldValue(object fieldValue) {
return FormattingOptions.FormatValue(fieldValue);
}
/// <summary>
/// Return either the input value or null based on ConvertEmptyStringToNull and NullDisplayText
/// </summary>
/// <param name="value">The input value</param>
/// <returns>The converted value</returns>
protected virtual object ConvertEditedValue(string value) {
return FormattingOptions.ConvertEditedValue(value);
}
/// <summary>
/// Set up a validator for dynamic data use. It sets the ValidationGroup on all validators,
/// and also performs additional logic for some specific validator types. e.g. for a RangeValidator
/// it sets the range values if they exist on the model.
/// </summary>
/// <param name="validator">The validator to be set up</param>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly",
Justification = "We really want Set Up as two words")]
protected virtual void SetUpValidator(BaseValidator validator) {
SetUpValidator(validator, Column);
}
/// <summary>
/// Set up a validator for dynamic data use. It sets the ValidationGroup on all validators,
/// and also performs additional logic for some specific validator types. e.g. for a RangeValidator
/// it sets the range values if they exist on the model.
/// </summary>
/// <param name="validator">The validator to be set up</param>
/// <param name="column">The column for which the validator is getting set</param>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly",
Justification = "We really want Set Up as two words")]
protected virtual void SetUpValidator(BaseValidator validator, MetaColumn column) {
// Set the validation group to match the dynamic control
validator.ValidationGroup = Host.ValidationGroup;
if (validator is DynamicValidator) {
SetUpDynamicValidator((DynamicValidator)validator, column);
}
else if (validator is RequiredFieldValidator) {
SetUpRequiredFieldValidator((RequiredFieldValidator)validator, column);
}
else if (validator is CompareValidator) {
SetUpCompareValidator((CompareValidator)validator, column);
}
else if (validator is RangeValidator) {
SetUpRangeValidator((RangeValidator)validator, column);
}
else if (validator is RegularExpressionValidator) {
SetUpRegexValidator((RegularExpressionValidator)validator, column);
}
validator.ToolTip = validator.ErrorMessage;
validator.Text = "*";
}
private void SetUpDynamicValidator(DynamicValidator validator, MetaColumn column) {
validator.Column = column;
// Tell the DynamicValidator which validation attributes it should ignore (because
// they're already handled by server side ASP.NET validator controls)
validator.SetIgnoredModelValidationAttributes(_ignoredModelValidationAttributes);
}
private void SetUpRequiredFieldValidator(RequiredFieldValidator validator, MetaColumn column) {
var requiredAttribute = column.Metadata.RequiredAttribute;
if (requiredAttribute!= null && requiredAttribute.AllowEmptyStrings) {
// Dev10 Bug 749744
// If somone explicitly set AllowEmptyStrings = true then we assume that they want to
// allow empty strings to go into a database even if the column is marked as required.
// Since ASP.NET validators always get an empty string, this essential turns of
// required field validation.
IgnoreModelValidationAttribute(typeof(RequiredAttribute));
} else if (column.IsRequired) {
validator.Enabled = true;
// Make sure the attribute doesn't get validated a second time by the DynamicValidator
IgnoreModelValidationAttribute(typeof(RequiredAttribute));
if (String.IsNullOrEmpty(validator.ErrorMessage)) {
string columnErrorMessage = column.RequiredErrorMessage;
if (String.IsNullOrEmpty(columnErrorMessage)) {
// generate default error message
validator.ErrorMessage = HttpUtility.HtmlEncode(s_defaultRequiredAttribute.FormatErrorMessage(column.DisplayName));
} else {
validator.ErrorMessage = HttpUtility.HtmlEncode(columnErrorMessage);
}
}
}
}
private void SetUpCompareValidator(CompareValidator validator, MetaColumn column) {
validator.Operator = ValidationCompareOperator.DataTypeCheck;
ValidationDataType? dataType = null;
string errorMessage = null;
if (column.ColumnType == typeof(DateTime)) {
dataType = ValidationDataType.Date;
errorMessage = String.Format(CultureInfo.CurrentCulture,
DynamicDataResources.FieldTemplateUserControl_CompareValidationError_Date,
column.DisplayName);
} else if (column.IsInteger && column.ColumnType != typeof(long)) {
// long is unsupported because it's larger than int
dataType = ValidationDataType.Integer;
errorMessage = String.Format(CultureInfo.CurrentCulture,
DynamicDataResources.FieldTemplateUserControl_CompareValidationError_Integer,
column.DisplayName);
} else if (column.ColumnType == typeof(decimal)) {
//
dataType = ValidationDataType.Double;
errorMessage = String.Format(CultureInfo.CurrentCulture,
DynamicDataResources.FieldTemplateUserControl_CompareValidationError_Decimal,
column.DisplayName);
} else if (column.IsFloatingPoint) {
dataType = ValidationDataType.Double;
errorMessage = String.Format(CultureInfo.CurrentCulture,
DynamicDataResources.FieldTemplateUserControl_CompareValidationError_Decimal,
column.DisplayName);
}
if (dataType != null) {
Debug.Assert(errorMessage != null);
validator.Enabled = true;
validator.Type = dataType.Value;
if (String.IsNullOrEmpty(validator.ErrorMessage)) {
validator.ErrorMessage = HttpUtility.HtmlEncode(errorMessage);
}
} else {
// If we don't recognize the type, turn off the validator
validator.Enabled = false;
}
}
private void SetUpRangeValidator(RangeValidator validator, MetaColumn column) {
// Nothing to do if no range was specified
var rangeAttribute = column.Attributes.OfType<RangeAttribute>().FirstOrDefault();
if (rangeAttribute == null)
return;
// Make sure the attribute doesn't get validated a second time by the DynamicValidator
IgnoreModelValidationAttribute(rangeAttribute.GetType());
validator.Enabled = true;
Func<object, string> converter;
switch (validator.Type) {
case ValidationDataType.Integer:
converter = val => Convert.ToInt32(val, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
break;
case ValidationDataType.Double:
converter = val => Convert.ToDouble(val, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
break;
case ValidationDataType.String:
default:
converter = val => val.ToString();
break;
}
validator.MinimumValue = converter(rangeAttribute.Minimum);
validator.MaximumValue = converter(rangeAttribute.Maximum);
if (String.IsNullOrEmpty(validator.ErrorMessage)) {
validator.ErrorMessage = HttpUtility.HtmlEncode(rangeAttribute.FormatErrorMessage(column.DisplayName));
}
}
private void SetUpRegexValidator(RegularExpressionValidator validator, MetaColumn column) {
// Nothing to do if no regex was specified
var regexAttribute = column.Attributes.OfType<RegularExpressionAttribute>().FirstOrDefault();
if (regexAttribute == null)
return;
// Make sure the attribute doesn't get validated a second time by the DynamicValidator
IgnoreModelValidationAttribute(regexAttribute.GetType());
validator.Enabled = true;
validator.ValidationExpression = regexAttribute.Pattern;
if (String.IsNullOrEmpty(validator.ErrorMessage)) {
validator.ErrorMessage = HttpUtility.HtmlEncode(regexAttribute.FormatErrorMessage(column.DisplayName));
}
}
/// <summary>
/// This method instructs the DynamicValidator to ignore a specific type of model
/// validation attributes. This is called when that attribute type is already being
/// fully handled by an ASP.NET validator controls. Without this call, the validation
/// could happen twice, resulting in a duplicated error message
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2301:EmbeddableTypesInContainersRule", MessageId = "_ignoredModelValidationAttributes", Justification = "The types that go into this dictionary are specifically ValidationAttribute derived types.")]
protected void IgnoreModelValidationAttribute(Type attributeType)
{
// Create the dictionary on demand
if (_ignoredModelValidationAttributes == null) {
_ignoredModelValidationAttributes = new Dictionary<Type, bool>();
}
// Add the attribute type to the list
_ignoredModelValidationAttributes[attributeType] = true;
}
/// <summary>
/// Implementation of IBindableControl.ExtractValues
/// </summary>
/// <param name="dictionary">The dictionary that contains all the new values</param>
protected virtual void ExtractValues(IOrderedDictionary dictionary) {
// To nothing in the base class. Derived field templates decide what they want to save
}
#region IBindableControl Members
void IBindableControl.ExtractValues(IOrderedDictionary dictionary) {
ExtractValues(dictionary);
}
#endregion
#region IFieldTemplate Members
void IFieldTemplate.SetHost(IFieldTemplateHost host) {
Host = host;
FormattingOptions = Host.FormattingOptions;
}
#endregion
}
}
| esdrubal/referencesource | System.Web.DynamicData/DynamicData/FieldTemplateUserControl.cs | C# | mit | 24,603 |
/****************************************************************************
Copyright (c) 2012 cocos2d-x.org
Copyright (c) 2010 Sangwoo Im
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCTableView.h"
#include "CCTableViewCell.h"
NS_CC_EXT_BEGIN
TableView* TableView::create()
{
return TableView::create(nullptr, Size::ZERO);
}
TableView* TableView::create(TableViewDataSource* dataSource, Size size)
{
return TableView::create(dataSource, size, nullptr);
}
TableView* TableView::create(TableViewDataSource* dataSource, Size size, Node *container)
{
TableView *table = new (std::nothrow) TableView();
table->initWithViewSize(size, container);
table->autorelease();
table->setDataSource(dataSource);
table->_updateCellPositions();
table->_updateContentSize();
return table;
}
bool TableView::initWithViewSize(Size size, Node* container/* = nullptr*/)
{
if (ScrollView::initWithViewSize(size,container))
{
CC_SAFE_DELETE(_indices);
_indices = new (std::nothrow) std::set<ssize_t>();
_vordering = VerticalFillOrder::BOTTOM_UP;
this->setDirection(Direction::VERTICAL);
ScrollView::setDelegate(this);
return true;
}
return false;
}
TableView::TableView()
: _touchedCell(nullptr)
, _indices(nullptr)
, _dataSource(nullptr)
, _tableViewDelegate(nullptr)
, _oldDirection(Direction::NONE)
, _isUsedCellsDirty(false)
{
}
TableView::~TableView()
{
CC_SAFE_DELETE(_indices);
}
void TableView::setVerticalFillOrder(VerticalFillOrder fillOrder)
{
if (_vordering != fillOrder)
{
_vordering = fillOrder;
if (!_cellsUsed.empty())
{
this->reloadData();
}
}
}
TableView::VerticalFillOrder TableView::getVerticalFillOrder()
{
return _vordering;
}
void TableView::reloadData()
{
_oldDirection = Direction::NONE;
for(const auto &cell : _cellsUsed) {
if(_tableViewDelegate != nullptr) {
_tableViewDelegate->tableCellWillRecycle(this, cell);
}
_cellsFreed.pushBack(cell);
cell->reset();
if (cell->getParent() == this->getContainer())
{
this->getContainer()->removeChild(cell, true);
}
}
_indices->clear();
_cellsUsed.clear();
this->_updateCellPositions();
this->_updateContentSize();
if (_dataSource->numberOfCellsInTableView(this) > 0)
{
this->scrollViewDidScroll(this);
}
}
TableViewCell *TableView::cellAtIndex(ssize_t idx)
{
if (_indices->find(idx) != _indices->end())
{
for (const auto& cell : _cellsUsed)
{
if (cell->getIdx() == idx)
{
return cell;
}
}
}
return nullptr;
}
void TableView::updateCellAtIndex(ssize_t idx)
{
if (idx == CC_INVALID_INDEX)
{
return;
}
long countOfItems = _dataSource->numberOfCellsInTableView(this);
if (0 == countOfItems || idx > countOfItems-1)
{
return;
}
TableViewCell* cell = this->cellAtIndex(idx);
if (cell)
{
this->_moveCellOutOfSight(cell);
}
cell = _dataSource->tableCellAtIndex(this, idx);
this->_setIndexForCell(idx, cell);
this->_addCellIfNecessary(cell);
}
void TableView::insertCellAtIndex(ssize_t idx)
{
if (idx == CC_INVALID_INDEX)
{
return;
}
long countOfItems = _dataSource->numberOfCellsInTableView(this);
if (0 == countOfItems || idx > countOfItems-1)
{
return;
}
long newIdx = 0;
auto cell = cellAtIndex(idx);
if (cell)
{
newIdx = _cellsUsed.getIndex(cell);
// Move all cells behind the inserted position
for (long i = newIdx; i < _cellsUsed.size(); i++)
{
cell = _cellsUsed.at(i);
this->_setIndexForCell(cell->getIdx()+1, cell);
}
}
//insert a new cell
cell = _dataSource->tableCellAtIndex(this, idx);
this->_setIndexForCell(idx, cell);
this->_addCellIfNecessary(cell);
this->_updateCellPositions();
this->_updateContentSize();
}
void TableView::removeCellAtIndex(ssize_t idx)
{
if (idx == CC_INVALID_INDEX)
{
return;
}
long uCountOfItems = _dataSource->numberOfCellsInTableView(this);
if (0 == uCountOfItems || idx > uCountOfItems-1)
{
return;
}
ssize_t newIdx = 0;
TableViewCell* cell = this->cellAtIndex(idx);
if (!cell)
{
return;
}
newIdx = _cellsUsed.getIndex(cell);
//remove first
this->_moveCellOutOfSight(cell);
_indices->erase(idx);
this->_updateCellPositions();
for (ssize_t i = _cellsUsed.size()-1; i > newIdx; i--)
{
cell = _cellsUsed.at(i);
this->_setIndexForCell(cell->getIdx()-1, cell);
}
}
TableViewCell *TableView::dequeueCell()
{
TableViewCell *cell;
if (_cellsFreed.empty()) {
cell = nullptr;
} else {
cell = _cellsFreed.at(0);
cell->retain();
_cellsFreed.erase(0);
cell->autorelease();
}
return cell;
}
void TableView::_addCellIfNecessary(TableViewCell * cell)
{
if (cell->getParent() != this->getContainer())
{
this->getContainer()->addChild(cell);
}
_cellsUsed.pushBack(cell);
_indices->insert(cell->getIdx());
_isUsedCellsDirty = true;
}
void TableView::_updateContentSize()
{
Size size = Size::ZERO;
ssize_t cellsCount = _dataSource->numberOfCellsInTableView(this);
if (cellsCount > 0)
{
float maxPosition = _vCellsPositions[cellsCount];
switch (this->getDirection())
{
case Direction::HORIZONTAL:
size = Size(maxPosition, _viewSize.height);
break;
default:
size = Size(_viewSize.width, maxPosition);
break;
}
}
this->setContentSize(size);
if (_oldDirection != _direction)
{
if (_direction == Direction::HORIZONTAL)
{
this->setContentOffset(Vec2(0,0));
}
else
{
this->setContentOffset(Vec2(0,this->minContainerOffset().y));
}
_oldDirection = _direction;
}
}
Vec2 TableView::_offsetFromIndex(ssize_t index)
{
Vec2 offset = this->__offsetFromIndex(index);
const Size cellSize = _dataSource->tableCellSizeForIndex(this, index);
if (_vordering == VerticalFillOrder::TOP_DOWN)
{
offset.y = this->getContainer()->getContentSize().height - offset.y - cellSize.height;
}
return offset;
}
Vec2 TableView::__offsetFromIndex(ssize_t index)
{
Vec2 offset;
Size cellSize;
switch (this->getDirection())
{
case Direction::HORIZONTAL:
offset.set(_vCellsPositions[index], 0.0f);
break;
default:
offset.set(0.0f, _vCellsPositions[index]);
break;
}
return offset;
}
long TableView::_indexFromOffset(Vec2 offset)
{
long index = 0;
const long maxIdx = _dataSource->numberOfCellsInTableView(this) - 1;
if (_vordering == VerticalFillOrder::TOP_DOWN)
{
offset.y = this->getContainer()->getContentSize().height - offset.y;
}
index = this->__indexFromOffset(offset);
if (index != -1)
{
index = MAX(0, index);
if (index > maxIdx)
{
index = CC_INVALID_INDEX;
}
}
return index;
}
long TableView::__indexFromOffset(Vec2 offset)
{
long low = 0;
long high = _dataSource->numberOfCellsInTableView(this) - 1;
float search;
switch (this->getDirection())
{
case Direction::HORIZONTAL:
search = offset.x;
break;
default:
search = offset.y;
break;
}
while (high >= low)
{
long index = low + (high - low) / 2;
float cellStart = _vCellsPositions[index];
float cellEnd = _vCellsPositions[index + 1];
if (search >= cellStart && search <= cellEnd)
{
return index;
}
else if (search < cellStart)
{
high = index - 1;
}
else
{
low = index + 1;
}
}
if (low <= 0) {
return 0;
}
return -1;
}
void TableView::_moveCellOutOfSight(TableViewCell *cell)
{
if(_tableViewDelegate != nullptr) {
_tableViewDelegate->tableCellWillRecycle(this, cell);
}
_cellsFreed.pushBack(cell);
_cellsUsed.eraseObject(cell);
_isUsedCellsDirty = true;
_indices->erase(cell->getIdx());
cell->reset();
if (cell->getParent() == this->getContainer())
{
this->getContainer()->removeChild(cell, true);;
}
}
void TableView::_setIndexForCell(ssize_t index, TableViewCell *cell)
{
cell->setAnchorPoint(Vec2(0.0f, 0.0f));
cell->setPosition(this->_offsetFromIndex(index));
cell->setIdx(index);
}
void TableView::_updateCellPositions()
{
long cellsCount = _dataSource->numberOfCellsInTableView(this);
_vCellsPositions.resize(cellsCount + 1, 0.0);
if (cellsCount > 0)
{
float currentPos = 0;
Size cellSize;
for (int i=0; i < cellsCount; i++)
{
_vCellsPositions[i] = currentPos;
cellSize = _dataSource->tableCellSizeForIndex(this, i);
switch (this->getDirection())
{
case Direction::HORIZONTAL:
currentPos += cellSize.width;
break;
default:
currentPos += cellSize.height;
break;
}
}
_vCellsPositions[cellsCount] = currentPos;//1 extra value allows us to get right/bottom of the last cell
}
}
void TableView::scrollViewDidScroll(ScrollView* view)
{
long countOfItems = _dataSource->numberOfCellsInTableView(this);
if (0 == countOfItems)
{
return;
}
if (_isUsedCellsDirty)
{
_isUsedCellsDirty = false;
std::sort(_cellsUsed.begin(), _cellsUsed.end(), [](TableViewCell *a, TableViewCell *b) -> bool{
return a->getIdx() < b->getIdx();
});
}
if(_tableViewDelegate != nullptr) {
_tableViewDelegate->scrollViewDidScroll(this);
}
ssize_t startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0;
Vec2 offset = this->getContentOffset() * -1;
maxIdx = MAX(countOfItems-1, 0);
if (_vordering == VerticalFillOrder::TOP_DOWN)
{
offset.y = offset.y + _viewSize.height/this->getContainer()->getScaleY();
}
startIdx = this->_indexFromOffset(offset);
if (startIdx == CC_INVALID_INDEX)
{
startIdx = countOfItems - 1;
}
if (_vordering == VerticalFillOrder::TOP_DOWN)
{
offset.y -= _viewSize.height/this->getContainer()->getScaleY();
}
else
{
offset.y += _viewSize.height/this->getContainer()->getScaleY();
}
offset.x += _viewSize.width/this->getContainer()->getScaleX();
endIdx = this->_indexFromOffset(offset);
if (endIdx == CC_INVALID_INDEX)
{
endIdx = countOfItems - 1;
}
#if 0 // For Testing.
Ref* pObj;
int i = 0;
CCARRAY_FOREACH(_cellsUsed, pObj)
{
TableViewCell* pCell = static_cast<TableViewCell*>(pObj);
log("cells Used index %d, value = %d", i, pCell->getIdx());
i++;
}
log("---------------------------------------");
i = 0;
CCARRAY_FOREACH(_cellsFreed, pObj)
{
TableViewCell* pCell = static_cast<TableViewCell*>(pObj);
log("cells freed index %d, value = %d", i, pCell->getIdx());
i++;
}
log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
#endif
if (!_cellsUsed.empty())
{
auto cell = _cellsUsed.at(0);
idx = cell->getIdx();
while(idx < startIdx)
{
this->_moveCellOutOfSight(cell);
if (!_cellsUsed.empty())
{
cell = _cellsUsed.at(0);
idx = cell->getIdx();
}
else
{
break;
}
}
}
if (!_cellsUsed.empty())
{
auto cell = _cellsUsed.back();
idx = cell->getIdx();
while(idx <= maxIdx && idx > endIdx)
{
this->_moveCellOutOfSight(cell);
if (!_cellsUsed.empty())
{
cell = _cellsUsed.back();
idx = cell->getIdx();
}
else
{
break;
}
}
}
for (long i = startIdx; i <= endIdx; i++)
{
if (_indices->find(i) != _indices->end())
{
continue;
}
this->updateCellAtIndex(i);
}
}
void TableView::onTouchEnded(Touch *pTouch, Event *pEvent)
{
if (!this->isVisible()) {
return;
}
if (_touchedCell){
Rect bb = this->getBoundingBox();
bb.origin = _parent->convertToWorldSpace(bb.origin);
if (bb.containsPoint(pTouch->getLocation()) && _tableViewDelegate != nullptr)
{
_tableViewDelegate->tableCellUnhighlight(this, _touchedCell);
_tableViewDelegate->tableCellTouched(this, _touchedCell);
}
_touchedCell = nullptr;
}
ScrollView::onTouchEnded(pTouch, pEvent);
}
bool TableView::onTouchBegan(Touch *pTouch, Event *pEvent)
{
for (Node *c = this; c != nullptr; c = c->getParent())
{
if (!c->isVisible())
{
return false;
}
}
bool touchResult = ScrollView::onTouchBegan(pTouch, pEvent);
if(_touches.size() == 1)
{
long index;
Vec2 point;
point = this->getContainer()->convertTouchToNodeSpace(pTouch);
index = this->_indexFromOffset(point);
if (index == CC_INVALID_INDEX)
{
_touchedCell = nullptr;
}
else
{
_touchedCell = this->cellAtIndex(index);
}
if (_touchedCell && _tableViewDelegate != nullptr)
{
_tableViewDelegate->tableCellHighlight(this, _touchedCell);
}
}
else if (_touchedCell)
{
if(_tableViewDelegate != nullptr)
{
_tableViewDelegate->tableCellUnhighlight(this, _touchedCell);
}
_touchedCell = nullptr;
}
return touchResult;
}
void TableView::onTouchMoved(Touch *pTouch, Event *pEvent)
{
ScrollView::onTouchMoved(pTouch, pEvent);
if (_touchedCell && isTouchMoved())
{
if(_tableViewDelegate != nullptr)
{
_tableViewDelegate->tableCellUnhighlight(this, _touchedCell);
}
_touchedCell = nullptr;
}
}
void TableView::onTouchCancelled(Touch *pTouch, Event *pEvent)
{
ScrollView::onTouchCancelled(pTouch, pEvent);
if (_touchedCell)
{
if(_tableViewDelegate != nullptr)
{
_tableViewDelegate->tableCellUnhighlight(this, _touchedCell);
}
_touchedCell = nullptr;
}
}
NS_CC_EXT_END
| DmitryFrolov/courseWork | cocos2d/extensions/GUI/CCScrollView/CCTableView.cpp | C++ | mit | 16,040 |
# Module 'os2emxpath' -- common operations on OS/2 pathnames
"""Common pathname manipulations, OS/2 EMX version.
Instead of importing this module directly, import os and refer to this
module as os.path.
"""
import os
import stat
from genericpath import *
from genericpath import _unicode
from ntpath import (expanduser, expandvars, isabs, islink, splitdrive,
splitext, split, walk)
__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
"basename","dirname","commonprefix","getsize","getmtime",
"getatime","getctime", "islink","exists","lexists","isdir","isfile",
"ismount","walk","expanduser","expandvars","normpath","abspath",
"splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
"extsep","devnull","realpath","supports_unicode_filenames"]
# strings representing various path-related bits and pieces
curdir = '.'
pardir = '..'
extsep = '.'
sep = '/'
altsep = '\\'
pathsep = ';'
defpath = '.;C:\\bin'
devnull = 'nul'
# Normalize the case of a pathname and map slashes to backslashes.
# Other normalizations (such as optimizing '../' away) are not done
# (this is done by normpath).
def normcase(s):
"""Normalize case of pathname.
Makes all characters lowercase and all altseps into seps."""
return s.replace('\\', '/').lower()
# Join two (or more) paths.
def join(a, *p):
"""Join two or more pathname components, inserting sep as needed"""
path = a
for b in p:
if isabs(b):
path = b
elif path == '' or path[-1:] in '/\\:':
path = path + b
else:
path = path + '/' + b
return path
# Parse UNC paths
def splitunc(p):
"""Split a pathname into UNC mount point and relative path specifiers.
Return a 2-tuple (unc, rest); either part may be empty.
If unc is not empty, it has the form '//host/mount' (or similar
using backslashes). unc+rest is always the input path.
Paths containing drive letters never have an UNC part.
"""
if p[1:2] == ':':
return '', p # Drive letter present
firstTwo = p[0:2]
if firstTwo == '/' * 2 or firstTwo == '\\' * 2:
# is a UNC path:
# vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
# \\machine\mountpoint\directories...
# directory ^^^^^^^^^^^^^^^
normp = normcase(p)
index = normp.find('/', 2)
if index == -1:
##raise RuntimeError, 'illegal UNC path: "' + p + '"'
return ("", p)
index = normp.find('/', index + 1)
if index == -1:
index = len(p)
return p[:index], p[index:]
return '', p
# Return the tail (basename) part of a path.
def basename(p):
"""Returns the final component of a pathname"""
return split(p)[1]
# Return the head (dirname) part of a path.
def dirname(p):
"""Returns the directory component of a pathname"""
return split(p)[0]
# alias exists to lexists
lexists = exists
# Is a path a directory?
# Is a path a mount point? Either a root (with or without drive letter)
# or an UNC path with at most a / or \ after the mount point.
def ismount(path):
"""Test whether a path is a mount point (defined as root of drive)"""
unc, rest = splitunc(path)
if unc:
return rest in ("", "/", "\\")
p = splitdrive(path)[1]
return len(p) == 1 and p[0] in '/\\'
# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
path = path.replace('\\', '/')
prefix, path = splitdrive(path)
while path[:1] == '/':
prefix = prefix + '/'
path = path[1:]
comps = path.split('/')
i = 0
while i < len(comps):
if comps[i] == '.':
del comps[i]
elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
del comps[i-1:i+1]
i = i - 1
elif comps[i] == '' and i > 0 and comps[i-1] != '':
del comps[i]
else:
i = i + 1
# If the path is now empty, substitute '.'
if not prefix and not comps:
comps.append('.')
return prefix + '/'.join(comps)
# Return an absolute path.
def abspath(path):
"""Return the absolute version of a path"""
if not isabs(path):
if isinstance(path, _unicode):
cwd = os.getcwdu()
else:
cwd = os.getcwd()
path = join(cwd, path)
return normpath(path)
# realpath is a no-op on systems without islink support
realpath = abspath
supports_unicode_filenames = False
| mcking49/apache-flask | Python/Lib/os2emxpath.py | Python | mit | 4,637 |
/*
Simple DirectMedia Layer
Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#if SDL_AUDIO_DRIVER_ESD
/* Allow access to an ESD network stream mixing buffer */
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <esd.h>
#include "SDL_timer.h"
#include "SDL_audio.h"
#include "../SDL_audio_c.h"
#include "SDL_esdaudio.h"
#ifdef SDL_AUDIO_DRIVER_ESD_DYNAMIC
#include "SDL_name.h"
#include "SDL_loadso.h"
#else
#define SDL_NAME(X) X
#endif
#ifdef SDL_AUDIO_DRIVER_ESD_DYNAMIC
static const char *esd_library = SDL_AUDIO_DRIVER_ESD_DYNAMIC;
static void *esd_handle = NULL;
static int (*SDL_NAME(esd_open_sound)) (const char *host);
static int (*SDL_NAME(esd_close)) (int esd);
static int (*SDL_NAME(esd_play_stream)) (esd_format_t format, int rate,
const char *host, const char *name);
#define SDL_ESD_SYM(x) { #x, (void **) (char *) &SDL_NAME(x) }
static struct
{
const char *name;
void **func;
} const esd_functions[] = {
SDL_ESD_SYM(esd_open_sound),
SDL_ESD_SYM(esd_close), SDL_ESD_SYM(esd_play_stream),
};
#undef SDL_ESD_SYM
static void
UnloadESDLibrary()
{
if (esd_handle != NULL) {
SDL_UnloadObject(esd_handle);
esd_handle = NULL;
}
}
static int
LoadESDLibrary(void)
{
int i, retval = -1;
if (esd_handle == NULL) {
esd_handle = SDL_LoadObject(esd_library);
if (esd_handle) {
retval = 0;
for (i = 0; i < SDL_arraysize(esd_functions); ++i) {
*esd_functions[i].func =
SDL_LoadFunction(esd_handle, esd_functions[i].name);
if (!*esd_functions[i].func) {
retval = -1;
UnloadESDLibrary();
break;
}
}
}
}
return retval;
}
#else
static void
UnloadESDLibrary()
{
return;
}
static int
LoadESDLibrary(void)
{
return 0;
}
#endif /* SDL_AUDIO_DRIVER_ESD_DYNAMIC */
/* This function waits until it is possible to write a full sound buffer */
static void
ESD_WaitDevice(_THIS)
{
Sint32 ticks;
/* Check to see if the thread-parent process is still alive */
{
static int cnt = 0;
/* Note that this only works with thread implementations
that use a different process id for each thread.
*/
/* Check every 10 loops */
if (this->hidden->parent && (((++cnt) % 10) == 0)) {
if (kill(this->hidden->parent, 0) < 0 && errno == ESRCH) {
SDL_OpenedAudioDeviceDisconnected(this);
}
}
}
/* Use timer for general audio synchronization */
ticks = ((Sint32) (this->hidden->next_frame - SDL_GetTicks())) - FUDGE_TICKS;
if (ticks > 0) {
SDL_Delay(ticks);
}
}
static void
ESD_PlayDevice(_THIS)
{
int written = 0;
/* Write the audio data, checking for EAGAIN on broken audio drivers */
do {
written = write(this->hidden->audio_fd,
this->hidden->mixbuf, this->hidden->mixlen);
if ((written < 0) && ((errno == 0) || (errno == EAGAIN))) {
SDL_Delay(1); /* Let a little CPU time go by */
}
} while ((written < 0) &&
((errno == 0) || (errno == EAGAIN) || (errno == EINTR)));
/* Set the next write frame */
this->hidden->next_frame += this->hidden->frame_ticks;
/* If we couldn't write, assume fatal error for now */
if (written < 0) {
SDL_OpenedAudioDeviceDisconnected(this);
}
}
static Uint8 *
ESD_GetDeviceBuf(_THIS)
{
return (this->hidden->mixbuf);
}
static void
ESD_CloseDevice(_THIS)
{
if (this->hidden->audio_fd >= 0) {
SDL_NAME(esd_close) (this->hidden->audio_fd);
}
SDL_free(this->hidden->mixbuf);
SDL_free(this->hidden);
}
/* Try to get the name of the program */
static char *
get_progname(void)
{
char *progname = NULL;
#ifdef __LINUX__
FILE *fp;
static char temp[BUFSIZ];
SDL_snprintf(temp, SDL_arraysize(temp), "/proc/%d/cmdline", getpid());
fp = fopen(temp, "r");
if (fp != NULL) {
if (fgets(temp, sizeof(temp) - 1, fp)) {
progname = SDL_strrchr(temp, '/');
if (progname == NULL) {
progname = temp;
} else {
progname = progname + 1;
}
}
fclose(fp);
}
#endif
return (progname);
}
static int
ESD_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
{
esd_format_t format = (ESD_STREAM | ESD_PLAY);
SDL_AudioFormat test_format = 0;
int found = 0;
/* Initialize all variables that we clean on shutdown */
this->hidden = (struct SDL_PrivateAudioData *)
SDL_malloc((sizeof *this->hidden));
if (this->hidden == NULL) {
return SDL_OutOfMemory();
}
SDL_zerop(this->hidden);
this->hidden->audio_fd = -1;
/* Convert audio spec to the ESD audio format */
/* Try for a closest match on audio format */
for (test_format = SDL_FirstAudioFormat(this->spec.format);
!found && test_format; test_format = SDL_NextAudioFormat()) {
#ifdef DEBUG_AUDIO
fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
#endif
found = 1;
switch (test_format) {
case AUDIO_U8:
format |= ESD_BITS8;
break;
case AUDIO_S16SYS:
format |= ESD_BITS16;
break;
default:
found = 0;
break;
}
}
if (!found) {
return SDL_SetError("Couldn't find any hardware audio formats");
}
if (this->spec.channels == 1) {
format |= ESD_MONO;
} else {
format |= ESD_STEREO;
}
#if 0
this->spec.samples = ESD_BUF_SIZE; /* Darn, no way to change this yet */
#endif
/* Open a connection to the ESD audio server */
this->hidden->audio_fd =
SDL_NAME(esd_play_stream) (format, this->spec.freq, NULL,
get_progname());
if (this->hidden->audio_fd < 0) {
return SDL_SetError("Couldn't open ESD connection");
}
/* Calculate the final parameters for this audio specification */
SDL_CalculateAudioSpec(&this->spec);
this->hidden->frame_ticks =
(float) (this->spec.samples * 1000) / this->spec.freq;
this->hidden->next_frame = SDL_GetTicks() + this->hidden->frame_ticks;
/* Allocate mixing buffer */
this->hidden->mixlen = this->spec.size;
this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen);
if (this->hidden->mixbuf == NULL) {
return SDL_OutOfMemory();
}
SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);
/* Get the parent process id (we're the parent of the audio thread) */
this->hidden->parent = getpid();
/* We're ready to rock and roll. :-) */
return 0;
}
static void
ESD_Deinitialize(void)
{
UnloadESDLibrary();
}
static int
ESD_Init(SDL_AudioDriverImpl * impl)
{
if (LoadESDLibrary() < 0) {
return 0;
} else {
int connection = 0;
/* Don't start ESD if it's not running */
SDL_setenv("ESD_NO_SPAWN", "1", 0);
connection = SDL_NAME(esd_open_sound) (NULL);
if (connection < 0) {
UnloadESDLibrary();
SDL_SetError("ESD: esd_open_sound failed (no audio server?)");
return 0;
}
SDL_NAME(esd_close) (connection);
}
/* Set the function pointers */
impl->OpenDevice = ESD_OpenDevice;
impl->PlayDevice = ESD_PlayDevice;
impl->WaitDevice = ESD_WaitDevice;
impl->GetDeviceBuf = ESD_GetDeviceBuf;
impl->CloseDevice = ESD_CloseDevice;
impl->Deinitialize = ESD_Deinitialize;
impl->OnlyHasDefaultOutputDevice = 1;
return 1; /* this audio target is available. */
}
AudioBootStrap ESD_bootstrap = {
"esd", "Enlightened Sound Daemon", ESD_Init, 0
};
#endif /* SDL_AUDIO_DRIVER_ESD */
/* vi: set ts=4 sw=4 expandtab: */
| eugeneko/Urho3D | Source/ThirdParty/SDL/src/audio/esd/SDL_esdaudio.c | C | mit | 8,911 |
declare module ChangeLinr {
export interface IChangeLinrTransform {
(data: any, key: string, attributes: any, scope: IChangeLinr): any;
}
export interface IChangeLinrCache {
[i: string]: any;
}
export interface IChangeLinrCacheFull {
[i: string]: {
[i: string]: any;
}
}
export interface IChangeLinrSettings {
pipeline: string[];
transforms: {
[i: string]: IChangeLinrTransform
};
doMakeCache?: boolean;
doUseCache?: boolean;
}
export interface IChangeLinr {
getCache(): IChangeLinrCache;
getCached(key: string): any;
getCacheFull(): IChangeLinrCacheFull;
getDoMakeCache(): boolean;
getDoUseCache(): boolean;
process(data: any, key?: string, attributes?: any): any;
processFull(data: any, key?: string, attributes?: any): any;
}
}
module ChangeLinr {
"use strict";
/**
* A general utility for transforming raw input to processed output. This is
* done by keeping an Array of transform Functions to process input on.
* Outcomes for inputs are cached so repeat runs are O(1).
*/
export class ChangeLinr implements IChangeLinr {
/**
* Functions that may be used to transform data, keyed by name.
*/
private transforms: {
[i: string]: IChangeLinrTransform;
};
/**
* Ordered listing of Function names to be applied to raw input.
*/
private pipeline: string[];
/**
* Cached output of previous results of the the pipeline.
*/
private cache: IChangeLinrCache;
/**
* Cached output of each step of the pipeline.
*/
private cacheFull: IChangeLinrCacheFull;
/**
* Whether this should be caching responses.
*/
private doMakeCache: boolean;
/**
* Whether this should be retrieving and using cached results.
*/
private doUseCache: boolean;
/**
* @param {IChangeLinrSettings} settings
*/
constructor(settings: IChangeLinrSettings) {
var i: number;
if (typeof settings.pipeline === "undefined") {
throw new Error("No pipeline given to ChangeLinr.");
}
this.pipeline = settings.pipeline || [];
if (typeof settings.transforms === "undefined") {
throw new Error("No transforms given to ChangeLinr.");
}
this.transforms = settings.transforms || {};
this.doMakeCache = typeof settings.doMakeCache === "undefined"
? true : settings.doMakeCache;
this.doUseCache = typeof settings.doUseCache === "undefined"
? true : settings.doUseCache;
this.cache = {};
this.cacheFull = {};
// Ensure the pipeline is formatted correctly
for (i = 0; i < this.pipeline.length; ++i) {
// Don't allow null/false transforms
if (!this.pipeline[i]) {
throw new Error("Pipe[" + i + "] is invalid.");
}
// Make sure each part of the pipeline exists
if (!this.transforms.hasOwnProperty(this.pipeline[i])) {
if (!this.transforms.hasOwnProperty(this.pipeline[i])) {
throw new Error(
"Pipe[" + i + "] (\"" + this.pipeline[i] + "\") "
+ "not found in transforms."
);
}
}
// Also make sure each part of the pipeline is a Function
if (!(this.transforms[this.pipeline[i]] instanceof Function)) {
throw new Error(
"Pipe[" + i + "] (\"" + this.pipeline[i] + "\") "
+ "is not a valid Function from transforms."
);
}
this.cacheFull[i] = this.cacheFull[this.pipeline[i]] = {};
}
}
/* Simple gets
*/
/**
* @return {Mixed} The cached output of this.process and this.processFull.
*/
getCache(): IChangeLinrCache {
return this.cache;
}
/**
* @param {String} key The key under which the output was processed
* @return {Mixed} The cached output filed under the given key.
*/
getCached(key: string): any {
return this.cache[key];
}
/**
* @return {Object} A complete listing of the cached outputs from all
* processed information, from each pipeline transform.
*/
getCacheFull(): IChangeLinrCacheFull {
return this.cacheFull;
}
/**
* @return {Boolean} Whether the cache object is being kept.
*/
getDoMakeCache(): boolean {
return this.doMakeCache;
}
/**
* @return {Boolean} Whether previously cached output is being used in new
* process requests.
*/
getDoUseCache(): boolean {
return this.doUseCache;
}
/* Core processing
*/
/**
* Applies a series of transforms to input data. If doMakeCache is on, the
* outputs of this are stored in cache and cacheFull.
*
* @param {Mixed} data The data to be transformed.
* @param {String} [key] They key under which the data is to be stored.
* If needed but not provided, defaults to data.
* @param {Object} [attributes] Any extra attributes to be given to the
* transform Functions.
* @return {Mixed} The final output of the pipeline.
*/
process(data: any, key: string = undefined, attributes: any = undefined): any {
var i: number;
if (typeof key === "undefined" && (this.doMakeCache || this.doUseCache)) {
key = data;
}
// If this keyed input was already processed, get that
if (this.doUseCache && this.cache.hasOwnProperty(key)) {
return this.cache[key];
}
// Apply (and optionally cache) each transform in order
for (i = 0; i < this.pipeline.length; ++i) {
data = this.transforms[this.pipeline[i]](data, key, attributes, this);
if (this.doMakeCache) {
this.cacheFull[this.pipeline[i]][key] = data;
}
}
if (this.doMakeCache) {
this.cache[key] = data;
}
return data;
}
/**
* A version of this.process that returns the complete output from each
* pipelined transform Function in an Object.
*
* @param {Mixed} data The data to be transformed.
* @param {String} [key] They key under which the data is to be stored.
* If needed but not provided, defaults to data.
* @param {Object} [attributes] Any extra attributes to be given to the
* transform Functions.
* @return {Object} The complete output of the transforms.
*/
processFull(raw: any, key: string, attributes: any = undefined): any {
var output: any = {},
i: number;
this.process(raw, key, attributes);
for (i = 0; i < this.pipeline.length; ++i) {
output[i] = output[this.pipeline[i]] = this.cacheFull[this.pipeline[i]][key];
}
return output;
}
}
}
| shuidong/FullScreenMario | Source/References/ChangeLinr-0.2.0.ts | TypeScript | mit | 7,933 |
/**
* Copyright (c) 2008-2011 The Open Planning Project
*
* Published under the GPL license.
* See https://github.com/opengeo/gxp/raw/master/license.txt for the full text
* of the license.
*/
/**
* @requires plugins/ClickableFeatures.js
* @requires widgets/grid/FeatureGrid.js
* requires GeoExt/widgets/grid/FeatureSelectionModel.js
*/
/** api: (define)
* module = gxp.plugins
* class = FeatureGrid
*/
/** api: (extends)
* plugins/ClickableFeatures.js
*/
Ext.namespace("gxp.plugins");
/** api: constructor
* .. class:: FeatureGrid(config)
*
* Plugin for displaying vector features in a grid. Requires a
* :class:`gxp.plugins.FeatureManager`. Also provides a context menu for
* the grid.
*/
gxp.plugins.FeatureGrid = Ext.extend(gxp.plugins.ClickableFeatures, {
/** api: ptype = gxp_featuregrid */
ptype: "gxp_featuregrid",
/** private: property[schema]
* ``GeoExt.data.AttributeStore``
*/
schema: null,
/** api: config[showTotalResults]
* ``Boolean`` If set to true, the total number of records will be shown
* in the bottom toolbar of the grid, if available.
*/
showTotalResults: false,
/** api: config[alwaysDisplayOnMap]
* ``Boolean`` If set to true, the features that are shown in the grid
* will always be displayed on the map, and there will be no "Display on
* map" button in the toolbar. Default is false. If set to true, no
* "Display on map" button will be shown.
*/
alwaysDisplayOnMap: false,
/** api: config[displayMode]
* ``String`` Should we display all features on the map, or only the ones
* that are currently selected on the grid. Valid values are "all" and
* "selected". Default is "all".
*/
displayMode: "all",
/** api: config[autoExpand]
* ``Boolean`` If set to true, and when this tool's output is added to a
* container that can be expanded, it will be expanded when features are
* loaded. Default is false.
*/
autoExpand: false,
/** api: config[autoCollapse]
* ``Boolean`` If set to true, and when this tool's output is added to a
* container that can be collapsed, it will be collapsed when no features
* are to be displayed. Default is false.
*/
autoCollapse: false,
/** api: config[selectOnMap]
* ``Boolean`` If set to true, features can not only be selected on the
* grid, but also on the map, and multi-selection will be enabled. Only
* set to true when no feature editor or feature info tool is used with
* the underlying feature manager. Default is false.
*/
selectOnMap: false,
/** api: config[displayFeatureText]
* ``String``
* Text for feature display button (i18n).
*/
displayFeatureText: "Display on map",
/** api: config[zoomFirstPageTip]
* ``String``
* Tooltip string for first page action (i18n).
*/
firstPageTip: "First page",
/** api: config[previousPageTip]
* ``String``
* Tooltip string for previous page action (i18n).
*/
previousPageTip: "Previous page",
/** api: config[zoomFirstPageTip]
* ``String``
* Tooltip string for zoom to page extent action (i18n).
*/
zoomPageExtentTip: "Zoom to page extent",
/** api: config[nextPageTip]
* ``String``
* Tooltip string for next page action (i18n).
*/
nextPageTip: "Next page",
/** api: config[lastPageTip]
* ``String``
* Tooltip string for last page action (i18n).
*/
lastPageTip: "Last page",
/** api: config[totalMsg]
* ``String``
* String template for showing total number of records (i18n).
*/
totalMsg: "Total: {0} records",
/** private: method[displayTotalResults]
*/
displayTotalResults: function() {
var featureManager = this.target.tools[this.featureManager];
if (this.showTotalResults === true && featureManager.numberOfFeatures !== null) {
this.displayItem.setText(
String.format(
this.totalMsg,
featureManager.numberOfFeatures
)
);
}
},
/** api: method[addOutput]
*/
addOutput: function(config) {
var featureManager = this.target.tools[this.featureManager];
var map = this.target.mapPanel.map, smCfg;
// a minimal SelectFeature control - used just to provide select and
// unselect, won't be added to the map unless selectOnMap is true
this.selectControl = new OpenLayers.Control.SelectFeature(
featureManager.featureLayer, this.initialConfig.controlOptions
);
if (this.selectOnMap) {
if (featureManager.paging) {
this.selectControl.events.on({
"activate": function() {
map.events.register(
"click", this, this.noFeatureClick
);
},
"deactivate": function() {
map.events.unregister(
"click", this, this.noFeatureClick
);
},
scope: this
});
}
map.addControl(this.selectControl);
smCfg = {
selectControl: this.selectControl
};
} else {
smCfg = {
selectControl: this.selectControl,
singleSelect: false,
autoActivateControl: false,
listeners: {
"beforerowselect": function() {
if(this.selectControl.active || featureManager.featureStore.getModifiedRecords().length) {
return false;
}
},
scope: this
}
};
}
this.displayItem = new Ext.Toolbar.TextItem({});
config = Ext.apply({
xtype: "gxp_featuregrid",
sm: new GeoExt.grid.FeatureSelectionModel(smCfg),
autoScroll: true,
bbar: (featureManager.paging ? [{
iconCls: "x-tbar-page-first",
ref: "../firstPageButton",
tooltip: this.firstPageTip,
disabled: true,
handler: function() {
featureManager.setPage({index: 0});
}
}, {
iconCls: "x-tbar-page-prev",
ref: "../prevPageButton",
tooltip: this.previousPageTip,
disabled: true,
handler: function() {
featureManager.previousPage();
}
}, {
iconCls: "gxp-icon-zoom-to",
ref: "../zoomToPageButton",
tooltip: this.zoomPageExtentTip,
disabled: true,
hidden: featureManager.autoZoomPage,
handler: function() {
var extent = featureManager.getPageExtent();
if (extent !== null) {
map.zoomToExtent(extent);
}
}
}, {
iconCls: "x-tbar-page-next",
ref: "../nextPageButton",
tooltip: this.nextPageTip,
disabled: true,
handler: function() {
featureManager.nextPage();
}
}, {
iconCls: "x-tbar-page-last",
ref: "../lastPageButton",
tooltip: this.lastPageTip,
disabled: true,
handler: function() {
featureManager.setPage({index: "last"});
}
}, {xtype: 'tbspacer', width: 10}, this.displayItem] : []).concat(["->"].concat(!this.alwaysDisplayOnMap ? [{
text: this.displayFeatureText,
enableToggle: true,
toggleHandler: function(btn, pressed) {
this.selectOnMap && this.selectControl[pressed ? "activate" : "deactivate"]();
featureManager[pressed ? "showLayer" : "hideLayer"](this.id, this.displayMode);
},
scope: this
}] : [])),
listeners: {
"added": function(cmp, ownerCt) {
function onClear() {
this.displayTotalResults();
this.selectOnMap && this.selectControl.deactivate();
this.autoCollapse && typeof ownerCt.collapse == "function" &&
ownerCt.collapse();
}
function onPopulate() {
this.displayTotalResults();
this.selectOnMap && this.selectControl.activate();
this.autoExpand && typeof ownerCt.expand == "function" &&
ownerCt.expand();
}
featureManager.on({
"query": function(tool, store) {
if (store && store.getCount()) {
onPopulate.call(this);
} else {
onClear.call(this);
}
},
"layerchange": onClear,
"clearfeatures": onClear,
scope: this
});
},
contextmenu: function(event) {
if (featureGrid.contextMenu.items.getCount() > 0) {
var rowIndex = featureGrid.getView().findRowIndex(event.getTarget());
if (rowIndex !== false) {
featureGrid.getSelectionModel().selectRow(rowIndex);
featureGrid.contextMenu.showAt(event.getXY());
event.stopEvent();
}
}
},
scope: this
},
contextMenu: new Ext.menu.Menu({items: []})
}, config || {});
var featureGrid = gxp.plugins.FeatureGrid.superclass.addOutput.call(this, config);
if (this.alwaysDisplayOnMap || this.selectOnMap) {
featureManager.showLayer(this.id, this.displayMode);
}
featureManager.paging && featureManager.on({
"beforesetpage": function() {
featureGrid.zoomToPageButton.disable();
},
"setpage": function(mgr, condition, callback, scope, pageIndex, numPages) {
var paging = (numPages > 0);
featureGrid.zoomToPageButton.setDisabled(!paging);
var prev = (paging && (pageIndex !== 0));
featureGrid.firstPageButton.setDisabled(!prev);
featureGrid.prevPageButton.setDisabled(!prev);
var next = (paging && (pageIndex !== numPages-1));
featureGrid.lastPageButton.setDisabled(!next);
featureGrid.nextPageButton.setDisabled(!next);
},
scope: this
});
function onLayerChange() {
var schema = featureManager.schema,
ignoreFields = ["feature", "state", "fid"];
//TODO use schema instead of store to configure the fields
schema && schema.each(function(r) {
r.get("type").indexOf("gml:") == 0 && ignoreFields.push(r.get("name"));
});
featureGrid.ignoreFields = ignoreFields;
featureGrid.setStore(featureManager.featureStore, schema);
}
if (featureManager.featureStore) {
onLayerChange.call(this);
}
featureManager.on("layerchange", onLayerChange, this);
return featureGrid;
}
});
Ext.preg(gxp.plugins.FeatureGrid.prototype.ptype, gxp.plugins.FeatureGrid);
| code-for-india/sahana_shelter_worldbank | static/scripts/gis/gxp/plugins/FeatureGrid.js | JavaScript | mit | 12,534 |
//
// AppDelegate.m
// CLImageEditorDemo
//
// Created by sho yakushiji on 2013/11/14.
// Copyright (c) 2013年 CALACULU. All rights reserved.
//
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
/*
CGRect rect = CGRectMake(0, 0, 1, 1);
// Create a 1 by 1 pixel context
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
[[UIColor blueColor] setFill];
UIRectFill(rect); // Fill it with your color
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
*/
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
| ChronicStim/CLImageEditor | Demo/CLImageEditorDemo/CLImageEditorDemo/AppDelegate.m | Matlab | mit | 2,470 |
var fieldTests = require('./commonFieldTestUtils.js');
var ModelTestConfig = require('../../../modelTestConfig/HtmlModelTestConfig');
module.exports = {
before: function (browser) {
fieldTests.before(browser);
browser.adminUIInitialFormScreen.setDefaultModelTestConfig(ModelTestConfig);
browser.adminUIItemScreen.setDefaultModelTestConfig(ModelTestConfig);
browser.adminUIListScreen.setDefaultModelTestConfig(ModelTestConfig);
},
after: fieldTests.after,
'Html field should show correctly in the initial modal': function (browser) {
browser.adminUIApp.openList({ section: 'fields', list: 'Html' });
browser.adminUIListScreen.clickCreateItemButton();
browser.adminUIApp.waitForInitialFormScreen();
browser.adminUIInitialFormScreen.assertFieldUIVisible({
fields: [
{ name: 'name', },
{ name: 'fieldA', },
],
});
browser.adminUIInitialFormScreen.cancel();
browser.adminUIApp.waitForListScreen();
},
'Html field can be filled via the initial modal': function (browser) {
browser.adminUIApp.openList({ section: 'fields', list: 'Html' });
browser.adminUIListScreen.clickCreateItemButton();
browser.adminUIApp.waitForInitialFormScreen();
browser.adminUIInitialFormScreen.fillFieldInputs({
fields: [
{ name: 'name', input: { value: 'Html Field Test 1' }, },
{ name: 'fieldA', input: { value: 'Some test html code for field A' }, },
],
});
browser.adminUIInitialFormScreen.assertFieldInputs({
fields: [
{ name: 'name', input: { value: 'Html Field Test 1' }, },
// FIXME: webteckie Jan 13, 2017 -- For some reason this doesn't work in SauceLabs
//{ name: 'fieldA', input: { value: 'Some test html code for field A' }, },
],
});
browser.adminUIInitialFormScreen.save();
browser.adminUIApp.waitForItemScreen();
},
'Html field should show correctly in the edit form': function (browser) {
browser.adminUIItemScreen.assertFieldUIVisible({
fields: [
{ name: 'name', },
{ name: 'fieldA', },
{ name: 'fieldB', },
],
});
browser.adminUIItemScreen.assertFieldInputs({
fields: [
{ name: 'name', input: { value: 'Html Field Test 1' }, },
// FIXME: webteckie Jan 13, 2017 -- For some reason this doesn't work in SauceLabs
//{ name: 'fieldA', input: { value: 'Some test html code for field A' }, },
],
});
},
'Html field can be filled via the edit form': function (browser) {
browser.adminUIItemScreen.fillFieldInputs({
fields: [
{ name: 'fieldB', input: { value: 'Some test html code for field B' }, },
],
});
browser.adminUIItemScreen.save();
browser.adminUIApp.waitForItemScreen();
browser.adminUIItemScreen.assertElementTextEquals({ element: '@flashMessage', text: 'Your changes have been saved successfully' });
browser.adminUIItemScreen.assertFieldInputs({
fields: [
{ name: 'name', input: { value: 'Html Field Test 1' }, },
// FIXME: webteckie Jan 13, 2017 -- For some reason this doesn't work in SauceLabs
//{ name: 'fieldA', input: { value: 'Some test html code for field A' }, },
//{ name: 'fieldB', input: { value: 'Some test html code for field B' }, },
],
});
},
};
| rafmsou/keystone | test/e2e/adminUI/tests/group006Fields/testHtmlField.js | JavaScript | mit | 3,155 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_Appengine_FeatureSettings extends Google_Model
{
public $splitHealthChecks;
public $useContainerOptimizedOs;
public function setSplitHealthChecks($splitHealthChecks)
{
$this->splitHealthChecks = $splitHealthChecks;
}
public function getSplitHealthChecks()
{
return $this->splitHealthChecks;
}
public function setUseContainerOptimizedOs($useContainerOptimizedOs)
{
$this->useContainerOptimizedOs = $useContainerOptimizedOs;
}
public function getUseContainerOptimizedOs()
{
return $this->useContainerOptimizedOs;
}
}
| gamonoid/icehrm | core/lib/composer/vendor/google/apiclient-services/src/Google/Service/Appengine/FeatureSettings.php | PHP | mit | 1,179 |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
internal interface IContentFocusManager
{
void Activate(IDockContent content);
void GiveUpFocus(IDockContent content);
void AddToList(IDockContent content);
void RemoveFromList(IDockContent content);
}
partial class DockPanel
{
private interface IFocusManager
{
void SuspendFocusTracking();
void ResumeFocusTracking();
bool IsFocusTrackingSuspended { get; }
IDockContent ActiveContent { get; }
DockPane ActivePane { get; }
IDockContent ActiveDocument { get; }
DockPane ActiveDocumentPane { get; }
}
private class FocusManagerImpl : Component, IContentFocusManager, IFocusManager
{
private class HookEventArgs : EventArgs
{
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
public int HookCode;
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
public IntPtr wParam;
public IntPtr lParam;
}
private class LocalWindowsHook : IDisposable
{
// Internal properties
private IntPtr m_hHook = IntPtr.Zero;
private NativeMethods.HookProc m_filterFunc = null;
private Win32.HookType m_hookType;
// Event delegate
public delegate void HookEventHandler(object sender, HookEventArgs e);
// Event: HookInvoked
public event HookEventHandler HookInvoked;
protected void OnHookInvoked(HookEventArgs e)
{
if (HookInvoked != null)
HookInvoked(this, e);
}
public LocalWindowsHook(Win32.HookType hook)
{
m_hookType = hook;
m_filterFunc = new NativeMethods.HookProc(this.CoreHookProc);
}
// Default filter function
public IntPtr CoreHookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0)
return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam);
// Let clients determine what to do
HookEventArgs e = new HookEventArgs();
e.HookCode = code;
e.wParam = wParam;
e.lParam = lParam;
OnHookInvoked(e);
// Yield to the next hook in the chain
return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam);
}
// Install the hook
public void Install()
{
if (m_hHook != IntPtr.Zero)
Uninstall();
int threadId = NativeMethods.GetCurrentThreadId();
m_hHook = NativeMethods.SetWindowsHookEx(m_hookType, m_filterFunc, IntPtr.Zero, threadId);
}
// Uninstall the hook
public void Uninstall()
{
if (m_hHook != IntPtr.Zero)
{
NativeMethods.UnhookWindowsHookEx(m_hHook);
m_hHook = IntPtr.Zero;
}
}
~LocalWindowsHook()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
Uninstall();
}
}
private LocalWindowsHook m_localWindowsHook;
private LocalWindowsHook.HookEventHandler m_hookEventHandler;
public FocusManagerImpl(DockPanel dockPanel)
{
m_dockPanel = dockPanel;
m_localWindowsHook = new LocalWindowsHook(Win32.HookType.WH_CALLWNDPROCRET);
m_hookEventHandler = new LocalWindowsHook.HookEventHandler(HookEventHandler);
m_localWindowsHook.HookInvoked += m_hookEventHandler;
m_localWindowsHook.Install();
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
private bool m_disposed = false;
protected override void Dispose(bool disposing)
{
lock (this)
{
if (!m_disposed && disposing)
{
m_localWindowsHook.Dispose();
m_disposed = true;
}
base.Dispose(disposing);
}
}
private IDockContent m_contentActivating = null;
private IDockContent ContentActivating
{
get { return m_contentActivating; }
set { m_contentActivating = value; }
}
public void Activate(IDockContent content)
{
if (IsFocusTrackingSuspended)
{
ContentActivating = content;
return;
}
if (content == null)
return;
DockContentHandler handler = content.DockHandler;
if (handler.Form.IsDisposed)
return; // Should not reach here, but better than throwing an exception
if (ContentContains(content, handler.ActiveWindowHandle))
NativeMethods.SetFocus(handler.ActiveWindowHandle);
if (!handler.Form.ContainsFocus)
{
if (!handler.Form.SelectNextControl(handler.Form.ActiveControl, true, true, true, true))
// Since DockContent Form is not selectalbe, use Win32 SetFocus instead
NativeMethods.SetFocus(handler.Form.Handle);
}
}
private List<IDockContent> m_listContent = new List<IDockContent>();
private List<IDockContent> ListContent
{
get { return m_listContent; }
}
public void AddToList(IDockContent content)
{
if (ListContent.Contains(content) || IsInActiveList(content))
return;
ListContent.Add(content);
}
public void RemoveFromList(IDockContent content)
{
if (IsInActiveList(content))
RemoveFromActiveList(content);
if (ListContent.Contains(content))
ListContent.Remove(content);
}
private IDockContent m_lastActiveContent = null;
private IDockContent LastActiveContent
{
get { return m_lastActiveContent; }
set { m_lastActiveContent = value; }
}
private bool IsInActiveList(IDockContent content)
{
return !(content.DockHandler.NextActive == null && LastActiveContent != content);
}
private void AddLastToActiveList(IDockContent content)
{
IDockContent last = LastActiveContent;
if (last == content)
return;
DockContentHandler handler = content.DockHandler;
if (IsInActiveList(content))
RemoveFromActiveList(content);
handler.PreviousActive = last;
handler.NextActive = null;
LastActiveContent = content;
if (last != null)
last.DockHandler.NextActive = LastActiveContent;
}
private void RemoveFromActiveList(IDockContent content)
{
if (LastActiveContent == content)
LastActiveContent = content.DockHandler.PreviousActive;
IDockContent prev = content.DockHandler.PreviousActive;
IDockContent next = content.DockHandler.NextActive;
if (prev != null)
prev.DockHandler.NextActive = next;
if (next != null)
next.DockHandler.PreviousActive = prev;
content.DockHandler.PreviousActive = null;
content.DockHandler.NextActive = null;
}
public void GiveUpFocus(IDockContent content)
{
DockContentHandler handler = content.DockHandler;
if (!handler.Form.ContainsFocus)
return;
if (IsFocusTrackingSuspended)
DockPanel.DummyControl.Focus();
if (LastActiveContent == content)
{
IDockContent prev = handler.PreviousActive;
if (prev != null)
Activate(prev);
else if (ListContent.Count > 0)
Activate(ListContent[ListContent.Count - 1]);
}
else if (LastActiveContent != null)
Activate(LastActiveContent);
else if (ListContent.Count > 0)
Activate(ListContent[ListContent.Count - 1]);
}
private static bool ContentContains(IDockContent content, IntPtr hWnd)
{
Control control = Control.FromChildHandle(hWnd);
for (Control parent = control; parent != null; parent = parent.Parent)
if (parent == content.DockHandler.Form)
return true;
return false;
}
private int m_countSuspendFocusTracking = 0;
public void SuspendFocusTracking()
{
m_countSuspendFocusTracking++;
m_localWindowsHook.HookInvoked -= m_hookEventHandler;
}
public void ResumeFocusTracking()
{
if (m_countSuspendFocusTracking > 0)
m_countSuspendFocusTracking--;
if (m_countSuspendFocusTracking == 0)
{
if (ContentActivating != null)
{
Activate(ContentActivating);
ContentActivating = null;
}
m_localWindowsHook.HookInvoked += m_hookEventHandler;
if (!InRefreshActiveWindow)
RefreshActiveWindow();
}
}
public bool IsFocusTrackingSuspended
{
get { return m_countSuspendFocusTracking != 0; }
}
// Windows hook event handler
private void HookEventHandler(object sender, HookEventArgs e)
{
Win32.Msgs msg = (Win32.Msgs)Marshal.ReadInt32(e.lParam, IntPtr.Size * 3);
if (msg == Win32.Msgs.WM_KILLFOCUS)
{
IntPtr wParam = Marshal.ReadIntPtr(e.lParam, IntPtr.Size * 2);
DockPane pane = GetPaneFromHandle(wParam);
if (pane == null)
RefreshActiveWindow();
}
else if (msg == Win32.Msgs.WM_SETFOCUS)
RefreshActiveWindow();
}
private DockPane GetPaneFromHandle(IntPtr hWnd)
{
Control control = Control.FromChildHandle(hWnd);
IDockContent content = null;
DockPane pane = null;
for (; control != null; control = control.Parent)
{
content = control as IDockContent;
if (content != null)
content.DockHandler.ActiveWindowHandle = hWnd;
if (content != null && content.DockHandler.DockPanel == DockPanel)
return content.DockHandler.Pane;
pane = control as DockPane;
if (pane != null && pane.DockPanel == DockPanel)
break;
}
return pane;
}
private bool m_inRefreshActiveWindow = false;
private bool InRefreshActiveWindow
{
get { return m_inRefreshActiveWindow; }
}
private void RefreshActiveWindow()
{
SuspendFocusTracking();
m_inRefreshActiveWindow = true;
DockPane oldActivePane = ActivePane;
IDockContent oldActiveContent = ActiveContent;
IDockContent oldActiveDocument = ActiveDocument;
SetActivePane();
SetActiveContent();
SetActiveDocumentPane();
SetActiveDocument();
DockPanel.AutoHideWindow.RefreshActivePane();
ResumeFocusTracking();
m_inRefreshActiveWindow = false;
if (oldActiveContent != ActiveContent)
DockPanel.OnActiveContentChanged(EventArgs.Empty);
if (oldActiveDocument != ActiveDocument)
DockPanel.OnActiveDocumentChanged(EventArgs.Empty);
if (oldActivePane != ActivePane)
DockPanel.OnActivePaneChanged(EventArgs.Empty);
}
private DockPane m_activePane = null;
public DockPane ActivePane
{
get { return m_activePane; }
}
private void SetActivePane()
{
DockPane value = GetPaneFromHandle(NativeMethods.GetFocus());
if (m_activePane == value)
return;
if (m_activePane != null)
m_activePane.SetIsActivated(false);
m_activePane = value;
if (m_activePane != null)
m_activePane.SetIsActivated(true);
}
private IDockContent m_activeContent = null;
public IDockContent ActiveContent
{
get { return m_activeContent; }
}
internal void SetActiveContent()
{
IDockContent value = ActivePane == null ? null : ActivePane.ActiveContent;
if (m_activeContent == value)
return;
if (m_activeContent != null)
m_activeContent.DockHandler.IsActivated = false;
m_activeContent = value;
if (m_activeContent != null)
{
m_activeContent.DockHandler.IsActivated = true;
if (!DockHelper.IsDockStateAutoHide((m_activeContent.DockHandler.DockState)))
AddLastToActiveList(m_activeContent);
}
}
private DockPane m_activeDocumentPane = null;
public DockPane ActiveDocumentPane
{
get { return m_activeDocumentPane; }
}
private void SetActiveDocumentPane()
{
DockPane value = null;
if (ActivePane != null && ActivePane.DockState == DockState.Document)
value = ActivePane;
if (value == null && DockPanel.DockWindows != null)
{
if (ActiveDocumentPane == null)
value = DockPanel.DockWindows[DockState.Document].DefaultPane;
else if (ActiveDocumentPane.DockPanel != DockPanel || ActiveDocumentPane.DockState != DockState.Document)
value = DockPanel.DockWindows[DockState.Document].DefaultPane;
else
value = ActiveDocumentPane;
}
if (m_activeDocumentPane == value)
return;
if (m_activeDocumentPane != null)
m_activeDocumentPane.SetIsActiveDocumentPane(false);
m_activeDocumentPane = value;
if (m_activeDocumentPane != null)
m_activeDocumentPane.SetIsActiveDocumentPane(true);
}
private IDockContent m_activeDocument = null;
public IDockContent ActiveDocument
{
get { return m_activeDocument; }
}
private void SetActiveDocument()
{
IDockContent value = ActiveDocumentPane == null ? null : ActiveDocumentPane.ActiveContent;
if (m_activeDocument == value)
return;
m_activeDocument = value;
}
}
private IFocusManager FocusManager
{
get { return m_focusManager; }
}
internal IContentFocusManager ContentFocusManager
{
get { return m_focusManager; }
}
internal void SaveFocus()
{
DummyControl.Focus();
}
[Browsable(false)]
public IDockContent ActiveContent
{
get { return FocusManager.ActiveContent; }
}
[Browsable(false)]
public DockPane ActivePane
{
get { return FocusManager.ActivePane; }
}
[Browsable(false)]
public IDockContent ActiveDocument
{
get { return FocusManager.ActiveDocument; }
}
[Browsable(false)]
public DockPane ActiveDocumentPane
{
get { return FocusManager.ActiveDocumentPane; }
}
private static readonly object ActiveDocumentChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActiveDocumentChanged_Description")]
public event EventHandler ActiveDocumentChanged
{
add { Events.AddHandler(ActiveDocumentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveDocumentChangedEvent, value); }
}
protected virtual void OnActiveDocumentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveDocumentChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object ActiveContentChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActiveContentChanged_Description")]
public event EventHandler ActiveContentChanged
{
add { Events.AddHandler(ActiveContentChangedEvent, value); }
remove { Events.RemoveHandler(ActiveContentChangedEvent, value); }
}
protected void OnActiveContentChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActiveContentChangedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object ActivePaneChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("DockPanel_ActivePaneChanged_Description")]
public event EventHandler ActivePaneChanged
{
add { Events.AddHandler(ActivePaneChangedEvent, value); }
remove { Events.RemoveHandler(ActivePaneChangedEvent, value); }
}
protected virtual void OnActivePaneChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[ActivePaneChangedEvent];
if (handler != null)
handler(this, e);
}
}
}
| weimingtom/OtterUI | Tool/WeifenLuo/Src/WinFormsUI/Docking/DockPanel.FocusManager.cs | C# | mit | 20,246 |
require 'active_support/log_subscriber'
module ActionView
# = Action View Log Subscriber
#
# Provides functionality so that Rails can output logs from Action View.
class LogSubscriber < ActiveSupport::LogSubscriber
VIEWS_PATTERN = /^app\/views\//
def initialize
@root = nil
super
end
def render_template(event)
info do
message = " Rendered #{from_rails_root(event.payload[:identifier])}"
message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
message << " (#{event.duration.round(1)}ms)"
end
end
alias :render_partial :render_template
def render_collection(event)
identifier = event.payload[:identifier] || 'templates'
info do
" Rendered collection of #{from_rails_root(identifier)}" \
" #{render_count(event.payload)} (#{event.duration.round(1)}ms)"
end
end
def start(name, id, payload)
if name == "render_template.action_view"
log_rendering_start(payload)
end
super
end
def logger
ActionView::Base.logger
end
protected
EMPTY = ''
def from_rails_root(string)
string = string.sub(rails_root, EMPTY)
string.sub!(VIEWS_PATTERN, EMPTY)
string
end
def rails_root
@root ||= "#{Rails.root}/"
end
def render_count(payload)
if payload[:cache_hits]
"[#{payload[:cache_hits]} / #{payload[:count]} cache hits]"
else
"[#{payload[:count]} times]"
end
end
private
def log_rendering_start(payload)
info do
message = " Rendering #{from_rails_root(payload[:identifier])}"
message << " within #{from_rails_root(payload[:layout])}" if payload[:layout]
message
end
end
end
end
ActionView::LogSubscriber.attach_to :action_view
| yangyang810/ruby-notes | my_site/vendor/bundle/ruby/2.3.0/gems/actionview-5.0.0.1/lib/action_view/log_subscriber.rb | Ruby | mit | 1,865 |
package reporting
import (
"fmt"
"os"
"runtime"
"strings"
)
func init() {
if !isXterm() {
monochrome()
}
if runtime.GOOS == "windows" {
success, failure, error_ = dotSuccess, dotFailure, dotError
}
}
func BuildJsonReporter() Reporter {
out := NewPrinter(NewConsole())
return NewReporters(
NewGoTestReporter(),
NewJsonReporter(out))
}
func BuildDotReporter() Reporter {
out := NewPrinter(NewConsole())
return NewReporters(
NewGoTestReporter(),
NewDotReporter(out),
NewProblemReporter(out),
consoleStatistics)
}
func BuildStoryReporter() Reporter {
out := NewPrinter(NewConsole())
return NewReporters(
NewGoTestReporter(),
NewStoryReporter(out),
NewProblemReporter(out),
consoleStatistics)
}
func BuildSilentReporter() Reporter {
out := NewPrinter(NewConsole())
return NewReporters(
NewGoTestReporter(),
NewSilentProblemReporter(out))
}
var (
newline = "\n"
success = "✔"
failure = "✘"
error_ = "🔥"
skip = "⚠"
dotSuccess = "."
dotFailure = "x"
dotError = "E"
dotSkip = "S"
errorTemplate = "* %s \nLine %d: - %v \n%s\n"
failureTemplate = "* %s \nLine %d:\n%s\n"
)
var (
greenColor = "\033[32m"
yellowColor = "\033[33m"
redColor = "\033[31m"
resetColor = "\033[0m"
)
var consoleStatistics = NewStatisticsReporter(NewPrinter(NewConsole()))
func SuppressConsoleStatistics() { consoleStatistics.Suppress() }
func PrintConsoleStatistics() { consoleStatistics.PrintSummary() }
// QuiteMode disables all console output symbols. This is only meant to be used
// for tests that are internal to goconvey where the output is distracting or
// otherwise not needed in the test output.
func QuietMode() {
success, failure, error_, skip, dotSuccess, dotFailure, dotError, dotSkip = "", "", "", "", "", "", "", ""
}
func monochrome() {
greenColor, yellowColor, redColor, resetColor = "", "", "", ""
}
func isXterm() bool {
env := fmt.Sprintf("%v", os.Environ())
return strings.Contains(env, " TERM=isXterm") ||
strings.Contains(env, " TERM=xterm")
}
// This interface allows us to pass the *testing.T struct
// throughout the internals of this tool without ever
// having to import the "testing" package.
type T interface {
Fail()
}
| golang-devops/yaml-script-runner | vendor/github.com/smartystreets/goconvey/convey/reporting/init.go | GO | mit | 2,281 |
/**
* v1.0.13 generated on: Thu Dec 17 2015 10:48:03 GMT-0600 (CST)
* Copyright (c) 2014-2015, Corey Butler. All Rights Reserved.
*/
"use strict";window.NGN=window.NGN||{},window.NGN.DATA=window.NGN.DATA||{},window.NGN.DATA.Entity=function(e){e=e||{};var t=this;Object.defineProperties(this,{idAttribute:NGN.define(!1,!1,!1,e.idAttribute||"id"),fields:NGN.define(!1,!0,!0,e.fields||{id:{required:!0,type:String,"default":e.id||null}}),virtuals:NGN.define(!1,!0,!0,e.virtuals||{}),validators:NGN.define(!1,!0,!1,{}),validation:NGN.define(!0,!0,!1,NGN.coalesce(e.validation,!0)),isNew:NGN.define(!1,!0,!1,!0),isDestroyed:NGN.define(!1,!0,!1,!1),modified:NGN._get(function(){return this.checksum!==this.benchmark}),oid:NGN.define(!1,!0,!0,e[this.idAttribute]||null),id:{enumerable:!0,get:function(){return this.oid},set:function(e){this.oid=e}},checksum:NGN._get(function(){return NGN.DATA.util.checksum(JSON.stringify(this.data))}),benchmark:NGN.define(!1,!0,!1,null),setUnmodified:NGN.define(!1,!1,!1,function(){this.benchmark=this.checksum,this.changelog=[]}),allowInvalidSave:NGN.define(!1,!0,!1,NGN.coalesce(e.allowInvalidSave,!1)),disableDataValidation:NGN.define(!1,!0,!1,NGN.coalesce(e.disableDataValidation,!1)),invalidDataAttributes:NGN.define(!1,!0,!1,[]),initialDataAttributes:NGN.define(!1,!0,!1,[]),changelog:NGN.define(!1,!0,!1,[]),_nativeValidators:NGN.define(!1,!1,!1,{min:function(e,t){return t instanceof Array?t.length>=e:t instanceof Number?t>=e:t instanceof String?t.trim().length>=e:t instanceof Date?t.parse()>=e.parse():!1},max:function(e,t){return t instanceof Array?t.length<=e:t instanceof Number?e>=t:t instanceof String?t.trim().length<=e:t instanceof Date?t.parse()<=e.parse():!1},"enum":function(e,t){return e.indexOf(t)>=0},required:function(e){return this.hasOwnProperty(e)}}),_dataMap:NGN.define(!0,!0,!1,e.dataMap||null),_reverseDataMap:NGN.define(!0,!0,!1,null),dataMap:{get:function(){return this._dataMap},set:function(e){this._dataMap=e,this._reverseDataMap=null}},reverseMap:NGN._get(function(){if(null!==this.dataMap){if(null!==this._reverseDataMap)return this._reverseDataMap;var e={};return Object.keys(this._dataMap).forEach(function(i){e[t._dataMap[i]]=i}),this._reverseDataMap=e,e}return null}),raw:NGN.define(!1,!0,!1,{}),addValidator:NGN.define(!0,!1,!1,function(e,t){if(!this.hasOwnProperty(e))return void console.warn("No validator could be create for "+e.toUpperCase()+". It is not an attribute of "+this.type.toUpperCase()+".");switch(typeof t){case"function":this.validators[e]=this.validators[e]||[],this.validators[e].push(t),this.emit("validator.add",e);break;case"object":Array.isArray(t)?(this.validators[e]=this.validators[e]||[],this.validators[e].push(function(e){return t.indexOf(e)>=0}),this.emit("validator.add",e)):t.test?(this.validators[e]=this.validators[e]||[],this.validators[e].push(function(e){return t.test(e)}),this.emit("validator.add",e)):console.warn("No validator could be created for "+e.toUpperCase()+". The validator appears to be invalid.");break;case"string":case"number":case"date":this.validators[e]=this.validators[e]||[],this.validators[e].push(function(e){return e===t}),this.emit("validator.add",e);break;default:console.warn("No validator could be create for "+e.toUpperCase()+". The validator appears to be invalid.")}}),removeValidator:NGN.define(!0,!1,!1,function(e){this.validators.hasOwnProperty(e)&&(delete this.validators[e],this.emit("validator.remove",e))}),validate:NGN.define(!0,!1,!1,function(e){var i=!0;if(e&&this.validators.hasOwnProperty(e)){for(r=0;r<this.validators[e].length;r++)if(!t.validators[e][r](t[e]))return t.invalidDataAttributes.indexOf(e)<0&&t.invalidDataAttributes.push(e),!1;return!0}for(var a in this.validators)if(this[a]&&this.validators.hasOwnProperty(a)){for(var n=!0,r=0;r<this.validators[a].length&&(n=this.validators[a][r](this[a]),n);r++);!n&&this.invalidDataAttributes.indexOf(a)<0&&this.invalidDataAttributes.push(a),i&&!n&&(i=!1)}return!0}),valid:NGN._get(function(){return 0===this.invalidDataAttributes.length}),datafields:NGN._get(function(){return Object.keys(this.fields)}),getDataField:NGN.define(!0,!1,!1,function(e){return this.fields[e]}),hasDataField:NGN.define(!0,!1,!1,function(e){return this.fields.hasOwnProperty(e)}),data:NGN._get(function(){var e=this.serialize();return this.dataMap&&Object.keys(this.dataMap).forEach(function(i){e.hasOwnProperty(i)&&(e[t.dataMap[i]]=e[i],delete e[i])}),e}),serialize:NGN.define(!1,!1,!1,function(e){var t=e||this.raw,i={};for(var a in t)if(t.nonEnumerableProperties=t.nonEnumerableProperties||"",this.fields.hasOwnProperty(a)&&(a="id"===a?this.idAttribute:a,t.hasOwnProperty(a)&&t.nonEnumerableProperties.indexOf(a)<0&&/^[a-z0-9 ]$/.test(a.substr(0,1))||void 0!==t[a]&&t.enumerableProperties.indexOf(a)>=0)){var n=Object.getOwnPropertyDescriptor(t,a);if(!n.set)switch(typeof n.value){case"function":"Date"===n.value.name?i[a]=t[a].refs.toJSON():"RegExp"===n.value.name&&(i[a]=n.value());break;case"object":t[a]instanceof Array&&!Array.isArray(t[a])&&(t[a]=t[a].slice(0)),i[a]=t[a];break;default:i[a]=t[a]}}return i}),addField:NGN.define(!0,!1,!1,function(e,i){if(i=void 0!==i?i:!1,"id"!==e.toLowerCase()){if("object"==typeof e){if(!e.name)throw new Error("Cannot create data field. The supplied configuration does not contain a unique data field name.");var a=e;e=a.name,delete a.name}if(void 0!==t[e]&&(console.warn(e+" data field defined multiple times. Only the last defintion will be used."),delete t[e]),t.fields[e]=a||t.fields[e]||{},t.fields[e].required=NGN.coalesce(t.fields[e].required,!1),t.fields[e].type=NGN.coalesce(t.fields[e].type,String),t.fields[e]["default"]=NGN.coalesce(t.fields[e]["default"],null),t.raw[e]=t.fields[e]["default"],t[e]=t.raw[e],Object.defineProperty(t,e,{get:function(){return t.raw[e]},set:function(i){var a=t.raw[e];t.raw[e]=i;var n={action:"update",field:e,old:a,"new":t.raw[e]};this.changelog.push(n),this.emit("field.update",n),t.validate(e)||t.emit("field.invalid",{field:e})}}),!i){var n={action:"create",field:e};this.changelog.push(n),this.emit("field.create",n)}t.fields.hasOwnProperty(e)&&(t.fields[e].hasOwnProperty("pattern")&&t.addValidator(e,t.fields[e].pattern),["min","max","enum"].forEach(function(i){t.fields[e].hasOwnProperty(i)&&t.addValidator(e,function(a){return t._nativeValidators[i](t.fields[e],a)})}),t.fields[e].hasOwnProperty("required")&&t.fields[e].required&&t.addValidator(e,function(e){return t._nativeValidators.required(e)}),t.fields[e].hasOwnProperty("validate")&&("function"==typeof t.fields[e]?t.addValidator(e,function(i){return t.fields[e](i)}):console.warn("Invalid custom validation function. The value passed to the validate attribute must be a function.")))}}),removeField:NGN.define(!0,!1,!1,function(e){if(this.raw.hasOwnProperty(e)){var t=this.raw[e];delete this[e],delete this.fields[e],delete this.raw[e],this.invalidDataAttributes.indexOf(e)>=0&&this.invalidDataAttributes.splice(this.invalidDataAttributes.indexOf(e),1);var i={action:"delete",field:e,value:t};this.emit("field.delete",i),this.changelog.push(i)}}),history:NGN._get(function(){return this.changelog.reverse()}),undo:NGN.define(!0,!1,!1,function(e){e=e||1;var i=this.changelog.splice(this.changelog.length-e,e);i.reverse().forEach(function(e){switch(e.action){case"update":t[e.field]=e.old;break;case"create":t.removeField(e.field);break;case"delete":t.addField(e.field),t[e.field]=t.old}})}),load:NGN.define(!0,!1,!1,function(e){e=e||{},null!==this._dataMap&&Object.keys(this.reverseMap).forEach(function(i){e.hasOwnProperty(i)&&(e[t.reverseMap[i]]=e[i],delete e[i])}),Object.keys(e).forEach(function(i){t.raw.hasOwnProperty(i)?t.raw[i]=e[i]:i===t.idAttribute?t.id=e[i]:console.warn(i+" was specified as a data field but is not defined in the model.")}),this.setUnmodified()})}),this.fields.hasOwnProperty("id")||(e.fields.id={required:!0,type:String,"default":e.id||null}),Object.keys(this.fields).forEach(function(e){t.addField(e,!0)})},window.NGN.DATA.Model=function(e){var t=function(t){this.constructor(e),t&&this.load(t)};return NGN.DATA.util.inherit(NGN.DATA.Entity,t),t},NGN.DATA.util.inherit(NGN.DATA.util.EventEmitter,NGN.DATA.Entity); | perosb/jsdelivr | files/chassis/1.0.13/data.model.min.js | JavaScript | mit | 8,188 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Finder\Shell;
/**
* @author Jean-François Simon <contact@jfsimon.fr>
*/
class Command
{
/**
* @var Command|null
*/
private $parent;
/**
* @var array
*/
private $bits = array();
/**
* @var array
*/
private $labels = array();
/**
* @var \Closure|null
*/
private $errorHandler;
/**
* Constructor.
*
* @param Command|null $parent Parent command
*/
public function __construct(Command $parent = null)
{
$this->parent = $parent;
}
/**
* Returns command as string.
*
* @return string
*/
public function __toString()
{
return $this->join();
}
/**
* Creates a new Command instance.
*
* @param Command|null $parent Parent command
*
* @return Command New Command instance
*/
public static function create(Command $parent = null)
{
return new self($parent);
}
/**
* Escapes special chars from input.
*
* @param string $input A string to escape
*
* @return string The escaped string
*/
public static function escape($input)
{
return escapeshellcmd($input);
}
/**
* Quotes input.
*
* @param string $input An argument string
*
* @return string The quoted string
*/
public static function quote($input)
{
return escapeshellarg($input);
}
/**
* Appends a string or a Command instance.
*
* @param string|Command $bit
*
* @return Command The current Command instance
*/
public function add($bit)
{
$this->bits[] = $bit;
return $this;
}
/**
* Prepends a string or a command instance.
*
* @param string|Command $bit
*
* @return Command The current Command instance
*/
public function top($bit)
{
array_unshift($this->bits, $bit);
foreach ($this->labels as $label => $index) {
$this->labels[$label] += 1;
}
return $this;
}
/**
* Appends an argument, will be quoted.
*
* @param string $arg
*
* @return Command The current Command instance
*/
public function arg($arg)
{
$this->bits[] = self::quote($arg);
return $this;
}
/**
* Appends escaped special command chars.
*
* @param string $esc
*
* @return Command The current Command instance
*/
public function cmd($esc)
{
$this->bits[] = self::escape($esc);
return $this;
}
/**
* Inserts a labeled command to feed later.
*
* @param string $label The unique label
*
* @return Command The current Command instance
*
* @throws \RuntimeException If label already exists
*/
public function ins($label)
{
if (isset($this->labels[$label])) {
throw new \RuntimeException(sprintf('Label "%s" already exists.', $label));
}
$this->bits[] = self::create($this);
$this->labels[$label] = count($this->bits)-1;
return $this->bits[$this->labels[$label]];
}
/**
* Retrieves a previously labeled command.
*
* @param string $label
*
* @return Command The labeled command
*
* @throws \RuntimeException
*/
public function get($label)
{
if (!isset($this->labels[$label])) {
throw new \RuntimeException(sprintf('Label "%s" does not exist.', $label));
}
return $this->bits[$this->labels[$label]];
}
/**
* Returns parent command (if any).
*
* @return Command Parent command
*
* @throws \RuntimeException If command has no parent
*/
public function end()
{
if (null === $this->parent) {
throw new \RuntimeException('Calling end on root command doesn\'t make sense.');
}
return $this->parent;
}
/**
* Counts bits stored in command.
*
* @return int The bits count
*/
public function length()
{
return count($this->bits);
}
/**
* @param \Closure $errorHandler
*
* @return Command
*/
public function setErrorHandler(\Closure $errorHandler)
{
$this->errorHandler = $errorHandler;
return $this;
}
/**
* @return \Closure|null
*/
public function getErrorHandler()
{
return $this->errorHandler;
}
/**
* Executes current command.
*
* @return array The command result
*
* @throws \RuntimeException
*/
public function execute()
{
if (null === $errorHandler = $this->errorHandler) {
exec($this->join(), $output);
} else {
$process = proc_open($this->join(), array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')), $pipes);
$output = preg_split('~(\r\n|\r|\n)~', stream_get_contents($pipes[1]), -1, PREG_SPLIT_NO_EMPTY);
if ($error = stream_get_contents($pipes[2])) {
$errorHandler($error);
}
proc_close($process);
}
return $output ?: array();
}
/**
* Joins bits.
*
* @return string
*/
public function join()
{
return implode(' ', array_filter(
array_map(function ($bit) {
return $bit instanceof Command ? $bit->join() : ($bit ?: null);
}, $this->bits),
function ($bit) { return null !== $bit; }
));
}
/**
* Insert a string or a Command instance before the bit at given position $index (index starts from 0).
*
* @param string|Command $bit
* @param int $index
*
* @return Command The current Command instance
*/
public function addAtIndex($bit, $index)
{
array_splice($this->bits, $index, 0, $bit);
return $this;
}
}
| bfolliot/symfony | src/Symfony/Component/Finder/Shell/Command.php | PHP | mit | 6,290 |
.cm-s-tomorrow-night-eighties.CodeMirror{background:#000;color:#CCC}.cm-s-tomorrow-night-eighties div.CodeMirror-selected{background:#2D2D2D}.cm-s-tomorrow-night-eighties .CodeMirror-line::selection,.cm-s-tomorrow-night-eighties .CodeMirror-line>span::selection,.cm-s-tomorrow-night-eighties .CodeMirror-line>span>span::selection{background:rgba(45,45,45,.99)}.cm-s-tomorrow-night-eighties .CodeMirror-line::-moz-selection,.cm-s-tomorrow-night-eighties .CodeMirror-line>span::-moz-selection,.cm-s-tomorrow-night-eighties .CodeMirror-line>span>span::-moz-selection{background:rgba(45,45,45,.99)}.cm-s-tomorrow-night-eighties .CodeMirror-gutters{background:#000;border-right:0}.cm-s-tomorrow-night-eighties .CodeMirror-guttermarker{color:#f2777a}.cm-s-tomorrow-night-eighties .CodeMirror-guttermarker-subtle{color:#777}.cm-s-tomorrow-night-eighties .CodeMirror-linenumber{color:#515151}.cm-s-tomorrow-night-eighties .CodeMirror-cursor{border-left:1px solid #6A6A6A}.cm-s-tomorrow-night-eighties span.cm-comment{color:#d27b53}.cm-s-tomorrow-night-eighties span.cm-atom,.cm-s-tomorrow-night-eighties span.cm-number{color:#a16a94}.cm-s-tomorrow-night-eighties span.cm-attribute,.cm-s-tomorrow-night-eighties span.cm-property{color:#9c9}.cm-s-tomorrow-night-eighties span.cm-keyword{color:#f2777a}.cm-s-tomorrow-night-eighties span.cm-string{color:#fc6}.cm-s-tomorrow-night-eighties span.cm-variable{color:#9c9}.cm-s-tomorrow-night-eighties span.cm-variable-2{color:#69c}.cm-s-tomorrow-night-eighties span.cm-def{color:#f99157}.cm-s-tomorrow-night-eighties span.cm-bracket{color:#CCC}.cm-s-tomorrow-night-eighties span.cm-tag{color:#f2777a}.cm-s-tomorrow-night-eighties span.cm-link{color:#a16a94}.cm-s-tomorrow-night-eighties span.cm-error{background:#f2777a;color:#6A6A6A}.cm-s-tomorrow-night-eighties .CodeMirror-activeline-background{background:#343600}.cm-s-tomorrow-night-eighties .CodeMirror-matchingbracket{text-decoration:underline;color:#fff!important}/*# sourceMappingURL=tomorrow-night-eighties.min.css.map */ | brix/cdnjs | ajax/libs/codemirror/5.21.0/theme/tomorrow-night-eighties.min.css | CSS | mit | 2,015 |
if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
var B = require('../').Buffer
var test = require('tape')
test('buffer.toJSON', function (t) {
var data = [1, 2, 3, 4]
t.deepEqual(
new B(data).toJSON(),
{ type: 'Buffer', data: [ 1, 2, 3, 4 ] }
)
t.end()
})
test('buffer.copy', function (t) {
// copied from nodejs.org example
var buf1 = new B(26)
var buf2 = new B(26)
for (var i = 0; i < 26; i++) {
buf1[i] = i + 97 // 97 is ASCII a
buf2[i] = 33 // ASCII !
}
buf1.copy(buf2, 8, 16, 20)
t.equal(
buf2.toString('ascii', 0, 25),
'!!!!!!!!qrst!!!!!!!!!!!!!'
)
t.end()
})
test('test offset returns are correct', function (t) {
var b = new B(16)
t.equal(4, b.writeUInt32LE(0, 0))
t.equal(6, b.writeUInt16LE(0, 4))
t.equal(7, b.writeUInt8(0, 6))
t.equal(8, b.writeInt8(0, 7))
t.equal(16, b.writeDoubleLE(0, 8))
t.end()
})
test('concat() a varying number of buffers', function (t) {
var zero = []
var one = [ new B('asdf') ]
var long = []
for (var i = 0; i < 10; i++) {
long.push(new B('asdf'))
}
var flatZero = B.concat(zero)
var flatOne = B.concat(one)
var flatLong = B.concat(long)
var flatLongLen = B.concat(long, 40)
t.equal(flatZero.length, 0)
t.equal(flatOne.toString(), 'asdf')
t.deepEqual(flatOne, one[0])
t.equal(flatLong.toString(), (new Array(10 + 1).join('asdf')))
t.equal(flatLongLen.toString(), (new Array(10 + 1).join('asdf')))
t.end()
})
test('fill', function (t) {
var b = new B(10)
b.fill(2)
t.equal(b.toString('hex'), '02020202020202020202')
t.end()
})
test('fill (string)', function (t) {
var b = new B(10)
b.fill('abc')
t.equal(b.toString(), 'abcabcabca')
b.fill('է')
t.equal(b.toString(), 'էէէէէ')
t.end()
})
test('copy() empty buffer with sourceEnd=0', function (t) {
var source = new B([42])
var destination = new B([43])
source.copy(destination, 0, 0, 0)
t.equal(destination.readUInt8(0), 43)
t.end()
})
test('copy() after slice()', function (t) {
var source = new B(200)
var dest = new B(200)
var expected = new B(200)
for (var i = 0; i < 200; i++) {
source[i] = i
dest[i] = 0
}
source.slice(2).copy(dest)
source.copy(expected, 0, 2)
t.deepEqual(dest, expected)
t.end()
})
test('copy() ascending', function (t) {
var b = new B('abcdefghij')
b.copy(b, 0, 3, 10)
t.equal(b.toString(), 'defghijhij')
t.end()
})
test('copy() descending', function (t) {
var b = new B('abcdefghij')
b.copy(b, 3, 0, 7)
t.equal(b.toString(), 'abcabcdefg')
t.end()
})
test('buffer.slice sets indexes', function (t) {
t.equal((new B('hallo')).slice(0, 5).toString(), 'hallo')
t.end()
})
test('buffer.slice out of range', function (t) {
t.plan(2)
t.equal((new B('hallo')).slice(0, 10).toString(), 'hallo')
t.equal((new B('hallo')).slice(10, 2).toString(), '')
t.end()
})
| functionwell/webpack-demo | node_modules/buffer/test/methods.js | JavaScript | mit | 2,883 |
var conversions = require('./conversions');
/*
this function routes a model to all other models.
all functions that are routed have a property `.conversion` attached
to the returned synthetic function. This property is an array
of strings, each with the steps in between the 'from' and 'to'
color models (inclusive).
conversions that are not possible simply are not included.
*/
// https://jsperf.com/object-keys-vs-for-in-with-closure/3
var models = Object.keys(conversions);
function buildGraph() {
var graph = {};
for (var len = models.length, i = 0; i < len; i++) {
graph[models[i]] = {
// http://jsperf.com/1-vs-infinity
// micro-opt, but this is simple.
distance: -1,
parent: null
};
}
return graph;
}
// https://en.wikipedia.org/wiki/Breadth-first_search
function deriveBFS(fromModel) {
var graph = buildGraph();
var queue = [fromModel]; // unshift -> queue -> pop
graph[fromModel].distance = 0;
while (queue.length) {
var current = queue.pop();
var adjacents = Object.keys(conversions[current]);
for (var len = adjacents.length, i = 0; i < len; i++) {
var adjacent = adjacents[i];
var node = graph[adjacent];
if (node.distance === -1) {
node.distance = graph[current].distance + 1;
node.parent = current;
queue.unshift(adjacent);
}
}
}
return graph;
}
function link(from, to) {
return function (args) {
return to(from(args));
};
}
function wrapConversion(toModel, graph) {
var path = [graph[toModel].parent, toModel];
var fn = conversions[graph[toModel].parent][toModel];
var cur = graph[toModel].parent;
while (graph[cur].parent) {
path.unshift(graph[cur].parent);
fn = link(conversions[graph[cur].parent][cur], fn);
cur = graph[cur].parent;
}
fn.conversion = path;
return fn;
}
module.exports = function (fromModel) {
var graph = deriveBFS(fromModel);
var conversion = {};
var models = Object.keys(graph);
for (var len = models.length, i = 0; i < len; i++) {
var toModel = models[i];
var node = graph[toModel];
if (node.parent === null) {
// no possible conversion, or this node is the source model.
continue;
}
conversion[toModel] = wrapConversion(toModel, graph);
}
return conversion;
};
| verych/dymatrix | node_modules/color-convert/route.js | JavaScript | mit | 2,226 |
/* Modernizr 2.6.2 (Custom Build) | MIT & BSD
* Build: http://modernizr.com/download/#-cssanimations-csstransitions-touch-shiv-cssclasses-prefixed-teststyles-testprop-testallprops-prefixes-domprefixes-load
*/
;window.Modernizr=function(a,b,c){function z(a){j.cssText=a}function A(a,b){return z(m.join(a+";")+(b||""))}function B(a,b){return typeof a===b}function C(a,b){return!!~(""+a).indexOf(b)}function D(a,b){for(var d in a){var e=a[d];if(!C(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function E(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:B(f,"function")?f.bind(d||b):f}return!1}function F(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+o.join(d+" ")+d).split(" ");return B(b,"string")||B(b,"undefined")?D(e,b):(e=(a+" "+p.join(d+" ")+d).split(" "),E(e,b,c))}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n="Webkit Moz O ms",o=n.split(" "),p=n.toLowerCase().split(" "),q={},r={},s={},t=[],u=t.slice,v,w=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["­",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},x={}.hasOwnProperty,y;!B(x,"undefined")&&!B(x.call,"undefined")?y=function(a,b){return x.call(a,b)}:y=function(a,b){return b in a&&B(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=u.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(u.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(u.call(arguments)))};return e}),q.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:w(["@media (",m.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},q.cssanimations=function(){return F("animationName")},q.csstransitions=function(){return F("transition")};for(var G in q)y(q,G)&&(v=G.toLowerCase(),e[v]=q[G](),t.push((e[v]?"":"no-")+v));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)y(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},z(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=m,e._domPrefixes=p,e._cssomPrefixes=o,e.testProp=function(a){return D([a])},e.testAllProps=F,e.testStyles=w,e.prefixed=function(a,b,c){return b?F(a,b,c):F(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+t.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))}; | zbrad/zbrad.github.io | assets/js/vendor/modernizr-2.6.2.custom.min.js | JavaScript | mit | 9,174 |
/* This is a compiled file, you should be editing the file in the templates directory */
.pace {
-webkit-pointer-events: none;
pointer-events: none;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.pace-inactive {
display: none;
}
.pace .pace-progress {
background: #e90f92;
position: fixed;
z-index: 2000;
top: 0;
left: 0;
height: 2px;
}
.pace .pace-progress-inner {
display: block;
position: absolute;
right: 0px;
width: 100px;
height: 100%;
box-shadow: 0 0 10px #e90f92, 0 0 5px #e90f92;
opacity: 1.0;
-webkit-transform: rotate(3deg) translate(0px, -4px);
-moz-transform: rotate(3deg) translate(0px, -4px);
-ms-transform: rotate(3deg) translate(0px, -4px);
-o-transform: rotate(3deg) translate(0px, -4px);
transform: rotate(3deg) translate(0px, -4px);
}
.pace .pace-activity {
display: block;
position: fixed;
z-index: 2000;
top: 15px;
right: 15px;
width: 14px;
height: 14px;
border: solid 2px transparent;
border-top-color: #e90f92;
border-left-color: #e90f92;
border-radius: 10px;
-webkit-animation: pace-spinner 400ms linear infinite;
-moz-animation: pace-spinner 400ms linear infinite;
-ms-animation: pace-spinner 400ms linear infinite;
-o-animation: pace-spinner 400ms linear infinite;
animation: pace-spinner 400ms linear infinite;
}
@-webkit-keyframes pace-spinner {
0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); }
}
@-moz-keyframes pace-spinner {
0% { -moz-transform: rotate(0deg); transform: rotate(0deg); }
100% { -moz-transform: rotate(360deg); transform: rotate(360deg); }
}
@-o-keyframes pace-spinner {
0% { -o-transform: rotate(0deg); transform: rotate(0deg); }
100% { -o-transform: rotate(360deg); transform: rotate(360deg); }
}
@-ms-keyframes pace-spinner {
0% { -ms-transform: rotate(0deg); transform: rotate(0deg); }
100% { -ms-transform: rotate(360deg); transform: rotate(360deg); }
}
@keyframes pace-spinner {
0% { transform: rotate(0deg); transform: rotate(0deg); }
100% { transform: rotate(360deg); transform: rotate(360deg); }
}
| ram-nadella/cdnjs | ajax/libs/pace/0.6.0/themes/pink/pace-theme-flash.css | CSS | mit | 2,172 |
/*!
* Copyright (c) 2015, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var vows = require('vows');
var assert = require('assert');
var tough = require('../lib/cookie');
var Cookie = tough.Cookie;
vows
.describe('Parsing')
.addBatch({
"simple": {
topic: function() {
return Cookie.parse('a=bcd') || null;
},
"parsed": function(c) { assert.ok(c) },
"key": function(c) { assert.equal(c.key, 'a') },
"value": function(c) { assert.equal(c.value, 'bcd') },
"no path": function(c) { assert.equal(c.path, null) },
"no domain": function(c) { assert.equal(c.domain, null) },
"no extensions": function(c) { assert.ok(!c.extensions) }
},
"with expiry": {
topic: function() {
return Cookie.parse('a=bcd; Expires=Tue, 18 Oct 2011 07:05:03 GMT') || null;
},
"parsed": function(c) { assert.ok(c) },
"key": function(c) { assert.equal(c.key, 'a') },
"value": function(c) { assert.equal(c.value, 'bcd') },
"has expires": function(c) {
assert.ok(c.expires !== Infinity, 'expiry is infinite when it shouldn\'t be');
assert.equal(c.expires.getTime(), 1318921503000);
}
},
"with expiry and path": {
topic: function() {
return Cookie.parse('abc="xyzzy!"; Expires=Tue, 18 Oct 2011 07:05:03 GMT; Path=/aBc') || null;
},
"parsed": function(c) { assert.ok(c) },
"key": function(c) { assert.equal(c.key, 'abc') },
"value": function(c) { assert.equal(c.value, '"xyzzy!"') },
"has expires": function(c) {
assert.ok(c.expires !== Infinity, 'expiry is infinite when it shouldn\'t be');
assert.equal(c.expires.getTime(), 1318921503000);
},
"has path": function(c) { assert.equal(c.path, '/aBc'); },
"no httponly or secure": function(c) {
assert.ok(!c.httpOnly);
assert.ok(!c.secure);
}
},
"with everything": {
topic: function() {
return Cookie.parse('abc="xyzzy!"; Expires=Tue, 18 Oct 2011 07:05:03 GMT; Path=/aBc; Domain=example.com; Secure; HTTPOnly; Max-Age=1234; Foo=Bar; Baz') || null;
},
"parsed": function(c) { assert.ok(c) },
"key": function(c) { assert.equal(c.key, 'abc') },
"value": function(c) { assert.equal(c.value, '"xyzzy!"') },
"has expires": function(c) {
assert.ok(c.expires !== Infinity, 'expiry is infinite when it shouldn\'t be');
assert.equal(c.expires.getTime(), 1318921503000);
},
"has path": function(c) { assert.equal(c.path, '/aBc'); },
"has domain": function(c) { assert.equal(c.domain, 'example.com'); },
"has httponly": function(c) { assert.equal(c.httpOnly, true); },
"has secure": function(c) { assert.equal(c.secure, true); },
"has max-age": function(c) { assert.equal(c.maxAge, 1234); },
"has extensions": function(c) {
assert.ok(c.extensions);
assert.equal(c.extensions[0], 'Foo=Bar');
assert.equal(c.extensions[1], 'Baz');
}
},
"invalid expires": function() {
var c = Cookie.parse("a=b; Expires=xyzzy");
assert.ok(c);
assert.equal(c.expires, Infinity);
},
"zero max-age": function() {
var c = Cookie.parse("a=b; Max-Age=0");
assert.ok(c);
assert.equal(c.maxAge, 0);
},
"negative max-age": function() {
var c = Cookie.parse("a=b; Max-Age=-1");
assert.ok(c);
assert.equal(c.maxAge, -1);
},
"empty domain": function() {
var c = Cookie.parse("a=b; domain=");
assert.ok(c);
assert.equal(c.domain, null);
},
"dot domain": function() {
var c = Cookie.parse("a=b; domain=.");
assert.ok(c);
assert.equal(c.domain, null);
},
"uppercase domain": function() {
var c = Cookie.parse("a=b; domain=EXAMPLE.COM");
assert.ok(c);
assert.equal(c.domain, 'example.com');
},
"trailing dot in domain": {
topic: function() {
return Cookie.parse("a=b; Domain=example.com.", true) || null;
},
"has the domain": function(c) { assert.equal(c.domain,"example.com.") },
"but doesn't validate": function(c) { assert.equal(c.validate(),false) }
},
"empty path": function() {
var c = Cookie.parse("a=b; path=");
assert.ok(c);
assert.equal(c.path, null);
},
"no-slash path": function() {
var c = Cookie.parse("a=b; path=xyzzy");
assert.ok(c);
assert.equal(c.path, null);
},
"trailing semi-colons after path": {
topic: function () {
return [
"a=b; path=/;",
"c=d;;;;"
];
},
"strips semi-colons": function (t) {
var c1 = Cookie.parse(t[0]);
var c2 = Cookie.parse(t[1]);
assert.ok(c1);
assert.ok(c2);
assert.equal(c1.path, '/');
}
},
"secure-with-value": function() {
var c = Cookie.parse("a=b; Secure=xyzzy");
assert.ok(c);
assert.equal(c.secure, true);
},
"httponly-with-value": function() {
var c = Cookie.parse("a=b; HttpOnly=xyzzy");
assert.ok(c);
assert.equal(c.httpOnly, true);
},
"garbage": {
topic: function() {
return Cookie.parse("\x08", true) || null;
},
"doesn't parse": function(c) { assert.equal(c,null) }
},
"public suffix domain": {
topic: function() {
return Cookie.parse("a=b; domain=kyoto.jp", true) || null;
},
"parses fine": function(c) {
assert.ok(c);
assert.equal(c.domain, 'kyoto.jp');
},
"but fails validation": function(c) {
assert.ok(c);
assert.ok(!c.validate());
}
},
"public suffix foonet.net": {
"top level": {
topic: function() {
return Cookie.parse("a=b; domain=foonet.net") || null;
},
"parses and is valid": function(c) {
assert.ok(c);
assert.equal(c.domain, 'foonet.net');
assert.ok(c.validate());
}
},
"www": {
topic: function() {
return Cookie.parse("a=b; domain=www.foonet.net") || null;
},
"parses and is valid": function(c) {
assert.ok(c);
assert.equal(c.domain, 'www.foonet.net');
assert.ok(c.validate());
}
},
"with a dot": {
topic: function() {
return Cookie.parse("a=b; domain=.foonet.net") || null;
},
"parses and is valid": function(c) {
assert.ok(c);
assert.equal(c.domain, 'foonet.net');
assert.ok(c.validate());
}
}
},
"Ironically, Google 'GAPS' cookie has very little whitespace": {
topic: function() {
return Cookie.parse("GAPS=1:A1aaaaAaAAa1aaAaAaaAAAaaa1a11a:aaaAaAaAa-aaaA1-;Path=/;Expires=Thu, 17-Apr-2014 02:12:29 GMT;Secure;HttpOnly");
},
"parsed": function(c) { assert.ok(c) },
"key": function(c) { assert.equal(c.key, 'GAPS') },
"value": function(c) { assert.equal(c.value, '1:A1aaaaAaAAa1aaAaAaaAAAaaa1a11a:aaaAaAaAa-aaaA1-') },
"path": function(c) {
assert.notEqual(c.path, '/;Expires'); // BUG
assert.equal(c.path, '/');
},
"expires": function(c) {
assert.notEqual(c.expires, Infinity);
assert.equal(c.expires.getTime(), 1397700749000);
},
"secure": function(c) { assert.ok(c.secure) },
"httponly": function(c) { assert.ok(c.httpOnly) }
},
"lots of equal signs": {
topic: function() {
return Cookie.parse("queryPref=b=c&d=e; Path=/f=g; Expires=Thu, 17 Apr 2014 02:12:29 GMT; HttpOnly");
},
"parsed": function(c) { assert.ok(c) },
"key": function(c) { assert.equal(c.key, 'queryPref') },
"value": function(c) { assert.equal(c.value, 'b=c&d=e') },
"path": function(c) {
assert.equal(c.path, '/f=g');
},
"expires": function(c) {
assert.notEqual(c.expires, Infinity);
assert.equal(c.expires.getTime(), 1397700749000);
},
"httponly": function(c) { assert.ok(c.httpOnly) }
},
"spaces in value": {
topic: function() {
return Cookie.parse('a=one two three',false) || null;
},
"parsed": function(c) { assert.ok(c) },
"key": function(c) { assert.equal(c.key, 'a') },
"value": function(c) { assert.equal(c.value, 'one two three') },
"no path": function(c) { assert.equal(c.path, null) },
"no domain": function(c) { assert.equal(c.domain, null) },
"no extensions": function(c) { assert.ok(!c.extensions) }
},
"quoted spaces in value": {
topic: function() {
return Cookie.parse('a="one two three"',false) || null;
},
"parsed": function(c) { assert.ok(c) },
"key": function(c) { assert.equal(c.key, 'a') },
"value": function(c) { assert.equal(c.value, '"one two three"') },
"no path": function(c) { assert.equal(c.path, null) },
"no domain": function(c) { assert.equal(c.domain, null) },
"no extensions": function(c) { assert.ok(!c.extensions) }
},
"non-ASCII in value": {
topic: function() {
return Cookie.parse('farbe=weiß',false) || null;
},
"parsed": function(c) { assert.ok(c) },
"key": function(c) { assert.equal(c.key, 'farbe') },
"value": function(c) { assert.equal(c.value, 'weiß') },
"no path": function(c) { assert.equal(c.path, null) },
"no domain": function(c) { assert.equal(c.domain, null) },
"no extensions": function(c) { assert.ok(!c.extensions) }
}
})
.export(module);
| mkaminsky11/imgurize | node_modules/request/node_modules/tough-cookie/test/parsing_test.js | JavaScript | mit | 11,108 |
var test = require('tape');
var resolve = require('../');
test('foo', function (t) {
var dir = __dirname + '/resolver';
t.equal(
resolve.sync('./foo', { basedir : dir }),
dir + '/foo.js'
);
t.equal(
resolve.sync('./foo.js', { basedir : dir }),
dir + '/foo.js'
);
t.throws(function () {
resolve.sync('foo', { basedir : dir });
});
t.end();
});
test('bar', function (t) {
var dir = __dirname + '/resolver';
t.equal(
resolve.sync('foo', { basedir : dir + '/bar' }),
dir + '/bar/node_modules/foo/index.js'
);
t.end();
});
test('baz', function (t) {
var dir = __dirname + '/resolver';
t.equal(
resolve.sync('./baz', { basedir : dir }),
dir + '/baz/quux.js'
);
t.end();
});
test('biz', function (t) {
var dir = __dirname + '/resolver/biz/node_modules';
t.equal(
resolve.sync('./grux', { basedir : dir }),
dir + '/grux/index.js'
);
t.equal(
resolve.sync('tiv', { basedir : dir + '/grux' }),
dir + '/tiv/index.js'
);
t.equal(
resolve.sync('grux', { basedir : dir + '/tiv' }),
dir + '/grux/index.js'
);
t.end();
});
test('normalize', function (t) {
var dir = __dirname + '/resolver/biz/node_modules/grux';
t.equal(
resolve.sync('../grux', { basedir : dir }),
dir + '/index.js'
);
t.end();
});
test('cup', function (t) {
var dir = __dirname + '/resolver';
t.equal(
resolve.sync('./cup', {
basedir : dir,
extensions : [ '.js', '.coffee' ]
}),
dir + '/cup.coffee'
);
t.equal(
resolve.sync('./cup.coffee', {
basedir : dir
}),
dir + '/cup.coffee'
);
t.throws(function () {
resolve.sync('./cup', {
basedir : dir,
extensions : [ '.js' ]
})
});
t.end();
});
test('mug', function (t) {
var dir = __dirname + '/resolver';
t.equal(
resolve.sync('./mug', { basedir : dir }),
dir + '/mug.js'
);
t.equal(
resolve.sync('./mug', {
basedir : dir,
extensions : [ '.coffee', '.js' ]
}),
dir + '/mug.coffee'
);
t.equal(
resolve.sync('./mug', {
basedir : dir,
extensions : [ '.js', '.coffee' ]
}),
dir + '/mug.js'
);
t.end();
});
test('other path', function (t) {
var resolverDir = __dirname + '/resolver';
var dir = resolverDir + '/bar';
var otherDir = resolverDir + '/other_path';
var path = require('path');
t.equal(
resolve.sync('root', {
basedir : dir,
paths: [otherDir] }),
resolverDir + '/other_path/root.js'
);
t.equal(
resolve.sync('lib/other-lib', {
basedir : dir,
paths: [otherDir] }),
resolverDir + '/other_path/lib/other-lib.js'
);
t.throws(function () {
resolve.sync('root', { basedir : dir, });
});
t.throws(function () {
resolve.sync('zzz', {
basedir : dir,
paths: [otherDir] });
});
t.end();
});
test('incorrect main', function (t) {
var resolverDir = __dirname + '/resolver';
var dir = resolverDir + '/incorrect_main';
t.equal(
resolve.sync('./incorrect_main', { basedir : resolverDir }),
dir + '/index.js'
)
t.end()
});
test('#25: node modules with the same name as node stdlib modules', function (t) {
var resolverDir = __dirname + '/resolver/punycode';
t.equal(
resolve.sync('punycode', { basedir : resolverDir }),
resolverDir + '/node_modules/punycode/index.js'
)
t.end()
});
| popalexandruvasile/underscorejs-examples | advanced-topics-2/gulp-browserify/node_modules/browserify/node_modules/resolve/test/resolver_sync.js | JavaScript | mit | 3,862 |
'use strict';
var a, group, parser, helptext;
var assert = require('assert');
var _ = require('underscore');
_.str = require('underscore.string');
var print = function () {
return console.log.apply(console, arguments);
};
// print = function () {};
var argparse = require('argparse');
print("TEST argparse.ArgumentDefaultsHelpFormatter");
parser = new argparse.ArgumentParser({
debug: true,
formatterClass: argparse.ArgumentDefaultsHelpFormatter,
description: 'description'
});
parser.addArgument(['--foo'], {
help: 'foo help - oh and by the way, %(defaultValue)s'
});
parser.addArgument(['--bar'], {
action: 'storeTrue',
help: 'bar help'
});
parser.addArgument(['spam'], {
help: 'spam help'
});
parser.addArgument(['badger'], {
nargs: '?',
defaultValue: 'wooden',
help: 'badger help'
});
group = parser.addArgumentGroup({
title: 'title',
description: 'group description'
});
group.addArgument(['--baz'], {
type: 'int',
defaultValue: 42,
help: 'baz help'
});
helptext = parser.formatHelp();
print(helptext);
// test selected clips
assert(helptext.match(/badger help \(default: wooden\)/));
assert(helptext.match(/foo help - oh and by the way, null/));
assert(helptext.match(/bar help \(default: false\)/));
assert(helptext.match(/title:\n {2}group description/)); // test indent
assert(helptext.match(/baz help \(default: 42\)/im));
/*
usage: PROG [-h] [--foo FOO] [--bar] [--baz BAZ] spam [badger]
description
positional arguments:
spam spam help
badger badger help (default: wooden)
optional arguments:
-h, --help show this help message and exit
--foo FOO foo help - oh and by the way, null
--bar bar help (default: false)
title:
group description
--baz BAZ baz help (default: 42)
*/
print("TEST argparse.RawDescriptionHelpFormatter");
parser = new argparse.ArgumentParser({
debug: true,
prog: 'PROG',
formatterClass: argparse.RawDescriptionHelpFormatter,
description: 'Keep the formatting\n' +
' exactly as it is written\n' +
'\n' +
'here\n'
});
a = parser.addArgument(['--foo'], {
help: ' foo help should not\n' +
' retain this odd formatting'
});
parser.addArgument(['spam'], {
'help': 'spam help'
});
group = parser.addArgumentGroup({
title: 'title',
description: ' This text\n' +
' should be indented\n' +
' exactly like it is here\n'
});
group.addArgument(['--bar'], {
help: 'bar help'
});
helptext = parser.formatHelp();
print(helptext);
// test selected clips
assert(helptext.match(parser.description));
assert.equal(helptext.match(a.help), null);
assert(helptext.match(/foo help should not retain this odd formatting/));
/*
class TestHelpRawDescription(HelpTestCase):
"""Test the RawTextHelpFormatter"""
....
usage: PROG [-h] [--foo FOO] [--bar BAR] spam
Keep the formatting
exactly as it is written
here
positional arguments:
spam spam help
optional arguments:
-h, --help show this help message and exit
--foo FOO foo help should not retain this odd formatting
title:
This text
should be indented
exactly like it is here
--bar BAR bar help
*/
print("TEST argparse.RawTextHelpFormatter");
parser = new argparse.ArgumentParser({
debug: true,
prog: 'PROG',
formatterClass: argparse.RawTextHelpFormatter,
description: 'Keep the formatting\n' +
' exactly as it is written\n' +
'\n' +
'here\n'
});
parser.addArgument(['--baz'], {
help: ' baz help should also\n' +
'appear as given here'
});
a = parser.addArgument(['--foo'], {
help: ' foo help should also\n' +
'appear as given here'
});
parser.addArgument(['spam'], {
'help': 'spam help'
});
group = parser.addArgumentGroup({
title: 'title',
description: ' This text\n' +
' should be indented\n' +
' exactly like it is here\n'
});
group.addArgument(['--bar'], {
help: 'bar help'
});
helptext = parser.formatHelp();
print(helptext);
// test selected clips
assert(helptext.match(parser.description));
assert(helptext.match(/( {14})appear as given here/gm));
/*
class TestHelpRawText(HelpTestCase):
"""Test the RawTextHelpFormatter"""
usage: PROG [-h] [--foo FOO] [--bar BAR] spam
Keep the formatting
exactly as it is written
here
positional arguments:
spam spam help
optional arguments:
-h, --help show this help message and exit
--foo FOO foo help should also
appear as given here
title:
This text
should be indented
exactly like it is here
--bar BAR bar help
*/
print("TEST metavar as a tuple");
parser = new argparse.ArgumentParser({
prog: 'PROG'
});
parser.addArgument(['-w'], {
help: 'w',
nargs: '+',
metavar: ['W1', 'W2']
});
parser.addArgument(['-x'], {
help: 'x',
nargs: '*',
metavar: ['X1', 'X2']
});
parser.addArgument(['-y'], {
help: 'y',
nargs: 3,
metavar: ['Y1', 'Y2', 'Y3']
});
parser.addArgument(['-z'], {
help: 'z',
nargs: '?',
metavar: ['Z1']
});
helptext = parser.formatHelp();
print(helptext);
var ustring = 'PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] [-z [Z1]]';
ustring = ustring.replace(/\[/g, '\\[').replace(/\]/g, '\\]');
// print(ustring)
assert(helptext.match(new RegExp(ustring)));
/*
class TestHelpTupleMetavar(HelpTestCase):
"""Test specifying metavar as a tuple"""
usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] [-z [Z1]]
optional arguments:
-h, --help show this help message and exit
-w W1 [W2 ...] w
-x [X1 [X2 ...]] x
-y Y1 Y2 Y3 y
-z [Z1] z
*/
| dorton/tiy-information-kiosk | node_modules/grunt/node_modules/js-yaml/node_modules/argparse/examples/testformatters.js | JavaScript | mit | 5,718 |
Capybara::SpecHelper.spec '#reset_session!' do
it "removes cookies" do
@session.visit('/set_cookie')
@session.visit('/get_cookie')
expect(@session).to have_content('test_cookie')
@session.reset_session!
@session.visit('/get_cookie')
expect(@session.body).not_to include('test_cookie')
end
it "resets current url, host, path" do
@session.visit '/foo'
expect(@session.current_url).not_to be_empty
expect(@session.current_host).not_to be_empty
expect(@session.current_path).to eq('/foo')
@session.reset_session!
expect([nil, '', 'about:blank']).to include(@session.current_url)
expect(['', nil]).to include(@session.current_path)
expect(@session.current_host).to be_nil
end
it "resets page body" do
@session.visit('/with_html')
expect(@session).to have_content('This is a test')
expect(@session.find('.//h1').text).to include('This is a test')
@session.reset_session!
expect(@session.body).not_to include('This is a test')
expect(@session).to have_no_selector('.//h1')
end
it "is synchronous" do
@session.visit("/with_html")
@session.reset_session!
expect(@session).to have_no_selector :xpath, "/html/body/*", wait: false
end
it "raises any errors caught inside the server", :requires => [:server] do
quietly { @session.visit("/error") }
expect do
@session.reset_session!
end.to raise_error(TestApp::TestAppError)
@session.visit("/")
expect(@session.current_path).to eq("/")
end
it "ignores server errors when `Capybara.raise_server_errors = false`", :requires => [:server] do
Capybara.raise_server_errors = false
quietly { @session.visit("/error") }
@session.reset_session!
@session.visit("/")
expect(@session.current_path).to eq("/")
end
end
| carolineartz/Polity | vendor/bundle/gems/capybara-2.4.1/lib/capybara/spec/session/reset_session_spec.rb | Ruby | mit | 1,811 |
//
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//
class ___FILEBASENAME___: AKInstrument {
// Instrument Properties
var pan = AKInstrumentProperty(value: 0.0, minimum: 0.0, maximum: 1.0)
// Auxilliary Outputs (if any)
var auxilliaryOutput = AKAudio()
override init() {
super.init()
// Instrument Properties
// Note Properties
let note = ___FILEBASENAME___Note()
// Instrument Definition
let oscillator = AKFMOscillator();
oscillator.baseFrequency = note.frequency;
oscillator.amplitude = note.amplitude;
let panner = AKPanner(audioSource: oscillator, pan: pan)
auxilliaryOutput = AKAudio.globalParameter()
assignOutput(auxilliaryOutput, to:panner)
}
}
class ___FILEBASENAME___Note: AKNote {
// Note Properties
var frequency = AKNoteProperty(minimum: 440, maximum: 880)
var amplitude = AKNoteProperty(minimum: 0, maximum: 1)
override init() {
super.init()
addProperty(frequency)
addProperty(amplitude)
}
}
| mfk-ableton/MusicKit | Examples/Keyboard/Carthage/Checkouts/AudioKit/Templates/File Templates/AudioKit/Swift AudioKit Instrument.xctemplate/___FILEBASENAME___.swift | Swift | mit | 1,143 |
<?php
namespace Illuminate\Tests\Notifications;
use Mockery;
use PHPUnit\Framework\TestCase;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\SlackMessage;
class NotificationSlackChannelTest extends TestCase
{
public function tearDown()
{
Mockery::close();
}
/**
* @param \Illuminate\Notifications\Notification $notification
* @param array $payload
*/
protected function validatePayload($notification, $payload)
{
$notifiable = new NotificationSlackChannelTestNotifiable;
$channel = new \Illuminate\Notifications\Channels\SlackWebhookChannel(
$http = Mockery::mock('GuzzleHttp\Client')
);
$http->shouldReceive('post')->with('url', $payload);
$channel->send($notifiable, $notification);
}
public function testCorrectPayloadIsSentToSlack()
{
$this->validatePayload(
new NotificationSlackChannelTestNotification,
[
'json' => [
'username' => 'Ghostbot',
'icon_emoji' => ':ghost:',
'channel' => '#ghost-talk',
'text' => 'Content',
'attachments' => [
[
'title' => 'Laravel',
'title_link' => 'https://laravel.com',
'text' => 'Attachment Content',
'fallback' => 'Attachment Fallback',
'fields' => [
[
'title' => 'Project',
'value' => 'Laravel',
'short' => true,
],
],
'mrkdwn_in' => ['text'],
'footer' => 'Laravel',
'footer_icon' => 'https://laravel.com/fake.png',
'ts' => 1234567890,
],
],
],
]
);
}
public function testCorrectPayloadIsSentToSlackWithImageIcon()
{
$this->validatePayload(
new NotificationSlackChannelTestNotificationWithImageIcon,
[
'json' => [
'username' => 'Ghostbot',
'icon_url' => 'http://example.com/image.png',
'channel' => '#ghost-talk',
'text' => 'Content',
'attachments' => [
[
'title' => 'Laravel',
'title_link' => 'https://laravel.com',
'text' => 'Attachment Content',
'fallback' => 'Attachment Fallback',
'fields' => [
[
'title' => 'Project',
'value' => 'Laravel',
'short' => true,
],
],
'mrkdwn_in' => ['text'],
'footer' => 'Laravel',
'footer_icon' => 'https://laravel.com/fake.png',
'ts' => 1234567890,
],
],
],
]
);
}
public function testCorrectPayloadWithoutOptionalFieldsIsSentToSlack()
{
$this->validatePayload(
new NotificationSlackChannelWithoutOptionalFieldsTestNotification,
[
'json' => [
'text' => 'Content',
'attachments' => [
[
'title' => 'Laravel',
'title_link' => 'https://laravel.com',
'text' => 'Attachment Content',
'fields' => [
[
'title' => 'Project',
'value' => 'Laravel',
'short' => true,
],
],
],
],
],
]
);
}
public function testCorrectPayloadWithAttachmentFieldBuilderIsSentToSlack()
{
$this->validatePayload(
new NotificationSlackChannelWithAttachmentFieldBuilderTestNotification,
[
'json' => [
'text' => 'Content',
'attachments' => [
[
'title' => 'Laravel',
'text' => 'Attachment Content',
'title_link' => 'https://laravel.com',
'fields' => [
[
'title' => 'Project',
'value' => 'Laravel',
'short' => true,
],
[
'title' => 'Special powers',
'value' => 'Zonda',
'short' => false,
],
],
],
],
],
]
);
}
}
class NotificationSlackChannelTestNotifiable
{
use \Illuminate\Notifications\Notifiable;
public function routeNotificationForSlack()
{
return 'url';
}
}
class NotificationSlackChannelTestNotification extends Notification
{
public function toSlack($notifiable)
{
return (new SlackMessage)
->from('Ghostbot', ':ghost:')
->to('#ghost-talk')
->content('Content')
->attachment(function ($attachment) {
$timestamp = Mockery::mock('Carbon\Carbon');
$timestamp->shouldReceive('getTimestamp')->andReturn(1234567890);
$attachment->title('Laravel', 'https://laravel.com')
->content('Attachment Content')
->fallback('Attachment Fallback')
->fields([
'Project' => 'Laravel',
])
->footer('Laravel')
->footerIcon('https://laravel.com/fake.png')
->markdown(['text'])
->timestamp($timestamp);
});
}
}
class NotificationSlackChannelTestNotificationWithImageIcon extends Notification
{
public function toSlack($notifiable)
{
return (new SlackMessage)
->from('Ghostbot')
->image('http://example.com/image.png')
->to('#ghost-talk')
->content('Content')
->attachment(function ($attachment) {
$timestamp = Mockery::mock('Carbon\Carbon');
$timestamp->shouldReceive('getTimestamp')->andReturn(1234567890);
$attachment->title('Laravel', 'https://laravel.com')
->content('Attachment Content')
->fallback('Attachment Fallback')
->fields([
'Project' => 'Laravel',
])
->footer('Laravel')
->footerIcon('https://laravel.com/fake.png')
->markdown(['text'])
->timestamp($timestamp);
});
}
}
class NotificationSlackChannelWithoutOptionalFieldsTestNotification extends Notification
{
public function toSlack($notifiable)
{
return (new SlackMessage)
->content('Content')
->attachment(function ($attachment) {
$attachment->title('Laravel', 'https://laravel.com')
->content('Attachment Content')
->fields([
'Project' => 'Laravel',
]);
});
}
}
class NotificationSlackChannelWithAttachmentFieldBuilderTestNotification extends Notification
{
public function toSlack($notifiable)
{
return (new SlackMessage)
->content('Content')
->attachment(function ($attachment) {
$attachment->title('Laravel', 'https://laravel.com')
->content('Attachment Content')
->field('Project', 'Laravel')
->field(function ($attachmentField) {
$attachmentField
->title('Special powers')
->content('Zonda')
->long();
});
});
}
}
| GreenLightt/laravel-framework | tests/Notifications/NotificationSlackChannelTest.php | PHP | mit | 9,492 |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using TestGrainInterfaces;
namespace TestGrains
{
class GeneratedEventReporterGrain : Grain, IGeneratedEventReporterGrain
{
private Logger logger;
private Dictionary<Tuple<string, string>, Dictionary<Guid, int>> reports;
public override Task OnActivateAsync()
{
logger = base.GetLogger("GeneratedEventReporterGrain " + base.IdentityString);
logger.Info("OnActivateAsync");
reports = new Dictionary<Tuple<string, string>, Dictionary<Guid, int>>();
return base.OnActivateAsync();
}
public Task ReportResult(Guid streamGuid, string streamProvider, string streamNamespace, int count)
{
Dictionary<Guid, int> counts;
Tuple<string, string> key = Tuple.Create(streamProvider, streamNamespace);
if (!reports.TryGetValue(key, out counts))
{
counts = new Dictionary<Guid, int>();
reports[key] = counts;
}
logger.Info("ReportResult. StreamProvider: {0}, StreamNamespace: {1}, StreamGuid: {2}, Count: {3}", streamProvider, streamNamespace, streamGuid, count);
counts[streamGuid] = count;
return TaskDone.Done;
}
public Task<IDictionary<Guid, int>> GetReport(string streamProvider, string streamNamespace)
{
Dictionary<Guid, int> counts;
Tuple<string, string> key = Tuple.Create(streamProvider, streamNamespace);
if (!reports.TryGetValue(key, out counts))
{
return Task.FromResult<IDictionary<Guid, int>>(new Dictionary<Guid, int>());
}
return Task.FromResult<IDictionary<Guid, int>>(counts);
}
public Task Reset()
{
reports = new Dictionary<Tuple<string, string>, Dictionary<Guid, int>>();
return TaskDone.Done;
}
public Task<bool> IsLocatedOnSilo(SiloAddress siloAddress)
{
return Task.FromResult(RuntimeIdentity == siloAddress.ToLongString());
}
}
}
| gabikliot/orleans | test/TestGrains/GeneratedEventReporterGrain.cs | C# | mit | 2,212 |
//
// SliderTests.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Xwt
{
public abstract class SliderTests: WidgetTests
{
public override Widget CreateWidget ()
{
return CreateSlider ();
}
public abstract Slider CreateSlider ();
}
public class VSliderTests: SliderTests
{
public override Slider CreateSlider ()
{
return new VSlider ();
}
}
public class HSliderTests: SliderTests
{
public override Slider CreateSlider ()
{
return new HSlider ();
}
}
}
| iainx/xwt | Testing/Tests/SliderTests.cs | C# | mit | 1,642 |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using FluentAssertions;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.DependencyModel.Resolution;
using Xunit;
using F = Microsoft.Extensions.DependencyModel.Tests.TestLibraryFactory;
namespace Microsoft.Extensions.DependencyModel.Tests
{
public class ReferenceAssemblyResolverTests
{
private static string ReferencePath = Path.Combine("reference", "assembly", "directory", "location");
[Fact]
public void SkipsNonReferenceAssembly()
{
var resolver = new ReferenceAssemblyPathResolver();
var library = F.Create(
F.PackageType);
var result = resolver.TryResolveAssemblyPaths(library, null);
result.Should().BeFalse();
}
[Fact]
public void UsesEnvironmentVariableForDefaultPath()
{
var environment = EnvironmentMockBuilder.Create()
.AddVariable("DOTNET_REFERENCE_ASSEMBLIES_PATH", ReferencePath)
.Build();
var result = ReferenceAssemblyPathResolver.GetDefaultReferenceAssembliesPath(FileSystemMockBuilder.Empty, Platform.Windows, environment);
result.Should().Be(ReferencePath);
}
[Fact]
public void LooksOnlyOnEnvironmentVariableOnNonWindows()
{
var result = ReferenceAssemblyPathResolver.GetDefaultReferenceAssembliesPath(FileSystemMockBuilder.Empty, Platform.Linux, EnvironmentMockBuilder.Empty);
result.Should().BeNull();
}
[Fact]
public void ReturnsProgramFiles86AsDefaultLocationOnWin64()
{
var environment = EnvironmentMockBuilder.Create()
.AddVariable("ProgramFiles(x86)", "Program Files (x86)")
.AddVariable("ProgramFiles", "Program Files")
.Build();
var result = ReferenceAssemblyPathResolver.GetDefaultReferenceAssembliesPath(FileSystemMockBuilder.Empty, Platform.Windows, environment);
result.Should().Be(Path.Combine("Program Files (x86)", "Reference Assemblies", "Microsoft", "Framework"));
}
[Fact]
public void ReturnsProgramFilesAsDefaultLocationOnWin32()
{
var environment = EnvironmentMockBuilder.Create()
.AddVariable("ProgramFiles", "Program Files")
.Build();
var result = ReferenceAssemblyPathResolver.GetDefaultReferenceAssembliesPath(FileSystemMockBuilder.Empty, Platform.Windows, environment);
result.Should().Be(Path.Combine("Program Files", "Reference Assemblies", "Microsoft", "Framework"));
}
[Fact]
public void ReturnNet20PathAsFallbackOnWindows()
{
var net20Path = Path.Combine("Windows", "Microsoft.NET", "Framework", "v2.0.50727");
var fileSystem = FileSystemMockBuilder.Create()
.AddFiles(net20Path, "some.dll")
.Build();
var environment = EnvironmentMockBuilder.Create()
.AddVariable("WINDIR", "Windows")
.Build();
var result = ReferenceAssemblyPathResolver.GetFallbackSearchPaths(fileSystem, Platform.Windows, environment);
result.Should().Contain(net20Path);
}
[Fact]
public void ChecksForRelativePathUnderDefaultLocation()
{
var fileSystem = FileSystemMockBuilder.Create()
.AddFiles(ReferencePath, F.DefaultAssemblyPath)
.Build();
var library = F.Create(libraryType: F.ReferenceAssemblyType);
var assemblies = new List<string>();
var resolver = new ReferenceAssemblyPathResolver(fileSystem, ReferencePath, new string[] { });
var result = resolver.TryResolveAssemblyPaths(library, assemblies);
result.Should().BeTrue();
assemblies.Should().Contain(Path.Combine(ReferencePath, F.DefaultAssemblyPath));
}
[Fact]
public void ChecksForFileNameInFallbackLocation()
{
var fileSystem = FileSystemMockBuilder.Create()
.AddFiles(ReferencePath, F.DefaultAssembly)
.Build();
var library = F.Create(libraryType: F.ReferenceAssemblyType);
var assemblies = new List<string>();
var resolver = new ReferenceAssemblyPathResolver(fileSystem, null, new string[] { ReferencePath });
var result = resolver.TryResolveAssemblyPaths(library, assemblies);
result.Should().BeTrue();
assemblies.Should().Contain(Path.Combine(ReferencePath, F.DefaultAssembly));
}
[Fact]
public void ShouldResolveAll()
{
var fileSystem = FileSystemMockBuilder.Create()
.AddFiles(ReferencePath, F.DefaultAssembly)
.Build();
var library = F.Create(libraryType: F.ReferenceAssemblyType, assemblies: F.TwoAssemblies);
var assemblies = new List<string>();
var resolver = new ReferenceAssemblyPathResolver(fileSystem, null, new string[] { ReferencePath });
var exception = Assert.Throws<InvalidOperationException>(() => resolver.TryResolveAssemblyPaths(library, assemblies));
exception.Message.Should()
.Contain(F.SecondAssemblyPath)
.And.Contain(library.Name);
}
}
}
| gkhanna79/core-setup | src/test/Microsoft.Extensions.DependencyModel.Tests/ReferenceAssemblyResolverTests.cs | C# | mit | 5,718 |
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Mapping\Driver;
use Doctrine\Common\Cache\ArrayCache,
Doctrine\Common\Annotations\AnnotationReader,
Doctrine\ORM\Mapping\ClassMetadataInfo,
Doctrine\ORM\Mapping\MappingException;
require __DIR__ . '/DoctrineAnnotations.php';
/**
* The AnnotationDriver reads the mapping metadata from docblock annotations.
*
* @since 2.0
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class AnnotationDriver implements Driver
{
/**
* The AnnotationReader.
*
* @var AnnotationReader
*/
private $_reader;
/**
* The paths where to look for mapping files.
*
* @var array
*/
protected $_paths = array();
/**
* The file extension of mapping documents.
*
* @var string
*/
protected $_fileExtension = '.php';
/**
* @param array
*/
protected $_classNames;
/**
* Initializes a new AnnotationDriver that uses the given AnnotationReader for reading
* docblock annotations.
*
* @param AnnotationReader $reader The AnnotationReader to use, duck-typed.
* @param string|array $paths One or multiple paths where mapping classes can be found.
*/
public function __construct($reader, $paths = null)
{
$this->_reader = $reader;
if ($paths) {
$this->addPaths((array) $paths);
}
}
/**
* Append lookup paths to metadata driver.
*
* @param array $paths
*/
public function addPaths(array $paths)
{
$this->_paths = array_unique(array_merge($this->_paths, $paths));
}
/**
* Retrieve the defined metadata lookup paths.
*
* @return array
*/
public function getPaths()
{
return $this->_paths;
}
/**
* Get the file extension used to look for mapping files under
*
* @return void
*/
public function getFileExtension()
{
return $this->_fileExtension;
}
/**
* Set the file extension used to look for mapping files under
*
* @param string $fileExtension The file extension to set
* @return void
*/
public function setFileExtension($fileExtension)
{
$this->_fileExtension = $fileExtension;
}
/**
* {@inheritdoc}
*/
public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
{
$class = $metadata->getReflectionClass();
$classAnnotations = $this->_reader->getClassAnnotations($class);
// Evaluate Entity annotation
if (isset($classAnnotations['Doctrine\ORM\Mapping\Entity'])) {
$entityAnnot = $classAnnotations['Doctrine\ORM\Mapping\Entity'];
$metadata->setCustomRepositoryClass($entityAnnot->repositoryClass);
} else if (isset($classAnnotations['Doctrine\ORM\Mapping\MappedSuperclass'])) {
$metadata->isMappedSuperclass = true;
} else {
throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className);
}
// Evaluate Table annotation
if (isset($classAnnotations['Doctrine\ORM\Mapping\Table'])) {
$tableAnnot = $classAnnotations['Doctrine\ORM\Mapping\Table'];
$primaryTable = array(
'name' => $tableAnnot->name,
'schema' => $tableAnnot->schema
);
if ($tableAnnot->indexes !== null) {
foreach ($tableAnnot->indexes as $indexAnnot) {
$primaryTable['indexes'][$indexAnnot->name] = array(
'columns' => $indexAnnot->columns
);
}
}
if ($tableAnnot->uniqueConstraints !== null) {
foreach ($tableAnnot->uniqueConstraints as $uniqueConstraint) {
$primaryTable['uniqueConstraints'][$uniqueConstraint->name] = array(
'columns' => $uniqueConstraint->columns
);
}
}
$metadata->setPrimaryTable($primaryTable);
}
// Evaluate InheritanceType annotation
if (isset($classAnnotations['Doctrine\ORM\Mapping\InheritanceType'])) {
$inheritanceTypeAnnot = $classAnnotations['Doctrine\ORM\Mapping\InheritanceType'];
$metadata->setInheritanceType(constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceTypeAnnot->value));
if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) {
// Evaluate DiscriminatorColumn annotation
if (isset($classAnnotations['Doctrine\ORM\Mapping\DiscriminatorColumn'])) {
$discrColumnAnnot = $classAnnotations['Doctrine\ORM\Mapping\DiscriminatorColumn'];
$metadata->setDiscriminatorColumn(array(
'name' => $discrColumnAnnot->name,
'type' => $discrColumnAnnot->type,
'length' => $discrColumnAnnot->length
));
} else {
$metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255));
}
// Evaluate DiscriminatorMap annotation
if (isset($classAnnotations['Doctrine\ORM\Mapping\DiscriminatorMap'])) {
$discrMapAnnot = $classAnnotations['Doctrine\ORM\Mapping\DiscriminatorMap'];
$metadata->setDiscriminatorMap($discrMapAnnot->value);
}
}
}
// Evaluate DoctrineChangeTrackingPolicy annotation
if (isset($classAnnotations['Doctrine\ORM\Mapping\ChangeTrackingPolicy'])) {
$changeTrackingAnnot = $classAnnotations['Doctrine\ORM\Mapping\ChangeTrackingPolicy'];
$metadata->setChangeTrackingPolicy(constant('Doctrine\ORM\Mapping\ClassMetadata::CHANGETRACKING_' . $changeTrackingAnnot->value));
}
// Evaluate annotations on properties/fields
foreach ($class->getProperties() as $property) {
if ($metadata->isMappedSuperclass && ! $property->isPrivate()
||
$metadata->isInheritedField($property->name)
||
$metadata->isInheritedAssociation($property->name)) {
continue;
}
$mapping = array();
$mapping['fieldName'] = $property->getName();
// Check for JoinColummn/JoinColumns annotations
$joinColumns = array();
if ($joinColumnAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\JoinColumn')) {
$joinColumns[] = array(
'name' => $joinColumnAnnot->name,
'referencedColumnName' => $joinColumnAnnot->referencedColumnName,
'unique' => $joinColumnAnnot->unique,
'nullable' => $joinColumnAnnot->nullable,
'onDelete' => $joinColumnAnnot->onDelete,
'onUpdate' => $joinColumnAnnot->onUpdate,
'columnDefinition' => $joinColumnAnnot->columnDefinition,
);
} else if ($joinColumnsAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\JoinColumns')) {
foreach ($joinColumnsAnnot->value as $joinColumn) {
$joinColumns[] = array(
'name' => $joinColumn->name,
'referencedColumnName' => $joinColumn->referencedColumnName,
'unique' => $joinColumn->unique,
'nullable' => $joinColumn->nullable,
'onDelete' => $joinColumn->onDelete,
'onUpdate' => $joinColumn->onUpdate,
'columnDefinition' => $joinColumn->columnDefinition,
);
}
}
// Field can only be annotated with one of:
// @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany
if ($columnAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Column')) {
if ($columnAnnot->type == null) {
throw MappingException::propertyTypeIsRequired($className, $property->getName());
}
$mapping['type'] = $columnAnnot->type;
$mapping['length'] = $columnAnnot->length;
$mapping['precision'] = $columnAnnot->precision;
$mapping['scale'] = $columnAnnot->scale;
$mapping['nullable'] = $columnAnnot->nullable;
$mapping['unique'] = $columnAnnot->unique;
if ($columnAnnot->options) {
$mapping['options'] = $columnAnnot->options;
}
if (isset($columnAnnot->name)) {
$mapping['columnName'] = $columnAnnot->name;
}
if (isset($columnAnnot->columnDefinition)) {
$mapping['columnDefinition'] = $columnAnnot->columnDefinition;
}
if ($idAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Id')) {
$mapping['id'] = true;
}
if ($generatedValueAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\GeneratedValue')) {
$metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy));
}
if ($versionAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Version')) {
$metadata->setVersionMapping($mapping);
}
$metadata->mapField($mapping);
// Check for SequenceGenerator/TableGenerator definition
if ($seqGeneratorAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\SequenceGenerator')) {
$metadata->setSequenceGeneratorDefinition(array(
'sequenceName' => $seqGeneratorAnnot->sequenceName,
'allocationSize' => $seqGeneratorAnnot->allocationSize,
'initialValue' => $seqGeneratorAnnot->initialValue
));
} else if ($tblGeneratorAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\TableGenerator')) {
throw MappingException::tableIdGeneratorNotImplemented($className);
}
} else if ($oneToOneAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\OneToOne')) {
$mapping['targetEntity'] = $oneToOneAnnot->targetEntity;
$mapping['joinColumns'] = $joinColumns;
$mapping['mappedBy'] = $oneToOneAnnot->mappedBy;
$mapping['inversedBy'] = $oneToOneAnnot->inversedBy;
$mapping['cascade'] = $oneToOneAnnot->cascade;
$mapping['orphanRemoval'] = $oneToOneAnnot->orphanRemoval;
$mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $oneToOneAnnot->fetch);
$metadata->mapOneToOne($mapping);
} else if ($oneToManyAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\OneToMany')) {
$mapping['mappedBy'] = $oneToManyAnnot->mappedBy;
$mapping['targetEntity'] = $oneToManyAnnot->targetEntity;
$mapping['cascade'] = $oneToManyAnnot->cascade;
$mapping['orphanRemoval'] = $oneToManyAnnot->orphanRemoval;
$mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $oneToManyAnnot->fetch);
if ($orderByAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\OrderBy')) {
$mapping['orderBy'] = $orderByAnnot->value;
}
$metadata->mapOneToMany($mapping);
} else if ($manyToOneAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\ManyToOne')) {
$mapping['joinColumns'] = $joinColumns;
$mapping['cascade'] = $manyToOneAnnot->cascade;
$mapping['inversedBy'] = $manyToOneAnnot->inversedBy;
$mapping['targetEntity'] = $manyToOneAnnot->targetEntity;
$mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $manyToOneAnnot->fetch);
$metadata->mapManyToOne($mapping);
} else if ($manyToManyAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\ManyToMany')) {
$joinTable = array();
if ($joinTableAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\JoinTable')) {
$joinTable = array(
'name' => $joinTableAnnot->name,
'schema' => $joinTableAnnot->schema
);
foreach ($joinTableAnnot->joinColumns as $joinColumn) {
$joinTable['joinColumns'][] = array(
'name' => $joinColumn->name,
'referencedColumnName' => $joinColumn->referencedColumnName,
'unique' => $joinColumn->unique,
'nullable' => $joinColumn->nullable,
'onDelete' => $joinColumn->onDelete,
'onUpdate' => $joinColumn->onUpdate,
'columnDefinition' => $joinColumn->columnDefinition,
);
}
foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) {
$joinTable['inverseJoinColumns'][] = array(
'name' => $joinColumn->name,
'referencedColumnName' => $joinColumn->referencedColumnName,
'unique' => $joinColumn->unique,
'nullable' => $joinColumn->nullable,
'onDelete' => $joinColumn->onDelete,
'onUpdate' => $joinColumn->onUpdate,
'columnDefinition' => $joinColumn->columnDefinition,
);
}
}
$mapping['joinTable'] = $joinTable;
$mapping['targetEntity'] = $manyToManyAnnot->targetEntity;
$mapping['mappedBy'] = $manyToManyAnnot->mappedBy;
$mapping['inversedBy'] = $manyToManyAnnot->inversedBy;
$mapping['cascade'] = $manyToManyAnnot->cascade;
$mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $manyToManyAnnot->fetch);
if ($orderByAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\OrderBy')) {
$mapping['orderBy'] = $orderByAnnot->value;
}
$metadata->mapManyToMany($mapping);
}
}
// Evaluate @HasLifecycleCallbacks annotation
if (isset($classAnnotations['Doctrine\ORM\Mapping\HasLifecycleCallbacks'])) {
foreach ($class->getMethods() as $method) {
// filter for the declaring class only, callbacks from parents will already be registered.
if ($method->isPublic() && $method->getDeclaringClass()->getName() == $class->name) {
$annotations = $this->_reader->getMethodAnnotations($method);
if (isset($annotations['Doctrine\ORM\Mapping\PrePersist'])) {
$metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::prePersist);
}
if (isset($annotations['Doctrine\ORM\Mapping\PostPersist'])) {
$metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postPersist);
}
if (isset($annotations['Doctrine\ORM\Mapping\PreUpdate'])) {
$metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preUpdate);
}
if (isset($annotations['Doctrine\ORM\Mapping\PostUpdate'])) {
$metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postUpdate);
}
if (isset($annotations['Doctrine\ORM\Mapping\PreRemove'])) {
$metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preRemove);
}
if (isset($annotations['Doctrine\ORM\Mapping\PostRemove'])) {
$metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postRemove);
}
if (isset($annotations['Doctrine\ORM\Mapping\PostLoad'])) {
$metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postLoad);
}
}
}
}
}
/**
* Whether the class with the specified name is transient. Only non-transient
* classes, that is entities and mapped superclasses, should have their metadata loaded.
* A class is non-transient if it is annotated with either @Entity or
* @MappedSuperclass in the class doc block.
*
* @param string $className
* @return boolean
*/
public function isTransient($className)
{
$classAnnotations = $this->_reader->getClassAnnotations(new \ReflectionClass($className));
return ! isset($classAnnotations['Doctrine\ORM\Mapping\Entity']) &&
! isset($classAnnotations['Doctrine\ORM\Mapping\MappedSuperclass']);
}
/**
* {@inheritDoc}
*/
public function getAllClassNames()
{
if ($this->_classNames !== null) {
return $this->_classNames;
}
if (!$this->_paths) {
throw MappingException::pathRequired();
}
$classes = array();
$includedFiles = array();
foreach ($this->_paths as $path) {
if ( ! is_dir($path)) {
throw MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path);
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path),
\RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $file) {
if (($fileName = $file->getBasename($this->_fileExtension)) == $file->getBasename()) {
continue;
}
$sourceFile = realpath($file->getPathName());
require_once $sourceFile;
$includedFiles[] = $sourceFile;
}
}
$declared = get_declared_classes();
foreach ($declared as $className) {
$rc = new \ReflectionClass($className);
$sourceFile = $rc->getFileName();
if (in_array($sourceFile, $includedFiles) && ! $this->isTransient($className)) {
$classes[] = $className;
}
}
$this->_classNames = $classes;
return $classes;
}
/**
* Factory method for the Annotation Driver
*
* @param array|string $paths
* @param AnnotationReader $reader
* @return AnnotationDriver
*/
static public function create($paths = array(), AnnotationReader $reader = null)
{
if ($reader == null) {
$reader = new AnnotationReader();
$reader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\');
}
return new self($reader, $paths);
}
}
| VelvetMirror/login | vendor/doctrine/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php | PHP | mit | 21,125 |
.el-switch{display:-webkit-inline-box;display:-ms-inline-flexbox;display:inline-flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center;position:relative;font-size:14px;line-height:20px;height:20px;vertical-align:middle}.el-switch.is-disabled .el-switch__core,.el-switch.is-disabled .el-switch__label{cursor:not-allowed}.el-switch__core,.el-switch__label{display:inline-block;cursor:pointer;vertical-align:middle}.el-switch__label{-webkit-transition:.2s;transition:.2s;height:20px;font-size:14px;font-weight:500;color:#303133}.el-switch__label.is-active{color:#409EFF}.el-switch__label--left{margin-right:10px}.el-switch__label--right{margin-left:10px}.el-switch__label *{line-height:1;font-size:14px;display:inline-block}.el-switch__input{position:absolute;width:0;height:0;opacity:0;margin:0}.el-switch__core{margin:0;position:relative;width:40px;height:20px;border:1px solid #DCDFE6;outline:0;border-radius:10px;-webkit-box-sizing:border-box;box-sizing:border-box;background:#DCDFE6;-webkit-transition:border-color .3s,background-color .3s;transition:border-color .3s,background-color .3s}.el-switch__core .el-switch__action{position:absolute;top:1px;left:1px;border-radius:100%;-webkit-transition:all .3s;transition:all .3s;width:16px;height:16px;background-color:#FFF;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;color:#DCDFE6}.el-switch.is-checked .el-switch__core{border-color:#409EFF;background-color:#409EFF}.el-switch.is-checked .el-switch__core .el-switch__action{left:100%;margin-left:-17px;color:#409EFF}.el-switch.is-disabled{opacity:.6}.el-switch--wide .el-switch__label.el-switch__label--left span{left:10px}.el-switch--wide .el-switch__label.el-switch__label--right span{right:10px}.el-switch .label-fade-enter-from,.el-switch .label-fade-leave-active{opacity:0} | cdnjs/cdnjs | ajax/libs/element-plus/1.0.2-beta.51/theme-chalk/el-switch.css | CSS | mit | 1,936 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Creation and Modification</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="Chapter 1. Geometry">
<link rel="up" href="../spatial_indexes.html" title="Spatial Indexes">
<link rel="prev" href="rtree_quickstart.html" title="Quick Start">
<link rel="next" href="queries.html" title="Queries">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="rtree_quickstart.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../spatial_indexes.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="queries.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="geometry.spatial_indexes.creation_and_modification"></a><a class="link" href="creation_and_modification.html" title="Creation and Modification">Creation
and Modification</a>
</h3></div></div></div>
<h5>
<a name="geometry.spatial_indexes.creation_and_modification.h0"></a>
<span class="phrase"><a name="geometry.spatial_indexes.creation_and_modification.template_parameters"></a></span><a class="link" href="creation_and_modification.html#geometry.spatial_indexes.creation_and_modification.template_parameters">Template
parameters</a>
</h5>
<p>
R-tree has 5 parameters but only 2 are required:
</p>
<pre class="programlisting"><span class="identifier">rtree</span><span class="special"><</span><span class="identifier">Value</span><span class="special">,</span>
<span class="identifier">Parameters</span><span class="special">,</span>
<span class="identifier">IndexableGetter</span> <span class="special">=</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">indexable</span><span class="special"><</span><span class="identifier">Value</span><span class="special">>,</span>
<span class="identifier">EqualTo</span> <span class="special">=</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">equal_to</span><span class="special"><</span><span class="identifier">Value</span><span class="special">>,</span>
<span class="identifier">Allocator</span> <span class="special">=</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">allocator</span><span class="special"><</span><span class="identifier">Value</span><span class="special">></span> <span class="special">></span>
</pre>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
<code class="computeroutput">Value</code> - type of object which will be stored in the container,
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">Parameters</span></code> - parameters
type, inserting/splitting algorithm,
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">IndexableGetter</span></code> - function
object translating <code class="computeroutput">Value</code> to <code class="computeroutput">Indexable</code> (<code class="computeroutput">Point</code>
or <code class="computeroutput">Box</code>) which R-tree can handle,
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">EqualTo</span></code> - function object
comparing <code class="computeroutput">Value</code>s,
</li>
<li class="listitem">
<code class="computeroutput"><span class="identifier">Allocator</span></code> - <code class="computeroutput"><span class="identifier">Value</span></code>s allocator, all allocators needed
by the container are created from it.
</li>
</ul></div>
<h5>
<a name="geometry.spatial_indexes.creation_and_modification.h1"></a>
<span class="phrase"><a name="geometry.spatial_indexes.creation_and_modification.values_and_indexables"></a></span><a class="link" href="creation_and_modification.html#geometry.spatial_indexes.creation_and_modification.values_and_indexables">Values
and Indexables</a>
</h5>
<p>
R-tree may store <code class="computeroutput">Value</code>s of any type as long as passed function
objects know how to interpret those <code class="computeroutput">Value</code>s, that is extract
an <code class="computeroutput">Indexable</code> that the R-tree can handle and compare <code class="computeroutput">Value</code>s.
The <code class="computeroutput">Indexable</code> is a type adapted to Point, Box or Segment concept.
The examples of rtrees storing <code class="computeroutput">Value</code>s translatable to various
<code class="computeroutput">Indexable</code>s are presented below.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
rtree<Point, ...>
</p>
</th>
<th>
<p>
rtree<Box, ...>
</p>
</th>
<th>
<p>
rtree<Segment, ...>
</p>
</th>
</tr></thead>
<tbody><tr>
<td>
<p>
<span class="inlinemediaobject"><img src="../../img/index/rtree/rtree_pt.png" alt="rtree_pt"></span>
</p>
</td>
<td>
<p>
<span class="inlinemediaobject"><img src="../../img/index/rtree/rstar.png" alt="rstar"></span>
</p>
</td>
<td>
<p>
<span class="inlinemediaobject"><img src="../../img/index/rtree/rtree_seg.png" alt="rtree_seg"></span>
</p>
</td>
</tr></tbody>
</table></div>
<p>
By default function objects <code class="computeroutput"><span class="identifier">index</span><span class="special">::</span><span class="identifier">indexable</span><span class="special"><</span><span class="identifier">Value</span><span class="special">></span></code> and <code class="computeroutput"><span class="identifier">index</span><span class="special">::</span><span class="identifier">equal_to</span><span class="special"><</span><span class="identifier">Value</span><span class="special">></span></code> are defined for some typically used
<code class="computeroutput">Value</code> types which may be stored without defining any additional
classes. By default the rtree may store pure <code class="computeroutput">Indexable</code>s, pairs
and tuples. In the case of those two collection types, the <code class="computeroutput">Indexable</code>
must be the first stored type.
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
<code class="computeroutput">Indexable <span class="special">=</span> Point <span class="special">|</span>
Box <span class="special">|</span> <span class="identifier">Segment</span></code>
</li>
<li class="listitem">
<code class="computeroutput">Value <span class="special">=</span> <span class="identifier">Indexable</span>
<span class="special">|</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span>Indexable<span class="special">,</span>
<span class="identifier">T</span><span class="special">></span>
<span class="special">|</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">tuple</span><span class="special"><</span>Indexable<span class="special">,</span>
<span class="special">...></span> <span class="special">[</span>
<span class="special">|</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">tuple</span><span class="special"><</span>Indexable<span class="special">,</span>
<span class="special">...></span> <span class="special">]</span></code>
</li>
</ul></div>
<p>
By default <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">tuple</span><span class="special"><...></span></code>
is supported on all compilers. If the compiler supports C++11 tuples and
variadic templates then <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">tuple</span><span class="special"><...></span></code> may be used "out of the box"
as well.
</p>
<p>
Examples of default <code class="computeroutput">Value</code> types:
</p>
<pre class="programlisting"><span class="identifier">geometry</span><span class="special">::</span><span class="identifier">model</span><span class="special">::</span><span class="identifier">point</span><span class="special"><...></span>
<span class="identifier">geometry</span><span class="special">::</span><span class="identifier">model</span><span class="special">::</span><span class="identifier">point_xy</span><span class="special"><...></span>
<span class="identifier">geometry</span><span class="special">::</span><span class="identifier">model</span><span class="special">::</span><span class="identifier">box</span><span class="special"><...></span>
<span class="identifier">geometry</span><span class="special">::</span><span class="identifier">model</span><span class="special">::</span><span class="identifier">segment</span><span class="special"><...></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span><span class="identifier">geometry</span><span class="special">::</span><span class="identifier">model</span><span class="special">::</span><span class="identifier">box</span><span class="special"><...>,</span> <span class="keyword">unsigned</span><span class="special">></span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">tuple</span><span class="special"><</span><span class="identifier">geometry</span><span class="special">::</span><span class="identifier">model</span><span class="special">::</span><span class="identifier">point</span><span class="special"><...>,</span> <span class="keyword">int</span><span class="special">,</span> <span class="keyword">float</span><span class="special">></span>
</pre>
<p>
The predefined <code class="computeroutput"><span class="identifier">index</span><span class="special">::</span><span class="identifier">indexable</span><span class="special"><</span><span class="identifier">Value</span><span class="special">></span></code>
returns const reference to the <code class="computeroutput">Indexable</code> stored in the <code class="computeroutput">Value</code>.
</p>
<div class="important"><table border="0" summary="Important">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Important]" src="../../../../../../doc/src/images/important.png"></td>
<th align="left">Important</th>
</tr>
<tr><td align="left" valign="top"><p>
The translation is done quite frequently inside the container - each time
the rtree needs it.
</p></td></tr>
</table></div>
<p>
The predefined <code class="computeroutput"><span class="identifier">index</span><span class="special">::</span><span class="identifier">equal_to</span><span class="special"><</span><span class="identifier">Value</span><span class="special">></span></code>:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
for <code class="computeroutput">Point</code>, <code class="computeroutput">Box</code> and <code class="computeroutput"><span class="identifier">Segment</span></code>
- compares <code class="computeroutput">Value</code>s with geometry::equals().
</li>
<li class="listitem">
for <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><...></span></code>
- compares both components of the <code class="computeroutput">Value</code>. The first value
stored in the pair is compared before the second one. If the value stored
in the pair is a Geometry, <code class="computeroutput"><span class="identifier">geometry</span><span class="special">::</span><span class="identifier">equals</span><span class="special">()</span></code> is used. For other types it uses <code class="computeroutput"><span class="keyword">operator</span><span class="special">==()</span></code>.
</li>
<li class="listitem">
for <code class="computeroutput"><span class="identifier">tuple</span><span class="special"><...></span></code>
- compares all components of the <code class="computeroutput">Value</code>. If the component
is a <code class="computeroutput"><span class="identifier">Geometry</span></code>, <code class="computeroutput"><span class="identifier">geometry</span><span class="special">::</span><span class="identifier">equals</span><span class="special">()</span></code>
function is used. For other types it uses <code class="computeroutput"><span class="keyword">operator</span><span class="special">==()</span></code>.
</li>
</ul></div>
<h5>
<a name="geometry.spatial_indexes.creation_and_modification.h2"></a>
<span class="phrase"><a name="geometry.spatial_indexes.creation_and_modification.balancing_algorithms_compile_time_parameters"></a></span><a class="link" href="creation_and_modification.html#geometry.spatial_indexes.creation_and_modification.balancing_algorithms_compile_time_parameters">Balancing
algorithms compile-time parameters</a>
</h5>
<p>
<code class="computeroutput">Value</code>s may be inserted to the R-tree in many various ways. Final
internal structure of the R-tree depends on algorithms used in the insertion
process and parameters. The most important is nodes' balancing algorithm.
Currently, three well-known types of R-trees may be created.
</p>
<p>
Linear - classic R-tree using balancing algorithm of linear complexity
</p>
<pre class="programlisting"><span class="identifier">index</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span> Value<span class="special">,</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">linear</span><span class="special"><</span><span class="number">16</span><span class="special">></span> <span class="special">></span> <span class="identifier">rt</span><span class="special">;</span>
</pre>
<p>
Quadratic - classic R-tree using balancing algorithm of quadratic complexity
</p>
<pre class="programlisting"><span class="identifier">index</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span> Value<span class="special">,</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">quadratic</span><span class="special"><</span><span class="number">16</span><span class="special">></span> <span class="special">></span> <span class="identifier">rt</span><span class="special">;</span>
</pre>
<p>
R*-tree - balancing algorithm minimizing nodes' overlap with forced reinsertions
</p>
<pre class="programlisting"><span class="identifier">index</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span> Value<span class="special">,</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">rstar</span><span class="special"><</span><span class="number">16</span><span class="special">></span> <span class="special">></span> <span class="identifier">rt</span><span class="special">;</span>
</pre>
<h5>
<a name="geometry.spatial_indexes.creation_and_modification.h3"></a>
<span class="phrase"><a name="geometry.spatial_indexes.creation_and_modification.balancing_algorithms_run_time_parameters"></a></span><a class="link" href="creation_and_modification.html#geometry.spatial_indexes.creation_and_modification.balancing_algorithms_run_time_parameters">Balancing
algorithms run-time parameters</a>
</h5>
<p>
Balancing algorithm parameters may be passed to the R-tree in run-time. To
use run-time versions of the R-tree one may pass parameters which names start
with <code class="computeroutput"><span class="identifier">dynamic_</span></code>.
</p>
<pre class="programlisting"><span class="comment">// linear</span>
<span class="identifier">index</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span>Value<span class="special">,</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">dynamic_linear</span><span class="special">></span> <span class="identifier">rt</span><span class="special">(</span><span class="identifier">index</span><span class="special">::</span><span class="identifier">dynamic_linear</span><span class="special">(</span><span class="number">16</span><span class="special">));</span>
<span class="comment">// quadratic</span>
<span class="identifier">index</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span>Value<span class="special">,</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">dynamic_quadratic</span><span class="special">></span> <span class="identifier">rt</span><span class="special">(</span><span class="identifier">index</span><span class="special">::</span><span class="identifier">dynamic_quadratic</span><span class="special">(</span><span class="number">16</span><span class="special">));</span>
<span class="comment">// rstar</span>
<span class="identifier">index</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span>Value<span class="special">,</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">dynamic_rstar</span><span class="special">></span> <span class="identifier">rt</span><span class="special">(</span><span class="identifier">index</span><span class="special">::</span><span class="identifier">dynamic_rstar</span><span class="special">(</span><span class="number">16</span><span class="special">));</span>
</pre>
<p>
The obvious drawback is a slightly slower R-tree.
</p>
<h5>
<a name="geometry.spatial_indexes.creation_and_modification.h4"></a>
<span class="phrase"><a name="geometry.spatial_indexes.creation_and_modification.non_default_parameters"></a></span><a class="link" href="creation_and_modification.html#geometry.spatial_indexes.creation_and_modification.non_default_parameters">Non-default
parameters</a>
</h5>
<p>
Non-default R-tree parameters are described in the reference.
</p>
<h5>
<a name="geometry.spatial_indexes.creation_and_modification.h5"></a>
<span class="phrase"><a name="geometry.spatial_indexes.creation_and_modification.copying__moving_and_swapping"></a></span><a class="link" href="creation_and_modification.html#geometry.spatial_indexes.creation_and_modification.copying__moving_and_swapping">Copying,
moving and swapping</a>
</h5>
<p>
The R-tree is copyable and movable container. Move semantics is implemented
using Boost.Move library so it's possible to move the container on a compilers
without rvalue references support.
</p>
<pre class="programlisting"><span class="comment">// default constructor</span>
<span class="identifier">index</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span> Value<span class="special">,</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">rstar</span><span class="special"><</span><span class="number">8</span><span class="special">></span> <span class="special">></span> <span class="identifier">rt1</span><span class="special">;</span>
<span class="comment">// copy constructor</span>
<span class="identifier">index</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span> Value<span class="special">,</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">rstar</span><span class="special"><</span><span class="number">8</span><span class="special">></span> <span class="special">></span> <span class="identifier">rt2</span><span class="special">(</span><span class="identifier">r1</span><span class="special">);</span>
<span class="comment">// copy assignment</span>
<span class="identifier">rt2</span> <span class="special">=</span> <span class="identifier">r1</span><span class="special">;</span>
<span class="comment">// move constructor</span>
<span class="identifier">index</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span> Value<span class="special">,</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">rstar</span><span class="special"><</span><span class="number">8</span><span class="special">></span> <span class="special">></span> <span class="identifier">rt3</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">move</span><span class="special">(</span><span class="identifier">rt1</span><span class="special">));</span>
<span class="comment">// move assignment</span>
<span class="identifier">rt3</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">move</span><span class="special">(</span><span class="identifier">rt2</span><span class="special">);</span>
<span class="comment">// swap</span>
<span class="identifier">rt3</span><span class="special">.</span><span class="identifier">swap</span><span class="special">(</span><span class="identifier">rt2</span><span class="special">);</span>
</pre>
<h5>
<a name="geometry.spatial_indexes.creation_and_modification.h6"></a>
<span class="phrase"><a name="geometry.spatial_indexes.creation_and_modification.inserting_and_removing_values"></a></span><a class="link" href="creation_and_modification.html#geometry.spatial_indexes.creation_and_modification.inserting_and_removing_values">Inserting
and removing Values</a>
</h5>
<p>
The following code creates an R-tree using quadratic balancing algorithm.
</p>
<pre class="programlisting"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">geometry</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span><span class="identifier">Box</span><span class="special">,</span> <span class="keyword">int</span><span class="special">></span> Value<span class="special">;</span>
<span class="identifier">index</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span> Value<span class="special">,</span> <span class="identifier">index</span><span class="special">::</span><span class="identifier">quadratic</span><span class="special"><</span><span class="number">16</span><span class="special">></span> <span class="special">></span> <span class="identifier">rt</span><span class="special">;</span>
</pre>
<p>
To insert or remove a `Value' by method call one may use the following code.
</p>
<pre class="programlisting">Value <span class="identifier">v</span> <span class="special">=</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">make_pair</span><span class="special">(</span>Box<span class="special">(...),</span> <span class="number">0</span><span class="special">);</span>
<span class="identifier">rt</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span><span class="identifier">v</span><span class="special">);</span>
<span class="identifier">rt</span><span class="special">.</span><span class="identifier">remove</span><span class="special">(</span><span class="identifier">v</span><span class="special">);</span>
</pre>
<p>
To insert or remove a `Value' by function call one may use the following
code.
</p>
<pre class="programlisting">Value <span class="identifier">v</span> <span class="special">=</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">make_pair</span><span class="special">(</span>Box<span class="special">(...),</span> <span class="number">0</span><span class="special">);</span>
<span class="identifier">index</span><span class="special">::</span><span class="identifier">insert</span><span class="special">(</span><span class="identifier">rt</span><span class="special">,</span> <span class="identifier">v</span><span class="special">);</span>
<span class="identifier">index</span><span class="special">::</span><span class="identifier">remove</span><span class="special">(</span><span class="identifier">rt</span><span class="special">,</span> <span class="identifier">v</span><span class="special">);</span>
</pre>
<p>
Typically you will perform those operations in a loop in order to e.g. insert
some number of <code class="computeroutput">Value</code>s corresponding to geometrical objects (e.g.
<code class="computeroutput"><span class="identifier">Polygons</span></code>) stored in another
container.
</p>
<h5>
<a name="geometry.spatial_indexes.creation_and_modification.h7"></a>
<span class="phrase"><a name="geometry.spatial_indexes.creation_and_modification.additional_interface"></a></span><a class="link" href="creation_and_modification.html#geometry.spatial_indexes.creation_and_modification.additional_interface">Additional
interface</a>
</h5>
<p>
The R-tree allows creation, inserting and removing of Values from a range.
The range may be passed as <code class="computeroutput"><span class="special">[</span><span class="identifier">first</span><span class="special">,</span> <span class="identifier">last</span><span class="special">)</span></code> Iterators
pair or as a Range adapted to one of the Boost.Range Concepts.
</p>
<pre class="programlisting"><span class="keyword">namespace</span> <span class="identifier">bgi</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">geometry</span><span class="special">::</span><span class="identifier">index</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span><span class="identifier">Box</span><span class="special">,</span> <span class="keyword">int</span><span class="special">></span> Value<span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">bgi</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span> Value<span class="special">,</span> <span class="identifier">bgi</span><span class="special">::</span><span class="identifier">linear</span><span class="special"><</span><span class="number">32</span><span class="special">></span> <span class="special">></span> <span class="identifier">RTree</span><span class="special">;</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">vector</span><span class="special"><</span>Value<span class="special">></span> <span class="identifier">values</span><span class="special">;</span>
<span class="comment">/* vector filling code, here */</span>
<span class="comment">// create R-tree with default constructor and insert values with insert(Value const&)</span>
<span class="identifier">RTree</span> <span class="identifier">rt1</span><span class="special">;</span>
<span class="identifier">BOOST_FOREACH</span><span class="special">(</span>Value <span class="keyword">const</span><span class="special">&</span> <span class="identifier">v</span><span class="special">,</span> <span class="identifier">values</span><span class="special">)</span>
<span class="identifier">rt1</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span><span class="identifier">v</span><span class="special">);</span>
<span class="comment">// create R-tree with default constructor and insert values with insert(Iter, Iter)</span>
<span class="identifier">RTree</span> <span class="identifier">rt2</span><span class="special">;</span>
<span class="identifier">rt2</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span><span class="identifier">values</span><span class="special">.</span><span class="identifier">begin</span><span class="special">(),</span> <span class="identifier">values</span><span class="special">.</span><span class="identifier">end</span><span class="special">());</span>
<span class="comment">// create R-tree with default constructor and insert values with insert(Range)</span>
<span class="identifier">RTree</span> <span class="identifier">rt3</span><span class="special">;</span>
<span class="identifier">rt3</span><span class="special">.</span><span class="identifier">insert</span><span class="special">(</span><span class="identifier">values_range</span><span class="special">);</span>
<span class="comment">// create R-tree with constructor taking Iterators</span>
<span class="identifier">RTree</span> <span class="identifier">rt4</span><span class="special">(</span><span class="identifier">values</span><span class="special">.</span><span class="identifier">begin</span><span class="special">(),</span> <span class="identifier">values</span><span class="special">.</span><span class="identifier">end</span><span class="special">());</span>
<span class="comment">// create R-tree with constructor taking Range</span>
<span class="identifier">RTree</span> <span class="identifier">rt5</span><span class="special">(</span><span class="identifier">values_range</span><span class="special">);</span>
<span class="comment">// remove values with remove(Value const&)</span>
<span class="identifier">BOOST_FOREACH</span><span class="special">(</span>Value <span class="keyword">const</span><span class="special">&</span> <span class="identifier">v</span><span class="special">,</span> <span class="identifier">values</span><span class="special">)</span>
<span class="identifier">rt1</span><span class="special">.</span><span class="identifier">remove</span><span class="special">(</span><span class="identifier">v</span><span class="special">);</span>
<span class="comment">// remove values with remove(Iter, Iter)</span>
<span class="identifier">rt2</span><span class="special">.</span><span class="identifier">remove</span><span class="special">(</span><span class="identifier">values</span><span class="special">.</span><span class="identifier">begin</span><span class="special">(),</span> <span class="identifier">values</span><span class="special">.</span><span class="identifier">end</span><span class="special">());</span>
<span class="comment">// remove values with remove(Range)</span>
<span class="identifier">rt3</span><span class="special">.</span><span class="identifier">remove</span><span class="special">(</span><span class="identifier">values_range</span><span class="special">);</span>
</pre>
<p>
Furthermore, it's possible to pass a Range adapted by one of the Boost.Range
adaptors into the rtree (more complete example can be found in the <span class="bold"><strong>Examples</strong></span> section).
</p>
<pre class="programlisting"><span class="comment">// create Rtree containing `std::pair<Box, int>` from a container of Boxes on the fly.</span>
<span class="identifier">RTree</span> <span class="identifier">rt6</span><span class="special">(</span><span class="identifier">boxes</span> <span class="special">|</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">adaptors</span><span class="special">::</span><span class="identifier">indexed</span><span class="special">()</span>
<span class="special">|</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">adaptors</span><span class="special">::</span><span class="identifier">transformed</span><span class="special">(</span><span class="identifier">pair_maker</span><span class="special">()));</span>
</pre>
<h5>
<a name="geometry.spatial_indexes.creation_and_modification.h8"></a>
<span class="phrase"><a name="geometry.spatial_indexes.creation_and_modification.insert_iterator"></a></span><a class="link" href="creation_and_modification.html#geometry.spatial_indexes.creation_and_modification.insert_iterator">Insert
iterator</a>
</h5>
<p>
There are functions like <code class="computeroutput"><span class="identifier">std</span><span class="special">::</span><span class="identifier">copy</span><span class="special">()</span></code>, or R-tree's queries that copy values to
an output iterator. In order to insert values to a container in this kind
of function insert iterators may be used. Geometry.Index provide its own
<code class="computeroutput"><span class="identifier">bgi</span><span class="special">::</span><span class="identifier">insert_iterator</span><span class="special"><</span><span class="identifier">Container</span><span class="special">></span></code>
which is generated by <code class="computeroutput"><span class="identifier">bgi</span><span class="special">::</span><span class="identifier">inserter</span><span class="special">()</span></code> function.
</p>
<pre class="programlisting"><span class="keyword">namespace</span> <span class="identifier">bgi</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">geometry</span><span class="special">::</span><span class="identifier">index</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">pair</span><span class="special"><</span><span class="identifier">Box</span><span class="special">,</span> <span class="keyword">int</span><span class="special">></span> Value<span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">bgi</span><span class="special">::</span><span class="identifier">rtree</span><span class="special"><</span> Value<span class="special">,</span> <span class="identifier">bgi</span><span class="special">::</span><span class="identifier">linear</span><span class="special"><</span><span class="number">32</span><span class="special">></span> <span class="special">></span> <span class="identifier">RTree</span><span class="special">;</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">vector</span><span class="special"><</span>Value<span class="special">></span> <span class="identifier">values</span><span class="special">;</span>
<span class="comment">/* vector filling code, here */</span>
<span class="comment">// create R-tree and insert values from the vector</span>
<span class="identifier">RTree</span> <span class="identifier">rt1</span><span class="special">;</span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">copy</span><span class="special">(</span><span class="identifier">values</span><span class="special">.</span><span class="identifier">begin</span><span class="special">(),</span> <span class="identifier">values</span><span class="special">.</span><span class="identifier">end</span><span class="special">(),</span> <span class="identifier">bgi</span><span class="special">::</span><span class="identifier">inserter</span><span class="special">(</span><span class="identifier">rt1</span><span class="special">));</span>
<span class="comment">// create R-tree and insert values returned by a query</span>
<span class="identifier">RTree</span> <span class="identifier">rt2</span><span class="special">;</span>
<span class="identifier">rt1</span><span class="special">.</span><span class="identifier">spatial_query</span><span class="special">(</span><span class="identifier">Box</span><span class="special">(/*...*/),</span> <span class="identifier">bgi</span><span class="special">::</span><span class="identifier">inserter</span><span class="special">(</span><span class="identifier">rt2</span><span class="special">));</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2009-2015 Barend Gehrels, Bruno Lalande,
Mateusz Loskot, Adam Wulkiewicz, Oracle and/or its affiliates<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="rtree_quickstart.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../spatial_indexes.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="queries.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| Franky666/programmiersprachen-raytracer | external/boost_1_59_0/libs/geometry/doc/html/geometry/spatial_indexes/creation_and_modification.html | HTML | mit | 39,990 |
/*!
* Bootstrap v3.3.5 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*//*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}input{line-height:normal}input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid silver}legend{padding:0;border:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-spacing:0;border-collapse:collapse}td,th{padding:0}/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}blockquote,pre{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #ddd!important}}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff2) format('woff2'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\002a"}.glyphicon-plus:before{content:"\002b"}.glyphicon-eur:before,.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}.glyphicon-cd:before{content:"\e201"}.glyphicon-save-file:before{content:"\e202"}.glyphicon-open-file:before{content:"\e203"}.glyphicon-level-up:before{content:"\e204"}.glyphicon-copy:before{content:"\e205"}.glyphicon-paste:before{content:"\e206"}.glyphicon-alert:before{content:"\e209"}.glyphicon-equalizer:before{content:"\e210"}.glyphicon-king:before{content:"\e211"}.glyphicon-queen:before{content:"\e212"}.glyphicon-pawn:before{content:"\e213"}.glyphicon-bishop:before{content:"\e214"}.glyphicon-knight:before{content:"\e215"}.glyphicon-baby-formula:before{content:"\e216"}.glyphicon-tent:before{content:"\26fa"}.glyphicon-blackboard:before{content:"\e218"}.glyphicon-bed:before{content:"\e219"}.glyphicon-apple:before{content:"\f8ff"}.glyphicon-erase:before{content:"\e221"}.glyphicon-hourglass:before{content:"\231b"}.glyphicon-lamp:before{content:"\e223"}.glyphicon-duplicate:before{content:"\e224"}.glyphicon-piggy-bank:before{content:"\e225"}.glyphicon-scissors:before{content:"\e226"}.glyphicon-bitcoin:before{content:"\e227"}.glyphicon-btc:before{content:"\e227"}.glyphicon-xbt:before{content:"\e227"}.glyphicon-yen:before{content:"\00a5"}.glyphicon-jpy:before{content:"\00a5"}.glyphicon-ruble:before{content:"\20bd"}.glyphicon-rub:before{content:"\20bd"}.glyphicon-scale:before{content:"\e230"}.glyphicon-ice-lolly:before{content:"\e231"}.glyphicon-ice-lolly-tasted:before{content:"\e232"}.glyphicon-education:before{content:"\e233"}.glyphicon-option-horizontal:before{content:"\e234"}.glyphicon-option-vertical:before{content:"\e235"}.glyphicon-menu-hamburger:before{content:"\e236"}.glyphicon-modal-window:before{content:"\e237"}.glyphicon-oil:before{content:"\e238"}.glyphicon-grain:before{content:"\e239"}.glyphicon-sunglasses:before{content:"\e240"}.glyphicon-text-size:before{content:"\e241"}.glyphicon-text-color:before{content:"\e242"}.glyphicon-text-background:before{content:"\e243"}.glyphicon-object-align-top:before{content:"\e244"}.glyphicon-object-align-bottom:before{content:"\e245"}.glyphicon-object-align-horizontal:before{content:"\e246"}.glyphicon-object-align-left:before{content:"\e247"}.glyphicon-object-align-vertical:before{content:"\e248"}.glyphicon-object-align-right:before{content:"\e249"}.glyphicon-triangle-right:before{content:"\e250"}.glyphicon-triangle-left:before{content:"\e251"}.glyphicon-triangle-bottom:before{content:"\e252"}.glyphicon-triangle-top:before{content:"\e253"}.glyphicon-console:before{content:"\e254"}.glyphicon-superscript:before{content:"\e255"}.glyphicon-subscript:before{content:"\e256"}.glyphicon-menu-left:before{content:"\e257"}.glyphicon-menu-right:before{content:"\e258"}.glyphicon-menu-down:before{content:"\e259"}.glyphicon-menu-up:before{content:"\e260"}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:after,:before{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}button,input,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#337ab7;text-decoration:none}a:focus,a:hover{color:#23527c;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.carousel-inner>.item>a>img,.carousel-inner>.item>img,.img-responsive,.thumbnail a>img,.thumbnail>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}[role=button]{cursor:pointer}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-weight:400;line-height:1;color:#777}.h1,.h2,.h3,h1,h2,h3{margin-top:20px;margin-bottom:10px}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small{font-size:65%}.h4,.h5,.h6,h4,h5,h6{margin-top:10px;margin-bottom:10px}.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-size:75%}.h1,h1{font-size:36px}.h2,h2{font-size:30px}.h3,h3{font-size:24px}.h4,h4{font-size:18px}.h5,h5{font-size:14px}.h6,h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}.small,small{font-size:85%}.mark,mark{padding:.2em;background-color:#fcf8e3}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#337ab7}a.text-primary:focus,a.text-primary:hover{color:#286090}.text-success{color:#3c763d}a.text-success:focus,a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:focus,a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:focus,a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:focus,a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#337ab7}a.bg-primary:focus,a.bg-primary:hover{background-color:#286090}.bg-success{background-color:#dff0d8}a.bg-success:focus,a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:focus,a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:focus,a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:focus,a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ol,ul{margin-top:0;margin-bottom:10px}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;margin-left:-5px;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-top:0;margin-bottom:20px}dd,dt{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[data-original-title],abbr[title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote ol:last-child,blockquote p:last-child,blockquote ul:last-child{margin-bottom:0}blockquote .small,blockquote footer,blockquote small{display:block;font-size:80%;line-height:1.42857143;color:#777}blockquote .small:before,blockquote footer:before,blockquote small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;text-align:right;border-right:5px solid #eee;border-left:0}.blockquote-reverse .small:before,.blockquote-reverse footer:before,.blockquote-reverse small:before,blockquote.pull-right .small:before,blockquote.pull-right footer:before,blockquote.pull-right small:before{content:''}.blockquote-reverse .small:after,.blockquote-reverse footer:after,.blockquote-reverse small:after,blockquote.pull-right .small:after,blockquote.pull-right footer:after,blockquote.pull-right small:after{content:'\00A0 \2014'}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;font-weight:700;-webkit-box-shadow:none;box-shadow:none}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{margin-right:-15px;margin-left:-15px}.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:auto}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:auto}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:auto}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:auto}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:auto}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:auto}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{background-color:transparent}caption{padding-top:8px;padding-bottom:8px;color:#777;text-align:left}th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:20px}.table>tbody>tr>td,.table>tbody>tr>th,.table>tfoot>tr>td,.table>tfoot>tr>th,.table>thead>tr>td,.table>thead>tr>th{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>td,.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>td,.table>thead:first-child>tr:first-child>th{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>tbody>tr>td,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>td,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>thead>tr>th{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>tbody>tr>td,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>td,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border:1px solid #ddd}.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border-bottom-width:2px}.table-striped>tbody>tr:nth-of-type(odd){background-color:#f9f9f9}.table-hover>tbody>tr:hover{background-color:#f5f5f5}table col[class*=col-]{position:static;display:table-column;float:none}table td[class*=col-],table th[class*=col-]{position:static;display:table-cell;float:none}.table>tbody>tr.active>td,.table>tbody>tr.active>th,.table>tbody>tr>td.active,.table>tbody>tr>th.active,.table>tfoot>tr.active>td,.table>tfoot>tr.active>th,.table>tfoot>tr>td.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>thead>tr.active>th,.table>thead>tr>td.active,.table>thead>tr>th.active{background-color:#f5f5f5}.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover{background-color:#e8e8e8}.table>tbody>tr.success>td,.table>tbody>tr.success>th,.table>tbody>tr>td.success,.table>tbody>tr>th.success,.table>tfoot>tr.success>td,.table>tfoot>tr.success>th,.table>tfoot>tr>td.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>thead>tr.success>th,.table>thead>tr>td.success,.table>thead>tr>th.success{background-color:#dff0d8}.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover{background-color:#d0e9c6}.table>tbody>tr.info>td,.table>tbody>tr.info>th,.table>tbody>tr>td.info,.table>tbody>tr>th.info,.table>tfoot>tr.info>td,.table>tfoot>tr.info>th,.table>tfoot>tr>td.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>thead>tr.info>th,.table>thead>tr>td.info,.table>thead>tr>th.info{background-color:#d9edf7}.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover{background-color:#c4e3f3}.table>tbody>tr.warning>td,.table>tbody>tr.warning>th,.table>tbody>tr>td.warning,.table>tbody>tr>th.warning,.table>tfoot>tr.warning>td,.table>tfoot>tr.warning>th,.table>tfoot>tr>td.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>thead>tr.warning>th,.table>thead>tr>td.warning,.table>thead>tr>th.warning{background-color:#fcf8e3}.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover{background-color:#faf2cc}.table>tbody>tr.danger>td,.table>tbody>tr.danger>th,.table>tbody>tr>td.danger,.table>tbody>tr>th.danger,.table>tfoot>tr.danger>td,.table>tfoot>tr.danger>th,.table>tfoot>tr>td.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>thead>tr.danger>th,.table>thead>tr>td.danger,.table>thead>tr>th.danger{background-color:#f2dede}.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover{background-color:#ebcccc}.table-responsive{min-height:.01%;overflow-x:auto}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>td,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>thead>tr>th{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=checkbox],input[type=radio]{margin:4px 0 0;margin-top:1px\9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=checkbox]:focus,input[type=radio]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control::-ms-expand{background-color:transparent;border:0}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{background-color:#eee;opacity:1}.form-control[disabled],fieldset[disabled] .form-control{cursor:not-allowed}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}@media screen and (-webkit-min-device-pixel-ratio:0){input[type=date].form-control,input[type=time].form-control,input[type=datetime-local].form-control,input[type=month].form-control{line-height:34px}.input-group-sm input[type=date],.input-group-sm input[type=time],.input-group-sm input[type=datetime-local],.input-group-sm input[type=month],input[type=date].input-sm,input[type=time].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm{line-height:30px}.input-group-lg input[type=date],.input-group-lg input[type=time],.input-group-lg input[type=datetime-local],.input-group-lg input[type=month],input[type=date].input-lg,input[type=time].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg{line-height:46px}}.form-group{margin-bottom:15px}.checkbox,.radio{position:relative;display:block;margin-top:10px;margin-bottom:10px}.checkbox label,.radio label{min-height:20px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox],.radio input[type=radio],.radio-inline input[type=radio]{position:absolute;margin-top:4px\9;margin-left:-20px}.checkbox+.checkbox,.radio+.radio{margin-top:-5px}.checkbox-inline,.radio-inline{position:relative;display:inline-block;padding-left:20px;margin-bottom:0;font-weight:400;vertical-align:middle;cursor:pointer}.checkbox-inline+.checkbox-inline,.radio-inline+.radio-inline{margin-top:0;margin-left:10px}fieldset[disabled] input[type=checkbox],fieldset[disabled] input[type=radio],input[type=checkbox].disabled,input[type=checkbox][disabled],input[type=radio].disabled,input[type=radio][disabled]{cursor:not-allowed}.checkbox-inline.disabled,.radio-inline.disabled,fieldset[disabled] .checkbox-inline,fieldset[disabled] .radio-inline{cursor:not-allowed}.checkbox.disabled label,.radio.disabled label,fieldset[disabled] .checkbox label,fieldset[disabled] .radio label{cursor:not-allowed}.form-control-static{min-height:34px;padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-control-static.input-sm{padding-right:0;padding-left:0}.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}select[multiple].input-sm,textarea.input-sm{height:auto}.form-group-sm .form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.form-group-sm select.form-control{height:30px;line-height:30px}.form-group-sm select[multiple].form-control,.form-group-sm textarea.form-control{height:auto}.form-group-sm .form-control-static{height:30px;min-height:32px;padding:6px 10px;font-size:12px;line-height:1.5}.input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-lg{height:46px;line-height:46px}select[multiple].input-lg,textarea.input-lg{height:auto}.form-group-lg .form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.form-group-lg select.form-control{height:46px;line-height:46px}.form-group-lg select[multiple].form-control,.form-group-lg textarea.form-control{height:auto}.form-group-lg .form-control-static{height:46px;min-height:38px;padding:11px 16px;font-size:18px;line-height:1.3333333}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center;pointer-events:none}.form-group-lg .form-control+.form-control-feedback,.input-group-lg+.form-control-feedback,.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.form-group-sm .form-control+.form-control-feedback,.input-group-sm+.form-control-feedback,.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .checkbox,.has-success .checkbox-inline,.has-success .control-label,.has-success .help-block,.has-success .radio,.has-success .radio-inline,.has-success.checkbox label,.has-success.checkbox-inline label,.has-success.radio label,.has-success.radio-inline label{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;background-color:#dff0d8;border-color:#3c763d}.has-success .form-control-feedback{color:#3c763d}.has-warning .checkbox,.has-warning .checkbox-inline,.has-warning .control-label,.has-warning .help-block,.has-warning .radio,.has-warning .radio-inline,.has-warning.checkbox label,.has-warning.checkbox-inline label,.has-warning.radio label,.has-warning.radio-inline label{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;background-color:#fcf8e3;border-color:#8a6d3b}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .checkbox,.has-error .checkbox-inline,.has-error .control-label,.has-error .help-block,.has-error .radio,.has-error .radio-inline,.has-error.checkbox label,.has-error.checkbox-inline label,.has-error.radio label,.has-error.radio-inline label{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;background-color:#f2dede;border-color:#a94442}.has-error .form-control-feedback{color:#a94442}.has-feedback label~.form-control-feedback{top:25px}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-static{display:inline-block}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .form-control,.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .checkbox,.form-inline .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .checkbox label,.form-inline .radio label{padding-left:0}.form-inline .checkbox input[type=checkbox],.form-inline .radio input[type=radio]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .checkbox,.form-horizontal .checkbox-inline,.form-horizontal .radio,.form-horizontal .radio-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .checkbox,.form-horizontal .radio{min-height:27px}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.form-horizontal .control-label{padding-top:7px;margin-bottom:0;text-align:right}}.form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:11px;font-size:18px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px;font-size:12px}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.btn.active.focus,.btn.active:focus,.btn.focus,.btn:active.focus,.btn:active:focus,.btn:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.focus,.btn:focus,.btn:hover{color:#333;text-decoration:none}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none;opacity:.65}a.btn.disabled,fieldset[disabled] a.btn{pointer-events:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default.focus,.btn-default:focus{color:#333;background-color:#e6e6e6;border-color:#8c8c8c}.btn-default:hover{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default.active.focus,.btn-default.active:focus,.btn-default.active:hover,.btn-default:active.focus,.btn-default:active:focus,.btn-default:active:hover,.open>.dropdown-toggle.btn-default.focus,.open>.dropdown-toggle.btn-default:focus,.open>.dropdown-toggle.btn-default:hover{color:#333;background-color:#d4d4d4;border-color:#8c8c8c}.btn-default.active,.btn-default:active,.open>.dropdown-toggle.btn-default{background-image:none}.btn-default.disabled.focus,.btn-default.disabled:focus,.btn-default.disabled:hover,.btn-default[disabled].focus,.btn-default[disabled]:focus,.btn-default[disabled]:hover,fieldset[disabled] .btn-default.focus,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:hover{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#337ab7;border-color:#2e6da4}.btn-primary.focus,.btn-primary:focus{color:#fff;background-color:#286090;border-color:#122b40}.btn-primary:hover{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{color:#fff;background-color:#286090;border-color:#204d74}.btn-primary.active.focus,.btn-primary.active:focus,.btn-primary.active:hover,.btn-primary:active.focus,.btn-primary:active:focus,.btn-primary:active:hover,.open>.dropdown-toggle.btn-primary.focus,.open>.dropdown-toggle.btn-primary:focus,.open>.dropdown-toggle.btn-primary:hover{color:#fff;background-color:#204d74;border-color:#122b40}.btn-primary.active,.btn-primary:active,.open>.dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled.focus,.btn-primary.disabled:focus,.btn-primary.disabled:hover,.btn-primary[disabled].focus,.btn-primary[disabled]:focus,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary.focus,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:hover{background-color:#337ab7;border-color:#2e6da4}.btn-primary .badge{color:#337ab7;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success.focus,.btn-success:focus{color:#fff;background-color:#449d44;border-color:#255625}.btn-success:hover{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{color:#fff;background-color:#449d44;border-color:#398439}.btn-success.active.focus,.btn-success.active:focus,.btn-success.active:hover,.btn-success:active.focus,.btn-success:active:focus,.btn-success:active:hover,.open>.dropdown-toggle.btn-success.focus,.open>.dropdown-toggle.btn-success:focus,.open>.dropdown-toggle.btn-success:hover{color:#fff;background-color:#398439;border-color:#255625}.btn-success.active,.btn-success:active,.open>.dropdown-toggle.btn-success{background-image:none}.btn-success.disabled.focus,.btn-success.disabled:focus,.btn-success.disabled:hover,.btn-success[disabled].focus,.btn-success[disabled]:focus,.btn-success[disabled]:hover,fieldset[disabled] .btn-success.focus,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:hover{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info.focus,.btn-info:focus{color:#fff;background-color:#31b0d5;border-color:#1b6d85}.btn-info:hover{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info.active.focus,.btn-info.active:focus,.btn-info.active:hover,.btn-info:active.focus,.btn-info:active:focus,.btn-info:active:hover,.open>.dropdown-toggle.btn-info.focus,.open>.dropdown-toggle.btn-info:focus,.open>.dropdown-toggle.btn-info:hover{color:#fff;background-color:#269abc;border-color:#1b6d85}.btn-info.active,.btn-info:active,.open>.dropdown-toggle.btn-info{background-image:none}.btn-info.disabled.focus,.btn-info.disabled:focus,.btn-info.disabled:hover,.btn-info[disabled].focus,.btn-info[disabled]:focus,.btn-info[disabled]:hover,fieldset[disabled] .btn-info.focus,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:hover{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning.focus,.btn-warning:focus{color:#fff;background-color:#ec971f;border-color:#985f0d}.btn-warning:hover{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning.active.focus,.btn-warning.active:focus,.btn-warning.active:hover,.btn-warning:active.focus,.btn-warning:active:focus,.btn-warning:active:hover,.open>.dropdown-toggle.btn-warning.focus,.open>.dropdown-toggle.btn-warning:focus,.open>.dropdown-toggle.btn-warning:hover{color:#fff;background-color:#d58512;border-color:#985f0d}.btn-warning.active,.btn-warning:active,.open>.dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled.focus,.btn-warning.disabled:focus,.btn-warning.disabled:hover,.btn-warning[disabled].focus,.btn-warning[disabled]:focus,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning.focus,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:hover{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger.focus,.btn-danger:focus{color:#fff;background-color:#c9302c;border-color:#761c19}.btn-danger:hover{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger.active.focus,.btn-danger.active:focus,.btn-danger.active:hover,.btn-danger:active.focus,.btn-danger:active:focus,.btn-danger:active:hover,.open>.dropdown-toggle.btn-danger.focus,.open>.dropdown-toggle.btn-danger:focus,.open>.dropdown-toggle.btn-danger:hover{color:#fff;background-color:#ac2925;border-color:#761c19}.btn-danger.active,.btn-danger:active,.open>.dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled.focus,.btn-danger.disabled:focus,.btn-danger.disabled:hover,.btn-danger[disabled].focus,.btn-danger[disabled]:focus,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger.focus,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:hover{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{font-weight:400;color:#337ab7;border-radius:0}.btn-link,.btn-link.active,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:active,.btn-link:focus,.btn-link:hover{border-color:transparent}.btn-link:focus,.btn-link:hover{color:#23527c;text-decoration:underline;background-color:transparent}.btn-link[disabled]:focus,.btn-link[disabled]:hover,fieldset[disabled] .btn-link:focus,fieldset[disabled] .btn-link:hover{color:#777;text-decoration:none}.btn-group-lg>.btn,.btn-lg{padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}.btn-group-sm>.btn,.btn-sm{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-xs>.btn,.btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-timing-function:ease;-o-transition-timing-function:ease;transition-timing-function:ease;-webkit-transition-duration:.35s;-o-transition-duration:.35s;transition-duration:.35s;-webkit-transition-property:height,visibility;-o-transition-property:height,visibility;transition-property:height,visibility}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px dashed;border-top:4px solid\9;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown,.dropup{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:focus,.dropdown-menu>li>a:hover{color:#262626;text-decoration:none;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:focus,.dropdown-menu>.active>a:hover{color:#fff;text-decoration:none;background-color:#337ab7;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{color:#777}.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{right:0;left:auto}.dropdown-menu-left{right:auto;left:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{content:"";border-top:0;border-bottom:4px dashed;border-bottom:4px solid\9}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:2px}@media (min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}.navbar-right .dropdown-menu-left{right:auto;left:0}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;float:left}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group-vertical>.btn:hover,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus,.btn-group>.btn:hover{z-index:2}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn,.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-bottom-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-left-radius:0;border-top-right-radius:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-top-right-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{display:table-cell;float:none;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn input[type=checkbox],[data-toggle=buttons]>.btn input[type=radio],[data-toggle=buttons]>.btn-group>.btn input[type=checkbox],[data-toggle=buttons]>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-right:0;padding-left:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.3333333;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn,textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn,textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn{height:auto}.input-group .form-control,.input-group-addon,.input-group-btn{display:table-cell}.input-group .form-control:not(:first-child):not(:last-child),.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=checkbox],.input-group-addon input[type=radio]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn-group:not(:last-child)>.btn,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:first-child>.btn-group:not(:first-child)>.btn,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:active,.input-group-btn>.btn:focus,.input-group-btn>.btn:hover{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{z-index:2;margin-left:-1px}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:focus,.nav>li>a:hover{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:focus,.nav>li.disabled>a:hover{color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:focus,.nav .open>a:hover{background-color:#eee;border-color:#337ab7}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:focus,.nav-tabs>li.active>a:hover{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:focus,.nav-pills>li.active>a:hover{color:#fff;background-color:#337ab7}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse{padding-right:0;padding-left:0}}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:340px}@media (max-device-width:480px) and (orientation:landscape){.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:200px}}.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-bottom,.navbar-fixed-top{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-bottom,.navbar-fixed-top{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-nav .open .dropdown-menu .dropdown-header,.navbar-nav .open .dropdown-menu>li>a{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:focus,.navbar-nav .open .dropdown-menu>li>a:hover{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .form-control-static{display:inline-block}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .form-control,.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .checkbox,.navbar-form .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .checkbox label,.navbar-form .radio label{padding-left:0}.navbar-form .checkbox input[type=checkbox],.navbar-form .radio input[type=radio]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}.navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-left-radius:0;border-top-right-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{margin-bottom:0;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-right:15px;margin-left:15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important;margin-right:-15px}.navbar-right~.navbar-right{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:focus,.navbar-default .navbar-brand:hover{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:focus,.navbar-default .navbar-nav>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:focus,.navbar-default .navbar-nav>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:focus,.navbar-default .navbar-nav>.disabled>a:hover{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:focus,.navbar-default .navbar-toggle:hover{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:focus,.navbar-default .navbar-nav>.open>a:hover{color:#555;background-color:#e7e7e7}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:focus,.navbar-default .btn-link:hover{color:#333}.navbar-default .btn-link[disabled]:focus,.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:focus,fieldset[disabled] .navbar-default .btn-link:hover{color:#ccc}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#9d9d9d}.navbar-inverse .navbar-brand:focus,.navbar-inverse .navbar-brand:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a:focus,.navbar-inverse .navbar-nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:focus,.navbar-inverse .navbar-nav>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:focus,.navbar-inverse .navbar-nav>.disabled>a:hover{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:focus,.navbar-inverse .navbar-toggle:hover{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:focus,.navbar-inverse .navbar-nav>.open>a:hover{color:#fff;background-color:#080808}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#9d9d9d}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#9d9d9d}.navbar-inverse .btn-link:focus,.navbar-inverse .btn-link:hover{color:#fff}.navbar-inverse .btn-link[disabled]:focus,.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:focus,fieldset[disabled] .navbar-inverse .btn-link:hover{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.42857143;color:#337ab7;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-top-left-radius:4px;border-bottom-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:focus,.pagination>li>a:hover,.pagination>li>span:focus,.pagination>li>span:hover{z-index:2;color:#23527c;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:focus,.pagination>.active>a:hover,.pagination>.active>span,.pagination>.active>span:focus,.pagination>.active>span:hover{z-index:3;color:#fff;cursor:default;background-color:#337ab7;border-color:#337ab7}.pagination>.disabled>a,.pagination>.disabled>a:focus,.pagination>.disabled>a:hover,.pagination>.disabled>span,.pagination>.disabled>span:focus,.pagination>.disabled>span:hover{color:#777;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px;line-height:1.3333333}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-top-left-radius:6px;border-bottom-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px;line-height:1.5}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-top-left-radius:3px;border-bottom-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:focus,.pager li>a:hover{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:focus,.pager .disabled>a:hover,.pager .disabled>span{color:#777;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}a.label:focus,a.label:hover{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#777}.label-default[href]:focus,.label-default[href]:hover{background-color:#5e5e5e}.label-primary{background-color:#337ab7}.label-primary[href]:focus,.label-primary[href]:hover{background-color:#286090}.label-success{background-color:#5cb85c}.label-success[href]:focus,.label-success[href]:hover{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:focus,.label-info[href]:hover{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:focus,.label-warning[href]:hover{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:focus,.label-danger[href]:hover{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:middle;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-group-xs>.btn .badge,.btn-xs .badge{top:0;padding:1px 5px}a.badge:focus,a.badge:hover{color:#fff;text-decoration:none;cursor:pointer}.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#337ab7;background-color:#fff}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding-top:30px;padding-bottom:30px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron .h1,.jumbotron h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container .jumbotron,.container-fluid .jumbotron{padding-right:15px;padding-left:15px;border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron,.container-fluid .jumbotron{padding-right:60px;padding-left:60px}.jumbotron .h1,.jumbotron h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;-o-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.thumbnail a>img,.thumbnail>img{margin-right:auto;margin-left:auto}a.thumbnail.active,a.thumbnail:focus,a.thumbnail:hover{border-color:#337ab7}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#337ab7;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress-bar-striped,.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;background-size:40px 40px}.progress-bar.active,.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media{margin-top:15px}.media:first-child{margin-top:0}.media,.media-body{overflow:hidden;zoom:1}.media-body{width:10000px}.media-object{display:block}.media-object.img-thumbnail{max-width:none}.media-right,.media>.pull-right{padding-left:10px}.media-left,.media>.pull-left{padding-right:10px}.media-body,.media-left,.media-right{display:table-cell;vertical-align:top}.media-middle{vertical-align:middle}.media-bottom{vertical-align:bottom}.media-heading{margin-top:0;margin-bottom:5px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}a.list-group-item,button.list-group-item{color:#555}a.list-group-item .list-group-item-heading,button.list-group-item .list-group-item-heading{color:#333}a.list-group-item:focus,a.list-group-item:hover,button.list-group-item:focus,button.list-group-item:hover{color:#555;text-decoration:none;background-color:#f5f5f5}button.list-group-item{width:100%;text-align:left}.list-group-item.disabled,.list-group-item.disabled:focus,.list-group-item.disabled:hover{color:#777;cursor:not-allowed;background-color:#eee}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7}.list-group-item.active .list-group-item-heading,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:focus .list-group-item-text,.list-group-item.active:hover .list-group-item-text{color:#c7ddef}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success,button.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading,button.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:focus,a.list-group-item-success:hover,button.list-group-item-success:focus,button.list-group-item-success:hover{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:focus,a.list-group-item-success.active:hover,button.list-group-item-success.active,button.list-group-item-success.active:focus,button.list-group-item-success.active:hover{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info,button.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading,button.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:focus,a.list-group-item-info:hover,button.list-group-item-info:focus,button.list-group-item-info:hover{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:focus,a.list-group-item-info.active:hover,button.list-group-item-info.active,button.list-group-item-info.active:focus,button.list-group-item-info.active:hover{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning,button.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading,button.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:focus,a.list-group-item-warning:hover,button.list-group-item-warning:focus,button.list-group-item-warning:hover{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:focus,a.list-group-item-warning.active:hover,button.list-group-item-warning.active,button.list-group-item-warning.active:focus,button.list-group-item-warning.active:hover{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger,button.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading,button.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:focus,a.list-group-item-danger:hover,button.list-group-item-danger:focus,button.list-group-item-danger:hover{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:focus,a.list-group-item-danger.active:hover,button.list-group-item-danger.active,button.list-group-item-danger.active:focus,button.list-group-item-danger.active:hover{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-left-radius:3px;border-top-right-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>.small,.panel-title>.small>a,.panel-title>a,.panel-title>small,.panel-title>small>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group,.panel>.panel-collapse>.list-group{margin-bottom:0}.panel>.list-group .list-group-item,.panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child,.panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-left-radius:3px;border-top-right-radius:3px}.panel>.list-group:last-child .list-group-item:last-child,.panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.panel-heading+.panel-collapse>.list-group .list-group-item:first-child{border-top-left-radius:0;border-top-right-radius:0}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.list-group+.panel-footer{border-top-width:0}.panel>.panel-collapse>.table,.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.panel-collapse>.table caption,.panel>.table caption,.panel>.table-responsive>.table caption{padding-right:15px;padding-left:15px}.panel>.table-responsive:first-child>.table:first-child,.panel>.table:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child,.panel>.table:first-child>thead:first-child>tr:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table-responsive:last-child>.table:last-child,.panel>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive,.panel>.table+.panel-body,.panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child td,.panel>.table>tbody:first-child>tr:first-child th{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{margin-bottom:0;border:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.list-group,.panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#337ab7}.panel-primary>.panel-heading{color:#fff;background-color:#337ab7;border-color:#337ab7}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#337ab7}.panel-primary>.panel-heading .badge{color:#337ab7;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#337ab7}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;filter:alpha(opacity=20);opacity:.2}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer;filter:alpha(opacity=50);opacity:.5}button.close{-webkit-appearance:none;padding:0;cursor:pointer;background:0 0;border:0}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transition:-webkit-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out;-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);-o-transform:translate(0,-25%);transform:translate(0,-25%)}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);-o-transform:translate(0,0);transform:translate(0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5)}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{filter:alpha(opacity=0);opacity:0}.modal-backdrop.in{filter:alpha(opacity=50);opacity:.5}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:12px;font-style:normal;font-weight:400;line-height:1.42857143;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;word-wrap:normal;white-space:normal;filter:alpha(opacity=0);opacity:0;line-break:auto}.tooltip.in{filter:alpha(opacity=90);opacity:.9}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{right:5px;bottom:0;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{bottom:0;left:5px;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;right:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;left:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;font-style:normal;font-weight:400;line-height:1.42857143;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;word-wrap:normal;white-space:normal;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);line-break:auto}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{content:"";border-width:10px}.popover.top>.arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,.25);border-bottom-width:0}.popover.top>.arrow:after{bottom:1px;margin-left:-10px;content:" ";border-top-color:#fff;border-bottom-width:0}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,.25);border-left-width:0}.popover.right>.arrow:after{bottom:-10px;left:1px;content:" ";border-right-color:#fff;border-left-width:0}.popover.bottom>.arrow{top:-11px;left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25)}.popover.bottom>.arrow:after{top:1px;margin-left:-10px;content:" ";border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{right:1px;bottom:-10px;content:" ";border-right-width:0;border-left-color:#fff}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>a>img,.carousel-inner>.item>img{line-height:1}@media all and (transform-3d),(-webkit-transform-3d){.carousel-inner>.item{-webkit-transition:-webkit-transform .6s ease-in-out;-o-transition:-o-transform .6s ease-in-out;transition:transform .6s ease-in-out;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000px;perspective:1000px}.carousel-inner>.item.active.right,.carousel-inner>.item.next{left:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.carousel-inner>.item.active.left,.carousel-inner>.item.prev{left:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.carousel-inner>.item.active,.carousel-inner>.item.next.left,.carousel-inner>.item.prev.right{left:0;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6);filter:alpha(opacity=50);opacity:.5}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);background-repeat:repeat-x}.carousel-control.right{right:0;left:auto;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);background-repeat:repeat-x}.carousel-control:focus,.carousel-control:hover{color:#fff;text-decoration:none;filter:alpha(opacity=90);outline:0;opacity:.9}.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{position:absolute;top:50%;z-index:5;display:inline-block;margin-top:-10px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{left:50%;margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{right:50%;margin-right:-10px}.carousel-control .icon-next,.carousel-control .icon-prev{width:20px;height:20px;font-family:serif;line-height:1}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;background-color:#000\9;background-color:rgba(0,0,0,0);border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{width:30px;height:30px;margin-top:-15px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-15px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-15px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.btn-group-vertical>.btn-group:after,.btn-group-vertical>.btn-group:before,.btn-toolbar:after,.btn-toolbar:before,.clearfix:after,.clearfix:before,.container-fluid:after,.container-fluid:before,.container:after,.container:before,.dl-horizontal dd:after,.dl-horizontal dd:before,.form-horizontal .form-group:after,.form-horizontal .form-group:before,.modal-footer:after,.modal-footer:before,.modal-header:after,.modal-header:before,.nav:after,.nav:before,.navbar-collapse:after,.navbar-collapse:before,.navbar-header:after,.navbar-header:before,.navbar:after,.navbar:before,.pager:after,.pager:before,.panel-body:after,.panel-body:before,.row:after,.row:before{display:table;content:" "}.btn-group-vertical>.btn-group:after,.btn-toolbar:after,.clearfix:after,.container-fluid:after,.container:after,.dl-horizontal dd:after,.form-horizontal .form-group:after,.modal-footer:after,.modal-header:after,.nav:after,.navbar-collapse:after,.navbar-header:after,.navbar:after,.pager:after,.panel-body:after,.row:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-lg,.visible-md,.visible-sm,.visible-xs{display:none!important}.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table!important}tr.visible-xs{display:table-row!important}td.visible-xs,th.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table!important}tr.visible-sm{display:table-row!important}td.visible-sm,th.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table!important}tr.visible-md{display:table-row!important}td.visible-md,th.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table!important}tr.visible-lg{display:table-row!important}td.visible-lg,th.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table!important}tr.visible-print{display:table-row!important}td.visible-print,th.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}}
/*# sourceMappingURL=bootstrap.min.css.map */ | ujangwalker/cekodp | dist/css/bootstrap.min.css | CSS | mit | 121,186 |
module.exports={title:"OpenCV",slug:"opencv",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>OpenCV icon</title><path d="M11.8992.8525C8.735.8525 6.17 3.4175 6.17 6.5817c0 2.102 1.1321 3.9398 2.8198 4.9366l1.6412-2.7849c.0411-.0699.0176-.1593-.0495-.2048-.6233-.4227-1.0328-1.137-1.0328-1.947 0-1.298 1.0524-2.3504 2.3505-2.3504 1.2981 0 2.3505 1.0524 2.3505 2.3505 0 .8098-.4095 1.5242-1.0328 1.947-.0671.0454-.0907.1348-.0495.2047l1.6414 2.785c1.6878-.9969 2.8199-2.8346 2.8199-4.9367 0-3.1642-2.5653-5.7292-5.7295-5.7292zm-6.17 10.8366C2.565 11.6891 0 14.2541 0 17.4183c0 3.1642 2.565 5.7292 5.7292 5.7292 3.1798 0 5.8074-2.6995 5.7275-5.8762H8.2313c-.0847 0-.1513.0717-.1519.1564-.0082 1.266-1.0644 2.3411-2.3502 2.3411-1.2981 0-2.3505-1.0524-2.3505-2.3505 0-1.2982 1.0524-2.3505 2.3505-2.3505.34 0 .663.0724.9547.2022.0713.0318.1566.0077.1962-.0595l1.6464-2.7935c-.8273-.4636-1.7815-.7279-2.7973-.7279zm15.4424.7614l-1.6366 2.7878c-.041.07-.0172.1594.05.2048.624.4217 1.0348 1.1354 1.0363 1.9452.0022 1.298-1.0483 2.352-2.3465 2.3542-1.298.0023-2.3523-1.0482-2.3545-2.3462-.0015-.8098.4068-1.5248 1.0294-1.9486.067-.0457.0905-.1353.0492-.2051l-1.6464-2.7818c-1.6859.9998-2.8146 2.8394-2.811 4.9415.0056 3.1641 2.575 5.7248 5.7393 5.7192 3.1641-.0054 5.7246-2.575 5.7192-5.7392-.0037-2.1022-1.139-3.938-2.8284-4.9318z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://opencv.org/resources/media-kit/",hex:"5C3EE8"}; | cdnjs/cdnjs | ajax/libs/simple-icons/4.9.0/opencv.js | JavaScript | mit | 1,489 |
(function() {
// CommonJS require()
function require(p){
var path = require.resolve(p)
, mod = require.modules[path];
if (!mod) throw new Error('failed to require "' + p + '"');
if (!mod.exports) {
mod.exports = {};
mod.call(mod.exports, mod, mod.exports, require.relative(path));
}
return mod.exports;
}
require.modules = {};
require.resolve = function (path){
var orig = path
, reg = path + '.js'
, index = path + '/index.js';
return require.modules[reg] && reg
|| require.modules[index] && index
|| orig;
};
require.register = function (path, fn){
require.modules[path] = fn;
};
require.relative = function (parent) {
return function(p){
if ('.' != p[0]) return require(p);
var path = parent.split('/')
, segs = p.split('/');
path.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if ('..' == seg) path.pop();
else if ('.' != seg) path.push(seg);
}
return require(path.join('/'));
};
};
require.register("compiler.js", function(module, exports, require){
/*!
* Jade - Compiler
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var nodes = require('./nodes')
, filters = require('./filters')
, doctypes = require('./doctypes')
, selfClosing = require('./self-closing')
, inlineTags = require('./inline-tags')
, utils = require('./utils');
if (!Object.keys) {
Object.keys = function(obj){
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(key);
}
}
return arr;
}
}
if (!String.prototype.trimLeft) {
String.prototype.trimLeft = function(){
return this.replace(/^\s+/, '');
}
}
/**
* Initialize `Compiler` with the given `node`.
*
* @param {Node} node
* @param {Object} options
* @api public
*/
var Compiler = module.exports = function Compiler(node, options) {
this.options = options = options || {};
this.node = node;
this.hasCompiledDoctype = false;
this.hasCompiledTag = false;
this.pp = options.pretty || false;
this.debug = false !== options.compileDebug;
this.indents = 0;
if (options.doctype) this.setDoctype(options.doctype);
};
/**
* Compiler prototype.
*/
Compiler.prototype = {
/**
* Compile parse tree to JavaScript.
*
* @api public
*/
compile: function(){
this.buf = ['var interp;'];
this.lastBufferedIdx = -1
this.visit(this.node);
return this.buf.join('\n');
},
/**
* Sets the default doctype `name`. Sets terse mode to `true` when
* html 5 is used, causing self-closing tags to end with ">" vs "/>",
* and boolean attributes are not mirrored.
*
* @param {string} name
* @api public
*/
setDoctype: function(name){
var doctype = doctypes[(name || 'default').toLowerCase()];
doctype = doctype || '<!DOCTYPE ' + name + '>';
this.doctype = doctype;
this.terse = '5' == name || 'html' == name;
this.xml = 0 == this.doctype.indexOf('<?xml');
},
/**
* Buffer the given `str` optionally escaped.
*
* @param {String} str
* @param {Boolean} esc
* @api public
*/
buffer: function(str, esc){
if (esc) str = utils.escape(str);
if (this.lastBufferedIdx == this.buf.length) {
this.lastBuffered += str;
this.buf[this.lastBufferedIdx - 1] = "buf.push('" + this.lastBuffered + "');"
} else {
this.buf.push("buf.push('" + str + "');");
this.lastBuffered = str;
this.lastBufferedIdx = this.buf.length;
}
},
/**
* Visit `node`.
*
* @param {Node} node
* @api public
*/
visit: function(node){
var debug = this.debug;
if (debug) {
this.buf.push('__jade.unshift({ lineno: ' + node.line
+ ', filename: ' + (node.filename
? '"' + node.filename + '"'
: '__jade[0].filename')
+ ' });');
}
// Massive hack to fix our context
// stack for - else[ if] etc
if (false === node.debug && this.debug) {
this.buf.pop();
this.buf.pop();
}
this.visitNode(node);
if (debug) this.buf.push('__jade.shift();');
},
/**
* Visit `node`.
*
* @param {Node} node
* @api public
*/
visitNode: function(node){
var name = node.constructor.name
|| node.constructor.toString().match(/function ([^(\s]+)()/)[1];
return this['visit' + name](node);
},
/**
* Visit case `node`.
*
* @param {Literal} node
* @api public
*/
visitCase: function(node){
var _ = this.withinCase;
this.withinCase = true;
this.buf.push('switch (' + node.expr + '){');
this.visit(node.block);
this.buf.push('}');
this.withinCase = _;
},
/**
* Visit when `node`.
*
* @param {Literal} node
* @api public
*/
visitWhen: function(node){
if ('default' == node.expr) {
this.buf.push('default:');
} else {
this.buf.push('case ' + node.expr + ':');
}
this.visit(node.block);
this.buf.push(' break;');
},
/**
* Visit literal `node`.
*
* @param {Literal} node
* @api public
*/
visitLiteral: function(node){
var str = node.str.replace(/\n/g, '\\\\n');
this.buffer(str);
},
/**
* Visit all nodes in `block`.
*
* @param {Block} block
* @api public
*/
visitBlock: function(block){
var len = block.nodes.length;
for (var i = 0; i < len; ++i) {
this.visit(block.nodes[i]);
}
},
/**
* Visit `doctype`. Sets terse mode to `true` when html 5
* is used, causing self-closing tags to end with ">" vs "/>",
* and boolean attributes are not mirrored.
*
* @param {Doctype} doctype
* @api public
*/
visitDoctype: function(doctype){
if (doctype && (doctype.val || !this.doctype)) {
this.setDoctype(doctype.val || 'default');
}
if (this.doctype) this.buffer(this.doctype);
this.hasCompiledDoctype = true;
},
/**
* Visit `mixin`, generating a function that
* may be called within the template.
*
* @param {Mixin} mixin
* @api public
*/
visitMixin: function(mixin){
var name = mixin.name.replace(/-/g, '_') + '_mixin'
, args = mixin.args || '';
if (mixin.block) {
this.buf.push('var ' + name + ' = function(' + args + '){');
this.visit(mixin.block);
this.buf.push('}');
} else {
this.buf.push(name + '(' + args + ');');
}
},
/**
* Visit `tag` buffering tag markup, generating
* attributes, visiting the `tag`'s code and block.
*
* @param {Tag} tag
* @api public
*/
visitTag: function(tag){
this.indents++;
var name = tag.name;
if (!this.hasCompiledTag) {
if (!this.hasCompiledDoctype && 'html' == name) {
this.visitDoctype();
}
this.hasCompiledTag = true;
}
// pretty print
if (this.pp && inlineTags.indexOf(name) == -1) {
this.buffer('\\n' + Array(this.indents).join(' '));
}
if (~selfClosing.indexOf(name) && !this.xml) {
this.buffer('<' + name);
this.visitAttributes(tag.attrs);
this.terse
? this.buffer('>')
: this.buffer('/>');
} else {
// Optimize attributes buffering
if (tag.attrs.length) {
this.buffer('<' + name);
if (tag.attrs.length) this.visitAttributes(tag.attrs);
this.buffer('>');
} else {
this.buffer('<' + name + '>');
}
if (tag.code) this.visitCode(tag.code);
if (tag.text) this.buffer(utils.text(tag.text.nodes[0].trimLeft()));
this.escape = 'pre' == tag.name;
this.visit(tag.block);
// pretty print
if (this.pp && !~inlineTags.indexOf(name) && !tag.textOnly) {
this.buffer('\\n' + Array(this.indents).join(' '));
}
this.buffer('</' + name + '>');
}
this.indents--;
},
/**
* Visit `filter`, throwing when the filter does not exist.
*
* @param {Filter} filter
* @api public
*/
visitFilter: function(filter){
var fn = filters[filter.name];
// unknown filter
if (!fn) {
if (filter.isASTFilter) {
throw new Error('unknown ast filter "' + filter.name + ':"');
} else {
throw new Error('unknown filter ":' + filter.name + '"');
}
}
if (filter.isASTFilter) {
this.buf.push(fn(filter.block, this, filter.attrs));
} else {
var text = filter.block.nodes.join('');
this.buffer(utils.text(fn(text, filter.attrs)));
}
},
/**
* Visit `text` node.
*
* @param {Text} text
* @api public
*/
visitText: function(text){
text = utils.text(text.nodes.join(''));
if (this.escape) text = escape(text);
this.buffer(text);
this.buffer('\\n');
},
/**
* Visit a `comment`, only buffering when the buffer flag is set.
*
* @param {Comment} comment
* @api public
*/
visitComment: function(comment){
if (!comment.buffer) return;
if (this.pp) this.buffer('\\n' + Array(this.indents + 1).join(' '));
this.buffer('<!--' + utils.escape(comment.val) + '-->');
},
/**
* Visit a `BlockComment`.
*
* @param {Comment} comment
* @api public
*/
visitBlockComment: function(comment){
if (!comment.buffer) return;
if (0 == comment.val.trim().indexOf('if')) {
this.buffer('<!--[' + comment.val.trim() + ']>');
this.visit(comment.block);
this.buffer('<![endif]-->');
} else {
this.buffer('<!--' + comment.val);
this.visit(comment.block);
this.buffer('-->');
}
},
/**
* Visit `code`, respecting buffer / escape flags.
* If the code is followed by a block, wrap it in
* a self-calling function.
*
* @param {Code} code
* @api public
*/
visitCode: function(code){
// Wrap code blocks with {}.
// we only wrap unbuffered code blocks ATM
// since they are usually flow control
// Buffer code
if (code.buffer) {
var val = code.val.trimLeft();
this.buf.push('var __val__ = ' + val);
val = 'null == __val__ ? "" : __val__';
if (code.escape) val = 'escape(' + val + ')';
this.buf.push("buf.push(" + val + ");");
} else {
this.buf.push(code.val);
}
// Block support
if (code.block) {
if (!code.buffer) this.buf.push('{');
this.visit(code.block);
if (!code.buffer) this.buf.push('}');
}
},
/**
* Visit `each` block.
*
* @param {Each} each
* @api public
*/
visitEach: function(each){
this.buf.push(''
+ '// iterate ' + each.obj + '\n'
+ '(function(){\n'
+ ' if (\'number\' == typeof ' + each.obj + '.length) {\n'
+ ' for (var ' + each.key + ' = 0, $$l = ' + each.obj + '.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n'
+ ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n');
this.visit(each.block);
this.buf.push(''
+ ' }\n'
+ ' } else {\n'
+ ' for (var ' + each.key + ' in ' + each.obj + ') {\n'
+ ' if (' + each.obj + '.hasOwnProperty(' + each.key + ')){'
+ ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n');
this.visit(each.block);
this.buf.push(' }\n');
this.buf.push(' }\n }\n}).call(this);\n');
},
/**
* Visit `attrs`.
*
* @param {Array} attrs
* @api public
*/
visitAttributes: function(attrs){
var buf = []
, classes = [];
if (this.terse) buf.push('terse: true');
attrs.forEach(function(attr){
if (attr.name == 'class') {
classes.push('(' + attr.val + ')');
} else {
var pair = "'" + attr.name + "':(" + attr.val + ')';
buf.push(pair);
}
});
if (classes.length) {
classes = classes.join(" + ' ' + ");
buf.push("class: " + classes);
}
buf = buf.join(', ').replace('class:', '"class":');
this.buf.push("buf.push(attrs({ " + buf + " }));");
}
};
/**
* Escape the given string of `html`.
*
* @param {String} html
* @return {String}
* @api private
*/
function escape(html){
return String(html)
.replace(/&(?!\w+;)/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
}); // module: compiler.js
require.register("doctypes.js", function(module, exports, require){
/*!
* Jade - doctypes
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
module.exports = {
'5': '<!DOCTYPE html>'
, 'xml': '<?xml version="1.0" encoding="utf-8" ?>'
, 'default': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
, 'transitional': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
, 'strict': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
, 'frameset': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">'
, '1.1': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'
, 'basic': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">'
, 'mobile': '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">'
};
}); // module: doctypes.js
require.register("filters.js", function(module, exports, require){
/*!
* Jade - filters
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
module.exports = {
/**
* Wrap text with CDATA block.
*/
cdata: function(str){
return '<![CDATA[\\n' + str + '\\n]]>';
},
/**
* Transform sass to css, wrapped in style tags.
*/
sass: function(str){
str = str.replace(/\\n/g, '\n');
var sass = require('sass').render(str).replace(/\n/g, '\\n');
return '<style type="text/css">' + sass + '</style>';
},
/**
* Transform stylus to css, wrapped in style tags.
*/
stylus: function(str, options){
var ret;
str = str.replace(/\\n/g, '\n');
var stylus = require('stylus');
stylus(str, options).render(function(err, css){
if (err) throw err;
ret = css.replace(/\n/g, '\\n');
});
return '<style type="text/css">' + ret + '</style>';
},
/**
* Transform less to css, wrapped in style tags.
*/
less: function(str){
var ret;
str = str.replace(/\\n/g, '\n');
require('less').render(str, function(err, css){
if (err) throw err;
ret = '<style type="text/css">' + css.replace(/\n/g, '\\n') + '</style>';
});
return ret;
},
/**
* Transform markdown to html.
*/
markdown: function(str){
var md;
// support markdown / discount
try {
md = require('markdown');
} catch (err){
try {
md = require('discount');
} catch (err) {
try {
md = require('markdown-js');
} catch (err) {
throw new Error('Cannot find markdown library, install markdown or discount');
}
}
}
str = str.replace(/\\n/g, '\n');
return md.parse(str).replace(/\n/g, '\\n').replace(/'/g,''');
},
/**
* Transform coffeescript to javascript.
*/
coffeescript: function(str){
str = str.replace(/\\n/g, '\n');
var js = require('coffee-script').compile(str).replace(/\n/g, '\\n');
return '<script type="text/javascript">\\n' + js + '</script>';
}
};
}); // module: filters.js
require.register("inline-tags.js", function(module, exports, require){
/*!
* Jade - inline tags
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
module.exports = [
'a'
, 'abbr'
, 'acronym'
, 'b'
, 'br'
, 'code'
, 'em'
, 'font'
, 'i'
, 'img'
, 'ins'
, 'kbd'
, 'map'
, 'samp'
, 'small'
, 'span'
, 'strong'
, 'sub'
, 'sup'
];
}); // module: inline-tags.js
require.register("jade.js", function(module, exports, require){
/*!
* Jade
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Parser = require('./parser')
, Lexer = require('./lexer')
, Compiler = require('./compiler')
, runtime = require('./runtime')
/**
* Library version.
*/
exports.version = '0.19.0';
/**
* Expose self closing tags.
*/
exports.selfClosing = require('./self-closing');
/**
* Default supported doctypes.
*/
exports.doctypes = require('./doctypes');
/**
* Text filters.
*/
exports.filters = require('./filters');
/**
* Utilities.
*/
exports.utils = require('./utils');
/**
* Expose `Compiler`.
*/
exports.Compiler = Compiler;
/**
* Expose `Parser`.
*/
exports.Parser = Parser;
/**
* Expose `Lexer`.
*/
exports.Lexer = Lexer;
/**
* Nodes.
*/
exports.nodes = require('./nodes');
/**
* Jade runtime helpers.
*/
exports.runtime = runtime;
/**
* Template function cache.
*/
exports.cache = {};
/**
* Parse the given `str` of jade and return a function body.
*
* @param {String} str
* @param {Object} options
* @return {String}
* @api private
*/
function parse(str, options){
try {
// Parse
var parser = new Parser(str, options.filename, options);
// Compile
var compiler = new (options.compiler || Compiler)(parser.parse(), options)
, js = compiler.compile();
// Debug compiler
if (options.debug) {
console.error('\nCompiled Function:\n\n\033[90m%s\033[0m', js.replace(/^/gm, ' '));
}
return ''
+ 'var buf = [];\n'
+ (options.self
? 'var self = locals || {};\n' + js
: 'with (locals || {}) {\n' + js + '\n}\n')
+ 'return buf.join("");';
} catch (err) {
parser = parser.context();
runtime.rethrow(err, parser.filename, parser.lexer.lineno);
}
}
/**
* Compile a `Function` representation of the given jade `str`.
*
* Options:
*
* - `compileDebug` when `false` debugging code is stripped from the compiled template
* - `client` when `true` the helper functions `escape()` etc will reference `jade.escape()`
* for use with the Jade client-side runtime.js
*
* @param {String} str
* @param {Options} options
* @return {Function}
* @api public
*/
exports.compile = function(str, options){
var options = options || {}
, client = options.client
, filename = options.filename
? JSON.stringify(options.filename)
: 'undefined'
, fn;
if (options.compileDebug !== false) {
fn = [
'var __jade = [{ lineno: 1, filename: ' + filename + ' }];'
, 'try {'
, parse(String(str), options || {})
, '} catch (err) {'
, ' rethrow(err, __jade[0].filename, __jade[0].lineno);'
, '}'
].join('\n');
} else {
fn = parse(String(str), options || {});
}
if (client) {
fn = 'var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow;\n' + fn;
}
fn = new Function('locals, attrs, escape, rethrow', fn);
if (client) return fn;
return function(locals){
return fn(locals, runtime.attrs, runtime.escape, runtime.rethrow);
};
};
/**
* Render the given `str` of jade and invoke
* the callback `fn(err, str)`.
*
* Options:
*
* - `cache` enable template caching
* - `filename` filename required for `include` / `extends` and caching
*
* @param {String} str
* @param {Object|Function} options or fn
* @param {Function} fn
* @api public
*/
exports.render = function(str, options, fn){
// swap args
if ('function' == typeof options) {
fn = options, options = {};
}
// cache requires .filename
if (options.cache && !options.filename) {
return fn(new Error('the "filename" option is required for caching'));
}
try {
var path = options.filename;
var tmpl = options.cache
? exports.cache[path] || (exports.cache[path] = exports.compile(str, options))
: exports.compile(str, options);
fn(null, tmpl(options));
} catch (err) {
fn(err);
}
};
/**
* Render a Jade file at the given `path` and callback `fn(err, str)`.
*
* @param {String} path
* @param {Object|Function} options or callback
* @param {Function} fn
* @api public
*/
exports.renderFile = function(path, options, fn){
var key = path + ':string';
if ('function' == typeof options) {
fn = options, options = {};
}
try {
options.filename = path;
var str = options.cache
? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8'))
: fs.readFileSync(path, 'utf8');
exports.render(str, options, fn);
} catch (err) {
fn(err);
}
};
/**
* Express support.
*/
exports.__express = exports.renderFile;
}); // module: jade.js
require.register("lexer.js", function(module, exports, require){
/*!
* Jade - Lexer
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Initialize `Lexer` with the given `str`.
*
* Options:
*
* - `colons` allow colons for attr delimiters
*
* @param {String} str
* @param {Object} options
* @api private
*/
var Lexer = module.exports = function Lexer(str, options) {
options = options || {};
this.input = str.replace(/\r\n|\r/g, '\n');
this.colons = options.colons;
this.deferredTokens = [];
this.lastIndents = 0;
this.lineno = 1;
this.stash = [];
this.indentStack = [];
this.indentRe = null;
this.pipeless = false;
};
/**
* Lexer prototype.
*/
Lexer.prototype = {
/**
* Construct a token with the given `type` and `val`.
*
* @param {String} type
* @param {String} val
* @return {Object}
* @api private
*/
tok: function(type, val){
return {
type: type
, line: this.lineno
, val: val
}
},
/**
* Consume the given `len` of input.
*
* @param {Number} len
* @api private
*/
consume: function(len){
this.input = this.input.substr(len);
},
/**
* Scan for `type` with the given `regexp`.
*
* @param {String} type
* @param {RegExp} regexp
* @return {Object}
* @api private
*/
scan: function(regexp, type){
var captures;
if (captures = regexp.exec(this.input)) {
this.consume(captures[0].length);
return this.tok(type, captures[1]);
}
},
/**
* Defer the given `tok`.
*
* @param {Object} tok
* @api private
*/
defer: function(tok){
this.deferredTokens.push(tok);
},
/**
* Lookahead `n` tokens.
*
* @param {Number} n
* @return {Object}
* @api private
*/
lookahead: function(n){
var fetch = n - this.stash.length;
while (fetch-- > 0) this.stash.push(this.next());
return this.stash[--n];
},
/**
* Return the indexOf `start` / `end` delimiters.
*
* @param {String} start
* @param {String} end
* @return {Number}
* @api private
*/
indexOfDelimiters: function(start, end){
var str = this.input
, nstart = 0
, nend = 0
, pos = 0;
for (var i = 0, len = str.length; i < len; ++i) {
if (start == str[i]) {
++nstart;
} else if (end == str[i]) {
if (++nend == nstart) {
pos = i;
break;
}
}
}
return pos;
},
/**
* Stashed token.
*/
stashed: function() {
return this.stash.length
&& this.stash.shift();
},
/**
* Deferred token.
*/
deferred: function() {
return this.deferredTokens.length
&& this.deferredTokens.shift();
},
/**
* end-of-source.
*/
eos: function() {
if (this.input.length) return;
if (this.indentStack.length) {
this.indentStack.shift();
return this.tok('outdent');
} else {
return this.tok('eos');
}
},
/**
* Comment.
*/
comment: function() {
var captures;
if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('comment', captures[2]);
tok.buffer = '-' != captures[1];
return tok;
}
},
/**
* Tag.
*/
tag: function() {
var captures;
if (captures = /^(\w[-:\w]*)/.exec(this.input)) {
this.consume(captures[0].length);
var tok, name = captures[1];
if (':' == name[name.length - 1]) {
name = name.slice(0, -1);
tok = this.tok('tag', name);
this.defer(this.tok(':'));
while (' ' == this.input[0]) this.input = this.input.substr(1);
} else {
tok = this.tok('tag', name);
}
return tok;
}
},
/**
* Filter.
*/
filter: function() {
return this.scan(/^:(\w+)/, 'filter');
},
/**
* Doctype.
*/
doctype: function() {
return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype');
},
/**
* Id.
*/
id: function() {
return this.scan(/^#([\w-]+)/, 'id');
},
/**
* Class.
*/
className: function() {
return this.scan(/^\.([\w-]+)/, 'class');
},
/**
* Text.
*/
text: function() {
return this.scan(/^(?:\| ?)?([^\n]+)/, 'text');
},
/**
* Extends.
*/
extends: function() {
return this.scan(/^extends +([^\n]+)/, 'extends');
},
/**
* Block prepend.
*/
prepend: function() {
var captures;
if (captures = /^prepend +([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var mode = 'prepend'
, name = captures[1]
, tok = this.tok('block', name);
tok.mode = mode;
return tok;
}
},
/**
* Block append.
*/
append: function() {
var captures;
if (captures = /^append +([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var mode = 'append'
, name = captures[1]
, tok = this.tok('block', name);
tok.mode = mode;
return tok;
}
},
/**
* Block.
*/
block: function() {
var captures;
if (captures = /^block +(?:(prepend|append) +)?([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var mode = captures[1] || 'replace'
, name = captures[2]
, tok = this.tok('block', name);
tok.mode = mode;
return tok;
}
},
/**
* Yield.
*/
yield: function() {
return this.scan(/^yield */, 'yield');
},
/**
* Include.
*/
include: function() {
return this.scan(/^include +([^\n]+)/, 'include');
},
/**
* Case.
*/
case: function() {
return this.scan(/^case +([^\n]+)/, 'case');
},
/**
* When.
*/
when: function() {
return this.scan(/^when +([^:\n]+)/, 'when');
},
/**
* Default.
*/
default: function() {
return this.scan(/^default */, 'default');
},
/**
* Assignment.
*/
assignment: function() {
var captures;
if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) {
this.consume(captures[0].length);
var name = captures[1]
, val = captures[2];
return this.tok('code', 'var ' + name + ' = (' + val + ');');
}
},
/**
* Mixin.
*/
mixin: function(){
var captures;
if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('mixin', captures[1]);
tok.args = captures[2];
return tok;
}
},
/**
* Conditional.
*/
conditional: function() {
var captures;
if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) {
this.consume(captures[0].length);
var type = captures[1]
, js = captures[2];
switch (type) {
case 'if': js = 'if (' + js + ')'; break;
case 'unless': js = 'if (!(' + js + '))'; break;
case 'else if': js = 'else if (' + js + ')'; break;
case 'else': js = 'else'; break;
}
return this.tok('code', js);
}
},
/**
* While.
*/
while: function() {
var captures;
if (captures = /^while +([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
return this.tok('code', 'while (' + captures[1] + ')');
}
},
/**
* Each.
*/
each: function() {
var captures;
if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('each', captures[1]);
tok.key = captures[2] || '$index';
tok.code = captures[3];
return tok;
}
},
/**
* Code.
*/
code: function() {
var captures;
if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var flags = captures[1];
captures[1] = captures[2];
var tok = this.tok('code', captures[1]);
tok.escape = flags[0] === '=';
tok.buffer = flags[0] === '=' || flags[1] === '=';
return tok;
}
},
/**
* Attributes.
*/
attrs: function() {
if ('(' == this.input[0]) {
var index = this.indexOfDelimiters('(', ')')
, str = this.input.substr(1, index-1)
, tok = this.tok('attrs')
, len = str.length
, colons = this.colons
, states = ['key']
, key = ''
, val = ''
, quote
, c;
function state(){
return states[states.length - 1];
}
function interpolate(attr) {
return attr.replace(/#\{([^}]+)\}/g, function(_, expr){
return quote + " + (" + expr + ") + " + quote;
});
}
this.consume(index + 1);
tok.attrs = {};
function parse(c) {
var real = c;
// TODO: remove when people fix ":"
if (colons && ':' == c) c = '=';
switch (c) {
case ',':
case '\n':
switch (state()) {
case 'expr':
case 'array':
case 'string':
case 'object':
val += c;
break;
default:
states.push('key');
val = val.trim();
key = key.trim();
if ('' == key) return;
tok.attrs[key.replace(/^['"]|['"]$/g, '')] = '' == val
? true
: interpolate(val);
key = val = '';
}
break;
case '=':
switch (state()) {
case 'key char':
key += real;
break;
case 'val':
case 'expr':
case 'array':
case 'string':
case 'object':
val += real;
break;
default:
states.push('val');
}
break;
case '(':
if ('val' == state()
|| 'expr' == state()) states.push('expr');
val += c;
break;
case ')':
if ('expr' == state()
|| 'val' == state()) states.pop();
val += c;
break;
case '{':
if ('val' == state()) states.push('object');
val += c;
break;
case '}':
if ('object' == state()) states.pop();
val += c;
break;
case '[':
if ('val' == state()) states.push('array');
val += c;
break;
case ']':
if ('array' == state()) states.pop();
val += c;
break;
case '"':
case "'":
switch (state()) {
case 'key':
states.push('key char');
break;
case 'key char':
states.pop();
break;
case 'string':
if (c == quote) states.pop();
val += c;
break;
default:
states.push('string');
val += c;
quote = c;
}
break;
case '':
break;
default:
switch (state()) {
case 'key':
case 'key char':
key += c;
break;
default:
val += c;
}
}
}
for (var i = 0; i < len; ++i) {
parse(str[i]);
}
parse(',');
return tok;
}
},
/**
* Indent | Outdent | Newline.
*/
indent: function() {
var captures, re;
// established regexp
if (this.indentRe) {
captures = this.indentRe.exec(this.input);
// determine regexp
} else {
// tabs
re = /^\n(\t*) */;
captures = re.exec(this.input);
// spaces
if (captures && !captures[1].length) {
re = /^\n( *)/;
captures = re.exec(this.input);
}
// established
if (captures && captures[1].length) this.indentRe = re;
}
if (captures) {
var tok
, indents = captures[1].length;
++this.lineno;
this.consume(indents + 1);
if (' ' == this.input[0] || '\t' == this.input[0]) {
throw new Error('Invalid indentation, you can use tabs or spaces but not both');
}
// blank line
if ('\n' == this.input[0]) return this.tok('newline');
// outdent
if (this.indentStack.length && indents < this.indentStack[0]) {
while (this.indentStack.length && this.indentStack[0] > indents) {
this.stash.push(this.tok('outdent'));
this.indentStack.shift();
}
tok = this.stash.pop();
// indent
} else if (indents && indents != this.indentStack[0]) {
this.indentStack.unshift(indents);
tok = this.tok('indent', indents);
// newline
} else {
tok = this.tok('newline');
}
return tok;
}
},
/**
* Pipe-less text consumed only when
* pipeless is true;
*/
pipelessText: function() {
if (this.pipeless) {
if ('\n' == this.input[0]) return;
var i = this.input.indexOf('\n');
if (-1 == i) i = this.input.length;
var str = this.input.substr(0, i);
this.consume(str.length);
return this.tok('text', str);
}
},
/**
* ':'
*/
colon: function() {
return this.scan(/^: */, ':');
},
/**
* Return the next token object, or those
* previously stashed by lookahead.
*
* @return {Object}
* @api private
*/
advance: function(){
return this.stashed()
|| this.next();
},
/**
* Return the next token object.
*
* @return {Object}
* @api private
*/
next: function() {
return this.deferred()
|| this.eos()
|| this.pipelessText()
|| this.yield()
|| this.doctype()
|| this.case()
|| this.when()
|| this.default()
|| this.extends()
|| this.append()
|| this.prepend()
|| this.block()
|| this.include()
|| this.mixin()
|| this.conditional()
|| this.each()
|| this.while()
|| this.assignment()
|| this.tag()
|| this.filter()
|| this.code()
|| this.id()
|| this.className()
|| this.attrs()
|| this.indent()
|| this.comment()
|| this.colon()
|| this.text();
}
};
}); // module: lexer.js
require.register("nodes/block-comment.js", function(module, exports, require){
/*!
* Jade - nodes - BlockComment
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node');
/**
* Initialize a `BlockComment` with the given `block`.
*
* @param {String} val
* @param {Block} block
* @param {Boolean} buffer
* @api public
*/
var BlockComment = module.exports = function BlockComment(val, block, buffer) {
this.block = block;
this.val = val;
this.buffer = buffer;
};
/**
* Inherit from `Node`.
*/
BlockComment.prototype = new Node;
BlockComment.prototype.constructor = BlockComment;
}); // module: nodes/block-comment.js
require.register("nodes/block.js", function(module, exports, require){
/*!
* Jade - nodes - Block
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node');
/**
* Initialize a new `Block` with an optional `node`.
*
* @param {Node} node
* @api public
*/
var Block = module.exports = function Block(node){
this.nodes = [];
if (node) this.push(node);
};
/**
* Inherit from `Node`.
*/
Block.prototype = new Node;
Block.prototype.constructor = Block;
/**
* Replace the nodes in `other` with the nodes
* in `this` block.
*
* @param {Block} other
* @api private
*/
Block.prototype.replace = function(other){
other.nodes = this.nodes;
};
/**
* Pust the given `node`.
*
* @param {Node} node
* @return {Number}
* @api public
*/
Block.prototype.push = function(node){
return this.nodes.push(node);
};
/**
* Check if this block is empty.
*
* @return {Boolean}
* @api public
*/
Block.prototype.isEmpty = function(){
return 0 == this.nodes.length;
};
/**
* Unshift the given `node`.
*
* @param {Node} node
* @return {Number}
* @api public
*/
Block.prototype.unshift = function(node){
return this.nodes.unshift(node);
};
/**
* Return the "last" block, or the first `yield` node.
*
* @return {Block}
* @api private
*/
Block.prototype.includeBlock = function(){
var ret = this
, node;
for (var i = 0, len = this.nodes.length; i < len; ++i) {
node = this.nodes[i];
if (node.yield) return node;
else if (node.includeBlock) ret = node.includeBlock();
else if (node.block && !node.block.isEmpty()) ret = node.block.includeBlock();
}
return ret;
};
}); // module: nodes/block.js
require.register("nodes/case.js", function(module, exports, require){
/*!
* Jade - nodes - Case
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node');
/**
* Initialize a new `Case` with `expr`.
*
* @param {String} expr
* @api public
*/
var Case = exports = module.exports = function Case(expr, block){
this.expr = expr;
this.block = block;
};
/**
* Inherit from `Node`.
*/
Case.prototype = new Node;
Case.prototype.constructor = Case;
var When = exports.When = function When(expr, block){
this.expr = expr;
this.block = block;
this.debug = false;
};
/**
* Inherit from `Node`.
*/
When.prototype = new Node;
When.prototype.constructor = When;
}); // module: nodes/case.js
require.register("nodes/code.js", function(module, exports, require){
/*!
* Jade - nodes - Code
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node');
/**
* Initialize a `Code` node with the given code `val`.
* Code may also be optionally buffered and escaped.
*
* @param {String} val
* @param {Boolean} buffer
* @param {Boolean} escape
* @api public
*/
var Code = module.exports = function Code(val, buffer, escape) {
this.val = val;
this.buffer = buffer;
this.escape = escape;
if (val.match(/^ *else/)) this.debug = false;
};
/**
* Inherit from `Node`.
*/
Code.prototype = new Node;
Code.prototype.constructor = Code;
}); // module: nodes/code.js
require.register("nodes/comment.js", function(module, exports, require){
/*!
* Jade - nodes - Comment
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node');
/**
* Initialize a `Comment` with the given `val`, optionally `buffer`,
* otherwise the comment may render in the output.
*
* @param {String} val
* @param {Boolean} buffer
* @api public
*/
var Comment = module.exports = function Comment(val, buffer) {
this.val = val;
this.buffer = buffer;
};
/**
* Inherit from `Node`.
*/
Comment.prototype = new Node;
Comment.prototype.constructor = Comment;
}); // module: nodes/comment.js
require.register("nodes/doctype.js", function(module, exports, require){
/*!
* Jade - nodes - Doctype
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node');
/**
* Initialize a `Doctype` with the given `val`.
*
* @param {String} val
* @api public
*/
var Doctype = module.exports = function Doctype(val) {
this.val = val;
};
/**
* Inherit from `Node`.
*/
Doctype.prototype = new Node;
Doctype.prototype.constructor = Doctype;
}); // module: nodes/doctype.js
require.register("nodes/each.js", function(module, exports, require){
/*!
* Jade - nodes - Each
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node');
/**
* Initialize an `Each` node, representing iteration
*
* @param {String} obj
* @param {String} val
* @param {String} key
* @param {Block} block
* @api public
*/
var Each = module.exports = function Each(obj, val, key, block) {
this.obj = obj;
this.val = val;
this.key = key;
this.block = block;
};
/**
* Inherit from `Node`.
*/
Each.prototype = new Node;
Each.prototype.constructor = Each;
}); // module: nodes/each.js
require.register("nodes/filter.js", function(module, exports, require){
/*!
* Jade - nodes - Filter
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node')
, Block = require('./block');
/**
* Initialize a `Filter` node with the given
* filter `name` and `block`.
*
* @param {String} name
* @param {Block|Node} block
* @api public
*/
var Filter = module.exports = function Filter(name, block, attrs) {
this.name = name;
this.block = block;
this.attrs = attrs;
this.isASTFilter = block instanceof Block;
};
/**
* Inherit from `Node`.
*/
Filter.prototype = new Node;
Filter.prototype.constructor = Filter;
}); // module: nodes/filter.js
require.register("nodes/index.js", function(module, exports, require){
/*!
* Jade - nodes
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
exports.Node = require('./node');
exports.Tag = require('./tag');
exports.Code = require('./code');
exports.Each = require('./each');
exports.Case = require('./case');
exports.Text = require('./text');
exports.Block = require('./block');
exports.Mixin = require('./mixin');
exports.Filter = require('./filter');
exports.Comment = require('./comment');
exports.Literal = require('./literal');
exports.BlockComment = require('./block-comment');
exports.Doctype = require('./doctype');
}); // module: nodes/index.js
require.register("nodes/literal.js", function(module, exports, require){
/*!
* Jade - nodes - Literal
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node');
/**
* Initialize a `Literal` node with the given `str.
*
* @param {String} str
* @api public
*/
var Literal = module.exports = function Literal(str) {
this.str = str
.replace(/\n/g, "\\n")
.replace(/'/g, "\\'");
};
/**
* Inherit from `Node`.
*/
Literal.prototype = new Node;
Literal.prototype.constructor = Literal;
}); // module: nodes/literal.js
require.register("nodes/mixin.js", function(module, exports, require){
/*!
* Jade - nodes - Mixin
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node');
/**
* Initialize a new `Mixin` with `name` and `block`.
*
* @param {String} name
* @param {String} args
* @param {Block} block
* @api public
*/
var Mixin = module.exports = function Mixin(name, args, block){
this.name = name;
this.args = args;
this.block = block;
};
/**
* Inherit from `Node`.
*/
Mixin.prototype = new Node;
Mixin.prototype.constructor = Mixin;
}); // module: nodes/mixin.js
require.register("nodes/node.js", function(module, exports, require){
/*!
* Jade - nodes - Node
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Initialize a `Node`.
*
* @api public
*/
var Node = module.exports = function Node(){};
}); // module: nodes/node.js
require.register("nodes/tag.js", function(module, exports, require){
/*!
* Jade - nodes - Tag
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node'),
Block = require('./block');
/**
* Initialize a `Tag` node with the given tag `name` and optional `block`.
*
* @param {String} name
* @param {Block} block
* @api public
*/
var Tag = module.exports = function Tag(name, block) {
this.name = name;
this.attrs = [];
this.block = block || new Block;
};
/**
* Inherit from `Node`.
*/
Tag.prototype = new Node;
Tag.prototype.constructor = Tag;
/**
* Set attribute `name` to `val`, keep in mind these become
* part of a raw js object literal, so to quote a value you must
* '"quote me"', otherwise or example 'user.name' is literal JavaScript.
*
* @param {String} name
* @param {String} val
* @return {Tag} for chaining
* @api public
*/
Tag.prototype.setAttribute = function(name, val){
this.attrs.push({ name: name, val: val });
return this;
};
/**
* Remove attribute `name` when present.
*
* @param {String} name
* @api public
*/
Tag.prototype.removeAttribute = function(name){
for (var i = 0, len = this.attrs.length; i < len; ++i) {
if (this.attrs[i] && this.attrs[i].name == name) {
delete this.attrs[i];
}
}
};
/**
* Get attribute value by `name`.
*
* @param {String} name
* @return {String}
* @api public
*/
Tag.prototype.getAttribute = function(name){
for (var i = 0, len = this.attrs.length; i < len; ++i) {
if (this.attrs[i] && this.attrs[i].name == name) {
return this.attrs[i].val;
}
}
};
}); // module: nodes/tag.js
require.register("nodes/text.js", function(module, exports, require){
/*!
* Jade - nodes - Text
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Node = require('./node');
/**
* Initialize a `Text` node with optional `line`.
*
* @param {String} line
* @api public
*/
var Text = module.exports = function Text(line) {
this.nodes = [];
if ('string' == typeof line) this.push(line);
};
/**
* Inherit from `Node`.
*/
Text.prototype = new Node;
Text.prototype.constructor = Text;
/**
* Push the given `node.`
*
* @param {Node} node
* @return {Number}
* @api public
*/
Text.prototype.push = function(node){
return this.nodes.push(node);
};
}); // module: nodes/text.js
require.register("parser.js", function(module, exports, require){
/*!
* Jade - Parser
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Lexer = require('./lexer')
, nodes = require('./nodes');
/**
* Initialize `Parser` with the given input `str` and `filename`.
*
* @param {String} str
* @param {String} filename
* @param {Object} options
* @api public
*/
var Parser = exports = module.exports = function Parser(str, filename, options){
this.input = str;
this.lexer = new Lexer(str, options);
this.filename = filename;
this.blocks = {};
this.options = options;
this.contexts = [this];
};
/**
* Tags that may not contain tags.
*/
var textOnly = exports.textOnly = ['script', 'style'];
/**
* Parser prototype.
*/
Parser.prototype = {
/**
* Push `parser` onto the context stack,
* or pop and return a `Parser`.
*/
context: function(parser){
if (parser) {
this.contexts.push(parser);
} else {
return this.contexts.pop();
}
},
/**
* Return the next token object.
*
* @return {Object}
* @api private
*/
advance: function(){
return this.lexer.advance();
},
/**
* Skip `n` tokens.
*
* @param {Number} n
* @api private
*/
skip: function(n){
while (n--) this.advance();
},
/**
* Single token lookahead.
*
* @return {Object}
* @api private
*/
peek: function() {
return this.lookahead(1);
},
/**
* Return lexer lineno.
*
* @return {Number}
* @api private
*/
line: function() {
return this.lexer.lineno;
},
/**
* `n` token lookahead.
*
* @param {Number} n
* @return {Object}
* @api private
*/
lookahead: function(n){
return this.lexer.lookahead(n);
},
/**
* Parse input returning a string of js for evaluation.
*
* @return {String}
* @api public
*/
parse: function(){
var block = new nodes.Block, parser;
block.line = this.line();
while ('eos' != this.peek().type) {
if ('newline' == this.peek().type) {
this.advance();
} else {
block.push(this.parseExpr());
}
}
if (parser = this.extending) {
this.context(parser);
var ast = parser.parse();
this.context();
return ast;
}
return block;
},
/**
* Expect the given type, or throw an exception.
*
* @param {String} type
* @api private
*/
expect: function(type){
if (this.peek().type === type) {
return this.advance();
} else {
throw new Error('expected "' + type + '", but got "' + this.peek().type + '"');
}
},
/**
* Accept the given `type`.
*
* @param {String} type
* @api private
*/
accept: function(type){
if (this.peek().type === type) {
return this.advance();
}
},
/**
* tag
* | doctype
* | mixin
* | include
* | filter
* | comment
* | text
* | each
* | code
* | yield
* | id
* | class
*/
parseExpr: function(){
switch (this.peek().type) {
case 'tag':
return this.parseTag();
case 'mixin':
return this.parseMixin();
case 'block':
return this.parseBlock();
case 'case':
return this.parseCase();
case 'when':
return this.parseWhen();
case 'default':
return this.parseDefault();
case 'extends':
return this.parseExtends();
case 'include':
return this.parseInclude();
case 'doctype':
return this.parseDoctype();
case 'filter':
return this.parseFilter();
case 'comment':
return this.parseComment();
case 'text':
return this.parseText();
case 'each':
return this.parseEach();
case 'code':
return this.parseCode();
case 'yield':
this.advance();
var block = new nodes.Block;
block.yield = true;
return block;
case 'id':
case 'class':
var tok = this.advance();
this.lexer.defer(this.lexer.tok('tag', 'div'));
this.lexer.defer(tok);
return this.parseExpr();
default:
throw new Error('unexpected token "' + this.peek().type + '"');
}
},
/**
* Text
*/
parseText: function(){
var tok = this.expect('text')
, node = new nodes.Text(tok.val);
node.line = this.line();
return node;
},
/**
* ':' expr
* | block
*/
parseBlockExpansion: function(){
if (':' == this.peek().type) {
this.advance();
return new nodes.Block(this.parseExpr());
} else {
return this.block();
}
},
/**
* case
*/
parseCase: function(){
var val = this.expect('case').val
, node = new nodes.Case(val);
node.line = this.line();
node.block = this.block();
return node;
},
/**
* when
*/
parseWhen: function(){
var val = this.expect('when').val
return new nodes.Case.When(val, this.parseBlockExpansion());
},
/**
* default
*/
parseDefault: function(){
this.expect('default');
return new nodes.Case.When('default', this.parseBlockExpansion());
},
/**
* code
*/
parseCode: function(){
var tok = this.expect('code')
, node = new nodes.Code(tok.val, tok.buffer, tok.escape)
, block
, i = 1;
node.line = this.line();
while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i;
block = 'indent' == this.lookahead(i).type;
if (block) {
this.skip(i-1);
node.block = this.block();
}
return node;
},
/**
* comment
*/
parseComment: function(){
var tok = this.expect('comment')
, node;
if ('indent' == this.peek().type) {
node = new nodes.BlockComment(tok.val, this.block(), tok.buffer);
} else {
node = new nodes.Comment(tok.val, tok.buffer);
}
node.line = this.line();
return node;
},
/**
* doctype
*/
parseDoctype: function(){
var tok = this.expect('doctype')
, node = new nodes.Doctype(tok.val);
node.line = this.line();
return node;
},
/**
* filter attrs? text-block
*/
parseFilter: function(){
var block
, tok = this.expect('filter')
, attrs = this.accept('attrs');
this.lexer.pipeless = true;
block = this.parseTextBlock();
this.lexer.pipeless = false;
var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs);
node.line = this.line();
return node;
},
/**
* tag ':' attrs? block
*/
parseASTFilter: function(){
var block
, tok = this.expect('tag')
, attrs = this.accept('attrs');
this.expect(':');
block = this.block();
var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs);
node.line = this.line();
return node;
},
/**
* each block
*/
parseEach: function(){
var tok = this.expect('each')
, node = new nodes.Each(tok.code, tok.val, tok.key);
node.line = this.line();
node.block = this.block();
return node;
},
/**
* 'extends' name
*/
parseExtends: function(){
var path = require('path')
, fs = require('fs')
, dirname = path.dirname
, basename = path.basename
, join = path.join;
if (!this.filename)
throw new Error('the "filename" option is required to extend templates');
var path = this.expect('extends').val.trim()
, dir = dirname(this.filename);
var path = join(dir, path + '.jade')
, str = fs.readFileSync(path, 'utf8')
, parser = new Parser(str, path, this.options);
parser.blocks = this.blocks;
parser.contexts = this.contexts;
this.extending = parser;
// TODO: null node
return new nodes.Literal('');
},
/**
* 'block' name block
*/
parseBlock: function(){
var block = this.expect('block')
, mode = block.mode
, name = block.val.trim();
block = 'indent' == this.peek().type
? this.block()
: new nodes.Block(new nodes.Literal(''));
var prev = this.blocks[name];
if (prev) {
switch (prev.mode) {
case 'append':
block.nodes = block.nodes.concat(prev.nodes);
prev = block;
break;
case 'prepend':
block.nodes = prev.nodes.concat(block.nodes);
prev = block;
break;
}
}
block.mode = mode;
return this.blocks[name] = prev || block;
},
/**
* include block?
*/
parseInclude: function(){
var path = require('path')
, fs = require('fs')
, dirname = path.dirname
, basename = path.basename
, join = path.join;
var path = this.expect('include').val.trim()
, dir = dirname(this.filename);
if (!this.filename)
throw new Error('the "filename" option is required to use includes');
// no extension
if (!~basename(path).indexOf('.')) {
path += '.jade';
}
// non-jade
if ('.jade' != path.substr(-5)) {
var path = join(dir, path)
, str = fs.readFileSync(path, 'utf8');
return new nodes.Literal(str);
}
var path = join(dir, path)
, str = fs.readFileSync(path, 'utf8')
, parser = new Parser(str, path, this.options);
this.context(parser);
var ast = parser.parse();
this.context();
ast.filename = path;
if ('indent' == this.peek().type) {
ast.includeBlock().push(this.block());
}
return ast;
},
/**
* mixin block
*/
parseMixin: function(){
var tok = this.expect('mixin')
, name = tok.val
, args = tok.args;
var block = 'indent' == this.peek().type
? this.block()
: null;
return new nodes.Mixin(name, args, block);
},
/**
* indent (text | newline)* outdent
*/
parseTextBlock: function(){
var text = new nodes.Text;
text.line = this.line();
var spaces = this.expect('indent').val;
if (null == this._spaces) this._spaces = spaces;
var indent = Array(spaces - this._spaces + 1).join(' ');
while ('outdent' != this.peek().type) {
switch (this.peek().type) {
case 'newline':
text.push('\\n');
this.advance();
break;
case 'indent':
text.push('\\n');
this.parseTextBlock().nodes.forEach(function(node){
text.push(node);
});
text.push('\\n');
break;
default:
text.push(indent + this.advance().val);
}
}
if (spaces == this._spaces) this._spaces = null;
this.expect('outdent');
return text;
},
/**
* indent expr* outdent
*/
block: function(){
var block = new nodes.Block;
block.line = this.line();
this.expect('indent');
while ('outdent' != this.peek().type) {
if ('newline' == this.peek().type) {
this.advance();
} else {
block.push(this.parseExpr());
}
}
this.expect('outdent');
return block;
},
/**
* tag (attrs | class | id)* (text | code | ':')? newline* block?
*/
parseTag: function(){
// ast-filter look-ahead
var i = 2;
if ('attrs' == this.lookahead(i).type) ++i;
if (':' == this.lookahead(i).type) {
if ('indent' == this.lookahead(++i).type) {
return this.parseASTFilter();
}
}
var name = this.advance().val
, tag = new nodes.Tag(name)
, dot;
tag.line = this.line();
// (attrs | class | id)*
out:
while (true) {
switch (this.peek().type) {
case 'id':
case 'class':
var tok = this.advance();
tag.setAttribute(tok.type, "'" + tok.val + "'");
continue;
case 'attrs':
var obj = this.advance().attrs
, names = Object.keys(obj);
for (var i = 0, len = names.length; i < len; ++i) {
var name = names[i]
, val = obj[name];
tag.setAttribute(name, val);
}
continue;
default:
break out;
}
}
// check immediate '.'
if ('.' == this.peek().val) {
dot = tag.textOnly = true;
this.advance();
}
// (text | code | ':')?
switch (this.peek().type) {
case 'text':
tag.text = this.parseText();
break;
case 'code':
tag.code = this.parseCode();
break;
case ':':
this.advance();
tag.block = new nodes.Block;
tag.block.push(this.parseTag());
break;
}
// newline*
while ('newline' == this.peek().type) this.advance();
tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name);
// script special-case
if ('script' == tag.name) {
var type = tag.getAttribute('type');
if (!dot && type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) {
tag.textOnly = false;
}
}
// block?
if ('indent' == this.peek().type) {
if (tag.textOnly) {
this.lexer.pipeless = true;
tag.block = this.parseTextBlock();
this.lexer.pipeless = false;
} else {
var block = this.block();
if (tag.block) {
for (var i = 0, len = block.nodes.length; i < len; ++i) {
tag.block.push(block.nodes[i]);
}
} else {
tag.block = block;
}
}
}
return tag;
}
};
}); // module: parser.js
require.register("runtime.js", function(module, exports, require){
/*!
* Jade - runtime
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Lame Array.isArray() polyfill for now.
*/
if (!Array.isArray) {
Array.isArray = function(arr){
return '[object Array]' == Object.prototype.toString.call(arr);
};
}
/**
* Lame Object.keys() polyfill for now.
*/
if (!Object.keys) {
Object.keys = function(obj){
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(key);
}
}
return arr;
}
}
/**
* Render the given attributes object.
*
* @param {Object} obj
* @return {String}
* @api private
*/
exports.attrs = function attrs(obj){
var buf = []
, terse = obj.terse;
delete obj.terse;
var keys = Object.keys(obj)
, len = keys.length;
if (len) {
buf.push('');
for (var i = 0; i < len; ++i) {
var key = keys[i]
, val = obj[key];
if ('boolean' == typeof val || null == val) {
if (val) {
terse
? buf.push(key)
: buf.push(key + '="' + key + '"');
}
} else if ('class' == key && Array.isArray(val)) {
buf.push(key + '="' + exports.escape(val.join(' ')) + '"');
} else {
buf.push(key + '="' + exports.escape(val) + '"');
}
}
}
return buf.join(' ');
};
/**
* Escape the given string of `html`.
*
* @param {String} html
* @return {String}
* @api private
*/
exports.escape = function escape(html){
return String(html)
.replace(/&(?!\w+;)/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
/**
* Re-throw the given `err` in context to the
* the jade in `filename` at the given `lineno`.
*
* @param {Error} err
* @param {String} filename
* @param {String} lineno
* @api private
*/
exports.rethrow = function rethrow(err, filename, lineno){
if (!filename) throw err;
var context = 3
, str = require('fs').readFileSync(filename, 'utf8')
, lines = str.split('\n')
, start = Math.max(lineno - context, 0)
, end = Math.min(lines.length, lineno + context);
// Error context
var context = lines.slice(start, end).map(function(line, i){
var curr = i + start + 1;
return (curr == lineno ? ' > ' : ' ')
+ curr
+ '| '
+ line;
}).join('\n');
// Alter exception message
err.path = filename;
err.message = (filename || 'Jade') + ':' + lineno
+ '\n' + context + '\n\n' + err.message;
throw err;
};
}); // module: runtime.js
require.register("self-closing.js", function(module, exports, require){
/*!
* Jade - self closing tags
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
module.exports = [
'meta'
, 'img'
, 'link'
, 'input'
, 'area'
, 'base'
, 'col'
, 'br'
, 'hr'
];
}); // module: self-closing.js
require.register("utils.js", function(module, exports, require){
/*!
* Jade - utils
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Convert interpolation in the given string to JavaScript.
*
* @param {String} str
* @return {String}
* @api private
*/
var interpolate = exports.interpolate = function(str){
return str.replace(/(\\)?([#!]){(.*?)}/g, function(str, escape, flag, code){
return escape
? str
: "' + "
+ ('!' == flag ? '' : 'escape')
+ "((interp = " + code.replace(/\\'/g, "'")
+ ") == null ? '' : interp) + '";
});
};
/**
* Escape single quotes in `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
var escape = exports.escape = function(str) {
return str.replace(/'/g, "\\'");
};
/**
* Interpolate, and escape the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
exports.text = function(str){
return interpolate(escape(str));
};
}); // module: utils.js
window.jade = require("jade");
})();
| Olical/cdnjs | ajax/libs/jade/0.20.0/jade.js | JavaScript | mit | 64,460 |
/*!
* # Semantic UI 1.11.3 - Popup
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2014 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
!function(e,t,o,n){"use strict";e.fn.popup=function(i){var r,s=e(this),a=e(o),p=s.selector||"",l="ontouchstart"in o.documentElement,u=(new Date).getTime(),c=[],d=arguments[0],f="string"==typeof d,g=[].slice.call(arguments,1);return s.each(function(){var o,s,h,m,b,v=e.isPlainObject(i)?e.extend(!0,{},e.fn.popup.settings,i):e.extend({},e.fn.popup.settings),y=v.selector,w=v.className,P=v.error,T=v.metadata,C=v.namespace,x="."+v.namespace,k="module-"+C,S=e(this),O=e(v.context),E=v.target?e(v.target):S,j=e(t),A=e("body"),R=0,F=!1,D=this,H=S.data(k);b={initialize:function(){b.debug("Initializing",S),b.createID(),b.bind.events(),!b.exists()&&v.preserve&&b.create(),b.instantiate()},instantiate:function(){b.verbose("Storing instance",b),H=b,S.data(k,H)},refresh:function(){v.popup?o=e(v.popup).eq(0):v.inline&&(o=E.next(y.popup).eq(0)),v.popup?(o.addClass(w.loading),s=b.get.offsetParent(),o.removeClass(w.loading),v.movePopup&&b.has.popup()&&b.get.offsetParent(o)[0]!==s[0]&&(b.debug("Moving popup to the same offset parent as activating element"),o.detach().appendTo(s))):s=v.inline?b.get.offsetParent(E):b.has.popup()?b.get.offsetParent(o):A,s.is("html")&&(b.debug("Setting page as offset parent"),s=A)},reposition:function(){b.refresh(),b.set.position()},destroy:function(){b.debug("Destroying previous module"),o&&!v.preserve&&b.removePopup(),clearTimeout(b.hideTimer),clearTimeout(b.showTimer),j.off(h),S.off(x).removeData(k)},event:{start:function(){var t=e.isPlainObject(v.delay)?v.delay.show:v.delay;clearTimeout(b.hideTimer),b.showTimer=setTimeout(function(){!b.is.hidden()||b.is.active()&&b.is.dropdown()||b.show()},t)},end:function(){var t=e.isPlainObject(v.delay)?v.delay.hide:v.delay;clearTimeout(b.showTimer),b.hideTimer=setTimeout(function(){b.is.visible()&&b.hide()},t)},resize:function(){b.is.visible()&&b.set.position()}},create:function(){var t=S.data(T.html)||v.html,n=S.data(T.variation)||v.variation,i=S.data(T.title)||v.title,r=S.data(T.content)||S.attr("title")||v.content;t||r||i?(b.debug("Creating pop-up html"),t||(t=v.templates.popup({title:i,content:r})),o=e("<div/>").addClass(w.popup).addClass(n).data(T.activator,S).html(t),n&&o.addClass(n),v.inline?(b.verbose("Inserting popup element inline",o),o.insertAfter(S)):(b.verbose("Appending popup element to body",o),o.appendTo(O)),b.refresh(),v.hoverable&&b.bind.popup(),v.onCreate.call(o,D)):0!==E.next(y.popup).length?(b.verbose("Pre-existing popup found"),v.inline=!0,v.popup=E.next(y.popup).data(T.activator,S),b.refresh(),v.hoverable&&b.bind.popup()):v.popup?(v.popup.data(T.activator,S),b.verbose("Used popup specified in settings"),b.refresh(),v.hoverable&&b.bind.popup()):b.debug("No content specified skipping display",D)},createID:function(){m=(Math.random().toString(16)+"000000000").substr(2,8),h="."+m,b.verbose("Creating unique id for element",m)},toggle:function(){b.debug("Toggling pop-up"),b.is.hidden()?(b.debug("Popup is hidden, showing pop-up"),b.unbind.close(),b.show()):(b.debug("Popup is visible, hiding pop-up"),b.hide())},show:function(t){t=e.isFunction(t)?t:function(){},b.debug("Showing pop-up",v.transition),b.exists()?v.preserve||v.popup||b.refresh():b.create(),o&&b.set.position()&&(b.save.conditions(),v.exclusive&&b.hideAll(),b.animate.show(t))},hide:function(t){t=e.isFunction(t)?t:function(){},b.remove.visible(),b.unbind.close(),b.is.visible()&&(b.restore.conditions(),b.animate.hide(t))},hideAll:function(){e(y.popup).filter("."+w.visible).each(function(){e(this).data(T.activator).popup("hide")})},hideGracefully:function(t){t&&0===e(t.target).closest(y.popup).length?(b.debug("Click occurred outside popup hiding popup"),b.hide()):b.debug("Click was inside popup, keeping popup open")},exists:function(){return o?v.inline||v.popup?b.has.popup():o.closest(O).length>=1?!0:!1:!1},removePopup:function(){b.debug("Removing popup",o),b.has.popup()&&!v.popup&&(o.remove(),o=n),v.onRemove.call(o,D)},save:{conditions:function(){b.cache={title:S.attr("title")},b.cache.title&&S.removeAttr("title"),b.verbose("Saving original attributes",b.cache.title)}},restore:{conditions:function(){return b.cache&&b.cache.title&&(S.attr("title",b.cache.title),b.verbose("Restoring original attributes",b.cache.title)),!0}},animate:{show:function(t){t=e.isFunction(t)?t:function(){},v.transition&&e.fn.transition!==n&&S.transition("is supported")?(b.set.visible(),o.transition({animation:v.transition+" in",queue:!1,debug:v.debug,verbose:v.verbose,duration:v.duration,onComplete:function(){b.bind.close(),t.call(o,D),v.onVisible.call(o,D)}})):(b.set.visible(),o.stop().fadeIn(v.duration,v.easing,function(){b.bind.close(),t.call(o,D),v.onVisible.call(o,D)})),v.onShow.call(o,D)},hide:function(t){t=e.isFunction(t)?t:function(){},b.debug("Hiding pop-up"),v.transition&&e.fn.transition!==n&&S.transition("is supported")?o.transition({animation:v.transition+" out",queue:!1,duration:v.duration,debug:v.debug,verbose:v.verbose,onComplete:function(){b.reset(),t.call(o,D),v.onHidden.call(o,D)}}):o.stop().fadeOut(v.duration,v.easing,function(){b.reset(),t.call(o,D),v.onHidden.call(o,D)}),v.onHide.call(o,D)}},get:{id:function(){return m},startEvent:function(){return"hover"==v.on?l?"touchstart mouseenter":"mouseenter":"focus"==v.on?"focus":!1},scrollEvent:function(){return l?"touchmove scroll":"scroll"},endEvent:function(){return"hover"==v.on?"mouseleave":"focus"==v.on?"blur":!1},offsetParent:function(t){var o=t!==n?t[0]:S[0],i=o.parentNode,r=e(i);if(i)for(var s="none"===r.css("transform"),a="static"===r.css("position"),p=r.is("html");i&&!p&&a&&s;)i=i.parentNode,r=e(i),s="none"===r.css("transform"),a="static"===r.css("position"),p=r.is("html");return r&&r.length>0?r:e()},offstagePosition:function(n){var i={top:e(t).scrollTop(),bottom:e(t).scrollTop()+e(t).height(),left:0,right:e(t).width()},r={width:o.width(),height:o.height(),offset:o.offset()},s={},a=[];return n=n||!1,r.offset&&n&&(b.verbose("Checking if outside viewable area",r.offset),s={top:r.offset.top<i.top,bottom:r.offset.top+r.height>i.bottom,right:r.offset.left+r.width>i.right,left:r.offset.left<i.left}),e.each(s,function(e,t){t&&a.push(e)}),a.length>0?a.join(" "):!1},positions:function(){return{"top left":!1,"top center":!1,"top right":!1,"bottom left":!1,"bottom center":!1,"bottom right":!1,"left center":!1,"right center":!1}},nextPosition:function(e){var t=e.split(" "),o=t[0],n=t[1],i={top:"bottom",bottom:"top",left:"right",right:"left"},r={left:"center",center:"right",right:"left"},s={"top left":"top center","top center":"top right","top right":"right center","right center":"bottom right","bottom right":"bottom center","bottom center":"bottom left","bottom left":"left center","left center":"top left"},a="top"==o||"bottom"==o,p=!1,l=!1,u=!1;return F||(b.verbose("All available positions available"),F=b.get.positions()),b.debug("Recording last position tried",e),F[e]=!0,"opposite"===v.prefer&&(u=[i[o],n],u=u.join(" "),p=F[u]===!0,b.debug("Trying opposite strategy",u)),"adjacent"===v.prefer&&a&&(u=[o,r[n]],u=u.join(" "),l=F[u]===!0,b.debug("Trying adjacent strategy",u)),(l||p)&&(b.debug("Using backup position",u),u=s[e]),u}},set:{position:function(i,r){var a,p,l,u=(e(t).width(),e(t).height(),E.outerWidth()),c=E.outerHeight(),d=o.outerWidth(),f=o.outerHeight(),g=s.outerWidth(),h=s.outerHeight(),m=v.distanceAway,y=E[0],C=v.inline?parseInt(t.getComputedStyle(y).getPropertyValue("margin-top"),10):0,x=v.inline?parseInt(t.getComputedStyle(y).getPropertyValue(b.is.rtl()?"margin-right":"margin-left"),10):0,k=v.inline||v.popup?E.position():E.offset();switch(i=i||S.data(T.position)||v.position,r=r||S.data(T.offset)||v.offset,R==v.maxSearchDepth&&v.lastResort&&(b.debug("Using last resort position to display",v.lastResort),i=v.lastResort),v.inline&&(b.debug("Adding targets margin to calculation"),"left center"==i||"right center"==i?(r+=C,m+=-x):"top left"==i||"top center"==i||"top right"==i?(r+=x,m-=C):(r+=x,m+=C)),b.debug("Calculating popup positioning",i),a=i,b.is.rtl()&&(a=a.replace(/left|right/g,function(e){return"left"==e?"right":"left"}),b.debug("RTL: Popup positioning updated",a)),a){case"top left":p={top:"auto",bottom:h-k.top+m,left:k.left+r,right:"auto"};break;case"top center":p={bottom:h-k.top+m,left:k.left+u/2-d/2+r,top:"auto",right:"auto"};break;case"top right":p={bottom:h-k.top+m,right:g-k.left-u-r,top:"auto",left:"auto"};break;case"left center":p={top:k.top+c/2-f/2+r,right:g-k.left+m,left:"auto",bottom:"auto"};break;case"right center":p={top:k.top+c/2-f/2+r,left:k.left+u+m,bottom:"auto",right:"auto"};break;case"bottom left":p={top:k.top+c+m,left:k.left+r,bottom:"auto",right:"auto"};break;case"bottom center":p={top:k.top+c+m,left:k.left+u/2-d/2+r,bottom:"auto",right:"auto"};break;case"bottom right":p={top:k.top+c+m,right:g-k.left-u-r,left:"auto",bottom:"auto"}}if(p===n&&b.error(P.invalidPosition,i),b.debug("Calculated popup positioning values",p),o.css(p).removeClass(w.position).addClass(i).addClass(w.loading),l=b.get.offstagePosition(i)){if(b.debug("Popup cant fit into viewport",l),R<v.maxSearchDepth)return R++,i=b.get.nextPosition(i),b.debug("Trying new position",i),o?b.set.position(i):!1;if(!v.lastResort)return b.debug("Popup could not find a position in view",o),b.error(P.cannotPlace,D),b.remove.attempts(),b.remove.loading(),b.reset(),!1}return b.debug("Position is on stage",i),b.remove.attempts(),b.set.fluidWidth(),b.remove.loading(),!0},fluidWidth:function(){v.setFluidWidth&&o.hasClass(w.fluid)&&o.css("width",s.width())},visible:function(){S.addClass(w.visible)}},remove:{loading:function(){o.removeClass(w.loading)},visible:function(){S.removeClass(w.visible)},attempts:function(){b.verbose("Resetting all searched positions"),R=0,F=!1}},bind:{events:function(){b.debug("Binding popup events to module"),"click"==v.on?S.on("click"+x,b.toggle):b.get.startEvent()&&S.on(b.get.startEvent()+x,b.event.start).on(b.get.endEvent()+x,b.event.end),v.target&&b.debug("Target set to element",E),j.on("resize"+h,b.event.resize)},popup:function(){b.verbose("Allowing hover events on popup to prevent closing"),o&&b.has.popup()&&o.on("mouseenter"+x,b.event.start).on("mouseleave"+x,b.event.end)},close:function(){(v.hideOnScroll===!0||"auto"==v.hideOnScroll&&"click"!=v.on)&&(a.one(b.get.scrollEvent()+h,b.hideGracefully),O.one(b.get.scrollEvent()+h,b.hideGracefully)),"click"==v.on&&v.closable&&(b.verbose("Binding popup close event to document"),a.on("click"+h,function(e){b.verbose("Pop-up clickaway intent detected"),b.hideGracefully.call(D,e)}))}},unbind:{close:function(){(v.hideOnScroll===!0||"auto"==v.hideOnScroll&&"click"!=v.on)&&(a.off("scroll"+h,b.hide),O.off("scroll"+h,b.hide)),"click"==v.on&&v.closable&&(b.verbose("Removing close event from document"),a.off("click"+h))}},has:{popup:function(){return o&&o.length>0}},is:{active:function(){return S.hasClass(w.active)},animating:function(){return o&&o.is(":animated")||o.hasClass(w.animating)},visible:function(){return o&&o.is(":visible")},dropdown:function(){return S.hasClass(w.dropdown)},hidden:function(){return!b.is.visible()},rtl:function(){return"rtl"==S.css("direction")}},reset:function(){b.remove.visible(),v.preserve?e.fn.transition!==n&&o.transition("remove transition"):b.removePopup()},setting:function(t,o){if(e.isPlainObject(t))e.extend(!0,v,t);else{if(o===n)return v[t];v[t]=o}},internal:function(t,o){if(e.isPlainObject(t))e.extend(!0,b,t);else{if(o===n)return b[t];b[t]=o}},debug:function(){v.debug&&(v.performance?b.performance.log(arguments):(b.debug=Function.prototype.bind.call(console.info,console,v.name+":"),b.debug.apply(console,arguments)))},verbose:function(){v.verbose&&v.debug&&(v.performance?b.performance.log(arguments):(b.verbose=Function.prototype.bind.call(console.info,console,v.name+":"),b.verbose.apply(console,arguments)))},error:function(){b.error=Function.prototype.bind.call(console.error,console,v.name+":"),b.error.apply(console,arguments)},performance:{log:function(e){var t,o,n;v.performance&&(t=(new Date).getTime(),n=u||t,o=t-n,u=t,c.push({Name:e[0],Arguments:[].slice.call(e,1)||"",Element:D,"Execution Time":o})),clearTimeout(b.performance.timer),b.performance.timer=setTimeout(b.performance.display,100)},display:function(){var t=v.name+":",o=0;u=!1,clearTimeout(b.performance.timer),e.each(c,function(e,t){o+=t["Execution Time"]}),t+=" "+o+"ms",p&&(t+=" '"+p+"'"),(console.group!==n||console.table!==n)&&c.length>0&&(console.groupCollapsed(t),console.table?console.table(c):e.each(c,function(e,t){console.log(t.Name+": "+t["Execution Time"]+"ms")}),console.groupEnd()),c=[]}},invoke:function(t,o,i){var s,a,p,l=H;return o=o||g,i=D||i,"string"==typeof t&&l!==n&&(t=t.split(/[\. ]/),s=t.length-1,e.each(t,function(o,i){var r=o!=s?i+t[o+1].charAt(0).toUpperCase()+t[o+1].slice(1):t;if(e.isPlainObject(l[r])&&o!=s)l=l[r];else{if(l[r]!==n)return a=l[r],!1;if(!e.isPlainObject(l[i])||o==s)return l[i]!==n?(a=l[i],!1):!1;l=l[i]}})),e.isFunction(a)?p=a.apply(i,o):a!==n&&(p=a),e.isArray(r)?r.push(p):r!==n?r=[r,p]:p!==n&&(r=p),a}},f?(H===n&&b.initialize(),b.invoke(d)):(H!==n&&H.invoke("destroy"),b.initialize())}),r!==n?r:this},e.fn.popup.settings={name:"Popup",debug:!1,verbose:!0,performance:!0,namespace:"popup",onCreate:function(){},onRemove:function(){},onShow:function(){},onVisible:function(){},onHide:function(){},onHidden:function(){},variation:"",content:!1,html:!1,title:!1,on:"hover",closable:!0,hideOnScroll:"auto",exclusive:!0,context:"body",position:"top left",prefer:"opposite",lastResort:!1,delay:{show:30,hide:0},setFluidWidth:!0,movePopup:!0,target:!1,popup:!1,inline:!1,preserve:!1,hoverable:!1,duration:200,easing:"easeOutQuint",transition:"scale",distanceAway:0,offset:0,maxSearchDepth:20,error:{invalidPosition:"The position you specified is not a valid position",cannotPlace:"No visible position could be found for the popup",method:"The method you called is not defined."},metadata:{activator:"activator",content:"content",html:"html",offset:"offset",position:"position",title:"title",variation:"variation"},className:{active:"active",animating:"animating",dropdown:"dropdown",fluid:"fluid",loading:"loading",popup:"ui popup",position:"top left center bottom right",visible:"visible"},selector:{popup:".ui.popup"},templates:{escape:function(e){var t=/[&<>"'`]/g,o=/[&<>"'`]/,n={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},i=function(e){return n[e]};return o.test(e)?e.replace(t,i):e},popup:function(t){var o="",i=e.fn.popup.settings.templates.escape;return typeof t!==n&&(typeof t.title!==n&&t.title&&(t.title=i(t.title),o+='<div class="header">'+t.title+"</div>"),typeof t.content!==n&&t.content&&(t.content=i(t.content),o+='<div class="content">'+t.content+"</div>")),o}}},e.extend(e.easing,{easeOutQuad:function(e,t,o,n,i){return-n*(t/=i)*(t-2)+o}})}(jQuery,window,document); | ematsusaka/cdnjs | ajax/libs/semantic-ui/1.11.3/components/popup.min.js | JavaScript | mit | 14,974 |
/*! 3.2.1 */
!function(){function a(a,b){window.XMLHttpRequest.prototype[a]=b(window.XMLHttpRequest.prototype[a])}function b(a,b,c,d,g,h){function j(){return"input"===b[0].tagName.toLowerCase()&&b.attr("type")&&"file"===b.attr("type").toLowerCase()}function k(b){c.ngMultiple&&b.attr("multiple",g(c.ngMultiple)(a)),c.accept&&b.attr("accept",c.accept),c.ngCapture&&b.attr("capture",g(c.ngCapture)(a)),c.ngDisabled&&b.attr("disabled",g(c.ngDisabled)(a));var j=!1;b.bind("change",function(k){if(!j){j=!0;try{var l=k.__files_||k.target&&k.target.files,m=[],n=[],o=g(c.ngAccept);for(i=0;i<l.length;i++){var p=l.item(i);f(a,o,p,k)?m.push(p):n.push(p)}console.log("change"+m),e(g,h,a,d,c,c.ngFileChange||c.ngFileSelect,m,n,k),0==m.length&&(b[0].value=m),b.attr("__afu_gen__")&&b.remove()}finally{j=!1}}})}function l(a){m(a),j()&&a.preventDefault()}function m(f){if(!b.attr("disabled")){fileElem=angular.element('<input type="file">');for(var i=0;i<b[0].attributes.length;i++){var m=b[0].attributes[i];fileElem.attr(m.name,m.value)}j()?(b.replaceWith(fileElem),b=fileElem):(fileElem.css("width","0px").css("height","0px").css("position","absolute").css("padding",0).css("margin",0).css("overflow","hidden").attr("tabindex","-1").css("opacity",0).attr("__afu_gen__",!0),b.attr("__refElem__",!0),fileElem[0].__refElem__=b[0],b.parent()[0].insertBefore(fileElem[0],b[0]),b.css("overflow","hidden")),k(fileElem),e(g,h,a,d,c,c.ngFileChange||c.ngFileSelect,[],[],f,!0),fileElem[0].click(),j()&&b.bind("click",l)}}b.bind("click",l)}function c(a,b,c,g,h,j,k){function l(a,b,c){var d=!0,e=c.dataTransfer.items;if(null!=e)for(i=0;i<e.length&&d;i++)d=d&&("file"==e[i].kind||""==e[i].kind)&&f(a,s,e[i],c);var g=h(b.dragOverClass)(a,{$event:c});return g&&(g.delay&&(r=g.delay),g.accept&&(g=d?g.accept:g.reject)),g||b.dragOverClass||"dragover"}function m(b,c,d,e){function g(c){f(a,s,c,b)?l.push(c):m.push(c)}function h(a,b,c){if(null!=b)if(b.isDirectory){var d=(c||"")+b.name;g({name:b.name,type:"directory",path:d});var e=b.createReader(),f=[];o++;var j=function(){e.readEntries(function(d){try{if(d.length)f=f.concat(Array.prototype.slice.call(d||[],0)),j();else{for(i=0;i<f.length;i++)h(a,f[i],(c?c:"")+b.name+"/");o--}}catch(e){o--,console.error(e)}},function(){o--})};j()}else o++,b.file(function(a){try{o--,a.path=(c?c:"")+a.name,g(a)}catch(b){o--,console.error(b)}},function(){o--})}var l=[],m=[],n=b.dataTransfer.items,o=0;if(n&&n.length>0&&"file"!=k.protocol())for(i=0;i<n.length;i++){if(n[i].webkitGetAsEntry&&n[i].webkitGetAsEntry()&&n[i].webkitGetAsEntry().isDirectory){var p=n[i].webkitGetAsEntry();if(p.isDirectory&&!d)continue;null!=p&&h(l,p)}else{var q=n[i].getAsFile();null!=q&&g(q)}if(!e&&l.length>0)break}else{var r=b.dataTransfer.files;if(null!=r)for(i=0;i<r.length&&(g(r.item(i)),e||!(l.length>0));i++);}var t=0;!function u(a){j(function(){if(o)10*t++<2e4&&u(10);else{if(!e&&l.length>1){for(i=0;"directory"==l[i].type;)i++;l=[l[i]]}c(l,m)}},a||0)}()}var n=d();if(c.dropAvailable&&j(function(){a.dropAvailable?a.dropAvailable.value=n:a.dropAvailable=n}),!n)return 0!=h(c.hideOnDropNotAvailable)(a)&&b.css("display","none"),void 0;var o,p=null,q=h(c.stopPropagation),r=1,s=h(c.ngAccept),t=h(c.ngDisabled);b[0].addEventListener("dragover",function(d){if(!t(a)){if(d.preventDefault(),q(a)&&d.stopPropagation(),navigator.userAgent.indexOf("Chrome")>-1){var e=d.dataTransfer.effectAllowed;d.dataTransfer.dropEffect="move"===e||"linkMove"===e?"move":"copy"}j.cancel(p),a.actualDragOverClass||(o=l(a,c,d)),b.addClass(o)}},!1),b[0].addEventListener("dragenter",function(b){t(a)||(b.preventDefault(),q(a)&&b.stopPropagation())},!1),b[0].addEventListener("dragleave",function(){t(a)||(p=j(function(){b.removeClass(o),o=null},r||1))},!1),b[0].addEventListener("drop",function(d){t(a)||(d.preventDefault(),q(a)&&d.stopPropagation(),b.removeClass(o),o=null,m(d,function(b,f){e(h,j,a,g,c,c.ngFileChange||c.ngFileDrop,b,f,d)},0!=h(c.allowDir)(a),c.multiple||h(c.ngMultiple)(a)))},!1)}function d(){var a=document.createElement("div");return"draggable"in a&&"ondrop"in a}function e(a,b,c,d,e,f,g,h,i,j){function k(){d&&(a(e.ngModel).assign(c,g),b(function(){d&&d.$setViewValue(null!=g&&0==g.length?null:g)})),e.ngModelRejected&&a(e.ngModelRejected).assign(c,h),f&&a(f)(c,{$files:g,$rejectedFiles:h,$event:i})}console.log("aa "+g),j?k():b(function(){k()})}function f(a,b,c,d){var e=b(a,{$file:c,$event:d});if(null==e)return!0;if(angular.isString(e)){var f=new RegExp(g(e),"gi");e=null!=c.type&&c.type.match(f)||null!=c.name&&c.name.match(f)}return e}function g(a){if(a.length>2&&"/"===a[0]&&"/"===a[a.length-1])return a.substring(1,a.length-1);var b=a.split(","),c="";if(b.length>1)for(i=0;i<b.length;i++)c+="("+g(b[i])+")",i<b.length-1&&(c+="|");else 0==a.indexOf(".")&&(a="*"+a),c="^"+a.replace(new RegExp("[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\-]","g"),"\\$&")+"$",c=c.replace(/\\\*/g,".*").replace(/\\\?/g,".");return c}var h,i;window.XMLHttpRequest&&!window.XMLHttpRequest.__isFileAPIShim&&a("setRequestHeader",function(a){return function(b,c){if("__setXHR_"===b){var d=c(this);d instanceof Function&&d(this)}else a.apply(this,arguments)}});var j=angular.module("angularFileUpload",[]);j.version="3.2.1",j.service("$upload",["$http","$q","$timeout",function(a,b,c){function d(d){d.method=d.method||"POST",d.headers=d.headers||{},d.transformRequest=d.transformRequest||function(b,c){return window.ArrayBuffer&&b instanceof window.ArrayBuffer?b:a.defaults.transformRequest[0](b,c)};var e=b.defer(),f=e.promise;return d.headers.__setXHR_=function(){return function(a){a&&(d.__XHR=a,d.xhrFn&&d.xhrFn(a),a.upload.addEventListener("progress",function(a){a.config=d,e.notify?e.notify(a):f.progress_fn&&c(function(){f.progress_fn(a)})},!1),a.upload.addEventListener("load",function(a){a.lengthComputable&&(a.config=d,e.notify?e.notify(a):f.progress_fn&&c(function(){f.progress_fn(a)}))},!1))}},a(d).then(function(a){e.resolve(a)},function(a){e.reject(a)},function(a){e.notify(a)}),f.success=function(a){return f.then(function(b){a(b.data,b.status,b.headers,d)}),f},f.error=function(a){return f.then(null,function(b){a(b.data,b.status,b.headers,d)}),f},f.progress=function(a){return f.progress_fn=a,f.then(null,null,function(b){a(b)}),f},f.abort=function(){return d.__XHR&&c(function(){d.__XHR.abort()}),f},f.xhr=function(a){return d.xhrFn=function(b){return function(){b&&b.apply(f,arguments),a.apply(f,arguments)}}(d.xhrFn),f},f}this.upload=function(a){return a.headers=a.headers||{},a.headers["Content-Type"]=void 0,a.transformRequest=a.transformRequest?"[object Array]"===Object.prototype.toString.call(a.transformRequest)?a.transformRequest:[a.transformRequest]:[],a.transformRequest.push(function(b){var c=new FormData,d={};for(h in a.fields)a.fields.hasOwnProperty(h)&&(d[h]=a.fields[h]);if(b&&(d.data=b),a.formDataAppender)for(h in d)d.hasOwnProperty(h)&&a.formDataAppender(c,h,d[h]);else for(h in d)if(d.hasOwnProperty(h)){var e=d[h];void 0!==e&&("[object String]"===Object.prototype.toString.call(e)?c.append(h,e):a.sendObjectsAsJsonBlob&&"object"==typeof e?c.append(h,new Blob([e],{type:"application/json"})):c.append(h,JSON.stringify(e)))}if(null!=a.file){var f=a.fileFormDataName||"file";if("[object Array]"===Object.prototype.toString.call(a.file)){var g="[object String]"===Object.prototype.toString.call(f);for(i=0;i<a.file.length;i++)c.append(g?f:f[i],a.file[i],a.fileName&&a.fileName[i]||a.file[i].name)}else c.append(f,a.file,a.fileName||a.file.name)}return c}),d(a)},this.http=function(a){return d(a)}}]),j.directive("ngFileSelect",["$parse","$timeout","$compile",function(a,c,d){return{restrict:"AEC",require:"?ngModel",link:function(e,f,g,h){b(e,f,g,h,a,c,d)}}}]),j.directive("ngFileDrop",["$parse","$timeout","$location",function(a,b,d){return{restrict:"AEC",require:"?ngModel",link:function(e,f,g,h){c(e,f,g,h,a,b,d)}}}]),j.directive("ngNoFileDrop",function(){return function(a,b){d()&&b.css("display","none")}}),j.directive("ngFileDropAvailable",["$parse","$timeout",function(a,b){return function(c,e,f){if(d()){var g=a(f.ngFileDropAvailable);b(function(){g(c)})}}}]);var k=angular.module("ngFileUpload",[]);for(h in j)j.hasOwnProperty(h)&&(k[h]=j[h])}(); | ljharb/cdnjs | ajax/libs/danialfarid-angular-file-upload/3.2.1/angular-file-upload.min.js | JavaScript | mit | 8,150 |
/*
SoundManager 2: Javascript Sound for the Web
--------------------------------------------
http://schillmania.com/projects/soundmanager2/
Copyright (c) 2007, Scott Schiller. All rights reserved.
Code provided under the BSD License:
http://schillmania.com/projects/soundmanager2/license.txt
V2.96a.20100822
*/
(function(j){function ga(xa,ya){function ha(){if(b.debugURLParam.test(N))b.debugMode=true}this.flashVersion=8;this.debugFlash=this.debugMode=false;this.useConsole=true;this.waitForWindowLoad=this.consoleOnly=false;this.nullURL="about:blank";this.allowPolling=true;this.useFastPolling=false;this.useMovieStar=true;this.bgColor="#ffffff";this.useHighPerformance=false;this.flashLoadTimeout=1E3;this.wmode=null;this.allowFullScreen=true;this.allowScriptAccess="always";this.useHTML5Audio=this.useFlashBlock=
false;this.html5Test=/^probably$/i;this.audioFormats={mp3:{type:['audio/mpeg; codecs="mp3"',"audio/mpeg","audio/mp3","audio/MPA","audio/mpa-robust"],required:true},mp4:{related:["aac","m4a"],type:['audio/mp4; codecs="mp4a.40.2"',"audio/aac","audio/x-m4a","audio/MP4A-LATM","audio/mpeg4-generic"],required:true},ogg:{type:["audio/ogg; codecs=vorbis"],required:false},wav:{type:['audio/wav; codecs="1"',"audio/wav","audio/wave","audio/x-wav"],required:false}};this.defaultOptions={autoLoad:false,stream:true,
autoPlay:false,loops:1,onid3:null,onload:null,whileloading:null,onplay:null,onpause:null,onresume:null,whileplaying:null,onstop:null,onfinish:null,onbeforefinish:null,onbeforefinishtime:5E3,onbeforefinishcomplete:null,onjustbeforefinish:null,onjustbeforefinishtime:200,multiShot:true,multiShotEvents:false,position:null,pan:0,type:null,volume:100};this.flash9Options={isMovieStar:null,usePeakData:false,useWaveformData:false,useEQData:false,onbufferchange:null,ondataerror:null};this.movieStarOptions=
{onmetadata:null,useVideo:false,bufferTime:3,serverURL:null,onconnect:null};this.version=null;this.versionNumber="V2.96a.20100822";this.movieURL=null;this.url=xa||null;this.altURL=null;this.enabled=this.swfLoaded=false;this.o=null;this.movieID="sm2-container";this.id=ya||"sm2movie";this.swfCSS={swfDefault:"movieContainer",swfError:"swf_error",swfTimedout:"swf_timedout",swfUnblocked:"swf_unblocked",sm2Debug:"sm2_debug",highPerf:"high_performance",flashDebug:"flash_debug"};this.oMC=null;this.sounds=
{};this.soundIDs=[];this.isFullScreen=this.muted=false;this.isIE=navigator.userAgent.match(/MSIE/i);this.isSafari=navigator.userAgent.match(/safari/i);this.debugID="soundmanager-debug";this.debugURLParam=/([#?&])debug=1/i;this.didFlashBlock=this.specialWmodeCase=false;this.filePattern=null;this.filePatterns={flash8:/\.mp3(\?.*)?$/i,flash9:/\.mp3(\?.*)?$/i};this.baseMimeTypes=/^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i;this.netStreamMimeTypes=/^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i;this.netStreamTypes=
["aac","flv","mov","mp4","m4v","f4v","m4a","mp4v","3gp","3g2"];this.netStreamPattern=RegExp("\\.("+this.netStreamTypes.join("|")+")(\\?.*)?$","i");this.mimePattern=this.baseMimeTypes;this.features={buffering:false,peakData:false,waveformData:false,eqData:false,movieStar:false};this.sandbox={type:null,types:{remote:"remote (domain-based) rules",localWithFile:"local with file access (no internet access)",localWithNetwork:"local with network (internet access only, no local access)",localTrusted:"local, trusted (local+internet access)"},
description:null,noRemote:null,noLocal:null};this.hasHTML5=null;this.html5={usingFlash:null};this.ignoreFlash=false;var W,b=this,y,t=navigator.userAgent,N=j.location.href.toString(),k=this.flashVersion,ia,O,z=[],E=false,F=false,p=false,v=false,ja=false,G,q,ka,A,B,la,X,Y,w,ma,P,Q,H,Z,na,R,$,oa,pa,I,qa,J=null,aa=null,K,ba,L,S,ca,n,T=false,da=false,ra,sa,C=null,ta,U,x=false,M,u,ea,ua,va=t.match(/pre\//i),za=t.match(/(ipad|iphone)/i);t.match(/mobile/i);var fa=typeof document.hasFocus!=="undefined"?document.hasFocus():
null,D=typeof document.hasFocus==="undefined"&&this.isSafari,wa=!D;this._use_maybe=N.match(/sm2\-useHTML5Maybe\=1/i);this._overHTTP=document.location?document.location.protocol.match(/http/i):null;this.useAltURL=!this._overHTTP;if(za||va){b.useHTML5Audio=true;b.ignoreFlash=true}if(va||this._use_maybe)b.html5Test=/^(probably|maybe)$/i;this.supported=function(){return C?p&&!v:b.useHTML5Audio&&b.hasHTML5};this.getMovie=function(c){return b.isIE?j[c]:b.isSafari?y(c)||document[c]:y(c)};this.loadFromXML=
function(c){try{b.o._loadFromXML(c)}catch(a){I();return true}};this.createSound=function(c){function a(){f=S(f);b.sounds[e.id]=new W(e);b.soundIDs.push(e.id);return b.sounds[e.id]}var f=null,g=null,e=null;if(!p)throw ca("soundManager.createSound(): "+K("notReady"),arguments.callee.caller);if(arguments.length===2)c={id:arguments[0],url:arguments[1]};e=f=q(c);if(n(e.id,true))return b.sounds[e.id];if(U(e)){g=a();g._setup_html5(e)}else{if(k>8&&b.useMovieStar){if(e.isMovieStar===null)e.isMovieStar=e.serverURL||
(e.type?e.type.match(b.netStreamPattern):false)||e.url.match(b.netStreamPattern)?true:false;if(e.isMovieStar)if(e.usePeakData)e.usePeakData=false}g=a();if(k===8)b.o._createSound(e.id,e.onjustbeforefinishtime,e.loops||1);else{b.o._createSound(e.id,e.url,e.onjustbeforefinishtime,e.usePeakData,e.useWaveformData,e.useEQData,e.isMovieStar,e.isMovieStar?e.useVideo:false,e.isMovieStar?e.bufferTime:false,e.loops||1,e.serverURL,e.duration||null,e.totalBytes||null,e.autoPlay,true);if(!e.serverURL){g.connected=
true;e.onconnect&&e.onconnect.apply(g)}}}if(e.autoLoad||e.autoPlay)if(g)if(b.isHTML5){g.autobuffer="auto";g.preload="auto"}else g.load(e);e.autoPlay&&g.play();return g};this.createVideo=function(c){if(arguments.length===2)c={id:arguments[0],url:arguments[1]};if(k>=9){c.isMovieStar=true;c.useVideo=true}else return false;return b.createSound(c)};this.destroyVideo=this.destroySound=function(c,a){if(!n(c))return false;for(var f=0;f<b.soundIDs.length;f++)b.soundIDs[f]===c&&b.soundIDs.splice(f,1);b.sounds[c].unload();
a||b.sounds[c].destruct();delete b.sounds[c]};this.load=function(c,a){if(!n(c))return false;return b.sounds[c].load(a)};this.unload=function(c){if(!n(c))return false;return b.sounds[c].unload()};this.start=this.play=function(c,a){if(!p)throw ca("soundManager.play(): "+K("notReady"),arguments.callee.caller);if(!n(c)){a instanceof Object||(a={url:a});if(a&&a.url){a.id=c;return b.createSound(a).play()}else return false}return b.sounds[c].play(a)};this.setPosition=function(c,a){if(!n(c))return false;
return b.sounds[c].setPosition(a)};this.stop=function(c){if(!n(c))return false;return b.sounds[c].stop()};this.stopAll=function(){for(var c in b.sounds)b.sounds[c]instanceof W&&b.sounds[c].stop()};this.pause=function(c){if(!n(c))return false;return b.sounds[c].pause()};this.pauseAll=function(){for(var c=b.soundIDs.length;c--;)b.sounds[b.soundIDs[c]].pause()};this.resume=function(c){if(!n(c))return false;return b.sounds[c].resume()};this.resumeAll=function(){for(var c=b.soundIDs.length;c--;)b.sounds[b.soundIDs[c]].resume()};
this.togglePause=function(c){if(!n(c))return false;return b.sounds[c].togglePause()};this.setPan=function(c,a){if(!n(c))return false;return b.sounds[c].setPan(a)};this.setVolume=function(c,a){if(!n(c))return false;return b.sounds[c].setVolume(a)};this.mute=function(c){var a=0;if(typeof c!=="string")c=null;if(c){if(!n(c))return false;return b.sounds[c].mute()}else{for(a=b.soundIDs.length;a--;)b.sounds[b.soundIDs[a]].mute();b.muted=true}};this.muteAll=function(){b.mute()};this.unmute=function(c){if(typeof c!==
"string")c=null;if(c){if(!n(c))return false;return b.sounds[c].unmute()}else{for(c=b.soundIDs.length;c--;)b.sounds[b.soundIDs[c]].unmute();b.muted=false}};this.unmuteAll=function(){b.unmute()};this.toggleMute=function(c){if(!n(c))return false;return b.sounds[c].toggleMute()};this.getMemoryUse=function(){if(k===8)return 0;if(b.o)return parseInt(b.o._getMemoryUse(),10)};this.disable=function(c){if(typeof c==="undefined")c=false;if(v)return false;v=true;for(var a=b.soundIDs.length;a--;)pa(b.sounds[b.soundIDs[a]]);
G(c);j.removeEventListener&&j.removeEventListener("load",B,false)};this.canPlayMIME=function(c){var a;if(b.hasHTML5)a=M({type:c});return!C||a?a:c?c.match(b.mimePattern)?true:false:null};this.canPlayURL=function(c){var a;if(b.hasHTML5)a=M(c);return!C||a?a:c?c.match(b.filePattern)?true:false:null};this.canPlayLink=function(c){if(typeof c.type!=="undefined"&&c.type)if(b.canPlayMIME(c.type))return true;return b.canPlayURL(c.href)};this.getSoundById=function(c){if(!c)throw Error("SoundManager.getSoundById(): sID is null/undefined");
return b.sounds[c]};this.onready=function(c,a){if(c&&c instanceof Function){a||(a=j);ka(c,a);A();return true}else throw K("needFunction");};this.oninitmovie=function(){};this.onload=function(){};this.onerror=function(){};this.getMoviePercent=function(){return b.o&&typeof b.o.PercentLoaded!=="undefined"?b.o.PercentLoaded():null};this._wD=this._writeDebug=function(){};this._debug=function(){};this.reboot=function(){for(var c=b.soundIDs.length;c--;)b.sounds[b.soundIDs[c]].destruct();try{if(b.isIE)aa=
b.o.innerHTML;J=b.o.parentNode.removeChild(b.o)}catch(a){}J=aa=null;v=F=E=da=T=p=b.enabled=false;b.swfLoaded=false;b.soundIDs=[];b.sounds=[];b.o=null;for(c=z.length;c--;)z[c].fired=false;j.setTimeout(function(){b.beginDelayedInit()},20)};this.destruct=function(){b.disable(true)};this.beginDelayedInit=function(){ja=true;H();setTimeout(X,500);setTimeout(ma,20)};U=function(c){return(c.type?M({type:c.type}):false)||M(c.url)};M=function(c){if(!b.useHTML5Audio||!b.hasHTML5)return false;var a,f=b.audioFormats;
if(!u){u=[];for(a in f)if(f.hasOwnProperty(a)){u.push(a);if(f[a].related)u=u.concat(f[a].related)}u=RegExp("\\.("+u.join("|")+")","i")}a=typeof c.type!=="undefined"?c.type:null;c=typeof c==="string"?c.toLowerCase().match(u):null;if(!c||!c.length){if(!a)return false}else c=c[0].substr(1);if(c&&typeof b.html5[c]!=="undefined")return b.html5[c];else{if(!a)if(c&&b.html5[c])return b.html5[c];else a="audio/"+c;a=b.html5.canPlayType(a);return b.html5[c]=a}};ua=function(){function c(l){var h,d,i=false;if(!a||
typeof a.canPlayType!=="function")return false;if(l instanceof Array){h=0;for(d=l.length;h<d&&!i;h++)if(b.html5[l[h]]||a.canPlayType(l[h]).match(b.html5Test)){i=true;b.html5[l[h]]=true}return i}else return(l=a&&typeof a.canPlayType==="function"?a.canPlayType(l):false)&&(l.match(b.html5Test)?true:false)}if(!b.useHTML5Audio||typeof Audio==="undefined")return false;var a=typeof Audio!=="undefined"?new Audio:null,f,g={},e,o;e=b.audioFormats;for(f in e)if(e.hasOwnProperty(f)){g[f]=c(e[f].type);if(e[f]&&
e[f].related)for(o=0;o<e[f].related.length;o++)b.html5[e[f].related[o]]=g[f]}g.canPlayType=a?c:null;b.html5=q(b.html5,g)};P={};y=function(c){return document.getElementById(c)};K=function(){var c=Array.prototype.slice.call(arguments),a=c.shift();a=P&&P[a]?P[a]:"";var f,g;if(a&&c&&c.length){f=0;for(g=c.length;f<g;f++)a=a.replace("%s",c[f])}return a};S=function(c){if(k===8&&c.loops>1&&c.stream)c.stream=false;return c};ca=function(c,a){var f;if(!a)return Error("Error: "+c);typeof console!=="undefined"&&
typeof console.trace!=="undefined"&&console.trace();f="Error: "+c+". \nCaller: "+a.toString();return Error(f)};ia=function(){return false};pa=function(c){for(var a in c)if(c.hasOwnProperty(a)&&typeof c[a]==="function")c[a]=ia};I=function(c){if(typeof c==="undefined")c=false;if(v||c)b.disable(c)};qa=function(c){var a=null;if(c)if(c.match(/\.swf(\?\.*)?$/i)){if(a=c.substr(c.toLowerCase().lastIndexOf(".swf?")+4))return c}else if(c.lastIndexOf("/")!==c.length-1)c+="/";return(c&&c.lastIndexOf("/")!==-1?
c.substr(0,c.lastIndexOf("/")+1):"./")+b.movieURL};Y=function(){if(k!==8&&k!==9)b.flashVersion=8;var c=b.debugMode||b.debugFlash?"_debug.swf":".swf";if(b.flashVersion<9&&b.useHTML5Audio&&b.audioFormats.mp4.required)b.flashVersion=9;k=b.flashVersion;b.version=b.versionNumber+(x?" (HTML5-only mode)":k===9?" (AS3/Flash 9)":" (AS2/Flash 8)");if(k>8){b.defaultOptions=q(b.defaultOptions,b.flash9Options);b.features.buffering=true}if(k>8&&b.useMovieStar){b.defaultOptions=q(b.defaultOptions,b.movieStarOptions);
b.filePatterns.flash9=RegExp("\\.(mp3|"+b.netStreamTypes.join("|")+")(\\?.*)?$","i");b.mimePattern=b.netStreamMimeTypes;b.features.movieStar=true}else b.features.movieStar=false;b.filePattern=b.filePatterns[k!==8?"flash9":"flash8"];b.movieURL=(k===8?"soundmanager2.swf":"soundmanager2_flash9.swf").replace(".swf",c);b.features.peakData=b.features.waveformData=b.features.eqData=k>8};na=function(){return document.body?document.body:document.documentElement?document.documentElement:document.getElementsByTagName("div")[0]};
oa=function(c,a){if(!b.o||!b.allowPolling)return false;b.o._setPolling(c,a)};$=function(){function c(){f.left=j.scrollX+"px";f.top=j.scrollY+"px"}function a(g){g=j[(g?"add":"remove")+"EventListener"];g("resize",c,false);g("scroll",c,false)}var f=null;return{check:function(g){f=b.oMC.style;if(t.match(/android/i)){if(g){if(b.flashLoadTimeout)b._s.flashLoadTimeout=0;return false}f.position="absolute";f.left=f.top="0px";a(true);b.onready(function(){a(false);if(f)f.left=f.top="-9999px"});c()}}}}();R=function(c,
a){var f=a?a:b.url,g=b.altURL?b.altURL:f,e,o,l,h;c=typeof c==="undefined"?b.id:c;if(E&&F)return false;if(x){Y();b.oMC=y(b.movieID);O();F=E=true;return false}E=true;Y();b.url=qa(this._overHTTP?f:g);a=b.url;if(b.useHighPerformance&&b.useMovieStar&&b.defaultOptions.useVideo===true)b.useHighPerformance=false;b.wmode=!b.wmode&&b.useHighPerformance&&!b.useMovieStar?"transparent":b.wmode;if(b.wmode!==null&&!b.isIE&&!b.useHighPerformance&&navigator.platform.match(/win32/i)){b.specialWmodeCase=true;b.wmode=
null}if(k===8)b.allowFullScreen=false;g={name:c,id:c,src:a,width:"100%",height:"100%",quality:"high",allowScriptAccess:b.allowScriptAccess,bgcolor:b.bgColor,pluginspage:"http://www.macromedia.com/go/getflashplayer",type:"application/x-shockwave-flash",wmode:b.wmode,allowFullScreen:b.allowFullScreen?"true":"false"};if(b.debugFlash)g.FlashVars="debug=1";b.wmode||delete g.wmode;if(b.isIE){f=document.createElement("div");o='<object id="'+c+'" data="'+a+'" type="'+g.type+'" width="'+g.width+'" height="'+
g.height+'"><param name="movie" value="'+a+'" /><param name="AllowScriptAccess" value="'+b.allowScriptAccess+'" /><param name="quality" value="'+g.quality+'" />'+(b.wmode?'<param name="wmode" value="'+b.wmode+'" /> ':"")+'<param name="bgcolor" value="'+b.bgColor+'" /><param name="allowFullScreen" value="'+g.allowFullScreen+'" />'+(b.debugFlash?'<param name="FlashVars" value="'+g.FlashVars+'" />':"")+"<!-- --\></object>"}else{f=document.createElement("embed");for(e in g)g.hasOwnProperty(e)&&f.setAttribute(e,
g[e])}ha();g=L();if(e=na()){b.oMC=y(b.movieID)?y(b.movieID):document.createElement("div");if(b.oMC.id){e=b.oMC.className;b.oMC.className=(e?e+" ":b.swfCSS.swfDefault)+(g?" "+g:"");b.oMC.appendChild(f);if(b.isIE){g=b.oMC.appendChild(document.createElement("div"));g.className="sm2-object-box";g.innerHTML=o}F=true;$.check(true)}else{b.oMC.id=b.movieID;b.oMC.className=b.swfCSS.swfDefault+" "+g;g=l=null;b.useFlashBlock||(l=b.useHighPerformance?{position:"fixed",width:"8px",height:"8px",bottom:"0px",left:"0px",
overflow:"hidden"}:{position:"absolute",width:"6px",height:"6px",top:"-9999px",left:"-9999px"});if(t.match(/webkit/i))b.oMC.style.zIndex=1E4;h=null;if(!b.debugFlash)for(h in l)if(l.hasOwnProperty(h))b.oMC.style[h]=l[h];try{b.isIE||b.oMC.appendChild(f);e.appendChild(b.oMC);if(b.isIE){g=b.oMC.appendChild(document.createElement("div"));g.className="sm2-object-box";g.innerHTML=o}F=true}catch(d){throw Error(K("appXHTML"));}$.check()}}};n=this.getSoundById;q=function(c,a){var f={},g,e;for(g in c)if(c.hasOwnProperty(g))f[g]=
c[g];g=typeof a==="undefined"?b.defaultOptions:a;for(e in g)if(g.hasOwnProperty(e)&&typeof f[e]==="undefined")f[e]=g[e];return f};Q=function(){if(x){R();return false}if(b.o)return false;b.o=b.getMovie(b.id);if(!b.o){if(J){if(b.isIE)b.oMC.innerHTML=aa;else b.oMC.appendChild(J);J=null;E=true}else R(b.id,b.url);b.o=b.getMovie(b.id)}typeof b.oninitmovie==="function"&&setTimeout(b.oninitmovie,1)};la=function(c){if(c)b.url=c;Q()};X=function(){if(T)return false;T=true;if(D&&!fa)return false;var c;p||(c=
b.getMoviePercent());setTimeout(function(){c=b.getMoviePercent();if(!p&&wa)if(c===null)if(b.useFlashBlock||b.flashLoadTimeout===0)b.useFlashBlock&&ba();else I(true);else b.flashLoadTimeout!==0&&I(true)},b.flashLoadTimeout)};L=function(){var c=[];b.debugMode&&c.push(b.swfCSS.sm2Debug);b.debugFlash&&c.push(b.swfCSS.flashDebug);b.useHighPerformance&&c.push(b.swfCSS.highPerf);return c.join(" ")};ba=function(){var c=b.getMoviePercent();if(b.supported()){if(b.oMC)b.oMC.className=L()+" "+b.swfCSS.swfDefault+
(" "+b.swfCSS.swfUnblocked)}else{if(C)b.oMC.className=L()+" "+b.swfCSS.swfDefault+" "+(c===null?b.swfCSS.swfTimedout:b.swfCSS.swfError);b.didFlashBlock=true;A(true);b.onerror instanceof Function&&b.onerror.apply(j)}};w=function(){if(fa||!D)return true;fa=wa=true;D&&j.removeEventListener("mousemove",w,false);T=false;setTimeout(X,500);if(j.removeEventListener)j.removeEventListener("focus",w,false);else j.detachEvent&&j.detachEvent("onfocus",w)};G=function(c){if(p)return false;if(x){p=true;A();B();return true}b.useFlashBlock&&
b.flashLoadTimeout&&!b.getMoviePercent()||(p=true);if(v||c){if(b.useFlashBlock)b.oMC.className=L()+" "+(b.getMoviePercent()===null?b.swfCSS.swfTimedout:b.swfCSS.swfError);A();b.onerror instanceof Function&&b.onerror.apply(j);return false}if(b.waitForWindowLoad&&!ja){if(j.addEventListener)j.addEventListener("load",B,false);else j.attachEvent&&j.attachEvent("onload",B);return false}else B()};ka=function(c,a){z.push({method:c,scope:a||null,fired:false})};A=function(c){if(!p&&!c)return false;c={success:c?
b.supported():!v};var a=[],f,g,e=!b.useFlashBlock||b.useFlashBlock&&!b.supported();f=0;for(g=z.length;f<g;f++)z[f].fired!==true&&a.push(z[f]);if(a.length){f=0;for(g=a.length;f<g;f++){a[f].scope?a[f].method.apply(a[f].scope,[c]):a[f].method(c);if(!e)a[f].fired=true}}};B=function(){j.setTimeout(function(){b.useFlashBlock&&ba();A();b.onload.apply(j)},1)};ta=function(){var c,a,f=!N.match(/usehtml5audio/i)&&!N.match(/sm2\-ignorebadua/i)&&b.isSafari&&t.match(/OS X 10_6_(3|4)/i)&&t.match(/(531\.22\.7|533\.16|533\.17\.8)/i);
if(t.match(/iphone os (1|2|3_0|3_1)/i)?true:false){b.hasHTML5=false;x=true;if(b.oMC)b.oMC.style.display="none";return false}if(b.useHTML5Audio){if(!b.html5||!b.html5.canPlayType){b.hasHTML5=false;return true}else b.hasHTML5=true;if(f){b.useHTML5Audio=false;b.hasHTML5=false;return true}}else return true;for(a in b.audioFormats)if(b.audioFormats.hasOwnProperty(a))if(b.audioFormats[a].required&&!b.html5.canPlayType(b.audioFormats[a].type))c=true;if(b.ignoreFlash)c=false;x=b.useHTML5Audio&&b.hasHTML5&&
!c;return c};O=function(){function c(){if(j.removeEventListener)j.removeEventListener("load",b.beginDelayedInit,false);else j.detachEvent&&j.detachEvent("onload",b.beginDelayedInit)}var a,f=[];if(p)return false;if(b.hasHTML5)for(a in b.audioFormats)b.audioFormats.hasOwnProperty(a)&&f.push(a+": "+b.html5[a]);if(x){if(!p){c();b.enabled=true;G()}return true}Q();try{b.o._externalInterfaceTest(false);if(b.allowPolling)oa(true,b.useFastPolling?true:false);b.debugMode||b.o._disableDebug();b.enabled=true}catch(g){I(true);
G();return false}G();c()};ma=function(){if(da)return false;R();Q();return da=true};H=function(){if(Z)return false;Z=true;ha();ua();b.html5.usingFlash=ta();C=b.html5.usingFlash;Z=true;la()};ra=function(c){if(!c._hasTimer)c._hasTimer=true};sa=function(c){if(c._hasTimer)c._hasTimer=false};this._setSandboxType=function(c){var a=b.sandbox;a.type=c;a.description=a.types[typeof a.types[c]!=="undefined"?c:"unknown"];if(a.type==="localWithFile"){a.noRemote=true;a.noLocal=false}else if(a.type==="localWithNetwork"){a.noRemote=
false;a.noLocal=true}else if(a.type==="localTrusted"){a.noRemote=false;a.noLocal=false}};this._externalInterfaceOK=function(){if(b.swfLoaded)return false;(new Date).getTime();b.swfLoaded=true;D=false;b.isIE?setTimeout(O,100):O()};this._onfullscreenchange=function(c){b.isFullScreen=c===1?true:false;if(!b.isFullScreen)try{j.focus()}catch(a){}};W=function(c){var a=this,f,g,e,o,l,h;this.sID=c.id;this.url=c.url;this._iO=this.instanceOptions=this.options=q(c);this.pan=this.options.pan;this.volume=this.options.volume;
this._lastURL=null;this.isHTML5=false;this.id3={};this._debug=function(){};this._debug();this.load=function(d){var i=null;if(typeof d!=="undefined"){a._iO=q(d);a.instanceOptions=a._iO}else{d=a.options;a._iO=d;a.instanceOptions=a._iO;if(a._lastURL&&a._lastURL!==a.url){a._iO.url=a.url;a.url=null}}if(a._iO.url===a.url&&a.readyState!==0&&a.readyState!==2)return a;a._lastURL=a.url;a.loaded=false;a.readyState=1;a.playState=0;if(U(a._iO)){i=a._setup_html5(a._iO);i.load();a._iO.autoPlay&&a.play()}else try{a.isHTML5=
false;a._iO=S(a._iO);if(k===8)b.o._load(a.sID,a._iO.url,a._iO.stream,a._iO.autoPlay,a._iO.whileloading?1:0,a._iO.loops||1);else{b.o._load(a.sID,a._iO.url,a._iO.stream?true:false,a._iO.autoPlay?true:false,a._iO.loops||1);a._iO.isMovieStar&&a._iO.autoLoad&&!a._iO.autoPlay&&a.pause()}}catch(m){b.onerror();b.disable()}return a};this.unload=function(){if(a.readyState!==0){a.readyState!==2&&a.setPosition(0,true);if(a.isHTML5){e();if(h){h.pause();h.src=b.nullURL;h.load();h=a._audio=null}}else if(k===8)b.o._unload(a.sID,
b.nullURL);else{a.setAutoPlay(false);b.o._unload(a.sID)}f()}return a};this.destruct=function(){if(a.isHTML5){e();if(h){h.pause();h.src="about:blank";h.load();h=a._audio=null}}else{a._iO.onfailure=null;b.o._destroySound(a.sID)}b.destroySound(a.sID,true)};this.start=this.play=function(d){d||(d={});a._iO=q(d,a._iO);a._iO=q(a._iO,a.options);a.instanceOptions=a._iO;if(a._iO.serverURL)if(!a.connected){a.setAutoPlay(true);return a}if(U(a._iO)){a._setup_html5(a._iO);o()}if(a.playState===1)if(d=a._iO.multiShot)a.isHTML5&&
a.setPosition(a._iO.position);else return a;if(!a.loaded)if(a.readyState===0)if(a.isHTML5){a.load(a._iO);a.readyState=1}else{if(!a._iO.serverURL){a._iO.autoPlay=true;a.load(a._iO)}}else if(a.readyState===2)return a;if(a.paused&&a.position!==null)a.resume();else{a.playState=1;a.paused=false;if(!a.instanceCount||k>8&&!a.isHTML5)a.instanceCount++;a.position=typeof a._iO.position!=="undefined"&&!isNaN(a._iO.position)?a._iO.position:0;a._iO=S(a._iO);a._iO.onplay&&a._iO.onplay.apply(a);a.setVolume(a._iO.volume,
true);a.setPan(a._iO.pan,true);if(a.isHTML5){o();a._setup_html5().play()}else{k===9&&a._iO.serverURL&&a.setAutoPlay(true);b.o._start(a.sID,a._iO.loops||1,k===9?a.position:a.position/1E3)}}return a};this.stop=function(d){if(a.playState===1){a._onbufferchange(0);a.resetOnPosition(0);if(!a.isHTML5)a.playState=0;a.paused=false;a._iO.onstop&&a._iO.onstop.apply(a);if(a.isHTML5){if(h){a.setPosition(0);h.pause();a.playState=0;a._onTimer();e();a.unload()}}else{b.o._stop(a.sID,d);a._iO.serverURL&&a.unload()}a.instanceCount=
0;a._iO={}}return a};this.setAutoPlay=function(d){a._iO.autoPlay=d;b.o._setAutoPlay(a.sID,d);if(d)a.instanceCount||a.instanceCount++};this.setPosition=function(d){if(typeof d==="undefined")d=0;a._iO.position=a.isHTML5?Math.max(d,0):Math.min(a.duration,Math.max(d,0));a.resetOnPosition(a._iO.position);if(a.isHTML5){if(h){if(a.playState)try{h.currentTime=a._iO.position/1E3}catch(i){}if(a.paused){a._onTimer(true);a._iO.useMovieStar&&a.resume()}}}else b.o._setPosition(a.sID,k===9?a._iO.position:a._iO.position/
1E3,a.paused||!a.playState);return a};this.pause=function(d){if(a.paused||a.playState===0&&a.readyState!==1)return a;a.paused=true;if(a.isHTML5){a._setup_html5().pause();e()}else if(d||d===undefined)b.o._pause(a.sID);a._iO.onpause&&a._iO.onpause.apply(a);return a};this.resume=function(){if(!a.paused||a.playState===0)return a;a.paused=false;a.playState=1;if(a.isHTML5){a._setup_html5().play();o()}else b.o._pause(a.sID);a._iO.onresume&&a._iO.onresume.apply(a);return a};this.togglePause=function(){if(a.playState===
0){a.play({position:k===9&&!a.isHTML5?a.position:a.position/1E3});return a}a.paused?a.resume():a.pause();return a};this.setPan=function(d,i){if(typeof d==="undefined")d=0;if(typeof i==="undefined")i=false;a.isHTML5||b.o._setPan(a.sID,d);a._iO.pan=d;if(!i)a.pan=d;return a};this.setVolume=function(d,i){if(typeof d==="undefined")d=100;if(typeof i==="undefined")i=false;if(a.isHTML5){if(h)h.volume=d/100}else b.o._setVolume(a.sID,b.muted&&!a.muted||a.muted?0:d);a._iO.volume=d;if(!i)a.volume=d;return a};
this.mute=function(){a.muted=true;if(a.isHTML5){if(h)h.muted=true}else b.o._setVolume(a.sID,0);return a};this.unmute=function(){a.muted=false;var d=typeof a._iO.volume!=="undefined";if(a.isHTML5){if(h)h.muted=false}else b.o._setVolume(a.sID,d?a._iO.volume:a.options.volume);return a};this.toggleMute=function(){return a.muted?a.unmute():a.mute()};this.onposition=function(d,i,m){a._onPositionItems.push({position:d,method:i,scope:typeof m!=="undefined"?m:a,fired:false});return a};this.processOnPosition=
function(){var d,i;d=a._onPositionItems.length;if(!d||!a.playState||a._onPositionFired>=d)return false;for(d=d;d--;){i=a._onPositionItems[d];if(!i.fired&&a.position>=i.position){i.method.apply(i.scope,[i.position]);i.fired=true;b._onPositionFired++}}};this.resetOnPosition=function(d){var i,m;i=a._onPositionItems.length;if(!i)return false;for(i=i;i--;){m=a._onPositionItems[i];if(m.fired&&d<=m.position){m.fired=false;b._onPositionFired--}}};this._onTimer=function(d){if(a._hasTimer||d)if(h&&(d||(a.playState>
0||a.readyState===1)&&!a.paused)){a.duration=l();a.durationEstimate=a.duration;d=h.currentTime?h.currentTime*1E3:0;a._whileplaying(d,{},{},{},{});return true}else return false};l=function(){var d=h?h.duration*1E3:undefined;if(d)return!isNaN(d)?d:null};o=function(){a.isHTML5&&ra(a)};e=function(){a.isHTML5&&sa(a)};f=function(){a._onPositionItems=[];a._onPositionFired=0;a._hasTimer=null;a._added_events=null;h=a._audio=null;a.bytesLoaded=null;a.bytesTotal=null;a.position=null;a.duration=null;a.durationEstimate=
null;a.failures=0;a.loaded=false;a.playState=0;a.paused=false;a.readyState=0;a.muted=false;a.didBeforeFinish=false;a.didJustBeforeFinish=false;a.isBuffering=false;a.instanceOptions={};a.instanceCount=0;a.peakData={left:0,right:0};a.waveformData={left:[],right:[]};a.eqData=[];a.eqData.left=[];a.eqData.right=[]};f();this._setup_html5=function(d){d=q(a._iO,d);if(h){if(a.url!==d.url)h.src=d.url}else{a._audio=new Audio(d.url);h=a._audio;a.isHTML5=true;g()}h.loop=d.loops>1?"loop":"";return a._audio};g=
function(){function d(i,m,r){return h?h.addEventListener(i,m,r||false):null}if(a._added_events)return false;a._added_events=true;d("load",function(){if(h){a._onbufferchange(0);a._whileloading(a.bytesTotal,a.bytesTotal,l());a._onload(1)}},false);d("canplay",function(){a._onbufferchange(0)},false);d("waiting",function(){a._onbufferchange(1)},false);d("progress",function(i){if(!a.loaded&&h){a._onbufferchange(0);a._whileloading(i.loaded||0,i.total||1,l())}},false);d("error",function(){h&&a._onload(0)},
false);d("loadstart",function(){a._onbufferchange(1)},false);d("play",function(){a._onbufferchange(0)},false);d("playing",function(){a._onbufferchange(0)},false);d("timeupdate",function(){a._onTimer()},false);setTimeout(function(){a&&h&&d("ended",function(){a._onfinish()},false)},250)};this._whileloading=function(d,i,m,r){a.bytesLoaded=d;a.bytesTotal=i;a.duration=Math.floor(m);if(a._iO.isMovieStar){a.durationEstimate=a.duration;a.readyState!==3&&a._iO.whileloading&&a._iO.whileloading.apply(a)}else{a.durationEstimate=
parseInt(a.bytesTotal/a.bytesLoaded*a.duration,10);if(a.durationEstimate===undefined)a.durationEstimate=a.duration;a.bufferLength=r;if((a._iO.isMovieStar||a.readyState!==3)&&a._iO.whileloading)a._iO.whileloading.apply(a)}};this._onid3=function(d,i){var m=[],r,s;r=0;for(s=d.length;r<s;r++)m[d[r]]=i[r];a.id3=q(a.id3,m);a._iO.onid3&&a._iO.onid3.apply(a)};this._whileplaying=function(d,i,m,r,s){if(isNaN(d)||d===null)return false;if(a.playState===0&&d>0)d=0;a.position=d;a.processOnPosition();if(k>8&&!a.isHTML5){if(a._iO.usePeakData&&
typeof i!=="undefined"&&i)a.peakData={left:i.leftPeak,right:i.rightPeak};if(a._iO.useWaveformData&&typeof m!=="undefined"&&m)a.waveformData={left:m.split(","),right:r.split(",")};if(a._iO.useEQData)if(typeof s!=="undefined"&&s&&s.leftEQ){d=s.leftEQ.split(",");a.eqData=d;a.eqData.left=d;if(typeof s.rightEQ!=="undefined"&&s.rightEQ)a.eqData.right=s.rightEQ.split(",")}}if(a.playState===1){!a.isHTML5&&a.isBuffering&&a._onbufferchange(0);a._iO.whileplaying&&a._iO.whileplaying.apply(a);if((a.loaded||!a.loaded&&
a._iO.isMovieStar)&&a._iO.onbeforefinish&&a._iO.onbeforefinishtime&&!a.didBeforeFinish&&a.duration-a.position<=a._iO.onbeforefinishtime)a._onbeforefinish()}};this._onconnect=function(d){d=d===1;if(a.connected=d){a.failures=0;if(a._iO.autoLoad||a._iO.autoPlay)a.load(a._iO);a._iO.autoPlay&&a.play();a._iO.onconnect&&a._iO.onconnect.apply(a,[d])}};this._onload=function(d){d=d===1?true:false;a.loaded=d;a.readyState=d?3:2;a._iO.onload&&a._iO.onload.apply(a)};this._onfailure=function(d){a.failures++;a._iO.onfailure&&
a.failures===1&&a._iO.onfailure(a,d)};this._onbeforefinish=function(){if(!a.didBeforeFinish){a.didBeforeFinish=true;a._iO.onbeforefinish&&a._iO.onbeforefinish.apply(a)}};this._onjustbeforefinish=function(){if(!a.didJustBeforeFinish){a.didJustBeforeFinish=true;a._iO.onjustbeforefinish&&a._iO.onjustbeforefinish.apply(a)}};this._onfinish=function(){a._onbufferchange(0);a.resetOnPosition(0);a._iO.onbeforefinishcomplete&&a._iO.onbeforefinishcomplete.apply(a);a.didBeforeFinish=false;a.didJustBeforeFinish=
false;if(a.instanceCount){a.instanceCount--;if(!a.instanceCount){a.playState=0;a.paused=false;a.instanceCount=0;a.instanceOptions={};e()}if(!a.instanceCount||a._iO.multiShotEvents)if(a._iO.onfinish)a._iO.onfinish.apply(a);else a.isHTML5&&a.unload()}};this._onmetadata=function(d){if(!d.width&&!d.height){d.width=320;d.height=240}a.metadata=d;a.width=d.width;a.height=d.height;a._iO.onmetadata&&a._iO.onmetadata.apply(a)};this._onbufferchange=function(d){if(a.playState===0)return false;if(d&&a.isBuffering||
!d&&!a.isBuffering)return false;a.isBuffering=d===1?true:false;a._iO.onbufferchange&&a._iO.onbufferchange.apply(a)};this._ondataerror=function(){a.playState>0&&a._iO.ondataerror&&a._iO.ondataerror.apply(a)}};if(!b.hasHTML5||C)if(j.addEventListener){j.addEventListener("focus",w,false);j.addEventListener("load",b.beginDelayedInit,false);j.addEventListener("unload",b.destruct,false);D&&j.addEventListener("mousemove",w,false)}else if(j.attachEvent){j.attachEvent("onfocus",w);j.attachEvent("onload",b.beginDelayedInit);
j.attachEvent("unload",b.destruct)}else{V.onerror();V.disable()}ea=function(){if(document.readyState==="complete"){H();document.detachEvent("onreadystatechange",ea)}};if(document.addEventListener)document.addEventListener("DOMContentLoaded",H,false);else document.attachEvent&&document.attachEvent("onreadystatechange",ea);document.readyState==="complete"&&setTimeout(H,100)}var V=null;if(typeof SM2_DEFER==="undefined"||!SM2_DEFER)V=new ga;j.SoundManager=ga;j.soundManager=V})(window);
| AMoo-Miki/cdnjs | ajax/libs/soundmanager2/2.96a.20100822/script/soundmanager2-nodebug-jsmin.js | JavaScript | mit | 31,068 |
/*!
* jQuery Cycle2; version: 2.1.5 build: 20140415
* http://jquery.malsup.com/cycle2/
* Copyright (c) 2014 M. Alsup; Dual licensed: MIT/GPL
*/
!function(a){"use strict";function b(a){return(a||"").toLowerCase()}var c="2.1.5";a.fn.cycle=function(c){var d;return 0!==this.length||a.isReady?this.each(function(){var d,e,f,g,h=a(this),i=a.fn.cycle.log;if(!h.data("cycle.opts")){(h.data("cycle-log")===!1||c&&c.log===!1||e&&e.log===!1)&&(i=a.noop),i("--c2 init--"),d=h.data();for(var j in d)d.hasOwnProperty(j)&&/^cycle[A-Z]+/.test(j)&&(g=d[j],f=j.match(/^cycle(.*)/)[1].replace(/^[A-Z]/,b),i(f+":",g,"("+typeof g+")"),d[f]=g);e=a.extend({},a.fn.cycle.defaults,d,c||{}),e.timeoutId=0,e.paused=e.paused||!1,e.container=h,e._maxZ=e.maxZ,e.API=a.extend({_container:h},a.fn.cycle.API),e.API.log=i,e.API.trigger=function(a,b){return e.container.trigger(a,b),e.API},h.data("cycle.opts",e),h.data("cycle.API",e.API),e.API.trigger("cycle-bootstrap",[e,e.API]),e.API.addInitialSlides(),e.API.preInitSlideshow(),e.slides.length&&e.API.initSlideshow()}}):(d={s:this.selector,c:this.context},a.fn.cycle.log("requeuing slideshow (dom not ready)"),a(function(){a(d.s,d.c).cycle(c)}),this)},a.fn.cycle.API={opts:function(){return this._container.data("cycle.opts")},addInitialSlides:function(){var b=this.opts(),c=b.slides;b.slideCount=0,b.slides=a(),c=c.jquery?c:b.container.find(c),b.random&&c.sort(function(){return Math.random()-.5}),b.API.add(c)},preInitSlideshow:function(){var b=this.opts();b.API.trigger("cycle-pre-initialize",[b]);var c=a.fn.cycle.transitions[b.fx];c&&a.isFunction(c.preInit)&&c.preInit(b),b._preInitialized=!0},postInitSlideshow:function(){var b=this.opts();b.API.trigger("cycle-post-initialize",[b]);var c=a.fn.cycle.transitions[b.fx];c&&a.isFunction(c.postInit)&&c.postInit(b)},initSlideshow:function(){var b,c=this.opts(),d=c.container;c.API.calcFirstSlide(),"static"==c.container.css("position")&&c.container.css("position","relative"),a(c.slides[c.currSlide]).css({opacity:1,display:"block",visibility:"visible"}),c.API.stackSlides(c.slides[c.currSlide],c.slides[c.nextSlide],!c.reverse),c.pauseOnHover&&(c.pauseOnHover!==!0&&(d=a(c.pauseOnHover)),d.hover(function(){c.API.pause(!0)},function(){c.API.resume(!0)})),c.timeout&&(b=c.API.getSlideOpts(c.currSlide),c.API.queueTransition(b,b.timeout+c.delay)),c._initialized=!0,c.API.updateView(!0),c.API.trigger("cycle-initialized",[c]),c.API.postInitSlideshow()},pause:function(b){var c=this.opts(),d=c.API.getSlideOpts(),e=c.hoverPaused||c.paused;b?c.hoverPaused=!0:c.paused=!0,e||(c.container.addClass("cycle-paused"),c.API.trigger("cycle-paused",[c]).log("cycle-paused"),d.timeout&&(clearTimeout(c.timeoutId),c.timeoutId=0,c._remainingTimeout-=a.now()-c._lastQueue,(c._remainingTimeout<0||isNaN(c._remainingTimeout))&&(c._remainingTimeout=void 0)))},resume:function(a){var b=this.opts(),c=!b.hoverPaused&&!b.paused;a?b.hoverPaused=!1:b.paused=!1,c||(b.container.removeClass("cycle-paused"),0===b.slides.filter(":animated").length&&b.API.queueTransition(b.API.getSlideOpts(),b._remainingTimeout),b.API.trigger("cycle-resumed",[b,b._remainingTimeout]).log("cycle-resumed"))},add:function(b,c){var d,e=this.opts(),f=e.slideCount,g=!1;"string"==a.type(b)&&(b=a.trim(b)),a(b).each(function(){var b,d=a(this);c?e.container.prepend(d):e.container.append(d),e.slideCount++,b=e.API.buildSlideOpts(d),e.slides=c?a(d).add(e.slides):e.slides.add(d),e.API.initSlide(b,d,--e._maxZ),d.data("cycle.opts",b),e.API.trigger("cycle-slide-added",[e,b,d])}),e.API.updateView(!0),g=e._preInitialized&&2>f&&e.slideCount>=1,g&&(e._initialized?e.timeout&&(d=e.slides.length,e.nextSlide=e.reverse?d-1:1,e.timeoutId||e.API.queueTransition(e)):e.API.initSlideshow())},calcFirstSlide:function(){var a,b=this.opts();a=parseInt(b.startingSlide||0,10),(a>=b.slides.length||0>a)&&(a=0),b.currSlide=a,b.reverse?(b.nextSlide=a-1,b.nextSlide<0&&(b.nextSlide=b.slides.length-1)):(b.nextSlide=a+1,b.nextSlide==b.slides.length&&(b.nextSlide=0))},calcNextSlide:function(){var a,b=this.opts();b.reverse?(a=b.nextSlide-1<0,b.nextSlide=a?b.slideCount-1:b.nextSlide-1,b.currSlide=a?0:b.nextSlide+1):(a=b.nextSlide+1==b.slides.length,b.nextSlide=a?0:b.nextSlide+1,b.currSlide=a?b.slides.length-1:b.nextSlide-1)},calcTx:function(b,c){var d,e=b;return e._tempFx?d=a.fn.cycle.transitions[e._tempFx]:c&&e.manualFx&&(d=a.fn.cycle.transitions[e.manualFx]),d||(d=a.fn.cycle.transitions[e.fx]),e._tempFx=null,this.opts()._tempFx=null,d||(d=a.fn.cycle.transitions.fade,e.API.log('Transition "'+e.fx+'" not found. Using fade.')),d},prepareTx:function(a,b){var c,d,e,f,g,h=this.opts();return h.slideCount<2?void(h.timeoutId=0):(!a||h.busy&&!h.manualTrump||(h.API.stopTransition(),h.busy=!1,clearTimeout(h.timeoutId),h.timeoutId=0),void(h.busy||(0!==h.timeoutId||a)&&(d=h.slides[h.currSlide],e=h.slides[h.nextSlide],f=h.API.getSlideOpts(h.nextSlide),g=h.API.calcTx(f,a),h._tx=g,a&&void 0!==f.manualSpeed&&(f.speed=f.manualSpeed),h.nextSlide!=h.currSlide&&(a||!h.paused&&!h.hoverPaused&&h.timeout)?(h.API.trigger("cycle-before",[f,d,e,b]),g.before&&g.before(f,d,e,b),c=function(){h.busy=!1,h.container.data("cycle.opts")&&(g.after&&g.after(f,d,e,b),h.API.trigger("cycle-after",[f,d,e,b]),h.API.queueTransition(f),h.API.updateView(!0))},h.busy=!0,g.transition?g.transition(f,d,e,b,c):h.API.doTransition(f,d,e,b,c),h.API.calcNextSlide(),h.API.updateView()):h.API.queueTransition(f))))},doTransition:function(b,c,d,e,f){var g=b,h=a(c),i=a(d),j=function(){i.animate(g.animIn||{opacity:1},g.speed,g.easeIn||g.easing,f)};i.css(g.cssBefore||{}),h.animate(g.animOut||{},g.speed,g.easeOut||g.easing,function(){h.css(g.cssAfter||{}),g.sync||j()}),g.sync&&j()},queueTransition:function(b,c){var d=this.opts(),e=void 0!==c?c:b.timeout;return 0===d.nextSlide&&0===--d.loop?(d.API.log("terminating; loop=0"),d.timeout=0,e?setTimeout(function(){d.API.trigger("cycle-finished",[d])},e):d.API.trigger("cycle-finished",[d]),void(d.nextSlide=d.currSlide)):void 0!==d.continueAuto&&(d.continueAuto===!1||a.isFunction(d.continueAuto)&&d.continueAuto()===!1)?(d.API.log("terminating automatic transitions"),d.timeout=0,void(d.timeoutId&&clearTimeout(d.timeoutId))):void(e&&(d._lastQueue=a.now(),void 0===c&&(d._remainingTimeout=b.timeout),d.paused||d.hoverPaused||(d.timeoutId=setTimeout(function(){d.API.prepareTx(!1,!d.reverse)},e))))},stopTransition:function(){var a=this.opts();a.slides.filter(":animated").length&&(a.slides.stop(!1,!0),a.API.trigger("cycle-transition-stopped",[a])),a._tx&&a._tx.stopTransition&&a._tx.stopTransition(a)},advanceSlide:function(a){var b=this.opts();return clearTimeout(b.timeoutId),b.timeoutId=0,b.nextSlide=b.currSlide+a,b.nextSlide<0?b.nextSlide=b.slides.length-1:b.nextSlide>=b.slides.length&&(b.nextSlide=0),b.API.prepareTx(!0,a>=0),!1},buildSlideOpts:function(c){var d,e,f=this.opts(),g=c.data()||{};for(var h in g)g.hasOwnProperty(h)&&/^cycle[A-Z]+/.test(h)&&(d=g[h],e=h.match(/^cycle(.*)/)[1].replace(/^[A-Z]/,b),f.API.log("["+(f.slideCount-1)+"]",e+":",d,"("+typeof d+")"),g[e]=d);g=a.extend({},a.fn.cycle.defaults,f,g),g.slideNum=f.slideCount;try{delete g.API,delete g.slideCount,delete g.currSlide,delete g.nextSlide,delete g.slides}catch(i){}return g},getSlideOpts:function(b){var c=this.opts();void 0===b&&(b=c.currSlide);var d=c.slides[b],e=a(d).data("cycle.opts");return a.extend({},c,e)},initSlide:function(b,c,d){var e=this.opts();c.css(b.slideCss||{}),d>0&&c.css("zIndex",d),isNaN(b.speed)&&(b.speed=a.fx.speeds[b.speed]||a.fx.speeds._default),b.sync||(b.speed=b.speed/2),c.addClass(e.slideClass)},updateView:function(a,b){var c=this.opts();if(c._initialized){var d=c.API.getSlideOpts(),e=c.slides[c.currSlide];!a&&b!==!0&&(c.API.trigger("cycle-update-view-before",[c,d,e]),c.updateView<0)||(c.slideActiveClass&&c.slides.removeClass(c.slideActiveClass).eq(c.currSlide).addClass(c.slideActiveClass),a&&c.hideNonActive&&c.slides.filter(":not(."+c.slideActiveClass+")").css("visibility","hidden"),0===c.updateView&&setTimeout(function(){c.API.trigger("cycle-update-view",[c,d,e,a])},d.speed/(c.sync?2:1)),0!==c.updateView&&c.API.trigger("cycle-update-view",[c,d,e,a]),a&&c.API.trigger("cycle-update-view-after",[c,d,e]))}},getComponent:function(b){var c=this.opts(),d=c[b];return"string"==typeof d?/^\s*[\>|\+|~]/.test(d)?c.container.find(d):a(d):d.jquery?d:a(d)},stackSlides:function(b,c,d){var e=this.opts();b||(b=e.slides[e.currSlide],c=e.slides[e.nextSlide],d=!e.reverse),a(b).css("zIndex",e.maxZ);var f,g=e.maxZ-2,h=e.slideCount;if(d){for(f=e.currSlide+1;h>f;f++)a(e.slides[f]).css("zIndex",g--);for(f=0;f<e.currSlide;f++)a(e.slides[f]).css("zIndex",g--)}else{for(f=e.currSlide-1;f>=0;f--)a(e.slides[f]).css("zIndex",g--);for(f=h-1;f>e.currSlide;f--)a(e.slides[f]).css("zIndex",g--)}a(c).css("zIndex",e.maxZ-1)},getSlideIndex:function(a){return this.opts().slides.index(a)}},a.fn.cycle.log=function(){window.console&&console.log&&console.log("[cycle2] "+Array.prototype.join.call(arguments," "))},a.fn.cycle.version=function(){return"Cycle2: "+c},a.fn.cycle.transitions={custom:{},none:{before:function(a,b,c,d){a.API.stackSlides(c,b,d),a.cssBefore={opacity:1,visibility:"visible",display:"block"}}},fade:{before:function(b,c,d,e){var f=b.API.getSlideOpts(b.nextSlide).slideCss||{};b.API.stackSlides(c,d,e),b.cssBefore=a.extend(f,{opacity:0,visibility:"visible",display:"block"}),b.animIn={opacity:1},b.animOut={opacity:0}}},fadeout:{before:function(b,c,d,e){var f=b.API.getSlideOpts(b.nextSlide).slideCss||{};b.API.stackSlides(c,d,e),b.cssBefore=a.extend(f,{opacity:1,visibility:"visible",display:"block"}),b.animOut={opacity:0}}},scrollHorz:{before:function(a,b,c,d){a.API.stackSlides(b,c,d);var e=a.container.css("overflow","hidden").width();a.cssBefore={left:d?e:-e,top:0,opacity:1,visibility:"visible",display:"block"},a.cssAfter={zIndex:a._maxZ-2,left:0},a.animIn={left:0},a.animOut={left:d?-e:e}}}},a.fn.cycle.defaults={allowWrap:!0,autoSelector:".cycle-slideshow[data-cycle-auto-init!=false]",delay:0,easing:null,fx:"fade",hideNonActive:!0,loop:0,manualFx:void 0,manualSpeed:void 0,manualTrump:!0,maxZ:100,pauseOnHover:!1,reverse:!1,slideActiveClass:"cycle-slide-active",slideClass:"cycle-slide",slideCss:{position:"absolute",top:0,left:0},slides:"> img",speed:500,startingSlide:0,sync:!0,timeout:4e3,updateView:0},a(document).ready(function(){a(a.fn.cycle.defaults.autoSelector).cycle()})}(jQuery); | iskitz/cdnjs | ajax/libs/jquery.cycle2/20140415/jquery.cycle2.core.min.js | JavaScript | mit | 10,345 |
// imported from ncp (this is temporary, will rewrite)
var fs = require('graceful-fs')
var path = require('path')
var utimes = require('../util/utimes')
function ncp (source, dest, options, callback) {
if (!callback) {
callback = options
options = {}
}
var basePath = process.cwd()
var currentPath = path.resolve(basePath, source)
var targetPath = path.resolve(basePath, dest)
var filter = options.filter
var transform = options.transform
var clobber = options.clobber !== false
var dereference = options.dereference
var preserveTimestamps = options.preserveTimestamps === true
var errs = null
var started = 0
var finished = 0
var running = 0
// this is pretty useless now that we're using graceful-fs
// consider removing
var limit = options.limit || 512
startCopy(currentPath)
function startCopy (source) {
started++
if (filter) {
if (filter instanceof RegExp) {
if (!filter.test(source)) {
return doneOne(true)
}
} else if (typeof filter === 'function') {
if (!filter(source)) {
return doneOne(true)
}
}
}
return getStats(source)
}
function getStats (source) {
var stat = dereference ? fs.stat : fs.lstat
if (running >= limit) {
return setImmediate(function () {
getStats(source)
})
}
running++
stat(source, function (err, stats) {
if (err) return onError(err)
// We need to get the mode from the stats object and preserve it.
var item = {
name: source,
mode: stats.mode,
mtime: stats.mtime, // modified time
atime: stats.atime, // access time
stats: stats // temporary
}
if (stats.isDirectory()) {
return onDir(item)
} else if (stats.isFile()) {
return onFile(item)
} else if (stats.isSymbolicLink()) {
// Symlinks don't really need to know about the mode.
return onLink(source)
}
})
}
function onFile (file) {
var target = file.name.replace(currentPath, targetPath)
isWritable(target, function (writable) {
if (writable) {
copyFile(file, target)
} else {
if (clobber) {
rmFile(target, function () {
copyFile(file, target)
})
} else {
doneOne()
}
}
})
}
function copyFile (file, target) {
var readStream = fs.createReadStream(file.name)
var writeStream = fs.createWriteStream(target, { mode: file.mode })
readStream.on('error', onError)
writeStream.on('error', onError)
if (transform) {
transform(readStream, writeStream, file)
} else {
writeStream.on('open', function () {
readStream.pipe(writeStream)
})
}
writeStream.once('finish', function () {
fs.chmod(target, file.mode, function (err) {
if (err) return onError(err)
if (preserveTimestamps) {
utimes.utimesMillis(target, file.atime, file.mtime, function (err) {
if (err) return onError(err)
return doneOne()
})
} else {
doneOne()
}
})
})
}
function rmFile (file, done) {
fs.unlink(file, function (err) {
if (err) return onError(err)
return done()
})
}
function onDir (dir) {
var target = dir.name.replace(currentPath, targetPath)
isWritable(target, function (writable) {
if (writable) {
return mkDir(dir, target)
}
copyDir(dir.name)
})
}
function mkDir (dir, target) {
fs.mkdir(target, dir.mode, function (err) {
if (err) return onError(err)
// despite setting mode in fs.mkdir, doesn't seem to work
// so we set it here.
fs.chmod(target, dir.mode, function (err) {
if (err) return onError(err)
copyDir(dir.name)
})
})
}
function copyDir (dir) {
fs.readdir(dir, function (err, items) {
if (err) return onError(err)
items.forEach(function (item) {
startCopy(path.join(dir, item))
})
return doneOne()
})
}
function onLink (link) {
var target = link.replace(currentPath, targetPath)
fs.readlink(link, function (err, resolvedPath) {
if (err) return onError(err)
checkLink(resolvedPath, target)
})
}
function checkLink (resolvedPath, target) {
if (dereference) {
resolvedPath = path.resolve(basePath, resolvedPath)
}
isWritable(target, function (writable) {
if (writable) {
return makeLink(resolvedPath, target)
}
fs.readlink(target, function (err, targetDest) {
if (err) return onError(err)
if (dereference) {
targetDest = path.resolve(basePath, targetDest)
}
if (targetDest === resolvedPath) {
return doneOne()
}
return rmFile(target, function () {
makeLink(resolvedPath, target)
})
})
})
}
function makeLink (linkPath, target) {
fs.symlink(linkPath, target, function (err) {
if (err) return onError(err)
return doneOne()
})
}
function isWritable (path, done) {
fs.lstat(path, function (err) {
if (err) {
if (err.code === 'ENOENT') return done(true)
return done(false)
}
return done(false)
})
}
function onError (err) {
if (options.stopOnError) {
return callback(err)
} else if (!errs && options.errs) {
errs = fs.createWriteStream(options.errs)
} else if (!errs) {
errs = []
}
if (typeof errs.write === 'undefined') {
errs.push(err)
} else {
errs.write(err.stack + '\n\n')
}
return doneOne()
}
function doneOne (skipped) {
if (!skipped) running--
finished++
if ((started === finished) && (running === 0)) {
if (callback !== undefined) {
return errs ? callback(errs) : callback(null)
}
}
}
}
module.exports = ncp
| h-a-t/h-a-t.github.io | apidays/node_modules/grunt-contrib-qunit/node_modules/grunt-lib-phantomjs/node_modules/phantomjs/node_modules/fs-extra/lib/copy/ncp.js | JavaScript | mit | 5,988 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Process\Tests;
use Symfony\Component\Process\PhpExecutableFinder;
/**
* @author Robert Schönthal <seroscho@googlemail.com>
*/
class PhpExecutableFinderTest extends \PHPUnit_Framework_TestCase
{
/**
* tests find() with the env var PHP_PATH
*/
public function testFindWithPhpPath()
{
if (defined('PHP_BINARY')) {
$this->markTestSkipped('The PHP binary is easily available as of PHP 5.4');
}
$f = new PhpExecutableFinder();
$current = $f->find();
//not executable PHP_PATH
putenv('PHP_PATH=/not/executable/php');
$this->assertFalse($f->find(), '::find() returns false for not executable php');
//executable PHP_PATH
putenv('PHP_PATH='.$current);
$this->assertEquals($f->find(), $current, '::find() returns the executable php');
}
/**
* tests find() with default executable
*/
public function testFindWithSuffix()
{
if (defined('PHP_BINARY')) {
$this->markTestSkipped('The PHP binary is easily available as of PHP 5.4');
}
putenv('PHP_PATH=');
putenv('PHP_PEAR_PHP_BIN=');
$f = new PhpExecutableFinder();
$current = $f->find();
//TODO maybe php executable is custom or even windows
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->assertTrue(is_executable($current));
$this->assertTrue((bool) preg_match('/'.addSlashes(DIRECTORY_SEPARATOR).'php\.(exe|bat|cmd|com)$/i', $current), '::find() returns the executable php with suffixes');
}
}
}
| limonazzo/wpv | vendor/symfony/symfony/src/Symfony/Component/Process/Tests/PhpExecutableFinderTest.php | PHP | mit | 1,869 |
!function(a,b){var c="object"==typeof exports&&exports,d=("object"==typeof module&&module&&module.exports==c&&module,"object"==typeof global&&global);d.global===d&&(window=d),"function"==typeof define&&define.amd?define(["rx","exports"],function(c,d){return a.Rx=b(a,d,c),a.Rx}):"object"==typeof module&&module&&module.exports===c?module.exports=b(a,module.exports,require("rx")):a.Rx=b(a,{},a.Rx)}(this,function(a,b,c,d){function e(a,b,c){if(a.addEventListener)return a.addEventListener(b,c,!1),m(function(){a.removeEventListener(b,c,!1)});if(a.attachEvent){var d=function(a){a||(a=window.event),a.target=a.target||a.srcElement,c(a)};return a.attachEvent("on"+b,d),m(function(){a.detachEvent("on"+b,d)})}var d=function(a){a||(a=window.event),a.target=a.target||a.srcElement,c(a)};return a["on"+b]=d,m(function(){a["on"+b]=null})}function f(a,b,c){var d=new n;if(a&&a.nodeName||a===window)d.add(e(a,b,c));else if(a&&a.length)for(var g=0,h=a.length;h>g;g++)d.add(f(a[g],b,c));return d}function g(){if(a.XMLHttpRequest)return new a.XMLHttpRequest;try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){throw new Error("XMLHttpRequest is not supported by your browser")}}var h="object"==typeof exports&&exports,i=("object"==typeof module&&module&&module.exports==h&&module,"object"==typeof a&&a);i.global===i&&(window=i);var c=window.Rx,j=c.Observable,k=(j.prototype,j.create),l=j.createWithDisposable,m=c.Disposable.create,n=c.CompositeDisposable,o=c.SingleAssignmentDisposable,p=c.Subject,q=c.Scheduler,r=c.DOM={},s=c.DOM.Request={};r.fromEvent=function(a,b){return l(function(c){return f(a,b,function(a){c.onNext(a)})})},s.ajaxCold=function(a){return l(function(b){"string"==typeof a&&(a={method:"GET",url:a,async:!0}),a.async===d&&(a.async=!0);var c;try{c=g()}catch(e){b.onError(e)}try{if(a.user?c.open(a.method,a.url,a.async,a.user,a.password):c.open(a.method,a.url,a.async),a.headers){var f=a.headers;for(var h in f)f.hasOwnProperty(h)&&c.setRequestHeader(h,f[h])}c.onreadystatechange=c.onload=function(){if(4===c.readyState){var a=c.status;a>=200&&300>=a||0===a||""===a?(b.onNext(c),b.onCompleted()):b.onError(c)}},c.onerror=function(){b.onError(c)},c.send(a.body||null)}catch(i){b.onError(i)}return m(function(){4!==c.readyState&&c.abort()})})};var t=s.ajaxCold,u=s.ajax=function(a){return t(a).publishLast().refCount()};s.post=function(a,b){return u({url:a,body:b,method:"POST",async:!0})};var v=s.get=function(a){return u({url:a,method:"GET",async:!0})};JSON&&"function"==typeof JSON.parse&&(s.getJSON=function(a){return v(a).select(function(a){return JSON.parse(a.responseText)})});var w=function(){var a=document.createElement("div");return function(b){a.appendChild(b),a.innerHTML=""}}();s.jsonpRequestCold=function(){var a=0;return function(b){return j.createWithDisposable(function(c){"string"==typeof b&&(b={url:b}),b.jsonp||(b.jsonp="JSONPCallback");var e=document.getElementsByTagName("head")[0]||document.documentElement,f=document.createElement("script"),g="rxjscallback"+a++;return b.url=b.url.replace("="+b.jsonp,"="+g),window[g]=function(a){c.onNext(a),c.onCompleted()},f.src=b.url,f.async=!0,f.onload=f.onreadystatechange=function(a,b){(b||!f.readyState||/loaded|complete/.test(f.readyState))&&(f.onload=f.onreadystatechange=null,e&&f.parentNode&&w(f),f=d,window[g]=d)},e.insertBefore(f,e.firstChild),m(function(){f&&(f.onload=f.onreadystatechange=null,e&&f.parentNode&&w(f),f=d,window[g]=d)})})}}();var x=s.jsonpRequestCold;s.jsonpRequest=function(a){return x(a).publishLast().refCount()},window.WebSocket&&(r.fromWebSocket=function(a,b,c){var d=new window.WebSocket(a,b),e=k(function(a){return c&&(d.onopen=function(a){"function"==typeof c?c(a):c.onNext&&c.onNext(a)}),d.onmessage=function(b){a.onNext(b)},d.onerror=function(b){a.onError(b)},d.onclose=function(){a.onCompleted()},function(){d.close()}}),f=observerCreate(function(a){d.readyState===WebSocket.OPEN&&d.send(a)});return p.create(f,e)}),window.Worker&&(r.fromWebWorker=function(a){var b=new window.Worker(a),c=l(function(a){return b.onmessage=function(b){a.onNext(b)},b.onerror=function(b){a.onError(b)},m(function(){b.close()})}),d=observerCreate(function(a){b.postMessage(a)});return p.create(d,c)}),window.MutationObserver&&(r.fromMutationObserver=function(a,b){return k(function(c){var d=new MutationObserver(function(a){c.onNext(a)});return d.observe(a,b),function(){d.disconnect()}})});var y,z;window.requestAnimationFrame?(y=window.requestAnimationFrame,z=window.cancelAnimationFrame):window.mozRequestAnimationFrame?(y=window.mozRequestAnimationFrame,z=window.mozCancelAnimationFrame):window.webkitRequestAnimationFrame?(y=window.webkitRequestAnimationFrame,z=window.webkitCancelAnimationFrame):window.msRequestAnimationFrame?(y=window.msRequestAnimationFrame,z=window.msCancelAnimationFrame):window.oRequestAnimationFrame?(y=window.oRequestAnimationFrame,z=window.oCancelAnimationFrame):(y=function(a){window.setTimeout(a,1e3/60)},z=window.clearTimeout),q.requestAnimationFrameScheduler=function(){function a(){return(new Date).getTime()}function b(a,b){var c=this,d=new o,e=y(function(){d.isDisposed||d.setDisposable(b(c,a))});return new n(d,m(function(){z(e)}))}function c(a,b,c){var d=this,e=q.normalize(b);if(0===e)return d.scheduleWithState(a,c);var f,g=new o,h=function(){f&&z(f),e-d.now()<=0?g.isDisposed||g.setDisposable(c(d,a)):f=y(h)};return f=y(h),new n(g,m(function(){z(f)}))}function d(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}return new q(a,b,c,d)}();var A=window.MutationObserver||window.WebKitMutationObserver;return A&&(q.mutationObserverScheduler=function(){function a(a){var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}function b(a){var b=i++;return h[b]=a,k.setAttribute("drainQueue","drainQueue"),b}function c(a){delete h[a]}function d(){return(new Date).getTime()}function e(a,c){var d=this,e=new o;return b(function(){e.isDisposed||e.setDisposable(c(d,a))}),e}function f(a,d,e){var f=this,g=q.normalize(d);if(0===g)return f.scheduleWithState(a,e);var h,i=new o,j=function(){h&&c(h),g-f.now()<=0?i.isDisposed||i.setDisposable(e(f,a)):h=b(j)};return h=b(j),new n(i,m(function(){c(h)}))}function g(a,b,c){return this.scheduleWithRelativeAndState(a,b-this.now(),c)}var h={},i=0,j=new A(function(){var b=a(h);h={};for(var c in b)b.hasOwnProperty(c)&&b[c]()}),k=document.createElement("div");return j.observe(k,{attributes:!0}),window.addEventListener("unload",function(){j.disconnect(),j=null},!1),new q(d,e,f,g)}()),c}); | aheinze/cdnjs | ajax/libs/rxjs-dom/2.0.3/rx.dom.min.js | JavaScript | mit | 6,482 |
(function(t,e){function n(){}function r(t){return t}function i(){return(new Date).getTime()}function o(t,e){return t===e}function s(t,e){return t-e}function u(t){return""+t}function c(t){throw t}function a(){if(this.isDisposed)throw Error(E)}function h(t,e){return 1===t.length&&Array.isArray(t[e])?t[e]:x.call(t)}function l(t,e){for(var n=Array(t),r=0;t>r;r++)n[r]=e();return n}function f(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function p(t,e,n,r,i){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=i||s,this.disposable=new I}function d(t,n){return new xe(function(r){var i=new I,o=new F;return o.setDisposable(i),i.setDisposable(t.subscribe(r.onNext.bind(r),function(t){var i,s;try{s=n(t)}catch(u){return r.onError(u),e}i=new I,o.setDisposable(i),i.setDisposable(s.subscribe(r))},r.onCompleted.bind(r))),o})}function b(t,n){var r=this;return new xe(function(i){var o=0,s=t.length;return r.subscribe(function(r){if(s>o){var u,c=t[o++];try{u=n(r,c)}catch(a){return i.onError(a),e}i.onNext(u)}else i.onCompleted()},i.onError.bind(i),i.onCompleted.bind(i))})}function v(t){return this.select(t).mergeObservable()}var m="object"==typeof exports&&exports&&("object"==typeof global&&global&&global==global.global&&(t=global),exports),y={Internals:{}},w="Sequence contains no elements.",g="Argument out of range",E="Object has been disposed";Function.prototype.bind||(Function.prototype.bind=function(t){var e=this,n=x.call(arguments,1),r=function(){function i(){}if(this instanceof r){i.prototype=e.prototype;var o=new i,s=e.apply(o,n.concat(x.call(arguments)));return Object(s)===s?s:o}return e.apply(t,n.concat(x.call(arguments)))};return r});var x=Array.prototype.slice,A={}.hasOwnProperty,C=y.Internals.inherits=function(t,e){function n(){this.constructor=t}for(var r in e)"prototype"!==r&&A.call(e,r)&&(t[r]=e[r]);return n.prototype=e.prototype,t.prototype=new n,t.super_=e.prototype,t},_=y.Internals.addProperties=function(t){for(var e=x.call(arguments,1),n=0,r=e.length;r>n;n++){var i=e[n];for(var o in i)t[o]=i[o]}},D=y.Internals.addRef=function(t,e){return new xe(function(n){return new O(e.getDisposable(),t.subscribe(n))})},S=Object("a"),N="a"!=S[0]||!(0 in S);Array.prototype.every||(Array.prototype.every=function(t){var e=Object(this),n=N&&"[object String]"=={}.toString.call(this)?this.split(""):e,r=n.length>>>0,i=arguments[1];if("[object Function]"!={}.toString.call(t))throw new TypeError(t+" is not a function");for(var o=0;r>o;o++)if(o in n&&!t.call(i,n[o],o,e))return!1;return!0}),Array.prototype.map||(Array.prototype.map=function(t){var e=Object(this),n=N&&"[object String]"=={}.toString.call(this)?this.split(""):e,r=n.length>>>0,i=Array(r),o=arguments[1];if("[object Function]"!={}.toString.call(t))throw new TypeError(t+" is not a function");for(var s=0;r>s;s++)s in n&&(i[s]=t.call(o,n[s],s,e));return i}),Array.prototype.filter||(Array.prototype.filter=function(t){for(var e,n=[],r=Object(this),i=0,o=r.length>>>0;o>i;i++)e=r[i],i in r&&t.call(arguments[1],e,i,r)&&n.push(e);return n}),Array.isArray||(Array.isArray=function(t){return"[object Array]"==Object.prototype.toString.call(t)}),Array.prototype.indexOf||(Array.prototype.indexOf=function(t){var e=Object(this),n=e.length>>>0;if(0===n)return-1;var r=0;if(arguments.length>1&&(r=Number(arguments[1]),r!=r?r=0:0!=r&&1/0!=r&&r!=-1/0&&(r=(r>0||-1)*Math.floor(Math.abs(r)))),r>=n)return-1;for(var i=r>=0?r:Math.max(n-Math.abs(r),0);n>i;i++)if(i in e&&e[i]===t)return i;return-1});var R=function(t,e){this.id=t,this.value=e};R.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var W=function(t){this.items=Array(t),this.length=0},k=W.prototype;k.isHigherPriority=function(t,e){return 0>this.items[t].compareTo(this.items[e])},k.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},k.heapify=function(t){if(t===e&&(t=0),!(t>=this.length||0>t)){var n=2*t+1,r=2*t+2,i=t;if(this.length>n&&this.isHigherPriority(n,i)&&(i=n),this.length>r&&this.isHigherPriority(r,i)&&(i=r),i!==t){var o=this.items[t];this.items[t]=this.items[i],this.items[i]=o,this.heapify(i)}}},k.peek=function(){return this.items[0].value},k.removeAt=function(t){this.items[t]=this.items[--this.length],delete this.items[this.length],this.heapify()},k.dequeue=function(){var t=this.peek();return this.removeAt(0),t},k.enqueue=function(t){var e=this.length++;this.items[e]=new R(W.count++,t),this.percolate(e)},k.remove=function(t){for(var e=0;this.length>e;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},W.count=0;var O=y.CompositeDisposable=function(){this.disposables=h(arguments,0),this.isDisposed=!1,this.length=this.disposables.length};O.prototype.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},O.prototype.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},O.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()}},O.prototype.clear=function(){var t=this.disposables.slice(0);this.disposables=[],this.length=0;for(var e=0,n=t.length;n>e;e++)t[e].dispose()},O.prototype.contains=function(t){return-1!==this.disposables.indexOf(t)},O.prototype.toArray=function(){return this.disposables.slice(0)};var q=y.Disposable=function(t){this.isDisposed=!1,this.action=t};q.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var T=q.create=function(t){return new q(t)},j=q.empty={dispose:n},I=y.SingleAssignmentDisposable=function(){this.isDisposed=!1,this.current=null};I.prototype.disposable=function(t){return t?this.setDisposable(t):this.getDisposable()},I.prototype.getDisposable=function(){return this.current},I.prototype.setDisposable=function(t){if(this.current)throw Error("Disposable has already been assigned");var e=this.isDisposed;e||(this.current=t),e&&t&&t.dispose()},I.prototype.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()};var F=y.SerialDisposable=function(){this.isDisposed=!1,this.current=null};F.prototype.getDisposable=function(){return this.current},F.prototype.setDisposable=function(t){var e,n=this.isDisposed;n||(e=this.current,this.current=t),e&&e.dispose(),n&&t&&t.dispose()},F.prototype.disposable=function(t){return t?(this.setDisposable(t),e):this.getDisposable()},F.prototype.dispose=function(){var t;this.isDisposed||(this.isDisposed=!0,t=this.current,this.current=null),t&&t.dispose()};var P=y.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?j:new t(this)},e}();f.prototype.dispose=function(){var t=this;this.scheduler.schedule(function(){t.isDisposed||(t.isDisposed=!0,t.disposable.dispose())})},p.prototype.invoke=function(){this.disposable.disposable(this.invokeCore())},p.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},p.prototype.isCancelled=function(){return this.disposable.isDisposed},p.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var V=y.Scheduler=function(){function e(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function n(t,e){var n=e.first,r=e.second,i=new O,o=function(e){r(e,function(e){var n=!1,r=!1,s=t.scheduleWithState(e,function(t,e){return n?i.remove(s):r=!0,o(e),j});r||(i.add(s),n=!0)})};return o(n),i}function r(t,e,n){var r=e.first,i=e.second,o=new O,s=function(e){i(e,function(e,r){var i=!1,u=!1,c=t[n].call(t,e,r,function(t,e){return i?o.remove(c):u=!0,s(e),j});u||(o.add(c),i=!0)})};return s(r),o}function o(t,e){return e(),j}var s=e.prototype;return s.catchException=function(t){return new U(this,t)},s.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,function(){e()})},s.schedulePeriodicWithState=function(e,n,r){var i=e,o=t.setInterval(function(){i=r(i)},n);return T(function(){t.clearInterval(o)})},s.schedule=function(t){return this._schedule(t,o)},s.scheduleWithState=function(t,e){return this._schedule(t,e)},s.scheduleWithRelative=function(t,e){return this._scheduleRelative(e,t,o)},s.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},s.scheduleWithAbsolute=function(t,e){return this._scheduleAbsolute(e,t,o)},s.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},s.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,function(t,e){t(function(){e(t)})})},s.scheduleRecursiveWithState=function(t,e){return this.scheduleWithState({first:t,second:e},function(t,e){return n(t,e)})},s.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,function(t,e){t(function(n){e(t,n)})})},s.scheduleRecursiveWithRelativeAndState=function(t,e,n){return this._scheduleRelative({first:t,second:n},e,function(t,e){return r(t,e,"scheduleWithRelativeAndState")})},s.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,function(t,e){t(function(n){e(t,n)})})},s.scheduleRecursiveWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute({first:t,second:n},e,function(t,e){return r(t,e,"scheduleWithAbsoluteAndState")})},e.now=i,e.normalize=function(t){return 0>t&&(t=0),t},e}(),M="Scheduler is not allowed to block the thread",z=V.immediate=function(){function t(t,e){return e(this,t)}function e(t,e,n){if(e>0)throw Error(M);return n(this,t)}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new V(i,t,e,n)}(),L=V.currentThread=function(){function t(){o=new W(4)}function e(t,e){return this.scheduleWithRelativeAndState(t,0,e)}function n(e,n,r){var i,s=this.now()+V.normalize(n),u=new p(this,e,r,s);if(o)o.enqueue(u);else{i=new t;try{o.enqueue(u),i.run()}catch(c){throw c}finally{i.dispose()}}return u.disposable}function r(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var o;t.prototype.dispose=function(){o=null},t.prototype.run=function(){for(var t;o.length>0;)if(t=o.dequeue(),!t.isCancelled()){for(;t.dueTime-V.now()>0;);t.isCancelled()||t.invoke()}};var s=new V(i,e,n,r);return s.scheduleRequired=function(){return null===o},s.ensureTrampoline=function(t){return null===o?this.schedule(t):t()},s}(),B=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new I;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}();y.VirtualTimeScheduler=function(){function t(){return this.toDateTimeOffset(this.clock)}function n(t,e){return this.scheduleAbsoluteWithState(t,this.clock,e)}function r(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e),n)}function i(t,e,n){return this.scheduleRelativeWithState(t,this.toRelative(e-this.now()),n)}function o(t,e){return e(),j}function s(e,o){this.clock=e,this.comparer=o,this.isEnabled=!1,this.queue=new W(1024),s.super_.constructor.call(this,t,n,r,i)}return C(s,V),_(s.prototype,{schedulePeriodicWithState:function(t,e,n){var r=new B(this,t,e,n);return r.start()},scheduleRelativeWithState:function(t,e,n){var r=this.add(this.clock,e);return this.scheduleAbsoluteWithState(t,r,n)},scheduleRelative:function(t,e){return this.scheduleRelativeWithState(e,t,o)},start:function(){var t;if(!this.isEnabled){this.isEnabled=!0;do t=this.getNext(),null!==t?(this.comparer(t.dueTime,this.clock)>0&&(this.clock=t.dueTime),t.invoke()):this.isEnabled=!1;while(this.isEnabled)}},stop:function(){this.isEnabled=!1},advanceTo:function(t){var e,n=this.comparer(this.clock,t);if(this.comparer(this.clock,t)>0)throw Error(g);if(0!==n&&!this.isEnabled){this.isEnabled=!0;do e=this.getNext(),null!==e&&0>=this.comparer(e.dueTime,t)?(this.comparer(e.dueTime,this.clock)>0&&(this.clock=e.dueTime),e.invoke()):this.isEnabled=!1;while(this.isEnabled);this.clock=t}},advanceBy:function(t){var n=this.add(this.clock,t),r=this.comparer(this.clock,n);if(r>0)throw Error(g);return 0!==r?this.advanceTo(n):e},sleep:function(t){var e=this.add(this.clock,t);if(this.comparer(this.clock,e)>=0)throw Error(g);this.clock=e},getNext:function(){for(var t;this.queue.length>0;){if(t=this.queue.peek(),!t.isCancelled())return t;this.queue.dequeue()}return null},scheduleAbsolute:function(t,e){return this.scheduleAbsoluteWithState(e,t,o)},scheduleAbsoluteWithState:function(t,e,n){var r=this,i=function(t,e){return r.queue.remove(o),n(t,e)},o=new p(r,t,i,e,r.comparer);return r.queue.enqueue(o),o.disposable}}),s}(),y.HistoricalScheduler=function(){function t(e,n){var r=null==e?0:e,i=n||s;t.super_.constructor.call(this,r,i)}C(t,y.VirtualTimeScheduler);var e=t.prototype;return e.add=function(t,e){return t+e},e.toDateTimeOffset=function(t){return new Date(t).getTime()},e.toRelative=function(t){return t},t}();var H=V.timeout=function(){function r(t,e){var n=this,r=new I,i=u(function(){r.setDisposable(e(n,t))});return new O(r,T(function(){c(i)}))}function o(e,n,r){var i=this,o=V.normalize(n);if(0===o)return i.scheduleWithState(e,r);var s=new I,u=t.setTimeout(function(){s.setDisposable(r(i,e))},o);return new O(s,T(function(){t.clearTimeout(u)}))}function s(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}var u,c,a=t.requestAnimationFrame||t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.oRequestAnimationFrame||t.msRequestAnimationFrame,h=t.cancelAnimationFrame||t.webkitCancelAnimationFrame||t.mozCancelAnimationFrame||t.oCancelAnimationFrame||t.msCancelAnimationFrame;return t.process!==e&&"function"==typeof t.process.nextTick?(u=t.process.nextTick,c=n):"function"==typeof t.setImmediate?(u=t.setImmediate,c=t.clearImmediate):"function"==typeof a?(u=a,c=h):(u=function(e){return t.setTimeout(e,0)},c=t.clearTimeout),new V(i,r,o,s)}(),U=function(){function t(){return this._scheduler.now()}function e(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function n(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function r(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function i(o,s){this._scheduler=o,this._handler=s,this._recursiveOriginal=null,this._recursiveWrapper=null,i.super_.constructor.call(this,t,e,n,r)}return C(i,V),i.prototype._clone=function(t){return new i(t,this._handler)},i.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(i){if(!e._handler(i))throw i;return j}}},i.prototype._getRecursiveWrapper=function(t){if(!this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},i.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,i=!1,o=new I;return o.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(i)return null;try{return n(t)}catch(e){if(i=!0,!r._handler(e))throw e;return o.dispose(),null}})),o},i}(),G=y.Notification=function(){function t(t,e){this.hasValue=null==e?!1:e,this.kind=t}var e=t.prototype;return e.accept=function(t,e,n){return arguments.length>1||"function"==typeof t?this._accept(t,e,n):this._acceptObservable(t)},e.toObservable=function(t){var e=this;return t=t||z,new xe(function(n){return t.schedule(function(){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},e.equals=function(t){var e=null==t?"":""+t;return""+this===e},t}(),J=G.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){var i=new G("N",!0);return i.value=r,i._accept=t.bind(i),i._acceptObservable=e.bind(i),i.toString=n.bind(i),i}}(),K=G.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){var i=new G("E");return i.exception=r,i._accept=t.bind(i),i._acceptObservable=e.bind(i),i.toString=n.bind(i),i}}(),Q=G.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){var r=new G("C");return r._accept=t.bind(r),r._acceptObservable=e.bind(r),r.toString=n.bind(r),r}}(),X=y.Internals.Enumerator=function(t,e,n){this.moveNext=t,this.getCurrent=e,this.dispose=n},Y=X.create=function(t,e,r){var i=!1;return r||(r=n),new X(function(){if(i)return!1;var e=t();return e||(i=!0,r()),e},function(){return e()},function(){i||(r(),i=!0)})},Z=y.Internals.Enumerable=function(){function t(t){this.getEnumerator=t}return t.prototype.concat=function(){var t=this;return new xe(function(n){var r=t.getEnumerator(),i=!1,o=new F,s=z.scheduleRecursive(function(t){var s,u,c=!1;if(!i){try{c=r.moveNext(),c?s=r.getCurrent():r.dispose()}catch(a){u=a,r.dispose()}if(u)return n.onError(u),e;if(!c)return n.onCompleted(),e;var h=new I;o.setDisposable(h),h.setDisposable(s.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){t()}))}});return new O(o,s,T(function(){i=!0,r.dispose()}))})},t.prototype.catchException=function(){var t=this;return new xe(function(n){var r,i=t.getEnumerator(),o=!1,s=new F,u=z.scheduleRecursive(function(t){var u,c,a;if(a=!1,!o){try{a=i.moveNext(),a&&(u=i.getCurrent())}catch(h){c=h}if(c)return n.onError(c),e;if(!a)return r?n.onError(r):n.onCompleted(),e;var l=new I;s.setDisposable(l),l.setDisposable(u.subscribe(n.onNext.bind(n),function(e){r=e,t()},n.onCompleted.bind(n)))}});return new O(s,u,T(function(){o=!0}))})},t}(),$=Z.repeat=function(t,n){return n===e&&(n=-1),new Z(function(){var e,r=n;return Y(function(){return 0===r?!1:(r>0&&r--,e=t,!0)},function(){return e})})},te=Z.forEach=function(t,e){return e||(e=r),new Z(function(){var n,r=-1;return Y(function(){return++r<t.length?(n=e(t[r],r),!0):!1},function(){return n})})},ee=y.Observer=function(){};ee.prototype.toNotifier=function(){var t=this;return function(e){return e.accept(t)}},ee.prototype.asObserver=function(){return new oe(this.onNext.bind(this),this.onError.bind(this),this.onCompleted.bind(this))},ee.prototype.checked=function(){return new se(this)};var ne=ee.create=function(t,e,r){return t||(t=n),e||(e=c),r||(r=n),new oe(t,e,r)};ee.fromNotifier=function(t){return new oe(function(e){return t(J(e))},function(e){return t(K(e))},function(){return t(Q())})};var re,ie=y.Internals.AbstractObserver=function(){function t(){this.isStopped=!1}return C(t,ee),t.prototype.onNext=function(t){this.isStopped||this.next(t)},t.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.error(t))},t.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.completed())},t.prototype.dispose=function(){this.isStopped=!0},t.prototype.fail=function(){return this.isStopped?!1:(this.isStopped=!0,this.error(!0),!0)},t}(),oe=y.AnonymousObserver=function(){function t(e,n,r){t.super_.constructor.call(this),this._onNext=e,this._onError=n,this._onCompleted=r}return C(t,ie),t.prototype.next=function(t){this._onNext(t)},t.prototype.error=function(t){this._onError(t)},t.prototype.completed=function(){this._onCompleted()},t}(),se=function(){function t(t){this._observer=t,this._state=0}return C(t,ee),t.prototype.onNext=function(t){this.checkAccess();try{this._observer.onNext(t)}catch(e){throw e}finally{this._state=0}},t.prototype.onError=function(t){this.checkAccess();try{this._observer.onError(t)}catch(e){throw e}finally{this._state=2}},t.prototype.onCompleted=function(){this.checkAccess();try{this._observer.onCompleted()}catch(t){throw t}finally{this._state=2}},t.prototype.checkAccess=function(){if(1===this._state)throw Error("Re-entrancy detected");if(2===this._state)throw Error("Observer completed");0===this._state&&(this._state=1)},t}(),ue=y.Internals.ScheduledObserver=function(){function t(e,n){t.super_.constructor.call(this),this.scheduler=e,this.observer=n,this.isAcquired=!1,this.hasFaulted=!1,this.queue=[],this.disposable=new F}return C(t,ie),t.prototype.next=function(t){var e=this;this.queue.push(function(){e.observer.onNext(t)})},t.prototype.error=function(t){var e=this;this.queue.push(function(){e.observer.onError(t)})},t.prototype.completed=function(){var t=this;this.queue.push(function(){t.observer.onCompleted()})},t.prototype.ensureActive=function(){var t=!1,n=this;!this.hasFaulted&&this.queue.length>0&&(t=!this.isAcquired,this.isAcquired=!0),t&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(t){var r;if(!(n.queue.length>0))return n.isAcquired=!1,e;r=n.queue.shift();try{r()}catch(i){throw n.queue=[],n.hasFaulted=!0,i}t()}))},t.prototype.dispose=function(){t.super_.dispose.call(this),this.disposable.dispose()},t}(),ce=function(){function t(){t.super_.constructor.apply(this,arguments)}return C(t,ue),t.prototype.next=function(e){t.super_.next.call(this,e),this.ensureActive()},t.prototype.error=function(e){t.super_.error.call(this,e),this.ensureActive()},t.prototype.completed=function(){t.super_.completed.call(this),this.ensureActive()},t}(),ae=y.Observable=function(){function t(t){this._subscribe=t}return re=t.prototype,re.finalValue=function(){var t=this;return new xe(function(e){var n,r=!1;return t.subscribe(function(t){r=!0,n=t},e.onError.bind(e),function(){r?(e.onNext(n),e.onCompleted()):e.onError(Error(w))})})},re.subscribe=re.forEach=function(t,e,n){var r;return r=0===arguments.length||arguments.length>1||"function"==typeof t?ne(t,e,n):t,this._subscribe(r)},re.toArray=function(){function t(t,e){return t.push(e),t.slice(0)}return this.scan([],t).startWith([]).finalValue()},t}();ae.start=function(t,e){return he(t,e)()};var he=ae.toAsync=function(t,n,r){return n||(n=H),function(){var i=x.call(arguments,0),o=new Se;return n.schedule(function(){var n;try{n=t.apply(r,i)}catch(s){return o.onError(s),e}o.onNext(n),o.onCompleted()}),o.asObservable()}};re.observeOn=function(t){var e=this;return new xe(function(n){return e.subscribe(new ce(t,n))})},re.subscribeOn=function(t){var e=this;return new xe(function(n){var r=new I,i=new F;return i.setDisposable(r),r.setDisposable(t.schedule(function(){i.setDisposable(new f(t,e.subscribe(n)))})),i})},ae.create=function(t){return new xe(function(e){return T(t(e))})},ae.createWithDisposable=function(t){return new xe(t)};var le=ae.defer=function(t){return new xe(function(e){var n;try{n=t()}catch(r){return ve(r).subscribe(e)}return n.subscribe(e)})},fe=ae.empty=function(t){return t||(t=z),new xe(function(e){return t.schedule(function(){e.onCompleted()})})},pe=ae.fromArray=function(t,e){return e||(e=L),new xe(function(n){var r=0;return e.scheduleRecursive(function(e){t.length>r?(n.onNext(t[r++]),e()):n.onCompleted()})})};ae.generate=function(t,n,r,i,o){return o||(o=L),new xe(function(s){var u=!0,c=t;return o.scheduleRecursive(function(t){var o,a;try{u?u=!1:c=r(c),o=n(c),o&&(a=i(c))}catch(h){return s.onError(h),e}o?(s.onNext(a),t()):s.onCompleted()})})};var de=ae.never=function(){return new xe(function(){return j})};ae.range=function(t,e,n){return n||(n=L),new xe(function(r){return n.scheduleRecursiveWithState(0,function(n,i){e>n?(r.onNext(t+n),i(n+1)):r.onCompleted()})})},ae.repeat=function(t,n,r){return r||(r=L),n==e&&(n=-1),be(t,r).repeat(n)};var be=ae.returnValue=function(t,e){return e||(e=z),new xe(function(n){return e.schedule(function(){n.onNext(t),n.onCompleted()})})},ve=ae.throwException=function(t,e){return e||(e=z),new xe(function(n){return e.schedule(function(){n.onError(t)})})};ae.using=function(t,e){return new xe(function(n){var r,i,o=j;try{r=t(),r&&(o=r),i=e(r)}catch(s){return new O(ve(s).subscribe(n),o)}return new O(i.subscribe(n),o)})},re.amb=function(t){var e=this;return new xe(function(n){function r(){o||(o=s,a.dispose())}function i(){o||(o=u,c.dispose())}var o,s="L",u="R",c=new I,a=new I;return c.setDisposable(e.subscribe(function(t){r(),o===s&&n.onNext(t)},function(t){r(),o===s&&n.onError(t)},function(){r(),o===s&&n.onCompleted()})),a.setDisposable(t.subscribe(function(t){i(),o===u&&n.onNext(t)},function(t){i(),o===u&&n.onError(t)},function(){i(),o===u&&n.onCompleted()})),new O(c,a)})},ae.amb=function(){function t(t,e){return t.amb(e)}for(var e=de(),n=h(arguments,0),r=0,i=n.length;i>r;r++)e=t(e,n[r]);return e},re.catchException=function(t){return"function"==typeof t?d(this,t):me([this,t])};var me=ae.catchException=function(){var t=h(arguments,0);return te(t).catchException()};re.combineLatest=function(){var t=x.call(arguments);return Array.isArray(t[0])?t[0].unshift(this):t.unshift(this),ye.apply(this,t)};var ye=ae.combineLatest=function(){var t=x.call(arguments),n=t.pop();return Array.isArray(t[0])&&(t=t[0]),new xe(function(r){function i(t){var i;if(c[t]=!0,a||(a=c.every(function(t){return t}))){try{i=n.apply(null,f)}catch(o){return r.onError(o),e}r.onNext(i)}else h.filter(function(e,n){return n!==t}).every(function(t){return t})&&r.onCompleted()}function o(t){h[t]=!0,h.every(function(t){return t})&&r.onCompleted()}for(var s=function(){return!1},u=t.length,c=l(u,s),a=!1,h=l(u,s),f=Array(u),p=Array(u),d=0;u>d;d++)(function(e){p[e]=new I,p[e].setDisposable(t[e].subscribe(function(t){f[e]=t,i(e)},r.onError.bind(r),function(){o(e)}))})(d);return new O(p)})};re.concat=function(){var t=x.call(arguments,0);return t.unshift(this),we.apply(this,t)};var we=ae.concat=function(){var t=h(arguments,0);return te(t).concat()};re.concatObservable=re.concatAll=function(){return this.merge(1)},re.merge=function(t){if("number"!=typeof t)return ge(this,t);var e=this;return new xe(function(n){var r=0,i=new O,o=!1,s=[],u=function(t){var e=new I;i.add(e),e.setDisposable(t.subscribe(n.onNext.bind(n),n.onError.bind(n),function(){var t;i.remove(e),s.length>0?(t=s.shift(),u(t)):(r--,o&&0===r&&n.onCompleted())}))};return i.add(e.subscribe(function(e){t>r?(r++,u(e)):s.push(e)},n.onError.bind(n),function(){o=!0,0===r&&n.onCompleted()})),i})};var ge=ae.merge=function(){var t,e;return arguments[0]?arguments[0].now?(t=arguments[0],e=x.call(arguments,1)):(t=z,e=x.call(arguments,0)):(t=z,e=x.call(arguments,1)),Array.isArray(e[0])&&(e=e[0]),pe(e,t).mergeObservable()};re.mergeObservable=re.mergeAll=function(){var t=this;return new xe(function(e){var n=new O,r=!1,i=new I;return n.add(i),i.setDisposable(t.subscribe(function(t){var i=new I;n.add(i),i.setDisposable(t.subscribe(function(t){e.onNext(t)},e.onError.bind(e),function(){n.remove(i),r&&1===n.length&&e.onCompleted()}))},e.onError.bind(e),function(){r=!0,1===n.length&&e.onCompleted()})),n})},re.onErrorResumeNext=function(t){if(!t)throw Error("Second observable is required");return Ee([this,t])};var Ee=ae.onErrorResumeNext=function(){var t=h(arguments,0);return new xe(function(e){var n=0,r=new F,i=z.scheduleRecursive(function(i){var o,s;t.length>n?(o=t[n++],s=new I,r.setDisposable(s),s.setDisposable(o.subscribe(e.onNext.bind(e),function(){i()},function(){i()}))):e.onCompleted()});return new O(r,i)})};re.skipUntil=function(t){var e=this;return new xe(function(n){var r=!1,i=new O(e.subscribe(function(t){r&&n.onNext(t)},n.onError.bind(n),function(){r&&n.onCompleted()})),o=new I;return i.add(o),o.setDisposable(t.subscribe(function(){r=!0,o.dispose()},n.onError.bind(n),function(){o.dispose()})),i})},re.switchLatest=function(){var t=this;return new xe(function(e){var n=!1,r=new F,i=!1,o=0,s=t.subscribe(function(t){var s=new I,u=++o;n=!0,r.setDisposable(s),s.setDisposable(t.subscribe(function(t){o===u&&e.onNext(t)},function(t){o===u&&e.onError(t)},function(){o===u&&(n=!1,i&&e.onCompleted())}))},e.onError.bind(e),function(){i=!0,n||e.onCompleted()});return new O(s,r)})},re.takeUntil=function(t){var e=this;return new xe(function(r){return new O(e.subscribe(r),t.subscribe(r.onCompleted.bind(r),r.onError.bind(r),n))})},re.zip=function(){if(Array.isArray(arguments[0]))return b.apply(this,arguments);var t=this,n=x.call(arguments),r=n.pop();return n.unshift(t),new xe(function(i){function o(t){c[t]=!0,c.every(function(t){return t})&&i.onCompleted()}for(var s=n.length,u=l(s,function(){return[]}),c=l(s,function(){return!1}),a=function(n){var o,s;if(u.every(function(t){return t.length>0})){try{s=u.map(function(t){return t.shift()}),o=r.apply(t,s)}catch(a){return i.onError(a),e}i.onNext(o)}else c.filter(function(t,e){return e!==n}).every(function(t){return t})&&i.onCompleted()},h=Array(s),f=0;s>f;f++)(function(t){h[t]=new I,h[t].setDisposable(n[t].subscribe(function(e){u[t].push(e),a(t)},i.onError.bind(i),function(){o(t)}))})(f);return new O(h)})},re.asObservable=function(){var t=this;return new xe(function(e){return t.subscribe(e)})},re.bufferWithCount=function(t,n){return n===e&&(n=t),this.windowWithCount(t,n).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},re.dematerialize=function(){var t=this;return new xe(function(e){return t.subscribe(function(t){return t.accept(e)},e.onError.bind(e),e.onCompleted.bind(e))})},re.distinctUntilChanged=function(t,n){var i=this;return t||(t=r),n||(n=o),new xe(function(r){var o,s=!1;return i.subscribe(function(i){var u,c=!1;try{u=t(i)}catch(a){return r.onError(a),e}if(s)try{c=n(o,u)}catch(a){return r.onError(a),e}s&&c||(s=!0,o=u,r.onNext(i))},r.onError.bind(r),r.onCompleted.bind(r))})},re.doAction=function(t,e,n){var r,i=this;return"function"==typeof t?r=t:(r=t.onNext.bind(t),e=t.onError.bind(t),n=t.onCompleted.bind(t)),new xe(function(t){return i.subscribe(function(e){try{r(e)}catch(n){t.onError(n)}t.onNext(e)},function(n){if(e){try{e(n)}catch(r){t.onError(r)}t.onError(n)}else t.onError(n)},function(){if(n){try{n()}catch(e){t.onError(e)}t.onCompleted()}else t.onCompleted()})})},re.finallyAction=function(t){var e=this;return new xe(function(n){var r=e.subscribe(n);return T(function(){try{r.dispose()}catch(e){throw e}finally{t()}})})},re.ignoreElements=function(){var t=this;return new xe(function(e){return t.subscribe(n,e.onError.bind(e),e.onCompleted.bind(e))})},re.materialize=function(){var t=this;return new xe(function(e){return t.subscribe(function(t){e.onNext(J(t))},function(t){e.onNext(K(t)),e.onCompleted()},function(){e.onNext(Q()),e.onCompleted()})})},re.repeat=function(t){return $(this,t).concat()},re.retry=function(t){return $(this,t).catchException()},re.scan=function(){var t,e,n=!1;2===arguments.length?(t=arguments[0],e=arguments[1],n=!0):e=arguments[0];var r=this;return le(function(){var i,o=!1;return r.select(function(r){return o?i=e(i,r):(i=n?e(t,r):r,o=!0),i})})},re.skipLast=function(t){var e=this;return new xe(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},n.onError.bind(n),n.onCompleted.bind(n))})},re.startWith=function(){var t,n,r=0;return arguments.length>0&&null!=arguments[0]&&arguments[0].now!==e?(n=arguments[0],r=1):n=z,t=x.call(arguments,r),te([pe(t,n),this]).concat()},re.takeLast=function(t,e){return this.takeLastBuffer(t).selectMany(function(t){return pe(t,e)})},re.takeLastBuffer=function(t){var e=this;return new xe(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},n.onError.bind(n),function(){n.onNext(r),n.onCompleted()
})})},re.windowWithCount=function(t,e){var n=this;if(0>=t)throw Error(g);if(null==e&&(e=t),0>=e)throw Error(g);return new xe(function(r){var i=new I,o=new P(i),s=0,u=[],c=function(){var t=new De;u.push(t),r.onNext(D(t,o))};return c(),i.setDisposable(n.subscribe(function(n){for(var r,i=0,o=u.length;o>i;i++)u[i].onNext(n);var a=s-t+1;a>=0&&0===a%e&&(r=u.shift(),r.onCompleted()),s++,0===s%e&&c()},function(t){for(;u.length>0;)u.shift().onError(t);r.onError(t)},function(){for(;u.length>0;)u.shift().onCompleted();r.onCompleted()})),o})},re.defaultIfEmpty=function(t){var n=this;return t===e&&(t=null),new xe(function(e){var r=!1;return n.subscribe(function(t){r=!0,e.onNext(t)},e.onError.bind(e),function(){r||e.onNext(t),e.onCompleted()})})},re.distinct=function(t,n){var i=this;return t||(t=r),n||(n=u),new xe(function(r){var o={};return i.subscribe(function(i){var s,u,c,a=!1;try{s=t(i),u=n(s)}catch(h){return r.onError(h),e}for(c in o)if(u===c){a=!0;break}a||(o[u]=null,r.onNext(i))},r.onError.bind(r),r.onCompleted.bind(r))})},re.groupBy=function(t,e,n){return this.groupByUntil(t,e,function(){return de()},n)},re.groupByUntil=function(t,i,o,s){var c=this;return i||(i=r),s||(s=u),new xe(function(r){var u={},a=new O,h=new P(a);return a.add(c.subscribe(function(c){var l,f,p,d,b,v,m,y,w,g,E;try{m=t(c),y=s(m)}catch(x){for(E in u)u[E].onError(x);return r.onError(x),e}b=!1;try{g=u[y],g||(g=new De,u[y]=g,b=!0)}catch(x){for(E in u)u[E].onError(x);return r.onError(x),e}if(b){v=new Ce(m,g,h),f=new Ce(m,g);try{l=o(f)}catch(x){for(E in u)u[E].onError(x);return r.onError(x),e}r.onNext(v),w=new I,a.add(w),d=function(){y in u&&(delete u[y],g.onCompleted()),a.remove(w)},w.setDisposable(l.take(1).subscribe(n,function(t){for(E in u)u[E].onError(t);r.onError(t)},function(){d()}))}try{p=i(c)}catch(x){for(E in u)u[E].onError(x);return r.onError(x),e}g.onNext(p)},function(t){for(var e in u)u[e].onError(t);r.onError(t)},function(){for(var t in u)u[t].onCompleted();r.onCompleted()})),h})},re.select=re.map=function(t){var n=this;return new xe(function(r){var i=0;return n.subscribe(function(n){var o;try{o=t(n,i++)}catch(s){return r.onError(s),e}r.onNext(o)},r.onError.bind(r),r.onCompleted.bind(r))})},re.selectMany=re.flatMap=function(t,e){return e?this.selectMany(function(n){return t(n).select(function(t){return e(n,t)})}):"function"==typeof t?v.call(this,t):v.call(this,function(){return t})},re.skip=function(t){if(0>t)throw Error(g);var e=this;return new xe(function(n){var r=t;return e.subscribe(function(t){0>=r?n.onNext(t):r--},n.onError.bind(n),n.onCompleted.bind(n))})},re.skipWhile=function(t){var n=this;return new xe(function(r){var i=0,o=!1;return n.subscribe(function(n){if(!o)try{o=!t(n,i++)}catch(s){return r.onError(s),e}o&&r.onNext(n)},r.onError.bind(r),r.onCompleted.bind(r))})},re.take=function(t,e){if(0>t)throw Error(g);if(0===t)return fe(e);var n=this;return new xe(function(e){var r=t;return n.subscribe(function(t){r>0&&(r--,e.onNext(t),0===r&&e.onCompleted())},e.onError.bind(e),e.onCompleted.bind(e))})},re.takeWhile=function(t){var n=this;return new xe(function(r){var i=0,o=!0;return n.subscribe(function(n){if(o){try{o=t(n,i++)}catch(s){return r.onError(s),e}o?r.onNext(n):r.onCompleted()}},r.onError.bind(r),r.onCompleted.bind(r))})},re.where=re.filter=function(t){var n=this;return new xe(function(r){var i=0;return n.subscribe(function(n){var o;try{o=t(n,i++)}catch(s){return r.onError(s),e}o&&r.onNext(n)},r.onError.bind(r),r.onCompleted.bind(r))})};var xe=y.Internals.AnonymousObservable=function(){function t(e){var n=function(t){var n=new Ae(t);if(L.scheduleRequired())L.schedule(function(){try{n.disposable(e(n))}catch(t){if(!n.fail(t))throw t}});else try{n.disposable(e(n))}catch(r){if(!n.fail(r))throw r}return n};t.super_.constructor.call(this,n)}return C(t,ae),t}(),Ae=function(){function t(e){t.super_.constructor.call(this),this.observer=e,this.m=new I}return C(t,ie),t.prototype.next=function(t){var e=!1;try{this.observer.onNext(t),e=!0}catch(n){throw n}finally{e||this.dispose()}},t.prototype.error=function(t){try{this.observer.onError(t)}catch(e){throw e}finally{this.dispose()}},t.prototype.completed=function(){try{this.observer.onCompleted()}catch(t){throw t}finally{this.dispose()}},t.prototype.disposable=function(t){return this.m.disposable(t)},t.prototype.dispose=function(){t.super_.dispose.call(this),this.m.dispose()},t}(),Ce=function(){function t(t){return this.underlyingObservable.subscribe(t)}function e(n,r,i){e.super_.constructor.call(this,t),this.key=n,this.underlyingObservable=i?new xe(function(t){return new O(i.getDisposable(),r.subscribe(t))}):r}return C(e,ae),e}(),_e=function(t,e){this.subject=t,this.observer=e};_e.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var De=y.Subject=function(){function t(t){return a.call(this),this.isStopped?this.exception?(t.onError(this.exception),j):(t.onCompleted(),j):(this.observers.push(t),new _e(this,t))}function e(){e.super_.constructor.call(this,t),this.isDisposed=!1,this.isStopped=!1,this.observers=[]}return C(e,ae),_(e.prototype,ee,{onCompleted:function(){if(a.call(this),!this.isStopped){var t=this.observers.slice(0);this.isStopped=!0;for(var e=0,n=t.length;n>e;e++)t[e].onCompleted();this.observers=[]}},onError:function(t){if(a.call(this),!this.isStopped){var e=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var n=0,r=e.length;r>n;n++)e[n].onError(t);this.observers=[]}},onNext:function(t){if(a.call(this),!this.isStopped)for(var e=this.observers.slice(0),n=0,r=e.length;r>n;n++)e[n].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),e.create=function(t,e){return new Ne(t,e)},e}(),Se=y.AsyncSubject=function(){function t(t){if(a.call(this),!this.isStopped)return this.observers.push(t),new _e(this,t);var e=this.exception,n=this.hasValue,r=this.value;return e?t.onError(e):n?(t.onNext(r),t.onCompleted()):t.onCompleted(),j}function e(){e.super_.constructor.call(this,t),this.isDisposed=!1,this.isStopped=!1,this.value=null,this.hasValue=!1,this.observers=[],this.exception=null}return C(e,ae),_(e.prototype,ee,{onCompleted:function(){var t,e,n;if(a.call(this),!this.isStopped){var r=this.observers.slice(0);this.isStopped=!0;var i=this.value,o=this.hasValue;if(o)for(e=0,n=r.length;n>e;e++)t=r[e],t.onNext(i),t.onCompleted();else for(e=0,n=r.length;n>e;e++)r[e].onCompleted();this.observers=[]}},onError:function(t){if(a.call(this),!this.isStopped){var e=this.observers.slice(0);this.isStopped=!0,this.exception=t;for(var n=0,r=e.length;r>n;n++)e[n].onError(t);this.observers=[]}},onNext:function(t){a.call(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),e}(),Ne=function(){function t(t){return this.observable.subscribe(t)}function e(n,r){e.super_.constructor.call(this,t),this.observer=n,this.observable=r}return C(e,ae),_(e.prototype,ee,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),e}();return"function"==typeof define&&"object"==typeof define.amd&&define.amd?(t.Rx=y,define(function(){return y})):(m?"object"==typeof module&&module&&module.exports==m?module.exports=y:m=y:t.Rx=y,e)})(this); | yinghunglai/cdnjs | ajax/libs/rxjs/2.1.0/rx.min.js | JavaScript | mit | 39,429 |
/*
YUI 3.15.0 (build 834026e)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('pjax', function (Y, NAME) {
/**
Provides seamless, gracefully degrading Pjax (pushState + Ajax) functionality,
which makes it easy to progressively enhance standard links on the page so that
they can be loaded normally in old browsers, or via Ajax (with HTML5 history
support) in newer browsers.
@module pjax
@main
@since 3.5.0
**/
/**
A stack of middleware which forms the default Pjax route.
@property defaultRoute
@type Array
@static
@since 3.7.0
**/
var defaultRoute = ['loadContent', '_defaultRoute'],
/**
Fired when an error occurs while attempting to load a URL via Ajax.
@event error
@param {Object} content Content extracted from the response, if any.
@param {Node} content.node A `Y.Node` instance for a document fragment
containing the extracted HTML content.
@param {String} [content.title] The title of the HTML page, if any,
extracted using the `titleSelector` attribute. If `titleSelector` is
not set or if a title could not be found, this property will be
`undefined`.
@param {String} responseText Raw Ajax response text.
@param {Number} status HTTP status code for the Ajax response.
@param {String} url The absolute URL that failed to load.
@since 3.5.0
**/
EVT_ERROR = 'error',
/**
Fired when a URL is successfully loaded via Ajax.
@event load
@param {Object} content Content extracted from the response, if any.
@param {Node} content.node A `Y.Node` instance for a document fragment
containing the extracted HTML content.
@param {String} [content.title] The title of the HTML page, if any,
extracted using the `titleSelector` attribute. If `titleSelector` is
not set or if a title could not be found, this property will be
`undefined`.
@param {String} responseText Raw Ajax response text.
@param {Number} status HTTP status code for the Ajax response.
@param {String} url The absolute URL that was loaded.
@since 3.5.0
**/
EVT_LOAD = 'load';
/**
Provides seamless, gracefully degrading Pjax (pushState + Ajax) functionality,
which makes it easy to progressively enhance standard links on the page so that
they can be loaded normally in old browsers, or via Ajax (with HTML5 history
support) in newer browsers.
@class Pjax
@extends Router
@uses PjaxBase
@uses PjaxContent
@constructor
@param {Object} [config] Config attributes.
@since 3.5.0
**/
Y.Pjax = Y.Base.create('pjax', Y.Router, [Y.PjaxBase, Y.PjaxContent], {
// -- Lifecycle Methods ----------------------------------------------------
initializer: function () {
this.publish(EVT_ERROR, {defaultFn: this._defCompleteFn});
this.publish(EVT_LOAD, {defaultFn: this._defCompleteFn});
},
// -- Protected Methods ----------------------------------------------------
/**
Default Pjax route callback. Fires either the `load` or `error` event based
on the status of the `Y.io` request made by the `loadContent()` middleware.
**Note:** This route callback assumes that it's called after the
`loadContent()` middleware.
@method _defaultRoute
@param {Object} req Request object.
@param {Object} res Response Object.
@param {Function} next Function to pass control to the next route callback.
@protected
@since 3.5.0
@see Y.Pjax.defaultRoute
**/
_defaultRoute: function (req, res, next) {
var ioResponse = res.ioResponse,
status = ioResponse.status,
event = status >= 200 && status < 300 ? EVT_LOAD : EVT_ERROR;
this.fire(event, {
content : res.content,
responseText: ioResponse.responseText,
status : status,
url : req.ioURL
});
next();
},
// -- Event Handlers -------------------------------------------------------
/**
Default event handler for both the `error` and `load` events. Attempts to
insert the loaded content into the `container` node and update the page's
title.
@method _defCompleteFn
@param {EventFacade} e
@protected
@since 3.5.0
**/
_defCompleteFn: function (e) {
var container = this.get('container'),
content = e.content;
if (container && content.node) {
container.setHTML(content.node);
}
if (content.title && Y.config.doc) {
Y.config.doc.title = content.title;
}
}
}, {
ATTRS: {
/**
Node into which content should be inserted when a page is loaded via
Pjax. This node's existing contents will be removed to make way for the
new content.
If not set, loaded content will not be automatically inserted into the
page.
@attribute container
@type Node
@default null
@since 3.5.0
**/
container: {
value : null,
setter: Y.one
},
// Inherited from Router and already documented there.
routes: {
value: [
{path: '*', callbacks: defaultRoute}
]
}
},
// Documented towards the top of this file.
defaultRoute: defaultRoute
});
}, '3.15.0', {"requires": ["pjax-base", "pjax-content"]});
| ruslanas/cdnjs | ajax/libs/yui/3.15.0/pjax/pjax.js | JavaScript | mit | 5,378 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.