code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
// Copyright 2009-2012 by contributors, MIT License
// vim: ts=4 sts=4 sw=4 expandtab
(function () {
setTimeout(function(){
webshims.isReady('es5', true);
});
/**
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* Annotated ES5: http://es5.github.com/ (specific links below)
* ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
* Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/
*/
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://es5.github.com/#x15.3.4.5
function Empty() {}
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
if (typeof target != "function") {
throw new TypeError("Function.prototype.bind called on incompatible " + target);
}
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
// XXX slicedArgs will stand in for "A" if used
var args = _Array_slice_.call(arguments, 1); // for normal call
// 4. Let F be a new native ECMAScript object.
// 11. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 12. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 13. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 14. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
var bound = function () {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs, the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Construct]] internal
// method of target providing args as the arguments.
var result = target.apply(
this,
args.concat(_Array_slice_.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs, the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Call]] internal method
// of target providing boundThis as the this value and
// providing args as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.apply(
that,
args.concat(_Array_slice_.call(arguments))
);
}
};
if(target.prototype) {
Empty.prototype = target.prototype;
bound.prototype = new Empty();
// Clean up dangling references.
Empty.prototype = null;
}
// XXX bound.length is never writable, so don't even try
//
// 15. If the [[Class]] internal property of Target is "Function", then
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is
// larger.
// 16. Else set the length own property of F to 0.
// 17. Set the attributes of the length own property of F to the values
// specified in 15.3.5.1.
// TODO
// 18. Set the [[Extensible]] internal property of F to true.
// TODO
// 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
// 20. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
// thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
// false.
// 21. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
// [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
// and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property or the [[Code]], [[FormalParameters]], and
// [[Scope]] internal properties.
// XXX can't delete prototype in pure-js.
// 22. Return F.
return bound;
};
}
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally.
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var _Array_slice_ = prototypeOfArray.slice;
// Having a toString local variable name breaks in Opera so use _toString.
var _toString = call.bind(prototypeOfObject.toString);
var owns = call.bind(prototypeOfObject.hasOwnProperty);
// If JS engine supports accessors creating shortcuts.
var defineGetter;
var defineSetter;
var lookupGetter;
var lookupSetter;
var supportsAccessors;
if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
//
// Array
// =====
//
// ES5 15.4.4.12
// http://es5.github.com/#x15.4.4.12
// Default value for second param
// [bugfix, ielt9, old browsers]
// IE < 9 bug: [1,2].splice(0).join("") == "" but should be "12"
if ([1,2].splice(0).length != 2) {
var array_splice = Array.prototype.splice;
if(function() { // test IE < 9 to splice bug - see issue #138
function makeArray(l) {
var a = [];
while (l--) {
a.unshift(l)
}
return a
}
var array = []
, lengthBefore
;
array.splice.bind(array, 0, 0).apply(null, makeArray(20));
array.splice.bind(array, 0, 0).apply(null, makeArray(26));
lengthBefore = array.length; //20
array.splice(5, 0, "XXX"); // add one element
if(lengthBefore + 1 == array.length) {
return true;// has right splice implementation without bugs
}
// else {
// IE8 bug
// }
}()) {//IE 6/7
Array.prototype.splice = function(start, deleteCount) {
if (!arguments.length) {
return [];
} else {
return array_splice.apply(this, [
start === void 0 ? 0 : start,
deleteCount === void 0 ? (this.length - start) : deleteCount
].concat(_Array_slice_.call(arguments, 2)))
}
};
}
else {//IE8
Array.prototype.splice = function(start, deleteCount) {
var result
, args = _Array_slice_.call(arguments, 2)
, addElementsCount = args.length
;
if(!arguments.length) {
return [];
}
if(start === void 0) { // default
start = 0;
}
if(deleteCount === void 0) { // default
deleteCount = this.length - start;
}
if(addElementsCount > 0) {
if(deleteCount <= 0) {
if(start == this.length) { // tiny optimisation #1
this.push.apply(this, args);
return [];
}
if(start == 0) { // tiny optimisation #2
this.unshift.apply(this, args);
return [];
}
}
// Array.prototype.splice implementation
result = _Array_slice_.call(this, start, start + deleteCount);// delete part
args.push.apply(args, _Array_slice_.call(this, start + deleteCount, this.length));// right part
args.unshift.apply(args, _Array_slice_.call(this, 0, start));// left part
// delete all items from this array and replace it to 'left part' + _Array_slice_.call(arguments, 2) + 'right part'
args.unshift(0, this.length);
array_splice.apply(this, args);
return result;
}
return array_splice.call(this, start, deleteCount);
}
}
}
// ES5 15.4.4.12
// http://es5.github.com/#x15.4.4.13
// Return len+argCount.
// [bugfix, ielt8]
// IE < 8 bug: [].unshift(0) == undefined but should be "1"
if ([].unshift(0) != 1) {
var array_unshift = Array.prototype.unshift;
Array.prototype.unshift = function() {
array_unshift.apply(this, arguments);
return this.length;
};
}
// ES5 15.4.3.2
// http://es5.github.com/#x15.4.3.2
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray) {
Array.isArray = function isArray(obj) {
return _toString(obj) == "[object Array]";
};
}
// The IsCallable() check in the Array functions
// has been replaced with a strict check on the
// internal class of the object to trap cases where
// the provided function was actually a regular
// expression literal, which in V8 and
// JavaScriptCore is a typeof "function". Only in
// V8 are regular expression literals permitted as
// reduce parameters, so it is desirable in the
// general case for the shim to match the more
// strict and common behavior of rejecting regular
// expressions.
// ES5 15.4.4.18
// http://es5.github.com/#x15.4.4.18
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach
// Check failure of by-index access of string characters (IE < 9)
// and failure of `0 in boxedString` (Rhino)
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(fun /*, thisp*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
thisp = arguments[1],
i = -1,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
while (++i < length) {
if (i in self) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object
// context
fun.call(thisp, self[i], i, object);
}
}
};
}
// ES5 15.4.4.19
// http://es5.github.com/#x15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, object);
}
return result;
};
}
// ES5 15.4.4.20
// http://es5.github.com/#x15.4.4.20
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
if (!Array.prototype.filter) {
Array.prototype.filter = function filter(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = [],
value,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
value = self[i];
if (fun.call(thisp, value, i, object)) {
result.push(value);
}
}
}
return result;
};
}
// ES5 15.4.4.16
// http://es5.github.com/#x15.4.4.16
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
// ES5 15.4.4.17
// http://es5.github.com/#x15.4.4.17
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
if (!Array.prototype.some) {
Array.prototype.some = function some(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, object)) {
return true;
}
}
return false;
};
}
// ES5 15.4.4.21
// http://es5.github.com/#x15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
// no value to return if no initial value and an empty array
if (!length && arguments.length == 1) {
throw new TypeError("reduce of empty array with no initial value");
}
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= length) {
throw new TypeError("reduce of empty array with no initial value");
}
} while (true);
}
for (; i < length; i++) {
if (i in self) {
result = fun.call(void 0, result, self[i], i, object);
}
}
return result;
};
}
// ES5 15.4.4.22
// http://es5.github.com/#x15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
// no value to return if no initial value, empty array
if (!length && arguments.length == 1) {
throw new TypeError("reduceRight of empty array with no initial value");
}
var result, i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0) {
throw new TypeError("reduceRight of empty array with no initial value");
}
} while (true);
}
if (i < 0) {
return result;
}
do {
if (i in this) {
result = fun.call(void 0, result, self[i], i, object);
}
} while (i--);
return result;
};
}
// ES5 15.4.4.14
// http://es5.github.com/#x15.4.4.14
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
var self = splitString && _toString(this) == "[object String]" ?
this.split("") :
toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = 0;
if (arguments.length > 1) {
i = toInteger(arguments[1]);
}
// handle negative indices
i = i >= 0 ? i : Math.max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === sought) {
return i;
}
}
return -1;
};
}
// ES5 15.4.4.15
// http://es5.github.com/#x15.4.4.15
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
var self = splitString && _toString(this) == "[object String]" ?
this.split("") :
toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = length - 1;
if (arguments.length > 1) {
i = Math.min(i, toInteger(arguments[1]));
}
// handle negative indices
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && sought === self[i]) {
return i;
}
}
return -1;
};
}
//
// Object
// ======
//
// ES5 15.2.3.14
// http://es5.github.com/#x15.2.3.14
if (!Object.keys) {
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
var hasDontEnumBug = true,
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null}) {
hasDontEnumBug = false;
}
Object.keys = function keys(object) {
if (
(typeof object != "object" && typeof object != "function") ||
object === null
) {
throw new TypeError("Object.keys called on a non-object");
}
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
//
// Date
// ====
//
// ES5 15.9.5.43
// http://es5.github.com/#x15.9.5.43
// This function returns a String value represent the instance in time
// represented by this Date object. The format of the String is the Date Time
// string format defined in 15.9.1.15. All fields are present in the String.
// The time zone is always UTC, denoted by the suffix Z. If the time value of
// this object is not a finite Number a RangeError exception is thrown.
var negativeDate = -62198755200000,
negativeYearString = "-000001";
if (
!Date.prototype.toISOString ||
(new Date(negativeDate).toISOString().indexOf(negativeYearString) === -1)
) {
Date.prototype.toISOString = function toISOString() {
var result, length, value, year, month;
if (!isFinite(this)) {
throw new RangeError("Date.prototype.toISOString called on non-finite value.");
}
year = this.getUTCFullYear();
month = this.getUTCMonth();
// see https://github.com/kriskowal/es5-shim/issues/111
year += Math.floor(month / 12);
month = (month % 12 + 12) % 12;
// the date time string format is specified in 15.9.1.15.
result = [month + 1, this.getUTCDate(),
this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()];
year = (
(year < 0 ? "-" : (year > 9999 ? "+" : "")) +
("00000" + Math.abs(year))
.slice(0 <= year && year <= 9999 ? -4 : -6)
);
length = result.length;
while (length--) {
value = result[length];
// pad months, days, hours, minutes, and seconds to have two
// digits.
if (value < 10) {
result[length] = "0" + value;
}
}
// pad milliseconds to have three digits.
return (
year + "-" + result.slice(0, 2).join("-") +
"T" + result.slice(2).join(":") + "." +
("000" + this.getUTCMilliseconds()).slice(-3) + "Z"
);
};
}
// ES5 15.9.5.44
// http://es5.github.com/#x15.9.5.44
// This function provides a String representation of a Date object for use by
// JSON.stringify (15.12.3).
var dateToJSONIsSupported = false;
try {
dateToJSONIsSupported = (
Date.prototype.toJSON &&
new Date(NaN).toJSON() === null &&
new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 &&
Date.prototype.toJSON.call({ // generic
toISOString: function () {
return true;
}
})
);
} catch (e) {
}
if (!dateToJSONIsSupported) {
Date.prototype.toJSON = function toJSON(key) {
// When the toJSON method is called with argument key, the following
// steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be toPrimitive(O, hint Number).
var o = Object(this),
tv = toPrimitive(o),
toISO;
// 3. If tv is a Number and is not finite, return null.
if (typeof tv === "number" && !isFinite(tv)) {
return null;
}
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
toISO = o.toISOString;
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
if (typeof toISO != "function") {
throw new TypeError("toISOString property is not callable");
}
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return toISO.call(o);
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// ES5 15.9.4.2
// http://es5.github.com/#x15.9.4.2
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
if (!Date.parse || "Date.parse is buggy") {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
Date = (function(NativeDate) {
// Date.length === 7
function Date(Y, M, D, h, m, s, ms) {
var length = arguments.length;
if (this instanceof NativeDate) {
var date = length == 1 && String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(Date.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) :
length >= 6 ? new NativeDate(Y, M, D, h, m, s) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
// Prevent mixups with unfixed Date object
date.constructor = Date;
return date;
}
return NativeDate.apply(this, arguments);
};
// 15.9.1.15 Date Time String Format.
var isoDateExpression = new RegExp("^" +
"(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign +
// 6-digit extended year
"(?:-(\\d{2})" + // optional month capture
"(?:-(\\d{2})" + // optional day capture
"(?:" + // capture hours:minutes:seconds.milliseconds
"T(\\d{2})" + // hours capture
":(\\d{2})" + // minutes capture
"(?:" + // optional :seconds.milliseconds
":(\\d{2})" + // seconds capture
"(?:(\\.\\d{1,}))?" + // milliseconds capture
")?" +
"(" + // capture UTC offset component
"Z|" + // UTC capture
"(?:" + // offset specifier +/-hours:minutes
"([-+])" + // sign capture
"(\\d{2})" + // hours offset capture
":(\\d{2})" + // minutes offset capture
")" +
")?)?)?)?" +
"$");
var months = [
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
];
function dayFromMonth(year, month) {
var t = month > 1 ? 1 : 0;
return (
months[month] +
Math.floor((year - 1969 + t) / 4) -
Math.floor((year - 1901 + t) / 100) +
Math.floor((year - 1601 + t) / 400) +
365 * (year - 1970)
);
}
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate) {
Date[key] = NativeDate[key];
}
// Copy "native" methods explicitly; they may be non-enumerable
Date.now = NativeDate.now;
Date.UTC = NativeDate.UTC;
Date.prototype = NativeDate.prototype;
Date.prototype.constructor = Date;
// Upgrade Date.parse to handle simplified ISO 8601 strings
Date.parse = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
// parse months, days, hours, minutes, seconds, and milliseconds
// provide default values if necessary
// parse the UTC offset component
var year = Number(match[1]),
month = Number(match[2] || 1) - 1,
day = Number(match[3] || 1) - 1,
hour = Number(match[4] || 0),
minute = Number(match[5] || 0),
second = Number(match[6] || 0),
millisecond = Math.floor(Number(match[7] || 0) * 1000),
// When time zone is missed, local offset should be used
// (ES 5.1 bug)
// see https://bugs.ecmascript.org/show_bug.cgi?id=112
offset = !match[4] || match[8] ?
0 : Number(new NativeDate(1970, 0)),
signOffset = match[9] === "-" ? 1 : -1,
hourOffset = Number(match[10] || 0),
minuteOffset = Number(match[11] || 0),
result;
if (
hour < (
minute > 0 || second > 0 || millisecond > 0 ?
24 : 25
) &&
minute < 60 && second < 60 && millisecond < 1000 &&
month > -1 && month < 12 && hourOffset < 24 &&
minuteOffset < 60 && // detect invalid offsets
day > -1 &&
day < (
dayFromMonth(year, month + 1) -
dayFromMonth(year, month)
)
) {
result = (
(dayFromMonth(year, month) + day) * 24 +
hour +
hourOffset * signOffset
) * 60;
result = (
(result + minute + minuteOffset * signOffset) * 60 +
second
) * 1000 + millisecond + offset;
if (-8.64e15 <= result && result <= 8.64e15) {
return result;
}
}
return NaN;
}
return NativeDate.parse.apply(this, arguments);
};
return Date;
})(Date);
}
// ES5 15.9.4.4
// http://es5.github.com/#x15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
//
// Number
// ======
//
// ES5.1 15.7.4.5
// http://es5.github.com/#x15.7.4.5
if (!Number.prototype.toFixed || (0.00008).toFixed(3) !== '0.000' || (0.9).toFixed(0) === '0' || (1.255).toFixed(2) !== '1.25' || (1000000000000000128).toFixed(0) !== "1000000000000000128") {
// Hide these variables and functions
(function () {
var base, size, data, i;
base = 1e7;
size = 6;
data = [0, 0, 0, 0, 0, 0];
function multiply(n, c) {
var i = -1;
while (++i < size) {
c += n * data[i];
data[i] = c % base;
c = Math.floor(c / base);
}
}
function divide(n) {
var i = size, c = 0;
while (--i >= 0) {
c += data[i];
data[i] = Math.floor(c / n);
c = (c % n) * base;
}
}
function toString() {
var i = size;
var s = '';
while (--i >= 0) {
if (s !== '' || i === 0 || data[i] !== 0) {
var t = String(data[i]);
if (s === '') {
s = t;
} else {
s += '0000000'.slice(0, 7 - t.length) + t;
}
}
}
return s;
}
function pow(x, n, acc) {
return (n === 0 ? acc : (n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc)));
}
function log(x) {
var n = 0;
while (x >= 4096) {
n += 12;
x /= 4096;
}
while (x >= 2) {
n += 1;
x /= 2;
}
return n;
}
Number.prototype.toFixed = function (fractionDigits) {
var f, x, s, m, e, z, j, k;
// Test for NaN and round fractionDigits down
f = Number(fractionDigits);
f = f !== f ? 0 : Math.floor(f);
if (f < 0 || f > 20) {
throw new RangeError("Number.toFixed called with invalid number of decimals");
}
x = Number(this);
// Test for NaN
if (x !== x) {
return "NaN";
}
// If it is too big or small, return the string value of the number
if (x <= -1e21 || x >= 1e21) {
return String(x);
}
s = "";
if (x < 0) {
s = "-";
x = -x;
}
m = "0";
if (x > 1e-21) {
// 1e-21 < x < 1e21
// -70 < log2(x) < 70
e = log(x * pow(2, 69, 1)) - 69;
z = (e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1));
z *= 0x10000000000000; // Math.pow(2, 52);
e = 52 - e;
// -18 < e < 122
// x = z / 2 ^ e
if (e > 0) {
multiply(0, z);
j = f;
while (j >= 7) {
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while (j >= 23) {
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = toString();
} else {
multiply(0, z);
multiply(1 << (-e), 0);
m = toString() + '0.00000000000000000000'.slice(2, 2 + f);
}
}
if (f > 0) {
k = m.length;
if (k <= f) {
m = s + '0.0000000000000000000'.slice(0, f - k + 2) + m;
} else {
m = s + m.slice(0, k - f) + '.' + m.slice(k - f);
}
} else {
m = s + m;
}
return m;
}
}());
}
//
// String
// ======
//
// ES5 15.5.4.14
// http://es5.github.com/#x15.5.4.14
// [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers]
// Many browsers do not split properly with regular expressions or they
// do not perform the split correctly under obscure conditions.
// See http://blog.stevenlevithan.com/archives/cross-browser-split
// I've tested in many browsers and this seems to cover the deviant ones:
// 'ab'.split(/(?:ab)*/) should be ["", ""], not [""]
// '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""]
// 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not
// [undefined, "t", undefined, "e", ...]
// ''.split(/.?/) should be [], not [""]
// '.'.split(/()()/) should be ["."], not ["", "", "."]
var string_split = String.prototype.split;
if (
'ab'.split(/(?:ab)*/).length !== 2 ||
'.'.split(/(.?)(.?)/).length !== 4 ||
'tesst'.split(/(s)*/)[1] === "t" ||
''.split(/.?/).length === 0 ||
'.'.split(/()()/).length > 1
) {
(function () {
var compliantExecNpcg = /()??/.exec("")[1] === void 0; // NPCG: nonparticipating capturing group
String.prototype.split = function (separator, limit) {
var string = this;
if (separator === void 0 && limit === 0)
return [];
// If `separator` is not a regex, use native split
if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
return string_split.apply(this, arguments);
}
var output = [],
flags = (separator.ignoreCase ? "i" : "") +
(separator.multiline ? "m" : "") +
(separator.extended ? "x" : "") + // Proposed for ES6
(separator.sticky ? "y" : ""), // Firefox 3+
lastLastIndex = 0,
// Make `global` and avoid `lastIndex` issues by working with a copy
separator = new RegExp(separator.source, flags + "g"),
separator2, match, lastIndex, lastLength;
string += ""; // Type-convert
if (!compliantExecNpcg) {
// Doesn't need flags gy, but they don't hurt
separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
}
/* Values for `limit`, per the spec:
* If undefined: 4294967295 // Math.pow(2, 32) - 1
* If 0, Infinity, or NaN: 0
* If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
* If negative number: 4294967296 - Math.floor(Math.abs(limit))
* If other: Type-convert, then use the above rules
*/
limit = limit === void 0 ?
-1 >>> 0 : // Math.pow(2, 32) - 1
limit >>> 0; // ToUint32(limit)
while (match = separator.exec(string)) {
// `separator.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0].length;
if (lastIndex > lastLastIndex) {
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1) {
match[0].replace(separator2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === void 0) {
match[i] = void 0;
}
}
});
}
if (match.length > 1 && match.index < string.length) {
Array.prototype.push.apply(output, match.slice(1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= limit) {
break;
}
}
if (separator.lastIndex === match.index) {
separator.lastIndex++; // Avoid an infinite loop
}
}
if (lastLastIndex === string.length) {
if (lastLength || !separator.test("")) {
output.push("");
}
} else {
output.push(string.slice(lastLastIndex));
}
return output.length > limit ? output.slice(0, limit) : output;
};
}());
// [bugfix, chrome]
// If separator is undefined, then the result array contains just one String,
// which is the this value (converted to a String). If limit is not undefined,
// then the output array is truncated so that it contains no more than limit
// elements.
// "0".split(undefined, 0) -> []
} else if ("0".split(void 0, 0).length) {
String.prototype.split = function(separator, limit) {
if (separator === void 0 && limit === 0) return [];
return string_split.apply(this, arguments);
}
}
// ECMA-262, 3rd B.2.3
// Note an ECMAScript standart, although ECMAScript 3rd Edition has a
// non-normative section suggesting uniform semantics and it should be
// normalized across all browsers
// [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE
if("".substr && "0b".substr(-1) !== "b") {
var string_substr = String.prototype.substr;
/**
* Get the substring of a string
* @param {integer} start where to start the substring
* @param {integer} length how many characters to return
* @return {string}
*/
String.prototype.substr = function(start, length) {
return string_substr.call(
this,
start < 0 ? ((start = this.length + start) < 0 ? 0 : start) : start,
length
);
}
}
// ES5 15.5.4.20
// http://es5.github.com/#x15.5.4.20
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
if (this === void 0 || this === null) {
throw new TypeError("can't convert "+this+" to object");
}
return String(this)
.replace(trimBeginRegexp, "")
.replace(trimEndRegexp, "");
};
}
//
// Util
// ======
//
// ES5 9.4
// http://es5.github.com/#x9.4
// http://jsperf.com/to-integer
function toInteger(n) {
n = +n;
if (n !== n) { // isNaN
n = 0;
} else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
return n;
}
function isPrimitive(input) {
var type = typeof input;
return (
input === null ||
type === "undefined" ||
type === "boolean" ||
type === "number" ||
type === "string"
);
}
function toPrimitive(input) {
var val, valueOf, toString;
if (isPrimitive(input)) {
return input;
}
valueOf = input.valueOf;
if (typeof valueOf === "function") {
val = valueOf.call(input);
if (isPrimitive(val)) {
return val;
}
}
toString = input.toString;
if (typeof toString === "function") {
val = toString.call(input);
if (isPrimitive(val)) {
return val;
}
}
throw new TypeError();
}
// ES5 9.9
// http://es5.github.com/#x9.9
var toObject = function (o) {
if (o == null) { // this matches both null and undefined
throw new TypeError("can't convert "+o+" to object");
}
return Object(o);
};
})();
(function($, shims){
var defineProperty = 'defineProperty';
var advancedObjectProperties = !!(Object.create && Object.defineProperties && Object.getOwnPropertyDescriptor);
//safari5 has defineProperty-interface, but it can't be used on dom-object
//only do this test in non-IE browsers, because this hurts dhtml-behavior in some IE8 versions
if (advancedObjectProperties && Object[defineProperty] && Object.prototype.__defineGetter__) {
(function(){
try {
var foo = document.createElement('foo');
Object[defineProperty](foo, 'bar', {
get: function(){
return true;
}
});
advancedObjectProperties = !!foo.bar;
}
catch (e) {
advancedObjectProperties = false;
}
foo = null;
})();
}
Modernizr.objectAccessor = !!((advancedObjectProperties || (Object.prototype.__defineGetter__ && Object.prototype.__lookupSetter__)));
Modernizr.advancedObjectProperties = advancedObjectProperties;
if((!advancedObjectProperties || !Object.create || !Object.defineProperties || !Object.getOwnPropertyDescriptor || !Object.defineProperty)){
var call = Function.prototype.call;
var prototypeOfObject = Object.prototype;
var owns = call.bind(prototypeOfObject.hasOwnProperty);
shims.objectCreate = function(proto, props, opts, no__proto__){
var o;
var f = function(){};
f.prototype = proto;
o = new f();
if(!no__proto__ && !('__proto__' in o) && !Modernizr.objectAccessor){
o.__proto__ = proto;
}
if(props){
shims.defineProperties(o, props);
}
if(opts){
o.options = $.extend(true, {}, o.options || {}, opts);
opts = o.options;
}
if(o._create && $.isFunction(o._create)){
o._create(opts);
}
return o;
};
shims.defineProperties = function(object, props){
for (var name in props) {
if (owns(props, name)) {
shims.defineProperty(object, name, props[name]);
}
}
return object;
};
var descProps = ['configurable', 'enumerable', 'writable'];
shims.defineProperty = function(proto, property, descriptor){
if(typeof descriptor != "object" || descriptor === null){return proto;}
if(owns(descriptor, "value")){
proto[property] = descriptor.value;
return proto;
}
if(proto.__defineGetter__){
if (typeof descriptor.get == "function") {
proto.__defineGetter__(property, descriptor.get);
}
if (typeof descriptor.set == "function"){
proto.__defineSetter__(property, descriptor.set);
}
}
return proto;
};
shims.getPrototypeOf = function (object) {
return Object.getPrototypeOf && Object.getPrototypeOf(object) || object.__proto__ || object.constructor && object.constructor.prototype;
};
//based on http://www.refactory.org/s/object_getownpropertydescriptor/view/latest
shims.getOwnPropertyDescriptor = function(obj, prop){
if (typeof obj !== "object" && typeof obj !== "function" || obj === null){
throw new TypeError("Object.getOwnPropertyDescriptor called on a non-object");
}
var descriptor;
if(Object.defineProperty && Object.getOwnPropertyDescriptor){
try{
descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return descriptor;
} catch(e){}
}
descriptor = {
configurable: true,
enumerable: true,
writable: true,
value: undefined
};
var getter = obj.__lookupGetter__ && obj.__lookupGetter__(prop),
setter = obj.__lookupSetter__ && obj.__lookupSetter__(prop)
;
if (!getter && !setter) { // not an accessor so return prop
if(!owns(obj, prop)){
return;
}
descriptor.value = obj[prop];
return descriptor;
}
// there is an accessor, remove descriptor.writable; populate descriptor.get and descriptor.set
delete descriptor.writable;
delete descriptor.value;
descriptor.get = descriptor.set = undefined;
if(getter){
descriptor.get = getter;
}
if(setter){
descriptor.set = setter;
}
return descriptor;
};
}
webshims.isReady('es5', true);
})(webshims.$, webshims);
;webshims.register('form-number-date-api', function($, webshims, window, document, undefined, options){
"use strict";
if(!webshims.addInputType){
webshims.error("you can not call forms-ext feature after calling forms feature. call both at once instead: $.webshims.polyfill('forms forms-ext')");
}
if(!webshims.getStep){
webshims.getStep = function(elem, type){
var step = $.attr(elem, 'step');
if(step === 'any'){
return step;
}
type = type || getType(elem);
if(!typeModels[type] || !typeModels[type].step){
return step;
}
step = typeProtos.number.asNumber(step);
return ((!isNaN(step) && step > 0) ? step : typeModels[type].step) * (typeModels[type].stepScaleFactor || 1);
};
}
if(!webshims.addMinMaxNumberToCache){
webshims.addMinMaxNumberToCache = function(attr, elem, cache){
if (!(attr+'AsNumber' in cache)) {
cache[attr+'AsNumber'] = typeModels[cache.type].asNumber(elem.attr(attr));
if(isNaN(cache[attr+'AsNumber']) && (attr+'Default' in typeModels[cache.type])){
cache[attr+'AsNumber'] = typeModels[cache.type][attr+'Default'];
}
}
};
}
var nan = parseInt('NaN', 10),
doc = document,
typeModels = webshims.inputTypes,
isNumber = function(string){
return (typeof string == 'number' || (string && string == string * 1));
},
supportsType = function(type){
return ($('<input type="'+type+'" />').prop('type') === type);
},
getType = function(elem){
return (elem.getAttribute('type') || '').toLowerCase();
},
isDateTimePart = function(string){
return (string && !(isNaN(string * 1)));
},
addMinMaxNumberToCache = webshims.addMinMaxNumberToCache,
addleadingZero = function(val, len){
val = ''+val;
len = len - val.length;
for(var i = 0; i < len; i++){
val = '0'+val;
}
return val;
},
EPS = 1e-7,
typeBugs = webshims.bugs.bustedValidity
;
webshims.addValidityRule('stepMismatch', function(input, val, cache, validityState){
if(val === ''){return false;}
if(!('type' in cache)){
cache.type = getType(input[0]);
}
if(cache.type == 'week'){return false;}
var base, attrVal;
var ret = (validityState || {}).stepMismatch || false;
if(typeModels[cache.type] && typeModels[cache.type].step){
if( !('step' in cache) ){
cache.step = webshims.getStep(input[0], cache.type);
}
if(cache.step == 'any'){return false;}
if(!('valueAsNumber' in cache)){
cache.valueAsNumber = typeModels[cache.type].asNumber( val );
}
if(isNaN(cache.valueAsNumber)){return false;}
addMinMaxNumberToCache('min', input, cache);
base = cache.minAsNumber;
if(isNaN(base) && (attrVal = input.prop('defaultValue'))){
base = typeModels[cache.type].asNumber( attrVal );
}
if(isNaN(base)){
base = typeModels[cache.type].stepBase || 0;
}
ret = Math.abs((cache.valueAsNumber - base) % cache.step);
ret = !( ret <= EPS || Math.abs(ret - cache.step) <= EPS );
}
return ret;
});
[{name: 'rangeOverflow', attr: 'max', factor: 1}, {name: 'rangeUnderflow', attr: 'min', factor: -1}].forEach(function(data, i){
webshims.addValidityRule(data.name, function(input, val, cache, validityState) {
var ret = (validityState || {})[data.name] || false;
if(val === ''){return ret;}
if (!('type' in cache)) {
cache.type = getType(input[0]);
}
if (typeModels[cache.type] && typeModels[cache.type].asNumber) {
if(!('valueAsNumber' in cache)){
cache.valueAsNumber = typeModels[cache.type].asNumber( val );
}
if(isNaN(cache.valueAsNumber)){
return false;
}
addMinMaxNumberToCache(data.attr, input, cache);
if(isNaN(cache[data.attr+'AsNumber'])){
return ret;
}
ret = ( cache[data.attr+'AsNumber'] * data.factor < cache.valueAsNumber * data.factor - EPS );
}
return ret;
});
});
webshims.reflectProperties(['input'], ['max', 'min', 'step']);
//IDLs and methods, that aren't part of constrain validation, but strongly tight to it
var valueAsNumberDescriptor = webshims.defineNodeNameProperty('input', 'valueAsNumber', {
prop: {
get: function(){
var elem = this;
var type = getType(elem);
var ret = (typeModels[type] && typeModels[type].asNumber) ?
typeModels[type].asNumber($.prop(elem, 'value')) :
(valueAsNumberDescriptor.prop._supget && valueAsNumberDescriptor.prop._supget.apply(elem, arguments));
if(ret == null){
ret = nan;
}
return ret;
},
set: function(val){
var elem = this;
var type = getType(elem);
if(typeModels[type] && typeModels[type].numberToString){
//is NaN a number?
if(isNaN(val)){
$.prop(elem, 'value', '');
return;
}
var set = typeModels[type].numberToString(val);
if(set !== false){
$.prop(elem, 'value', set);
} else {
webshims.error('INVALID_STATE_ERR: DOM Exception 11');
}
} else if(valueAsNumberDescriptor.prop._supset) {
valueAsNumberDescriptor.prop._supset.apply(elem, arguments);
}
}
}
});
var valueAsDateDescriptor = webshims.defineNodeNameProperty('input', 'valueAsDate', {
prop: {
get: function(){
var elem = this;
var type = getType(elem);
return (typeModels[type] && typeModels[type].asDate && !typeModels[type].noAsDate) ?
typeModels[type].asDate($.prop(elem, 'value')) :
valueAsDateDescriptor.prop._supget && valueAsDateDescriptor.prop._supget.call(elem) || null;
},
set: function(value){
var elem = this;
var type = getType(elem);
if(typeModels[type] && typeModels[type].dateToString && !typeModels[type].noAsDate){
if(value === null){
$.prop(elem, 'value', '');
return '';
}
var set = typeModels[type].dateToString(value);
if(set !== false){
$.prop(elem, 'value', set);
return set;
} else {
webshims.error('INVALID_STATE_ERR: DOM Exception 11');
}
} else {
return valueAsDateDescriptor.prop._supset && valueAsDateDescriptor.prop._supset.apply(elem, arguments) || null;
}
}
}
});
$.each({stepUp: 1, stepDown: -1}, function(name, stepFactor){
var stepDescriptor = webshims.defineNodeNameProperty('input', name, {
prop: {
value: function(factor){
var step, val, valModStep, alignValue, cache, base, attrVal;
var type = getType(this);
if(typeModels[type] && typeModels[type].asNumber){
cache = {type: type};
if(!factor){
factor = 1;
webshims.warn("you should always use a factor for stepUp/stepDown");
}
factor *= stepFactor;
step = webshims.getStep(this, type);
if(step == 'any'){
webshims.info("step is 'any' can't apply stepUp/stepDown");
throw('invalid state error');
}
webshims.addMinMaxNumberToCache('min', $(this), cache);
webshims.addMinMaxNumberToCache('max', $(this), cache);
val = $.prop(this, 'valueAsNumber');
if(factor > 0 && !isNaN(cache.minAsNumber) && (isNaN(val) || cache.minAsNumber > val)){
$.prop(this, 'valueAsNumber', cache.minAsNumber);
return;
} else if(factor < 0 && !isNaN(cache.maxAsNumber) && (isNaN(val) || cache.maxAsNumber < val)){
$.prop(this, 'valueAsNumber', cache.maxAsNumber);
return;
}
if(isNaN(val)){
val = 0;
}
base = cache.minAsNumber;
if(isNaN(base) && (attrVal = $.prop(this, 'defaultValue'))){
base = typeModels[type].asNumber( attrVal );
}
if(!base){
base = 0;
}
step *= factor;
val = (val + step).toFixed(5) * 1;
valModStep = (val - base) % step;
if ( valModStep && (Math.abs(valModStep) > EPS) ) {
alignValue = val - valModStep;
alignValue += ( valModStep > 0 ) ? step : ( -step );
val = alignValue.toFixed(5) * 1;
}
if( (!isNaN(cache.maxAsNumber) && val > cache.maxAsNumber) || (!isNaN(cache.minAsNumber) && val < cache.minAsNumber) ){
webshims.info("max/min overflow can't apply stepUp/stepDown");
return;
}
$.prop(this, 'valueAsNumber', val);
} else if(stepDescriptor.prop && stepDescriptor.prop._supvalue){
return stepDescriptor.prop._supvalue.apply(this, arguments);
} else {
webshims.info("no step method for type: "+ type);
throw('invalid state error');
}
}
}
});
});
/*
* ToDO: WEEK
*/
// var getWeek = function(date){
// var time;
// var checkDate = new Date(date.getTime());
//
// checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
//
// time = checkDate.getTime();
// checkDate.setMonth(0);
// checkDate.setDate(1);
// return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
// };
//
// var setWeek = function(year, week){
// var date = new Date(year, 0, 1);
//
// week = (week - 1) * 86400000 * 7;
// date = new Date(date.getTime() + week);
// date.setDate(date.getDate() + 1 - (date.getDay() || 7));
// return date;
// };
var typeProtos = {
number: {
bad: function(val){
return !(isNumber(val));
},
step: 1,
//stepBase: 0, 0 = default
stepScaleFactor: 1,
asNumber: function(str){
return (isNumber(str)) ? str * 1 : nan;
},
numberToString: function(num){
return (isNumber(num)) ? num : false;
}
},
range: {
minDefault: 0,
maxDefault: 100
},
color: {
bad: (function(){
var cReg = /^\u0023[a-f0-9]{6}$/;
return function(val){
return (!val || val.length != 7 || !(cReg.test(val)));
};
})()
},
date: {
bad: function(val){
if(!val || !val.split || !(/\d$/.test(val))){return true;}
var i;
var valA = val.split(/\u002D/);
if(valA.length !== 3){return true;}
var ret = false;
if(valA[0].length < 4 || valA[1].length != 2 || valA[1] > 12 || valA[2].length != 2 || valA[2] > 33){
ret = true;
} else {
for(i = 0; i < 3; i++){
if(!isDateTimePart(valA[i])){
ret = true;
break;
}
}
}
return ret || (val !== this.dateToString( this.asDate(val, true) ) );
},
step: 1,
//stepBase: 0, 0 = default
stepScaleFactor: 86400000,
asDate: function(val, _noMismatch){
if(!_noMismatch && this.bad(val)){
return null;
}
return new Date(this.asNumber(val, true));
},
asNumber: function(str, _noMismatch){
var ret = nan;
if(_noMismatch || !this.bad(str)){
str = str.split(/\u002D/);
ret = Date.UTC(str[0], str[1] - 1, str[2]);
}
return ret;
},
numberToString: function(num){
return (isNumber(num)) ? this.dateToString(new Date( num * 1)) : false;
},
dateToString: function(date){
return (date && date.getFullYear) ? addleadingZero(date.getUTCFullYear(), 4) +'-'+ addleadingZero(date.getUTCMonth()+1, 2) +'-'+ addleadingZero(date.getUTCDate(), 2) : false;
}
},
/*
* ToDO: WEEK
*/
// week: {
// bad: function(val){
// if(!val || !val.split){return true;}
// var valA = val.split('-W');
// var ret = true;
// if(valA.length == 2 && valA[0].length > 3 && valA.length == 2){
// ret = this.dateToString(setWeek(valA[0], valA[1])) != val;
// }
// return ret;
// },
// step: 1,
// stepScaleFactor: 604800000,
// stepBase: -259200000,
// asDate: function(str, _noMismatch){
// var ret = null;
// if(_noMismatch || !this.bad(str)){
// ret = str.split('-W');
// ret = setWeek(ret[0], ret[1]);
// }
// return ret;
// },
// asNumber: function(str, _noMismatch){
// var ret = nan;
// var date = this.asDate(str, _noMismatch);
// if(date && date.getUTCFullYear){
// ret = date.getTime();
// }
// return ret;
// },
// dateToString: function(date){
// var week, checkDate;
// var ret = false;
// if(date && date.getFullYear){
// week = getWeek(date);
// if(week == 1){
// checkDate = new Date(date.getTime());
// checkDate.setDate(checkDate.getDate() + 7);
// date.setUTCFullYear(checkDate.getUTCFullYear());
// }
// ret = addleadingZero(date.getUTCFullYear(), 4) +'-W'+addleadingZero(week, 2);
// }
// return ret;
// },
// numberToString: function(num){
// return (isNumber(num)) ? this.dateToString(new Date( num * 1)) : false;
// }
// },
time: {
bad: function(val, _getParsed){
if(!val || !val.split || !(/\d$/.test(val))){return true;}
val = val.split(/\u003A/);
if(val.length < 2 || val.length > 3){return true;}
var ret = false,
sFraction;
if(val[2]){
val[2] = val[2].split(/\u002E/);
sFraction = parseInt(val[2][1], 10);
val[2] = val[2][0];
}
$.each(val, function(i, part){
if(!isDateTimePart(part) || part.length !== 2){
ret = true;
return false;
}
});
if(ret){return true;}
if(val[0] > 23 || val[0] < 0 || val[1] > 59 || val[1] < 0){
return true;
}
if(val[2] && (val[2] > 59 || val[2] < 0 )){
return true;
}
if(sFraction && isNaN(sFraction)){
return true;
}
if(sFraction){
if(sFraction < 100){
sFraction *= 100;
} else if(sFraction < 10){
sFraction *= 10;
}
}
return (_getParsed === true) ? [val, sFraction] : false;
},
step: 60,
stepBase: 0,
stepScaleFactor: 1000,
asDate: function(val){
val = new Date(this.asNumber(val));
return (isNaN(val)) ? null : val;
},
asNumber: function(val){
var ret = nan;
val = this.bad(val, true);
if(val !== true){
ret = Date.UTC('1970', 0, 1, val[0][0], val[0][1], val[0][2] || 0);
if(val[1]){
ret += val[1];
}
}
return ret;
},
dateToString: function(date){
if(date && date.getUTCHours){
var str = addleadingZero(date.getUTCHours(), 2) +':'+ addleadingZero(date.getUTCMinutes(), 2),
tmp = date.getSeconds()
;
if(tmp != "0"){
str += ':'+ addleadingZero(tmp, 2);
}
tmp = date.getUTCMilliseconds();
if(tmp != "0"){
str += '.'+ addleadingZero(tmp, 3);
}
return str;
} else {
return false;
}
}
},
month: {
bad: function(val){
return typeProtos.date.bad(val+'-01');
},
step: 1,
stepScaleFactor: false,
//stepBase: 0, 0 = default
asDate: function(val){
return new Date(typeProtos.date.asNumber(val+'-01'));
},
asNumber: function(val){
//1970-01
var ret = nan;
if(val && !this.bad(val)){
val = val.split(/\u002D/);
val[0] = (val[0] * 1) - 1970;
val[1] = (val[1] * 1) - 1;
ret = (val[0] * 12) + val[1];
}
return ret;
},
numberToString: function(num){
var mod;
var ret = false;
if(isNumber(num)){
mod = (num % 12);
num = ((num - mod) / 12) + 1970;
mod += 1;
if(mod < 1){
num -= 1;
mod += 12;
}
ret = addleadingZero(num, 4)+'-'+addleadingZero(mod, 2);
}
return ret;
},
dateToString: function(date){
if(date && date.getUTCHours){
var str = typeProtos.date.dateToString(date);
return (str.split && (str = str.split(/\u002D/))) ? str[0]+'-'+str[1] : false;
} else {
return false;
}
}
}
,'datetime-local': {
bad: function(val, _getParsed){
if(!val || !val.split || (val+'special').split(/\u0054/).length !== 2){return true;}
val = val.split(/\u0054/);
return ( typeProtos.date.bad(val[0]) || typeProtos.time.bad(val[1], _getParsed) );
},
noAsDate: true,
asDate: function(val){
val = new Date(this.asNumber(val));
return (isNaN(val)) ? null : val;
},
asNumber: function(val){
var ret = nan;
var time = this.bad(val, true);
if(time !== true){
val = val.split(/\u0054/)[0].split(/\u002D/);
ret = Date.UTC(val[0], val[1] - 1, val[2], time[0][0], time[0][1], time[0][2] || 0);
if(time[1]){
ret += time[1];
}
}
return ret;
},
dateToString: function(date, _getParsed){
return typeProtos.date.dateToString(date) +'T'+ typeProtos.time.dateToString(date, _getParsed);
}
}
};
if(typeBugs || !supportsType('range') || !supportsType('time') || !supportsType('month') || !supportsType('datetime-local')){
typeProtos.range = $.extend({}, typeProtos.number, typeProtos.range);
typeProtos.time = $.extend({}, typeProtos.date, typeProtos.time);
typeProtos.month = $.extend({}, typeProtos.date, typeProtos.month);
typeProtos['datetime-local'] = $.extend({}, typeProtos.date, typeProtos.time, typeProtos['datetime-local']);
}
//
['number', 'month', 'range', 'date', 'time', 'color', 'datetime-local'].forEach(function(type){
if(typeBugs || !supportsType(type)){
webshims.addInputType(type, typeProtos[type]);
}
});
if($('<input />').prop('labels') == null){
webshims.defineNodeNamesProperty('button, input, keygen, meter, output, progress, select, textarea', 'labels', {
prop: {
get: function(){
if(this.type == 'hidden'){return null;}
var id = this.id;
var labels = $(this)
.closest('label')
.filter(function(){
var hFor = (this.attributes['for'] || {});
return (!hFor.specified || hFor.value == id);
})
;
if(id) {
labels = labels.add('label[for="'+ id +'"]');
}
return labels.get();
},
writeable: false
}
});
}
});
;webshims.register('form-datalist', function($, webshims, window, document, undefined, options){
"use strict";
var lazyLoad = function(name){
if(!name || typeof name != 'string'){
name = 'DOM';
}
if(!lazyLoad[name+'Loaded']){
lazyLoad[name+'Loaded'] = true;
webshims.ready(name, function(){
webshims.loader.loadList(['form-datalist-lazy']);
});
}
};
var noDatalistSupport = {
submit: 1,
button: 1,
reset: 1,
hidden: 1,
range: 1,
date: 1,
month: 1
};
if(webshims.modules["form-number-date-ui"].loaded){
$.extend(noDatalistSupport, {
number: 1,
time: 1
});
}
/*
* implement propType "element" currently only used for list-attribute (will be moved to dom-extend, if needed)
*/
webshims.propTypes.element = function(descs, name){
webshims.createPropDefault(descs, 'attr');
if(descs.prop){return;}
descs.prop = {
get: function(){
var elem = $.attr(this, name);
if(elem){
elem = document.getElementById(elem);
if(elem && descs.propNodeName && !$.nodeName(elem, descs.propNodeName)){
elem = null;
}
}
return elem || null;
},
writeable: false
};
};
/*
* Implements datalist element and list attribute
*/
(function(){
var formsCFG = $.webshims.cfg.forms;
var listSupport = Modernizr.input.list;
if(listSupport && !formsCFG.customDatalist){return;}
var initializeDatalist = function(){
var updateDatlistAndOptions = function(){
var id;
if(!$.data(this, 'datalistWidgetData') && (id = $.prop(this, 'id'))){
$('input[list="'+ id +'"], input[data-wslist="'+ id +'"]').eq(0).attr('list', id);
} else {
$(this).triggerHandler('updateDatalist');
}
};
var inputListProto = {
//override autocomplete
autocomplete: {
attr: {
get: function(){
var elem = this;
var data = $.data(elem, 'datalistWidget');
if(data){
return data._autocomplete;
}
return ('autocomplete' in elem) ? elem.autocomplete : elem.getAttribute('autocomplete');
},
set: function(value){
var elem = this;
var data = $.data(elem, 'datalistWidget');
if(data){
data._autocomplete = value;
if(value == 'off'){
data.hideList();
}
} else {
if('autocomplete' in elem){
elem.autocomplete = value;
} else {
elem.setAttribute('autocomplete', value);
}
}
}
}
}
};
if(listSupport){
//options only return options, if option-elements are rooted: but this makes this part of HTML5 less backwards compatible
if(!($('<datalist><select><option></option></select></datalist>').prop('options') || []).length ){
webshims.defineNodeNameProperty('datalist', 'options', {
prop: {
writeable: false,
get: function(){
var options = this.options || [];
if(!options.length){
var elem = this;
var select = $('select', elem);
if(select[0] && select[0].options && select[0].options.length){
options = select[0].options;
}
}
return options;
}
}
});
}
inputListProto.list = {
attr: {
get: function(){
var val = webshims.contentAttr(this, 'list');
if(val != null){
$.data(this, 'datalistListAttr', val);
if(!noDatalistSupport[$.prop(this, 'type')] && !noDatalistSupport[$.attr(this, 'type')]){
this.removeAttribute('list');
}
} else {
val = $.data(this, 'datalistListAttr');
}
return (val == null) ? undefined : val;
},
set: function(value){
var elem = this;
$.data(elem, 'datalistListAttr', value);
if (!noDatalistSupport[$.prop(this, 'type')] && !noDatalistSupport[$.attr(this, 'type')]) {
webshims.objectCreate(shadowListProto, undefined, {
input: elem,
id: value,
datalist: $.prop(elem, 'list')
});
elem.setAttribute('data-wslist', value);
} else {
elem.setAttribute('list', value);
}
$(elem).triggerHandler('listdatalistchange');
}
},
initAttr: true,
reflect: true,
propType: 'element',
propNodeName: 'datalist'
};
} else {
webshims.defineNodeNameProperties('input', {
list: {
attr: {
get: function(){
var val = webshims.contentAttr(this, 'list');
return (val == null) ? undefined : val;
},
set: function(value){
var elem = this;
webshims.contentAttr(elem, 'list', value);
webshims.objectCreate(options.shadowListProto, undefined, {input: elem, id: value, datalist: $.prop(elem, 'list')});
$(elem).triggerHandler('listdatalistchange');
}
},
initAttr: true,
reflect: true,
propType: 'element',
propNodeName: 'datalist'
}
});
}
webshims.defineNodeNameProperties('input', inputListProto);
webshims.addReady(function(context, contextElem){
contextElem
.filter('datalist > select, datalist, datalist > option, datalist > select > option')
.closest('datalist')
.each(updateDatlistAndOptions)
;
});
};
/*
* ShadowList
*/
var shadowListProto = {
_create: function(opts){
if(noDatalistSupport[$.prop(opts.input, 'type')] || noDatalistSupport[$.attr(opts.input, 'type')]){return;}
var datalist = opts.datalist;
var data = $.data(opts.input, 'datalistWidget');
var that = this;
if(datalist && data && data.datalist !== datalist){
data.datalist = datalist;
data.id = opts.id;
$(data.datalist)
.off('updateDatalist.datalistWidget')
.on('updateDatalist.datalistWidget', $.proxy(data, '_resetListCached'))
;
data._resetListCached();
return;
} else if(!datalist){
if(data){
data.destroy();
}
return;
} else if(data && data.datalist === datalist){
return;
}
this.datalist = datalist;
this.id = opts.id;
this.hasViewableData = true;
this._autocomplete = $.attr(opts.input, 'autocomplete');
$.data(opts.input, 'datalistWidget', this);
$.data(datalist, 'datalistWidgetData', this);
lazyLoad('WINDOWLOAD');
if(webshims.isReady('form-datalist-lazy')){
if(window.QUnit){
that._lazyCreate(opts);
} else {
setTimeout(function(){
that._lazyCreate(opts);
}, 9);
}
} else {
$(opts.input).one('focus', lazyLoad);
webshims.ready('form-datalist-lazy', function(){
if(!that._destroyed){
that._lazyCreate(opts);
}
});
}
},
destroy: function(e){
var input;
var autocomplete = $.attr(this.input, 'autocomplete');
$(this.input)
.off('.datalistWidget')
.removeData('datalistWidget')
;
this.shadowList.remove();
$(document).off('.datalist'+this.id);
$(window).off('.datalist'+this.id);
if(this.input.form && this.input.id){
$(this.input.form).off('submit.datalistWidget'+this.input.id);
}
this.input.removeAttribute('aria-haspopup');
if(autocomplete === undefined){
this.input.removeAttribute('autocomplete');
} else {
$(this.input).attr('autocomplete', autocomplete);
}
if(e && e.type == 'beforeunload'){
input = this.input;
setTimeout(function(){
$.attr(input, 'list', $.attr(input, 'list'));
}, 9);
}
this._destroyed = true;
}
};
webshims.loader.addModule('form-datalist-lazy', {
noAutoCallback: true,
options: $.extend(options, {shadowListProto: shadowListProto})
});
if(!options.list){
options.list = {};
}
//init datalist update
initializeDatalist();
})();
});
| GuanyemBarcelona/apoyos | js/vendor/js-webshim/dev/shims/combos/32.js | JavaScript | agpl-3.0 | 74,688 |
require({
baseUrl: './',
paths: {
a: 'a1'
},
map: {
'a': {
c: 'c1'
},
'a/sub/one': {
'c': 'c2'
}
}
},
['a', 'b', 'c', 'a/sub/one'],
function(a, b, c, one) {
doh.register(
'mapConfig',
[
function mapConfig(t){
t.is('c1', a.c.name);
t.is('c1/sub', a.csub.name);
t.is('c2', one.c.name);
t.is('c2/sub', one.csub.name);
t.is('c', b.c.name);
t.is('c/sub', b.csub.name);
t.is('c', c.name);
}
]
);
doh.run();
}
);
| SesamTV/ChromecastCordovaExample | www/sesamcast/bower_components/requirejs/tests/mapConfig/mapConfig-tests.js | JavaScript | mit | 787 |
define(
"dojo/cldr/nls/ru/buddhist", //begin v1.x content
{
"dateFormatItem-yM": "M.y G",
"dateFormatItem-MMMEd": "ccc, d MMM",
"dateFormatItem-yQQQ": "QQQ y G",
"dateFormatItem-MMdd": "dd.MM",
"days-standAlone-wide": [
"Воскресенье",
"Понедельник",
"Вторник",
"Среда",
"Четверг",
"Пятница",
"Суббота"
],
"dateFormatItem-MMM": "LLL",
"months-standAlone-narrow": [
"Я",
"Ф",
"М",
"А",
"М",
"И",
"И",
"А",
"С",
"О",
"Н",
"Д"
],
"dateFormatItem-yyMMMEEEd": "EEE, d MMM yy G",
"dateFormatItem-y": "y G",
"timeFormat-full": "H:mm:ss zzzz",
"dateFormatItem-yyyy": "y G",
"months-standAlone-abbr": [
"янв.",
"февр.",
"март",
"апр.",
"май",
"июнь",
"июль",
"авг.",
"сент.",
"окт.",
"нояб.",
"дек."
],
"dateFormatItem-Ed": "E, d",
"dateFormatItem-yMMM": "LLL y G",
"dateFormatItem-yyyyLLLL": "LLLL y G",
"days-standAlone-narrow": [
"В",
"П",
"В",
"С",
"Ч",
"П",
"С"
],
"dateFormatItem-yyyyMM": "MM.yyyy G",
"dateFormatItem-yyyyMMMM": "LLLL y G",
"dateFormat-long": "d MMMM y 'г'. G",
"timeFormat-medium": "H:mm:ss",
"dateFormatItem-Hm": "H:mm",
"dateFormatItem-yyMM": "MM.yy G",
"dateFormat-medium": "dd.MM.yyyy G",
"dateFormatItem-Hms": "H:mm:ss",
"dateFormatItem-yyMMM": "LLL yy G",
"dateFormatItem-yMd": "d.M.y G",
"dateFormatItem-ms": "mm:ss",
"dateFormatItem-yyyyQQQQ": "QQQQ y 'г'. G",
"months-standAlone-wide": [
"Январь",
"Февраль",
"Март",
"Апрель",
"Май",
"Июнь",
"Июль",
"Август",
"Сентябрь",
"Октябрь",
"Ноябрь",
"Декабрь"
],
"dateFormatItem-MMMd": "d MMM",
"dateFormatItem-yyQ": "Q yy G",
"timeFormat-long": "H:mm:ss z",
"months-format-abbr": [
"янв.",
"февр.",
"марта",
"апр.",
"мая",
"июня",
"июля",
"авг.",
"сент.",
"окт.",
"нояб.",
"дек."
],
"timeFormat-short": "H:mm",
"dateFormatItem-H": "H",
"quarters-format-abbr": [
"1-й кв.",
"2-й кв.",
"3-й кв.",
"4-й кв."
],
"days-format-abbr": [
"вс",
"пн",
"вт",
"ср",
"чт",
"пт",
"сб"
],
"dateFormatItem-M": "L",
"dateFormatItem-MEd": "E, d.M",
"days-standAlone-abbr": [
"Вс",
"Пн",
"Вт",
"Ср",
"Чт",
"Пт",
"Сб"
],
"dateFormat-short": "dd.MM.yy G",
"dateFormatItem-yMMMEd": "E, d MMM y G",
"dateFormat-full": "EEEE, d MMMM y 'г'. G",
"dateFormatItem-Md": "d.M",
"dateFormatItem-yMEd": "EEE, d.M.y G",
"months-format-wide": [
"января",
"февраля",
"марта",
"апреля",
"мая",
"июня",
"июля",
"августа",
"сентября",
"октября",
"ноября",
"декабря"
],
"dateFormatItem-d": "d",
"quarters-format-wide": [
"1-й квартал",
"2-й квартал",
"3-й квартал",
"4-й квартал"
],
"days-format-wide": [
"воскресенье",
"понедельник",
"вторник",
"среда",
"четверг",
"пятница",
"суббота"
]
}
//end v1.x content
); | tmthrgd/pagespeed-libraries-cdnjs | packages/dojo/1.7.8/cldr/nls/ru/buddhist.js.uncompressed.js | JavaScript | mit | 3,237 |
define(
"dojo/cldr/nls/sk/number", //begin v1.x content
{
"group": " ",
"percentSign": "%",
"exponential": "E",
"scientificFormat": "#E0",
"percentFormat": "#,##0 %",
"list": ";",
"infinity": "∞",
"minusSign": "-",
"decimal": ",",
"superscriptingExponent": "×",
"nan": "NaN",
"perMille": "‰",
"decimalFormat": "#,##0.###",
"currencyFormat": "#,##0.00 ¤;(#,##0.00 ¤)",
"plusSign": "+",
"decimalFormat-long": "000 biliónov",
"decimalFormat-short": "000 bil'.'"
}
//end v1.x content
); | beeant0512/spring | spring-thymeleaf-dojo-bootstrap/src/main/webapp/assets/dojo/dojo/cldr/nls/sk/number.js.uncompressed.js | JavaScript | mit | 512 |
/*
YUI 3.17.1 (build 0eb5a52)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('axis-numeric', function (Y, NAME) {
/**
* Provides functionality for drawing a numeric axis for use with a chart.
*
* @module charts
* @submodule axis-numeric
*/
var Y_Lang = Y.Lang;
/**
* NumericAxis draws a numeric axis.
*
* @class NumericAxis
* @constructor
* @extends Axis
* @uses NumericImpl
* @param {Object} config (optional) Configuration parameters.
* @submodule axis-numeric
*/
Y.NumericAxis = Y.Base.create("numericAxis", Y.Axis, [Y.NumericImpl], {
/**
* Calculates and returns a value based on the number of labels and the index of
* the current label.
*
* @method getLabelByIndex
* @param {Number} i Index of the label.
* @param {Number} l Total number of labels.
* @return String
* @private
*/
_getLabelByIndex: function(i, l)
{
var min = this.get("minimum"),
max = this.get("maximum"),
increm = (max - min)/(l-1),
label,
roundingMethod = this.get("roundingMethod");
l -= 1;
//respect the min and max. calculate all other labels.
if(i === 0)
{
label = min;
}
else if(i === l)
{
label = max;
}
else
{
label = (i * increm);
if(roundingMethod === "niceNumber")
{
label = this._roundToNearest(label, increm);
}
label += min;
}
return parseFloat(label);
},
/**
* Returns an object literal containing and array of label values and an array of points.
*
* @method _getLabelData
* @param {Object} startPoint An object containing x and y values.
* @param {Number} edgeOffset Distance to offset coordinates.
* @param {Number} layoutLength Distance that the axis spans.
* @param {Number} count Number of labels.
* @param {String} direction Indicates whether the axis is horizontal or vertical.
* @param {Array} Array containing values for axis labels.
* @return Array
* @private
*/
_getLabelData: function(constantVal, staticCoord, dynamicCoord, min, max, edgeOffset, layoutLength, count, dataValues)
{
var dataValue,
i,
points = [],
values = [],
point,
isVertical = staticCoord === "x",
offset = isVertical ? layoutLength + edgeOffset : edgeOffset;
dataValues = dataValues || this._getDataValuesByCount(count, min, max);
for(i = 0; i < count; i = i + 1)
{
dataValue = parseFloat(dataValues[i]);
if(dataValue <= max && dataValue >= min)
{
point = {};
point[staticCoord] = constantVal;
point[dynamicCoord] = this._getCoordFromValue(
min,
max,
layoutLength,
dataValue,
offset,
isVertical
);
points.push(point);
values.push(dataValue);
}
}
return {
points: points,
values: values
};
},
/**
* Checks to see if data extends beyond the range of the axis. If so,
* that data will need to be hidden. This method is internal, temporary and subject
* to removal in the future.
*
* @method _hasDataOverflow
* @protected
* @return Boolean
*/
_hasDataOverflow: function()
{
var roundingMethod,
min,
max;
if(this.get("setMin") || this.get("setMax"))
{
return true;
}
roundingMethod = this.get("roundingMethod");
min = this._actualMinimum;
max = this._actualMaximum;
if(Y_Lang.isNumber(roundingMethod) &&
((Y_Lang.isNumber(max) && max > this._dataMaximum) || (Y_Lang.isNumber(min) && min < this._dataMinimum)))
{
return true;
}
return false;
}
});
}, '3.17.1', {"requires": ["axis", "axis-numeric-base"]});
| davidbau/cdnjs | ajax/libs/yui/3.17.1/axis-numeric/axis-numeric.js | JavaScript | mit | 4,282 |
/*
YUI 3.17.1 (build 0eb5a52)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('dd-gestures', function (Y, NAME) {
/**
* This module is the conditional loaded `dd` module to support gesture events
* in the event that `dd` is loaded onto a device that support touch based events.
*
* This module is loaded and over rides 2 key methods on `DD.Drag` and `DD.DDM` to
* attach the gesture events. Overrides `DD.Drag._prep` and `DD.DDM._setupListeners`
* methods as well as set's the property `DD.Drag.START_EVENT` to `gesturemovestart`
* to enable gesture movement instead of mouse based movement.
* @module dd
* @submodule dd-gestures
*/
Y.log('Drag gesture support loaded', 'info', 'drag-gestures');
Y.DD.Drag.START_EVENT = 'gesturemovestart';
Y.DD.Drag.prototype._prep = function() {
Y.log('Using DD override prep to attach gesture events', 'info', 'drag-gestures');
this._dragThreshMet = false;
var node = this.get('node'), DDM = Y.DD.DDM;
node.addClass(DDM.CSS_PREFIX + '-draggable');
node.on(Y.DD.Drag.START_EVENT, Y.bind(this._handleMouseDownEvent, this), {
minDistance: this.get('clickPixelThresh'),
minTime: this.get('clickTimeThresh')
});
node.on('gesturemoveend', Y.bind(this._handleMouseUp, this), { standAlone: true });
node.on('dragstart', Y.bind(this._fixDragStart, this));
};
var _unprep = Y.DD.Drag.prototype._unprep;
Y.DD.Drag.prototype._unprep = function() {
var node = this.get('node');
_unprep.call(this);
node.detachAll('gesturemoveend');
};
Y.DD.DDM._setupListeners = function() {
var DDM = Y.DD.DDM;
this._createPG();
this._active = true;
Y.one(Y.config.doc).on('gesturemove', Y.throttle(Y.bind(DDM._move, DDM), DDM.get('throttleTime')), {
standAlone: true
});
};
}, '3.17.1', {"requires": ["dd-drag", "event-synthetic", "event-gestures"]});
| neveldo/cdnjs | ajax/libs/yui/3.17.1/dd-gestures/dd-gestures-debug.js | JavaScript | mit | 2,094 |
var users = require('./users')();
var Promise = require('bluebird');
describe("data setting and getting", function() {
var user_list = [ {id: 'alexa', password: '123456', data: {name: { first: 'alexa' }}},
{id: 'admin', password: 'letmein', data: {name: { first: 'admin' }}},
{id: 'jerry', password: 'letmeout', data: {name: { first: 'jerry' }}} ];
beforeAll(function(done) {
users.migrate_down()
.then(function() {
return users.migrate_up();
})
.then(function() {
return Promise.map(user_list, function(user) {
return users.add(user);
});
})
.finally(function() {
done();
});
});
it("should count correct number of users", function(done) {
users.count()
.then(function(n) {
expect(n).toEqual(user_list.length);
})
.catch(function(error) {
fail(error);
})
.finally(function() {
done();
});
});
it("should retreive empty map for each user", function(done) {
Promise.map(user_list,
function(user) {
return users.get(user.id)
.then(function(record) {
expect(record.data).toEqual({});
})
.catch(function(error) {
fail(error);
});
})
.finally(function() {
done();
});
});
it("should set name property of data for each user", function(done) {
Promise.map(user_list,
function(user) {
return users.data_set(user.id, 'name', user.data.name)
.then(function() {
return users.data_get(user.id, 'name.first');
})
.then(function(name) {
expect(name).toEqual(user.data.name.first);
})
.catch(function(error) {
fail(error);
})
})
.finally(function() {
done();
});
});
it("should delete name property for each user", function(done) {
Promise.map(user_list,
function(user) {
return users.data_unset(user.id, 'name')
.then(function() {
return users.data_get(user.id, 'name');
})
.then(function(name) {
expect(name).toBeUndefined();
})
.catch(function(error) {
fail(error);
})
})
.finally(function() {
done();
});
});
});
| kanthoney/knex-users | spec/data_spec.js | JavaScript | isc | 2,760 |
var
FS = require('fs');
var
isFunction = require('../utility/is-function'),
extend = require('../utility/extend'),
getBasePath = require('../utility/get-base-path'),
getExtension = require('../utility/get-extension'),
stripExtension = require('../utility/strip-extension'),
getFilename = require('../utility/get-filename');
var
Test_Wrapper = require('./wrapper');
class Test_Runner {
constructor(server_factory) {
if (!isFunction(server_factory)) {
throw new Error(
'Must supply a server factory function to testServer'
);
}
this.setServerFactory(server_factory);
}
setServerFactory(server_factory) {
this.server_factory = server_factory;
return this;
}
getServerFactory() {
return this.server_factory;
}
standardizeTestKey(key) {
key = key.replace(/_/g, ' ');
if (key[0].toUpperCase() === key[0]) {
return key;
}
var
result = key[0].toUpperCase(),
index = 1;
while (index < key.length) {
let character = key[index];
if (character.toUpperCase() === character) {
result += ' ';
}
result += character.toLowerCase();
index++;
}
return result;
}
readDirectoryRecursively(directory, path) {
if (!FS.existsSync(path)) {
if (FS.existsSync(path + '.js')) {
path += '.js';
} else {
throw new Error('Test path not found: ' + path);
}
}
if (getExtension(path) === 'js') {
let
filename = getFilename(path),
key = stripExtension(filename);
key = this.standardizeTestKey(key);
return extend(directory, {
[key]: this.wrapTestExportsForPath(path)
});
}
var files = FS.readdirSync(path);
files.forEach(function each(file) {
var
subdirectory,
resolved_path = path + '/' + file,
stats = FS.statSync(resolved_path),
key;
if (stats.isDirectory()) {
// TODO:
// save a list of directories, and don't read them
// until the end to prevent too many files being open simultaneously
file = this.standardizeTestKey(file);
subdirectory = directory[file] = { };
return void this.readDirectoryRecursively(
subdirectory,
resolved_path
);
}
if (getExtension(file) !== 'js') {
return;
}
key = stripExtension(file);
key = this.standardizeTestKey(key);
if (directory[key] !== undefined) {
if (typeof directory[key] === 'function') {
throw new Error(
'Testcase ' + key
+ ' overwritten by nested module'
+ ' (in ' + path + ')'
);
}
directory[key] = extend(
directory[key],
this.wrapTestExportsForPath(resolved_path),
path
);
} else {
directory[key] = this.wrapTestExportsForPath(resolved_path);
}
}, this);
return directory;
}
wrapTestExportsForPath(path) {
var exports = require(path);
path = path.replace(/_/g, ' ');
if (isFunction(exports)) {
return this.wrapTestMethod(path, exports);
}
var
result = { },
key;
for (key in exports) {
let property = exports[key];
key = this.standardizeTestKey(key);
if (isFunction(property)) {
result[key] = this.wrapTestMethod(key, property);
} else {
result[key] = property;
}
}
return result;
}
wrapTestMethod(key, method) {
var server_factory = this.getServerFactory();
function wrappedMethod(test) {
return (new Test_Wrapper())
.setKey(key)
.setMethod(method)
.setTest(test)
.setServerFactory(server_factory)
.run();
}
return wrappedMethod;
}
getTimeoutDelay() {
// Five second timeout threshold:
return 5000;
}
getTests(section) {
var tests = this.readDirectoryRecursively({ }, this.getTestPath());
if (!section) {
return tests;
}
var section_result = this.getSectionFromTests(section, tests);
return {
[section]: section_result
};
}
getSectionFromTests(section, tests) {
var key;
for (key in tests) {
if (key.indexOf(section) === 0) {
return tests[key];
} else if (typeof tests[key] === 'object') {
let result = this.getSectionFromTests(section, tests[key]);
if (result) {
return result;
}
}
}
return null;
}
getReporter() {
var reporters = require('nodeunit/lib/reporters');
return reporters.default;
}
getTestPath() {
return getBasePath() + '/tests/';
}
run(section) {
this.addUncaughtExceptionHandler();
this.getReporter().run(
this.getTests(section),
null,
this.handleTestsComplete.bind(this)
);
}
handleTestsComplete(error) {
if (error) {
process.exit(1);
} else {
process.exit(0);
}
}
addUncaughtExceptionHandler() {
process.on('uncaughtException', this.handleUncaughtException.bind(this));
}
handleUncaughtException(error) {
console.error(error);
process.exit(1);
}
}
extend(Test_Runner.prototype, {
server_factory: null
});
module.exports = Test_Runner;
| burninggarden/pirc | lib/test/runner.js | JavaScript | isc | 4,853 |
"use strict"
const _ = require("lodash")
const path = require("path")
const webpack = require("webpack")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const commonConfig = require("./webpack.common.js")
const babelConfig = require("./babel.browser.js")
const testDir = path.resolve(path.join(__dirname, "..", "tmp"))
const config = _.mergeWith({
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
query: babelConfig,
},
],
},
externals: {
sinon: "sinon"
},
entry: {
"test": "./test/webpack-index",
},
output: {
path: path.join(testDir, "browser"),
},
plugins: [
new HtmlWebpackPlugin({
title: "Custom template using Handlebars",
template: "./build-config/templates/test.hbs",
filename: "test.html",
inject: false, // BECAUSE this plugin includes the same shit twice...
//chunks: [],
}),
new webpack.LoaderOptionsPlugin({
debug: true
}),
],
}, commonConfig.config, commonConfig.mergeCustomizer)
module.exports = config
| maxkoryukov/route4me-nodejs-sdk | build-config/webpack.test.js | JavaScript | isc | 1,082 |
module.exports = {
web: {
port: 8030
},
db:{
connection_string:"mongodb://db/crm"
}
} | Nightw0rk/cn0 | config/index.js | JavaScript | isc | 117 |
import mod1901 from './mod1901';
var value=mod1901+1;
export default value;
| MirekSz/webpack-es6-ts | app/mods/mod1902.js | JavaScript | isc | 76 |
"use strict";
import constants from './constants'
import * as util from 'util'
import EventEmitter from 'events'
import Request from './Request'
import Response from './Response'
import Event from './Event'
import rawTransport from '../transports/raw.js';
import Burtle from './Burtle.js';
import TEA from './TEA.js';
export default class ToyPadEmu extends EventEmitter {
constructor(opts){
opts = opts || { transport : new rawTransport('/dev/hidg0') }
super(opts)
if(!opts.transport && opts.transport !== false)
opts.transport = new rawTransport('/dev/hidg0')
if(opts.transport) this.setTransport(opts.transport)
constants.attach(this)
this._tokens = [];
this._hooks = []
this._builtinHooks = []
this._evqueue = []
this.burtle = new Burtle()
this.tea = new TEA()
this.tea.key = new Buffer([0x55,0xFE,0xF6,0xB0,0x62,0xBF,0x0B,0x41,0xC9,0xB3,0x7C,0xB4,0x97,0x3E,0x29,0x7B])
this.on('request',this.processRequest.bind(this))
setInterval(()=>{
while(this._evqueue.length)
this._write(this._evqueue.shift().build())
},500)
}
pad(pad){
return this._tokens.filter(t=>t.pad == pad)
}
get pad1(){ return this.pad(1) }
get pad2(){ return this.pad(2) }
get pad3(){ return this.pad(3) }
place(token, pad, index, uid) {
if(this.pad(pad).length == (pad==1?1:3))
return false;
var nt = {
index: index || this._tokens.map(v=>v.index).reduceRight((l,v,i)=>v>i?l-1:l,this._tokens.length),
pad: pad,
uid: uid,
token: token
}
this.tagPlaceEvent(nt)
this._tokens.push(nt)
this._tokens.sort((a,b)=>b.index-a.index)
return nt
}
remove(tag){
if (typeof tag == 'number')
tag = this._tokens.filter(v=> v.index == tag)[0]
var ind = this._tokens.indexOf(tag)
this._tokens.splice(ind,1)
this.tagRemoveEvent(tag)
}
tagPlaceEvent(tag){
var ev = new Event(tag)
ev.dir = 0
this._evqueue.push(ev)
}
tagRemoveEvent(tag){
var ev = new Event(tag)
ev.dir = 1
this._evqueue.push(ev)
}
_write(data){
if(this.transport)
this.transport.write(data)
else
throw new Error('Transport not set')
}
setTransport(transport){
this.transport = transport
this.transport.on('data',(data)=>{
this.emit('request', new Request(data))
})
}
processRequest(req){
var res = new Response()
res.cid = req.cid
res.payload = new Buffer(0)
var active = (h)=>(h.cmd == req.cmd || h.cmd == 0)
this._hooks.filter(active).forEach((h)=>h.cb(req,res))
if(res._cancel) return
if(!res._preventDefault)
this._builtinHooks.filter(active).forEach((h)=>h.cb(req,res))
if(res._cancel) return
this.emit('response',res)
this._write(res.build())
}
hook(cmd,cb){
if(typeof type == 'function'){ cb = cmd; cmd = 0 }
this._hooks.push({
cmd: cmd,
cb: cb
})
}
_hook(cmd,cb){
if(typeof type == 'function'){ cb = cmd; cmd = 0 }
this._builtinHooks.push({
cmd: cmd,
cb: cb
})
}
addEvent(ev){
this._evqueue.push(ev)
}
randomUID(){
var uid = new Buffer(7)
uid[0] = 0x0F
for(var i=1;i<7;i++)
uid[i] = Math.round(Math.random() * 256) % 256
return uid.toString('hex').toUpperCase()
}
registerDefaults(){
this._hook(this.CMD_WAKE,(req,res)=>{
res.payload = new Buffer('286329204c45474f2032303134','hex')
this._tokens.forEach(ev=>this.tagPlaceEvent(ev))
})
this._hook(this.CMD_READ,(req,res)=>{
var ind = req.payload[0]
var page = req.payload[1]
res.payload = new Buffer(17)
res.payload[0] = 0
var start = page * 4
var token = this._tokens.find(t=>t.index == ind)
console.log(token)
if(token)
token.token.copy(res.payload,1,start,start + 16)
})
this._hook(this.CMD_MODEL,(req,res)=>{
req.payload = this.decrypt(req.payload)
var index = req.payload.readUInt8(0)
var conf = req.payload.readUInt32BE(4)
var token = this._tokens.find(t=>t.index == index)
var buf = new Buffer(8)
buf.writeUInt32BE(conf,4)
res.payload = new Buffer(9)
if(token)
if(token.token.id)
buf.writeUInt32LE(token.token.id || 0,0)
else
res.payload[0] = 0xF9
else
res.payload[0] = 0xF2
console.log('D4',index,buf)
this.encrypt(buf).copy(res.payload,1)
})
this._hook(this.CMD_SEED,(req,res)=>{
req.payload = this.decrypt(req.payload)
var seed = req.payload.readUInt32LE(0)
var conf = req.payload.readUInt32BE(4)
this.burtle.init(seed)
console.log('SEED',seed)
res.payload = new Buffer(8)
res.payload.fill(0)
res.payload.writeUInt32BE(conf,0)
res.payload = this.encrypt(res.payload)
})
this._hook(this.CMD_CHAL,(req,res)=>{
req.payload = this.decrypt(req.payload)
var conf = req.payload.readUInt32BE(0)
res.payload = new Buffer(8)
var rand = this.burtle.rand()
console.log('RNG',rand.toString(16))
res.payload.writeUInt32LE(rand,0)
res.payload.writeUInt32BE(conf,4)
res.payload = this.encrypt(res.payload)
})
}
encrypt(buffer){
return this.tea.encrypt(buffer)
}
decrypt(buffer){
return this.tea.decrypt(buffer)
}
}
| withgallantry/vortex | src/lib/ToyPadEmu.js | JavaScript | isc | 4,994 |
import Firebase from 'firebase'
import { ROOT_FIREBASE_URL, FAVORITE_MOVIES } from '../constants/constants'
import { CHILD_ADDED } from '../constants/firebaseTypes'
function firebaseService(actions) {
var rootFirebaseRef = new Firebase(ROOT_FIREBASE_URL)
var favoriteMoviesFirebaseRef = rootFirebaseRef.child(FAVORITE_MOVIES)
return {
getRootFirebaseRef() {
return rootFirebaseRef
},
getFavoriteMoviesFirebaseRef() {
return favoriteMoviesFirebaseRef
},
addToFavoriteMovies(movie) {
return favoriteMoviesFirebaseRef.push(movie, (err) => {
if (err) {
console.error(err.message)
}
})
},
removeFromFavoriteMovies(key) {
let movieRef = favoriteMoviesFirebaseRef.child(key)
let errorHandler = (err) => {
if (err) {
console.error(err)
} else {
console.log(`movie ${ key } was removed`)
actions.childRemoved(key)
}
}
movieRef.remove(errorHandler)
},
on(type) {
switch(type) {
case CHILD_ADDED:
favoriteMoviesFirebaseRef.on(CHILD_ADDED, function childAdded(childSnapshot, prevChildKey) {
let movie = childSnapshot.val()
movie.firebaseKey = childSnapshot.key()
// TODO: how to postpone the actions while dealing with firebase?
setTimeout(() => actions.childAdded(movie), 0)
})
break;
}
}
}
}
export default firebaseService
// _listenToFavoriteMoviesSvc() {
// }
// _removeFromFavoriteMovies(key) {
// this._favoriteMovies = this._favoriteMovies.filter((movie) => movie.firebaseKey !== key)
// // FIXME: should send another action to the system?
// this.emitChange()
// }
| qmmr/react-movies | src/services/firebaseService.js | JavaScript | isc | 1,620 |
var levenmorpher = require('levenmorpher');
function builder(yargs) {}
function handler(argv)
{
var trail = levenmorpher(argv.word1, argv.word2);
if (trail) argv.reply(trail.join(' ➜ '));
else argv.reply(`cannot morph ${argv.word1} to ${argv.word2}`);
}
module.exports = {
command: 'morph <word1> <word2',
describe: 'morph the first word into the second',
builder: builder,
handler: handler
};
| ceejbot/opsbot | commands/levenmorph.js | JavaScript | isc | 406 |
'use strict';
angular.module('teamtoolApp')
.config(function ($stateProvider) {
$stateProvider
.state('metrics', {
parent: 'admin',
url: '/metrics',
data: {
roles: ['ROLE_ADMIN'],
pageTitle: 'metrics.title'
},
views: {
'content@': {
templateUrl: 'scripts/app/admin/metrics/metrics.html',
controller: 'MetricsController'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('metrics');
return $translate.refresh();
}]
}
});
});
| MilenkoBugueno/teamtool-sandbox | src/main/webapp/scripts/app/admin/metrics/metrics.js | JavaScript | mit | 922 |
// The MIT License (MIT)
// Copyright (c) 2014 John Franklin Pavley
// see LICENSE.txt for full license text
var assert = require('assert');
var PLAYER_STANCES = {
"ready" : 0,
"attacking" : 1,
"defending" : 2
};
var STD_HEALTH = 1000000,
STD_SHIELD = 1000000;
// Character Class - Represents a playable character in the game
function JFPCharacter () {
// instance vars
this.quietMode = false;
this.name = "New Guy";
this.health = 0;
this.shield = 0;
this.weapon = {
"name" : "Power Packed Punch",
"damage" : 75
};
this.stance = PLAYER_STANCES.ready;
this.target;
}
JFPCharacter.prototype.isDead = function () {
return this.health < 1;
}
JFPCharacter.prototype.isShieldDown = function () {
return this.shield < 1;
}
JFPCharacter.prototype.hitTarget = function (weapon) {
if (!this.target || this.target.isDead() || this.isDead()) {
// there must be a target
// the dead can not be attacked
// the dead can not attack
if (!this.quietMode) {
console.log("Can't hit because " + this.name + " has no target, or its target is dead, or it's dead!");
}
return;
}
if (!this.quietMode) {
console.log("* " + this.name + " hits " + this.target.name + " with " + this.weapon.name + " *");
}
var hitPoints = this.weapon.damage + Math.floor((Math.random() * 10) + 1);
if (!this.quietMode) {
console.log(" Damage Amount: " + hitPoints);
}
switch (this.target.stance) {
case PLAYER_STANCES.ready:
case PLAYER_STANCES.attacking:
this.target.health -= hitPoints;
break;
case PLAYER_STANCES.defending:
if (this.target.isShieldDown()) {
this.target.health -= hitPoints;
} else {
this.target.shield -= hitPoints;
}
}
if (this.target.health < 0) {
this.target.health = 0;
}
if (this.target.shield < 0) {
this.target.shield = 0;
}
if (!this.quietMode) {
console.log(" Results of attack:");
console.log(" Target " + this.target.name + " shield: " + this.target.shield + " health: " + this.target.health);
}
if (this.target.isDead()) {
if (!this.quietMode) {
console.log(" Target " + this.target.name + " is dead! ");
}
}
}
// test Character Class
var morgan = new JFPCharacter();
assert(morgan.isDead(), "morgan should be dead because he was just created!");
assert(morgan.isShieldDown())
morgan.name = "Morgan";
assert(morgan.name === "Morgan");
morgan.health = STD_HEALTH;
assert(morgan.health === STD_HEALTH);
assert(!morgan.isDead(), "morgan should not be dead yet!");
morgan.shield = STD_SHIELD;
assert(morgan.shield === STD_SHIELD);
assert(!morgan.isShieldDown());
morgan.stance = PLAYER_STANCES.attacking;
assert(morgan.stance === PLAYER_STANCES.attacking);
console.log(morgan);
var fing = new JFPCharacter();
fing.name = "Fing";
fing.stance = PLAYER_STANCES.defending;
fing.health = STD_HEALTH;
fing.shield = STD_SHIELD;
fing.weapon = { "name": "Super Slap Spell", "damage": 40 };
console.log(fing);
morgan.target = fing;
fing.target = morgan;
var gameLoop = function (id, goodGuy, badGuy) {
var count = 0;
var gameOver = false;
while (!gameOver) {
count++;
goodGuy.hitTarget();
badGuy.hitTarget();
if (goodGuy.isDead() || badGuy.isDead()) {
gameOver = true;
};
}
};
// Test run games
var gameStartTime = Date.now();
console.log("==========================");
console.log("Let the games begin!");
console.log("==========================");
for (var i = 10000; i >= 0; i--) {
var goodGuy = new JFPCharacter();
goodGuy.name = "Good Guy";
goodGuy.stance = PLAYER_STANCES.attacking;
goodGuy.health = STD_HEALTH;
goodGuy.shield = STD_SHIELD;
goodGuy.quietMode = true;
var badGuy = new JFPCharacter();
badGuy.name = "Bad Guy";
badGuy.stance = PLAYER_STANCES.attacking;
badGuy.health = STD_HEALTH;
badGuy.shield = STD_SHIELD;
badGuy.quietMode = true;
goodGuy.target = badGuy;
badGuy.target = goodGuy;
gameLoop(i, goodGuy, badGuy);
};
var gameEndTime = Date.now();
var gameElaspedTime = gameEndTime - gameStartTime;
console.log("===================================================");
console.log("Games duration in milliseconds: " + gameElaspedTime);
console.log("===================================================");
| jpavley/js_playground | dungeonators.js | JavaScript | mit | 4,322 |
import { RECEIVE_USER_REVISIONS, API_FAIL } from '../constants';
import logErrorMessage from '../utils/log_error_message';
import request from '../utils/request';
const fetchUserRevisionsPromise = async (courseId, userId) => {
const response = await request(`/revisions.json?user_id=${userId}&course_id=${courseId}`);
if (!response.ok) {
logErrorMessage(response);
const data = await response.text();
response.responseText = data;
throw response;
}
return response.json();
};
export const fetchUserRevisions = (courseId, userId) => (dispatch, getState) => {
// Don't refetch a user's revisions if they are already in the store.
if (getState().userRevisions[userId]) { return; }
return (
fetchUserRevisionsPromise(courseId, userId)
.then((resp) => {
dispatch({
type: RECEIVE_USER_REVISIONS,
data: resp,
userId
});
})
.catch(response => (dispatch({ type: API_FAIL, data: response })))
);
};
| WikiEducationFoundation/WikiEduDashboard | app/assets/javascripts/actions/user_revisions_actions.js | JavaScript | mit | 994 |
define(["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Resource {
constructor(descr, color) {
this.value = 0;
this.descr = descr;
this.color = color;
}
}
exports.Resource = Resource;
var RES;
(function (RES) {
RES[RES["cpu"] = 0] = "cpu";
RES[RES["ram"] = 1] = "ram";
RES[RES["hdd"] = 2] = "hdd";
RES[RES["net"] = 3] = "net";
RES[RES["int"] = 4] = "int";
RES[RES["count"] = 5] = "count";
})(RES = exports.RES || (exports.RES = {}));
});
| Xecutor/hypercloud-7drl | js/resources.js | JavaScript | mit | 658 |
/**
* Facebook
*
* Sharing service configuration
*
* Supported parameters:
* - [u=window.location.href] - URL of the page to share
*
* @see {@link https://dev.twitter.com/web/tweet-button#properties}
*/
export default {
BASE: 'http://www.facebook.com/sharer.php',
params: {
u: {
friendly: 'url',
parse: encodeURIComponent,
default: window.location.href,
},
},
};
| odopod/code-library | packages/odo-share/src/services/facebook.js | JavaScript | mit | 405 |
'use strict';
const _ = require('lodash');
const Utils = require('../../utils');
const DataTypes = require('../../data-types');
const Transaction = require('../../transaction');
const QueryTypes = require('../../query-types');
/**
* The interface that Sequelize uses to talk to all databases
*/
class QueryInterface {
constructor(sequelize, queryGenerator) {
this.sequelize = sequelize;
this.queryGenerator = queryGenerator;
}
/**
* Create a database
*
* @param {string} database Database name to create
* @param {object} [options] Query options
* @param {string} [options.charset] Database default character set, MYSQL only
* @param {string} [options.collate] Database default collation
* @param {string} [options.encoding] Database default character set, PostgreSQL only
* @param {string} [options.ctype] Database character classification, PostgreSQL only
* @param {string} [options.template] The name of the template from which to create the new database, PostgreSQL only
*
* @returns {Promise}
*/
async createDatabase(database, options) {
options = options || {};
const sql = this.queryGenerator.createDatabaseQuery(database, options);
return await this.sequelize.query(sql, options);
}
/**
* Drop a database
*
* @param {string} database Database name to drop
* @param {object} [options] Query options
*
* @returns {Promise}
*/
async dropDatabase(database, options) {
options = options || {};
const sql = this.queryGenerator.dropDatabaseQuery(database);
return await this.sequelize.query(sql, options);
}
/**
* Create a schema
*
* @param {string} schema Schema name to create
* @param {object} [options] Query options
*
* @returns {Promise}
*/
async createSchema(schema, options) {
options = options || {};
const sql = this.queryGenerator.createSchema(schema);
return await this.sequelize.query(sql, options);
}
/**
* Drop a schema
*
* @param {string} schema Schema name to drop
* @param {object} [options] Query options
*
* @returns {Promise}
*/
async dropSchema(schema, options) {
options = options || {};
const sql = this.queryGenerator.dropSchema(schema);
return await this.sequelize.query(sql, options);
}
/**
* Drop all schemas
*
* @param {object} [options] Query options
*
* @returns {Promise}
*/
async dropAllSchemas(options) {
options = options || {};
if (!this.queryGenerator._dialect.supports.schemas) {
return this.sequelize.drop(options);
}
const schemas = await this.showAllSchemas(options);
return Promise.all(schemas.map(schemaName => this.dropSchema(schemaName, options)));
}
/**
* Show all schemas
*
* @param {object} [options] Query options
*
* @returns {Promise<Array>}
*/
async showAllSchemas(options) {
options = {
...options,
raw: true,
type: this.sequelize.QueryTypes.SELECT
};
const showSchemasSql = this.queryGenerator.showSchemasQuery(options);
const schemaNames = await this.sequelize.query(showSchemasSql, options);
return _.flatten(schemaNames.map(value => value.schema_name ? value.schema_name : value));
}
/**
* Return database version
*
* @param {object} [options] Query options
* @param {QueryType} [options.type] Query type
*
* @returns {Promise}
* @private
*/
async databaseVersion(options) {
return await this.sequelize.query(
this.queryGenerator.versionQuery(),
{ ...options, type: QueryTypes.VERSION }
);
}
/**
* Create a table with given set of attributes
*
* ```js
* queryInterface.createTable(
* 'nameOfTheNewTable',
* {
* id: {
* type: Sequelize.INTEGER,
* primaryKey: true,
* autoIncrement: true
* },
* createdAt: {
* type: Sequelize.DATE
* },
* updatedAt: {
* type: Sequelize.DATE
* },
* attr1: Sequelize.STRING,
* attr2: Sequelize.INTEGER,
* attr3: {
* type: Sequelize.BOOLEAN,
* defaultValue: false,
* allowNull: false
* },
* //foreign key usage
* attr4: {
* type: Sequelize.INTEGER,
* references: {
* model: 'another_table_name',
* key: 'id'
* },
* onUpdate: 'cascade',
* onDelete: 'cascade'
* }
* },
* {
* engine: 'MYISAM', // default: 'InnoDB'
* charset: 'latin1', // default: null
* schema: 'public', // default: public, PostgreSQL only.
* comment: 'my table', // comment for table
* collate: 'latin1_danish_ci' // collation, MYSQL only
* }
* )
* ```
*
* @param {string} tableName Name of table to create
* @param {object} attributes Object representing a list of table attributes to create
* @param {object} [options] create table and query options
* @param {Model} [model] model class
*
* @returns {Promise}
*/
async createTable(tableName, attributes, options, model) {
let sql = '';
options = { ...options };
if (options && options.uniqueKeys) {
_.forOwn(options.uniqueKeys, uniqueKey => {
if (uniqueKey.customIndex === undefined) {
uniqueKey.customIndex = true;
}
});
}
if (model) {
options.uniqueKeys = options.uniqueKeys || model.uniqueKeys;
}
attributes = _.mapValues(
attributes,
attribute => this.sequelize.normalizeAttribute(attribute)
);
// Postgres requires special SQL commands for ENUM/ENUM[]
await this.ensureEnums(tableName, attributes, options, model);
if (
!tableName.schema &&
(options.schema || !!model && model._schema)
) {
tableName = this.queryGenerator.addSchema({
tableName,
_schema: !!model && model._schema || options.schema
});
}
attributes = this.queryGenerator.attributesToSQL(attributes, { table: tableName, context: 'createTable' });
sql = this.queryGenerator.createTableQuery(tableName, attributes, options);
return await this.sequelize.query(sql, options);
}
/**
* Drop a table from database
*
* @param {string} tableName Table name to drop
* @param {object} options Query options
*
* @returns {Promise}
*/
async dropTable(tableName, options) {
// if we're forcing we should be cascading unless explicitly stated otherwise
options = { ...options };
options.cascade = options.cascade || options.force || false;
const sql = this.queryGenerator.dropTableQuery(tableName, options);
await this.sequelize.query(sql, options);
}
async _dropAllTables(tableNames, skip, options) {
for (const tableName of tableNames) {
// if tableName is not in the Array of tables names then don't drop it
if (!skip.includes(tableName.tableName || tableName)) {
await this.dropTable(tableName, { ...options, cascade: true } );
}
}
}
/**
* Drop all tables from database
*
* @param {object} [options] query options
* @param {Array} [options.skip] List of table to skip
*
* @returns {Promise}
*/
async dropAllTables(options) {
options = options || {};
const skip = options.skip || [];
const tableNames = await this.showAllTables(options);
const foreignKeys = await this.getForeignKeysForTables(tableNames, options);
for (const tableName of tableNames) {
let normalizedTableName = tableName;
if (_.isObject(tableName)) {
normalizedTableName = `${tableName.schema}.${tableName.tableName}`;
}
for (const foreignKey of foreignKeys[normalizedTableName]) {
await this.sequelize.query(this.queryGenerator.dropForeignKeyQuery(tableName, foreignKey));
}
}
await this._dropAllTables(tableNames, skip, options);
}
/**
* Rename a table
*
* @param {string} before Current name of table
* @param {string} after New name from table
* @param {object} [options] Query options
*
* @returns {Promise}
*/
async renameTable(before, after, options) {
options = options || {};
const sql = this.queryGenerator.renameTableQuery(before, after);
return await this.sequelize.query(sql, options);
}
/**
* Get all tables in current database
*
* @param {object} [options] Query options
* @param {boolean} [options.raw=true] Run query in raw mode
* @param {QueryType} [options.type=QueryType.SHOWTABLE] query type
*
* @returns {Promise<Array>}
* @private
*/
async showAllTables(options) {
options = {
...options,
raw: true,
type: QueryTypes.SHOWTABLES
};
const showTablesSql = this.queryGenerator.showTablesQuery(this.sequelize.config.database);
const tableNames = await this.sequelize.query(showTablesSql, options);
return _.flatten(tableNames);
}
/**
* Describe a table structure
*
* This method returns an array of hashes containing information about all attributes in the table.
*
* ```js
* {
* name: {
* type: 'VARCHAR(255)', // this will be 'CHARACTER VARYING' for pg!
* allowNull: true,
* defaultValue: null
* },
* isBetaMember: {
* type: 'TINYINT(1)', // this will be 'BOOLEAN' for pg!
* allowNull: false,
* defaultValue: false
* }
* }
* ```
*
* @param {string} tableName table name
* @param {object} [options] Query options
*
* @returns {Promise<object>}
*/
async describeTable(tableName, options) {
let schema = null;
let schemaDelimiter = null;
if (typeof options === 'string') {
schema = options;
} else if (typeof options === 'object' && options !== null) {
schema = options.schema || null;
schemaDelimiter = options.schemaDelimiter || null;
}
if (typeof tableName === 'object' && tableName !== null) {
schema = tableName.schema;
tableName = tableName.tableName;
}
const sql = this.queryGenerator.describeTableQuery(tableName, schema, schemaDelimiter);
options = { ...options, type: QueryTypes.DESCRIBE };
try {
const data = await this.sequelize.query(sql, options);
/*
* If no data is returned from the query, then the table name may be wrong.
* Query generators that use information_schema for retrieving table info will just return an empty result set,
* it will not throw an error like built-ins do (e.g. DESCRIBE on MySql).
*/
if (_.isEmpty(data)) {
throw new Error(`No description found for "${tableName}" table. Check the table name and schema; remember, they _are_ case sensitive.`);
}
return data;
} catch (e) {
if (e.original && e.original.code === 'ER_NO_SUCH_TABLE') {
throw new Error(`No description found for "${tableName}" table. Check the table name and schema; remember, they _are_ case sensitive.`);
}
throw e;
}
}
/**
* Add a new column to a table
*
* ```js
* queryInterface.addColumn('tableA', 'columnC', Sequelize.STRING, {
* after: 'columnB' // after option is only supported by MySQL
* });
* ```
*
* @param {string} table Table to add column to
* @param {string} key Column name
* @param {object} attribute Attribute definition
* @param {object} [options] Query options
*
* @returns {Promise}
*/
async addColumn(table, key, attribute, options) {
if (!table || !key || !attribute) {
throw new Error('addColumn takes at least 3 arguments (table, attribute name, attribute definition)');
}
options = options || {};
attribute = this.sequelize.normalizeAttribute(attribute);
return await this.sequelize.query(this.queryGenerator.addColumnQuery(table, key, attribute), options);
}
/**
* Remove a column from a table
*
* @param {string} tableName Table to remove column from
* @param {string} attributeName Column name to remove
* @param {object} [options] Query options
*/
async removeColumn(tableName, attributeName, options) {
return this.sequelize.query(this.queryGenerator.removeColumnQuery(tableName, attributeName), options);
}
normalizeAttribute(dataTypeOrOptions) {
let attribute;
if (Object.values(DataTypes).includes(dataTypeOrOptions)) {
attribute = { type: dataTypeOrOptions, allowNull: true };
} else {
attribute = dataTypeOrOptions;
}
return this.sequelize.normalizeAttribute(attribute);
}
/**
* Change a column definition
*
* @param {string} tableName Table name to change from
* @param {string} attributeName Column name
* @param {object} dataTypeOrOptions Attribute definition for new column
* @param {object} [options] Query options
*/
async changeColumn(tableName, attributeName, dataTypeOrOptions, options) {
options = options || {};
const query = this.queryGenerator.attributesToSQL({
[attributeName]: this.normalizeAttribute(dataTypeOrOptions)
}, {
context: 'changeColumn',
table: tableName
});
const sql = this.queryGenerator.changeColumnQuery(tableName, query);
return this.sequelize.query(sql, options);
}
/**
* Rejects if the table doesn't have the specified column, otherwise returns the column description.
*
* @param {string} tableName
* @param {string} columnName
* @param {object} options
* @private
*/
async assertTableHasColumn(tableName, columnName, options) {
const description = await this.describeTable(tableName, options);
if (description[columnName]) {
return description;
}
throw new Error(`Table ${tableName} doesn't have the column ${columnName}`);
}
/**
* Rename a column
*
* @param {string} tableName Table name whose column to rename
* @param {string} attrNameBefore Current column name
* @param {string} attrNameAfter New column name
* @param {object} [options] Query option
*
* @returns {Promise}
*/
async renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
const data = (await this.assertTableHasColumn(tableName, attrNameBefore, options))[attrNameBefore];
const _options = {};
_options[attrNameAfter] = {
attribute: attrNameAfter,
type: data.type,
allowNull: data.allowNull,
defaultValue: data.defaultValue
};
// fix: a not-null column cannot have null as default value
if (data.defaultValue === null && !data.allowNull) {
delete _options[attrNameAfter].defaultValue;
}
const sql = this.queryGenerator.renameColumnQuery(
tableName,
attrNameBefore,
this.queryGenerator.attributesToSQL(_options)
);
return await this.sequelize.query(sql, options);
}
/**
* Add an index to a column
*
* @param {string|object} tableName Table name to add index on, can be a object with schema
* @param {Array} [attributes] Use options.fields instead, List of attributes to add index on
* @param {object} options indexes options
* @param {Array} options.fields List of attributes to add index on
* @param {boolean} [options.concurrently] Pass CONCURRENT so other operations run while the index is created
* @param {boolean} [options.unique] Create a unique index
* @param {string} [options.using] Useful for GIN indexes
* @param {string} [options.operator] Index operator
* @param {string} [options.type] Type of index, available options are UNIQUE|FULLTEXT|SPATIAL
* @param {string} [options.name] Name of the index. Default is <table>_<attr1>_<attr2>
* @param {object} [options.where] Where condition on index, for partial indexes
* @param {string} [rawTablename] table name, this is just for backward compatibiity
*
* @returns {Promise}
*/
async addIndex(tableName, attributes, options, rawTablename) {
// Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes)
if (!Array.isArray(attributes)) {
rawTablename = options;
options = attributes;
attributes = options.fields;
}
if (!rawTablename) {
// Map for backwards compat
rawTablename = tableName;
}
options = Utils.cloneDeep(options);
options.fields = attributes;
const sql = this.queryGenerator.addIndexQuery(tableName, options, rawTablename);
return await this.sequelize.query(sql, { ...options, supportsSearchPath: false });
}
/**
* Show indexes on a table
*
* @param {string} tableName table name
* @param {object} [options] Query options
*
* @returns {Promise<Array>}
* @private
*/
async showIndex(tableName, options) {
const sql = this.queryGenerator.showIndexesQuery(tableName, options);
return await this.sequelize.query(sql, { ...options, type: QueryTypes.SHOWINDEXES });
}
/**
* Returns all foreign key constraints of requested tables
*
* @param {string[]} tableNames table names
* @param {object} [options] Query options
*
* @returns {Promise}
*/
async getForeignKeysForTables(tableNames, options) {
if (tableNames.length === 0) {
return {};
}
options = { ...options, type: QueryTypes.FOREIGNKEYS };
const results = await Promise.all(tableNames.map(tableName =>
this.sequelize.query(this.queryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options)));
const result = {};
tableNames.forEach((tableName, i) => {
if (_.isObject(tableName)) {
tableName = `${tableName.schema}.${tableName.tableName}`;
}
result[tableName] = Array.isArray(results[i])
? results[i].map(r => r.constraint_name)
: [results[i] && results[i].constraint_name];
result[tableName] = result[tableName].filter(_.identity);
});
return result;
}
/**
* Get foreign key references details for the table
*
* Those details contains constraintSchema, constraintName, constraintCatalog
* tableCatalog, tableSchema, tableName, columnName,
* referencedTableCatalog, referencedTableCatalog, referencedTableSchema, referencedTableName, referencedColumnName.
* Remind: constraint informations won't return if it's sqlite.
*
* @param {string} tableName table name
* @param {object} [options] Query options
*/
async getForeignKeyReferencesForTable(tableName, options) {
const queryOptions = {
...options,
type: QueryTypes.FOREIGNKEYS
};
const query = this.queryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database);
return this.sequelize.query(query, queryOptions);
}
/**
* Remove an already existing index from a table
*
* @param {string} tableName Table name to drop index from
* @param {string|string[]} indexNameOrAttributes Index name or list of attributes that in the index
* @param {object} [options] Query options
*
* @returns {Promise}
*/
async removeIndex(tableName, indexNameOrAttributes, options) {
options = options || {};
const sql = this.queryGenerator.removeIndexQuery(tableName, indexNameOrAttributes);
return await this.sequelize.query(sql, options);
}
/**
* Add a constraint to a table
*
* Available constraints:
* - UNIQUE
* - DEFAULT (MSSQL only)
* - CHECK (MySQL - Ignored by the database engine )
* - FOREIGN KEY
* - PRIMARY KEY
*
* @example <caption>UNIQUE</caption>
* queryInterface.addConstraint('Users', {
* fields: ['email'],
* type: 'unique',
* name: 'custom_unique_constraint_name'
* });
*
* @example <caption>CHECK</caption>
* queryInterface.addConstraint('Users', {
* fields: ['roles'],
* type: 'check',
* where: {
* roles: ['user', 'admin', 'moderator', 'guest']
* }
* });
*
* @example <caption>Default - MSSQL only</caption>
* queryInterface.addConstraint('Users', {
* fields: ['roles'],
* type: 'default',
* defaultValue: 'guest'
* });
*
* @example <caption>Primary Key</caption>
* queryInterface.addConstraint('Users', {
* fields: ['username'],
* type: 'primary key',
* name: 'custom_primary_constraint_name'
* });
*
* @example <caption>Foreign Key</caption>
* queryInterface.addConstraint('Posts', {
* fields: ['username'],
* type: 'foreign key',
* name: 'custom_fkey_constraint_name',
* references: { //Required field
* table: 'target_table_name',
* field: 'target_column_name'
* },
* onDelete: 'cascade',
* onUpdate: 'cascade'
* });
*
* @param {string} tableName Table name where you want to add a constraint
* @param {object} options An object to define the constraint name, type etc
* @param {string} options.type Type of constraint. One of the values in available constraints(case insensitive)
* @param {Array} options.fields Array of column names to apply the constraint over
* @param {string} [options.name] Name of the constraint. If not specified, sequelize automatically creates a named constraint based on constraint type, table & column names
* @param {string} [options.defaultValue] The value for the default constraint
* @param {object} [options.where] Where clause/expression for the CHECK constraint
* @param {object} [options.references] Object specifying target table, column name to create foreign key constraint
* @param {string} [options.references.table] Target table name
* @param {string} [options.references.field] Target column name
*
* @returns {Promise}
*/
async addConstraint(tableName, options) {
if (!options.fields) {
throw new Error('Fields must be specified through options.fields');
}
if (!options.type) {
throw new Error('Constraint type must be specified through options.type');
}
options = Utils.cloneDeep(options);
const sql = this.queryGenerator.addConstraintQuery(tableName, options);
return await this.sequelize.query(sql, options);
}
async showConstraint(tableName, constraintName, options) {
const sql = this.queryGenerator.showConstraintsQuery(tableName, constraintName);
return await this.sequelize.query(sql, { ...options, type: QueryTypes.SHOWCONSTRAINTS });
}
/**
* Remove a constraint from a table
*
* @param {string} tableName Table name to drop constraint from
* @param {string} constraintName Constraint name
* @param {object} options Query options
*/
async removeConstraint(tableName, constraintName, options) {
return this.sequelize.query(this.queryGenerator.removeConstraintQuery(tableName, constraintName), options);
}
async insert(instance, tableName, values, options) {
options = Utils.cloneDeep(options);
options.hasTrigger = instance && instance.constructor.options.hasTrigger;
const sql = this.queryGenerator.insertQuery(tableName, values, instance && instance.constructor.rawAttributes, options);
options.type = QueryTypes.INSERT;
options.instance = instance;
const results = await this.sequelize.query(sql, options);
if (instance) results[0].isNewRecord = false;
return results;
}
/**
* Upsert
*
* @param {string} tableName table to upsert on
* @param {object} insertValues values to be inserted, mapped to field name
* @param {object} updateValues values to be updated, mapped to field name
* @param {object} where where conditions, which can be used for UPDATE part when INSERT fails
* @param {object} options query options
*
* @returns {Promise<boolean,?number>} Resolves an array with <created, primaryKey>
*/
async upsert(tableName, insertValues, updateValues, where, options) {
options = { ...options };
const model = options.model;
const primaryKeys = Object.values(model.primaryKeys).map(item => item.field);
const uniqueKeys = Object.values(model.uniqueKeys).filter(c => c.fields.length >= 1).map(c => c.fields);
const indexKeys = Object.values(model._indexes).filter(c => c.unique && c.fields.length >= 1).map(c => c.fields);
options.type = QueryTypes.UPSERT;
options.updateOnDuplicate = Object.keys(updateValues);
options.upsertKeys = [];
// For fields in updateValues, try to find a constraint or unique index
// that includes given field. Only first matching upsert key is used.
for (const field of options.updateOnDuplicate) {
const uniqueKey = uniqueKeys.find(fields => fields.includes(field));
if (uniqueKey) {
options.upsertKeys = uniqueKey;
break;
}
const indexKey = indexKeys.find(fields => fields.includes(field));
if (indexKey) {
options.upsertKeys = indexKey;
break;
}
}
// Always use PK, if no constraint available OR update data contains PK
if (
options.upsertKeys.length === 0
|| _.intersection(options.updateOnDuplicate, primaryKeys).length
) {
options.upsertKeys = primaryKeys;
}
options.upsertKeys = _.uniq(options.upsertKeys);
const sql = this.queryGenerator.insertQuery(tableName, insertValues, model.rawAttributes, options);
return await this.sequelize.query(sql, options);
}
/**
* Insert multiple records into a table
*
* @example
* queryInterface.bulkInsert('roles', [{
* label: 'user',
* createdAt: new Date(),
* updatedAt: new Date()
* }, {
* label: 'admin',
* createdAt: new Date(),
* updatedAt: new Date()
* }]);
*
* @param {string} tableName Table name to insert record to
* @param {Array} records List of records to insert
* @param {object} options Various options, please see Model.bulkCreate options
* @param {object} attributes Various attributes mapped by field name
*
* @returns {Promise}
*/
async bulkInsert(tableName, records, options, attributes) {
options = { ...options };
options.type = QueryTypes.INSERT;
const results = await this.sequelize.query(
this.queryGenerator.bulkInsertQuery(tableName, records, options, attributes),
options
);
return results[0];
}
async update(instance, tableName, values, identifier, options) {
options = { ...options };
options.hasTrigger = instance && instance.constructor.options.hasTrigger;
const sql = this.queryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes);
options.type = QueryTypes.UPDATE;
options.instance = instance;
return await this.sequelize.query(sql, options);
}
/**
* Update multiple records of a table
*
* @example
* queryInterface.bulkUpdate('roles', {
* label: 'admin',
* }, {
* userType: 3,
* },
* );
*
* @param {string} tableName Table name to update
* @param {object} values Values to be inserted, mapped to field name
* @param {object} identifier A hash with conditions OR an ID as integer OR a string with conditions
* @param {object} [options] Various options, please see Model.bulkCreate options
* @param {object} [attributes] Attributes on return objects if supported by SQL dialect
*
* @returns {Promise}
*/
async bulkUpdate(tableName, values, identifier, options, attributes) {
options = Utils.cloneDeep(options);
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
const sql = this.queryGenerator.updateQuery(tableName, values, identifier, options, attributes);
const table = _.isObject(tableName) ? tableName : { tableName };
const model = _.find(this.sequelize.modelManager.models, { tableName: table.tableName });
options.type = QueryTypes.BULKUPDATE;
options.model = model;
return await this.sequelize.query(sql, options);
}
async delete(instance, tableName, identifier, options) {
const cascades = [];
const sql = this.queryGenerator.deleteQuery(tableName, identifier, {}, instance.constructor);
options = { ...options };
// Check for a restrict field
if (!!instance.constructor && !!instance.constructor.associations) {
const keys = Object.keys(instance.constructor.associations);
const length = keys.length;
let association;
for (let i = 0; i < length; i++) {
association = instance.constructor.associations[keys[i]];
if (association.options && association.options.onDelete &&
association.options.onDelete.toLowerCase() === 'cascade' &&
association.options.useHooks === true) {
cascades.push(association.accessors.get);
}
}
}
for (const cascade of cascades) {
let instances = await instance[cascade](options);
// Check for hasOne relationship with non-existing associate ("has zero")
if (!instances) continue;
if (!Array.isArray(instances)) instances = [instances];
for (const _instance of instances) await _instance.destroy(options);
}
options.instance = instance;
return await this.sequelize.query(sql, options);
}
/**
* Delete multiple records from a table
*
* @param {string} tableName table name from where to delete records
* @param {object} where where conditions to find records to delete
* @param {object} [options] options
* @param {boolean} [options.truncate] Use truncate table command
* @param {boolean} [options.cascade=false] Only used in conjunction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE.
* @param {boolean} [options.restartIdentity=false] Only used in conjunction with TRUNCATE. Automatically restart sequences owned by columns of the truncated table.
* @param {Model} [model] Model
*
* @returns {Promise}
*/
async bulkDelete(tableName, where, options, model) {
options = Utils.cloneDeep(options);
options = _.defaults(options, { limit: null });
if (options.truncate === true) {
return this.sequelize.query(
this.queryGenerator.truncateTableQuery(tableName, options),
options
);
}
if (typeof identifier === 'object') where = Utils.cloneDeep(where);
return await this.sequelize.query(
this.queryGenerator.deleteQuery(tableName, where, options, model),
options
);
}
async select(model, tableName, optionsArg) {
const options = { ...optionsArg, type: QueryTypes.SELECT, model };
return await this.sequelize.query(
this.queryGenerator.selectQuery(tableName, options, model),
options
);
}
async increment(model, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options) {
options = Utils.cloneDeep(options);
const sql = this.queryGenerator.arithmeticQuery('+', tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options);
options.type = QueryTypes.UPDATE;
options.model = model;
return await this.sequelize.query(sql, options);
}
async decrement(model, tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options) {
options = Utils.cloneDeep(options);
const sql = this.queryGenerator.arithmeticQuery('-', tableName, where, incrementAmountsByField, extraAttributesToBeUpdated, options);
options.type = QueryTypes.UPDATE;
options.model = model;
return await this.sequelize.query(sql, options);
}
async rawSelect(tableName, options, attributeSelector, Model) {
options = Utils.cloneDeep(options);
options = _.defaults(options, {
raw: true,
plain: true,
type: QueryTypes.SELECT
});
const sql = this.queryGenerator.selectQuery(tableName, options, Model);
if (attributeSelector === undefined) {
throw new Error('Please pass an attribute selector!');
}
const data = await this.sequelize.query(sql, options);
if (!options.plain) {
return data;
}
const result = data ? data[attributeSelector] : null;
if (!options || !options.dataType) {
return result;
}
const dataType = options.dataType;
if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
if (result !== null) {
return parseFloat(result);
}
}
if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
return parseInt(result, 10);
}
if (dataType instanceof DataTypes.DATE) {
if (result !== null && !(result instanceof Date)) {
return new Date(result);
}
}
return result;
}
async createTrigger(
tableName,
triggerName,
timingType,
fireOnArray,
functionName,
functionParams,
optionsArray,
options
) {
const sql = this.queryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray);
options = options || {};
if (sql) {
return await this.sequelize.query(sql, options);
}
}
async dropTrigger(tableName, triggerName, options) {
const sql = this.queryGenerator.dropTrigger(tableName, triggerName);
options = options || {};
if (sql) {
return await this.sequelize.query(sql, options);
}
}
async renameTrigger(tableName, oldTriggerName, newTriggerName, options) {
const sql = this.queryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName);
options = options || {};
if (sql) {
return await this.sequelize.query(sql, options);
}
}
/**
* Create an SQL function
*
* @example
* queryInterface.createFunction(
* 'someFunction',
* [
* {type: 'integer', name: 'param', direction: 'IN'}
* ],
* 'integer',
* 'plpgsql',
* 'RETURN param + 1;',
* [
* 'IMMUTABLE',
* 'LEAKPROOF'
* ],
* {
* variables:
* [
* {type: 'integer', name: 'myVar', default: 100}
* ],
* force: true
* };
* );
*
* @param {string} functionName Name of SQL function to create
* @param {Array} params List of parameters declared for SQL function
* @param {string} returnType SQL type of function returned value
* @param {string} language The name of the language that the function is implemented in
* @param {string} body Source code of function
* @param {Array} optionsArray Extra-options for creation
* @param {object} [options] query options
* @param {boolean} options.force If force is true, any existing functions with the same parameters will be replaced. For postgres, this means using `CREATE OR REPLACE FUNCTION` instead of `CREATE FUNCTION`. Default is false
* @param {Array<object>} options.variables List of declared variables. Each variable should be an object with string fields `type` and `name`, and optionally having a `default` field as well.
*
* @returns {Promise}
*/
async createFunction(functionName, params, returnType, language, body, optionsArray, options) {
const sql = this.queryGenerator.createFunction(functionName, params, returnType, language, body, optionsArray, options);
options = options || {};
if (sql) {
return await this.sequelize.query(sql, options);
}
}
/**
* Drop an SQL function
*
* @example
* queryInterface.dropFunction(
* 'someFunction',
* [
* {type: 'varchar', name: 'param1', direction: 'IN'},
* {type: 'integer', name: 'param2', direction: 'INOUT'}
* ]
* );
*
* @param {string} functionName Name of SQL function to drop
* @param {Array} params List of parameters declared for SQL function
* @param {object} [options] query options
*
* @returns {Promise}
*/
async dropFunction(functionName, params, options) {
const sql = this.queryGenerator.dropFunction(functionName, params);
options = options || {};
if (sql) {
return await this.sequelize.query(sql, options);
}
}
/**
* Rename an SQL function
*
* @example
* queryInterface.renameFunction(
* 'fooFunction',
* [
* {type: 'varchar', name: 'param1', direction: 'IN'},
* {type: 'integer', name: 'param2', direction: 'INOUT'}
* ],
* 'barFunction'
* );
*
* @param {string} oldFunctionName Current name of function
* @param {Array} params List of parameters declared for SQL function
* @param {string} newFunctionName New name of function
* @param {object} [options] query options
*
* @returns {Promise}
*/
async renameFunction(oldFunctionName, params, newFunctionName, options) {
const sql = this.queryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
options = options || {};
if (sql) {
return await this.sequelize.query(sql, options);
}
}
// Helper methods useful for querying
/**
* @private
*/
ensureEnums() {
// noop by default
}
async setIsolationLevel(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set isolation level for a transaction without transaction object!');
}
if (transaction.parent || !value) {
// Not possible to set a separate isolation level for savepoints
return;
}
options = { ...options, transaction: transaction.parent || transaction };
const sql = this.queryGenerator.setIsolationLevelQuery(value, {
parent: transaction.parent
});
if (!sql) return;
return await this.sequelize.query(sql, options);
}
async startTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to start a transaction without transaction object!');
}
options = { ...options, transaction: transaction.parent || transaction };
options.transaction.name = transaction.parent ? transaction.name : undefined;
const sql = this.queryGenerator.startTransactionQuery(transaction);
return await this.sequelize.query(sql, options);
}
async deferConstraints(transaction, options) {
options = { ...options, transaction: transaction.parent || transaction };
const sql = this.queryGenerator.deferConstraintsQuery(options);
if (sql) {
return await this.sequelize.query(sql, options);
}
}
async commitTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to commit a transaction without transaction object!');
}
if (transaction.parent) {
// Savepoints cannot be committed
return;
}
options = {
...options,
transaction: transaction.parent || transaction,
supportsSearchPath: false,
completesTransaction: true
};
const sql = this.queryGenerator.commitTransactionQuery(transaction);
const promise = this.sequelize.query(sql, options);
transaction.finished = 'commit';
return await promise;
}
async rollbackTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to rollback a transaction without transaction object!');
}
options = {
...options,
transaction: transaction.parent || transaction,
supportsSearchPath: false,
completesTransaction: true
};
options.transaction.name = transaction.parent ? transaction.name : undefined;
const sql = this.queryGenerator.rollbackTransactionQuery(transaction);
const promise = this.sequelize.query(sql, options);
transaction.finished = 'rollback';
return await promise;
}
}
exports.QueryInterface = QueryInterface;
| jayprakash1/sequelize | lib/dialects/abstract/query-interface.js | JavaScript | mit | 40,247 |
request = require('supertest-as-promised')
exports.post_credentials = function(payload){
return request('http://localhost:3001')
.post('/auth')
.send(payload)
};
| g33klady/api-framework | js/api/authorise.js | JavaScript | mit | 187 |
import { registerTheme } from './themes';
import { indigo as primary } from '@material-ui/core/colors';
import { deepPurple as secondary } from '@material-ui/core/colors';
import { red as error } from '@material-ui/core/colors';
import { blue as info } from '@material-ui/core/colors';
import { green as success } from '@material-ui/core/colors';
import { orange as warning } from '@material-ui/core/colors';
/** @ignore */
/**
*
* Sample theme to get you out of the gate quickly
*
* For a complete list of configuration variables see:
* https://material-ui.com/customization/themes/
*
*/
const theme = {
palette: {
primary: {
light: primary[200],
main: primary[500],
dark: primary[800],
contrastText: '#fff',
...primary
},
secondary: {
light: secondary[200],
main: secondary[500],
dark: secondary[800],
contrastText: '#fff',
...secondary
},
error: {
light: error[200],
main: error[500],
dark: error[800],
contrastText: '#fff',
...error
},
warning: {
light: warning[100],
main: warning[500],
dark: warning[900],
contrastText: '#fff',
...warning
},
success: {
light: success[100],
main: success[500],
dark: success[900],
contrastText: '#fff',
...success
},
info: {
light: info[100],
main: info[500],
dark: info[900],
contrastText: '#fff',
...info
},
},
utils: {
tooltipEnterDelay: 700,
errorMessage: {
textAlign: 'center',
backgroundColor: error[500],
color: 'white',
borderRadius: '4px',
fontWeight: 'bold',
},
denseTable: {
'& > thead > tr > th, & > tbody > tr > td': {
padding: '4px 16px 4px 16px',
},
'& > thead > tr > th:last-child, & > tbody > tr > td:last-child': {
paddingRight: '16px',
},
},
flatTable: {
'& > thead > tr > th, & > tbody > tr > td': {
padding: '4px 16px 4px 16px',
whiteSpace: 'nowrap',
},
'& > thead > tr > th:last-child, & > tbody > tr > td:last-child': {
paddingRight: '16px',
},
},
denserTable: {
'& > thead > tr, & > tbody > tr': {
height: '40px',
},
'& > thead > tr > th, & > tbody > tr > td': {
padding: '4px 16px 4px 16px',
whiteSpace: 'nowrap',
},
'& > thead > tr > th:last-child, & > tbody > tr > td:last-child': {
paddingRight: '16px',
},
},
testPaper: {
backgroundColor: warning[50],
},
closeButton: {
display: 'block !important',
position: 'absolute',
right: 8,
top: 8,
},
},
overrides: {
MuiButton: {
root: {
lineHeight: 1,
padding: '4px 16px',
minHeight: 40,
},
text: {
padding: '4px 16px',
},
outlined: {
padding: '4px 16px',
},
sizeSmall: {
padding: '4px 8px',
minHeight: 32,
},
sizeLarge: {
padding: '4px 24px',
minHeight: 48,
},
label: {
flexDirection: 'inherit',
'& > svg': {
marginRight: '8px',
},
'& > span.icon-wrap': {
marginRight: '8px',
fontSize: 0,
},
},
},
},
};
registerTheme('Sample', theme);
| VulcanJS/Vulcan | packages/vulcan-ui-material/lib/modules/sampleTheme.js | JavaScript | mit | 3,410 |
import { connect } from 'react-redux';
import { removeCaravanaFromDraftMovement } from 'app/actions/movement-actions/movement-draft-action';
import React, { Component } from 'react';
import { getDraftMovement } from 'app/reducers';
import styles from './style/movement-caravana-list.scss';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
import IconButton from 'material-ui/IconButton';
import ActionRemove from 'material-ui/svg-icons/content/delete-sweep';
class MovementCaravanaList extends Component {
render() {
return (
<div className={styles['movement-caravana-list']}>
{this.props.draftMovement.caravanas.length === 0 && (
<p className={styles['movement-caravana-list-empty']} >
Comienza agregando caravanas de la lista de la izquierda para crear
un movimiento.
</p>
)}
{this.props.draftMovement.caravanas.length > 0 && (
<div>
<div className={styles['movement-caravana-list-total']}>
Total caravanas: {this.props.draftMovement.caravanas.length}
</div>
<Table selectable={false}>
<TableHeader
adjustForCheckbox={false}
displaySelectAll={false}
>
<TableRow>
<TableHeaderColumn style={{width: '200px'}}>Número</TableHeaderColumn>
{this.props.showDelete && (
<TableHeaderColumn>Eliminar</TableHeaderColumn>
)}
</TableRow>
</TableHeader>
<TableBody displayRowCheckbox={false}>
{this.props.draftMovement.caravanas.map((caravana) => (
<TableRow key={caravana.id}>
<TableRowColumn style={{width: '200px'}}>{caravana.number}</TableRowColumn>
{this.props.showDelete && (
<TableRowColumn>
<IconButton iconStyle={{color: '#FF4081'}}>
<ActionRemove
onClick={() => this.props.removeCaravanaFromDraftMovement(caravana.id)}
/>
</IconButton>
</TableRowColumn>
)}
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</div>
);
}
}
MovementCaravanaList.defaultProps = {
showDelete: true,
};
function mapStateToProps(state) {
const draftMovement = getDraftMovement(state);
return {
draftMovement,
};
}
export default connect(
mapStateToProps,
{
removeCaravanaFromDraftMovement,
}
)(MovementCaravanaList);
| kimurakenshi/caravanas | app/containers/create-movement/components/movement-caravana-list/index.js | JavaScript | mit | 2,785 |
var ConfigService = require('./config-service'),
FirebaseService = require('./firebase-service'),
LogService = require('./log-service'),
Redis = require('redis'),
redis = Redis.createClient(),
moment = require('moment'),
_ = require('underscore'),
Utility = require('../extensions/utility'),
redisTTL = ConfigService.get('private.redis.ttl');
redis.select(ConfigService.get('private.redis.dbIndex'));
redis.on('ready', function(e) {
LogService.info('redis ready');
});
redis.on('error', function(err) {
LogService.error('redis error', err);
});
var handlers = {},
getter = function(name, individual) {
return function(key, cb) {
var deferred = Utility.async(cb),
newName = individual ? name + '-' + key : name;
redis.get(newName, function(err, data) {
return err ? deferred.reject(err) : deferred.resolve(JSON.parse(data));
});
return deferred.promise;
}
},
setter = function(name, getRef, saveIndividual, individualAttribute) {
return function(cb) {
var deferred = Utility.async(cb),
ref = getRef(),
timer = moment(),
handler = handlers[ref.key() + '-value'];
if (handler) {
ref.off('value', handler);
}
handlers[ref.key() + '-value'] = ref.on('value', function(snap) {
var object = snap.val(),
stringy = JSON.stringify(object);
redis.set(name, stringy, function(err, data) {
return err ? deferred.reject(err) : deferred.resolve(object);
});
if (timer) {
LogService.info(name + ' loaded seconds:', moment().diff(timer, 'seconds'));
timer = false;
}
if (saveIndividual) {
redis.keys(name + '-*', function(err, keys) {
var i = keys.length,
addedHandler = handlers[ref.key() + '-added'],
removedHandler = handlers[ref.key() + '-removed'];
while (i--) {
redis.del(keys[i]);
}
if (addedHandler) {
ref.off('child_added', addedHandler);
}
handlers[ref.key() + '-added'] = ref.on('child_added', function(snap) { // Gets called for each child on initial load and on every change... so it's called a lot.
var value = snap.val(),
key = snap.key(),
slug = individualAttribute ? value[individualAttribute] : key;
// console.log('adding individual', name + '-' + slug + ' ' + value.code);
redis.set(name + '-' + slug, JSON.stringify(snap.val()));
});
if (removedHandler) {
ref.off('child_removed', removedHandler);
}
handlers[ref.key() + '-removed'] = ref.on('child_removed', function(snap) {
var value = snap.val(),
key = snap.key(),
slug = individualAttribute ? value[individualAttribute] : key;
// console.log('removing individual', name + '-' + slug + ' ' + value.code);
redis.del(name + '-' + slug);
});
});
}
});
return deferred.promise;
}
};
module.exports = {
redis: redis,
setPage: function(url, html, cb) {
var deferred = Utility.async(cb);
redis.set('page-' + url, html, function(err, result) {
redis.expire('page-' + url, redisTTL);
return err ? deferred.reject(err) : deferred.resolve(result);
});
return deferred.promise;
},
getPage: function(key, cb) {
var deferred = Utility.async(cb);
redis.get('page' + '-' + key, function(err, data) {
return err ? deferred.reject(err) : deferred.resolve(data);
});
return deferred.promise;
},
getDiscounts: getter('discounts'),
getDiscount: getter('discounts', true),
setDiscounts: setter('discounts', FirebaseService.getDiscounts, true),
getWords: getter('words'),
getWord: getter('words', true),
setWords: setter('words', FirebaseService.getWords, true, 'slug'),
getProducts: getter('products'),
getProduct: getter('products', true),
setProducts: setter('products', FirebaseService.getProducts, true, 'slug'),
getSettings: getter('settings'),
setSettings: setter('settings', FirebaseService.getSettings),
getTheme: getter('theme'),
setTheme: setter('theme', FirebaseService.getTheme),
getHashtags: getter('hashtags'),
setHashtags: setter('hashtags', FirebaseService.getHashtags)
}; | deltaepsilon/quiver-cms | lib/services/redis-service.js | JavaScript | mit | 5,189 |
// Controller naming conventions should start with an uppercase letter
function MainCtrl($rootScope, $scope) {
'use strict';
$scope.test = null;
console.log('Up and running!');
}
// $inject is necessary for minification. See http://bit.ly/1lNICde for explanation.
MainCtrl.$inject = ['$rootScope', '$scope'];
module.exports = MainCtrl;
| leftiness/Optical | app/modules/MainController.js | JavaScript | mit | 344 |
'use strict';
var assert = require('chai').assert;
var HiddenMarkovModel = require('../../lib/hmm');
var fs = require('fs');
suite('Chapter 8: A not-so-simple example', function() {
var a, b, pi, observations;
setup(function() {
a = [[0.47468, 0.52532],
[0.51656, 0.48344]];
b = [[0.03735, 0.03408, 0.03455, 0.03828, 0.03782, 0.03922, 0.03688, 0.03408, 0.03875, 0.04062, 0.03735, 0.03968, 0.03548, 0.03735, 0.04062, 0.03595, 0.03641, 0.03408, 0.04062, 0.03548, 0.03922, 0.04062, 0.03455, 0.03595, 0.03408, 0.03408, 0.03688],
[0.03909, 0.03537, 0.03537, 0.03909, 0.03583, 0.03630, 0.04048, 0.03537, 0.03816, 0.03909, 0.03490, 0.03723, 0.03537, 0.03909, 0.03397, 0.03397, 0.03816, 0.03676, 0.04048, 0.03443, 0.03537, 0.03955, 0.03816, 0.03723, 0.03769, 0.03955, 0.03397]];
pi = [[0.51316, 0.48684]];
observations = fs.readFileSync(
__dirname + '/../resources/brown-corpus-50000.data');
});
// I suspect the corpus data converted is not exact so I am not getting the
// exact numbers, but obviously there are other problems here.
//
// The assertion here simply list the results we currently got.
test('Train the model to fit observations (incomplete)', function() {
this.timeout(60000);
var hmm = new HiddenMarkovModel(a, b, pi);
hmm.fitObservations(observations, 1);
var initialLogProb =
hmm.getProbabilityOfObservations(observations, true);
// assert.equal(initialLogProb.toFixed(2), '-165097.29');
assert.equal(initialLogProb.toFixed(2), '-142387.95');
var iter = hmm.fitObservations(observations, 99);
// assert.equal(iter, 99);
assert.equal(iter, 6);
var logProb = hmm.getProbabilityOfObservations(observations, true);
// assert.equal(logProb.toFixed(2), '-137305.28');
assert.equal(logProb.toFixed(2), '-142317.47');
var figure3 = [];
for (var i = 0; i < 26; i++) {
figure3.push([
' ' + String.fromCharCode(0x61 + i),
b[0][i].toFixed(5),
b[1][i].toFixed(5),
hmm.observationProbabilityMatrix[0][i].toFixed(5),
hmm.observationProbabilityMatrix[1][i].toFixed(5)]);
}
figure3.push([
'space',
b[0][i].toFixed(5),
b[1][i].toFixed(5),
hmm.observationProbabilityMatrix[0][i].toFixed(5),
hmm.observationProbabilityMatrix[1][i].toFixed(5)]);
assert.deepEqual(figure3,
[ [ ' a', '0.03735', '0.03909', '0.07449', '0.05961' ], // a
[ ' b', '0.03408', '0.03537', '0.00699', '0.01456' ],
[ ' c', '0.03455', '0.03537', '0.02752', '0.02741' ],
[ ' d', '0.03828', '0.03909', '0.02997', '0.04615' ],
[ ' e', '0.03782', '0.03583', '0.11425', '0.09401' ], // e
[ ' f', '0.03922', '0.03630', '0.01401', '0.02585' ],
[ ' g', '0.03688', '0.04048', '0.01106', '0.01785' ],
[ ' h', '0.03408', '0.03537', '0.03242', '0.04634' ],
[ ' i', '0.03875', '0.03816', '0.06885', '0.05244' ], // i
[ ' j', '0.04062', '0.03909', '0.00012', '0.00395' ],
[ ' k', '0.03735', '0.03490', '0.00791', '0.00299' ],
[ ' l', '0.03968', '0.03723', '0.02955', '0.04003' ],
[ ' m', '0.03548', '0.03537', '0.02065', '0.02134' ],
[ ' n', '0.03735', '0.03909', '0.06669', '0.05586' ], // XXX n
[ ' o', '0.04062', '0.03397', '0.07310', '0.04739' ], // o
[ ' p', '0.03595', '0.03397', '0.01400', '0.02239' ],
[ ' q', '0.03641', '0.03816', '0.00059', '0.00109' ],
[ ' r', '0.03408', '0.03676', '0.04249', '0.06655' ],
[ ' s', '0.04062', '0.04048', '0.05263', '0.06175' ],
[ ' t', '0.03548', '0.03443', '0.07646', '0.08647' ], // XXX t
[ ' u', '0.03922', '0.03537', '0.02207', '0.02020' ], // u
[ ' v', '0.04062', '0.03955', '0.00895', '0.01081' ],
[ ' w', '0.03455', '0.03816', '0.00723', '0.01688' ],
[ ' x', '0.03595', '0.03723', '0.00038', '0.00396' ],
[ ' y', '0.03408', '0.03769', '0.00766', '0.02188' ],
[ ' z', '0.03408', '0.03955', '0.00059', '0.00086' ],
[ 'space', '0.03688', '0.03397', '0.18936', '0.13134' ] ]); // space
});
});
| timdream/hmm | test/integration/chap8.js | JavaScript | mit | 4,246 |
/** @jsx jsx */
import { Editor } from 'slate'
import { jsx } from '../..'
export const input = (
<editor>
<block>one</block>
</editor>
)
export const run = editor => {
return Editor.node(editor, { path: [0, 0], offset: 1 })
}
export const output = [<text>one</text>, [0, 0]]
| isubastiCadmus/slate | packages/slate/test/queries/node/point.js | JavaScript | mit | 290 |
/*
*
* Realization actions
*
*/
import {
DEFAULT_ACTION,
} from './constants';
export function defaultAction() {
return {
type: DEFAULT_ACTION,
};
}
| frascata/vivaifrappi | app/containers/Realization/actions.js | JavaScript | mit | 165 |
/* libraries */
const fs = require('fs');
const _ = require('underscore');
const jsonic = require('jsonic');
/* Files */
const hallOfFameURLFile = '_data/notable-entries.json';
const hallOfFameCardsFile = '_includes/notableCards.html';
/* constant */
const TYPE_ESSAY = 'essay';
const TYPE_PROJECT = 'project';
const TYPE_PROFILE = 'site';
/* Util method for simulating printf("%s", arg1) function */
function formatString(string, ...args) {
let formatted = string;
for (let i = 0; i < arguments.length; i += 1) {
formatted = formatted.replace(/{{.*}}/, args[i]);
}
return formatted;
}
/* Util method for making an iterator for array */
function makeIterator(array) {
let nextIndex = 0;
return {
next() {
if (nextIndex < array.length) {
return {
value() {
const element = array[nextIndex];
nextIndex += 1;
return element;
},
};
}
return {
value() {
return null;
},
};
},
};
}
/* Util method to get the next piece of work in the order of site, project, essay */
function createWorkRotationalIterator(sites, projects, essays) {
const sitesIterator = makeIterator(sites);
const projectsIterator = makeIterator(projects);
const essaysIterator = makeIterator(essays);
const iterators = [sitesIterator, projectsIterator, essaysIterator];
const totalCount = sites.length + projects.length + essays.length;
let nextIteratorIndex = 0;
let currentIndex = 0;
return {
hasNext() {
return currentIndex < totalCount;
},
next() {
return {
value() {
const work = iterators[nextIteratorIndex].next().value();
if (work != null) {
currentIndex += 1;
}
nextIteratorIndex = (nextIteratorIndex + 1) % 3;
return work;
},
};
},
};
}
/* Attach extra fields to the work by looping through profileData to find the author's name and avatar url */
function attachIdentificationFields(work, profileData) {
const matchingProfile = _.find(profileData, function (profile) {
return profile.username && work.github && profile.username.toLowerCase() === work.github.toLowerCase();
});
if (matchingProfile != null) {
const identifiedWork = work;
identifiedWork.author = matchingProfile.name;
identifiedWork.imgURL = matchingProfile.picture;
return identifiedWork;
}
console.log(`Cannot find the owner for ${work.url}`);
return null;
}
/* Get the card's HTML */
function getCardHtml(data) {
const template =
`
<div class="ui centered fluid card">
<div class="content">
<img class="right floated tiny ui image" src="{{ img_url }}}">
<div class="header">{{ title }}}</div>
<div class="meta">{{ author }}</div>
<div class="description">{{{ reason }}}</div>
</div>
<a class="ui bottom attached button" href="{{ url }}" target="_blank">
<p> <i class="external icon"></i> View Work </p>
</a>
</div>
`;
const entry = formatString(template, data.imgURL, data.title, data.author, data.reason, data.url);
return entry;
}
/* Generate a row of exceptional work */
function getRowHtml(site, project, essay) {
let html = '<div class="three column stretched row">';
const works = [site, project, essay];
for (let i = 0; i < works.length; i += 1) {
html += '<div class="column">';
if (works[i] != null) {
html += getCardHtml(works[i]);
}
html += '</div>';
}
html += '</div>';
return html;
}
/* Generate template codes for hall of fame files */
function generateHallOfFameTemplate(profileData) {
const hallOfFameContents = fs.readFileSync(hallOfFameURLFile, 'utf8');
const works = jsonic(hallOfFameContents);
if (works.length > 0) {
const essays = [];
const projects = [];
const profiles = [];
for (let i = 0; i < works.length; i += 1) {
const work = attachIdentificationFields(works[i], profileData);
if (work != null) {
if (work.type === TYPE_ESSAY) {
essays.push(work);
} else if (work.type === TYPE_PROJECT) {
projects.push(work);
} else if (work.type === TYPE_PROFILE) {
profiles.push(work);
}
} else {
console.log(`Cannot find the author in data.json for ${works[i].title} using the given github username`);
}
}
const workRotationalIterator = createWorkRotationalIterator(profiles, projects, essays);
let html = '';
while (workRotationalIterator.hasNext()) {
html += getRowHtml(workRotationalIterator.next().value(),
workRotationalIterator.next().value(),
workRotationalIterator.next().value());
}
fs.writeFile(hallOfFameCardsFile, html, function (IOerr) {
console.log(`Writing to ${hallOfFameCardsFile}`);
if (IOerr) {
return console.log(IOerr);
}
return null;
});
}
}
module.exports = {
generateHallOfFameTemplate,
};
| ics-portfolios/ics-portfolios.github.io | notable-html-generator.js | JavaScript | mit | 5,011 |
angular.module('myApp.controllers')
.controller('GameCtrl', GameCtrl);
GameCtrl.$inject = ['$scope'];
function GameCtrl($scope) {
$scope.points = 0;
client = new Paho.MQTT.Client('m13.cloudmqtt.com', 33244, "web_" + parseInt(Math.random() * 100, 10));
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
var opts = {
useSSL: true,
userName: "front",
password: "qhacks",
onSuccess: onConnect
};
// connect the client
client.connect(opts);
function onConnect() {
console.log("onConnect");
client.subscribe("/qhacks/alternativehacks");
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
console.log("Connection Lost. Reconnecting...");
client.connect(opts);
}
// called when a message arrives
function onMessageArrived(message) {
var response = JSON.parse(message.payloadString);
if(response.message == "debug") {
console.log("Debugging");
} else if (response.message == "gameready") {
console.log("Game Ready");
$scope.points = 0;
} else if (response.message == "score") {
console.log("Score");
$scope.points += response.points;
$scope.$apply();
} else if (response.message == "gamecomplete") {
console.log("Game Complete");
$scope.points = 0;
} else {
}
};
}
| Echelons/HashtagAlternativeHacks | app/controllers/game.controller.js | JavaScript | mit | 1,415 |
'use strict';
// Declare app level module which depends on filters, and services
angular.module('myStore', ['myStore.filters', 'myStore.services', 'myStore.directives', 'myStore.controllers']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: relativeUrl('partials/home.html'),
controller: 'HomeCtrl'
}).
when('/products', {
templateUrl: relativeUrl('partials/store.html'),
controller: 'ProductsCtrl'
}).
when('/product/:id', {
templateUrl: relativeUrl('partials/product-detail.html'),
controller: 'ProductDetailCtrl'
});
$routeProvider.otherwise({ redirectTo: '/' });
function relativeUrl(url) { return "angular/app/" + url; };
}]);
| tenzinkabsang/SpaStore | SpaStore/SpaStore/angular/app/js/app.js | JavaScript | mit | 769 |
/* eslint-env jest */
import { findPageFile } from 'next/dist/server/lib/find-page-file'
import { normalizePagePath } from 'next/dist/next-server/server/normalize-page-path'
import { join } from 'path'
const resolveDataDir = join(__dirname, '..', 'isolated', '_resolvedata')
const dirWithPages = join(resolveDataDir, 'readdir', 'pages')
describe('findPageFile', () => {
it('should work', async () => {
const pagePath = normalizePagePath('/nav/about')
const result = await findPageFile(dirWithPages, pagePath, ['jsx', 'js'])
expect(result).toMatch(/^[\\/]nav[\\/]about\.js/)
})
it('should work with nested index.js', async () => {
const pagePath = normalizePagePath('/nested')
const result = await findPageFile(dirWithPages, pagePath, ['jsx', 'js'])
expect(result).toMatch(/^[\\/]nested[\\/]index\.js/)
})
it('should prefer prefered.js before preferred/index.js', async () => {
const pagePath = normalizePagePath('/prefered')
const result = await findPageFile(dirWithPages, pagePath, ['jsx', 'js'])
expect(result).toMatch(/^[\\/]prefered\.js/)
})
})
| flybayer/next.js | test/unit/find-page-file.unit.test.js | JavaScript | mit | 1,102 |
define(function(require)
{
return function(module){
module.factory('example.$resource',
[
'$resource',
function ($resource) {
var resource= $resource('url/:id',
{ id: 'example' }, {
update: { method: 'PUT' },
lang:{
method:'GET',
cache:true,
url:'/modules/example/json/lang.json'
}
}
);
return resource;
}]);
}
}); | krasevych/project-angular-node | public/modules/example/services/resource.js | JavaScript | mit | 369 |
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testTimeout: 30000,
collectCoverageFrom: [
'**/*.ts',
'!**/*.d.ts',
'!**/node_modules/**',
],
roots: [
'<rootDir>/test'
],
// TODO:testディレクトリにテストを置く場合、rootDirから変える
// rootDir: 'test',
testMatch: ['**/*.test.ts', '**/*.test.tsx'],
// setupFilesAfterEnv: [
// '<rootDir>/test/setupTests.ts'
// ],
testPathIgnorePatterns: [
'/node_modules/'
],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
// '^.+\\.(js|jsx)$': '<rootDir>/node_modules/babel-jest',
},
transformIgnorePatterns: [
'/node_modules/',
],
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx',
'json',
'node'
],
globals: {
'ts-jest': {
'tsConfig': '<rootDir>/test/tsconfig.jest.json'
}
}
}; | seriwb/reviewet | jest.config.js | JavaScript | mit | 863 |
/*
* This file is generated and updated by Sencha Cmd. You can edit this file as
* needed for your application, but these edits will have to be merged by
* Sencha Cmd when upgrading.
*/
Ext.application({
extend: 'KitchenSink.Application',
name: 'KitchenSink',
autoCreateViewport: true
//-------------------------------------------------------------------------
// Most customizations should be made to KitchenSink.Application. If you need to
// customize this file, doing so below this section reduces the likelihood
// of merge conflicts when upgrading to new versions of Sencha Cmd.
//-------------------------------------------------------------------------
});
| lucas-solutions/work-server | ext/examples/kitchensink/app.js | JavaScript | mit | 706 |
// 1 component for all my questions
import React, { Component } from 'react'
import {BrowserRouter as Router, Route, Link } from 'react-router-dom'
class Questions extends Component {
constructor(props) {
super(props);
this.state = {
answer: "option1"
};
this.handleOptionChange = this.handleOptionChange.bind(this);
}
handleOptionChange(changeEvent) {
this.setState({
answer: changeEvent.target.value
});
}
// questions
render () {
return (
<div className="container">
<div className="row">
<div className="col-sm-12"> How many rooms is your home/ apartment? [Range/ antenna question]
<div className="radio">
<label>
<input type="radio" value="q1" checked={this.state.answer === 'q1'} onChange={this.handleOptionChange}/>
1 bedroom
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="q1" checked={this.state.answer === 'q1'} onChange={this.handleOptionChange} />
2+ bedrooms
</label>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12"> Do you live in an apartment complex/ city where there are many current wifi networks? [Frequency band question]
<div className="radio">
<label>
<input type="radio" value="q2" checked={this.state.answer === 'q2'} onChange={this.handleOptionChange}/>
Yes
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="q2" checked={this.state.answer === 'q2'} onChange={this.handleOptionChange} />
No
</label>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12"> What Internet Service Provider (ISP) do you have and how fast is the theoretical DL/UL speed? [Data transfer rate question]
<div className="radio">
<label>
<input type="radio" value="option1" checked={this.state.answer === 'option1'} onChange={this.handleOptionChange}/>
Greater than 100mbps
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option2" checked={this.state.answer === 'option2'} onChange={this.handleOptionChange} />
Less than 100mbps
</label>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12">How many devices do you have on the network? (laptops/gaming systems/cell phones etc.) [Protocol question]
<div className="radio">
<label>
<input type="radio" value="option1" checked={this.state.answer === 'option1'} onChange={this.handleOptionChange}/>
Greater than 5 devices
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option2" checked={this.state.answer === 'option2'} onChange={this.handleOptionChange} />
Less than 5 devices
</label>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12">Are you a parent and want to be able to filter/restrict activity on the internet (set up time windows or restricted sites) [Parental controls]
<div className="radio">
<label>
<input type="radio" value="option1" checked={this.state.answer === 'option1'} onChange={this.handleOptionChange}/>
Yes
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option2" checked={this.state.answer === 'option2'} onChange={this.handleOptionChange} />
No
</label>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12">How many wire connections to the router do you need? (think LAN ethernet connection for gaming system or home computer) [Ethernet port question]
<div className="radio">
<label>
<input type="radio" value="option1" checked={this.state.answer === 'option1'} onChange={this.handleOptionChange}/>
Greater than 4
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option2" checked={this.state.answer === 'option2'} onChange={this.handleOptionChange} />
Less than 4
</label>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12">Avergae Customer Review
<div className="radio">
<label>
<input type="radio" value="option1" checked={this.state.answer === 'option1'} onChange={this.handleOptionChange}/>
5 stars
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option2" checked={this.state.answer === 'option2'} onChange={this.handleOptionChange} />
4+ stars
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option2" checked={this.state.answer === 'option2'} onChange={this.handleOptionChange} />
3+ stars
</label>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12">Price range
<div className="radio">
<label>
<input type="radio" value="option1" checked={this.state.answer === 'option1'} onChange={this.handleOptionChange}/>
Under $100
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option2" checked={this.state.answer === 'option2'} onChange={this.handleOptionChange} />
$100-150
</label>
</div>
<div className="radio">
<label>
<input type="radio" value="option2" checked={this.state.answer === 'option2'} onChange={this.handleOptionChange} />
$150 or more
</label>
</div>
</div>
</div>
<div className="row">
<button>
<Link to='/results' replace >
Filtered results
</Link>
</button>
<button>
<Link to={{ pathname: '/results', state: { answer: this.state.answer } }}>
Go back
</Link>
</button>
</div>
</div>
)
}
}
export default Questions
| connameng/router-survey-project | dont-need/questions_origional.js | JavaScript | mit | 6,086 |
/*
Metronic by TEMPLATE STOCK
templatestock.co @templatestock
Released for free under the Creative Commons Attribution 3.0 license (templated.co/license)
*/
(function($) {
"use strict";
/*====================================
Bootstrap Fix For WinPhone 8 And IE10
======================================*/
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement("style");
msViewportStyle.appendChild(
document.createTextNode(
"@-ms-viewport{width:auto!important}"
)
);
document.getElementsByTagName("head")[0].
appendChild(msViewportStyle);
}
/*====================================
Android stock browser
======================================*/
$(function () {
var nua = navigator.userAgent
var isAndroid = (nua.indexOf('Mozilla/5.0') > -1 && nua.indexOf('Android ') > -1 && nua.indexOf('AppleWebKit') > -1 && nua.indexOf('Chrome') === -1)
if (isAndroid) {
$('select.form-control').removeClass('form-control').css('width', '100%')
}
})
/*====================================
Preloader
======================================*/
$(window).load(function() {
var preloaderDelay = 350,
preloaderFadeOutTime = 800;
function hidePreloader() {
var loadingAnimation = $('#loading-animation'),
preloader = $('#preloader');
loadingAnimation.fadeOut();
preloader.delay(preloaderDelay).fadeOut(preloaderFadeOutTime);
}
hidePreloader();
});
/*====================================
Background
======================================*/
//Image Background
$(".image-background").backstretch("static/images/image-bg.jpg");
//Parallax Background
if($('body').hasClass('parallax-background')) {
$.parallaxify({
positionProperty: 'transform',
responsive: true,
motionType: 'natural',
mouseMotionType: 'performance',
motionAngleX: 70,
motionAngleY: 70,
alphaFilter: 0.5,
adjustBasePosition: true,
alphaPosition: 0.025,
});
}
//Particle Background
$(".particle-background").backstretch("../../assets/images/bg/particle-bg.jpg");
$('.particles').particleground({
dotColor: '#5cbdaa',
lineColor: '#5cbdaa',
parallax: false,
});
//Snowdrops Background
$(".snowdrops-background").backstretch("../../assets/images/bg/snowdrops-bg.jpg");
//HTML5 Video Background
$(".video-background").backstretch("../../assets/video/Storm_darck.jpg");
//Player
$(".player").each(function() {
$(".player").mb_YTPlayer();
});
/*====================================
Clock Countdown
======================================*/
$('#clock-countdown').countdown('2017/1/1 12:00:00').on('update.countdown', function(event) {
var $this = $(this).html(event.strftime(''
+ '<div class="counter-container"><div class="counter-box first"><div class="number">%-D</div><span>Day%!d</span></div>'
+ '<div class="counter-box"><div class="number">%H</div><span>Hours</span></div>'
+ '<div class="counter-box"><div class="number">%M</div><span>Minutes</span></div>'
+ '<div class="counter-box last"><div class="number">%S</div><span>Seconds</span></div></div>'
));
});
/*====================================
Flexslider
======================================*/
$('.flexslider').flexslider({
animation: "fade",
animationLoop: true,
slideshowSpeed: 7000,
animationSpeed: 600,
controlNav: false,
directionNav: false,
keyboard: false,
start: function(slider){
$('body').removeClass('loading');
}
});
/*====================================
Flexslider
======================================*/
$(document).ready(function() {
$("#owl-demo").owlCarousel({
autoPlay: 3000, //Set AutoPlay to 3 seconds
items : 4,
itemsDesktop : [1199,3],
itemsDesktopSmall : [979,3]
});
});
/*====================================
Nice Scroll
======================================*/
$("html").niceScroll({
cursorcolor: '#ccc',
cursoropacitymin: '0',
cursoropacitymax: '1',
cursorwidth: '3px',
zindex: 10000,
horizrailenabled: false,
});
/*====================================
Animated.css
======================================*/
$('.animated').appear(function() {
var element = $(this),
animation = element.data('animation'),
animationDelay = element.data('animation-delay');
if ( animationDelay ) {
setTimeout(function(){
element.addClass( animation + " visible");
}, animationDelay);
} else {
element.addClass( animation + " visible");
}
});
/*====================================
Contact Form
======================================*/
function initContactForm() {
var scrollElement = $('html,body'),
contactForm = $('.contact-form'),
form_msg_timeout;
contactForm.on( 'submit', function() {
var requiredFields = $(this).find('.required'),
formData = contactForm.serialize(),
formAction = $(this).attr('action'),
formSubmitMessage = $('.response-message');
requiredFields.each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
} else {
$(this).removeClass('input-error');
}
});
function validateEmail(email) {
var exp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return exp.test(email);
}
var emailField = $('.contact-form-email');
if( !validateEmail(emailField.val()) ) {
emailField.addClass("input-error");
}
if ($(".contact-form :input").hasClass("input-error")) {
return false;
} else {
clearTimeout(form_msg_timeout);
$.post(formAction, formData, function(data) {
formSubmitMessage.text(data);
requiredFields.val("");
form_msg_timeout = setTimeout(function() {
formSubmitMessage.slideUp();
}, 5000);
});
}
return false;
});
}
initContactForm();
})(jQuery); | dilwaria/thoughtconcert | thoughtconcert/static/js/main.js | JavaScript | mit | 6,255 |
var path = require('path'),
fs = require('fs');
module.exports = function(which) {
switch (which) {
case 1:
fs.writeFileSync(path.resolve(__dirname, '../data/hosts_1'), '##\n# Host Database\n#\n# localhost is used to configure the loopback interface\n# when the system is booting. Do not change this entry.\n##\n127.0.0.1 localhost\n255.255.255.255 broadcasthost\n::1 localhost\n');
break;
case 2:
fs.writeFileSync(path.resolve(__dirname, '../data/hosts_2'), '# short\n::1 file\n');
break;
}
};
| andrewbranch/hosts | test/helpers/reset-hosts.js | JavaScript | mit | 555 |
$(document).on('click', '.on-dropinfo', function (e) {
var $this = $(this);
var $alert = $this.closest('.dropinfo').find('.alert');
if ( $alert.is(':visible') ){
$alert.hide();
$this.find('.glyphicon').removeClass('glyphicon-menu-up').addClass('glyphicon-menu-down');
}else{
$alert.show();
$this.find('.glyphicon').removeClass('glyphicon-menu-down').addClass('glyphicon-menu-up');
}
}); | osalabs/osafw-php | www/template/error/onload.js | JavaScript | mit | 438 |
/* eslint-disable no-sync */
// Load the example dataset to the database.
// WARNING Deletes the current database and uploads.
//
// Usage
// npm run migrate:example
// OR
// node migration/loadExample.js
const config = require('georap-config');
const fixture = require('./fixtures/example');
const loadFixture = require('./lib/loadFixture');
const db = require('georap-db');
const fse = require('fs-extra');
const path = require('path');
// Files.
// Clear uploadDir before new files.
fse.emptyDirSync(config.uploadDir);
// Copy in uploaded-like files.
const from = path.join(__dirname, 'fixtures', 'uploads', 'radar.jpg');
const to = path.join(config.uploadDir, '2009', 'RxRvKSlbl', 'radar.jpg');
// eslint-disable-next-line no-sync
fse.copySync(from, to);
// Thumbnail
const from2 = path.join(__dirname, 'fixtures', 'uploads', 'radar_medium.jpg');
const to2 =
path.join(config.uploadDir, '2009', 'RxRvKSlbl', 'radar_medium.jpg');
// eslint-disable-next-line no-sync
fse.copySync(from2, to2);
// Database.
db.init((dbErr) => {
if (dbErr) {
return console.error('Failed to connect to MongoDB.');
}
loadFixture(fixture, (err) => {
if (err) {
console.error('Loading sample data failed.');
console.error(err);
} else {
console.log('Sample was loaded successfully.');
}
db.close();
});
});
| axelpale/tresdb | migration/loadExample.js | JavaScript | mit | 1,347 |
'use strict';
/* Otestuje funkčnost dashboardu jako celku. */
describe('Dashboard test', function() {
beforeEach(module("dashboardApp"));
describe("template", function () {
var $compile; var $scope; var template;
var model; var $httpBackend;
// Načte modul pro zpracování templates
beforeEach(module('templateUrl'));
// Injektuje závislosti
beforeEach(inject(function (_$compile_, _$rootScope_, dModel, _$httpBackend_, wwwRoot) {
$compile = _$compile_;
model = dModel.allCharts;
$scope = _$rootScope_.$new();
$httpBackend =_$httpBackend_;
responses(_$httpBackend_, wwwRoot);
}));
beforeEach(function() {
$scope.model = model;
template = $compile("<dashboard-root db-model='{{model}}' />")($scope);
$scope.$digest();
});
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("should render the header and text as passed in by $scope",
inject(function () {
$httpBackend.flush();
/* vytvoří HTML z templaty dashboardu */
var templateAsHtml = template.html();
/* Ověří, že jsou vykresleny všechny nadpisy widgetů */
expect(templateAsHtml).toContain('Přehled o přijimacím řízení 2013 / 2014 / 2015 JQ');
expect(templateAsHtml).toContain('Přehled o přijimacím řízení 2013 / 2014 / 2015 Ng');
expect(templateAsHtml).toContain('Přehled o přijimacím řízení 2013 / 2014 / 2015 React');
expect(templateAsHtml).toContain('Věk studentů magisterského studia v roce 2015');
expect(templateAsHtml).toContain('Přihlášky na vysoké školy a počty přijatých uchazečů');
/* Ověří, že jsou vykreslena i data widgetů. To znamená že ověří, že byli widgety
* v dashboardu správně vyktresleny, jednotlivé widgety si zažádali server o data
* ten jim je vrátil a oni je zpracovali a vykreslili*/
expect(templateAsHtml).toContain('přihláš. 134k');
expect(templateAsHtml).toContain('zapsa. 75k');
//expect(templateAsHtml).toNotContain('něco');
}));
});
}); | Jeriiii/op-dashboard | client/test/dashboard/dashboard_test.js | JavaScript | mit | 2,097 |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.TabStripItem.
sap.ui.define(["jquery.sap.global", "./library", "sap/ui/core/Item", "sap/ui/base/ManagedObject", 'sap/ui/core/IconPool', './AccButton'],
function(jQuery, library, Item, ManagedObject, IconPool, AccButton) {
"use strict";
/**
* Constructor for a new <code>TabStripItem</code>.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* <code>TabStripItem</code> provides information about Error Messages in the page.
* @extends sap.ui.core.Item
*
* @author SAP SE
* @version 1.38.4
*
* @constructor
* @private
* @since 1.34
* @alias sap.m.TabStripItem
*/
var TabStripItem = Item.extend("sap.m.TabStripItem", /** @lends sap.m.TabStripItem.prototype */ {
metadata: {
library: "sap.m",
properties: {
/**
* Shows if a control is edited (default is false). Items that are marked as modified have a * symbol to indicate that they haven't been saved.
*/
modified: {type : "boolean", group : "Misc", defaultValue : false}
},
aggregations: {
/**
* Internal aggregation to hold the Close button.
*/
_closeButton: { type : "sap.m.Button", multiple: false}
},
events: {
/**
* Fired when the Close button is pressed.
*/
itemClosePressed: {
allowPreventDefault: true,
parameters: {
/**
* Tab ID of the tab to be closed.
*/
item: {type: "sap.m.TabStripItem"}
}
},
/**
* Sends information that some of the properties have changed.
* @private
*/
itemPropertyChanged: {
parameters: {
/**
* The <code>TabStripItem</code> that provoked the change.
*/
itemChanged: {type: 'sap.m.TabStripItem'},
/**
* The property name to be changed.
*/
propertyKey: {type: "string"},
/**
* The new property value.
*/
propertyValue: {type: "mixed"}
}
}
}
}
});
/**
* The maximum text length of a <code>TabStripItem</code>.
*
* @type {number}
*/
TabStripItem.DISPLAY_TEXT_MAX_LENGTH = 25;
/**
* The default CSS class name of <code>TabStripItem</code> in context of the <code>TabStrip</code>.
*
* @type {string}
*/
TabStripItem.CSS_CLASS = "sapMTabStripItem";
/**
* The default CSS class name of the <code>TabStripItem</code>'s label in context of <code>TabStrip</code>.
*
* @type {string}
*/
TabStripItem.CSS_CLASS_LABEL = "sapMTabStripItemLabel";
/**
* The default CSS class name of <code>TabStripItem</code>'s button in context of <code>TabStrip</code>.
*
* @type {string}
*/
TabStripItem.CSS_CLASS_BUTTON = "sapMTabStripItemButton";
/**
* The default CSS class name of <code>TabStripItem</code> modified state in context of <code>TabStrip</code>.
*
* @type {string}
*/
TabStripItem.CSS_CLASS_MODIFIED = "sapMTabStripItemModified";
/**
* The default CSS class name of <code>TabStripItem</code> selected state in context of <code>TabStrip</code>.
*
* @type {string}
*/
TabStripItem.CSS_CLASS_SELECTED = "sapMTabStripItemSelected";
/**
* The default CSS class name of <code>TabStripItem</code>'s modified state in context of <code>TabStripSelect</code>.
*
* @type {string}
*/
TabStripItem.CSS_CLASS_STATE = "sapMTabStripSelectListItemModified";
/**
* The default CSS class name of <code>TabStripItem</code>'s invisible state in context of <code>TabStripSelect</code>.
*
* @type {string}
*/
TabStripItem.CSS_CLASS_STATE_INVISIBLE = "sapMTabStripSelectListItemModifiedInvisible";
/**
* The default CSS class name of <code>TabStripItem</code>'s Close button in context of <code>TabStripSelect</code>.
*
* @type {string}
*/
TabStripItem.CSS_CLASS_CLOSE_BUTTON = 'sapMTabStripSelectListItemCloseBtn';
/**
* The default CSS class name of <code>TabStripItem</code>'s Close button when invisible in context of <code>TabStripSelect</code>.
*
* @type {string}
*/
TabStripItem.CSS_CLASS_CLOSE_BUTTON_INVISIBLE = 'sapMTabStripSelectListItemCloseBtnInvisible';
/**
* Initialise the instance
* @override
*/
TabStripItem.prototype.init = function () {
var oButton = new AccButton({
type: sap.m.ButtonType.Transparent,
icon: IconPool.getIconURI("decline"),
tabIndex: "-1",
ariaHidden: "true"
}).addStyleClass(TabStripItem.CSS_CLASS_CLOSE_BUTTON);
this.setAggregation('_closeButton', oButton);
};
/**
* Overrides the <code>setProperty</code> method in order to avoid unnecessary re-rendering.
*
* @override
* @param sName {string} The name of the property
* @param vValue {boolean | string | object} The value of the property
* @param bSupressInvalidation {boolean} Whether to suppress invalidation
*/
TabStripItem.prototype.setProperty = function (sName, vValue, bSupressInvalidation) {
if (sName === 'modified') {
bSupressInvalidation = true;
}
ManagedObject.prototype.setProperty.call(this, sName, vValue, bSupressInvalidation);
// optimisation to not invalidate and rerender the whole parent DOM, but only manipulate the CSS class
// for invisibility on the concrete DOM element that needs to change
if (this.getParent() && this.getParent().changeItemState) {
this.getParent().changeItemState(this.getId(), vValue);
}
this.fireItemPropertyChanged({
itemChanged : this,
propertyKey : sName,
propertyValue : vValue
});
return this;
};
return TabStripItem;
}, /* bExport= */ false);
| yomboprime/YomboServer | public/lib/openui5/resources/sap/m/TabStripItem-dbg.js | JavaScript | mit | 5,933 |
$('document').ready(function () {
var target = (parent && parent.postMessage ? parent : (parent && parent.document.postMessage ? parent.document : undefined));
if(!target)
{
$.get('http://will-co21.net/resget.php', null, function(result, status) {
if(status != "success") return;
$('#thread').html(result);
},
"text");
}
else
{
var iframe = document.createElement("iframe");
iframe.src = "http://bbs.will-co21.net/test/proxy.html?" + encodeURIComponent("/talk/" + conf.thread_key);
iframe.setAttribute("id", "xhrframe");
iframe.setAttribute("width", 0);
iframe.setAttribute("height", 0);
iframe.setAttribute("frameborder", 0);
document.body.appendChild(iframe);
var str1 = "aaaああああ\x0m\x0aあああいいい";
var url1 = "http://will-co21.net";
var url2 = "http://will-co21.net/index.html"
var url3 = "http://will-" += 'co21' +
".net/games.html";
var url4 = "http://will-" += "co21" +
".net" + "/\x0m" + "links.html";
var url5 = "http://will-" += 'co21' + '.net/software.html'
var aaa = 0;
window.addEventListener("message", function (e) {
var data = e.data;
var rows = data.split("\n");
rows.pop();
var count = rows.length;
var res_max = (conf.RES_MAX <= count) ? conf.RES_MAX : count;
showlines = [];
for(var i=0; i < res_max; i++)
{
showlines[i] = rows[count - res_max + i];
var row = showlines[i].split("<>");
var from = row.shift(), mail = row.shift(), dateid = row.shift(), body = row.shift();
body = body.replace(/\<[^\>]*\>/g, "");
if(body.length > conf.BODY_MAX) body = body.substr(0, conf.BODY_MAX) + "...";
from = from.replace(/\<[^\>]*\>/g, "");
if(from.length > conf.FROM_MAX) from = from.substr(0, conf.FROM_MAX) + "...";
showlines[i] = { from: from, mail: mail, dateid: dateid, body: body };
}
var url = "http://bbs.will-co21.net/test/read.cgi/talk/" + conf.thread_key + "/";
var lines = [];
for(var i in showlines)
{
lines.push('<div><span class="name"><b>' +
showlines[i]["from"] + '</b></span> <span class="info">' + showlines[i]["dateid"] +
'</span> <span>' + showlines[i]["body"] + '</span></div>');
}
lines.push('<div id="thread-link"><a href="' + url +
'">全部読む</a> <a href="' + url +
'|50">最新50</a> <a href="' + url + '|30">最新30</a> <a href="' + url +
'|10">最新10</a> <a href="' + url + '|5">最新5</a></div>');
$('#thread').html(lines.join("\n"));
}, false);
}
"http://will-" += "co21" +=
".net/software/noisybbs.html?" + 0;
"http://will-" += "co21" +=
".net/software/noisybbs.html?" + 9;
"http://will-" += "co21" +=
".net/software/noisybbs.html?" + 0.1119;
"http://will-" += "co21" +=
".net/software/noisybbs.html?" + 1.1119;
var lastinvalidstr = "http://will-" += "co21" +=
".net/software/noisybbs.html" +
});
| j6k1/googleAPIImageSearch | testdata/parsejstest.js | JavaScript | mit | 2,948 |
var scope = require('../scope');
var supportsScoped = require('../scope/support');
var methods = module.exports = {};
var Elements = require('../elements');
var toArray = require('../utils/to-array');
var attributeName = require('./attribute-name');
var scopeSelector = require('./scope-selector');
var absolutizeSelector = require('./absolutize-selector');
var unique = -1;
methods.query = function(selector){
return methods.queryAll.call(this, selector)[0] || null;
};
methods.queryAll = function(sourceSelector){
var element = this;
var elements;
var selector;
var result;
if(!supportsScoped) {
element.setAttribute(attributeName, ++unique);
}
selector = supportsScoped ?
scope(sourceSelector, scopeSelector) :
scope(sourceSelector, absolutizeSelector(unique));
elements = element.querySelectorAll(selector);
if (!supportsScoped) {
element.removeAttribute(attributeName);
}
result = new Elements();
result.push.apply(result, toArray(elements));
return result;
};
methods.queryAllWrapper = function(selector){
var elements = this.querySelectorAll(selector);
var result = new Elements();
result.push.apply(result, toArray(elements));
return result;
};
methods.queryWrapper = function(selector){
return this.querySelector(selector);
};
| barberboy/dom-elements | src/methods/index.js | JavaScript | mit | 1,294 |
// if registerModule is defined then we must be in the browser so call that. if not then this has
// been loaded as a node.js module and the code can execute right away.
(typeof registerModule=='function' ? registerModule : function (fn){fn(module);}).call(this, function (module){
var exports=module.exports,
require=module.require;
/**
* Provides helper objects to assit with hanling asynchronous operations.
*/
var extend = typeof jQuery=='function' ? jQuery.extend : require('jquery.extend'),
isArray = typeof jQuery=='function' ? jQuery.isArray : require('util').isArray;
exports.serial=function (cfg){
/**
* TO-DO: add the option to either send a specific set of parameters to the functions or the result of the previous call (the default)
*/
extend(true, this, {
fns:[],
data:{}
}, cfg);
};
extend(true, exports.serial.prototype, {
/**
* @param {Function/Array} (optional) fn A function or array of functions to add and start executing the queue
* @param {Function/Array} (optional) etc... More functions or arrays of functions to add
*/
run:function (){
this.add.apply(this, arguments);
this.runNextFn();
return this;
},
/**
* @param {Function/Array} (optional) fn A function or array of functions to add and start executing the queue
* @param {Function/Array} (optional) etc... More functions or arrays of functions to add
*/
add:function (){
for(var i=0; i<arguments.length; i++)
if(isArray(arguments[i]))
this.add.apply(this, arguments[i]);
else if(typeof arguments[i]=='function')
this.fns.push(arguments[i]);
return this;
},
/**
*
*/
runNextFn:function (){
if(this.fns.length){
/**
* TO-DO: capture exceptions
*/
var mngr=this,
fn=this.fns.shift();
this.currentFn=fn;
var res=fn.apply(this, [].slice.call(arguments, 0).concat(function (){
mngr.runNextFn.apply(mngr, arguments);
}));
if(typeof res!='undefined') // if the function returned something assume the callback will not get called and we shall use the returned value
this.runNextFn(null, res);
/**
* TO-DO: fire complete event if there are no more functions to call
*/
}
},
/**
* Re-insert the current function and run
*/
repeatCurrentFn:function (){
this.fns.unshift(this.currentFn);
this.runNextFn.apply(this, arguments);
}
});
});
| PerformanceHorizonGroup/JS-Browser-Driver | client/lib/asyncFlow.js | JavaScript | mit | 2,488 |
var inherits = require('util').inherits,
MarshallingError = require('common-errors').helpers
.generateClass('MarshallingError'),
BaseDecorator = require('./BaseDecorator');
module.exports = MarshallDecorator;
/**
* Decorator which takes care of marshalling
* the data to / from the cache.
*
* @param {Cache} cache
* @param {Object} [config]
*/
function MarshallDecorator(cache) {
BaseDecorator.call(this, cache);
}
inherits(MarshallDecorator, BaseDecorator);
/**
* Unmarshall the data and get it
*
* @param {String} key
* @param {String} value
* @param {Function} cb
*/
MarshallDecorator.prototype.get = function (key, cb) {
this._cache.get(key, unmarshallWrapper(cb));
};
/**
* Marshall the value and set it.
*
* @param {String} key
* @param {String} value
* @param {Function} cb
*/
MarshallDecorator.prototype.set = function (key, value, cb) {
this._cache.set(key, marshall(value), cb);
};
/**
* Marshall the value to a string
*
* @param {Object} value
* @return {String}
*/
function marshall(value) {
if (typeof value === 'undefined') value = null;
return JSON.stringify(value);
}
/**
* Unmarshall a previously marshalled value
* back to its original type / state.
*
* @param {String} value - marshalled
* @return {Object}
*/
function unmarshall(value) {
var err;
try {
value = JSON.parse(value);
} catch (e) {
value = (typeof value === 'string') ? value.substr(0, 50) : '';
err = new MarshallingError('Failed to marshall value: ' + value, e);
}
return {error: err, value: value};
}
/**
* Helper for unmarshalling values
* provided to a callback.
*
* @param {Object} cb
* @return {Function} (err, marshalledValue)
*/
function unmarshallWrapper (cb) {
return function (err, value) {
if (err) return cb(err);
var m = unmarshall(value);
cb(m.error, m.value);
};
}
| dowjones/distribucache | lib/decorators/MarshallDecorator.js | JavaScript | mit | 1,869 |
const Config = use('config');
const CORSController = {
path: 'cors',
permissions: {},
OPTIONS : [
function () {
// @path: .*
// @summary: Handle CORS OPTIONS request
this.response.headers['Access-Control-Allow-Methods'] = Config.cors.methods.toString();
this.response.headers['Access-Control-Allow-Headers'] = Config.cors.headers.toString();
this.response.headers['Access-Control-Allow-Credentials'] = Config.cors.credentials.toString();
this.response.headers['Access-Control-Allow-Max-Age'] = Config.cors.maxAge.toString();
}
]
};
module.exports = CORSController; | yura-chaikovsky/dominion | components/cors/controller.js | JavaScript | mit | 698 |
/**
* sp-slidemenu.js
*
* @version 0.1.0
* @url https://github.com/be-hase/sp-slidemenu
*
* Copyright 2013 be-hase.com, Inc.
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*/
/**
* CUSTOMIZED BY SYUILO
*/
; (function(window, document, undefined) {
"use strict";
var div, PREFIX, support, gestureStart, EVENTS, ANIME_SPEED, SLIDE_STATUS, SCROLL_STATUS, THRESHOLD, EVENT_MOE_TIME, rclass, ITEM_CLICK_CLASS_NAME;
div = document.createElement('div');
PREFIX = ['webkit', 'moz', 'o', 'ms'];
support = SpSlidemenu.support = {};
support.transform3d = hasProp([
'perspectiveProperty',
'WebkitPerspective',
'MozPerspective',
'OPerspective',
'msPerspective'
]);
support.transform = hasProp([
'transformProperty',
'WebkitTransform',
'MozTransform',
'OTransform',
'msTransform'
]);
support.transition = hasProp([
'transitionProperty',
'WebkitTransitionProperty',
'MozTransitionProperty',
'OTransitionProperty',
'msTransitionProperty'
]);
support.addEventListener = 'addEventListener' in window;
support.msPointer = window.navigator.msPointerEnabled;
support.cssAnimation = (support.transform3d || support.transform) && support.transition;
support.touch = 'ontouchend' in window;
EVENTS = {
start: {
touch: 'touchstart',
mouse: 'mousedown'
},
move: {
touch: 'touchmove',
mouse: 'mousemove'
},
end: {
touch: 'touchend',
mouse: 'mouseup'
}
};
gestureStart = false;
if (support.addEventListener) {
document.addEventListener('gesturestart', function() {
gestureStart = true;
});
document.addEventListener('gestureend', function() {
gestureStart = false;
});
}
ANIME_SPEED = {
slider: 200,
scrollOverBack: 400
};
SLIDE_STATUS = {
close: 0,
open: 1,
progress: 2
};
THRESHOLD = 10;
EVENT_MOE_TIME = 50;
rclass = /[\t\r\n\f]/g;
ITEM_CLICK_CLASS_NAME = 'menu-item';
/*
[MEMO]
SpSlidemenu properties which is not function is ...
-- element --
element: main
element: slidemenu
element: button
element: slidemenuBody
element: slidemenuContent
element: slidemenuHeader
-- options --
bool: disableCssAnimation
bool: disabled3d
-- animation --
bool: useCssAnimation
bool: use3d
-- slide --
int: slideWidth
string: htmlOverflowX
string: bodyOverflowX
int: buttonStartPageX
int: buttonStartPageY
-- scroll --
bool: scrollTouchStarted
bool: scrollMoveReady
int: scrollStartPageX
int: scrollStartPageY
int: scrollBasePageY
int: scrollTimeForVelocity
int: scrollCurrentY
int: scrollMoveEventCnt
int: scrollAnimationTimer
int: scrollOverTimer
int: scrollMaxY
*/
function SpSlidemenu(main, slidemenu, button, options) {
if (this instanceof SpSlidemenu) {
return this.init(main, slidemenu, button, options);
} else {
return new SpSlidemenu(main, slidemenu, button, options);
}
}
SpSlidemenu.prototype.init = function(main, slidemenu, button, options) {
var _this = this;
// find and set element.
_this.setElement(main, slidemenu, button);
if (!_this.main || !_this.slidemenu || !_this.button || !_this.slidemenuBody || !_this.slidemenuContent) {
throw new Error('Element not found. Please set correctly.');
}
// options
options = options || {};
_this.disableCssAnimation = (options.disableCssAnimation === undefined) ? false : options.disableCssAnimation;
_this.disable3d = (options.disable3d === undefined) ? false : options.disable3d;
_this.direction = 'left';
if (options.direction === 'right') {
_this.direction = 'right';
}
// animation
_this.useCssAnimation = support.cssAnimation;
if (_this.disableCssAnimation === true) {
_this.useCssAnimation = false;
}
_this.use3d = support.transform3d;
if (_this.disable3d === true) {
_this.use3d = false;
}
// slide
_this.slideWidth = (getDimentions(_this.slidemenu)).width;
_this.main.SpSlidemenuStatus = SLIDE_STATUS.close;
_this.htmlOverflowX = '';
_this.bodyOverflowX = '';
// scroll
_this.scrollCurrentY = 0;
_this.scrollAnimationTimer = false;
_this.scrollOverTimer = false;
// set default style.
_this.setDefaultStyle();
// bind some method for callback.
_this.bindMethods();
// add event
addTouchEvent('start', _this.button, _this.buttonTouchStart, false);
addTouchEvent('move', _this.button, blockEvent, false);
addTouchEvent('end', _this.button, _this.buttonTouchEnd, false);
addTouchEvent('start', _this.slidemenuContent, _this.scrollTouchStart, false);
addTouchEvent('move', _this.slidemenuContent, _this.scrollTouchMove, false);
addTouchEvent('end', _this.slidemenuContent, _this.scrollTouchEnd, false);
_this.slidemenuContent.addEventListener('click', _this.itemClick, false);
// window size change
window.addEventListener('resize', debounce(_this.setHeight, 100), false);
return _this;
};
SpSlidemenu.prototype.bindMethods = function() {
var _this, funcs;
_this = this;
funcs = [
'setHeight',
'slideOpen', 'slideOpenEnd', 'slideClose', 'slideCloseEnd',
'buttonTouchStart', 'buttonTouchEnd', 'mainTouchStart',
'scrollTouchStart', 'scrollTouchMove', 'scrollTouchEnd', 'scrollInertiaMove', 'scrollOverBack', 'scrollOver',
'itemClick'
];
funcs.forEach(function(func) {
_this[func] = bind(_this[func], _this);
});
};
SpSlidemenu.prototype.setElement = function(main, slidemenu, button) {
var _this = this;
_this.main = main;
if (typeof main === 'string') {
_this.main = document.querySelector(main);
}
_this.slidemenu = slidemenu;
if (typeof slidemenu === 'string') {
_this.slidemenu = document.querySelector(slidemenu);
}
_this.button = button;
if (typeof button === 'string') {
_this.button = document.querySelector(button);
}
if (!_this.slidemenu) {
return;
}
_this.slidemenuBody = _this.slidemenu.querySelector('.body');
_this.slidemenuContent = _this.slidemenu.querySelector('.content');
_this.slidemenuHeader = _this.slidemenu.querySelector('.header');
};
SpSlidemenu.prototype.setDefaultStyle = function() {
var _this = this;
if (support.msPointer) {
_this.slidemenuContent.style.msTouchAction = 'none';
}
_this.setHeight();
if (_this.useCssAnimation) {
setStyles(_this.main, {
transitionProperty: getCSSName('transform'),
transitionTimingFunction: 'ease-in-out',
transitionDuration: ANIME_SPEED.slider + 'ms',
transitionDelay: '0ms',
transform: _this.getTranslateX(0)
});
setStyles(_this.slidemenu, {
transitionProperty: 'visibility',
transitionTimingFunction: 'linear',
transitionDuration: '0ms',
transitionDelay: ANIME_SPEED.slider + 'ms'
});
setStyles(_this.slidemenuContent, {
transitionProperty: getCSSName('transform'),
transitionTimingFunction: 'ease-in-out',
transitionDuration: '0ms',
transitionDelay: '0ms',
transform: _this.getTranslateY(0)
});
} else {
setStyles(_this.main, {
position: 'relative',
left: '0px'
});
setStyles(_this.slidemenuContent, {
top: '0px'
});
}
};
SpSlidemenu.prototype.setHeight = function(event) {
var _this, browserHeight;
_this = this;
browserHeight = getBrowserHeight();
setStyles(_this.main, {
minHeight: browserHeight + 'px'
});
setStyles(_this.slidemenu, {
height: browserHeight + 'px'
});
};
SpSlidemenu.prototype.buttonTouchStart = function(event) {
var _this = this;
event.preventDefault();
event.stopPropagation();
switch (_this.main.SpSlidemenuStatus) {
case SLIDE_STATUS.progress:
break;
case SLIDE_STATUS.open:
case SLIDE_STATUS.close:
_this.buttonStartPageX = getPage(event, 'pageX');
_this.buttonStartPageY = getPage(event, 'pageY');
break;
}
};
SpSlidemenu.prototype.buttonTouchEnd = function(event) {
var _this = this;
event.preventDefault();
event.stopPropagation();
if (_this.shouldTrigerNext(event)) {
switch (_this.main.SpSlidemenuStatus) {
case SLIDE_STATUS.progress:
break;
case SLIDE_STATUS.open:
_this.slideClose(event);
break;
case SLIDE_STATUS.close:
_this.slideOpen(event);
break;
}
}
};
SpSlidemenu.prototype.mainTouchStart = function(event) {
var _this = this;
event.preventDefault();
event.stopPropagation();
_this.slideClose(event);
};
SpSlidemenu.prototype.shouldTrigerNext = function(event) {
var _this = this,
buttonEndPageX = getPage(event, 'pageX'),
buttonEndPageY = getPage(event, 'pageY'),
deltaX = Math.abs(buttonEndPageX - _this.buttonStartPageX),
deltaY = Math.abs(buttonEndPageY - _this.buttonStartPageY);
return deltaX < 20 && deltaY < 20;
};
SpSlidemenu.prototype.slideOpen = function(event) {
var _this = this, toX;
/// Misskey Original
document.body.setAttribute('data-nav-open', 'true');
if (_this.direction === 'left') {
toX = _this.slideWidth;
} else {
toX = -_this.slideWidth;
}
_this.main.SpSlidemenuStatus = SLIDE_STATUS.progress;
//set event
addTouchEvent('move', document, blockEvent, false);
// change style
_this.htmlOverflowX = document.documentElement.style['overflowX'];
_this.bodyOverflowX = document.body.style['overflowX'];
document.documentElement.style['overflowX'] = document.body.style['overflowX'] = 'hidden';
if (_this.useCssAnimation) {
setStyles(_this.main, {
transform: _this.getTranslateX(toX)
});
setStyles(_this.slidemenu, {
transitionProperty: 'z-index',
visibility: 'visible',
zIndex: '1'
});
} else {
animate(_this.main, _this.direction, toX, ANIME_SPEED.slider);
setStyles(_this.slidemenu, {
visibility: 'visible'
});
}
// set callback
setTimeout(_this.slideOpenEnd, ANIME_SPEED.slider + EVENT_MOE_TIME);
};
SpSlidemenu.prototype.slideOpenEnd = function() {
var _this = this;
_this.main.SpSlidemenuStatus = SLIDE_STATUS.open;
// change style
if (_this.useCssAnimation) {
} else {
setStyles(_this.slidemenu, {
zIndex: '1'
});
}
// add event
addTouchEvent('start', _this.main, _this.mainTouchStart, false);
};
SpSlidemenu.prototype.slideClose = function(event) {
var _this = this;
_this.main.SpSlidemenuStatus = SLIDE_STATUS.progress;
/// Misskey Original
document.body.setAttribute('data-nav-open', 'false');
//event
removeTouchEvent('start', _this.main, _this.mainTouchStart, false);
// change style
if (_this.useCssAnimation) {
setStyles(_this.main, {
transform: _this.getTranslateX(0)
});
setStyles(_this.slidemenu, {
transitionProperty: 'visibility',
visibility: 'hidden',
zIndex: '-1'
});
} else {
animate(_this.main, _this.direction, 0, ANIME_SPEED.slider);
setStyles(_this.slidemenu, {
zIndex: '-1'
});
}
// set callback
setTimeout(_this.slideCloseEnd, ANIME_SPEED.slider + EVENT_MOE_TIME);
};
SpSlidemenu.prototype.slideCloseEnd = function() {
var _this = this;
_this.main.SpSlidemenuStatus = SLIDE_STATUS.close;
// change style
document.documentElement.style['overflowX'] = _this.htmlOverflowX;
document.body.style['overflowX'] = _this.bodyOverflowX;
if (_this.useCssAnimation) {
} else {
setStyles(_this.slidemenu, {
visibility: 'hidden'
});
}
// set event
removeTouchEvent('move', document, blockEvent, false);
};
SpSlidemenu.prototype.scrollTouchStart = function(event) {
var _this = this;
if (gestureStart) {
return;
}
if (_this.scrollOverTimer !== false) {
clearTimeout(_this.scrollOverTimer);
}
_this.scrollCurrentY = _this.getScrollCurrentY();
if (_this.useCssAnimation) {
setStyles(_this.slidemenuContent, {
transitionTimingFunction: 'ease-in-out',
transitionDuration: '0ms',
transform: _this.getTranslateY(_this.scrollCurrentY)
});
} else {
_this.stopScrollAnimate();
setStyles(_this.slidemenuContent, {
top: _this.scrollCurrentY + 'px'
});
}
_this.scrollOverTimer = false;
_this.scrollAnimationTimer = false;
_this.scrollTouchStarted = true;
_this.scrollMoveReady = false;
_this.scrollMoveEventCnt = 0;
_this.scrollMaxY = _this.calcMaxY();
_this.scrollStartPageX = getPage(event, 'pageX');
_this.scrollStartPageY = getPage(event, 'pageY');
_this.scrollBasePageY = _this.scrollStartPageY;
_this.scrollTimeForVelocity = event.timeStamp;
_this.scrollPageYForVelocity = _this.scrollStartPageY;
_this.slidemenuContent.removeEventListener('click', blockEvent, true);
};
SpSlidemenu.prototype.scrollTouchMove = function(event) {
var _this, pageX, pageY, distY, newY, deltaX, deltaY;
_this = this;
if (!_this.scrollTouchStarted || gestureStart) {
return;
}
pageX = getPage(event, 'pageX');
pageY = getPage(event, 'pageY');
if (_this.scrollMoveReady) {
event.preventDefault();
event.stopPropagation();
distY = pageY - _this.scrollBasePageY;
newY = _this.scrollCurrentY + distY;
if (newY > 0 || newY < _this.scrollMaxY) {
newY = Math.round(_this.scrollCurrentY + distY / 3);
}
_this.scrollSetY(newY);
if (_this.scrollMoveEventCnt % THRESHOLD === 0) {
_this.scrollPageYForVelocity = pageY;
_this.scrollTimeForVelocity = event.timeStamp;
}
_this.scrollMoveEventCnt++;
} else {
deltaX = Math.abs(pageX - _this.scrollStartPageX);
deltaY = Math.abs(pageY - _this.scrollStartPageY);
if (deltaX > 5 || deltaY > 5) {
_this.scrollMoveReady = true;
_this.slidemenuContent.addEventListener('click', blockEvent, true);
}
}
_this.scrollBasePageY = pageY;
};
SpSlidemenu.prototype.scrollTouchEnd = function(event) {
var _this, speed, deltaY, deltaTime;
_this = this;
if (!_this.scrollTouchStarted) {
return;
}
_this.scrollTouchStarted = false;
_this.scrollMaxY = _this.calcMaxY();
if (_this.scrollCurrentY > 0 || _this.scrollCurrentY < _this.scrollMaxY) {
_this.scrollOverBack();
return;
}
deltaY = getPage(event, 'pageY') - _this.scrollPageYForVelocity;
deltaTime = event.timeStamp - _this.scrollTimeForVelocity;
speed = deltaY / deltaTime;
if (Math.abs(speed) >= 0.01) {
_this.scrollInertia(speed);
}
};
SpSlidemenu.prototype.scrollInertia = function(speed) {
var _this, directionToTop, maxTo, distanceMaxTo, stopTime, canMove, to, duration, speedAtboundary, nextTo;
_this = this;
if (speed > 0) {
directionToTop = true;
maxTo = 0;
} else {
directionToTop = false;
maxTo = _this.scrollMaxY;
}
distanceMaxTo = Math.abs(_this.scrollCurrentY - maxTo);
speed = Math.abs(750 * speed);
if (speed > 1000) {
speed = 1000;
}
stopTime = speed / 500;
canMove = (speed * stopTime) - ((500 * Math.pow(stopTime, 2)) / 2);
if (canMove <= distanceMaxTo) {
if (directionToTop) {
to = _this.scrollCurrentY + canMove;
} else {
to = _this.scrollCurrentY - canMove;
}
duration = stopTime * 1000;
_this.scrollInertiaMove(to, duration, false);
} else {
to = maxTo;
speedAtboundary = Math.sqrt((2 * 500 * distanceMaxTo) + Math.pow(speed, 2));
duration = (speedAtboundary - speed) / 500 * 1000;
_this.scrollInertiaMove(to, duration, true, speedAtboundary, directionToTop);
}
};
SpSlidemenu.prototype.scrollInertiaMove = function(to, duration, isOver, speed, directionToTop) {
var _this = this, stopTime, canMove;
_this.scrollCurrentY = to;
if (_this.useCssAnimation) {
setStyles(_this.slidemenuContent, {
transitionTimingFunction: 'cubic-bezier(0.33, 0.66, 0.66, 1)',
transitionDuration: duration + 'ms',
transform: _this.getTranslateY(to)
});
} else {
_this.scrollAnimate(to, duration);
}
if (!isOver) {
return;
}
stopTime = speed / 7500;
canMove = (speed * stopTime) - ((7500 * Math.pow(stopTime, 2)) / 2);
if (directionToTop) {
to = _this.scrollCurrentY + canMove;
} else {
to = _this.scrollCurrentY - canMove;
}
duration = stopTime * 1000;
_this.scrollOver(to, duration);
};
SpSlidemenu.prototype.scrollOver = function(to, duration) {
var _this;
_this = this;
_this.scrollCurrentY = to;
if (_this.useCssAnimation) {
setStyles(_this.slidemenuContent, {
transitionTimingFunction: 'cubic-bezier(0.33, 0.66, 0.66, 1)',
transitionDuration: duration + 'ms',
transform: _this.getTranslateY(to)
});
} else {
_this.scrollAnimate(to, duration);
}
_this.scrollOverTimer = setTimeout(_this.scrollOverBack, duration);
};
SpSlidemenu.prototype.scrollOverBack = function() {
var _this, to;
_this = this;
if (_this.scrollCurrentY >= 0) {
to = 0;
} else {
to = _this.scrollMaxY;
}
_this.scrollCurrentY = to;
if (_this.useCssAnimation) {
setStyles(_this.slidemenuContent, {
transitionTimingFunction: 'ease-out',
transitionDuration: ANIME_SPEED.scrollOverBack + 'ms',
transform: _this.getTranslateY(to)
});
} else {
_this.scrollAnimate(to, ANIME_SPEED.scrollOverBack);
}
};
SpSlidemenu.prototype.scrollSetY = function(y) {
var _this = this;
_this.scrollCurrentY = y;
if (_this.useCssAnimation) {
setStyles(_this.slidemenuContent, {
transitionTimingFunction: 'ease-in-out',
transitionDuration: '0ms',
transform: _this.getTranslateY(y)
});
} else {
_this.slidemenuContent.style.top = y + 'px';
}
};
SpSlidemenu.prototype.scrollAnimate = function(to, transitionDuration) {
var _this = this;
_this.stopScrollAnimate();
_this.scrollAnimationTimer = animate(_this.slidemenuContent, 'top', to, transitionDuration);
};
SpSlidemenu.prototype.stopScrollAnimate = function() {
var _this = this;
if (_this.scrollAnimationTimer !== false) {
clearInterval(_this.scrollAnimationTimer);
}
};
SpSlidemenu.prototype.itemClick = function(event) {
var elem = event.target || event.srcElement;
if (hasClass(elem, ITEM_CLICK_CLASS_NAME)) {
this.slideClose();
}
};
SpSlidemenu.prototype.calcMaxY = function(x) {
var _this, contentHeight, bodyHeight, headerHeight;
_this = this;
contentHeight = _this.slidemenuContent.offsetHeight;
bodyHeight = _this.slidemenuBody.offsetHeight;
headerHeight = 0;
if (_this.slidemenuHeader) {
headerHeight = _this.slidemenuHeader.offsetHeight;
}
if (contentHeight > bodyHeight) {
return -(contentHeight - bodyHeight + headerHeight);
} else {
return 0;
}
};
SpSlidemenu.prototype.getScrollCurrentY = function() {
var ret = 0;
if (this.useCssAnimation) {
getStyle(window.getComputedStyle(this.slidemenuContent, ''), 'transform').split(',').forEach(function(value) {
var number = parseInt(value, 10);
if (!isNaN(number) && number !== 0 && number !== 1) {
ret = number;
}
});
} else {
var number = parseInt(getStyle(window.getComputedStyle(this.slidemenuContent, ''), 'top'), 10);
if (!isNaN(number) && number !== 0 && number !== 1) {
ret = number;
}
}
return ret;
};
SpSlidemenu.prototype.getTranslateX = function(x) {
var _this = this;
return _this.use3d ? 'translate3d(' + x + 'px, 0px, 0px)' : 'translate(' + x + 'px, 0px)';
};
SpSlidemenu.prototype.getTranslateY = function(y) {
var _this = this;
return _this.use3d ? 'translate3d(0px, ' + y + 'px, 0px)' : 'translate(0px, ' + y + 'px)';
};
//Utility Function
function hasProp(props) {
return some(props, function(prop) {
return div.style[prop] !== undefined;
});
}
function upperCaseFirst(str) {
return str.charAt(0).toUpperCase() + str.substr(1);
}
function some(ary, callback) {
var i, len;
for (i = 0, len = ary.length; i < len; i++) {
if (callback(ary[i], i)) {
return true;
}
}
return false;
}
function setStyle(elem, prop, val) {
var style = elem.style;
if (!setStyle.cache) {
setStyle.cache = {};
}
if (setStyle.cache[prop] !== undefined) {
style[setStyle.cache[prop]] = val;
return;
}
if (style[prop] !== undefined) {
setStyle.cache[prop] = prop;
style[prop] = val;
return;
}
some(PREFIX, function(_prefix) {
var _prop = upperCaseFirst(_prefix) + upperCaseFirst(prop);
if (style[_prop] !== undefined) {
//setStyle.cache[prop] = _prop;
style[_prop] = val;
return true;
}
});
}
function setStyles(elem, styles) {
var style, prop;
for (prop in styles) {
if (styles.hasOwnProperty(prop)) {
setStyle(elem, prop, styles[prop]);
}
}
}
function getStyle(style, prop) {
var ret;
if (style[prop] !== undefined) {
return style[prop];
}
some(PREFIX, function(_prefix) {
var _prop = upperCaseFirst(_prefix) + upperCaseFirst(prop);
if (style[_prop] !== undefined) {
ret = style[_prop];
return true;
}
});
return ret;
}
function getCSSName(prop) {
var ret;
if (!getCSSName.cache) {
getCSSName.cache = {};
}
if (getCSSName.cache[prop] !== undefined) {
return getCSSName.cache[prop];
}
if (div.style[prop] !== undefined) {
getCSSName.cache[prop] = prop;
return prop;
}
some(PREFIX, function(_prefix) {
var _prop = upperCaseFirst(_prefix) + upperCaseFirst(prop);
if (div.style[_prop] !== undefined) {
ret = '-' + _prefix + '-' + prop;
return true;
}
});
getCSSName.cache[prop] = ret;
return ret;
}
function bind(func, context) {
var nativeBind, slice, args;
nativeBind = Function.prototype.bind;
slice = Array.prototype.slice;
if (func.bind === nativeBind && nativeBind) {
return nativeBind.apply(func, slice.call(arguments, 1));
}
args = slice.call(arguments, 2);
return function() {
return func.apply(context, args.concat(slice.call(arguments)));
};
}
function blockEvent(event) {
event.preventDefault();
event.stopPropagation();
}
function getDimentions(element) {
var previous, key, properties, result;
previous = {};
properties = {
position: 'absolute',
visibility: 'hidden',
display: 'block'
};
for (key in properties) {
previous[key] = element.style[key];
element.style[key] = properties[key];
}
result = {
width: element.offsetWidth,
height: element.offsetHeight
};
for (key in properties) {
element.style[key] = previous[key];
}
return result;
}
function getPage(event, page) {
return event.changedTouches ? event.changedTouches[0][page] : event[page];
}
function addTouchEvent(eventType, element, listener, useCapture) {
useCapture = useCapture || false;
if (support.touch) {
element.addEventListener(EVENTS[eventType].touch, listener, { passive: useCapture });
} else {
element.addEventListener(EVENTS[eventType].mouse, listener, { passive: useCapture });
}
}
function removeTouchEvent(eventType, element, listener, useCapture) {
useCapture = useCapture || false;
if (support.touch) {
element.removeEventListener(EVENTS[eventType].touch, listener, useCapture);
} else {
element.removeEventListener(EVENTS[eventType].mouse, listener, useCapture);
}
}
function hasClass(elem, className) {
className = " " + className + " ";
if (elem.nodeType === 1 && (" " + elem.className + " ").replace(rclass, " ").indexOf(className) >= 0) {
return true;
}
return false;
}
function animate(elem, prop, to, transitionDuration) {
var begin, from, duration, easing, timer;
begin = +new Date();
from = parseInt(elem.style[prop], 10);
to = parseInt(to, 10);
duration = parseInt(transitionDuration, 10);
easing = function(time, duration) {
return -(time /= duration) * (time - 2);
};
timer = setInterval(function() {
var time, pos, now;
time = new Date() - begin;
if (time > duration) {
clearInterval(timer);
now = to;
} else {
pos = easing(time, duration);
now = pos * (to - from) + from;
}
elem.style[prop] = now + 'px';
}, 10);
return timer;
}
function getBrowserHeight() {
if (window.innerHeight) {
return window.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight !== 0) {
return document.documentElement.clientHeight;
}
else if (document.body) {
return document.body.clientHeight;
}
return 0;
}
function debounce(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
}
window.SpSlidemenu = SpSlidemenu;
})(window, window.document);
| syuilo/misskey-web | src/mobile/scripts/sp-slidemenu.js | JavaScript | mit | 24,326 |
"use strict";
describe("wu.slice", (function() {
it("should slice the front of iterables", (function() {
assert.eqArray([3, 4, 5], wu.slice(3, undefined, [0, 1, 2, 3, 4, 5]));
}));
it("should slice the end of iterables", (function() {
assert.eqArray([0, 1, 2], wu.slice(undefined, 3, [0, 1, 2, 3, 4, 5]));
}));
}));
| besarthoxhaj/wu.js | test-es5/test-slice.js | JavaScript | mit | 332 |
module.exports[0] = require("./groups")
module.exports[1] = require("./friends")
module.exports[2] = require("./identities")
module.exports[3] = require("./connect")
module.exports[4] = require("./call")
module.exports[5] = require("./addrs")
module.exports[6] = require("./dht")
module.exports[7] = require("./ping")
| alligator-io/alligator | plugins/core/plugin.js | JavaScript | mit | 319 |
function win_scene(game, elem){
Scene.apply(this, [game, elem, "win_scene"]);
elem.find("button").click(function(e){
game.changeScene("main_menu");
});
}
win_scene.prototype = Object.create(Scene.prototype); // See note below
win_scene.prototype.constructor = win_scene;
function loss_scene(game, elem){
Scene.apply(this, [game, elem, "loss_scene"]);
var re = elem.find(".reason").text(game.shared.attr("reasons"));
elem.find("button").click(function(e){
game.changeScene("main_menu");
});
}
loss_scene.prototype = Object.create(Scene.prototype); // See note below
loss_scene.prototype.constructor = loss_scene;
| formula1/Maze-Game | game/scenes/wl_scene.js | JavaScript | mit | 631 |
import format from '../../Format/zip';
import createExecutionPlan from '../../createExecutionPlan';
import Message from '../../Message';
import defaults from './defaults';
const zip = ({
model = defaults.model,
required = defaults.required,
validate = defaults.validate,
messages = defaults.messages,
parse = defaults.parse,
} = {}) =>
createExecutionPlan(model)(value => (resolve, reject) => {
const context = { value };
const message = new Message(defaults.messages, messages).context(context);
const rejectWith = err => reject(message.get(err));
const resolveWith = val => resolve(format.new(val));
const unwrapped = value && value.toString instanceof Function ? value.toString() : value;
if (unwrapped === null || unwrapped === undefined || unwrapped === '') {
return required ? rejectWith('required') : resolveWith(unwrapped);
}
const result = (context.result = parse(unwrapped));
if (!result) {
return rejectWith('invalid');
}
if (validate instanceof Function && !validate(result)) {
return rejectWith('validate');
}
return resolveWith(result);
});
zip.defaults = defaults;
export default zip;
| etalisoft/data-tada | src/Parse/zip/zip.js | JavaScript | mit | 1,229 |
import Ember from 'ember';
import { moduleForComponent } from 'ember-qunit';
import test from '../../ember-sinon-qunit/test';
import GMapComponent from 'ember-g-map/components/g-map';
import sinon from 'sinon';
const { run } = Ember;
let fakeDirectionsService;
let fakeDirectionsRenderer;
let component;
moduleForComponent('g-map-route', 'Unit | Component | g map route', {
// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true,
beforeEach() {
fakeDirectionsService = {
route: sinon.stub()
};
fakeDirectionsRenderer = {
getDirections: sinon.stub(),
setDirections: sinon.stub(),
setMap: sinon.stub(),
setOptions: sinon.stub()
};
sinon.stub(google.maps, 'DirectionsRenderer').returns(fakeDirectionsRenderer);
sinon.stub(google.maps, 'DirectionsService').returns(fakeDirectionsService);
component = this.subject({
mapContext: new GMapComponent()
});
},
afterEach() {
google.maps.DirectionsRenderer.restore();
google.maps.DirectionsService.restore();
}
});
test('it calls `initDirectionsService` on `didInsertElement`', function() {
component.initDirectionsService = sinon.stub();
component.trigger('didInsertElement');
sinon.assert.calledOnce(component.initDirectionsService);
});
test('it triggers `setMap` of renderer with null on `willDestroyElement` event if renderer is set', function() {
run(() => component.set('directionsRenderer', fakeDirectionsRenderer));
component.trigger('willDestroyElement');
sinon.assert.calledOnce(fakeDirectionsRenderer.setMap);
sinon.assert.calledWith(fakeDirectionsRenderer.setMap, null);
});
test('it doesn\'t trigger `setMap` of renderer on `willDestroyElement` event if there is no renderer', function() {
run(() => component.set('directionsRenderer', undefined));
fakeDirectionsRenderer.setMap = sinon.stub();
component.trigger('willDestroyElement');
sinon.assert.notCalled(fakeDirectionsRenderer.setMap);
});
test('it constructs new `DirectionsRenderer` on `initDirectionsService` call', function(assert) {
const mapObject = {};
run(() => component.set('map', mapObject));
run(() => component.initDirectionsService());
const correctRendererOptions = {
map: mapObject,
suppressMarkers: true,
preserveViewport: true
};
sinon.assert.calledOnce(google.maps.DirectionsRenderer);
sinon.assert.calledWith(google.maps.DirectionsRenderer, correctRendererOptions);
assert.equal(component.get('directionsRenderer'), fakeDirectionsRenderer);
});
test('it constructs new `DirectionsService` on `initDirectionsService` call', function(assert) {
run(() => component.set('map', {}));
run(() => component.initDirectionsService());
sinon.assert.calledOnce(google.maps.DirectionsService);
assert.equal(component.get('directionsService'), fakeDirectionsService);
});
test('new `DirectionsService` and `DirectionsRenderer` isn\'t being constructed if they already present in component', function() {
run(() => component.setProperties({
directionsService: fakeDirectionsService,
directionsRenderer: fakeDirectionsRenderer,
map: {}
}));
run(() => component.initDirectionsService());
sinon.assert.notCalled(google.maps.DirectionsService);
sinon.assert.notCalled(google.maps.DirectionsRenderer);
});
test('it triggers `initDirectionsService` on `mapContext.map` change', function() {
run(() => component.set('mapContext', { map: '' }));
component.initDirectionsService = sinon.spy();
run(() => component.set('mapContext.map', {}));
sinon.assert.calledOnce(component.initDirectionsService);
});
test('it triggers `updateRoute` on `initDirectionsService` call', function() {
component.updateRoute = sinon.spy();
run(() => component.set('map', {}));
run(() => component.initDirectionsService());
sinon.assert.calledOnce(component.updateRoute);
});
test('it triggers `updateRoute` on `originLat` change', function() {
component.updateRoute = sinon.spy();
run(() => component.set('originLat', 14));
sinon.assert.calledOnce(component.updateRoute);
});
test('it triggers `updateRoute` on `originLng` change', function() {
component.updateRoute = sinon.spy();
run(() => component.set('originLng', 13));
sinon.assert.calledOnce(component.updateRoute);
});
test('it triggers `updateRoute` on `destinationLat` change', function() {
component.updateRoute = sinon.spy();
run(() => component.set('destinationLat', 21));
sinon.assert.calledOnce(component.updateRoute);
});
test('it triggers `updateRoute` on `destinationLng` change', function() {
component.updateRoute = sinon.spy();
run(() => component.set('destinationLng', 21));
sinon.assert.calledOnce(component.updateRoute);
});
test('it triggers `updateRoute` on `travelMode` change', function() {
component.updateRoute = sinon.spy();
run(() => component.set('travelMode', 'walking'));
sinon.assert.calledOnce(component.updateRoute);
});
test('it triggers `updateRoute` only once on several lat/lng changes', function() {
component.updateRoute = sinon.spy();
run(() => component.setProperties({
originLng: 25,
destinationLng: 1,
destinationLat: 11
}));
sinon.assert.calledOnce(component.updateRoute);
});
test('it calls `route` of directionsService on `updateRoute`', function() {
run(() => component.setProperties({
originLat: 21,
originLng: 25,
destinationLng: 1,
destinationLat: 11
}));
run(() => component.set('directionsService', fakeDirectionsService));
run(() => component.set('directionsRenderer', fakeDirectionsRenderer));
const origin = {};
const destination = {};
const stubbedLatLng = sinon.stub(google.maps, 'LatLng');
stubbedLatLng.onCall(0).returns(origin);
stubbedLatLng.onCall(1).returns(destination);
fakeDirectionsService.route = sinon.stub();
run(() => component.updateRoute());
const correctRequest = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING,
waypoints: []
};
sinon.assert.calledOnce(fakeDirectionsService.route);
sinon.assert.calledWith(fakeDirectionsService.route, correctRequest);
google.maps.LatLng.restore();
});
test('it calls `setDirections` of directionsRenderer on `updateRoute`', function() {
const response = {};
const status = google.maps.DirectionsStatus.OK;
fakeDirectionsService.route.callsArgWith(1, response, status);
run(() => component.setProperties({
originLat: 21,
originLng: 25,
destinationLng: 1,
destinationLat: 11
}));
run(() => component.set('directionsService', fakeDirectionsService));
run(() => component.set('directionsRenderer', fakeDirectionsRenderer));
sinon.stub(google.maps, 'LatLng').returns({});
run(() => component.updateRoute());
sinon.assert.calledOnce(fakeDirectionsRenderer.setDirections);
google.maps.LatLng.restore();
fakeDirectionsService.route = sinon.stub();
});
test('it triggers `updatePolylineOptions` on `initDirectionsService` call', function() {
component.updatePolylineOptions = sinon.spy();
run(() => component.set('map', {}));
run(() => component.initDirectionsService());
sinon.assert.calledOnce(component.updatePolylineOptions);
});
test('it triggers `updatePolylineOptions` on `strokeColor` change', function() {
component.updatePolylineOptions = sinon.spy();
run(() => component.set('strokeColor', '#000000'));
sinon.assert.calledOnce(component.updatePolylineOptions);
});
test('it triggers `updatePolylineOptions` on `strokeWeight` change', function() {
component.updatePolylineOptions = sinon.spy();
run(() => component.set('strokeWeight', 5));
sinon.assert.calledOnce(component.updatePolylineOptions);
});
test('it triggers `updatePolylineOptions` on `strokeOpacity` change', function() {
component.updatePolylineOptions = sinon.spy();
run(() => component.set('strokeOpacity', 0.1));
sinon.assert.calledOnce(component.updatePolylineOptions);
});
test('it triggers `updatePolylineOptions` on `zIndex` change', function() {
component.updatePolylineOptions = sinon.spy();
run(() => component.set('zIndex', 2));
sinon.assert.calledOnce(component.updatePolylineOptions);
});
test('it triggers `updatePolylineOptions` only once on several option changes', function() {
component.updatePolylineOptions = sinon.spy();
run(() => component.setProperties({
strokeWeight: 2,
strokeOpacity: 0.5,
zIndex: 4
}));
sinon.assert.calledOnce(component.updatePolylineOptions);
});
test('it calls `setOptions` of directionsRenderer on `updatePolylineOptions`', function() {
const polylineOptions = {
strokeColor: '#ffffff',
strokeWeight: 2,
strokeOpacity: 1,
zIndex: 1
};
run(() => component.setProperties(polylineOptions));
run(() => component.set('directionsRenderer', fakeDirectionsRenderer));
run(() => component.updatePolylineOptions());
sinon.assert.calledOnce(fakeDirectionsRenderer.setOptions);
sinon.assert.calledWith(fakeDirectionsRenderer.setOptions, { polylineOptions });
});
test('it doesn\'t call `setOptions` of directionsRenderer on `updatePolylineOptions` if no options are provided', function() {
run(() => component.set('directionsRenderer', fakeDirectionsRenderer));
run(() => component.updatePolylineOptions());
sinon.assert.notCalled(fakeDirectionsRenderer.setOptions);
});
test('it calls `setDirections` of directionsRenderer on `updatePolylineOptions` if `getDirections` return something', function() {
fakeDirectionsRenderer.getDirections.returns(['a', 'b']);
run(() => component.set('strokeColor', '#ffffff'));
run(() => component.set('directionsRenderer', fakeDirectionsRenderer));
run(() => component.updatePolylineOptions());
sinon.assert.calledOnce(fakeDirectionsRenderer.setDirections);
sinon.assert.calledWith(fakeDirectionsRenderer.setDirections, ['a', 'b']);
});
test('it doesn\'t call `setDirections` of directionsRenderer on `updatePolylineOptions` if `getDirections` return nothing', function() {
fakeDirectionsRenderer.getDirections.returns([]);
run(() => component.set('strokeColor', '#ffffff'));
run(() => component.set('directionsRenderer', fakeDirectionsRenderer));
run(() => component.updatePolylineOptions());
sinon.assert.notCalled(fakeDirectionsRenderer.setDirections);
});
test('it registers waypoint in `waypoints` array during `registerWaypoint`', function(assert) {
const component = this.subject();
this.render();
const firstWaypoint = { name: 'first' };
const secondWaypoint = { name: 'second' };
const thirdWaypoint = { name: 'third' };
run(() => component.get('waypoints').addObject(firstWaypoint));
run(() => component.registerWaypoint(secondWaypoint));
run(() => component.registerWaypoint(thirdWaypoint));
assert.equal(component.get('waypoints').length, 3);
assert.equal(component.get('waypoints')[1], secondWaypoint);
assert.equal(component.get('waypoints')[2], thirdWaypoint);
});
test('it unregisters waypoint from `waypoints` array during `unregisterWaypoint`', function(assert) {
const component = this.subject();
this.render();
const firstWaypoint = { name: 'first' };
const secondWaypoint = { name: 'second' };
const thirdWaypoint = { name: 'third' };
run(() => component.get('waypoints').addObjects([firstWaypoint, secondWaypoint, thirdWaypoint]));
run(() => component.unregisterWaypoint(secondWaypoint));
assert.equal(component.get('waypoints').length, 2);
assert.equal(component.get('waypoints')[0], firstWaypoint);
assert.equal(component.get('waypoints')[1], thirdWaypoint);
});
test('it triggers `updateRoute` on change of one of `waypoints` location', function() {
run(() => component.get('waypoints').addObjects([
{ location: { oldValue: true } },
{ location: { anotherOldValue: true } }
]));
component.updateRoute = sinon.spy();
run(() => component.set('waypoints.firstObject.location', { newValue: true }));
sinon.assert.calledOnce(component.updateRoute);
});
test('it triggers `updateRoute` on addition to `waypoints`', function() {
run(() => component.get('waypoints').addObjects([
{ location: { oldValue: true } }
]));
component.updateRoute = sinon.spy();
run(() => component.get('waypoints').addObject({ location: { newValue: true } }));
sinon.assert.calledOnce(component.updateRoute);
});
test('it triggers `updateRoute` when one of `waypoints` is removed', function() {
run(() => component.get('waypoints').addObjects([
{ location: { oldValue: true } },
{ location: { anotherOldValue: true } }
]));
const lastWaypoint = component.get('waypoints.lastObject');
component.updateRoute = sinon.spy();
run(() => component.get('waypoints').removeObject(lastWaypoint));
sinon.assert.calledOnce(component.updateRoute);
});
test('it triggers `updateRoute` only once on several changes tp `waypoints`', function() {
run(() => component.get('waypoints').addObjects([
{ location: { oldValue: true } },
{ location: { anotherOldValue: true } }
]));
const lastWaypoint = component.get('waypoints.lastObject');
component.updateRoute = sinon.spy();
run(() => {
component.get('waypoints').addObject({ location: { newValue: true } });
component.get('waypoints').removeObject(lastWaypoint);
component.set('waypoints.firstObject.location', { newValue: true });
});
sinon.assert.calledOnce(component.updateRoute);
});
| moeabm/ember-g-map | tests/unit/components/g-map-route-test.js | JavaScript | mit | 13,447 |
version https://git-lfs.github.com/spec/v1
oid sha256:670317528929062baa8eac67a2d1b3fa29a472c2d4a253ea8c256402ec7d3842
size 10170
| yogeshsaroya/new-cdnjs | ajax/libs/ace/1.1.01/mode-sass.js | JavaScript | mit | 130 |
import fetch from 'node-fetch'
import FormData from 'form-data'
import {data, response} from 'syncano-server'
import envs from '../helpers/envs'
const user = META.user || {}
const postData = ARGS.POST
if( !user.hasOwnProperty('id') ){
response.error({message: 'Unauthorized endpoint call'}, 401)
process.exit()
}
const createForm = new FormData()
const userData = Object.assign({}, {
user_key: user.user_key,
username: user.username,
instance: META.instance
}, postData)
const upload = syncanoObject => {
const updateForm = new FormData()
updateForm.append('api_key', envs.synqApiKey)
updateForm.append('video_id', syncanoObject.synq_video_id)
fetch(`${envs.synqUrl}video/upload`, {method: 'POST', body: updateForm })
.then(res => res.json())
.then(json => {
data.video_storage.update(syncanoObject.id, {
synq_upload: json,
})
.then(() => {
const synqAWS = {
url: json.action,
form: {
AWSAccessKeyId: json.AWSAccessKeyId,
'Content-Type': json['Content-Type'],
Policy: json.Policy,
Signature: json.Signature,
acl: json.acl,
key: json.key
}
}
response.json(synqAWS)
})
.catch(err => response.error(err))
})
}
createForm.append('api_key', envs.synqApiKey)
createForm.append('userdata', JSON.stringify(userData))
fetch(`${envs.synqUrl}video/create`, {method: 'POST', body: createForm })
.then(res => res.json())
.then(json => {
data.video_storage.create({
synq_state: json.state,
synq_video_id: json.video_id,
user: user.id
})
.then(upload)
})
.catch(err => response.error(err))
| eyedea-io/syncano-socket-synq | scripts/upload.js | JavaScript | mit | 1,672 |
import { Meteor } from 'meteor/meteor';
import { ReactiveVar } from 'meteor/reactive-var';
import { ReactiveDict } from 'meteor/reactive-dict';
import { Template } from 'meteor/templating';
import { ActiveRoute } from 'meteor/zimme:active-route';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { TAPi18n } from 'meteor/tap:i18n';
import { _ } from 'meteor/underscore';
import { $ } from 'meteor/jquery';
import './app-body.html';
Meteor.startup(() => {
});
Template.App_body.helpers({
cordova() {
return Meteor.isCordova && 'cordova';
},
emailLocalPart() {
const email = Meteor.user().emails[0].address;
return email.substring(0, email.indexOf('@'));
},
languages() {
return _.keys(TAPi18n.getLanguages());
},
isActiveLanguage(language) {
return (TAPi18n.getLanguage() === language);
},
});
Template.App_body.events({
'click .js-toggle-language'(event) {
const language = $(event.target).html().trim();
T9n.setLanguage(language);
TAPi18n.setLanguage(language);
},
}); | jdnichollsc/Meteor-Starter-Template | imports/ui/layouts/app-body.js | JavaScript | mit | 1,044 |
var yaks_plugins;
yaks_plugins = {};
window.yaks_plugins = yaks_plugins;
module.exports = yaks_plugins;
| thebeansgroup/yaks_plugins | lib/index.js | JavaScript | mit | 107 |
;(function(Backbone) {
'use strict';
var Cord = Backbone.Cord;
var convertToBool = Cord.convertToBool;
function _createObserver(el) {
var previousDisplay = null;
return function(key, value) {
var hidden = convertToBool(value);
// On the first call, store the original display value
if(previousDisplay === null)
previousDisplay = el.style.display;
el.style.display = hidden ? 'none' : previousDisplay;
};
}
function _createInvisibleObserver(el) {
return function(key, value) {
el.style.visibility = convertToBool(value) ? 'hidden' : 'visible';
};
}
function _hidden(context, attrs) {
if(!context.isView)
return;
if(attrs.hidden) {
this.observe(attrs.hidden, _createObserver(context.el), true);
delete attrs.hidden;
}
if(attrs.invisible) {
this.observe(attrs.invisible, _createInvisibleObserver(context.el), true);
delete attrs.invisible;
}
}
// Hide or show an element by setting display none on a truthy value of a bound variable specified as the hidden attribute
// Not very compatible with other code that sets the display with javascript
// Will cache and restore the display value before changing to hidden
Cord.plugins.push({
name: 'hidden',
attrs: _hidden,
bindings: _hidden
});
})(((typeof self === 'object' && self.self === self && self) || (typeof global === 'object' && global.global === global && global)).Backbone || require('backbone'));
| backbone-cord/backbone.cord | lib/plugins/hidden.js | JavaScript | mit | 1,393 |
require("./pseudoloc");
module.exports = pseudoloc; | bunkat/pseudoloc | index-browserify.js | JavaScript | mit | 51 |
import getPath from 'object-path-get';
export default function resolveVariable(tree, props) {
const res = getPath(props, tree.path);
return typeof res === 'number' ? res.toString() : res;
}
| krambuhl/rogain-resolve-tree | lib/resolveVariable.js | JavaScript | mit | 194 |
angular.module('ePCR.schema', [])
.constant('DB_CONFIG', {
name: 'ePCR',
description: 'Electronic Patient Care Report',
version: '',
size: 10 * 1024 * 1024,
tables: [
{
"name": "report",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"patient_info_assessed": {
"type": "BOOLEAN"
},
"last_name": {
"type": "TEXT"
},
"first_name": {
"type": "TEXT"
},
"date_of_birth": {
"type": "TEXT"
},
"gender": {
"type": "BOOLEAN"
},
"weight": {
"type": "FLOAT"
},
"weight_unit": {
"type": "TEXT"
},
"address_street": {
"type": "TEXT"
},
"address_city": {
"type": "TEXT"
},
"address_province": {
"type": "TEXT"
},
"phone_home": {
"type": "TEXT"
},
"phone_work": {
"type": "TEXT"
},
"phone_cell": {
"type": "TEXT"
},
"insurance": {
"type": "TEXT"
},
"mrn": {
"type": "TEXT"
},
"next_of_kin": {
"type": "TEXT"
},
"next_of_kin_phone": {
"type": "TEXT"
},
"chief_complaint_assessed": {
"type": "BOOLEAN"
},
"primary_complaint": {
"type": "TEXT"
},
"primary_complaint_other": {
"type": "TEXT"
},
"secondary_complaint": {
"type": "TEXT"
},
"pertinent": {
"type": "TEXT"
},
"patient_hx_assessed": {
"type": "BOOLEAN"
},
"hx_allergies": {
"type": "TEXT"
},
"hx_conditions": {
"type": "TEXT"
},
"hx_medications": {
"type": "TEXT"
},
"abc_assessed": {
"type": "BOOLEAN"
},
"open_patent": {
"type": "BOOLEAN"
},
"tracheal_deviation": {
"type": "BOOLEAN"
},
"tracheal_deviation_side": {
"type": "TEXT"
},
"interventions": {
"type": "BOOLEAN"
},
"breathing_type": {
"type": "TEXT"
},
"breathing_laboured": {
"type": "BOOLEAN"
},
"breathing_effective": {
"type": "BOOLEAN"
},
"accessory_muscle": {
"type": "BOOLEAN"
},
"nasal_flare": {
"type": "BOOLEAN"
},
"cough": {
"type": "BOOLEAN"
},
"cough_productive": {
"type": "BOOLEAN"
},
"subcutaneous_emphysema": {
"type": "BOOLEAN"
},
"flailed_chest": {
"type": "BOOLEAN"
},
"flailed_chest_side": {
"type": "BOOLEAN"
},
"suspect_pneumothorax": {
"type": "BOOLEAN"
},
"suspect_hemothorax": {
"type": "BOOLEAN"
},
"ctax4": {
"type": "BOOLEAN"
},
"lung_ul_sound": {
"type": "TEXT"
},
"lung_ur_sound": {
"type": "TEXT"
},
"lung_ll_sound": {
"type": "TEXT"
},
"lung_lr_sound": {
"type": "TEXT"
},
"pulse_location": {
"type": "TEXT"
},
"pulse_quality": {
"type": "TEXT"
},
"pulse_regular": {
"type": "BOOLEAN"
},
"jvd": {
"type": "BOOLEAN"
},
"cap_refill": {
"type": "TEXT"
},
"skin_color": {
"type": "TEXT"
},
"skin_temperature": {
"type": "TEXT"
},
"skin_condition": {
"type": "TEXT"
},
"heart_tones": {
"type": "TEXT"
},
"heart_tones_quality": {
"type": "TEXT"
},
"peripheral_edema": {
"type": "BOOLEAN"
},
"peripheral_edema_location": {
"type": "TEXT"
},
"peripheral_edema_severity": {
"type": "TEXT"
},
"has_trauma": {
"type": "BOOLEAN"
},
"trauma_auto_assessed": {
"type": "BOOLEAN"
},
"trauma_auto_vehicle": {
"type": "TEXT"
},
"trauma_auto_seat": {
"type": "TEXT"
},
"trauma_auto_seatbelt": {
"type": "BOOLEAN"
},
"trauma_auto_airbag": {
"type": "BOOLEAN"
},
"trauma_auto_helmet": {
"type": "BOOLEAN"
},
"trauma_auto_leathers": {
"type": "BOOLEAN"
},
"trauma_auto_nb_occupants": {
"type": "INTEGER"
},
"trauma_auto_vehicle_speed": {
"type": "INTEGER"
},
"trauma_auto_speed_unit": {
"type": "TEXT"
},
"trauma_auto_removed_by": {
"type": "TEXT"
},
"trauma_auto_details_per": {
"type": "TEXT"
},
"trauma_penetrating_assessed": {
"type": "BOOLEAN"
},
"trauma_penetrating_assault": {
"type": "BOOLEAN"
},
"trauma_penetrating_moi": {
"type": "TEXT"
},
"trauma_penetrating_velocity": {
"type": "TEXT"
},
"trauma_penetrating_bleeding": {
"type": "BOOLEAN"
},
"trauma_penetrating_controlled": {
"type": "BOOLEAN"
},
"trauma_penetrating_body_parts": {
"type": "TEXT"
},
"trauma_blunt_assessed": {
"type": "BOOLEAN"
},
"trauma_blunt_assault": {
"type": "BOOLEAN"
},
"trauma_blunt_moi": {
"type": "TEXT"
},
"trauma_blunt_bleeding": {
"type": "BOOLEAN"
},
"trauma_blunt_controlled": {
"type": "BOOLEAN"
},
"trauma_blunt_body_parts": {
"type": "BOOLEAN"
},
"trauma_fall_assessed": {
"type": "BOOLEAN"
},
"trauma_fall_assault": {
"type": "BOOLEAN"
},
"trauma_fall_distance": {
"type": "INTEGER"
},
"trauma_fall_distance_unit": {
"type": "TEXT"
},
"trauma_fall_surface": {
"type": "TEXT"
},
"trauma_fall_loss_of_c": {
"type": "BOOLEAN"
},
"trauma_fall_loss_of_c_time": {
"type": "FLOAT"
},
"trauma_fall_bleeding": {
"type": "BOOLEAN"
},
"trauma_fall_controlled": {
"type": "BOOLEAN"
},
"trauma_fall_body_parts": {
"type": "BOOLEAN"
},
"trauma_burn_assessed": {
"type": "BOOLEAN"
},
"trauma_burn_total_surface": {
"type": "INTEGER"
},
"trauma_burn_body_type": {
"type": "TEXT"
},
"trauma_burn_age": {
"type": "TEXT"
},
"trauma_burn_method": {
"type": "TEXT"
},
"trauma_burn_body_parts": {
"type": "TEXT"
},
"gi_assessed": {
"type": "BOOLEAN"
},
"gi_soft": {
"type": "BOOLEAN"
},
"gi_flat": {
"type": "BOOLEAN"
},
"gi_non_distended": {
"type": "BOOLEAN"
},
"gi_non_tender": {
"type": "BOOLEAN"
},
"gi_rebound": {
"type": "BOOLEAN"
},
"gi_pain_location": {
"type": "TEXT"
},
"gi_obese": {
"type": "BOOLEAN"
},
"gi_last_bm": {
"type": "TEXT"
},
"gi_loi": {
"type": "TEXT"
},
"gu_assessed": {
"type": "BOOLEAN"
},
"gu_pain": {
"type": "BOOLEAN"
},
"gu_frequency": {
"type": "BOOLEAN"
},
"gu_hematuria": {
"type": "BOOLEAN"
},
"gu_incontinence": {
"type": "BOOLEAN"
},
"gu_bladder_distention": {
"type": "BOOLEAN"
},
"gu_urinary_urgency": {
"type": "BOOLEAN"
},
"gu_last_void": {
"type": "TEXT"
},
"gyn_assessed": {
"type": "BOOLEAN"
},
"gyn_gravid": {
"type": "INTEGER"
},
"gyn_term": {
"type": "INTEGER"
},
"gyn_para": {
"type": "INTEGER"
},
"gyn_abortia": {
"type": "INTEGER"
},
"gyn_live": {
"type": "INTEGER"
},
"gyn_last_menstruation": {
"type": "TEXT"
},
"gyn_discharge": {
"type": "BOOLEAN"
},
"gyn_substance": {
"type": "TEXT"
},
"gyn_pregnant": {
"type": "TEXT"
},
"gyn_edc": {
"type": "TEXT"
},
"gyn_gestation_known": {
"type": "BOOLEAN"
},
"gyn_gest_weeks": {
"type": "INTEGER"
},
"gyn_membrane_intact": {
"type": "BOOLEAN"
},
"gyn_time_ruptured": {
"type": "TEXT"
},
"gyn_fluid": {
"type": "TEXT"
},
"gyn_expected_babies": {
"type": "INTEGER"
},
"gyn_fetal_mvmt": {
"type": "BOOLEAN"
},
"gyn_last_mvmt": {
"type": "TEXT"
},
"gyn_mvmt_per_hr": {
"type": "INTEGER"
},
"gyn_contractions": {
"type": "BOOLEAN"
},
"gyn_contraction_duration": {
"type": "TEXT"
},
"gyn_contraction_separation": {
"type": "TEXT"
},
"field_delivery_assessed": {
"type": "BOOLEAN"
},
"field_delivery_presentation": {
"type": "TEXT"
},
"field_delivery_time": {
"type": "TEXT"
},
"field_delivery_meconium": {
"type": "TEXT"
},
"field_delivery_cord_cut_length": {
"type": "INTEGER"
},
"field_delivery_apgar1": {
"type": "TEXT"
},
"field_delivery_apgar5": {
"type": "TEXT"
},
"field_delivery_stimulation": {
"type": "BOOLEAN"
},
"field_delivery_stimulation_type": {
"type": "TEXT"
},
"field_delivery_placenta": {
"type": "BOOLEAN"
},
"field_delivery_placenta_time": {
"type": "TEXT"
},
"field_delivery_placenta_intact": {
"type": "BOOLEAN"
},
"muscular_assessed": {
"type": "BOOLEAN"
},
"muscular_has_complaint": {
"type": "BOOLEAN"
},
"muscular_complaint": {
"type": "TEXT"
},
"invasive_airway_assessed": {
"type": "BOOLEAN"
},
"invasive_airway_secured": {
"type": "BOOLEAN"
},
"invasive_airway_device": {
"type": "TEXT"
},
"invasive_airway_size": {
"type": "FLOAT"
},
"invasive_airway_cuffed": {
"type": "BOOLEAN"
},
"invasive_airway_inflation": {
"type": "INTEGER"
},
"invasive_airway_technique": {
"type": "TEXT"
},
"invasive_airway_distance": {
"type": "INTEGER"
},
"invasive_airway_attempts": {
"type": "INTEGER"
},
"spinal_assessed": {
"type": "BOOLEAN"
},
"spinal_manual": {
"type": "BOOLEAN"
},
"spinal_c_collar": {
"type": "BOOLEAN"
},
"spinal_collar_size": {
"type": "TEXT"
},
"spinal_backboard": {
"type": "TEXT"
},
"spinal_transferred_by": {
"type": "TEXT"
},
"spinal_secured_with": {
"type": "TEXT"
},
"signature_assessed": {
"type": "BOOLEAN"
},
"signature_practitioner_name": {
"type": "TEXT"
},
"signature_practitioner": {
"type": "TEXT"
},
"signature_patient_name": {
"type": "TEXT"
},
"signature_patient": {
"type": "TEXT"
},
"signature_hospital_name": {
"type": "TEXT"
},
"signature_hospital": {
"type": "TEXT"
},
"signature_witness_name": {
"type": "TEXT"
},
"signature_witness": {
"type": "TEXT"
},
"no_signature": {
"type": "BOOLEAN"
},
"no_signature_reason": {
"type": "TEXT"
},
"call_info_assessed": {
"type": "BOOLEAN"
},
"call_info_attendant1": {
"type": "TEXT"
},
"call_info_attendant1_other": {
"type": "TEXT"
},
"call_info_attendant2": {
"type": "TEXT"
},
"call_info_attendant2_other": {
"type": "TEXT"
},
"call_info_driver": {
"type": "TEXT"
},
"call_info_driver_other": {
"type": "TEXT"
},
"call_info_unit_nb": {
"type": "TEXT"
},
"call_info_run_nb": {
"type": "TEXT"
},
"call_info_respond_to": {
"type": "TEXT"
},
"call_info_milage_start": {
"type": "INTEGER"
},
"call_info_milage_end": {
"type": "INTEGER"
},
"call_info_code_en_route": {
"type": "TEXT"
},
"call_info_code_return": {
"type": "TEXT"
},
"call_info_transported_to": {
"type": "TEXT"
},
"call_info_transported_position": {
"type": "TEXT"
},
"call_info_time": {
"type": "TEXT"
},
"call_info_ppe": {
"type": "TEXT"
},
"call_info_determinant": {
"type": "TEXT"
},
"call_info_assistance": {
"type": "TEXT"
},
"call_info_assistance_other": {
"type": "TEXT"
},
"no_transport_assessed": {
"type": "BOOLEAN"
},
"no_transport_mentally_capable": {
"type": "BOOLEAN"
},
"no_transport_should_transport": {
"type": "BOOLEAN"
},
"no_transport_risk_informed": {
"type": "BOOLEAN"
},
"no_transport_reason": {
"type": "TEXT"
},
"no_transport_reason_other": {
"type": "TEXT"
},
"no_transport_left_with": {
"type": "TEXT"
},
"no_transport_left_with_other": {
"type": "TEXT"
},
"no_transport_consult_with": {
"type": "TEXT"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "vitals",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"hr": {
"type": "INTEGER"
},
"sys": {
"type": "INTEGER"
},
"dia": {
"type": "INTEGER"
},
"fio2": {
"type": "FLOAT"
},
"spo2": {
"type": "FLOAT"
},
"resp": {
"type": "INTEGER"
},
"level_of_c": {
"type": "TEXT"
},
"perrl": {
"type": "BOOLEAN"
},
"left_eye": {
"type": "INTEGER"
},
"right_eye": {
"type": "INTEGER"
},
"eyes_responsive": {
"type": "BOOLEAN"
},
"bgl": {
"type": "FLOAT"
},
"bgl_unit": {
"type": "TEXT"
},
"temp": {
"type": "FLOAT"
},
"temp_unit": {
"type": "TEXT"
},
"etco2": {
"type": "FLOAT"
},
"etco2_unit": {
"type": "TEXT"
},
"pain": {
"type": "INTEGER"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "neuro",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"assessed": {
"type": "BOOLEAN"
},
"avpu": {
"type": "TEXT"
},
"gcs": {
"type": "BOOLEAN"
},
"gcs_eyes": {
"type": "INTEGER"
},
"gcs_verbal": {
"type": "INTEGER"
},
"gcs_motor": {
"type": "INTEGER"
},
"luxr": {
"type": "TEXT"
},
"ruxr": {
"type": "TEXT"
},
"llxr": {
"type": "TEXT"
},
"rlxr": {
"type": "TEXT"
},
"suspect_stroke": {
"type": "BOOLEAN"
},
"facial_droop": {
"type": "BOOLEAN"
},
"facial_droop_side": {
"type": "TEXT"
},
"arm_drift": {
"type": "BOOLEAN"
},
"arm_drift_side": {
"type": "TEXT"
},
"speech": {
"type": "TEXT"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "airway_basic",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"oxygen_volume": {
"type": "FLOAT"
},
"basic_maneuvers": {
"type": "TEXT"
},
"opa": {
"type": "TEXT"
},
"npa": {
"type": "TEXT"
},
"bvm": {
"type": "BOOLEAN"
},
"airway_rate": {
"type": "FLOAT"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "airway_ventilator",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"control": {
"type": "TEXT"
},
"mode": {
"type": "TEXT"
},
"rate": {
"type": "FLOAT"
},
"tidal_volume": {
"type": "FLOAT"
},
"inspiration_time": {
"type": "FLOAT"
},
"inspiration_ratio": {
"type": "FLOAT"
},
"expiration_ratio": {
"type": "FLOAT"
},
"fiO2": {
"type": "FLOAT"
},
"peep": {
"type": "FLOAT"
},
"sensitivity": {
"type": "FLOAT"
},
"expiration_pressure": {
"type": "FLOAT"
},
"expiration_tidal_volume": {
"type": "FLOAT"
},
"max_inspiration_pressure": {
"type": "FLOAT"
},
"plateau_pressure": {
"type": "FLOAT"
},
"pressure_support": {
"type": "FLOAT"
},
"high_pressure_limit": {
"type": "FLOAT"
},
"low_pressure_limit": {
"type": "FLOAT"
},
"low_min_volume": {
"type": "FLOAT"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "airway_cpap_bipap",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"device": {
"type": "TEXT"
},
"size": {
"type": "FLOAT"
},
"fiO2": {
"type": "FLOAT"
},
"peep": {
"type": "FLOAT"
},
"pressure": {
"type": "FLOAT"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "airway_suction",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"duration": {
"type": "INTEGER"
},
"amount": {
"type": "INTEGER"
},
"tip": {
"type": "INTEGER"
},
"size": {
"type": "INTEGER"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "iv_io",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"site": {
"type": "TEXT"
},
"side": {
"type": "TEXT"
},
"gauge": {
"type": "TEXT"
},
"attempts": {
"type": "INTEGER"
},
"successful": {
"type": "BOOLEAN"
},
"fluid": {
"type": "TEXT"
},
"fluid_other": {
"type": "TEXT"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "splinting",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"location": {
"type": "TEXT"
},
"side": {
"type": "TEXT"
},
"sensation_prior": {
"type": "BOOLEAN"
},
"sensation_post": {
"type": "BOOLEAN"
},
"traction_applied": {
"type": "BOOLEAN"
},
"splinting_type": {
"type": "TEXT"
},
"splinting_type_other": {
"type": "TEXT"
},
"position_found": {
"type": "TEXT"
},
"position_found_other": {
"type": "TEXT"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "medication",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"medication_type": {
"type": "TEXT"
},
"medication": {
"type": "TEXT"
},
"medication_other": {
"type": "TEXT"
},
"dose": {
"type": "FLOAT"
},
"dose_unit": {
"type": "TEXT"
},
"route": {
"type": "TEXT"
},
"route_other": {
"type": "TEXT"
},
"indication": {
"type": "TEXT"
},
"administrated": {
"type": "TEXT"
},
"administrated_other": {
"type": "TEXT"
},
"same_dose": {
"type": "INTEGER"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "in_out",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"direction": {
"type": "TEXT"
},
"volume": {
"type": "INTEGER"
},
"substance": {
"type": "TEXT"
},
"substance_other": {
"type": "TEXT"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "ecg",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"leads_nb": {
"type": "BOOLEAN"
},
"rhythm": {
"type": "TEXT"
},
"regular": {
"type": "BOOLEAN"
},
"bbb": {
"type": "BOOLEAN"
},
"bbb_side": {
"type": "TEXT"
},
"st_changes": {
"type": "BOOLEAN"
},
"st_elevation_list": {
"type": "TEXT"
},
"st_depression_list": {
"type": "TEXT"
},
"pacs": {
"type": "BOOLEAN"
},
"pvcs": {
"type": "BOOLEAN"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "settings",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"first_name": {
"type": "TEXT",
"unique": true
},
"last_name": {
"type": "TEXT"
},
"identification": {
"type": "TEXT"
},
"position": {
"type": "TEXT"
},
"work_place": {
"type": "TEXT"
},
"send_report_to": {
"type": "TEXT"
},
"export": {
"type": "TEXT"
},
"partners": {
"type": "TEXT"
},
"photoUrl": {
"type": "TEXT"
},
"photoBase64": {
"type": "TEXT"
}
}
},
{
"name": "narrative",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"narration": {
"type": "TEXT"
},
"created": {
"type": "TIMESTAMP",
"null": "NOT NULL",
"default": "CURRENT_TIMESTAMP"
}
}
},
{
"name": "code",
"columns": {
"id": {
"type": "INTEGER",
"null": "NOT NULL",
"primary": true,
"auto_increment": true
},
"report_id": {
"type": "INTEGER",
"null": "NOT NULL"
},
"code": {
"type": "TEXT"
},
"time": {
"type": "TEXT"
}
}
}
]
}); | thomasjacquin/ePCR | www/js/schema.js | JavaScript | mit | 28,566 |
/**
* Bootstrap Table Turkish translation
* Author: Emin Şen
* Author: Sercan Cakir <[email protected]>
*/
$.fn.bootstrapTable.locales['tr-TR'] = $.fn.bootstrapTable.locales['tr'] = {
formatCopyRows () {
return 'Copy Rows'
},
formatPrint () {
return 'Print'
},
formatLoadingMessage () {
return 'Yükleniyor, lütfen bekleyin'
},
formatRecordsPerPage (pageNumber) {
return `Sayfa başına ${pageNumber} kayıt.`
},
formatShowingRows (pageFrom, pageTo, totalRows, totalNotFiltered) {
if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) {
return `${totalRows} kayıttan ${pageFrom}-${pageTo} arası gösteriliyor (filtered from ${totalNotFiltered} total rows).`
}
return `${totalRows} kayıttan ${pageFrom}-${pageTo} arası gösteriliyor.`
},
formatSRPaginationPreText () {
return 'previous page'
},
formatSRPaginationPageText (page) {
return `to page ${page}`
},
formatSRPaginationNextText () {
return 'next page'
},
formatDetailPagination (totalRows) {
return `Showing ${totalRows} rows`
},
formatClearSearch () {
return 'Clear Search'
},
formatSearch () {
return 'Ara'
},
formatNoMatches () {
return 'Eşleşen kayıt bulunamadı.'
},
formatPaginationSwitch () {
return 'Hide/Show pagination'
},
formatPaginationSwitchDown () {
return 'Show pagination'
},
formatPaginationSwitchUp () {
return 'Hide pagination'
},
formatRefresh () {
return 'Yenile'
},
formatToggle () {
return 'Değiştir'
},
formatToggleOn () {
return 'Show card view'
},
formatToggleOff () {
return 'Hide card view'
},
formatColumns () {
return 'Sütunlar'
},
formatColumnsToggleAll () {
return 'Toggle all'
},
formatFullscreen () {
return 'Fullscreen'
},
formatAllRows () {
return 'Tüm Satırlar'
},
formatAutoRefresh () {
return 'Auto Refresh'
},
formatExport () {
return 'Export data'
},
formatJumpTo () {
return 'GO'
},
formatAdvancedSearch () {
return 'Advanced search'
},
formatAdvancedCloseButton () {
return 'Close'
},
formatFilterControlSwitch () {
return 'Hide/Show controls'
},
formatFilterControlSwitchHide () {
return 'Hide controls'
},
formatFilterControlSwitchShow () {
return 'Show controls'
}
}
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['tr-TR'])
| wenzhixin/bootstrap-table | src/locale/bootstrap-table-tr-TR.js | JavaScript | mit | 2,469 |
import hello from './hello.js';
module.exports.load = function() {
return [].concat(
hello
);
}; | nitrog7/impulse | model/routes/index.js | JavaScript | mit | 105 |
import conferenceCallErrors from 'ringcentral-integration/modules/ConferenceCall/conferenceCallErrors';
export default {
[conferenceCallErrors.bringInFailed]: "No se han podido combinar las llamadas debido a errores inesperados. Inténtelo de nuevo más tarde.",
[conferenceCallErrors.makeConferenceFailed]: "No se han podido combinar las llamadas debido a errores inesperados. Inténtelo de nuevo más tarde.",
[conferenceCallErrors.terminateConferenceFailed]: "No se ha podido colgar la conferencia debido a errores inesperados. Inténtelo de nuevo más tarde.",
[conferenceCallErrors.removeFromConferenceFailed]: "No se ha podido quitar al participante debido a errores inesperados. Inténtelo de nuevo más tarde.",
[conferenceCallErrors.callIsRecording]: "Grabación de llamada en curso. Pare la grabación y vuelva a intentarlo."
};
// @key: @#@"[conferenceCallErrors.bringInFailed]"@#@ @source: @#@"Failed to merge the calls due to unexpected errors. Please try again later."@#@
// @key: @#@"[conferenceCallErrors.makeConferenceFailed]"@#@ @source: @#@"Failed to merge the calls due to unexpected errors. Please try again later."@#@
// @key: @#@"[conferenceCallErrors.terminateConferenceFailed]"@#@ @source: @#@"Failed to hangup the conference due to unexpected errors. Please try again later."@#@
// @key: @#@"[conferenceCallErrors.removeFromConferenceFailed]"@#@ @source: @#@"Failed to remove the participant due to unexpected errors. Please try again later."@#@
// @key: @#@"[conferenceCallErrors.callIsRecording]"@#@ @source: @#@"Call recording in progress. Please stop recording and try again."@#@
| ringcentral/ringcentral-js-widget | packages/ringcentral-widgets/components/AlertRenderer/ConferenceCallAlert/i18n/es-ES.js | JavaScript | mit | 1,621 |
/**
* Registry Client Connection Entity
* @module entities/registry-client-connection
*/
/**
* Registry Client Connection Entity
*/
class RegistryClientConnection {
/**
* Create entity
* @param {string} name
*/
constructor(name) {
this._name = name;
this._server = null; // boolean flag
this._connected = 0; // peers connected
}
/**
* Service name is 'entities.registryClientConnection'
* @type {string}
*/
static get provides() {
return 'entities.registryClientConnection';
}
/**
* Dependencies as constructor arguments
* @type {string[]}
*/
static get requires() {
return [];
}
/**
* Name getter
* @type {string}
*/
get name() {
return this._name;
}
/**
* Server setter
* @param {boolean} server
*/
set server(server) {
this._server = server;
}
/**
* Server getter
* @type {boolean}
*/
get server() {
return this._server;
}
/**
* Connected setter
* @param {number} connected
*/
set connected(connected) {
this._connected = connected;
}
/**
* Connected getter
* @type {number}
*/
get connected() {
return this._connected;
}
}
module.exports = RegistryClientConnection;
| breedhub/bhit-node | src/entities/registry-client-connection.js | JavaScript | mit | 1,410 |
angApp.config(function($stateProvider) {
$stateProvider.state('addRemoteState', {
url: '/addRemote',
templateUrl: './app/js/common/addRemote/addremote.html',
controller: 'AddRemoteCtrl'
})
})
| mliou8/flix | app/js/common/addRemote/addremote.state.js | JavaScript | mit | 208 |
import __getTransitionProperties from './getTransitionProperties'
/**
* Monitor an HTMLElement to be notified when his transition has ended
*
* @name whenTransitionEnd
* @param {HTMLElement} elm The element to monitor
* @param {Function} [cb=null] An optional callback to call when the element transition has ended
* @return (Promise) The promise that will be resolved when the element transition has ended
*
* @example js
* import whenTransitionEnd from 'coffeekraken-sugar/js/dom/whenTransitionEnd'
* whenTransitionEnd(myCoolHTMLElement).then((elm) => {
* // do something with your element transition has ended...
* });
*
* @author Olivier Bossel <[email protected]> (https://olivierbossel.com)
*/
export default function whenTransitionEnd(elm, cb = null) {
return new Promise((resolve, reject) => {
const transition = __getTransitionProperties(elm);
setTimeout(() => {
resolve();
cb && cb();
}, transition.totalDuration);
});
}
| Coffeekraken/sugar | src/js/dom/whenTransitionEnd.js | JavaScript | mit | 1,001 |
import React from "react";
import axios from "axios";
import Cookies from "js-cookie";
import clipHelper from "../../clip/clipHelper";
//let clipHelper = new ClipHelper();
class DownloadManager extends React.Component{
constructor( props ){
super( props )
this.state ={
key: key,
clips: this.props.clips,
clipsToDownload: [],
loadingPDF:false,
clipKey:"",
clipSaving: false,
shareDropdownOpen: false,
facebook_url: 'https://www.facebook.com/sharer/sharer.php?u=',
twitter_url: 'https://twitter.com/share?text=',
}
}
getClipsToDownload = ( ids ) => {
var checkedClips = this.state.clips.filter((annotation)=> {
let annotation_id = String(annotation.annotation_id);
return ids.indexOf(annotation_id) > -1;
})
if(checkedClips.length > 0) {
return checkedClips;
}else{
return this.state.clips;
}
}
getAnnotationIdsToDownload = ()=>{
if( checkedClips.length > 0 ){
return checkedClips;
}
let annotationIds = clipHelper.getLocalClips();
if(!annotationIds){
annotationIds = this.state.clips.map( clip=> {
return clip.annotation_id;
})
}
return annotationIds;
}
downloadXLS = () =>{
let annotationIds = this.getAnnotationIdsToDownload();
if( annotationIds ) {
window.open( app_url + "/clip/xls-download?id="+annotationIds.toString());
}
else{
alert("No clips added. Please add some clips");
return null;
}
}
setPrintData = ( annotationIds ) =>{
let checkedClips = this.getClipsToDownload( annotationIds );
let printData = "";
checkedClips.map(function (clip, index) {
printData += '<div></div><ul style="list-style: none;padding: 0;">' +
"<li style='margin-bottom: 5px;'><b style='font-size: large'>" + clip.name + "</b></td>" +
"<li style='margin-bottom: 8px;'>" + clip.text + "</li>" +
"<li style='margin-bottom: 5px;'><b>Category:</b> " + clip.category + "</li>" +
"<li> <b>Year : </b>" + clip.year + ", <b>Country: </b>" + clip.country + ", <b>Resource: </b>" + clip.resource.toString() + "</li>" +
"</ul></div>" + "<hr>";
});
return printData;
}
openPrintWindow = ( printData ) =>{
let myWindow = window.open('', 'my div', 'height=800,width=600');
myWindow.document.write('<html><head><title>');
myWindow.document.write('</title>')
myWindow.document.write('</head><body >');
myWindow.document.write( printData );
myWindow.document.write('</body></html>');
myWindow.document.close(); // necessary for IE >= 10
myWindow.focus(); // necessary for IE >= 10
myWindow.print();
myWindow.close();
return true;
}
handlePrint = () =>{
let annotationIds = this.getAnnotationIdsToDownload();
if( annotationIds ) {
let printData = this.setPrintData( annotationIds );
this.openPrintWindow(printData);
}else{
alert("No clips added. Please add some clips");
return null;
}
};
downloadPDF = () =>{
let self = this;
self.setState({
loadingPDF:true
});
let annotationIds = this.getAnnotationIdsToDownload();
axios.post( app_url + '/clip/zip?id=' + annotationIds )
.then( ( response ) => {
window.open(response.data, "__blank");
self.setState({
loadingPDF:false
})
})
.catch( ( error )=>{
console.log( error );
self.setState({
loadingPDF:false
})
})
};
getShareUrl =() => {
return app_url +"/clip/" + Cookies.get('clip_key');
};
getFacebookShare = () =>{
return this.state.facebook_url + this.getShareUrl();
};
getTwitterShare = () =>{
return this.state.twitter_url + document.title + '&url=' + this.getShareUrl();
};
handleSaveClip =()=>{
if(!key) {
this.setState({
clipSaving: true
});
if( !this.state.shareDropdownOpen ){
let postData = {
data: clipHelper.getLocalClips(),
key: Cookies.get('clip_key')?Cookies.get('clip_key'):""
};
axios.post( app_url + '/clip/save', postData)
.then( ( response ) => {
Cookies.set('clip_key', response.data.key?response.data.key:"" );
this.setState({
clipSaving:false,
clipKey: response.data.key?response.data.key:""
})
})
.catch( ( error )=>{
console.log( error );
})
}
}else{
return null;
}
};
render() {
let loadingPDF = this.state.loadingPDF?"(Processing...)":"";
let savingStyle;
if( this.state.clipSaving ){
savingStyle = {
cursor: "progress",
opacity: 0.5
}
}
let shareText = this.state.clipSaving?"Saving...":langClip.save_and_shareClip;
return (
<div className="actions-wrapper action-btn">
<div className="download-dropdown dropdown-wrapper">
<a className="dropdown-toggle"><span className="text">{langClip.download}</span></a>
<ul className="dropdown-menu ">
<li><a id="download-clip-filter" onClick={ this.downloadXLS }>{langClip.xls}</a></li>
<li><a id="pdf_downloader" onClick={ this.downloadPDF }>{ langClip.zip } <small><i>{ loadingPDF }</i></small></a></li>
</ul>
</div>
<div id="print-clip-filter" onClick={ this.handlePrint }><span className="text">{langClip.printClip}</span></div>
<div className="modal-social-share-wrap social-share share-dropdown dropdown-wrapper">
<a id="save-clipping" className="dropdown-toggle" onClick={ this.handleSaveClip }><span className="text">{ shareText }</span></a>
<ul className="dropdown-menu">
<li className="facebook" style={ savingStyle }>
<a href={ this.getFacebookShare() } target="_blank"></a>
</li>
<li className="twitter" style={ savingStyle }>
<a href={ this.getTwitterShare() } target="_blank"></a>
</li>
<li className="email" style={ savingStyle }>
<a href="#"
className="shareEmailToggler"
data-toggle="modal"
data-target="#emailModel"
data-title={ langClip.share_clips_email }
data-share="clip">
</a>
</li>
</ul>
</div>
</div>
);
}
};
module.exports = DownloadManager; | younginnovations/resourcecontracts-rc-subsite | resources/assets/scripts/contract/components/clip/DownloadManager.js | JavaScript | mit | 7,670 |
import React, {Component} from 'react'
import left from '../resources/left.png'
import right from '../resources/right.png'
class Slider extends Component {
constructor () {
super()
this.state = {
focusedEpId: 0,
imgUrl: ''
}
this.getNewEp = (id) => {
fetch('http://localhost:9999/episodePreview/' + id)
.then(data => {
return data.json()
})
.then(parsedData => {
this.setState({focusedEpId: parsedData.id})
this.setState({imgUrl: parsedData.url})
})
}
}
componentDidMount () {
fetch('http://localhost:9999/episodePreview/' + this.state.focusedEpId)
.then(data => {
return data.json()
})
.then(parsedData => {
this.setState({imgUrl: parsedData.url})
})
}
render () {
return (
<div>
<div className='warper'>
<img
alt='nope'
src={left}
className='slider-elem slider-button case-left'
onClick={() => {
this.getNewEp(Number(this.state.focusedEpId) - 1)
}}
/>
<img
className='sliderImg slider-elem'
alt='focusedEp'
src={this.state.imgUrl}
/>
<img
alt='nope'
src={right}
className='slider-elem slider-button case-right'
onClick={() => {
this.getNewEp(Number(this.state.focusedEpId) + 1)
}}
/>
</div>
</div>
)
}
}
export default Slider | Martotko/JS-Web | ReactJS/03.React-Components-Exercise/react-components-exercise/src/components/Slider.js | JavaScript | mit | 1,554 |
document.addEventListener ('DOMContentLoaded', function() {
var btn = document.getElementById("btn")
btn.addEventListener('click', function() {
document.getElementById("inp").value = document.getElementById("inp").value.toUpperCase();
});
});
document.addEventListener ('DOMContentLoaded', function() {
var btn = document.getElementById("btn1")
btn.addEventListener('click', function() {
document.getElementById("inp").value = document.getElementById("inp").value.toLowerCase();
});
});
document.addEventListener ('DOMContentLoaded', function() {
var inp= document.getElementById("inp")
inp.addEventListener('click', function() {
document.getElementById("inp").focus();
document.getElementById("inp").select();
});
}); | ProgaPanda/TextTools | CaseConverter/script.js | JavaScript | mit | 797 |
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// Routes
// const users = require('./src/routes/users');
// app.use('/users', users);
// app.get('/test', function(req, res) {
// res.send('TEST!');
// });
app.get('/', function(req, res) {
res.sendFile('index.html', { root: __dirname + '/public'});
// res.send('You shouldn\'t be here...');
});
app.get('*', function(req, res) {
res.redirect('/');
// res.send('You shouldn\'t be here...');
});
//test work for sockets
app.get('/chatview', function(req, res) {
res.send('/Debatechat');
})
const server = app.listen(8080, function() {
console.log('listening on port 8080!')
});
| garrulous-gorillas/garrulous-gorillas | client/client-server.js | JavaScript | mit | 865 |
localStorage.setItem("firstTime","false");
if(localStorage.getItem("firstTime") == null) {
localStorage.setItem("firstTime","true");
}
if (localStorage.getItem("firstTime") == "true") {
require("./welcome")();
}else{
require("./myClothes")();
}
| tiagostutz/lookabro | app.js | JavaScript | mit | 252 |
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { connect } from 'react-redux';
import { loadEntries as actionLoadEntries } from 'Actions/entries';
import { selectEntries } from 'Reducers';
import Entries from './Entries';
class EntriesCollection extends React.Component {
static propTypes = {
collection: ImmutablePropTypes.map.isRequired,
publicFolder: PropTypes.string.isRequired,
page: PropTypes.number,
entries: ImmutablePropTypes.list,
isFetching: PropTypes.bool.isRequired,
viewStyle: PropTypes.string,
};
componentDidMount() {
const { collection, loadEntries } = this.props;
if (collection) {
loadEntries(collection);
}
}
componentWillReceiveProps(nextProps) {
const { collection, loadEntries } = this.props;
if (nextProps.collection !== collection) {
loadEntries(nextProps.collection);
}
}
handleLoadMore = page => {
const { collection, loadEntries } = this.props;
loadEntries(collection, page);
}
render () {
const { collection, entries, publicFolder, page, isFetching, viewStyle } = this.props;
return (
<Entries
collections={collection}
entries={entries}
publicFolder={publicFolder}
page={page}
onPaginate={this.handleLoadMore}
isFetching={isFetching}
collectionName={collection.get('label')}
viewStyle={viewStyle}
/>
);
}
}
function mapStateToProps(state, ownProps) {
const { name, collection, viewStyle } = ownProps;
const { config } = state;
const publicFolder = config.get('public_folder');
const page = state.entries.getIn(['pages', collection.get('name'), 'page']);
const entries = selectEntries(state, collection.get('name'));
const isFetching = state.entries.getIn(['pages', collection.get('name'), 'isFetching'], false);
return { publicFolder, collection, page, entries, isFetching, viewStyle };
}
const mapDispatchToProps = {
loadEntries: actionLoadEntries,
};
export default connect(mapStateToProps, mapDispatchToProps)(EntriesCollection);
| Aloomaio/netlify-cms | src/components/Collection/Entries/EntriesCollection.js | JavaScript | mit | 2,148 |
const path = require("path");
const config = require("../config").default;
const assetPath = path.resolve(__dirname, "../../static/dist");
const WDSPort = config.server.port + 1;
const publicPath = `http://${config.server.host}:${WDSPort}/dist/`;
module.exports = {
entry: "./src/client.js",
output: {
filename: "[name]-[hash].js",
chunkFilename: "[name]-[chunkhash].js",
path: assetPath,
publicPath: publicPath
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
options: {
presets: [
"react",
"stage-0",
["env", { "targets": { "node": "current" } }]
],
cacheDirectory: true
}
}]
}
]
},
plugins: [],
devServer: {
contentBase: path.join(__dirname, "static"),
compress: true,
port: WDSPort
}
};
| jaraquistain/web-boilerplate | src/webpack/dev.webpack.config.js | JavaScript | mit | 944 |
/* global require, module */
module.exports = {
dbCleanUp: require('./dbCleanUp'),
dbTruncateTables: require('./dbTruncateTables'),
fixturesManager: require('./fixturesManager')
}; | luknei/rechat | test/utils/index.js | JavaScript | mit | 193 |
// testing 8 | pfeilbr/ForceKit | src/staticresources/a1/a1.js | JavaScript | mit | 12 |
'use strict';
window.onload = function () {
if (!('indexedDB' in window)) {
console.warn('IndexedDB not supported');
return;
}
var dbName = "my exercise";
var version = 1;
idb.open(dbName, version, function (upgradeDb) {
upgradeDb.createObjectStore('store1');
})
.then(function (db) { return console.log('success'); });
var timerComponent = document.querySelector(".timer"), setInputContainer = document.querySelector(".set-input"), timeInputContainer = document.querySelector(".time-input"), restContainer = document.querySelector(".rest-container"), titleDisplay = document.querySelector(".title-display"), stateDisplay = document.querySelector(".state-display"), setDisplay = document.querySelector(".sets-display"), timerDisplay = document.querySelector(".timer-display"), restDisplay = document.querySelector(".rest-display"), titleInput = document.querySelector("#title"), setInput = document.querySelector("#sets"), timerInput = document.querySelector("#time"), editButton = document.querySelector("#edit-btn"), playButton = document.querySelector("#start-btn"), stopButton = document.querySelector("#stop-btn");
var regEx = new RegExp('/^-?\d+\.?\d*$/');
var timeCount, setCount, countDownID, restIntervalID, timerTitle;
var restCount = 5;
stateDisplay.textContent = timerComponent.getAttribute("data-state");
restDisplay.textContent = restCount.toString();
timeCount = Number(timerInput.getAttribute("placeholder"));
setCount = Number(setInput.getAttribute("placeholder"));
setDisplay.textContent = setCount.toString();
timerDisplay.textContent = timeCount.toString();
editButton.addEventListener("click", editTimer, false);
playButton.addEventListener("click", startTimer, false);
stopButton.addEventListener("click", pauseTimer, false);
function updateTimer() {
setCount--;
if (setCount >= 0) {
setDisplay.textContent = setCount.toString();
timeCount = Number(timerInput.getAttribute("placeholder"));
restCount = 5;
restDisplay.textContent = restCount.toString();
timerDisplay.textContent = timerInput.getAttribute("placeholder");
timerComponent.setAttribute("data-state", "ready");
console.log("set count: " + setCount);
startTimer();
}
else {
console.log("you are done stretching");
timerComponent.setAttribute("data-state", "finished");
return;
}
}
function startTimer() {
if (timerComponent.getAttribute("data-state") != "stretching" && timerComponent.getAttribute("data-state") != "editing") {
countDownID = setInterval(initTime, 1000);
updateTimerState("stretching");
}
else {
if (timerComponent.getAttribute("data-state") == "editing") {
console.log("finish editing the timer");
}
if (timerComponent.getAttribute("data-state") == "stretching") {
console.log("Timer has already started");
}
}
}
function pauseTimer() {
if (timerComponent.getAttribute("data-state") == "stretching") {
updateTimerState("paused");
clearInterval(countDownID);
console.log("Paused the timer");
}
}
function startRest() {
restContainer.classList.add("active");
updateTimerState("resting");
restIntervalID = setInterval(initRest, 1000);
}
function createWarning(parent, warningString) {
if (parent.dataset.warningIssued) {
var warning = document.createElement("span");
var warningText = document.createTextNode(warningString);
warning.setAttribute("class", "warning");
warning.appendChild(warningText);
parent.appendChild(warning);
parent.dataset.warningIssued = true;
}
}
function editTimer() {
updateTimerState("editing");
console.log("initiate edit of timer");
setInput.classList.toggle("active");
timerInput.classList.toggle("active");
setInput.focus();
setInput.addEventListener("keyup", setSets, false);
timerInput.addEventListener("keyup", setTime, false);
}
function removeWarning(parent) {
if (parent.dataset.warningIssuedtrue) {
for (var i in parent.childNodes) {
if (parent.childNodes[i].className == "warning") {
parent.childNodes[i].remove();
}
}
parent.dataset.warningIssued = false;
}
}
function updateTimerState(state) {
timerComponent.setAttribute("data-state", state);
stateDisplay.textContent = timerComponent.getAttribute("data-state");
}
function setSets(e) {
if (e.keyCode === 13 && document.activeElement === setInput) {
setCount = this.value;
this.placeholder = setCount;
console.log("setInput value: " + this.value);
setDisplay.textContent = setCount.toString();
this.value = '';
this.classList.remove("active");
timerInput.focus();
}
}
function setTime(e) {
console.log(e.keyCode);
if (e.keyCode === 13 && document.activeElement === timerInput) {
timeCount = this.value;
this.placeholder = timeCount;
console.log("timerInput value:" + this.value);
timerDisplay.textContent = timeCount.toString();
this.value = '';
this.classList.remove("active");
updateTimerState("set");
}
}
function initTime() {
timeCount--;
timerDisplay.textContent = timeCount.toString();
if (timeCount == 0) {
console.log("time: " + timeCount);
pauseTimer();
startRest();
}
}
function initRest() {
restCount--;
restDisplay.textContent = restCount.toString();
if (restCount == 0) {
clearInterval(restIntervalID);
restContainer.classList.remove("active");
updateTimer();
}
}
};
//# sourceMappingURL=script.js.map | zberwaldt/stretch-clock | development/js/script.js | JavaScript | mit | 6,298 |
Dagaz.View.CLEAR_KO = true;
ZRF = {
JUMP: 0,
IF: 1,
FORK: 2,
FUNCTION: 3,
IN_ZONE: 4,
FLAG: 5,
SET_FLAG: 6,
POS_FLAG: 7,
SET_POS_FLAG: 8,
ATTR: 9,
SET_ATTR: 10,
PROMOTE: 11,
MODE: 12,
ON_BOARD_DIR: 13,
ON_BOARD_POS: 14,
PARAM: 15,
LITERAL: 16,
VERIFY: 20
};
Dagaz.Model.BuildDesign = function(design) {
design.checkVersion("z2j", "2");
design.checkVersion("animate-drops", "false");
design.checkVersion("animate-captures", "false");
design.checkVersion("show-blink", "false");
design.checkVersion("show-hints", "false");
design.checkVersion("show-drops", "true");
design.checkVersion("show-captures", "false");
design.addDirection("down"); // 0
design.addDirection("left"); // 1
design.addDirection("right"); // 2
design.addDirection("next"); // 3
design.addPlayer("You", [0, 1, 2, 3]);
design.addPlayer("Computer", [0, 1, 2, 3]);
design.addTurn(1);
design.addPosition("a8", [4, 0, 1, 0]);
design.addPosition("b8", [4, 0, 1, 0]);
design.addPosition("c8", [4, 0, 1, 0]);
design.addPosition("d8", [4, 0, 0, 0]);
design.addPosition("a7", [4, 0, 1, 32]);
design.addPosition("b7", [4, -1, 1, 0]);
design.addPosition("c7", [4, -2, 1, 0]);
design.addPosition("d7", [4, -3, 0, 0]);
design.addPosition("a6", [4, 0, 1, 32]);
design.addPosition("b6", [4, -1, 1, 0]);
design.addPosition("c6", [4, -2, 1, 0]);
design.addPosition("d6", [4, -3, 0, 0]);
design.addPosition("a5", [4, 0, 1, 32]);
design.addPosition("b5", [4, -1, 1, 0]);
design.addPosition("c5", [4, -2, 1, 0]);
design.addPosition("d5", [4, -3, 0, 0]);
design.addPosition("a4", [4, 0, 1, 32]);
design.addPosition("b4", [4, -1, 1, 0]);
design.addPosition("c4", [4, -2, 1, 0]);
design.addPosition("d4", [4, -3, 0, 0]);
design.addPosition("a3", [4, 0, 1, 32]);
design.addPosition("b3", [4, -1, 1, 0]);
design.addPosition("c3", [4, -2, 1, 0]);
design.addPosition("d3", [4, -3, 0, 0]);
design.addPosition("a2", [4, 0, 1, 32]);
design.addPosition("b2", [4, -1, 1, 0]);
design.addPosition("c2", [4, -2, 1, 0]);
design.addPosition("d2", [4, -3, 0, 0]);
design.addPosition("a1", [0, 0, 1, 32]);
design.addPosition("b1", [0, -1, 1, 0]);
design.addPosition("c1", [0, -2, 1, 0]);
design.addPosition("d1", [0, -3, 0, 0]);
design.addPosition("x16", [0, 0, 0, 0]);
design.addPosition("y16", [0, 0, 0, 0]);
design.addPosition("x15", [0, 0, 0, 0]);
design.addPosition("y15", [0, 0, 0, 0]);
design.addPosition("x14", [0, 0, 0, 1]);
design.addPosition("y14", [0, 0, 0, 1]);
design.addPosition("x13", [0, 0, 0, 1]);
design.addPosition("y13", [0, 0, 0, 0]);
design.addPosition("x12", [0, 0, 0, 1]);
design.addPosition("y12", [0, 0, 0, 1]);
design.addPosition("x11", [0, 0, 0, 1]);
design.addPosition("y11", [0, 0, 0, 0]);
design.addPosition("x10", [0, 0, 0, 1]);
design.addPosition("y10", [0, 0, 0, 1]);
design.addPosition("x9", [0, 0, 0, 1]);
design.addPosition("y9", [0, 0, 0, 0]);
design.addPosition("x8", [0, 0, 0, 1]);
design.addPosition("y8", [0, 0, 0, 1]);
design.addPosition("x7", [0, 0, 0, 1]);
design.addPosition("y7", [0, 0, 0, 0]);
design.addPosition("x6", [0, 0, 0, 1]);
design.addPosition("y6", [0, 0, 0, 1]);
design.addPosition("x5", [0, 0, 0, 1]);
design.addPosition("y5", [0, 0, 0, 0]);
design.addPosition("x4", [0, 0, 0, 1]);
design.addPosition("y4", [0, 0, 0, 1]);
design.addPosition("x3", [0, 0, 0, 1]);
design.addPosition("y3", [0, 0, 0, 0]);
design.addPosition("x2", [0, 0, 0, 1]);
design.addPosition("y2", [0, 0, 0, 1]);
design.addPosition("x1", [0, 0, 0, 1]);
design.addPosition("y1", [0, 0, 0, 0]);
design.addZone("last-rank", 1, [0, 1, 2, 3]);
design.addZone("board-zone", 1, [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]);
design.addCommand(0, ZRF.FUNCTION, 1); // empty?
design.addCommand(0, ZRF.FUNCTION, 20); // verify
design.addCommand(0, ZRF.IN_ZONE, 1); // board-zone
design.addCommand(0, ZRF.FUNCTION, 20); // verify
design.addCommand(0, ZRF.FUNCTION, 25); // to
design.addCommand(0, ZRF.FUNCTION, 28); // end
design.addPiece("red", 0);
design.addDrop(0, 0, [0], 0);
design.addPiece("blue", 1);
design.addDrop(1, 0, [1], 0);
design.addPiece("green", 2);
design.addDrop(2, 0, [2], 0);
design.addPiece("yellow", 3);
design.addDrop(3, 0, [3], 0);
design.addPiece("purple", 4);
design.addDrop(4, 0, [4], 0);
design.addPiece("cyan", 5);
design.addDrop(5, 0, [5], 0);
design.addPiece("white", 6);
design.addPiece("black", 7);
}
Dagaz.View.configure = function(view) {
view.defBoard("Board");
view.defPiece("Youred", "You red");
view.defPiece("Computerred", "Computer red");
view.defPiece("Youblue", "You blue");
view.defPiece("Computerblue", "Computer blue");
view.defPiece("Yougreen", "You green");
view.defPiece("Computergreen", "Computer green");
view.defPiece("Youyellow", "You yellow");
view.defPiece("Computeryellow", "Computer yellow");
view.defPiece("Youpurple", "You purple");
view.defPiece("Computerpurple", "Computer purple");
view.defPiece("Youcyan", "You cyan");
view.defPiece("Computercyan", "Computer cyan");
view.defPiece("Youwhite", "You white");
view.defPiece("Youblack", "You black");
view.defPiece("Ko", "Ko");
view.defPosition("a8", 2, 2, 50, 50);
view.defPosition("b8", 52, 2, 50, 50);
view.defPosition("c8", 102, 2, 50, 50);
view.defPosition("d8", 152, 2, 50, 50);
view.defPosition("a7", 2, 52, 50, 50);
view.defPosition("b7", 52, 52, 50, 50);
view.defPosition("c7", 102, 52, 50, 50);
view.defPosition("d7", 152, 52, 50, 50);
view.defPosition("a6", 2, 102, 50, 50);
view.defPosition("b6", 52, 102, 50, 50);
view.defPosition("c6", 102, 102, 50, 50);
view.defPosition("d6", 152, 102, 50, 50);
view.defPosition("a5", 2, 152, 50, 50);
view.defPosition("b5", 52, 152, 50, 50);
view.defPosition("c5", 102, 152, 50, 50);
view.defPosition("d5", 152, 152, 50, 50);
view.defPosition("a4", 2, 202, 50, 50);
view.defPosition("b4", 52, 202, 50, 50);
view.defPosition("c4", 102, 202, 50, 50);
view.defPosition("d4", 152, 202, 50, 50);
view.defPosition("a3", 2, 252, 50, 50);
view.defPosition("b3", 52, 252, 50, 50);
view.defPosition("c3", 102, 252, 50, 50);
view.defPosition("d3", 152, 252, 50, 50);
view.defPosition("a2", 2, 302, 50, 50);
view.defPosition("b2", 52, 302, 50, 50);
view.defPosition("c2", 102, 302, 50, 50);
view.defPosition("d2", 152, 302, 50, 50);
view.defPosition("a1", 2, 352, 50, 50);
view.defPosition("b1", 52, 352, 50, 50);
view.defPosition("c1", 102, 352, 50, 50);
view.defPosition("d1", 152, 352, 50, 50);
view.defPosition("x16", 210, 10, 10, 10);
view.defPosition("y16", 235, 10, 10, 10);
view.defPosition("x15", 210, 35, 10, 10);
view.defPosition("y15", 235, 35, 10, 10);
view.defPosition("x14", 210, 60, 10, 10);
view.defPosition("y14", 235, 60, 10, 10);
view.defPosition("x13", 210, 85, 10, 10);
view.defPosition("y13", 235, 85, 10, 10);
view.defPosition("x12", 210, 110, 10, 10);
view.defPosition("y12", 235, 110, 10, 10);
view.defPosition("x11", 210, 135, 10, 10);
view.defPosition("y11", 235, 135, 10, 10);
view.defPosition("x10", 210, 160, 10, 10);
view.defPosition("y10", 235, 160, 10, 10);
view.defPosition("x9", 210, 185, 10, 10);
view.defPosition("y9", 235, 185, 10, 10);
view.defPosition("x8", 210, 210, 10, 10);
view.defPosition("y8", 235, 210, 10, 10);
view.defPosition("x7", 210, 235, 10, 10);
view.defPosition("y7", 235, 235, 10, 10);
view.defPosition("x6", 210, 260, 10, 10);
view.defPosition("y6", 235, 260, 10, 10);
view.defPosition("x5", 210, 285, 10, 10);
view.defPosition("y5", 235, 285, 10, 10);
view.defPosition("x4", 210, 310, 10, 10);
view.defPosition("y4", 235, 310, 10, 10);
view.defPosition("x3", 210, 335, 10, 10);
view.defPosition("y3", 235, 335, 10, 10);
view.defPosition("x2", 210, 360, 10, 10);
view.defPosition("y2", 235, 360, 10, 10);
view.defPosition("x1", 210, 385, 10, 10);
view.defPosition("y1", 235, 385, 10, 10);
}
| GlukKazan/Dagaz | src/debug/games/arrange/mastermind.js | JavaScript | mit | 8,853 |
/**
* version_manager.js for LabJack Switchboard. Provides Kipling with the ability
* to query for various versions of LabJack software versions, firmeware
* versions, and drivers
*
* @author Chris Johnson (LabJack, 2014)
**/
var q = require('q');
var request = require('request');
var async = require('async');
var dict = require('dict');
var handlebars = require('handlebars');
// console.log('Initializing error_handler.js');
var errorTypes = {
'critical': 0,
'warning': 1,
'generic': 2
};
var errorTypesStr = {
0: 'critical',
1: 'warning',
2: 'generic'
};
var UNKNOWN_ERROR = 'unknownError';
var DEFAULT_SAVE_TYPE = 'start';
var registeredNames = [
{
'name':'GDM',
'saveType': 'start',
'location': 'global_data_manager.js',
'errorList': [
{'name': 'missingReqDir', 'message': 'Missing a required temp directory, LJM may not be installed properly.'}
]
},
{
'name': UNKNOWN_ERROR,
'saveType': 'start',
'location': 'unknown'
}
];
var savedErrors = dict();
var registeredNamesDict = dict();
registeredNames.forEach(function(registeredName) {
var errorDict = dict();
var errors = dict();
if(registeredName.errorList) {
registeredName.errorList.forEach(function(err){
errors.set(err.name,err.message);
});
}
savedErrors.set(registeredName.name,errorDict);
registeredName.errors = errors;
registeredNamesDict.set(registeredName.name,registeredName);
});
var numErrors = 0;
var latestError = null;
var allErrors = [];
var makeErrorObj = function(level, errorName, callerInfo, options) {
var message;
if(options.message) {
message = options.message;
} else {
message = callerInfo.name + ': ';
if(callerInfo.errors.has(errorName)) {
message += callerInfo.errors.get(errorName);
} else {
message += errorName + ' (undefined)';
}
}
var data;
if(options.data) {
data = options.data;
} else {
data = null;
}
var date = new Date();
var errorObject = {
'level': level,
'levelStr': errorTypesStr[level],
'type': errorName,
'callerName': callerInfo.name,
'location': callerInfo.location,
'message': message,
'data': data,
'options': options,
'time': date
};
return errorObject;
};
var saveStartError = function(callerName, errorName, newError) {
var curErrorDict = savedErrors.get(callerName);
var errorArray = [newError];
curErrorDict.set(errorName, errorArray);
};
var savePushError = function(callerName, errorName, newError) {
var curErrorDict = savedErrors.get(callerName);
if(curErrorDict.has(errorName)) {
var curArray = curErrorDict.get(errorName);
curArray.push(newError);
curErrorDict.set(errorName, curArray);
} else {
var errorArray = [newError];
curErrorDict.set(errorName, errorArray);
}
};
var makeError = function(level, callerName, errorName, options) {
if(!options) {
options = {};
}
if(!savedErrors.has(callerName)) {
callerName = UNKNOWN_ERROR;
}
numErrors += 1;
var curErrorDict = savedErrors.get(callerName);
var callerInfo = registeredNamesDict.get(callerName);
var newError = makeErrorObj(level, errorName, callerInfo, options);
latestError = newError;
allErrors.push(newError);
var saveType;
if(options.saveType) {
saveType = options.saveType;
} else {
saveType = callerInfo.saveType;
}
if(saveType === 'start') {
savePushError(callerName, errorName, newError);
} else if (saveType === 'push') {
saveStartError(callerName, errorName, newError);
} else {
saveStartError(callerName, errorName, newError);
}
return newError;
};
/**
* Possible Options are:
* 1. message {string} A user-readable message, if not given is auto-filled.
* 2. data {string} User-defined data, defaults to ''.
* 3. saveType {string} Either 'push' or 'start', defaults to start. Used to
* save errors to the error stack for later retrieval.
* @param {[type]} callerName [description]
* @param {[type]} errorName [description]
* @param {[type]} options [description]
* @return {[type]} [description]
*/
exports.criticalError = function(callerName, errorName, options) {
return makeError(errorTypes['critical'], callerName, errorName, options);
};
exports.warning= function(callerName, errorName, options) {
return makeError(errorTypes['warning'], callerName, errorName, options);
};
exports.getAllErrors = function() {
return allErrors;
};
exports.getLatestError = function() {
return latestError;
};
exports.getNumErrors = function() {
return numErrors;
};
exports.getSavedErrors = function() {
return savedErrors;
};
| Samnsparky/ljswitchboard | src/helper_scripts/error_handler.js | JavaScript | mit | 4,509 |
var NAVTREEINDEX0 =
{
"dir_13e138d54eb8818da29c3992edef070a.html":[7,0,2],
"dir_68267d1309a1af8e8297ef4c3efbcdba.html":[7,0,1],
"dir_d44c64559bbebec7f509842c48db8b23.html":[7,0,0],
"files.html":[7,0],
"globals.html":[7,1,0],
"globals_defs.html":[7,1,2],
"globals_func.html":[7,1,1],
"index.html":[],
"index.html":[0],
"md_README.html":[1],
"md_docs_testBin.html":[6],
"md_docs_testIncreasing.html":[3],
"md_docs_testSimple.html":[2],
"md_docs_testSubtracting.html":[4],
"md_docs_testUntil3000.html":[5],
"pages.html":[],
"roman-to-int_8c.html":[7,0,1,0],
"roman-to-int_8c.html#a0ddf1224851353fc92bfbff6f499fa97":[7,0,1,0,0],
"roman-to-int_8c_source.html":[7,0,1,0],
"roman_8c.html":[7,0,1,1],
"roman_8c.html#a4699cffee35f01be5409c50749293337":[7,0,1,1,1],
"roman_8c.html#a5d15ad3ed29e4dc0fed9b718523c48c8":[7,0,1,1,3],
"roman_8c.html#a5f42a20564ee7bb82242bc572ad34533":[7,0,1,1,4],
"roman_8c.html#ab8b51e6124eb6e0c237d64256bde1606":[7,0,1,1,2],
"roman_8c.html#afbee2dc5627d75ae539ec36e9fb1a4c6":[7,0,1,1,0],
"roman_8c_source.html":[7,0,1,1],
"roman_8h.html":[7,0,0,0],
"roman_8h.html#a5d15ad3ed29e4dc0fed9b718523c48c8":[7,0,0,0,0],
"roman_8h_source.html":[7,0,0,0],
"test_bin_8c.html":[7,0,2,0],
"test_bin_8c.html#a3c04138a5bfe5d72780bb7e82a18e627":[7,0,2,0,0],
"test_bin_8c.html#a85feadc23ad01a2a391deaa1d4d23a76":[7,0,2,0,1],
"test_bin_8c_source.html":[7,0,2,0],
"test_increasing_8c.html":[7,0,2,1],
"test_increasing_8c.html#a0e7fee3a9d51270a0e9593ef4c14575c":[7,0,2,1,6],
"test_increasing_8c.html#a1652abfeae14a287b82d1510b9766d53":[7,0,2,1,5],
"test_increasing_8c.html#a3c04138a5bfe5d72780bb7e82a18e627":[7,0,2,1,0],
"test_increasing_8c.html#a578c6adf00f73e5f2d177f78b1cc308e":[7,0,2,1,1],
"test_increasing_8c.html#a5b30da3eefffcd098caa52400f2fc209":[7,0,2,1,4],
"test_increasing_8c.html#a72add5b20757e98140ffa078f271897b":[7,0,2,1,3],
"test_increasing_8c.html#ae6c8ad374723e2fd0b26e4c8993c60c6":[7,0,2,1,2],
"test_increasing_8c_source.html":[7,0,2,1],
"test_simple_8c.html":[7,0,2,2],
"test_simple_8c.html#a3c04138a5bfe5d72780bb7e82a18e627":[7,0,2,2,0],
"test_simple_8c.html#a7780b7f477399a829f64fd94a5423bb6":[7,0,2,2,2],
"test_simple_8c.html#aff9fa977573ddab7597e233f1775d7c5":[7,0,2,2,1],
"test_simple_8c_source.html":[7,0,2,2],
"test_subtracting_8c.html":[7,0,2,3],
"test_subtracting_8c.html#a3c04138a5bfe5d72780bb7e82a18e627":[7,0,2,3,0],
"test_subtracting_8c.html#a4a3c4ddd22a00089ba61feb3a72fbbae":[7,0,2,3,2],
"test_subtracting_8c.html#a5b85a75cb9b1b65c04b295881185e5fd":[7,0,2,3,1],
"test_subtracting_8c.html#a61dc6f312f588f58e5c9d9b5b87c993f":[7,0,2,3,3],
"test_subtracting_8c_source.html":[7,0,2,3],
"test_until3000_8c.html":[7,0,2,4],
"test_until3000_8c.html#a3c04138a5bfe5d72780bb7e82a18e627":[7,0,2,4,1],
"test_until3000_8c.html#ae56c17e7745f0e7d9ad4f166d306e0c3":[7,0,2,4,2],
"test_until3000_8c.html#afff9b137f11d394618b464995fe76f99":[7,0,2,4,0],
"test_until3000_8c_source.html":[7,0,2,4]
};
| diogenes1oliveira/libroman | doc/html/navtreeindex0.js | JavaScript | mit | 2,913 |
var turningLeft = 0;
var turningRight = 0;
var turningLength = 52;
var backwardsLength = 31;
function agentLogic(sensorsData, worldData) {
var leftPower = 1;
var rightPower = 1;
if (turningLeft) {
leftPower = -1;
rightPower = 1;
if (turningLeft>backwardsLength) rightPower = -1;
turningLeft--;
} else if (turningRight) {
leftPower = 1;
rightPower = -1;
if (turningRight>backwardsLength) leftPower = -1;
turningRight--;
} else if (sensorsData.left_whisker || sensorsData.right_whisker) {
if (sensorsData.position_x < 4) turningLeft = turningLength;
else turningRight = turningLength;
}
return {
leftPower: leftPower,
rightPower: rightPower
};
}
| escalant3/ai-box | samples/brains/js/dumb-reactor.js | JavaScript | mit | 712 |
var Node = require("./node");
var he = require("he");
function Text (value) {
this.nodeValue = value ? he.encode(String(value)) : value;
}
Node.extend(Text, {
/**
*/
nodeType: 3,
/**
*/
getInnerHTML: function () {
return this.nodeValue;
},
/**
*/
cloneNode: function () {
var clone = new Text(this.nodeValue);
clone._buffer = this._buffer;
return clone;
}
});
Object.defineProperty(Text.prototype, "nodeValue", {
get: function() {
return this._nodeValue;
},
set: function(value) {
this._nodeValue = value;
this._triggerChange();
}
});
module.exports = Text;
| benaadams/nofactor.js | lib/string/text.js | JavaScript | mit | 634 |
import reducer from './siteVersionReducer';
import * as types from '../constants/actionTypes';
describe('mode reducer', () => {
it('should return the initial state', () => {
expect(
reducer(undefined, {})
).toEqual([]);
});
it('should handle load site Versions', () => {
expect(
reducer([], {
type: types.LOAD_SITEVERSIONS,
siteVersions: []
})
).toEqual(
[]
);
});
it('should handle create site Versions', () => {
expect(
reducer([], {
type: types.CREATE_SITEVERSIONS,
siteVersion: {
id: 1,
versionValue: '',
modeValue: '',
isActive: false
}
})
).toEqual(
[{
id: 1,
versionValue: '',
modeValue: '',
isActive: false
}]
);
});
it('should handle update site Versions', () => {
expect(
reducer([{
id: 1,
versionValue: '',
modeValue: '',
isActive: false
}], {
type: types.UPDATE_SITEVERSIONS,
siteVersion: {
id: 1,
versionValue: '1.0',
modeValue: '2.0',
isActive: true
}
})
).toEqual(
[{
id: 1,
versionValue: '1.0',
modeValue: '2.0',
isActive: true
}]
);
expect(
reducer([{
id: 1,
versionValue: '',
modeValue: '',
isActive: false
},
{
id: 2,
versionValue: '',
modeValue: '',
isActive: false
}], {
type: types.UPDATE_SITEVERSIONS,
siteVersion: {
id: 2,
versionValue: '1.0',
modeValue: '2.0',
isActive: true
}
})
).toEqual(
[{
id: 1,
versionValue: '',
modeValue: '',
isActive: false
},
{
id: 2,
versionValue: '1.0',
modeValue: '2.0',
isActive: true
}]
);
});
it('should handle remove site Versions', () => {
expect(
reducer([{
id: 1,
versionValue: '1.0',
modeValue: '2.0',
isActive: true
}], {
type: types.DELETE_SITEVERSIONS,
siteVersion: {
id: 1,
versionValue: '1.0',
modeValue: '2.0',
isActive: true
}
})
).toEqual(
[]
);
expect(
reducer([{
id: 1,
versionValue: '',
modeValue: '',
isActive: false
},
{
id: 2,
versionValue: '',
modeValue: '',
isActive: false
}], {
type: types.DELETE_SITEVERSIONS,
siteVersion: {
id: 2,
versionValue: '',
modeValue: '',
isActive: false
}
})
).toEqual(
[{
id: 1,
versionValue: '',
modeValue: '',
isActive: false
}]
);
});
}); | Naren090/wpp | src/reducers/siteVersionReducer.spec.js | JavaScript | mit | 2,486 |
import './test_case_list.html';
import {Blaze} from 'meteor/blaze';
import {Template} from 'meteor/templating';
import {FlowRouter} from 'meteor/kadira:flow-router';
import {TestCases} from '../../../../../imports/api/test_cases/test_cases.js';
import {TestGroups} from '../../../../../imports/api/test_cases/test_groups.js'
import './test_case_list_group.js';
import './test_case_list_item.js';
/**
* Template Helpers
*/
Template.TestCaseList.helpers({
baseGroups() {
return TestGroups.find({ parentGroupId: null, projectVersionId: FlowRouter.getParam("projectVersionId") }, { sort: { title: 1 } });
},
baseTestCases() {
return TestCases.find({ testGroupId: null, projectVersionId: FlowRouter.getParam("projectVersionId") }, { sort: { title: 1 } });
}
});
/**
* Template Event Handlers
*/
Template.TestCaseList.events({
"keyup .add-item-form input"(e, instance) {
var value = $(e.target).val();
if(e.which == 13 && value.length >= 2){
//instance.$(".add-item-form .dropdown-toggle").trigger("click");
// Search for the entered text
instance.$(".add-item-form .btn-search").trigger("click");
} else if(value.length >= 2){
if(instance.$(".add-item-form .btn-add-item").attr("disabled")){
instance.$(".add-item-form .btn-add-item").removeAttr("disabled");
}
if(instance.$(".add-item-form .btn-search").attr("disabled")){
instance.$(".add-item-form .btn-search").removeAttr("disabled");
}
} else {
instance.$(".add-item-form .btn-add-item").attr("disabled", "disabled");
instance.$(".add-item-form .btn-search").attr("disabled", "disabled");
}
},
"click .btn-search"(e, instance) {
var search = instance.$(".add-item-form input").val(),
projectVersionId = FlowRouter.getParam("projectVersionId");
if(search.length < 2){
return;
}
if(!projectVersionId){
console.error("Search failed: no project version id found");
}
// show the clear button
instance.$(".field-clear-btn").show();
// hide everything from the list
instance.$(".center-pole-list-selectable").hide();
// show everything that matches the search
var highlight = function (item) {
var item = instance.$(".center-pole-list-selectable[data-pk='" + item._id + "']");
item.show().addClass("highlight");
item.parents(".center-pole-list-group-items").each(function (i, el) {
var parentInstance = Blaze.getView(el).templateInstance();
if(parentInstance.expanded){
parentInstance.$(".center-pole-list-selectable").first().show();
parentInstance.expanded.set(true);
}
});
};
TestCases.find({ title: {$regex: search, $options: "i"}, projectVersionId: projectVersionId }).forEach(highlight);
TestGroups.find({ title: {$regex: search, $options: "i"}, projectVersionId: projectVersionId }).forEach(highlight);
// show no results if nothing matched
if(!instance.$(".center-pole-list-selectable.highlight").length){
instance.$(".search-no-results").show();
}
},
"click .field-clear-btn"(e, instance) {
instance.$(".add-item-form input").val("");
instance.$(".field-clear-btn").hide();
instance.$(".search-no-results").hide();
instance.$(".center-pole-list-selectable.highlight").removeClass("highlight");
instance.$(".center-pole-list-selectable").show();
},
"click .add-item-form a"(e, instance) {
var itemType = $(e.target).closest("a").attr("data-name"),
itemName = instance.$(".add-item-form input").val().trim(),
projectId = FlowRouter.getParam("projectId"),
versionId = FlowRouter.getParam("projectVersionId"),
groupId = instance.$(".center-pole-list-group.selected").attr("data-group-id");
if(itemType && itemName && itemName.length){
if(itemType == "testcase"){
TestCases.insert({
projectId: projectId,
projectVersionId: versionId,
testGroupId: groupId,
title: itemName
}, function (error, result) {
if(error){
console.error("Failed to insert test case: " + error.message);
RobaDialog.error("Failed to insert test case: " + error.message);
} else {
instance.$(".add-item-form input").val("")
}
});
} else if(itemType == "testgroup") {
TestGroups.insert({
projectId: projectId,
projectVersionId: versionId,
parentGroupId: groupId,
title: itemName
}, function (error, result) {
if(error){
console.error("Failed to insert test group: " + error.message);
RobaDialog.error("Failed to insert test group: " + error.message);
} else {
instance.$(".add-item-form input").val("")
}
});
}
}
},
"click .center-pole-list-item"(e, instance) {
if(instance.data.editable){
var selectable = $(e.target).closest(".center-pole-list-item");
instance.$(".center-pole-list-item.selected").removeClass("selected");
selectable.addClass("selected");
FlowRouter.setQueryParams({testCaseId: selectable.attr("data-pk")});
}
},
// make sure the draggable and droppable items stay up to date
"mouseover .center-pole-list-selectable:not(.ui-draggable)"(e, instance) {
$(e.target).closest(instance.draggableSelector).draggable(instance.draggableOptions);
},
"mouseover .center-pole-list-group:not(.ui-droppable)"(e, instance) {
if(instance.data.editable){
$(e.target).closest(".center-pole-list-group").droppable(instance.droppableOptions);
}
}
});
/**
* Template Created
*/
Template.TestCaseList.created = function () {
let instance = Template.instance();
instance.elementIdReactor = new ReactiveVar();
instance.autorun(function () {
var projectId = FlowRouter.getParam("projectId"),
projectVersionId = FlowRouter.getParam("projectVersionId");
instance.subscribe("test_cases", projectId, projectVersionId);
instance.subscribe("test_groups", projectId, projectVersionId);
});
};
/**
* Template Rendered
*/
Template.TestCaseList.rendered = function () {
var instance = Template.instance();
// setup the draggable config
instance.draggableSelector = ".center-pole-list-selectable";
instance.draggableOptions = {
revert: "invalid",
distance: 5,
start(event, ui) {
ui.helper.addClass("in-drag");
},
stop(event, ui) {
ui.helper.removeClass("in-drag");
}
};
if(instance.data.editable){
instance.draggableOptions.axis = "y";
}
if(instance.data.connectToSortable){
instance.draggableOptions.connectToSortable = instance.data.connectToSortable;
instance.draggableOptions.helper = "clone";
//instance.draggableSelector = ".center-pole-list-item";
}
// make the list items draggable
instance.$(instance.draggableSelector).draggable(instance.draggableOptions);
if(instance.data.editable) {
// setup the droppable config
instance.droppableOptions = {
greedy: true,
hoverClass: "center-pole-list-drop-hover",
drop(event, ui) {
var groupId = $(this).attr("data-group-id"),
itemId = ui.draggable.attr("data-pk"),
itemIsGroup = ui.draggable.hasClass("center-pole-list-group");
console.log("Drop: ", itemId, "on", groupId);
if (groupId && itemId) {
if (itemIsGroup) {
TestGroups.update(itemId, {$set: {parentGroupId: groupId}}, function (error) {
if (error) {
console.error("Failed to update parent group: " + error.message);
RobaDialog.error("Failed to update parent group: " + error.message);
}
});
} else {
TestCases.update(itemId, {$set: {testGroupId: groupId}}, function (error) {
if (error) {
console.error("Failed to update test group: " + error.message);
RobaDialog.error("Failed to update test group: " + error.message);
}
});
}
}
},
accept(el) {
var dragParentId = $(el).attr("data-parent-id"),
dragId = $(el).attr("data-group-id"),
targetId = $(this).attr("data-group-id"),
isChild = false;
if (dragId) {
isChild = $(this).closest("[data-group-id='" + dragId + "']").length > 0;
}
return dragParentId !== targetId && !isChild;
}
};
// make the groups droppable
instance.$(".center-pole-list-group").droppable(instance.droppableOptions);
// Select the selected item if there is one defined
var testCaseId = FlowRouter.getQueryParam("testCaseId");
if(testCaseId){
instance.autorun(function () {
var testCaseItem = instance.$(".center-pole-list-item[data-pk='" + testCaseId + "']"),
elementId = instance.elementIdReactor.get();
if(elementId){
testCaseItem.addClass("selected");
testCaseItem.parentsUntil(".center-pole-list", ".center-pole-list-group-items.hide").each(function (i, el) {
Blaze.getView(el).templateInstance().expanded.set(true);
});
}
});
}
}
};
/**
* Template Destroyed
*/
Template.TestCaseList.destroyed = function () {
};
| austinsand/doc-roba | meteor/client/ui/components/nav_menus/test_case_nav/test_case_list.js | JavaScript | mit | 9,365 |
export function add(lhs, rhs) {
return lhs + rhs;
}
export function subtract(lhs, rhs) {
return lhs - rhs;
}
export function multiply(lhs, rhs) {
return lhs * rhs;
}
export function divide(lhs, rhs) {
return lhs / rhs;
} | Nulifier/Obsidian | src/helpers/math.js | JavaScript | mit | 241 |
import {
defaultAction,
} from '../actions';
import {
DEFAULT_ACTION,
} from '../constants';
describe('UserPage actions', () => {
describe('Default Action', () => {
it('has a type of DEFAULT_ACTION', () => {
const expected = {
type: DEFAULT_ACTION,
};
expect(defaultAction()).toEqual(expected);
});
});
});
| balintsoos/app.rezsi.io | app/containers/UserPage/tests/actions.test.js | JavaScript | mit | 351 |
/* eslint-disable ember/no-new-mixins */
import Mixin from '@ember/object/mixin';
export default Mixin.create({
activate(...args) {
this._super(...args);
if (typeof FastBoot === 'undefined') {
window.scrollTo(0, 0);
}
},
});
| null-null-null/ember-keyboard | tests/dummy/app/mixins/reset-scroll-position.js | JavaScript | mit | 249 |
var gulp = require('gulp');
var paths = require('../paths');
var typedoc = require('gulp-typedoc');
var runSequence = require('run-sequence');
var through2 = require('through2');
gulp.task('doc-generate', function(){
return gulp.src([paths.output + paths.packageName + '.d.ts', paths.doc + '/i18next.d.ts'])
.pipe(typedoc({
target: 'es6',
includeDeclarations: true,
moduleResolution: 'node',
json: paths.doc + '/api.json',
name: paths.packageName + '-docs',
mode: 'modules',
excludeExternals: true,
ignoreCompilerErrors: false,
version: true
}));
});
gulp.task('doc-shape', function(){
return gulp.src([paths.doc + '/api.json'])
.pipe(through2.obj(function(file, enc, callback) {
var json = JSON.parse(file.contents.toString('utf8')).children[0];
json = {
name: paths.packageName,
children: json.children,
groups: json.groups
};
file.contents = new Buffer(JSON.stringify(json));
this.push(file);
return callback();
}))
.pipe(gulp.dest(paths.doc));
});
gulp.task('doc', function(callback){
return runSequence(
'doc-generate',
'doc-shape',
callback
);
});
| Jaans/aurelia-plugins-google-recaptcha | build/tasks/doc.js | JavaScript | mit | 1,224 |
require('normalize.css/normalize.css');
require('styles/App.scss');
import React from 'react';
import GalleryApp from '../sources/GalleryApp';
class AppComponent extends React.Component {
render() {
return (
<div className="stage">
<GalleryApp></GalleryApp>
</div>
);
}
}
AppComponent.defaultProps = {
};
export default AppComponent;
| liyangda/gallery-by-react | src/components/Main.js | JavaScript | mit | 371 |
+(function (global, factory) {
if (typeof exports === 'undefined') {
factory(global.webduino || {});
} else {
module.exports = factory;
}
}(this, function (scope) {
'use strict';
var PinEvent = scope.PinEvent,
Pin = scope.Pin,
Module = scope.Module;
var ShockEvent = {
HIGH: 'high',
LOW: 'low'
};
function Shock(board, pin) {
Module.call(this);
this._board = board;
this._pin = pin;
board.setDigitalPinMode(pin.number, Pin.DIN);
this._pin.value = Pin.HIGH;
this._pin.on(PinEvent.CHANGE, onPinChange.bind(this));
}
function onPinChange(pin) {
if (pin.value === Pin.HIGH) {
this.emit(ShockEvent.HIGH);
} else {
this.emit(ShockEvent.LOW);
}
}
Shock.prototype = Object.create(Module.prototype, {
constructor: {
value: Shock
}
});
scope.module.ShockEvent = ShockEvent;
scope.module.Shock = Shock;
}));
| webduinoio/webduino-js | src/module/Shock.js | JavaScript | mit | 922 |
angular.module('Frosch')
.controller('SeleccionJugadoresCtrl',
function ($scope, $rootScope, $state, config, hotkeys) {
$scope.iniciar = function () {
if ($scope.creditosExactos()) {
config.setNumJugadores($scope.numJugadores());
$rootScope.restarCreditos($scope.numJugadores() * config.creditosPorJugador());
$state.go('jugar.chico.principal');
}
};
hotkeys.bindTo($scope)
.add({
combo: config.configuracion.keymap.enter,
callback: $scope.iniciar
});
if (!config.puntos)
$state.go('jugar.chico.seleccionPuntos');
$scope.config = config;
$scope.numJugadores = function () {
return Math.min($scope.creditos / config.creditosPorJugador(), 6);
};
$scope.creditosJugador = function (numJugador) {
return $scope.numJugadores() - (numJugador - 1);
};
$scope.creditosExactos = function () {
return $scope.creditos && Math.round($scope.numJugadores()) === $scope.numJugadores() && $scope.numJugadores() > 1;
};
$scope.creditosFaltantes = function () {
if ($scope.numJugadores() == 6)
return false;
return config.creditosPorJugador() - ($scope.creditos % config.creditosPorJugador());
};
$scope.siguienteJugador = function () {
return Math.floor($scope.numJugadores() + 1);
};
$scope.sonido = function(){
var creditos = 'credito'+config.creditosPorJugador();
if(config.equipos)
creditos += '_equipo';
return creditos + '.ogg';
};
var keymap = config.configuracion.keymap;
//para poder terminar temprano el juego
hotkeys.bindTo($scope)
.add({
combo: keymap.arriba + ' ' + keymap.abajo + ' ' + keymap.arriba + ' ' + keymap.abajo + ' ' + keymap.arriba + ' ' + keymap.abajo + ' ' + keymap.enter,
callback: function () {
$state.go('inicio');
}
})
.add({
combo: keymap.arriba,
callback: function(){
if($rootScope.creditos > 0) {
$rootScope.creditosExcedente++;
$rootScope.creditos--;
$rootScope.guardarCreditos();
}
}
})
.add({
combo: keymap.abajo,
callback: function(){
if($rootScope.creditosExcedente > 0) {
$rootScope.creditosExcedente--;
$rootScope.creditos++;
$rootScope.guardarCreditos();
}
}
})
}); | ivanrey/Frosch | app/js/controllers/SeleccionJugadoresCtrl.js | JavaScript | mit | 2,919 |
var gulp = require('gulp');
var yuimd = require('./index');
gulp.task('spies', function() {
// TODO: Use the src stream for input directory.
return gulp.src('gulpfile.js')
.pipe(yuimd({
'projectName': 'Spies',
'$home': '../spies/doc-theme/Home.theme',
'$class': '../spies/doc-theme/class.theme',
'src': './src-spies/'
}))
.pipe(gulp.dest('./doc-spies'));
});
gulp.task('protoboard', function() {
return gulp.src('gulpfile.js')
.pipe(yuimd({
'projectName': 'Protoboard',
'$home': '../protoboard/doc-theme/Home.theme',
'$class': '../protoboard/doc-theme/class.theme',
'src': './src-protoboard/'
}))
.pipe(gulp.dest('./doc-protoboard'));
});
| garysoed/yuimd | gulpfile.js | JavaScript | mit | 748 |
/**
* Base search class for AJAX searching
*/
!function(global, $) {
'use strict';
function ConcreteAjaxSearch($element, options) {
options = options || {};
options = $.extend({
'result': {},
'onLoad': false,
'onUpdateResults': false,
'bulkParameterName': 'item'
}, options);
this.$element = $element;
this.$results = $element.find('div[data-search-element=results]');
this.$resultsTableBody = this.$results.find('tbody');
this.$resultsTableHead = this.$results.find('thead');
this.$resultsPagination = this.$results.find('div.ccm-search-results-pagination');
this.$menuTemplate = $element.find('script[data-template=search-results-menu]');
this.$searchFieldRowTemplate = $element.find('script[data-template=search-field-row]');
this.options = options;
this._templateSearchForm = _.template($element.find('script[data-template=search-form]').html());
this._templateSearchResultsTableHead = _.template($element.find('script[data-template=search-results-table-head]').html());
this._templateSearchResultsTableBody = _.template($element.find('script[data-template=search-results-table-body]').html());
this._templateSearchResultsPagination = _.template($element.find('script[data-template=search-results-pagination]').html());
if (this.$menuTemplate.length) {
this._templateSearchResultsMenu = _.template(this.$menuTemplate.html());
}
if (this.$searchFieldRowTemplate.length) {
this._templateAdvancedSearchFieldRow = _.template(this.$searchFieldRowTemplate.html());
}
this.setupSearch();
this.setupCheckboxes();
this.setupBulkActions();
this.setupSort();
this.setupPagination();
this.setupSelect2();
this.setupAdvancedSearch();
this.setupCustomizeColumns();
this.updateResults(options.result);
if (options.onLoad) {
options.onLoad(this);
}
}
ConcreteAjaxSearch.prototype.ajaxUpdate = function(url, data, callback) {
var cs = this;
$.concreteAjax({
url: url,
data: data,
success: function(r) {
if (!callback) {
cs.updateResults(r);
} else {
callback(r);
}
}
})
}
ConcreteAjaxSearch.prototype.setupSelect2 = function() {
var selects = this.$element.find('.select2-select');
if (selects.length) {
selects.select2();
}
}
ConcreteAjaxSearch.prototype.createMenu = function($selector) {
$selector.concreteMenu({
'menu': $('[data-search-menu=' + $selector.attr('data-launch-search-menu') + ']')
});
}
ConcreteAjaxSearch.prototype.setupMenus = function(result) {
var cs = this;
if (cs._templateSearchResultsMenu) {
cs.$element.find('[data-search-menu]').remove();
// loop through all results,
// create nodes for them.
$.each(result.items, function(i, item) {
cs.$results.append(cs._templateSearchResultsMenu({'item': item}));
});
cs.$element.find('tbody tr').each(function() {
cs.createMenu($(this));
});
}
}
ConcreteAjaxSearch.prototype.setupCustomizeColumns = function() {
var cs = this;
cs.$element.on('click', 'a[data-search-toggle=customize]', function() {
var url = $(this).attr('data-search-column-customize-url');
$.fn.dialog.open({
width: 480,
height: 400,
href: url,
modal: true,
title: ccmi18n.customizeSearch,
onOpen: function() {
var $form = $('form[data-dialog-form=search-customize'),
$selectDefault = $form.find('select[data-search-select-default-column]'),
$columns = $form.find('ul[data-search-column-list]');
$('ul[data-search-column-list]').sortable({
cursor: 'move',
opacity: 0.5
});
$form.on('click', 'input[type=checkbox]', function() {
var label = $(this).parent().find('span').html(),
id = $(this).attr('id');
if ($(this).prop('checked')) {
if ($form.find('li[data-field-order-column=' + id + ']').length == 0) {
$selectDefault.append($('<option>', {'value': id, 'text': label}));
$selectDefault.prop('disabled', false);
$columns.append('<li data-field-order-column="' + id + '"><input type="hidden" name="column[]" value="' + id + '" />' + label + '<\/li>');
}
} else {
$columns.find('li[data-field-order-column=' + id + ']').remove();
$selectDefault.find('option[value=' + id + ']').remove();
if ($columns.find('li').length == 0) {
$selectDefault.prop('disabled', true);
}
}
});
ConcreteEvent.subscribe('AjaxFormSubmitSuccess', function(e, data) {
cs.updateResults(data.response.result);
});
}
});
return false;
});
}
ConcreteAjaxSearch.prototype.updateResults = function(result) {
var cs = this,
options = cs.options;
cs.$resultsTableHead.html(cs._templateSearchResultsTableHead({'columns': result.columns}));
cs.$resultsTableBody.html(cs._templateSearchResultsTableBody({'items': result.items}));
cs.$resultsPagination.html(cs._templateSearchResultsPagination({'paginationTemplate': result.paginationTemplate}));
cs.$advancedFields.html('');
$.each(result.fields, function(i, field) {
cs.$advancedFields.append(cs._templateAdvancedSearchFieldRow({'field': field}));
});
cs.setupMenus(result);
if (options.onUpdateResults) {
options.onUpdateResults(this);
}
}
ConcreteAjaxSearch.prototype.setupAdvancedSearch = function() {
var cs = this;
cs.$advancedFields = cs.$element.find('div.ccm-search-fields-advanced');
cs.$element.on('click', 'a[data-search-toggle=advanced]', function() {
cs.$advancedFields.append(cs._templateAdvancedSearchFieldRow());
return false;
});
cs.$element.on('change', 'select[data-search-field]', function() {
var $content = $(this).parent().find('.ccm-search-field-content');
$content.html('');
var field = $(this).find(':selected').attr('data-search-field-url');
if (field) {
cs.ajaxUpdate(field, false, function(r) {
$content.html(r.html);
});
}
});
cs.$element.on('click', 'a[data-search-remove=search-field]', function() {
var $row = $(this).parent();
$row.remove();
return false;
});
}
ConcreteAjaxSearch.prototype.setupSort = function() {
var cs = this;
this.$element.on('click', 'thead th a', function() {
cs.ajaxUpdate($(this).attr('href'));
return false;
});
}
ConcreteAjaxSearch.prototype.refreshResults = function() {
var cs = this;
cs.$element.find('form[data-search-form]').trigger('submit');
}
ConcreteAjaxSearch.prototype.setupSearch = function() {
var cs = this;
cs.$element.find('[data-search-element=wrapper]').html(cs._templateSearchForm());
cs.$element.on('submit', 'form[data-search-form]', function() {
var data = $(this).serializeArray();
data.push({'name': 'submitSearch', 'value': '1'});
cs.ajaxUpdate($(this).attr('action'), data);
return false;
});
}
ConcreteAjaxSearch.prototype.handleSelectedBulkAction = function(value, type, $option, $items) {
var cs = this,
itemIDs = [];
$.each($items, function(i, checkbox) {
itemIDs.push({'name': cs.options.bulkParameterName + '[]', 'value': $(checkbox).val()});
});
if (type == 'dialog') {
jQuery.fn.dialog.open({
width: $option.attr('data-bulk-action-dialog-width'),
height: $option.attr('data-bulk-action-dialog-height'),
modal: true,
href: $option.attr('data-bulk-action-url') + '?' + jQuery.param(itemIDs),
title: $option.attr('data-bulk-action-title')
});
}
if (type == 'ajax') {
$.concreteAjax({
url: $option.attr('data-bulk-action-url'),
data: itemIDs,
success: function(r) {
if (r.message) {
ConcreteAlert.notify({
'message': r.message,
'title': r.title
});
}
}
});
}
cs.publish('SearchBulkActionSelect', {value: value, option: $option, items: $items});
}
ConcreteAjaxSearch.prototype.publish = function(eventName, data) {
var cs = this;
ConcreteEvent.publish(eventName, data, cs);
}
ConcreteAjaxSearch.prototype.subscribe = function(eventName, callback) {
var cs = this;
ConcreteEvent.subscribe(eventName, callback, cs);
}
ConcreteAjaxSearch.prototype.setupBulkActions = function() {
var cs = this;
cs.$bulkActions = cs.$element.find('select[data-bulk-action]');
cs.$element.on('change', 'select[data-bulk-action]', function() {
var $option = $(this).find('option:selected'),
value = $option.val(),
type = $option.attr('data-bulk-action-type'),
items = [];
cs.handleSelectedBulkAction(value, type, $option, cs.$element.find('input[data-search-checkbox=individual]:checked'));
});
}
ConcreteAjaxSearch.prototype.setupPagination = function() {
var cs = this;
this.$element.on('click', 'ul.pagination a', function() {
cs.ajaxUpdate($(this).attr('href'));
return false;
});
}
ConcreteAjaxSearch.prototype.setupCheckboxes = function() {
var cs = this;
cs.$element.on('click', 'input[data-search-checkbox=select-all]', function() {
cs.$element.find('input[data-search-checkbox=individual]').prop('checked', $(this).is(':checked')).trigger('change');
});
cs.$element.on('change', 'input[data-search-checkbox=individual]', function() {
if (cs.$element.find('input[data-search-checkbox=individual]:checked').length) {
cs.$bulkActions.prop('disabled', false);
} else {
cs.$bulkActions.prop('disabled', true);
}
});
}
// jQuery Plugin
$.fn.concreteAjaxSearch = function(options) {
return new ConcreteAjaxSearch(this, options);
}
global.ConcreteAjaxSearch = ConcreteAjaxSearch;
}(this, $);
| victorli/cms | concrete/js/build/core/app/search/base.js | JavaScript | mit | 9,708 |
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _unexpected = require('unexpected');
var _unexpected2 = _interopRequireDefault(_unexpected);
var _mochaJsdom = require('mocha-jsdom');
var _mochaJsdom2 = _interopRequireDefault(_mochaJsdom);
var _reactAddons = require('react/addons');
var _reactAddons2 = _interopRequireDefault(_reactAddons);
var _index = require('./index');
var _index2 = _interopRequireDefault(_index);
var _AccordionItem = require('../AccordionItem');
var _AccordionItem2 = _interopRequireDefault(_AccordionItem);
var _AccordionItemTitle = require('../AccordionItemTitle');
var _AccordionItemTitle2 = _interopRequireDefault(_AccordionItemTitle);
var TestUtils = _reactAddons2['default'].addons.TestUtils;
describe('Accordion Test Case', function () {
(0, _mochaJsdom2['default'])();
it('should render', function () {
var instance = TestUtils.renderIntoDocument(_reactAddons2['default'].createElement(_index2['default'], null));
(0, _unexpected2['default'])(instance, 'to be defined');
});
describe('selectedIndex', function () {
it('should select the first item as default', function () {
var instance = TestUtils.renderIntoDocument(_reactAddons2['default'].createElement(
_index2['default'],
null,
_reactAddons2['default'].createElement(_AccordionItem2['default'], { title: 'First' }),
_reactAddons2['default'].createElement(_AccordionItem2['default'], { title: 'Second' })
));
var items = TestUtils.scryRenderedComponentsWithType(instance, _AccordionItem2['default']);
(0, _unexpected2['default'])(items[0].props.expanded, 'to be true');
(0, _unexpected2['default'])(items[1].props.expanded, 'to be false');
});
it('should accept a selectedIndex prop', function () {
var instance = TestUtils.renderIntoDocument(_reactAddons2['default'].createElement(
_index2['default'],
{ selectedIndex: 1 },
_reactAddons2['default'].createElement(_AccordionItem2['default'], { title: 'First' }),
_reactAddons2['default'].createElement(_AccordionItem2['default'], { title: 'Second' })
));
var items = TestUtils.scryRenderedComponentsWithType(instance, _AccordionItem2['default']);
(0, _unexpected2['default'])(items[0].props.expanded, 'to be false');
(0, _unexpected2['default'])(items[1].props.expanded, 'to be true');
});
});
describe('allowMultiple', function () {
it('should allow multiple expanded items', function () {
var instance = TestUtils.renderIntoDocument(_reactAddons2['default'].createElement(
_index2['default'],
{ selectedIndex: 1, allowMultiple: true },
_reactAddons2['default'].createElement(_AccordionItem2['default'], { title: 'First' }),
_reactAddons2['default'].createElement(_AccordionItem2['default'], { title: 'Second' })
));
var items = TestUtils.scryRenderedComponentsWithType(instance, _AccordionItem2['default']);
var title = TestUtils.findRenderedComponentWithType(items[0], _AccordionItemTitle2['default']);
(0, _unexpected2['default'])(items[0].props.expanded, 'to be false');
(0, _unexpected2['default'])(items[1].props.expanded, 'to be true');
TestUtils.Simulate.click(_reactAddons2['default'].findDOMNode(title));
(0, _unexpected2['default'])(items[0].props.expanded, 'to be true');
(0, _unexpected2['default'])(items[1].props.expanded, 'to be true');
});
it('should save activeItems on state when allowMultiple is true', function () {
var instance = TestUtils.renderIntoDocument(_reactAddons2['default'].createElement(
_index2['default'],
{ selectedIndex: 1, allowMultiple: true },
_reactAddons2['default'].createElement(_AccordionItem2['default'], { title: 'First' }),
_reactAddons2['default'].createElement(_AccordionItem2['default'], { title: 'Second' })
));
(0, _unexpected2['default'])(instance.state.activeItems, 'to equal', [1]);
});
it('should update activeItems state when clicking on an item', function () {
var instance = TestUtils.renderIntoDocument(_reactAddons2['default'].createElement(
_index2['default'],
{ selectedIndex: 1, allowMultiple: true },
_reactAddons2['default'].createElement(_AccordionItem2['default'], { title: 'First' }),
_reactAddons2['default'].createElement(_AccordionItem2['default'], { title: 'Second' })
));
var items = TestUtils.scryRenderedComponentsWithType(instance, _AccordionItem2['default']);
var title = TestUtils.findRenderedComponentWithType(items[0], _AccordionItemTitle2['default']);
(0, _unexpected2['default'])(instance.state.activeItems, 'to equal', [1]);
TestUtils.Simulate.click(_reactAddons2['default'].findDOMNode(title));
(0, _unexpected2['default'])(instance.state.activeItems, 'to equal', [1, 0]);
});
});
}); | clemsos/react-sanfona | dist-modules/Accordion/test.js | JavaScript | mit | 5,012 |
/// <reference path="../lib/jquery-2.0.3.js" />
define(["jquery","class"], function ($, Class) {
var TableView = Class.create({
// settings is an object of type {rows:5, cols: 3} || {rows:3} || {cols:4}
// if not provided it calculates the rows and cols
// if rows provided calculates cols
// if cols provided calculates rows
init: function (itemsSource, settings) {
if (!(itemsSource instanceof Array)) {
throw "The itemsSource of a ListView must be an array!";
}
this.itemsSource = itemsSource;
var len = itemsSource.length;
var rows = 0;
var cols = 0;
if (!settings || (!settings.rows && !settings.cols)) {
var sqrtLen = Math.sqrt(len);
cols = Math.ceil(sqrtLen);
rows = Math.floor(sqrtLen);
}
else if (!settings.cols) {
cols = Math.ceil(len / settings.rows);
}
else {
cols = settings.cols;
}
//this.rows = rows;
this.cols = cols;
},
render: function (template) {
var table = document.createElement("table");
var len = this.itemsSource.length;
var tr = "";
var elements = 0;
if (len === 0) {
return "<h1>Empty students list recieved from server. Refresh</h1>";
}
for (var i = 0; i < len; i++) {
var item = this.itemsSource[i];
tr += "<td>" + template(item); + "</td>";
elements++;
if (elements == this.cols || i == len - 1) {
table.innerHTML += "" + tr;
elements = 0;
tr = "";
}
}
return table.outerHTML;
}
});
var ListView = Class.create({
init: function (itemsSource) {
if (!(itemsSource instanceof Array)) {
throw "The itemsSource of a ListView must be an array!";
}
this.itemsSource = itemsSource;
},
render: function (template) {
if (this.itemsSource.length === 0) {
return "<h1>Empty students list recieved from server. Refresh</h1>";
}
var list = document.createElement("ul");
for (var i = 0; i < this.itemsSource.length; i++) {
var listItem = document.createElement("li");
var item = this.itemsSource[i];
listItem.innerHTML = template(item);
list.appendChild(listItem);
}
return list.outerHTML;
}
});
//<div id="combo-box">
// <div id="content"></div>
// <div id="arrow-down"></div>
// <div id="other-elements"></div>
//</div>
var ComboBoxView = Class.create({
itemsSource: {},
container: {},
content: {},
//hiddenItems:,
init: function (container, itemsSource) {
if (!(itemsSource instanceof Array)) {
throw "The itemsSource of a ListView must be an array!";
}
this.container = $(container);
this.itemsSource = itemsSource;
},
render: function (template) {
var comboBoxContainer = document.createDocumentFragment();
this.content = $("<div id='combo-box-content'/>");
//this.content.id = "";
this.hiddenItems = $("<div id='hidden-items'/>").hide();
//this.hiddenItems.id = "";
var firstStudentHtml = template(this.itemsSource[0])
this.content.html(firstStudentHtml);
var hiddenItems = "";
for (var i = 0; i < this.itemsSource.length; i++) {
hiddenItems += "<div class='combo-box-element'>" + template(this.itemsSource[i]) + "</div>";
}
if (!this.hiddenItems) {
this.hiddenItems = $("#hidden-items")
}
this.hiddenItems.html(hiddenItems);
this.container.append(this.content).append(this.hiddenItems);
this.initEvents();
},
initEvents: function () {
var self = this;
this.container.on("click", "#combo-box-content", function () {
self.hiddenItems.toggle("slow");
});
this.container.on("click", ".combo-box-element", function () {
self.content.html($(this).html());
self.hiddenItems.toggle("slow");
});
}
});
// gets an itemSource(array) and optional settings Object
return {
getTableView: function (itemsSource, settings) {
return new TableView(itemsSource, settings);
},
getListView: function (itemsSource) {
return new ListView(itemsSource);
},
getComboBoxView: function (container, itemsSource) {
return new ComboBoxView(container, itemsSource);
}
}
}); | gparlakov/js-frameworks | 5.RequireJs/Students/scripts/app/view.js | JavaScript | mit | 5,304 |
"use strict"
const url = "https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&photoset_id=72157689349104906&user_id=126785613%40N04&extras=original_format&format=json&nojsoncallback=1&api_key=9f46232676650675ddd2cc7bf3ca979d";
const carousel = document.querySelector("#carousel");
const link = document.getElementById("link");
const download = document.getElementById("download");
const left = document.querySelectorAll("button.flip.left")[0];
const right = document.querySelectorAll("button.flip.right")[0];
const leftIcon = document.querySelectorAll("i.left.material-icons.md-light")[0];
const rightIcon = document.querySelectorAll("i.right.material-icons.md-light")[0];
var photoArr = [];
var index = 0;
function getData(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function (error, response, data) {
var data = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == 200) {
callback(data);
} else {
console.error(data);
}
}
xhr.send(null);
}
function loadUrls(data) {
var photos = data.photoset.photo;
for (var i = 0; i < photos.length; i++) {
var photo = {};
photo.id = photos[i].id;
photo.url = "https://farm" + photos[i].farm + ".staticflickr.com/" + photos[i].server + "/" + photos[i].id + "_" + photos[i].secret + "_b.jpg";
photo.original = "https://farm" + photos[i].farm + ".staticflickr.com/" + photos[i].server + "/" + photos[i].id + "_" + photos[i].originalsecret + "_o." + photos[i].originalformat;
photo.title = photos[i].title;
photoArr.push(photo);
}
var urlString = "url('" + photoArr[0].url + "')";
carousel.style.backgroundImage = urlString;
link.href = "https://flickr.com/photos/" + data.photoset.owner + "/" + photoArr[0].id + "/in/album-" + data.photoset.id;
var dlUrl = photoArr[index].original.replace("_o", "_o_d");
download.href = dlUrl;
leftIcon.classList.add("md-inactive");
left.onclick = function () {
if (index > 0) {
index--;
var urlString = "url('" + photoArr[index].url + "')";
carousel.style.backgroundImage = urlString;
link.href = "https://flickr.com/photos/" + data.photoset.owner + "/" + photoArr[index].id + "/in/album-" + data.photoset.id;
var dlUrl = photoArr[index].original.replace("_o", "_o_d");
download.href = dlUrl;
if (index == 0 && !leftIcon.classList.contains("md-inactive")) {
leftIcon.classList.add("md-inactive");
} else {
leftIcon.classList.remove("md-inactive");
if (index != photoArr.length - 1 && photoArr.length > 1) {
rightIcon.classList.remove("md-inactive");
}
}
}
}
right.onclick = function () {
if (index < photoArr.length - 1) {
index++;
var urlString = "url('" + photoArr[index].url + "')";
carousel.style.backgroundImage = urlString;
link.href = "https://flickr.com/photos/" + data.photoset.owner + "/" + photoArr[index].id + "/in/album-" + data.photoset.id;
var dlUrl = photoArr[index].original.replace("_o", "_o_d");
download.href = dlUrl;
if (index == photoArr.length - 1 && !rightIcon.classList.contains("md-inactive")) {
rightIcon.classList.add("md-inactive");
if (index != 0 && photoArr.length > 1) {
leftIcon.classList.remove("md-inactive");
}
} else {
rightIcon.classList.remove("md-inactive");
if (index != 0 && photoArr.length > 1) {
leftIcon.classList.remove("md-inactive");
}
}
}
}
}
getData(url, loadUrls); | willzhang05/wzhang.me | scripts/gallery.js | JavaScript | mit | 3,917 |
// middleware
var bodyParser = require('body-parser'),
methodOverride = require('method-override');
var favicon = require('serve-favicon'),
serveStatic = require('serve-static');
var app = require('../app.js');
var pathMap = require('../config/').pathMap;
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// use HTTP verbs with fallback on "X-HTTP-Method-Override" header
app.use(methodOverride());
// static middleware
app.use(serveStatic('assets'));
app.use(serveStatic('public'));
// serve favicon
app.use(favicon(pathMap.favicon));
| chehopar/game | core/middleware.js | JavaScript | mit | 653 |
'use strict';
//system
//var fs = require('fs');
//var http = require('http');
//middleware
/*
var connect = require('connect');
var quip = require('quip');
var passport = require('passport');
var poweredBy = require('connect-powered-by');
var merge = require('deepmerge');
var bodyParser = require('body-parser');
var request = require('./libs/request');
*/
//DI
var DIFactory = require('dependency-injection/DIFactory');
var Configuration = require('dependency-injection/Configuration');
var Helpers = require('dependency-injection/lib/Helpers');
//Tools
//var HttpStatus = require('http-status-codes');
//var async = require('async');
//Router
var Router = require('barista').Router;
var router = new Router;
//Default config
var configuration = new Configuration;
//default config have to figure out the paths
configuration.addConfig('./config/config.json');
var App = require('./libs/app');
module.exports.DIFactory = DIFactory;
module.exports.configuration = configuration;
module.exports.router = router;
module.exports.App = App;
/*
var server = http.createServer(app).listen(parameters.server.port, parameters.server.host, function() {
var address = server.address();
logger.info("server listening on %s:%s", address.address, address.port);
});
*/ | bazo/mazagran | index.js | JavaScript | mit | 1,270 |
// We don't use the platform bootstrapper, so fake this stuff.
window.Platform = {};
var logFlags = {};
// DOMTokenList polyfill for IE9
(function () {
if (typeof window.Element === "undefined" || "classList" in document.documentElement) return;
var prototype = Array.prototype,
indexOf = prototype.indexOf,
slice = prototype.slice,
push = prototype.push,
splice = prototype.splice,
join = prototype.join;
function DOMTokenList(el) {
this._element = el;
if (el.className != this._classCache) {
this._classCache = el.className;
if (!this._classCache) return;
// The className needs to be trimmed and split on whitespace
// to retrieve a list of classes.
var classes = this._classCache.replace(/^\s+|\s+$/g,'').split(/\s+/),
i;
for (i = 0; i < classes.length; i++) {
push.call(this, classes[i]);
}
}
};
function setToClassName(el, classes) {
el.className = classes.join(' ');
}
DOMTokenList.prototype = {
add: function(token) {
if(this.contains(token)) return;
push.call(this, token);
setToClassName(this._element, slice.call(this, 0));
},
contains: function(token) {
return indexOf.call(this, token) !== -1;
},
item: function(index) {
return this[index] || null;
},
remove: function(token) {
var i = indexOf.call(this, token);
if (i === -1) {
return;
}
splice.call(this, i, 1);
setToClassName(this._element, slice.call(this, 0));
},
toString: function() {
return join.call(this, ' ');
},
toggle: function(token) {
if (indexOf.call(this, token) === -1) {
this.add(token);
} else {
this.remove(token);
}
}
};
window.DOMTokenList = DOMTokenList;
function defineElementGetter (obj, prop, getter) {
if (Object.defineProperty) {
Object.defineProperty(obj, prop,{
get : getter
})
} else {
obj.__defineGetter__(prop, getter);
}
}
defineElementGetter(Element.prototype, 'classList', function () {
return new DOMTokenList(this);
});
})();
/*
* Copyright 2012 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
if (typeof WeakMap === 'undefined') {
(function() {
var defineProperty = Object.defineProperty;
var counter = Date.now() % 1e9;
var WeakMap = function() {
this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__');
};
WeakMap.prototype = {
set: function(key, value) {
var entry = key[this.name];
if (entry && entry[0] === key)
entry[1] = value;
else
defineProperty(key, this.name, {value: [key, value], writable: true});
},
get: function(key) {
var entry;
return (entry = key[this.name]) && entry[0] === key ?
entry[1] : undefined;
},
delete: function(key) {
this.set(key, undefined);
}
};
window.WeakMap = WeakMap;
})();
}
/*
* Copyright 2012 The Polymer Authors. All rights reserved.
* Use of this source code is goverened by a BSD-style
* license that can be found in the LICENSE file.
*/
(function(global) {
var registrationsTable = new WeakMap();
// We use setImmediate or postMessage for our future callback.
var setImmediate = window.msSetImmediate;
// Use post message to emulate setImmediate.
if (!setImmediate) {
var setImmediateQueue = [];
var sentinel = String(Math.random());
window.addEventListener('message', function(e) {
if (e.data === sentinel) {
var queue = setImmediateQueue;
setImmediateQueue = [];
queue.forEach(function(func) {
func();
});
}
});
setImmediate = function(func) {
setImmediateQueue.push(func);
window.postMessage(sentinel, '*');
};
}
// This is used to ensure that we never schedule 2 callas to setImmediate
var isScheduled = false;
// Keep track of observers that needs to be notified next time.
var scheduledObservers = [];
/**
* Schedules |dispatchCallback| to be called in the future.
* @param {MutationObserver} observer
*/
function scheduleCallback(observer) {
scheduledObservers.push(observer);
if (!isScheduled) {
isScheduled = true;
setImmediate(dispatchCallbacks);
}
}
function wrapIfNeeded(node) {
return window.ShadowDOMPolyfill &&
window.ShadowDOMPolyfill.wrapIfNeeded(node) ||
node;
}
function dispatchCallbacks() {
// http://dom.spec.whatwg.org/#mutation-observers
isScheduled = false; // Used to allow a new setImmediate call above.
var observers = scheduledObservers;
scheduledObservers = [];
// Sort observers based on their creation UID (incremental).
observers.sort(function(o1, o2) {
return o1.uid_ - o2.uid_;
});
var anyNonEmpty = false;
observers.forEach(function(observer) {
// 2.1, 2.2
var queue = observer.takeRecords();
// 2.3. Remove all transient registered observers whose observer is mo.
removeTransientObserversFor(observer);
// 2.4
if (queue.length) {
observer.callback_(queue, observer);
anyNonEmpty = true;
}
});
// 3.
if (anyNonEmpty)
dispatchCallbacks();
}
function removeTransientObserversFor(observer) {
observer.nodes_.forEach(function(node) {
var registrations = registrationsTable.get(node);
if (!registrations)
return;
registrations.forEach(function(registration) {
if (registration.observer === observer)
registration.removeTransientObservers();
});
});
}
/**
* This function is used for the "For each registered observer observer (with
* observer's options as options) in target's list of registered observers,
* run these substeps:" and the "For each ancestor ancestor of target, and for
* each registered observer observer (with options options) in ancestor's list
* of registered observers, run these substeps:" part of the algorithms. The
* |options.subtree| is checked to ensure that the callback is called
* correctly.
*
* @param {Node} target
* @param {function(MutationObserverInit):MutationRecord} callback
*/
function forEachAncestorAndObserverEnqueueRecord(target, callback) {
for (var node = target; node; node = node.parentNode) {
var registrations = registrationsTable.get(node);
if (registrations) {
for (var j = 0; j < registrations.length; j++) {
var registration = registrations[j];
var options = registration.options;
// Only target ignores subtree.
if (node !== target && !options.subtree)
continue;
var record = callback(options);
if (record)
registration.enqueue(record);
}
}
}
}
var uidCounter = 0;
/**
* The class that maps to the DOM MutationObserver interface.
* @param {Function} callback.
* @constructor
*/
function JsMutationObserver(callback) {
this.callback_ = callback;
this.nodes_ = [];
this.records_ = [];
this.uid_ = ++uidCounter;
}
JsMutationObserver.prototype = {
observe: function(target, options) {
target = wrapIfNeeded(target);
// 1.1
if (!options.childList && !options.attributes && !options.characterData ||
// 1.2
options.attributeOldValue && !options.attributes ||
// 1.3
options.attributeFilter && options.attributeFilter.length &&
!options.attributes ||
// 1.4
options.characterDataOldValue && !options.characterData) {
throw new SyntaxError();
}
var registrations = registrationsTable.get(target);
if (!registrations)
registrationsTable.set(target, registrations = []);
// 2
// If target's list of registered observers already includes a registered
// observer associated with the context object, replace that registered
// observer's options with options.
var registration;
for (var i = 0; i < registrations.length; i++) {
if (registrations[i].observer === this) {
registration = registrations[i];
registration.removeListeners();
registration.options = options;
break;
}
}
// 3.
// Otherwise, add a new registered observer to target's list of registered
// observers with the context object as the observer and options as the
// options, and add target to context object's list of nodes on which it
// is registered.
if (!registration) {
registration = new Registration(this, target, options);
registrations.push(registration);
this.nodes_.push(target);
}
registration.addListeners();
},
disconnect: function() {
this.nodes_.forEach(function(node) {
var registrations = registrationsTable.get(node);
for (var i = 0; i < registrations.length; i++) {
var registration = registrations[i];
if (registration.observer === this) {
registration.removeListeners();
registrations.splice(i, 1);
// Each node can only have one registered observer associated with
// this observer.
break;
}
}
}, this);
this.records_ = [];
},
takeRecords: function() {
var copyOfRecords = this.records_;
this.records_ = [];
return copyOfRecords;
}
};
/**
* @param {string} type
* @param {Node} target
* @constructor
*/
function MutationRecord(type, target) {
this.type = type;
this.target = target;
this.addedNodes = [];
this.removedNodes = [];
this.previousSibling = null;
this.nextSibling = null;
this.attributeName = null;
this.attributeNamespace = null;
this.oldValue = null;
}
function copyMutationRecord(original) {
var record = new MutationRecord(original.type, original.target);
record.addedNodes = original.addedNodes.slice();
record.removedNodes = original.removedNodes.slice();
record.previousSibling = original.previousSibling;
record.nextSibling = original.nextSibling;
record.attributeName = original.attributeName;
record.attributeNamespace = original.attributeNamespace;
record.oldValue = original.oldValue;
return record;
};
// We keep track of the two (possibly one) records used in a single mutation.
var currentRecord, recordWithOldValue;
/**
* Creates a record without |oldValue| and caches it as |currentRecord| for
* later use.
* @param {string} oldValue
* @return {MutationRecord}
*/
function getRecord(type, target) {
return currentRecord = new MutationRecord(type, target);
}
/**
* Gets or creates a record with |oldValue| based in the |currentRecord|
* @param {string} oldValue
* @return {MutationRecord}
*/
function getRecordWithOldValue(oldValue) {
if (recordWithOldValue)
return recordWithOldValue;
recordWithOldValue = copyMutationRecord(currentRecord);
recordWithOldValue.oldValue = oldValue;
return recordWithOldValue;
}
function clearRecords() {
currentRecord = recordWithOldValue = undefined;
}
/**
* @param {MutationRecord} record
* @return {boolean} Whether the record represents a record from the current
* mutation event.
*/
function recordRepresentsCurrentMutation(record) {
return record === recordWithOldValue || record === currentRecord;
}
/**
* Selects which record, if any, to replace the last record in the queue.
* This returns |null| if no record should be replaced.
*
* @param {MutationRecord} lastRecord
* @param {MutationRecord} newRecord
* @param {MutationRecord}
*/
function selectRecord(lastRecord, newRecord) {
if (lastRecord === newRecord)
return lastRecord;
// Check if the the record we are adding represents the same record. If
// so, we keep the one with the oldValue in it.
if (recordWithOldValue && recordRepresentsCurrentMutation(lastRecord))
return recordWithOldValue;
return null;
}
/**
* Class used to represent a registered observer.
* @param {MutationObserver} observer
* @param {Node} target
* @param {MutationObserverInit} options
* @constructor
*/
function Registration(observer, target, options) {
this.observer = observer;
this.target = target;
this.options = options;
this.transientObservedNodes = [];
}
Registration.prototype = {
enqueue: function(record) {
var records = this.observer.records_;
var length = records.length;
// There are cases where we replace the last record with the new record.
// For example if the record represents the same mutation we need to use
// the one with the oldValue. If we get same record (this can happen as we
// walk up the tree) we ignore the new record.
if (records.length > 0) {
var lastRecord = records[length - 1];
var recordToReplaceLast = selectRecord(lastRecord, record);
if (recordToReplaceLast) {
records[length - 1] = recordToReplaceLast;
return;
}
} else {
scheduleCallback(this.observer);
}
records[length] = record;
},
addListeners: function() {
this.addListeners_(this.target);
},
addListeners_: function(node) {
var options = this.options;
if (options.attributes)
node.addEventListener('DOMAttrModified', this, true);
if (options.characterData)
node.addEventListener('DOMCharacterDataModified', this, true);
if (options.childList)
node.addEventListener('DOMNodeInserted', this, true);
if (options.childList || options.subtree)
node.addEventListener('DOMNodeRemoved', this, true);
},
removeListeners: function() {
this.removeListeners_(this.target);
},
removeListeners_: function(node) {
var options = this.options;
if (options.attributes)
node.removeEventListener('DOMAttrModified', this, true);
if (options.characterData)
node.removeEventListener('DOMCharacterDataModified', this, true);
if (options.childList)
node.removeEventListener('DOMNodeInserted', this, true);
if (options.childList || options.subtree)
node.removeEventListener('DOMNodeRemoved', this, true);
},
/**
* Adds a transient observer on node. The transient observer gets removed
* next time we deliver the change records.
* @param {Node} node
*/
addTransientObserver: function(node) {
// Don't add transient observers on the target itself. We already have all
// the required listeners set up on the target.
if (node === this.target)
return;
this.addListeners_(node);
this.transientObservedNodes.push(node);
var registrations = registrationsTable.get(node);
if (!registrations)
registrationsTable.set(node, registrations = []);
// We know that registrations does not contain this because we already
// checked if node === this.target.
registrations.push(this);
},
removeTransientObservers: function() {
var transientObservedNodes = this.transientObservedNodes;
this.transientObservedNodes = [];
transientObservedNodes.forEach(function(node) {
// Transient observers are never added to the target.
this.removeListeners_(node);
var registrations = registrationsTable.get(node);
for (var i = 0; i < registrations.length; i++) {
if (registrations[i] === this) {
registrations.splice(i, 1);
// Each node can only have one registered observer associated with
// this observer.
break;
}
}
}, this);
},
handleEvent: function(e) {
// Stop propagation since we are managing the propagation manually.
// This means that other mutation events on the page will not work
// correctly but that is by design.
e.stopImmediatePropagation();
switch (e.type) {
case 'DOMAttrModified':
// http://dom.spec.whatwg.org/#concept-mo-queue-attributes
var name = e.attrName;
var namespace = e.relatedNode.namespaceURI;
var target = e.target;
// 1.
var record = new getRecord('attributes', target);
record.attributeName = name;
record.attributeNamespace = namespace;
// 2.
var oldValue =
e.attrChange === MutationEvent.ADDITION ? null : e.prevValue;
forEachAncestorAndObserverEnqueueRecord(target, function(options) {
// 3.1, 4.2
if (!options.attributes)
return;
// 3.2, 4.3
if (options.attributeFilter && options.attributeFilter.length &&
options.attributeFilter.indexOf(name) === -1 &&
options.attributeFilter.indexOf(namespace) === -1) {
return;
}
// 3.3, 4.4
if (options.attributeOldValue)
return getRecordWithOldValue(oldValue);
// 3.4, 4.5
return record;
});
break;
case 'DOMCharacterDataModified':
// http://dom.spec.whatwg.org/#concept-mo-queue-characterdata
var target = e.target;
// 1.
var record = getRecord('characterData', target);
// 2.
var oldValue = e.prevValue;
forEachAncestorAndObserverEnqueueRecord(target, function(options) {
// 3.1, 4.2
if (!options.characterData)
return;
// 3.2, 4.3
if (options.characterDataOldValue)
return getRecordWithOldValue(oldValue);
// 3.3, 4.4
return record;
});
break;
case 'DOMNodeRemoved':
this.addTransientObserver(e.target);
// Fall through.
case 'DOMNodeInserted':
// http://dom.spec.whatwg.org/#concept-mo-queue-childlist
var target = e.relatedNode;
var changedNode = e.target;
var addedNodes, removedNodes;
if (e.type === 'DOMNodeInserted') {
addedNodes = [changedNode];
removedNodes = [];
} else {
addedNodes = [];
removedNodes = [changedNode];
}
var previousSibling = changedNode.previousSibling;
var nextSibling = changedNode.nextSibling;
// 1.
var record = getRecord('childList', target);
record.addedNodes = addedNodes;
record.removedNodes = removedNodes;
record.previousSibling = previousSibling;
record.nextSibling = nextSibling;
forEachAncestorAndObserverEnqueueRecord(target, function(options) {
// 2.1, 3.2
if (!options.childList)
return;
// 2.2, 3.3
return record;
});
}
clearRecords();
}
};
global.JsMutationObserver = JsMutationObserver;
if (!global.MutationObserver)
global.MutationObserver = JsMutationObserver;
})(this);
/*
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
/**
* Implements `document.registerElement`
* @module CustomElements
*/
/**
* Polyfilled extensions to the `document` object.
* @class Document
*/
(function(scope) {
// imports
if (!scope) {
scope = window.CustomElements = {flags:{}};
}
var flags = scope.flags;
// native document.registerElement?
var hasNative = Boolean(document.registerElement);
// For consistent timing, use native custom elements only when not polyfilling
// other key related web components features.
var useNative = !flags.register && hasNative && !window.ShadowDOMPolyfill && (!window.HTMLImports || HTMLImports.useNative);
if (useNative) {
// stub
var nop = function() {};
// exports
scope.registry = {};
scope.upgradeElement = nop;
scope.watchShadow = nop;
scope.upgrade = nop;
scope.upgradeAll = nop;
scope.upgradeSubtree = nop;
scope.observeDocument = nop;
scope.upgradeDocument = nop;
scope.upgradeDocumentTree = nop;
scope.takeRecords = nop;
scope.reservedTagList = [];
} else {
/**
* Registers a custom tag name with the document.
*
* When a registered element is created, a `readyCallback` method is called
* in the scope of the element. The `readyCallback` method can be specified on
* either `options.prototype` or `options.lifecycle` with the latter taking
* precedence.
*
* @method register
* @param {String} name The tag name to register. Must include a dash ('-'),
* for example 'x-component'.
* @param {Object} options
* @param {String} [options.extends]
* (_off spec_) Tag name of an element to extend (or blank for a new
* element). This parameter is not part of the specification, but instead
* is a hint for the polyfill because the extendee is difficult to infer.
* Remember that the input prototype must chain to the extended element's
* prototype (or HTMLElement.prototype) regardless of the value of
* `extends`.
* @param {Object} options.prototype The prototype to use for the new
* element. The prototype must inherit from HTMLElement.
* @param {Object} [options.lifecycle]
* Callbacks that fire at important phases in the life of the custom
* element.
*
* @example
* FancyButton = document.registerElement("fancy-button", {
* extends: 'button',
* prototype: Object.create(HTMLButtonElement.prototype, {
* readyCallback: {
* value: function() {
* console.log("a fancy-button was created",
* }
* }
* })
* });
* @return {Function} Constructor for the newly registered type.
*/
function register(name, options) {
//console.warn('document.registerElement("' + name + '", ', options, ')');
// construct a defintion out of options
// TODO(sjmiles): probably should clone options instead of mutating it
var definition = options || {};
if (!name) {
// TODO(sjmiles): replace with more appropriate error (EricB can probably
// offer guidance)
throw new Error('document.registerElement: first argument `name` must not be empty');
}
if (name.indexOf('-') < 0) {
// TODO(sjmiles): replace with more appropriate error (EricB can probably
// offer guidance)
throw new Error('document.registerElement: first argument (\'name\') must contain a dash (\'-\'). Argument provided was \'' + String(name) + '\'.');
}
// prevent registering reserved names
if (isReservedTag(name)) {
throw new Error('Failed to execute \'registerElement\' on \'Document\': Registration failed for type \'' + String(name) + '\'. The type name is invalid.');
}
// elements may only be registered once
if (getRegisteredDefinition(name)) {
throw new Error('DuplicateDefinitionError: a type with name \'' + String(name) + '\' is already registered');
}
// must have a prototype, default to an extension of HTMLElement
// TODO(sjmiles): probably should throw if no prototype, check spec
if (!definition.prototype) {
// TODO(sjmiles): replace with more appropriate error (EricB can probably
// offer guidance)
throw new Error('Options missing required prototype property');
}
// record name
definition.__name = name.toLowerCase();
// ensure a lifecycle object so we don't have to null test it
definition.lifecycle = definition.lifecycle || {};
// build a list of ancestral custom elements (for native base detection)
// TODO(sjmiles): we used to need to store this, but current code only
// uses it in 'resolveTagName': it should probably be inlined
definition.ancestry = ancestry(definition.extends);
// extensions of native specializations of HTMLElement require localName
// to remain native, and use secondary 'is' specifier for extension type
resolveTagName(definition);
// some platforms require modifications to the user-supplied prototype
// chain
resolvePrototypeChain(definition);
// overrides to implement attributeChanged callback
overrideAttributeApi(definition.prototype);
// 7.1.5: Register the DEFINITION with DOCUMENT
registerDefinition(definition.__name, definition);
// 7.1.7. Run custom element constructor generation algorithm with PROTOTYPE
// 7.1.8. Return the output of the previous step.
definition.ctor = generateConstructor(definition);
definition.ctor.prototype = definition.prototype;
// force our .constructor to be our actual constructor
definition.prototype.constructor = definition.ctor;
// if initial parsing is complete
if (scope.ready) {
// upgrade any pre-existing nodes of this type
scope.upgradeDocumentTree(document);
}
return definition.ctor;
}
function isReservedTag(name) {
for (var i = 0; i < reservedTagList.length; i++) {
if (name === reservedTagList[i]) {
return true;
}
}
}
var reservedTagList = [
'annotation-xml', 'color-profile', 'font-face', 'font-face-src',
'font-face-uri', 'font-face-format', 'font-face-name', 'missing-glyph'
];
function ancestry(extnds) {
var extendee = getRegisteredDefinition(extnds);
if (extendee) {
return ancestry(extendee.extends).concat([extendee]);
}
return [];
}
function resolveTagName(definition) {
// if we are explicitly extending something, that thing is our
// baseTag, unless it represents a custom component
var baseTag = definition.extends;
// if our ancestry includes custom components, we only have a
// baseTag if one of them does
for (var i=0, a; (a=definition.ancestry[i]); i++) {
baseTag = a.is && a.tag;
}
// our tag is our baseTag, if it exists, and otherwise just our name
definition.tag = baseTag || definition.__name;
if (baseTag) {
// if there is a base tag, use secondary 'is' specifier
definition.is = definition.__name;
}
}
function resolvePrototypeChain(definition) {
// if we don't support __proto__ we need to locate the native level
// prototype for precise mixing in
if (!Object.__proto__) {
// default prototype
var nativePrototype = HTMLElement.prototype;
// work out prototype when using type-extension
if (definition.is) {
var inst = document.createElement(definition.tag);
var expectedPrototype = Object.getPrototypeOf(inst);
// only set nativePrototype if it will actually appear in the definition's chain
if (expectedPrototype === definition.prototype) {
nativePrototype = expectedPrototype;
}
}
// ensure __proto__ reference is installed at each point on the prototype
// chain.
// NOTE: On platforms without __proto__, a mixin strategy is used instead
// of prototype swizzling. In this case, this generated __proto__ provides
// limited support for prototype traversal.
var proto = definition.prototype, ancestor;
while (proto && (proto !== nativePrototype)) {
ancestor = Object.getPrototypeOf(proto);
proto.__proto__ = ancestor;
proto = ancestor;
}
// cache this in case of mixin
definition.native = nativePrototype;
}
}
// SECTION 4
function instantiate(definition) {
// 4.a.1. Create a new object that implements PROTOTYPE
// 4.a.2. Let ELEMENT by this new object
//
// the custom element instantiation algorithm must also ensure that the
// output is a valid DOM element with the proper wrapper in place.
//
return upgrade(domCreateElement(definition.tag), definition);
}
function upgrade(element, definition) {
// some definitions specify an 'is' attribute
if (definition.is) {
element.setAttribute('is', definition.is);
}
// make 'element' implement definition.prototype
implement(element, definition);
// flag as upgraded
element.__upgraded__ = true;
// lifecycle management
created(element);
// attachedCallback fires in tree order, call before recursing
scope.insertedNode(element);
// there should never be a shadow root on element at this point
scope.upgradeSubtree(element);
// OUTPUT
return element;
}
function implement(element, definition) {
// prototype swizzling is best
if (Object.__proto__) {
element.__proto__ = definition.prototype;
} else {
// where above we can re-acquire inPrototype via
// getPrototypeOf(Element), we cannot do so when
// we use mixin, so we install a magic reference
customMixin(element, definition.prototype, definition.native);
element.__proto__ = definition.prototype;
}
}
function customMixin(inTarget, inSrc, inNative) {
// TODO(sjmiles): 'used' allows us to only copy the 'youngest' version of
// any property. This set should be precalculated. We also need to
// consider this for supporting 'super'.
var used = {};
// start with inSrc
var p = inSrc;
// The default is HTMLElement.prototype, so we add a test to avoid mixing in
// native prototypes
while (p !== inNative && p !== HTMLElement.prototype) {
var keys = Object.getOwnPropertyNames(p);
for (var i=0, k; k=keys[i]; i++) {
if (!used[k]) {
Object.defineProperty(inTarget, k,
Object.getOwnPropertyDescriptor(p, k));
used[k] = 1;
}
}
p = Object.getPrototypeOf(p);
}
}
function created(element) {
// invoke createdCallback
if (element.createdCallback) {
element.createdCallback();
}
}
// attribute watching
function overrideAttributeApi(prototype) {
// overrides to implement callbacks
// TODO(sjmiles): should support access via .attributes NamedNodeMap
// TODO(sjmiles): preserves user defined overrides, if any
if (prototype.setAttribute._polyfilled) {
return;
}
var setAttribute = prototype.setAttribute;
prototype.setAttribute = function(name, value) {
changeAttribute.call(this, name, value, setAttribute);
}
var removeAttribute = prototype.removeAttribute;
prototype.removeAttribute = function(name) {
changeAttribute.call(this, name, null, removeAttribute);
}
prototype.setAttribute._polyfilled = true;
}
// https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/custom/
// index.html#dfn-attribute-changed-callback
function changeAttribute(name, value, operation) {
name = name.toLowerCase();
var oldValue = this.getAttribute(name);
operation.apply(this, arguments);
var newValue = this.getAttribute(name);
if (this.attributeChangedCallback
&& (newValue !== oldValue)) {
this.attributeChangedCallback(name, oldValue, newValue);
}
}
// element registry (maps tag names to definitions)
var registry = {};
function getRegisteredDefinition(name) {
if (name) {
return registry[name.toLowerCase()];
}
}
function registerDefinition(name, definition) {
registry[name] = definition;
}
function generateConstructor(definition) {
return function() {
return instantiate(definition);
};
}
var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
function createElementNS(namespace, tag, typeExtension) {
// NOTE: we do not support non-HTML elements,
// just call createElementNS for non HTML Elements
if (namespace === HTML_NAMESPACE) {
return createElement(tag, typeExtension);
} else {
return domCreateElementNS(namespace, tag);
}
}
function createElement(tag, typeExtension) {
// TODO(sjmiles): ignore 'tag' when using 'typeExtension', we could
// error check it, or perhaps there should only ever be one argument
var definition = getRegisteredDefinition(typeExtension || tag);
if (definition) {
if (tag == definition.tag && typeExtension == definition.is) {
return new definition.ctor();
}
// Handle empty string for type extension.
if (!typeExtension && !definition.is) {
return new definition.ctor();
}
}
if (typeExtension) {
var element = createElement(tag);
element.setAttribute('is', typeExtension);
return element;
}
var element = domCreateElement(tag);
// Custom tags should be HTMLElements even if not upgraded.
if (tag.indexOf('-') >= 0) {
implement(element, HTMLElement);
}
return element;
}
function upgradeElement(element) {
if (!element.__upgraded__ && (element.nodeType === Node.ELEMENT_NODE)) {
var is = element.getAttribute('is');
var definition = getRegisteredDefinition(is || element.localName);
if (definition) {
if (is && definition.tag == element.localName) {
return upgrade(element, definition);
} else if (!is && !definition.extends) {
return upgrade(element, definition);
}
}
}
}
function cloneNode(deep) {
// call original clone
var n = domCloneNode.call(this, deep);
// upgrade the element and subtree
scope.upgradeAll(n);
// return the clone
return n;
}
// capture native createElement before we override it
var domCreateElement = document.createElement.bind(document);
var domCreateElementNS = document.createElementNS.bind(document);
// capture native cloneNode before we override it
var domCloneNode = Node.prototype.cloneNode;
// exports
document.registerElement = register;
document.createElement = createElement; // override
document.createElementNS = createElementNS; // override
Node.prototype.cloneNode = cloneNode; // override
scope.registry = registry;
/**
* Upgrade an element to a custom element. Upgrading an element
* causes the custom prototype to be applied, an `is` attribute
* to be attached (as needed), and invocation of the `readyCallback`.
* `upgrade` does nothing if the element is already upgraded, or
* if it matches no registered custom tag name.
*
* @method ugprade
* @param {Element} element The element to upgrade.
* @return {Element} The upgraded element.
*/
scope.upgrade = upgradeElement;
}
// Create a custom 'instanceof'. This is necessary when CustomElements
// are implemented via a mixin strategy, as for example on IE10.
var isInstance;
if (!Object.__proto__ && !useNative) {
isInstance = function(obj, ctor) {
var p = obj;
while (p) {
// NOTE: this is not technically correct since we're not checking if
// an object is an instance of a constructor; however, this should
// be good enough for the mixin strategy.
if (p === ctor.prototype) {
return true;
}
p = p.__proto__;
}
return false;
}
} else {
isInstance = function(obj, base) {
return obj instanceof base;
}
}
// exports
scope.instanceof = isInstance;
scope.reservedTagList = reservedTagList;
// bc
document.register = document.registerElement;
scope.hasNative = hasNative;
scope.useNative = useNative;
})(window.CustomElements);
/*
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function(scope){
var logFlags = window.logFlags || {};
var IMPORT_LINK_TYPE = window.HTMLImports ? HTMLImports.IMPORT_LINK_TYPE : 'none';
// walk the subtree rooted at node, applying 'find(element, data)' function
// to each element
// if 'find' returns true for 'element', do not search element's subtree
function findAll(node, find, data) {
var e = node.firstElementChild;
if (!e) {
e = node.firstChild;
while (e && e.nodeType !== Node.ELEMENT_NODE) {
e = e.nextSibling;
}
}
while (e) {
if (find(e, data) !== true) {
findAll(e, find, data);
}
e = e.nextElementSibling;
}
return null;
}
// walk all shadowRoots on a given node.
function forRoots(node, cb) {
var root = node.shadowRoot;
while(root) {
forSubtree(root, cb);
root = root.olderShadowRoot;
}
}
// walk the subtree rooted at node, including descent into shadow-roots,
// applying 'cb' to each element
function forSubtree(node, cb) {
//logFlags.dom && node.childNodes && node.childNodes.length && console.group('subTree: ', node);
findAll(node, function(e) {
if (cb(e)) {
return true;
}
forRoots(e, cb);
});
forRoots(node, cb);
//logFlags.dom && node.childNodes && node.childNodes.length && console.groupEnd();
}
// manage lifecycle on added node
function added(node) {
if (upgrade(node)) {
insertedNode(node);
return true;
}
inserted(node);
}
// manage lifecycle on added node's subtree only
function addedSubtree(node) {
forSubtree(node, function(e) {
if (added(e)) {
return true;
}
});
}
// manage lifecycle on added node and it's subtree
function addedNode(node) {
return added(node) || addedSubtree(node);
}
// upgrade custom elements at node, if applicable
function upgrade(node) {
if (!node.__upgraded__ && node.nodeType === Node.ELEMENT_NODE) {
var type = node.getAttribute('is') || node.localName;
var definition = scope.registry[type];
if (definition) {
logFlags.dom && console.group('upgrade:', node.localName);
scope.upgrade(node);
logFlags.dom && console.groupEnd();
return true;
}
}
}
function insertedNode(node) {
inserted(node);
if (inDocument(node)) {
forSubtree(node, function(e) {
inserted(e);
});
}
}
// TODO(sorvell): on platforms without MutationObserver, mutations may not be
// reliable and therefore attached/detached are not reliable.
// To make these callbacks less likely to fail, we defer all inserts and removes
// to give a chance for elements to be inserted into dom.
// This ensures attachedCallback fires for elements that are created and
// immediately added to dom.
var hasPolyfillMutations = (!window.MutationObserver ||
(window.MutationObserver === window.JsMutationObserver));
scope.hasPolyfillMutations = hasPolyfillMutations;
var isPendingMutations = false;
var pendingMutations = [];
function deferMutation(fn) {
pendingMutations.push(fn);
if (!isPendingMutations) {
isPendingMutations = true;
var async = (window.Platform && window.Platform.endOfMicrotask) ||
setTimeout;
async(takeMutations);
}
}
function takeMutations() {
isPendingMutations = false;
var $p = pendingMutations;
for (var i=0, l=$p.length, p; (i<l) && (p=$p[i]); i++) {
p();
}
pendingMutations = [];
}
function inserted(element) {
if (hasPolyfillMutations) {
deferMutation(function() {
_inserted(element);
});
} else {
_inserted(element);
}
}
// TODO(sjmiles): if there are descents into trees that can never have inDocument(*) true, fix this
function _inserted(element) {
// TODO(sjmiles): it's possible we were inserted and removed in the space
// of one microtask, in which case we won't be 'inDocument' here
// But there are other cases where we are testing for inserted without
// specific knowledge of mutations, and must test 'inDocument' to determine
// whether to call inserted
// If we can factor these cases into separate code paths we can have
// better diagnostics.
// TODO(sjmiles): when logging, do work on all custom elements so we can
// track behavior even when callbacks not defined
//console.log('inserted: ', element.localName);
if (element.attachedCallback || element.detachedCallback || (element.__upgraded__ && logFlags.dom)) {
logFlags.dom && console.group('inserted:', element.localName);
if (inDocument(element)) {
element.__inserted = (element.__inserted || 0) + 1;
// if we are in a 'removed' state, bluntly adjust to an 'inserted' state
if (element.__inserted < 1) {
element.__inserted = 1;
}
// if we are 'over inserted', squelch the callback
if (element.__inserted > 1) {
logFlags.dom && console.warn('inserted:', element.localName,
'insert/remove count:', element.__inserted)
} else if (element.attachedCallback) {
logFlags.dom && console.log('inserted:', element.localName);
element.attachedCallback();
}
}
logFlags.dom && console.groupEnd();
}
}
function removedNode(node) {
removed(node);
forSubtree(node, function(e) {
removed(e);
});
}
function removed(element) {
if (hasPolyfillMutations) {
deferMutation(function() {
_removed(element);
});
} else {
_removed(element);
}
}
function _removed(element) {
// TODO(sjmiles): temporary: do work on all custom elements so we can track
// behavior even when callbacks not defined
if (element.attachedCallback || element.detachedCallback || (element.__upgraded__ && logFlags.dom)) {
logFlags.dom && console.group('removed:', element.localName);
if (!inDocument(element)) {
element.__inserted = (element.__inserted || 0) - 1;
// if we are in a 'inserted' state, bluntly adjust to an 'removed' state
if (element.__inserted > 0) {
element.__inserted = 0;
}
// if we are 'over removed', squelch the callback
if (element.__inserted < 0) {
logFlags.dom && console.warn('removed:', element.localName,
'insert/remove count:', element.__inserted)
} else if (element.detachedCallback) {
element.detachedCallback();
}
}
logFlags.dom && console.groupEnd();
}
}
// SD polyfill intrustion due mainly to the fact that 'document'
// is not entirely wrapped
function wrapIfNeeded(node) {
return window.ShadowDOMPolyfill ? ShadowDOMPolyfill.wrapIfNeeded(node)
: node;
}
function inDocument(element) {
var p = element;
var doc = wrapIfNeeded(document);
while (p) {
if (p == doc) {
return true;
}
p = p.parentNode || p.host;
}
}
function watchShadow(node) {
if (node.shadowRoot && !node.shadowRoot.__watched) {
logFlags.dom && console.log('watching shadow-root for: ', node.localName);
// watch all unwatched roots...
var root = node.shadowRoot;
while (root) {
watchRoot(root);
root = root.olderShadowRoot;
}
}
}
function watchRoot(root) {
if (!root.__watched) {
observe(root);
root.__watched = true;
}
}
function handler(mutations) {
//
if (logFlags.dom) {
var mx = mutations[0];
if (mx && mx.type === 'childList' && mx.addedNodes) {
if (mx.addedNodes) {
var d = mx.addedNodes[0];
while (d && d !== document && !d.host) {
d = d.parentNode;
}
var u = d && (d.URL || d._URL || (d.host && d.host.localName)) || '';
u = u.split('/?').shift().split('/').pop();
}
}
console.group('mutations (%d) [%s]', mutations.length, u || '');
}
//
mutations.forEach(function(mx) {
//logFlags.dom && console.group('mutation');
if (mx.type === 'childList') {
forEach(mx.addedNodes, function(n) {
//logFlags.dom && console.log(n.localName);
if (!n.localName) {
return;
}
// nodes added may need lifecycle management
addedNode(n);
});
// removed nodes may need lifecycle management
forEach(mx.removedNodes, function(n) {
//logFlags.dom && console.log(n.localName);
if (!n.localName) {
return;
}
removedNode(n);
});
}
//logFlags.dom && console.groupEnd();
});
logFlags.dom && console.groupEnd();
};
var observer = new MutationObserver(handler);
function takeRecords() {
// TODO(sjmiles): ask Raf why we have to call handler ourselves
handler(observer.takeRecords());
takeMutations();
}
var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
function observe(inRoot) {
observer.observe(inRoot, {childList: true, subtree: true});
}
function observeDocument(doc) {
observe(doc);
}
function upgradeDocument(doc) {
logFlags.dom && console.group('upgradeDocument: ', (doc.baseURI).split('/').pop());
addedNode(doc);
logFlags.dom && console.groupEnd();
}
function upgradeDocumentTree(doc) {
doc = wrapIfNeeded(doc);
//console.log('upgradeDocumentTree: ', (doc.baseURI).split('/').pop());
// upgrade contained imported documents
var imports = doc.querySelectorAll('link[rel=' + IMPORT_LINK_TYPE + ']');
for (var i=0, l=imports.length, n; (i<l) && (n=imports[i]); i++) {
if (n.import && n.import.__parsed) {
upgradeDocumentTree(n.import);
}
}
upgradeDocument(doc);
}
// exports
scope.IMPORT_LINK_TYPE = IMPORT_LINK_TYPE;
scope.watchShadow = watchShadow;
scope.upgradeDocumentTree = upgradeDocumentTree;
scope.upgradeAll = addedNode;
scope.upgradeSubtree = addedSubtree;
scope.insertedNode = insertedNode;
scope.observeDocument = observeDocument;
scope.upgradeDocument = upgradeDocument;
scope.takeRecords = takeRecords;
})(window.CustomElements);
/*
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function(scope) {
// import
var IMPORT_LINK_TYPE = scope.IMPORT_LINK_TYPE;
// highlander object for parsing a document tree
var parser = {
selectors: [
'link[rel=' + IMPORT_LINK_TYPE + ']'
],
map: {
link: 'parseLink'
},
parse: function(inDocument) {
if (!inDocument.__parsed) {
// only parse once
inDocument.__parsed = true;
// all parsable elements in inDocument (depth-first pre-order traversal)
var elts = inDocument.querySelectorAll(parser.selectors);
// for each parsable node type, call the mapped parsing method
forEach(elts, function(e) {
parser[parser.map[e.localName]](e);
});
// upgrade all upgradeable static elements, anything dynamically
// created should be caught by observer
CustomElements.upgradeDocument(inDocument);
// observe document for dom changes
CustomElements.observeDocument(inDocument);
}
},
parseLink: function(linkElt) {
// imports
if (isDocumentLink(linkElt)) {
this.parseImport(linkElt);
}
},
parseImport: function(linkElt) {
if (linkElt.import) {
parser.parse(linkElt.import);
}
}
};
function isDocumentLink(inElt) {
return (inElt.localName === 'link'
&& inElt.getAttribute('rel') === IMPORT_LINK_TYPE);
}
var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
// exports
scope.parser = parser;
scope.IMPORT_LINK_TYPE = IMPORT_LINK_TYPE;
})(window.CustomElements);
/*
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function(scope){
// bootstrap parsing
function bootstrap() {
// parse document
CustomElements.parser.parse(document);
// one more pass before register is 'live'
CustomElements.upgradeDocument(document);
// install upgrade hook if HTMLImports are available
if (window.HTMLImports) {
HTMLImports.__importsParsingHook = function(elt) {
CustomElements.parser.parse(elt.import);
}
}
// set internal 'ready' flag, now document.registerElement will trigger
// synchronous upgrades
CustomElements.ready = true;
// async to ensure *native* custom elements upgrade prior to this
// DOMContentLoaded can fire before elements upgrade (e.g. when there's
// an external script)
setTimeout(function() {
// capture blunt profiling data
CustomElements.readyTime = Date.now();
if (window.HTMLImports) {
CustomElements.elapsed = CustomElements.readyTime - HTMLImports.readyTime;
}
// notify the system that we are bootstrapped
document.dispatchEvent(
new CustomEvent('WebComponentsReady', {bubbles: true})
);
});
}
// CustomEvent shim for IE
if (typeof window.CustomEvent !== 'function') {
window.CustomEvent = function(inType, params) {
params = params || {};
var e = document.createEvent('CustomEvent');
e.initCustomEvent(inType, Boolean(params.bubbles), Boolean(params.cancelable), params.detail);
return e;
};
window.CustomEvent.prototype = window.Event.prototype;
}
// When loading at readyState complete time (or via flag), boot custom elements
// immediately.
// If relevant, HTMLImports must already be loaded.
if (document.readyState === 'complete' || scope.flags.eager) {
bootstrap();
// When loading at readyState interactive time, bootstrap only if HTMLImports
// are not pending. Also avoid IE as the semantics of this state are unreliable.
} else if (document.readyState === 'interactive' && !window.attachEvent &&
(!window.HTMLImports || window.HTMLImports.ready)) {
bootstrap();
// When loading at other readyStates, wait for the appropriate DOM event to
// bootstrap.
} else {
var loadEvent = window.HTMLImports && !HTMLImports.ready ?
'HTMLImportsLoaded' : 'DOMContentLoaded';
window.addEventListener(loadEvent, bootstrap);
}
})(window.CustomElements);
(function () {
/*** Variables ***/
var win = window,
doc = document,
attrProto = {
setAttribute: Element.prototype.setAttribute,
removeAttribute: Element.prototype.removeAttribute
},
hasShadow = Element.prototype.createShadowRoot,
container = doc.createElement('div'),
noop = function(){},
trueop = function(){ return true; },
regexCamelToDash = /([a-z])([A-Z])/g,
regexPseudoParens = /\(|\)/g,
regexPseudoCapture = /:(\w+)\u276A(.+?(?=\u276B))|:(\w+)/g,
regexDigits = /(\d+)/g,
keypseudo = {
action: function (pseudo, event) {
return pseudo.value.match(regexDigits).indexOf(String(event.keyCode)) > -1 == (pseudo.name == 'keypass') || null;
}
},
/*
- The prefix object generated here is added to the xtag object as xtag.prefix later in the code
- Prefix provides a variety of prefix variations for the browser in which your code is running
- The 4 variations of prefix are as follows:
* prefix.dom: the correct prefix case and form when used on DOM elements/style properties
* prefix.lowercase: a lowercase version of the prefix for use in various user-code situations
* prefix.css: the lowercase, dashed version of the prefix
* prefix.js: addresses prefixed APIs present in global and non-Element contexts
*/
prefix = (function () {
var styles = win.getComputedStyle(doc.documentElement, ''),
pre = (Array.prototype.slice
.call(styles)
.join('')
.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
)[1];
return {
dom: pre == 'ms' ? 'MS' : pre,
lowercase: pre,
css: '-' + pre + '-',
js: pre == 'ms' ? pre : pre[0].toUpperCase() + pre.substr(1)
};
})(),
matchSelector = Element.prototype.matchesSelector || Element.prototype[prefix.lowercase + 'MatchesSelector'],
mutation = win.MutationObserver || win[prefix.js + 'MutationObserver'];
/*** Functions ***/
// Utilities
/*
This is an enhanced typeof check for all types of objects. Where typeof would normaly return
'object' for many common DOM objects (like NodeLists and HTMLCollections).
- For example: typeOf(document.children) will correctly return 'htmlcollection'
*/
var typeCache = {},
typeString = typeCache.toString,
typeRegexp = /\s([a-zA-Z]+)/;
function typeOf(obj) {
var type = typeString.call(obj);
return typeCache[type] || (typeCache[type] = type.match(typeRegexp)[1].toLowerCase());
}
function clone(item, type){
var fn = clone[type || typeOf(item)];
return fn ? fn(item) : item;
}
clone.object = function(src){
var obj = {};
for (var key in src) obj[key] = clone(src[key]);
return obj;
};
clone.array = function(src){
var i = src.length, array = new Array(i);
while (i--) array[i] = clone(src[i]);
return array;
};
/*
The toArray() method allows for conversion of any object to a true array. For types that
cannot be converted to an array, the method returns a 1 item array containing the passed-in object.
*/
var unsliceable = ['undefined', 'null', 'number', 'boolean', 'string', 'function'];
function toArray(obj){
return unsliceable.indexOf(typeOf(obj)) == -1 ?
Array.prototype.slice.call(obj, 0) :
[obj];
}
// DOM
var str = '';
function query(element, selector){
return (selector || str).length ? toArray(element.querySelectorAll(selector)) : [];
}
function parseMutations(element, mutations) {
var diff = { added: [], removed: [] };
mutations.forEach(function(record){
record._mutation = true;
for (var z in diff) {
var type = element._records[(z == 'added') ? 'inserted' : 'removed'],
nodes = record[z + 'Nodes'], length = nodes.length;
for (var i = 0; i < length && diff[z].indexOf(nodes[i]) == -1; i++){
diff[z].push(nodes[i]);
type.forEach(function(fn){
fn(nodes[i], record);
});
}
}
});
}
// Pseudos
function parsePseudo(fn){fn();}
// Mixins
function mergeOne(source, key, current){
var type = typeOf(current);
if (type == 'object' && typeOf(source[key]) == 'object') xtag.merge(source[key], current);
else source[key] = clone(current, type);
return source;
}
function wrapMixin(tag, key, pseudo, value, original){
var fn = original[key];
if (!(key in original)) {
original[key + (pseudo.match(':mixins') ? '' : ':mixins')] = value;
}
else if (typeof original[key] == 'function') {
if (!fn.__mixins__) fn.__mixins__ = [];
fn.__mixins__.push(xtag.applyPseudos(pseudo, value, tag.pseudos));
}
}
var uniqueMixinCount = 0;
function mergeMixin(tag, mixin, original, mix) {
if (mix) {
var uniques = {};
for (var z in original) uniques[z.split(':')[0]] = z;
for (z in mixin) {
wrapMixin(tag, uniques[z.split(':')[0]] || z, z, mixin[z], original);
}
}
else {
for (var zz in mixin){
original[zz + ':__mixin__(' + (uniqueMixinCount++) + ')'] = xtag.applyPseudos(zz, mixin[zz], tag.pseudos);
}
}
}
function applyMixins(tag) {
tag.mixins.forEach(function (name) {
var mixin = xtag.mixins[name];
for (var type in mixin) {
var item = mixin[type],
original = tag[type];
if (!original) tag[type] = item;
else {
switch (type){
case 'accessors': case 'prototype':
for (var z in item) {
if (!original[z]) original[z] = item[z];
else mergeMixin(tag, item[z], original[z], true);
}
break;
default: mergeMixin(tag, item, original, type != 'events');
}
}
}
});
return tag;
}
// Events
function delegateAction(pseudo, event) {
var match, target = event.target;
if (!target.tagName) return null;
if (xtag.matchSelector(target, pseudo.value)) match = target;
else if (xtag.matchSelector(target, pseudo.value + ' *')) {
var parent = target.parentNode;
while (!match) {
if (xtag.matchSelector(parent, pseudo.value)) match = parent;
parent = parent.parentNode;
}
}
return match ? pseudo.listener = pseudo.listener.bind(match) : null;
}
function touchFilter(event) {
if (event.type.match('touch')){
event.target.__touched__ = true;
}
else if (event.target.__touched__ && event.type.match('mouse')){
delete event.target.__touched__;
return;
}
return true;
}
function writeProperty(key, event, base, desc){
if (desc) event[key] = base[key];
else Object.defineProperty(event, key, {
writable: true,
enumerable: true,
value: base[key]
});
}
var skipProps = {};
for (var z in doc.createEvent('CustomEvent')) skipProps[z] = 1;
function inheritEvent(event, base){
var desc = Object.getOwnPropertyDescriptor(event, 'target');
for (var z in base) {
if (!skipProps[z]) writeProperty(z, event, base, desc);
}
event.baseEvent = base;
}
// Accessors
function modAttr(element, attr, name, value, method){
attrProto[method].call(element, name, attr && attr.boolean ? '' : value);
}
function syncAttr(element, attr, name, value, method){
if (attr && (attr.property || attr.selector)) {
var nodes = attr.property ? [element.xtag[attr.property]] : attr.selector ? xtag.query(element, attr.selector) : [],
index = nodes.length;
while (index--) nodes[index][method](name, value);
}
}
function updateView(element, name, value){
if (element.__view__){
element.__view__.updateBindingValue(element, name, value);
}
}
function attachProperties(tag, prop, z, accessor, attr, name){
var key = z.split(':'), type = key[0];
if (type == 'get') {
key[0] = prop;
tag.prototype[prop].get = xtag.applyPseudos(key.join(':'), accessor[z], tag.pseudos, accessor[z]);
}
else if (type == 'set') {
key[0] = prop;
var setter = tag.prototype[prop].set = xtag.applyPseudos(key.join(':'), attr ? function(value){
value = attr.boolean ? !!value : attr.validate ? attr.validate.call(this, value) : value;
var method = attr.boolean ? (value ? 'setAttribute' : 'removeAttribute') : 'setAttribute';
modAttr(this, attr, name, value, method);
accessor[z].call(this, value);
syncAttr(this, attr, name, value, method);
updateView(this, prop, value);
} : accessor[z] ? function(value){
accessor[z].call(this, value);
updateView(this, prop, value);
} : null, tag.pseudos, accessor[z]);
if (attr) attr.setter = accessor[z];
}
else tag.prototype[prop][z] = accessor[z];
}
function parseAccessor(tag, prop){
tag.prototype[prop] = {};
var accessor = tag.accessors[prop],
attr = accessor.attribute,
name;
if (attr) {
name = attr.name = (attr ? (attr.name || prop.replace(regexCamelToDash, '$1-$2')) : prop).toLowerCase();
attr.key = prop;
tag.attributes[name] = attr;
}
for (var z in accessor) attachProperties(tag, prop, z, accessor, attr, name);
if (attr) {
if (!tag.prototype[prop].get) {
var method = (attr.boolean ? 'has' : 'get') + 'Attribute';
tag.prototype[prop].get = function(){
return this[method](name);
};
}
if (!tag.prototype[prop].set) tag.prototype[prop].set = function(value){
value = attr.boolean ? !!value : attr.validate ? attr.validate.call(this, value) : value;
var method = attr.boolean ? (value ? 'setAttribute' : 'removeAttribute') : 'setAttribute';
modAttr(this, attr, name, value, method);
syncAttr(this, attr, name, value, method);
updateView(this, name, value);
};
}
}
var unwrapComment = /\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//;
function parseMultiline(fn){
return unwrapComment.exec(fn.toString())[1];
}
/*** X-Tag Object Definition ***/
var xtag = {
tags: {},
defaultOptions: {
pseudos: [],
mixins: [],
events: {},
methods: {},
accessors: {},
lifecycle: {},
attributes: {},
'prototype': {
xtag: {
get: function(){
return this.__xtag__ ? this.__xtag__ : (this.__xtag__ = { data: {} });
}
}
}
},
register: function (name, options) {
var _name;
if (typeof name == 'string') {
_name = name.toLowerCase();
} else {
return;
}
xtag.tags[_name] = options || {};
// save prototype for actual object creation below
var basePrototype = options.prototype;
delete options.prototype;
var tag = xtag.tags[_name].compiled = applyMixins(xtag.merge({}, xtag.defaultOptions, options));
for (var z in tag.events) tag.events[z] = xtag.parseEvent(z, tag.events[z]);
for (z in tag.lifecycle) tag.lifecycle[z.split(':')[0]] = xtag.applyPseudos(z, tag.lifecycle[z], tag.pseudos, tag.lifecycle[z]);
for (z in tag.methods) tag.prototype[z.split(':')[0]] = { value: xtag.applyPseudos(z, tag.methods[z], tag.pseudos, tag.methods[z]), enumerable: true };
for (z in tag.accessors) parseAccessor(tag, z);
tag.shadow = tag.shadow ? xtag.createFragment(tag.shadow) : null;
tag.content = tag.content ? xtag.createFragment(tag.content) : null;
var ready = tag.lifecycle.created || tag.lifecycle.ready;
tag.prototype.createdCallback = {
enumerable: true,
value: function(){
var element = this;
if (tag.shadow && hasShadow) this.createShadowRoot().appendChild(tag.shadow.cloneNode(true));
if (tag.content) this.appendChild(tag.content.cloneNode(true));
xtag.addEvents(this, tag.events);
var output = ready ? ready.apply(this, arguments) : null;
for (var name in tag.attributes) {
var attr = tag.attributes[name],
hasAttr = this.hasAttribute(name);
if (hasAttr || attr.boolean) {
this[attr.key] = attr.boolean ? hasAttr : this.getAttribute(name);
}
}
tag.pseudos.forEach(function(obj){
obj.onAdd.call(element, obj);
});
return output;
}
};
var inserted = tag.lifecycle.inserted,
removed = tag.lifecycle.removed;
if (inserted || removed) {
tag.prototype.attachedCallback = { value: function(){
if (removed) this.xtag.__parentNode__ = this.parentNode;
if (inserted) return inserted.apply(this, arguments);
}, enumerable: true };
}
if (removed) {
tag.prototype.detachedCallback = { value: function(){
var args = toArray(arguments);
args.unshift(this.xtag.__parentNode__);
var output = removed.apply(this, args);
delete this.xtag.__parentNode__;
return output;
}, enumerable: true };
}
if (tag.lifecycle.attributeChanged) tag.prototype.attributeChangedCallback = { value: tag.lifecycle.attributeChanged, enumerable: true };
tag.prototype.setAttribute = {
writable: true,
enumberable: true,
value: function (name, value){
var _name = name.toLowerCase();
var attr = tag.attributes[_name];
if (attr) {
value = attr.boolean ? '' : attr.validate ? attr.validate.call(this, value) : value;
}
modAttr(this, attr, _name, value, 'setAttribute');
if (attr) {
if (attr.setter) attr.setter.call(this, attr.boolean ? true : value);
syncAttr(this, attr, _name, value, 'setAttribute');
}
}
};
tag.prototype.removeAttribute = {
writable: true,
enumberable: true,
value: function (name){
var _name = name.toLowerCase();
var attr = tag.attributes[_name];
modAttr(this, attr, _name, '', 'removeAttribute');
if (attr) {
if (attr.setter) attr.setter.call(this, attr.boolean ? false : undefined);
syncAttr(this, attr, _name, '', 'removeAttribute');
}
}
};
var elementProto = basePrototype ?
basePrototype :
options['extends'] ?
Object.create(doc.createElement(options['extends']).constructor).prototype :
win.HTMLElement.prototype;
var definition = {
'prototype': Object.create(elementProto, tag.prototype)
};
if (options['extends']) {
definition['extends'] = options['extends'];
}
var reg = doc.registerElement(_name, definition);
return reg;
},
/* Exposed Variables */
mixins: {},
prefix: prefix,
captureEvents: ['focus', 'blur', 'input', 'scroll', 'underflow', 'overflow', 'overflowchanged', 'DOMMouseScroll'],
customEvents: {
animationstart: {
attach: [prefix.dom + 'AnimationStart']
},
animationend: {
attach: [prefix.dom + 'AnimationEnd']
},
transitionend: {
attach: [prefix.dom + 'TransitionEnd']
},
move: {
attach: ['mousemove', 'touchmove'],
condition: touchFilter
},
enter: {
attach: ['mouseover', 'touchenter'],
condition: touchFilter
},
leave: {
attach: ['mouseout', 'touchleave'],
condition: touchFilter
},
scrollwheel: {
attach: ['DOMMouseScroll', 'mousewheel'],
condition: function(event){
event.delta = event.wheelDelta ? event.wheelDelta / 40 : Math.round(event.detail / 3.5 * -1);
return true;
}
},
tapstart: {
observe: {
mousedown: doc,
touchstart: doc
},
condition: touchFilter
},
tapend: {
observe: {
mouseup: doc,
touchend: doc
},
condition: touchFilter
},
tapmove: {
attach: ['tapstart', 'dragend', 'touchcancel'],
condition: function(event, custom){
switch (event.type) {
case 'move': return true;
case 'dragover':
var last = custom.lastDrag || {};
custom.lastDrag = event;
return (last.pageX != event.pageX && last.pageY != event.pageY) || null;
case 'tapstart':
if (!custom.move) {
custom.current = this;
custom.move = xtag.addEvents(this, {
move: custom.listener,
dragover: custom.listener
});
custom.tapend = xtag.addEvent(doc, 'tapend', custom.listener);
}
break;
case 'tapend': case 'dragend': case 'touchcancel':
if (!event.touches.length) {
if (custom.move) xtag.removeEvents(custom.current , custom.move || {});
if (custom.tapend) xtag.removeEvent(doc, custom.tapend || {});
delete custom.lastDrag;
delete custom.current;
delete custom.tapend;
delete custom.move;
}
}
}
}
},
pseudos: {
__mixin__: {},
/*
*/
mixins: {
onCompiled: function(fn, pseudo){
var mixins = pseudo.source.__mixins__;
if (mixins) switch (pseudo.value) {
case 'before': return function(){
var self = this,
args = arguments;
mixins.forEach(function(m){
m.apply(self, args);
});
return fn.apply(self, args);
};
case null: case '': case 'after': return function(){
var self = this,
args = arguments;
returns = fn.apply(self, args);
mixins.forEach(function(m){
m.apply(self, args);
});
return returns;
};
}
}
},
keypass: keypseudo,
keyfail: keypseudo,
delegate: { action: delegateAction },
within: {
action: delegateAction,
onAdd: function(pseudo){
var condition = pseudo.source.condition;
if (condition) pseudo.source.condition = function(event, custom){
return xtag.query(this, pseudo.value).filter(function(node){
return node == event.target || node.contains ? node.contains(event.target) : null;
})[0] ? condition.call(this, event, custom) : null;
};
}
},
preventable: {
action: function (pseudo, event) {
return !event.defaultPrevented;
}
}
},
/* UTILITIES */
clone: clone,
typeOf: typeOf,
toArray: toArray,
wrap: function (original, fn) {
return function(){
var args = arguments,
output = original.apply(this, args);
fn.apply(this, args);
return output;
};
},
/*
Recursively merges one object with another. The first argument is the destination object,
all other objects passed in as arguments are merged from right to left, conflicts are overwritten
*/
merge: function(source, k, v){
if (typeOf(k) == 'string') return mergeOne(source, k, v);
for (var i = 1, l = arguments.length; i < l; i++){
var object = arguments[i];
for (var key in object) mergeOne(source, key, object[key]);
}
return source;
},
/*
----- This should be simplified! -----
Generates a random ID string
*/
uid: function(){
return Math.random().toString(36).substr(2,10);
},
/* DOM */
query: query,
skipTransition: function(element, fn, bind){
var prop = prefix.js + 'TransitionProperty';
element.style[prop] = element.style.transitionProperty = 'none';
var callback = fn ? fn.call(bind || element) : null;
return xtag.skipFrame(function(){
element.style[prop] = element.style.transitionProperty = '';
if (callback) callback.call(bind || element);
});
},
requestFrame: (function(){
var raf = win.requestAnimationFrame ||
win[prefix.lowercase + 'RequestAnimationFrame'] ||
function(fn){ return win.setTimeout(fn, 20); };
return function(fn){ return raf(fn); };
})(),
cancelFrame: (function(){
var cancel = win.cancelAnimationFrame ||
win[prefix.lowercase + 'CancelAnimationFrame'] ||
win.clearTimeout;
return function(id){ return cancel(id); };
})(),
skipFrame: function(fn){
var id = xtag.requestFrame(function(){ id = xtag.requestFrame(fn); });
return id;
},
matchSelector: function (element, selector) {
return matchSelector.call(element, selector);
},
set: function (element, method, value) {
element[method] = value;
if (window.CustomElements) CustomElements.upgradeAll(element);
},
innerHTML: function(el, html){
xtag.set(el, 'innerHTML', html);
},
hasClass: function (element, klass) {
return element.className.split(' ').indexOf(klass.trim())>-1;
},
addClass: function (element, klass) {
var list = element.className.trim().split(' ');
klass.trim().split(' ').forEach(function (name) {
if (!~list.indexOf(name)) list.push(name);
});
element.className = list.join(' ').trim();
return element;
},
removeClass: function (element, klass) {
var classes = klass.trim().split(' ');
element.className = element.className.trim().split(' ').filter(function (name) {
return name && !~classes.indexOf(name);
}).join(' ');
return element;
},
toggleClass: function (element, klass) {
return xtag[xtag.hasClass(element, klass) ? 'removeClass' : 'addClass'].call(null, element, klass);
},
/*
Runs a query on only the children of an element
*/
queryChildren: function (element, selector) {
var id = element.id,
guid = element.id = id || 'x_' + xtag.uid(),
attr = '#' + guid + ' > ',
noParent = false;
if (!element.parentNode){
noParent = true;
container.appendChild(element);
}
selector = attr + (selector + '').replace(',', ',' + attr, 'g');
var result = element.parentNode.querySelectorAll(selector);
if (!id) element.removeAttribute('id');
if (noParent){
container.removeChild(element);
}
return toArray(result);
},
/*
Creates a document fragment with the content passed in - content can be
a string of HTML, an element, or an array/collection of elements
*/
createFragment: function(content) {
var frag = doc.createDocumentFragment();
if (content) {
var div = frag.appendChild(doc.createElement('div')),
nodes = toArray(content.nodeName ? arguments : !(div.innerHTML = typeof content == 'function' ? parseMultiline(content) : content) || div.children),
length = nodes.length,
index = 0;
while (index < length) frag.insertBefore(nodes[index++], div);
frag.removeChild(div);
}
return frag;
},
/*
Removes an element from the DOM for more performant node manipulation. The element
is placed back into the DOM at the place it was taken from.
*/
manipulate: function(element, fn){
var next = element.nextSibling,
parent = element.parentNode,
frag = doc.createDocumentFragment(),
returned = fn.call(frag.appendChild(element), frag) || element;
if (next) parent.insertBefore(returned, next);
else parent.appendChild(returned);
},
/* PSEUDOS */
applyPseudos: function(key, fn, target, source) {
var listener = fn,
pseudos = {};
if (key.match(':')) {
var matches = [],
valueFlag = 0;
key.replace(regexPseudoParens, function(match){
if (match == '(') return ++valueFlag == 1 ? '\u276A' : '(';
return !--valueFlag ? '\u276B' : ')';
}).replace(regexPseudoCapture, function(z, name, value, solo){
matches.push([name || solo, value]);
});
var i = matches.length;
while (i--) parsePseudo(function(){
var name = matches[i][0],
value = matches[i][1];
if (!xtag.pseudos[name]) throw "pseudo not found: " + name + " " + value;
value = (value === '' || typeof value == 'undefined') ? null : value;
var pseudo = pseudos[i] = Object.create(xtag.pseudos[name]);
pseudo.key = key;
pseudo.name = name;
pseudo.value = value;
pseudo['arguments'] = (value || '').split(',');
pseudo.action = pseudo.action || trueop;
pseudo.source = source;
var original = pseudo.listener = listener;
listener = function(){
var output = pseudo.action.apply(this, [pseudo].concat(toArray(arguments)));
if (output === null || output === false) return output;
output = pseudo.listener.apply(this, arguments);
pseudo.listener = original;
return output;
};
if (target && pseudo.onAdd) {
if (target.nodeName) pseudo.onAdd.call(target, pseudo);
else target.push(pseudo);
}
});
}
for (var z in pseudos) {
if (pseudos[z].onCompiled) listener = pseudos[z].onCompiled(listener, pseudos[z]) || listener;
}
return listener;
},
removePseudos: function(target, pseudos){
pseudos.forEach(function(obj){
if (obj.onRemove) obj.onRemove.call(target, obj);
});
},
/*** Events ***/
parseEvent: function(type, fn) {
var pseudos = type.split(':'),
key = pseudos.shift(),
custom = xtag.customEvents[key],
event = xtag.merge({
type: key,
stack: noop,
condition: trueop,
attach: [],
_attach: [],
pseudos: '',
_pseudos: [],
onAdd: noop,
onRemove: noop
}, custom || {});
event.attach = toArray(event.base || event.attach);
event.chain = key + (event.pseudos.length ? ':' + event.pseudos : '') + (pseudos.length ? ':' + pseudos.join(':') : '');
var condition = event.condition;
event.condition = function(e){
var t = e.touches, tt = e.targetTouches;
return condition.apply(this, arguments);
};
var stack = xtag.applyPseudos(event.chain, fn, event._pseudos, event);
event.stack = function(e){
e.currentTarget = e.currentTarget || this;
var t = e.touches, tt = e.targetTouches;
var detail = e.detail || {};
if (!detail.__stack__) return stack.apply(this, arguments);
else if (detail.__stack__ == stack) {
e.stopPropagation();
e.cancelBubble = true;
return stack.apply(this, arguments);
}
};
event.listener = function(e){
var args = toArray(arguments),
output = event.condition.apply(this, args.concat([event]));
if (!output) return output;
// The second condition in this IF is to address the following Blink regression: https://code.google.com/p/chromium/issues/detail?id=367537
// Remove this when affected browser builds with this regression fall below 5% marketshare
if (e.type != key && (e.baseEvent && e.type != e.baseEvent.type)) {
xtag.fireEvent(e.target, key, {
baseEvent: e,
detail: output !== true && (output.__stack__ = stack) ? output : { __stack__: stack }
});
}
else return event.stack.apply(this, args);
};
event.attach.forEach(function(name) {
event._attach.push(xtag.parseEvent(name, event.listener));
});
if (custom && custom.observe && !custom.__observing__) {
custom.observer = function(e){
var output = event.condition.apply(this, toArray(arguments).concat([custom]));
if (!output) return output;
xtag.fireEvent(e.target, key, {
baseEvent: e,
detail: output !== true ? output : {}
});
};
for (var z in custom.observe) xtag.addEvent(custom.observe[z] || document, z, custom.observer, true);
custom.__observing__ = true;
}
return event;
},
addEvent: function (element, type, fn, capture) {
var event = typeof fn == 'function' ? xtag.parseEvent(type, fn) : fn;
event._pseudos.forEach(function(obj){
obj.onAdd.call(element, obj);
});
event._attach.forEach(function(obj) {
xtag.addEvent(element, obj.type, obj);
});
event.onAdd.call(element, event, event.listener);
element.addEventListener(event.type, event.stack, capture || xtag.captureEvents.indexOf(event.type) > -1);
return event;
},
addEvents: function (element, obj) {
var events = {};
for (var z in obj) {
events[z] = xtag.addEvent(element, z, obj[z]);
}
return events;
},
removeEvent: function (element, type, event) {
event = event || type;
event.onRemove.call(element, event, event.listener);
xtag.removePseudos(element, event._pseudos);
event._attach.forEach(function(obj) {
xtag.removeEvent(element, obj);
});
element.removeEventListener(event.type, event.stack);
},
removeEvents: function(element, obj){
for (var z in obj) xtag.removeEvent(element, obj[z]);
},
fireEvent: function(element, type, options){
var event = doc.createEvent('CustomEvent');
options = options || {};
event.initCustomEvent(type,
options.bubbles !== false,
options.cancelable !== false,
options.detail
);
if (options.baseEvent) inheritEvent(event, options.baseEvent);
element.dispatchEvent(event);
},
/*
Listens for insertion or removal of nodes from a given element using
Mutation Observers, or Mutation Events as a fallback
*/
addObserver: function(element, type, fn){
if (!element._records) {
element._records = { inserted: [], removed: [] };
if (mutation){
element._observer = new mutation(function(mutations) {
parseMutations(element, mutations);
});
element._observer.observe(element, {
subtree: true,
childList: true,
attributes: !true,
characterData: false
});
}
else ['Inserted', 'Removed'].forEach(function(type){
element.addEventListener('DOMNode' + type, function(event){
event._mutation = true;
element._records[type.toLowerCase()].forEach(function(fn){
fn(event.target, event);
});
}, false);
});
}
if (element._records[type].indexOf(fn) == -1) element._records[type].push(fn);
},
removeObserver: function(element, type, fn){
var obj = element._records;
if (obj && fn){
obj[type].splice(obj[type].indexOf(fn), 1);
}
else{
obj[type] = [];
}
}
};
/*** Universal Touch ***/
var touching = false,
touchTarget = null;
doc.addEventListener('mousedown', function(e){
touching = true;
touchTarget = e.target;
}, true);
doc.addEventListener('mouseup', function(){
touching = false;
touchTarget = null;
}, true);
doc.addEventListener('dragend', function(){
touching = false;
touchTarget = null;
}, true);
var UIEventProto = {
touches: {
configurable: true,
get: function(){
return this.__touches__ ||
(this.identifier = 0) ||
(this.__touches__ = touching ? [this] : []);
}
},
targetTouches: {
configurable: true,
get: function(){
return this.__targetTouches__ || (this.__targetTouches__ =
(touching && this.currentTarget &&
(this.currentTarget == touchTarget ||
(this.currentTarget.contains && this.currentTarget.contains(touchTarget)))) ? (this.identifier = 0) || [this] : []);
}
},
changedTouches: {
configurable: true,
get: function(){
return this.__changedTouches__ || (this.identifier = 0) || (this.__changedTouches__ = [this]);
}
}
};
for (z in UIEventProto){
UIEvent.prototype[z] = UIEventProto[z];
Object.defineProperty(UIEvent.prototype, z, UIEventProto[z]);
}
/*** Custom Event Definitions ***/
function addTap(el, tap, e){
if (!el.__tap__) {
el.__tap__ = { click: e.type == 'mousedown' };
if (el.__tap__.click) el.addEventListener('click', tap.observer);
else {
el.__tap__.scroll = tap.observer.bind(el);
window.addEventListener('scroll', el.__tap__.scroll, true);
el.addEventListener('touchmove', tap.observer);
el.addEventListener('touchcancel', tap.observer);
el.addEventListener('touchend', tap.observer);
}
}
if (!el.__tap__.click) {
el.__tap__.x = e.touches[0].pageX;
el.__tap__.y = e.touches[0].pageY;
}
}
function removeTap(el, tap){
if (el.__tap__) {
if (el.__tap__.click) el.removeEventListener('click', tap.observer);
else {
window.removeEventListener('scroll', el.__tap__.scroll, true);
el.removeEventListener('touchmove', tap.observer);
el.removeEventListener('touchcancel', tap.observer);
el.removeEventListener('touchend', tap.observer);
}
delete el.__tap__;
}
}
function checkTapPosition(el, tap, e){
var touch = e.changedTouches[0],
tol = tap.gesture.tolerance;
if (
touch.pageX < el.__tap__.x + tol &&
touch.pageX > el.__tap__.x - tol &&
touch.pageY < el.__tap__.y + tol &&
touch.pageY > el.__tap__.y - tol
) return true;
}
xtag.customEvents.tap = {
observe: {
mousedown: document,
touchstart: document
},
gesture: {
tolerance: 8
},
condition: function(e, tap){
var el = e.target;
switch (e.type) {
case 'touchstart':
if (el.__tap__ && el.__tap__.click) removeTap(el, tap);
addTap(el, tap, e);
return;
case 'mousedown':
if (!el.__tap__) addTap(el, tap, e);
return;
case 'scroll':
case 'touchcancel':
removeTap(this, tap);
return;
case 'touchmove':
case 'touchend':
if (this.__tap__ && !checkTapPosition(this, tap, e)) {
removeTap(this, tap);
return;
}
return e.type == 'touchend' || null;
case 'click':
removeTap(this, tap);
return true;
}
}
};
win.xtag = xtag;
if (typeof define == 'function' && define.amd) define(xtag);
doc.addEventListener('WebComponentsReady', function(){
xtag.fireEvent(doc.body, 'DOMComponentsLoaded');
});
})();
| MicrosoftDX/Web-Components | rating/demo/x-tag-components.js | JavaScript | mit | 86,513 |
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.unified.SplitContainer.
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/core/theming/Parameters', './library'],
function(jQuery, Control, Parameters, library) {
"use strict";
/**
* Constructor for a new SplitContainer.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Provides a main content and a secondary content area
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.26.8
*
* @constructor
* @public
* @since 1.15.0
* @experimental Since version 1.15.0.
* API is not yet finished and might change completely
* @alias sap.ui.unified.SplitContainer
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var SplitContainer = Control.extend("sap.ui.unified.SplitContainer", /** @lends sap.ui.unified.SplitContainer.prototype */ { metadata : {
library : "sap.ui.unified",
properties : {
/**
* Shows / Hides the secondary area.
*/
showSecondaryContent : {type : "boolean", group : "Appearance", defaultValue : null},
/**
* The width if the secondary content. The height is always 100%.
*/
secondaryContentSize : {type : "sap.ui.core.CSSSize", group : "Appearance", defaultValue : '250px'},
/**
* Do not use. Use secondaryContentSize instead.
* @deprecated Since version 1.22.
*
* Only available for backwards compatibility.
*/
secondaryContentWidth : {type : "sap.ui.core.CSSSize", group : "Appearance", defaultValue : '250px', deprecated: true},
/**
* Whether to show the secondary content on the left ("Horizontal", default) or on the top ("Vertical").
* @since 1.22.0
*/
orientation : {type : "sap.ui.core.Orientation", group : "Appearance", defaultValue : sap.ui.core.Orientation.Horizontal}
},
defaultAggregation : "content",
aggregations : {
/**
* The content to appear in the main area.
*/
content : {type : "sap.ui.core.Control", multiple : true, singularName : "content"},
/**
* The content to appear in the secondary area.
*/
secondaryContent : {type : "sap.ui.core.Control", multiple : true, singularName : "secondaryContent"}
}
}});
(function(window) {
////////////////////////////////////////// Public Methods //////////////////////////////////////////
SplitContainer.prototype.init = function(){
this.bRtl = sap.ui.getCore().getConfiguration().getRTL();
this._paneRenderer = new sap.ui.unified._ContentRenderer(this, this.getId() + "-panecntnt", "secondaryContent");
this._canvasRenderer = new sap.ui.unified._ContentRenderer(this, this.getId() + "-canvascntnt", "content");
// Design decided that content does not need to be handled differently depending on device - remove
// comments if needed again...
// sap.ui.Device.media.attachHandler(
// this._handleMediaChange, this, sap.ui.Device.media.RANGESETS.SAP_STANDARD
// );
// By default move the content when the secondaryContent is shown
this._moveContent = true;
};
SplitContainer.prototype.exit = function(){
this._paneRenderer.destroy();
delete this._paneRenderer;
this._canvasRenderer.destroy();
delete this._canvasRenderer;
delete this._contentContainer;
delete this._secondaryContentContainer;
};
////////////////////////////////////////// onEvent Methods /////////////////////////////////////////
SplitContainer.prototype.onAfterRendering = function() {
// Shortcuts to the main DOM containers
this._contentContainer = this.$("canvas");
this._secondaryContentContainer = this.$("pane");
// Design decided that content does not need to be handled differently depending on device - remove
// comments if needed again...
// this._lastDeviceName = "";
// this._handleMediaChange(
// sap.ui.Device.media.getCurrentRange(sap.ui.Device.media.RANGESETS.SAP_STANDARD)
// );
this._applySecondaryContentSize();
};
////////////////////////////////////////// Private Methods /////////////////////////////////////////
// Design decided that content does not need to be handled differently depending on device - remove
// comments if needed again...
///**
// * This method is called whenever the size of the document changes into a different range of values
// * that represent different devices (Desktop/Tablet/Phone).
// *
// * @private
// */
//sap.ui.unified.SplitContainer.prototype._handleMediaChange = function(mParams) {
// var sDeviceName = mParams.name;
//
// // By default, move the content to the right, there should be enough space
// this._moveContent = true;
//
// if (sDeviceName == "Phone") {
// // On phones, do not move the main content as it does not have enough
// // space as it is
// this._moveContent = false;
// }
//
// // Only write changes if something actually changed
// if (this._lastDeviceName !== sDeviceName) {
// this._applySecondaryContentSize();
// }
// this._lastDeviceName = sDeviceName;
//};
/**
* Applies the current status to the content areas (CSS left and width properties).
*
* @private
*/
SplitContainer.prototype._applySecondaryContentSize = function(){
// Only set if rendered...
if (this.getDomRef()) {
var bVertical = this.getOrientation() == sap.ui.core.Orientation.Vertical;
var sSize, sOtherSize;
var sDir, sOtherDir;
var sSizeValue = this.getSecondaryContentSize();
var bShow = this.getShowSecondaryContent();
if (bVertical) {
// Vertical mode
sSize = "height";
sOtherSize = "width";
sDir = "top";
sOtherDir = this.bRtl ? "right" : "left";
} else {
// Horizontal mode
sSize = "width";
sOtherSize = "height";
sDir = this.bRtl ? "right" : "left";
sOtherDir = "top";
}
if (this._closeContentDelayId) {
jQuery.sap.clearDelayedCall(this._closeContentDelayId);
}
this._secondaryContentContainer.css(sSize, sSizeValue);
this._secondaryContentContainer.css(sOtherSize, "");
this._secondaryContentContainer.css(sDir, bShow ? "0" : "-" + sSizeValue);
this._secondaryContentContainer.css(sOtherDir, "");
// Move main content if it should be completely visible. @see _handleMediaChange()
if (this._moveContent) {
this._contentContainer.css(sDir, bShow ? sSizeValue : "0");
} else {
this._contentContainer.css(sDir, "0");
}
if (!bShow) {
// The theming parameter is something along the lines of "500ms", the "ms"-part is
// ignored by parseInt.
// TODO: Cache the value.
var iHideDelay = parseInt(
Parameters.get("sapUiUfdSplitContAnimationDuration"),
10
);
// Maybe we could also allow "s"-values and then multiply everything below 20 with 1000...?
this._closeContentDelayId = jQuery.sap.delayedCall(iHideDelay, this, function() {
this._secondaryContentContainer.toggleClass("sapUiUfdSplitContSecondClosed", true);
});
} else {
this._secondaryContentContainer.toggleClass("sapUiUfdSplitContSecondClosed", false);
}
}
};
/**
* Optimization method that prevents the normal render from rerendering the whole control.
* See _ContentRenderer in file shared.js for details.
*
* @param {function} fMod Method that is called to perform the requested change
* @param {sap.ui.core.Renderer} oDoIfRendered Renderer Instance
* @returns {any} the return value from the first parameter
*
* @private
*/
SplitContainer.prototype._mod = function(fMod, oDoIfRendered){
var bRendered = !!this.getDomRef();
var res = fMod.apply(this, [bRendered]);
if (bRendered && oDoIfRendered) {
oDoIfRendered.render();
}
return res;
};
//////////////////////////////////////// Overridden Methods ////////////////////////////////////////
//////////////////////////// Property "showSecondaryContent" ///////////////////////////////
SplitContainer.prototype.setShowSecondaryContent = function(bShow){
var bRendered = this.getDomRef();
this.setProperty("showSecondaryContent", !!bShow, bRendered);
this._applySecondaryContentSize();
return this;
};
///////////////////////////// Property "secondaryContentSize" /////////////////////////////
SplitContainer.prototype.setSecondaryContentSize = function(sSize) {
this.setProperty("secondaryContentSize", sSize, true);
this._applySecondaryContentSize();
return this;
};
// Backwards compatibility with old property name
SplitContainer.prototype.getSecondaryContentWidth = function() {
jQuery.sap.log.warning(
"SplitContainer: Use of deprecated property \"SecondaryContentWidth\", please use " +
"\"SecondaryContentSize\" instead."
);
return this.getSecondaryContentSize.apply(this, arguments);
};
SplitContainer.prototype.setSecondaryContentWidth = function() {
jQuery.sap.log.warning(
"SplitContainer: Use of deprecated property \"SecondaryContentWidth\", please use " +
"\"SecondaryContentSize\" instead."
);
return this.setSecondaryContentSize.apply(this, arguments);
};
/////////////////////////////////// Aggregation "content" //////////////////////////////////
SplitContainer.prototype.insertContent = function(oContent, iIndex) {
return this._mod(function(bRendered){
return this.insertAggregation("content", oContent, iIndex, bRendered);
}, this._canvasRenderer);
};
SplitContainer.prototype.addContent = function(oContent) {
return this._mod(function(bRendered){
return this.addAggregation("content", oContent, bRendered);
}, this._canvasRenderer);
};
SplitContainer.prototype.removeContent = function(vIndex) {
return this._mod(function(bRendered){
return this.removeAggregation("content", vIndex, bRendered);
}, this._canvasRenderer);
};
SplitContainer.prototype.removeAllContent = function() {
return this._mod(function(bRendered){
return this.removeAllAggregation("content", bRendered);
}, this._canvasRenderer);
};
SplitContainer.prototype.destroyContent = function() {
return this._mod(function(bRendered){
return this.destroyAggregation("content", bRendered);
}, this._canvasRenderer);
};
////////////////////////////// Aggregation "secondaryContent" //////////////////////////////
SplitContainer.prototype.insertSecondaryContent = function(oContent, iIndex) {
return this._mod(function(bRendered){
return this.insertAggregation("secondaryContent", oContent, iIndex, bRendered);
}, this._paneRenderer);
};
SplitContainer.prototype.addSecondaryContent = function(oContent) {
return this._mod(function(bRendered){
return this.addAggregation("secondaryContent", oContent, bRendered);
}, this._paneRenderer);
};
SplitContainer.prototype.removeSecondaryContent = function(vIndex) {
return this._mod(function(bRendered){
return this.removeAggregation("secondaryContent", vIndex, bRendered);
}, this._paneRenderer);
};
SplitContainer.prototype.removeAllSecondaryContent = function() {
return this._mod(function(bRendered){
return this.removeAllAggregation("secondaryContent", bRendered);
}, this._paneRenderer);
};
SplitContainer.prototype.destroySecondaryContent = function() {
return this._mod(function(bRendered){
return this.destroyAggregation("secondaryContent", bRendered);
}, this._paneRenderer);
};
})(window);
return SplitContainer;
}, /* bExport= */ true);
| brakmic/OpenUI5_Table_Demo | Scripts/vendor/sap/resources/sap/ui/unified/SplitContainer-dbg.js | JavaScript | mit | 11,676 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.