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
|
|---|---|---|---|---|---|
'use strict';
var d = require('d')
, validateSymbol = require('./validate-symbol')
, create = Object.create, defineProperties = Object.defineProperties
, defineProperty = Object.defineProperty, objPrototype = Object.prototype
, NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null);
if (typeof Symbol === 'function') NativeSymbol = Symbol;
var generateName = (function () {
var created = create(null);
return function (desc) {
var postfix = 0, name;
while (created[desc + (postfix || '')]) ++postfix;
desc += (postfix || '');
created[desc] = true;
name = '@@' + desc;
defineProperty(objPrototype, name, d.gs(null, function (value) {
defineProperty(this, name, d(value));
}));
return name;
};
}());
HiddenSymbol = function Symbol(description) {
if (this instanceof HiddenSymbol) throw new TypeError('TypeError: Symbol is not a constructor');
return SymbolPolyfill(description);
};
module.exports = SymbolPolyfill = function Symbol(description) {
var symbol;
if (this instanceof Symbol) throw new TypeError('TypeError: Symbol is not a constructor');
symbol = create(HiddenSymbol.prototype);
description = (description === undefined ? '' : String(description));
return defineProperties(symbol, {
__description__: d('', description),
__name__: d('', generateName(description))
});
};
defineProperties(SymbolPolyfill, {
for: d(function (key) {
if (globalSymbols[key]) return globalSymbols[key];
return (globalSymbols[key] = SymbolPolyfill(String(key)));
}),
keyFor: d(function (s) {
var key;
validateSymbol(s);
for (key in globalSymbols) if (globalSymbols[key] === s) return key;
}),
hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')),
isConcatSpreadable: d('', (NativeSymbol && NativeSymbol.isConcatSpreadable) ||
SymbolPolyfill('isConcatSpreadable')),
iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')),
match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')),
replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')),
search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')),
species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')),
split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')),
toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')),
toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')),
unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables'))
});
defineProperties(HiddenSymbol.prototype, {
constructor: d(SymbolPolyfill),
toString: d('', function () { return this.__name__; })
});
defineProperties(SymbolPolyfill.prototype, {
toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }),
valueOf: d(function () { return validateSymbol(this); })
});
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('',
function () { return validateSymbol(this); }));
defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol'));
defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]));
defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));
|
nlhuykhang/atom-config
|
packages/minimap/node_modules/event-kit/node_modules/grim/node_modules/emissary/node_modules/es6-weak-map/node_modules/es5-ext/node_modules/es6-symbol/polyfill.js
|
JavaScript
|
mit
| 3,506
|
var searchData=
[
['main_2ecpp',['main.cpp',['../main_8cpp.html',1,'']]]
];
|
escudero89/femris
|
tech-docs/html/search/files_2.js
|
JavaScript
|
lgpl-2.1
| 78
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import warning from 'warning';
import { canUseDOM } from './ExecutionEnvironment';
import { parsePath } from './PathUtils';
import runTransitionHook from './runTransitionHook';
import deprecate from './deprecate';
function useBasename(createHistory) {
return function () {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var history = createHistory(options);
var basename = options.basename;
var checkedBaseHref = false;
function checkBaseHref() {
if (checkedBaseHref) {
return;
}
// Automatically use the value of <base href> in HTML
// documents as basename if it's not explicitly given.
if (basename == null && canUseDOM) {
var base = document.getElementsByTagName('base')[0];
var baseHref = base && base.getAttribute('href');
if (baseHref != null) {
basename = baseHref;
process.env.NODE_ENV !== 'production' ? warning(false, 'Automatically setting basename using <base href> is deprecated and will ' + 'be removed in the next major release. The semantics of <base href> are ' + 'subtly different from basename. Please pass the basename explicitly in ' + 'the options to createHistory') : undefined;
}
}
checkedBaseHref = true;
}
function addBasename(location) {
checkBaseHref();
if (basename && location.basename == null) {
if (location.pathname.indexOf(basename) === 0) {
location.pathname = location.pathname.substring(basename.length);
location.basename = basename;
if (location.pathname === '') location.pathname = '/';
} else {
location.basename = '';
}
}
return location;
}
function prependBasename(location) {
checkBaseHref();
if (!basename) return location;
if (typeof location === 'string') location = parsePath(location);
var pname = location.pathname;
var normalizedBasename = basename.slice(-1) === '/' ? basename : basename + '/';
var normalizedPathname = pname.charAt(0) === '/' ? pname.slice(1) : pname;
var pathname = normalizedBasename + normalizedPathname;
return _extends({}, location, {
pathname: pathname
});
}
// Override all read methods with basename-aware versions.
function listenBefore(hook) {
return history.listenBefore(function (location, callback) {
runTransitionHook(hook, addBasename(location), callback);
});
}
function listen(listener) {
return history.listen(function (location) {
listener(addBasename(location));
});
}
// Override all write methods with basename-aware versions.
function push(location) {
history.push(prependBasename(location));
}
function replace(location) {
history.replace(prependBasename(location));
}
function createPath(location) {
return history.createPath(prependBasename(location));
}
function createHref(location) {
return history.createHref(prependBasename(location));
}
function createLocation(location) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return addBasename(history.createLocation.apply(history, [prependBasename(location)].concat(args)));
}
// deprecated
function pushState(state, path) {
if (typeof path === 'string') path = parsePath(path);
push(_extends({ state: state }, path));
}
// deprecated
function replaceState(state, path) {
if (typeof path === 'string') path = parsePath(path);
replace(_extends({ state: state }, path));
}
return _extends({}, history, {
listenBefore: listenBefore,
listen: listen,
push: push,
replace: replace,
createPath: createPath,
createHref: createHref,
createLocation: createLocation,
pushState: deprecate(pushState, 'pushState is deprecated; use push instead'),
replaceState: deprecate(replaceState, 'replaceState is deprecated; use replace instead')
});
};
}
export default useBasename;
|
lokiiart/upali-mobile
|
www/frontend/node_modules/history/es6/useBasename.js
|
JavaScript
|
gpl-3.0
| 4,510
|
/*
YUI 3.16.0 (build 76f0e08)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('node-screen', function (Y, NAME) {
/**
* Extended Node interface for managing regions and screen positioning.
* Adds support for positioning elements and normalizes window size and scroll detection.
* @module node
* @submodule node-screen
*/
// these are all "safe" returns, no wrapping required
Y.each([
/**
* Returns the inner width of the viewport (exludes scrollbar).
* @config winWidth
* @for Node
* @type {Number}
*/
'winWidth',
/**
* Returns the inner height of the viewport (exludes scrollbar).
* @config winHeight
* @type {Number}
*/
'winHeight',
/**
* Document width
* @config docWidth
* @type {Number}
*/
'docWidth',
/**
* Document height
* @config docHeight
* @type {Number}
*/
'docHeight',
/**
* Pixel distance the page has been scrolled horizontally
* @config docScrollX
* @type {Number}
*/
'docScrollX',
/**
* Pixel distance the page has been scrolled vertically
* @config docScrollY
* @type {Number}
*/
'docScrollY'
],
function(name) {
Y.Node.ATTRS[name] = {
getter: function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(Y.Node.getDOMNode(this));
return Y.DOM[name].apply(this, args);
}
};
}
);
Y.Node.ATTRS.scrollLeft = {
getter: function() {
var node = Y.Node.getDOMNode(this);
return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node);
},
setter: function(val) {
var node = Y.Node.getDOMNode(this);
if (node) {
if ('scrollLeft' in node) {
node.scrollLeft = val;
} else if (node.document || node.nodeType === 9) {
Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc
}
} else {
Y.log('unable to set scrollLeft for ' + node, 'error', 'Node');
}
}
};
Y.Node.ATTRS.scrollTop = {
getter: function() {
var node = Y.Node.getDOMNode(this);
return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node);
},
setter: function(val) {
var node = Y.Node.getDOMNode(this);
if (node) {
if ('scrollTop' in node) {
node.scrollTop = val;
} else if (node.document || node.nodeType === 9) {
Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc
}
} else {
Y.log('unable to set scrollTop for ' + node, 'error', 'Node');
}
}
};
Y.Node.importMethod(Y.DOM, [
/**
* Gets the current position of the node in page coordinates.
* @method getXY
* @for Node
* @return {Array} The XY position of the node
*/
'getXY',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setXY
* @param {Array} xy Contains X & Y values for new position (coordinates are page-based)
* @chainable
*/
'setXY',
/**
* Gets the current position of the node in page coordinates.
* @method getX
* @return {Number} The X position of the node
*/
'getX',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setX
* @param {Number} x X value for new position (coordinates are page-based)
* @chainable
*/
'setX',
/**
* Gets the current position of the node in page coordinates.
* @method getY
* @return {Number} The Y position of the node
*/
'getY',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setY
* @param {Number} y Y value for new position (coordinates are page-based)
* @chainable
*/
'setY',
/**
* Swaps the XY position of this node with another node.
* @method swapXY
* @param {Node | HTMLElement} otherNode The node to swap with.
* @chainable
*/
'swapXY'
]);
/**
* @module node
* @submodule node-screen
*/
/**
* Returns a region object for the node
* @config region
* @for Node
* @type Node
*/
Y.Node.ATTRS.region = {
getter: function() {
var node = this.getDOMNode(),
region;
if (node && !node.tagName) {
if (node.nodeType === 9) { // document
node = node.documentElement;
}
}
if (Y.DOM.isWindow(node)) {
region = Y.DOM.viewportRegion(node);
} else {
region = Y.DOM.region(node);
}
return region;
}
};
/**
* Returns a region object for the node's viewport
* @config viewportRegion
* @type Node
*/
Y.Node.ATTRS.viewportRegion = {
getter: function() {
return Y.DOM.viewportRegion(Y.Node.getDOMNode(this));
}
};
Y.Node.importMethod(Y.DOM, 'inViewportRegion');
// these need special treatment to extract 2nd node arg
/**
* Compares the intersection of the node with another node or region
* @method intersect
* @for Node
* @param {Node|Object} node2 The node or region to compare with.
* @param {Object} altRegion An alternate region to use (rather than this node's).
* @return {Object} An object representing the intersection of the regions.
*/
Y.Node.prototype.intersect = function(node2, altRegion) {
var node1 = Y.Node.getDOMNode(this);
if (Y.instanceOf(node2, Y.Node)) { // might be a region object
node2 = Y.Node.getDOMNode(node2);
}
return Y.DOM.intersect(node1, node2, altRegion);
};
/**
* Determines whether or not the node is within the given region.
* @method inRegion
* @param {Node|Object} node2 The node or region to compare with.
* @param {Boolean} all Whether or not all of the node must be in the region.
* @param {Object} altRegion An alternate region to use (rather than this node's).
* @return {Boolean} True if in region, false if not.
*/
Y.Node.prototype.inRegion = function(node2, all, altRegion) {
var node1 = Y.Node.getDOMNode(this);
if (Y.instanceOf(node2, Y.Node)) { // might be a region object
node2 = Y.Node.getDOMNode(node2);
}
return Y.DOM.inRegion(node1, node2, all, altRegion);
};
}, '3.16.0', {"requires": ["dom-screen", "node-base"]});
|
siscia/jsdelivr
|
files/yui/3.16.0/node-screen/node-screen-debug.js
|
JavaScript
|
mit
| 6,460
|
'use strict';
var global = require('../internals/global');
var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
var fails = require('../internals/fails');
var Int8Array = global.Int8Array;
var aTypedArray = ArrayBufferViewCore.aTypedArray;
var exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;
var $toLocaleString = [].toLocaleString;
var $slice = [].slice;
// iOS Safari 6.x fails here
var TO_LOCALE_STRING_BUG = !!Int8Array && fails(function () {
$toLocaleString.call(new Int8Array(1));
});
var FORCED = fails(function () {
return [1, 2].toLocaleString() != new Int8Array([1, 2]).toLocaleString();
}) || !fails(function () {
Int8Array.prototype.toLocaleString.call([1, 2]);
});
// `%TypedArray%.prototype.toLocaleString` method
// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tolocalestring
exportTypedArrayMethod('toLocaleString', function toLocaleString() {
return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray(this)) : aTypedArray(this), arguments);
}, FORCED);
|
BigBoss424/portfolio
|
v8/development/node_modules/jimp/node_modules/core-js/modules/es.typed-array.to-locale-string.js
|
JavaScript
|
apache-2.0
| 1,056
|
(function (global) {
var babelHelpers = global.babelHelpers = {};
babelHelpers.inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
babelHelpers.defaults = function (obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = Object.getOwnPropertyDescriptor(defaults, key);
if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}
return obj;
};
babelHelpers.createClass = (function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
babelHelpers.createDecoratedClass = (function () {
function defineProperties(target, descriptors, initializers) {
for (var i = 0; i < descriptors.length; i++) {
var descriptor = descriptors[i];
var decorators = descriptor.decorators;
var key = descriptor.key;
delete descriptor.key;
delete descriptor.decorators;
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor || descriptor.initializer) descriptor.writable = true;
if (decorators) {
for (var f = 0; f < decorators.length; f++) {
var decorator = decorators[f];
if (typeof decorator === "function") {
descriptor = decorator(target, key, descriptor) || descriptor;
} else {
throw new TypeError("The decorator for method " + descriptor.key + " is of the invalid type " + typeof decorator);
}
}
if (descriptor.initializer !== undefined) {
initializers[key] = descriptor;
continue;
}
}
Object.defineProperty(target, key, descriptor);
}
}
return function (Constructor, protoProps, staticProps, protoInitializers, staticInitializers) {
if (protoProps) defineProperties(Constructor.prototype, protoProps, protoInitializers);
if (staticProps) defineProperties(Constructor, staticProps, staticInitializers);
return Constructor;
};
})();
babelHelpers.createDecoratedObject = function (descriptors) {
var target = {};
for (var i = 0; i < descriptors.length; i++) {
var descriptor = descriptors[i];
var decorators = descriptor.decorators;
var key = descriptor.key;
delete descriptor.key;
delete descriptor.decorators;
descriptor.enumerable = true;
descriptor.configurable = true;
if ("value" in descriptor || descriptor.initializer) descriptor.writable = true;
if (decorators) {
for (var f = 0; f < decorators.length; f++) {
var decorator = decorators[f];
if (typeof decorator === "function") {
descriptor = decorator(target, key, descriptor) || descriptor;
} else {
throw new TypeError("The decorator for method " + descriptor.key + " is of the invalid type " + typeof decorator);
}
}
}
if (descriptor.initializer) {
descriptor.value = descriptor.initializer.call(target);
}
Object.defineProperty(target, key, descriptor);
}
return target;
};
babelHelpers.defineDecoratedPropertyDescriptor = function (target, key, descriptors) {
var _descriptor = descriptors[key];
if (!_descriptor) return;
var descriptor = {};
for (var _key in _descriptor) descriptor[_key] = _descriptor[_key];
descriptor.value = descriptor.initializer ? descriptor.initializer.call(target) : undefined;
Object.defineProperty(target, key, descriptor);
};
babelHelpers.taggedTemplateLiteral = function (strings, raw) {
return Object.freeze(Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw)
}
}));
};
babelHelpers.taggedTemplateLiteralLoose = function (strings, raw) {
strings.raw = raw;
return strings;
};
babelHelpers.toArray = function (arr) {
return Array.isArray(arr) ? arr : Array.from(arr);
};
babelHelpers.toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
babelHelpers.slicedToArray = (function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
})();
babelHelpers.slicedToArrayLoose = function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
var _arr = [];
for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {
_arr.push(_step.value);
if (i && _arr.length === i) break;
}
return _arr;
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
babelHelpers.objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
babelHelpers.hasOwn = Object.prototype.hasOwnProperty;
babelHelpers.slice = Array.prototype.slice;
babelHelpers.bind = Function.prototype.bind;
babelHelpers.defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
babelHelpers.asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
var callNext = step.bind(null, "next");
var callThrow = step.bind(null, "throw");
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(callNext, callThrow);
}
}
callNext();
});
};
};
babelHelpers.interopExportWildcard = function (obj, defaults) {
var newObj = defaults({}, obj);
delete newObj["default"];
return newObj;
};
babelHelpers.interopRequireWildcard = function (obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj["default"] = obj;
return newObj;
}
};
babelHelpers.interopRequireDefault = function (obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
};
babelHelpers._typeof = function (obj) {
return obj && obj.constructor === Symbol ? "symbol" : typeof obj;
};
babelHelpers._extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
babelHelpers.get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
babelHelpers.set = function set(object, property, value, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent !== null) {
set(parent, property, value, receiver);
}
} else if ("value" in desc && desc.writable) {
desc.value = value;
} else {
var setter = desc.set;
if (setter !== undefined) {
setter.call(receiver, value);
}
}
return value;
};
babelHelpers.newArrowCheck = function (innerThis, boundThis) {
if (innerThis !== boundThis) {
throw new TypeError("Cannot instantiate an arrow function");
}
};
babelHelpers.classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
babelHelpers.objectDestructuringEmpty = function (obj) {
if (obj == null) throw new TypeError("Cannot destructure undefined");
};
babelHelpers.temporalUndefined = {};
babelHelpers.temporalAssertDefined = function (val, name, undef) {
if (val === undef) {
throw new ReferenceError(name + " is not defined - temporal dead zone");
}
return true;
};
babelHelpers.selfGlobal = typeof global === "undefined" ? self : global;
babelHelpers.typeofReactElement = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 60103;
babelHelpers.defaultProps = function (defaultProps, props) {
if (defaultProps) {
for (var propName in defaultProps) {
if (typeof props[propName] === "undefined") {
props[propName] = defaultProps[propName];
}
}
}
return props;
};
babelHelpers._instanceof = function (left, right) {
if (right != null && right[Symbol.hasInstance]) {
return right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
};
babelHelpers.interopRequire = function (obj) {
return obj && obj.__esModule ? obj["default"] : obj;
};
})(typeof global === "undefined" ? self : global);
|
yuyang545262477/Resume
|
项目三jQueryMobile/node_modules/babel-core/external-helpers.js
|
JavaScript
|
mit
| 12,076
|
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"a".replace(/a/g, function() { return "c"; });
function test() {
try {
test();
} catch(e) {
"b".replace(/(b)/g, function() { return "c"; });
}
}
test();
|
ramyfarid922/Quiz-Program
|
vendor/bundle/ruby/2.2.0/gems/libv8-3.16.14.7/vendor/v8/test/mjsunit/regress/regress-148378.js
|
JavaScript
|
cc0-1.0
| 1,767
|
onconnect = function(event) {
var port = event.ports[0];
port.postMessage("Worker connected.");
port.onmessage = function(event2) {
port.postMessage("Worker got a port.");
var anotherport = event2.data.port;
anotherport.start();
anotherport.onmessage = function(event3) {
anotherport.postMessage("Worker got a message via the passed port.");
};
};
}
|
s20121035/rk3288_android5.1_repo
|
external/chromium_org/content/test/data/workers/messageport_worker.js
|
JavaScript
|
gpl-3.0
| 384
|
export const result = 'resource from path-restriction.wbn';
|
scheib/chromium
|
third_party/blink/web_tests/external/wpt/web-bundle/resources/path-restriction/wbn1/resource.js
|
JavaScript
|
bsd-3-clause
| 60
|
IntlMessageFormat.__addLocaleData({"locale":"bez","pluralRuleFunction":function (n,ord){if(ord)return"other";return n==1?"one":"other"}});
IntlMessageFormat.__addLocaleData({"locale":"bez-TZ","parentLocale":"bez"});
|
evilhei/blog
|
node_modules/intl-messageformat/dist/locale-data/bez.js
|
JavaScript
|
mit
| 216
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react/addons"));
else if(typeof define === 'function' && define.amd)
define(["react", "react/addons"], factory);
else if(typeof exports === 'object')
exports["Alt"] = factory(require("react"), require("react/addons"));
else
root["Alt"] = factory(root["react"], root["react/addons"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_20__, __WEBPACK_EXTERNAL_MODULE_25__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(13);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
/* global window */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _bind = Function.prototype.bind;
var _get = function get(_x3, _x4, _x5) { var _again = true; _function: while (_again) { var object = _x3, property = _x4, receiver = _x5; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x3 = parent; _x4 = property; _x5 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _flux = __webpack_require__(2);
var _utilsStateFunctions = __webpack_require__(5);
var StateFunctions = _interopRequireWildcard(_utilsStateFunctions);
var _utilsFunctions = __webpack_require__(6);
var fn = _interopRequireWildcard(_utilsFunctions);
var _store = __webpack_require__(7);
var store = _interopRequireWildcard(_store);
var _utilsAltUtils = __webpack_require__(8);
var utils = _interopRequireWildcard(_utilsAltUtils);
var _actions = __webpack_require__(12);
var _actions2 = _interopRequireDefault(_actions);
var Alt = (function () {
function Alt() {
var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
_classCallCheck(this, Alt);
this.config = config;
this.serialize = config.serialize || JSON.stringify;
this.deserialize = config.deserialize || JSON.parse;
this.dispatcher = config.dispatcher || new _flux.Dispatcher();
this.batchingFunction = config.batchingFunction || function (callback) {
return callback();
};
this.actions = { global: {} };
this.stores = {};
this.storeTransforms = config.storeTransforms || [];
this.trapAsync = false;
this._actionsRegistry = {};
this._initSnapshot = {};
this._lastSnapshot = {};
}
_createClass(Alt, [{
key: 'dispatch',
value: function dispatch(action, data, details) {
var _this = this;
this.batchingFunction(function () {
var id = Math.random().toString(18).substr(2, 16);
// support straight dispatching of FSA-style actions
if (action.type && action.payload) {
var fsaDetails = {
id: action.type,
namespace: action.type,
name: action.type
};
return _this.dispatcher.dispatch(utils.fsa(id, action.type, action.payload, fsaDetails));
}
if (action.id && action.dispatch) {
return utils.dispatch(id, action, data, _this);
}
return _this.dispatcher.dispatch(utils.fsa(id, action, data, details));
});
}
}, {
key: 'createUnsavedStore',
value: function createUnsavedStore(StoreModel) {
var key = StoreModel.displayName || '';
store.createStoreConfig(this.config, StoreModel);
var Store = store.transformStore(this.storeTransforms, StoreModel);
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return fn.isFunction(Store) ? store.createStoreFromClass.apply(store, [this, Store, key].concat(args)) : store.createStoreFromObject(this, Store, key);
}
}, {
key: 'createStore',
value: function createStore(StoreModel, iden) {
var key = iden || StoreModel.displayName || StoreModel.name || '';
store.createStoreConfig(this.config, StoreModel);
var Store = store.transformStore(this.storeTransforms, StoreModel);
/* istanbul ignore next */
if (false) delete this.stores[key];
if (this.stores[key] || !key) {
if (this.stores[key]) {
utils.warn('A store named ' + key + ' already exists, double check your store ' + 'names or pass in your own custom identifier for each store');
} else {
utils.warn('Store name was not specified');
}
key = utils.uid(this.stores, key);
}
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
var storeInstance = fn.isFunction(Store) ? store.createStoreFromClass.apply(store, [this, Store, key].concat(args)) : store.createStoreFromObject(this, Store, key);
this.stores[key] = storeInstance;
StateFunctions.saveInitialSnapshot(this, key);
return storeInstance;
}
}, {
key: 'generateActions',
value: function generateActions() {
var actions = { name: 'global' };
for (var _len3 = arguments.length, actionNames = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
actionNames[_key3] = arguments[_key3];
}
return this.createActions(actionNames.reduce(function (obj, action) {
obj[action] = utils.dispatchIdentity;
return obj;
}, actions));
}
}, {
key: 'createAction',
value: function createAction(name, implementation, obj) {
return (0, _actions2['default'])(this, 'global', name, implementation, obj);
}
}, {
key: 'createActions',
value: function createActions(ActionsClass) {
var _arguments2 = arguments,
_this2 = this;
var exportObj = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var actions = {};
var key = utils.uid(this._actionsRegistry, ActionsClass.displayName || ActionsClass.name || 'Unknown');
if (fn.isFunction(ActionsClass)) {
var _len4, argsForConstructor, _key4;
(function () {
fn.assign(actions, utils.getInternalMethods(ActionsClass, true));
var ActionsGenerator = (function (_ActionsClass) {
_inherits(ActionsGenerator, _ActionsClass);
function ActionsGenerator() {
_classCallCheck(this, ActionsGenerator);
for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
_get(Object.getPrototypeOf(ActionsGenerator.prototype), 'constructor', this).apply(this, args);
}
_createClass(ActionsGenerator, [{
key: 'generateActions',
value: function generateActions() {
for (var _len6 = arguments.length, actionNames = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
actionNames[_key6] = arguments[_key6];
}
actionNames.forEach(function (actionName) {
actions[actionName] = utils.dispatchIdentity;
});
}
}]);
return ActionsGenerator;
})(ActionsClass);
for (_len4 = _arguments2.length, argsForConstructor = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
argsForConstructor[_key4 - 2] = _arguments2[_key4];
}
fn.assign(actions, new (_bind.apply(ActionsGenerator, [null].concat(_toConsumableArray(argsForConstructor))))());
})();
} else {
fn.assign(actions, ActionsClass);
}
this.actions[key] = this.actions[key] || {};
fn.eachObject(function (actionName, action) {
if (!fn.isFunction(action)) {
return;
}
// create the action
exportObj[actionName] = (0, _actions2['default'])(_this2, key, actionName, action, exportObj);
// generate a constant
var constant = utils.formatAsConstant(actionName);
exportObj[constant] = exportObj[actionName].id;
}, [actions]);
return exportObj;
}
}, {
key: 'takeSnapshot',
value: function takeSnapshot() {
for (var _len7 = arguments.length, storeNames = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
storeNames[_key7] = arguments[_key7];
}
var state = StateFunctions.snapshot(this, storeNames);
fn.assign(this._lastSnapshot, state);
return this.serialize(state);
}
}, {
key: 'rollback',
value: function rollback() {
StateFunctions.setAppState(this, this.serialize(this._lastSnapshot), function (storeInst) {
storeInst.lifecycle('rollback');
storeInst.emitChange();
});
}
}, {
key: 'recycle',
value: function recycle() {
for (var _len8 = arguments.length, storeNames = Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
storeNames[_key8] = arguments[_key8];
}
var initialSnapshot = storeNames.length ? StateFunctions.filterSnapshots(this, this._initSnapshot, storeNames) : this._initSnapshot;
StateFunctions.setAppState(this, this.serialize(initialSnapshot), function (storeInst) {
storeInst.lifecycle('init');
storeInst.emitChange();
});
}
}, {
key: 'flush',
value: function flush() {
var state = this.serialize(StateFunctions.snapshot(this));
this.recycle();
return state;
}
}, {
key: 'bootstrap',
value: function bootstrap(data) {
StateFunctions.setAppState(this, data, function (storeInst, state) {
storeInst.lifecycle('bootstrap', state);
storeInst.emitChange();
});
}
}, {
key: 'prepare',
value: function prepare(storeInst, payload) {
var data = {};
if (!storeInst.displayName) {
throw new ReferenceError('Store provided does not have a name');
}
data[storeInst.displayName] = payload;
return this.serialize(data);
}
// Instance type methods for injecting alt into your application as context
}, {
key: 'addActions',
value: function addActions(name, ActionsClass) {
for (var _len9 = arguments.length, args = Array(_len9 > 2 ? _len9 - 2 : 0), _key9 = 2; _key9 < _len9; _key9++) {
args[_key9 - 2] = arguments[_key9];
}
this.actions[name] = Array.isArray(ActionsClass) ? this.generateActions.apply(this, ActionsClass) : this.createActions.apply(this, [ActionsClass].concat(args));
}
}, {
key: 'addStore',
value: function addStore(name, StoreModel) {
for (var _len10 = arguments.length, args = Array(_len10 > 2 ? _len10 - 2 : 0), _key10 = 2; _key10 < _len10; _key10++) {
args[_key10 - 2] = arguments[_key10];
}
this.createStore.apply(this, [StoreModel, name].concat(args));
}
}, {
key: 'getActions',
value: function getActions(name) {
return this.actions[name];
}
}, {
key: 'getStore',
value: function getStore(name) {
return this.stores[name];
}
}], [{
key: 'debug',
value: function debug(name, alt) {
var key = 'alt.js.org';
if (typeof window !== 'undefined') {
window[key] = window[key] || [];
window[key].push({ name: name, alt: alt });
}
return alt;
}
}]);
return Alt;
})();
exports['default'] = Alt;
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
module.exports.Dispatcher = __webpack_require__(3)
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Dispatcher
* @typechecks
*/
"use strict";
var invariant = __webpack_require__(4);
var _lastID = 1;
var _prefix = 'ID_';
/**
* Dispatcher is used to broadcast payloads to registered callbacks. This is
* different from generic pub-sub systems in two ways:
*
* 1) Callbacks are not subscribed to particular events. Every payload is
* dispatched to every registered callback.
* 2) Callbacks can be deferred in whole or part until other callbacks have
* been executed.
*
* For example, consider this hypothetical flight destination form, which
* selects a default city when a country is selected:
*
* var flightDispatcher = new Dispatcher();
*
* // Keeps track of which country is selected
* var CountryStore = {country: null};
*
* // Keeps track of which city is selected
* var CityStore = {city: null};
*
* // Keeps track of the base flight price of the selected city
* var FlightPriceStore = {price: null}
*
* When a user changes the selected city, we dispatch the payload:
*
* flightDispatcher.dispatch({
* actionType: 'city-update',
* selectedCity: 'paris'
* });
*
* This payload is digested by `CityStore`:
*
* flightDispatcher.register(function(payload) {
* if (payload.actionType === 'city-update') {
* CityStore.city = payload.selectedCity;
* }
* });
*
* When the user selects a country, we dispatch the payload:
*
* flightDispatcher.dispatch({
* actionType: 'country-update',
* selectedCountry: 'australia'
* });
*
* This payload is digested by both stores:
*
* CountryStore.dispatchToken = flightDispatcher.register(function(payload) {
* if (payload.actionType === 'country-update') {
* CountryStore.country = payload.selectedCountry;
* }
* });
*
* When the callback to update `CountryStore` is registered, we save a reference
* to the returned token. Using this token with `waitFor()`, we can guarantee
* that `CountryStore` is updated before the callback that updates `CityStore`
* needs to query its data.
*
* CityStore.dispatchToken = flightDispatcher.register(function(payload) {
* if (payload.actionType === 'country-update') {
* // `CountryStore.country` may not be updated.
* flightDispatcher.waitFor([CountryStore.dispatchToken]);
* // `CountryStore.country` is now guaranteed to be updated.
*
* // Select the default city for the new country
* CityStore.city = getDefaultCityForCountry(CountryStore.country);
* }
* });
*
* The usage of `waitFor()` can be chained, for example:
*
* FlightPriceStore.dispatchToken =
* flightDispatcher.register(function(payload) {
* switch (payload.actionType) {
* case 'country-update':
* flightDispatcher.waitFor([CityStore.dispatchToken]);
* FlightPriceStore.price =
* getFlightPriceStore(CountryStore.country, CityStore.city);
* break;
*
* case 'city-update':
* FlightPriceStore.price =
* FlightPriceStore(CountryStore.country, CityStore.city);
* break;
* }
* });
*
* The `country-update` payload will be guaranteed to invoke the stores'
* registered callbacks in order: `CountryStore`, `CityStore`, then
* `FlightPriceStore`.
*/
function Dispatcher() {
this.$Dispatcher_callbacks = {};
this.$Dispatcher_isPending = {};
this.$Dispatcher_isHandled = {};
this.$Dispatcher_isDispatching = false;
this.$Dispatcher_pendingPayload = null;
}
/**
* Registers a callback to be invoked with every dispatched payload. Returns
* a token that can be used with `waitFor()`.
*
* @param {function} callback
* @return {string}
*/
Dispatcher.prototype.register=function(callback) {
var id = _prefix + _lastID++;
this.$Dispatcher_callbacks[id] = callback;
return id;
};
/**
* Removes a callback based on its token.
*
* @param {string} id
*/
Dispatcher.prototype.unregister=function(id) {
invariant(
this.$Dispatcher_callbacks[id],
'Dispatcher.unregister(...): `%s` does not map to a registered callback.',
id
);
delete this.$Dispatcher_callbacks[id];
};
/**
* Waits for the callbacks specified to be invoked before continuing execution
* of the current callback. This method should only be used by a callback in
* response to a dispatched payload.
*
* @param {array<string>} ids
*/
Dispatcher.prototype.waitFor=function(ids) {
invariant(
this.$Dispatcher_isDispatching,
'Dispatcher.waitFor(...): Must be invoked while dispatching.'
);
for (var ii = 0; ii < ids.length; ii++) {
var id = ids[ii];
if (this.$Dispatcher_isPending[id]) {
invariant(
this.$Dispatcher_isHandled[id],
'Dispatcher.waitFor(...): Circular dependency detected while ' +
'waiting for `%s`.',
id
);
continue;
}
invariant(
this.$Dispatcher_callbacks[id],
'Dispatcher.waitFor(...): `%s` does not map to a registered callback.',
id
);
this.$Dispatcher_invokeCallback(id);
}
};
/**
* Dispatches a payload to all registered callbacks.
*
* @param {object} payload
*/
Dispatcher.prototype.dispatch=function(payload) {
invariant(
!this.$Dispatcher_isDispatching,
'Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.'
);
this.$Dispatcher_startDispatching(payload);
try {
for (var id in this.$Dispatcher_callbacks) {
if (this.$Dispatcher_isPending[id]) {
continue;
}
this.$Dispatcher_invokeCallback(id);
}
} finally {
this.$Dispatcher_stopDispatching();
}
};
/**
* Is this Dispatcher currently dispatching.
*
* @return {boolean}
*/
Dispatcher.prototype.isDispatching=function() {
return this.$Dispatcher_isDispatching;
};
/**
* Call the callback stored with the given id. Also do some internal
* bookkeeping.
*
* @param {string} id
* @internal
*/
Dispatcher.prototype.$Dispatcher_invokeCallback=function(id) {
this.$Dispatcher_isPending[id] = true;
this.$Dispatcher_callbacks[id](this.$Dispatcher_pendingPayload);
this.$Dispatcher_isHandled[id] = true;
};
/**
* Set up bookkeeping needed when dispatching.
*
* @param {object} payload
* @internal
*/
Dispatcher.prototype.$Dispatcher_startDispatching=function(payload) {
for (var id in this.$Dispatcher_callbacks) {
this.$Dispatcher_isPending[id] = false;
this.$Dispatcher_isHandled[id] = false;
}
this.$Dispatcher_pendingPayload = payload;
this.$Dispatcher_isDispatching = true;
};
/**
* Clear bookkeeping used for dispatching.
*
* @internal
*/
Dispatcher.prototype.$Dispatcher_stopDispatching=function() {
this.$Dispatcher_pendingPayload = null;
this.$Dispatcher_isDispatching = false;
};
module.exports = Dispatcher;
/***/ },
/* 4 */
/***/ function(module, exports) {
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
"use strict";
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if (false) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
'Invariant Violation: ' +
format.replace(/%s/g, function() { return args[argIndex++]; })
);
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.setAppState = setAppState;
exports.snapshot = snapshot;
exports.saveInitialSnapshot = saveInitialSnapshot;
exports.filterSnapshots = filterSnapshots;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsFunctions = __webpack_require__(6);
var fn = _interopRequireWildcard(_utilsFunctions);
function setAppState(instance, data, onStore) {
var obj = instance.deserialize(data);
fn.eachObject(function (key, value) {
var store = instance.stores[key];
if (store) {
(function () {
var config = store.StoreModel.config;
var state = store.state;
if (config.onDeserialize) obj[key] = config.onDeserialize(value) || value;
if (fn.isPojo(state)) {
fn.eachObject(function (k) {
return delete state[k];
}, [state]);
fn.assign(state, obj[key]);
} else {
store.state = obj[key];
}
onStore(store, store.state);
})();
}
}, [obj]);
}
function snapshot(instance) {
var storeNames = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
var stores = storeNames.length ? storeNames : Object.keys(instance.stores);
return stores.reduce(function (obj, storeHandle) {
var storeName = storeHandle.displayName || storeHandle;
var store = instance.stores[storeName];
var config = store.StoreModel.config;
store.lifecycle('snapshot');
var customSnapshot = config.onSerialize && config.onSerialize(store.state);
obj[storeName] = customSnapshot ? customSnapshot : store.getState();
return obj;
}, {});
}
function saveInitialSnapshot(instance, key) {
var state = instance.deserialize(instance.serialize(instance.stores[key].state));
instance._initSnapshot[key] = state;
instance._lastSnapshot[key] = state;
}
function filterSnapshots(instance, state, stores) {
return stores.reduce(function (obj, store) {
var storeName = store.displayName || store;
if (!state[storeName]) {
throw new ReferenceError(storeName + ' is not a valid store');
}
obj[storeName] = state[storeName];
return obj;
}, {});
}
/***/ },
/* 6 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.isPojo = isPojo;
exports.isPromise = isPromise;
exports.eachObject = eachObject;
exports.assign = assign;
var isFunction = function isFunction(x) {
return typeof x === 'function';
};
exports.isFunction = isFunction;
function isPojo(target) {
var Ctor = target.constructor;
return !!target && typeof target === 'object' && Object.prototype.toString.call(target) === '[object Object]' && isFunction(Ctor) && (Ctor instanceof Ctor || target.type === 'AltStore');
}
function isPromise(obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
function eachObject(f, o) {
o.forEach(function (from) {
Object.keys(Object(from)).forEach(function (key) {
f(key, from[key]);
});
});
}
function assign(target) {
for (var _len = arguments.length, source = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
source[_key - 1] = arguments[_key];
}
eachObject(function (key, value) {
return target[key] = value;
}, source);
return target;
}
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _bind = Function.prototype.bind;
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
exports.createStoreConfig = createStoreConfig;
exports.transformStore = transformStore;
exports.createStoreFromObject = createStoreFromObject;
exports.createStoreFromClass = createStoreFromClass;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _utilsAltUtils = __webpack_require__(8);
var utils = _interopRequireWildcard(_utilsAltUtils);
var _utilsFunctions = __webpack_require__(6);
var fn = _interopRequireWildcard(_utilsFunctions);
var _AltStore = __webpack_require__(9);
var _AltStore2 = _interopRequireDefault(_AltStore);
var _StoreMixin = __webpack_require__(11);
var _StoreMixin2 = _interopRequireDefault(_StoreMixin);
function doSetState(store, storeInstance, state) {
if (!state) {
return;
}
var config = storeInstance.StoreModel.config;
var nextState = fn.isFunction(state) ? state(storeInstance.state) : state;
storeInstance.state = config.setState.call(store, storeInstance.state, nextState);
if (!store.alt.dispatcher.isDispatching()) {
store.emitChange();
}
}
function createPrototype(proto, alt, key, extras) {
return fn.assign(proto, _StoreMixin2['default'], {
displayName: key,
alt: alt,
dispatcher: alt.dispatcher,
preventDefault: function preventDefault() {
this.getInstance().preventDefault = true;
},
boundListeners: [],
lifecycleEvents: {},
actionListeners: {},
publicMethods: {},
handlesOwnErrors: false
}, extras);
}
function createStoreConfig(globalConfig, StoreModel) {
StoreModel.config = fn.assign({
getState: function getState(state) {
if (Array.isArray(state)) {
return state.slice();
} else if (fn.isPojo(state)) {
return fn.assign({}, state);
}
return state;
},
setState: function setState(currentState, nextState) {
if (fn.isPojo(nextState)) {
return fn.assign(currentState, nextState);
}
return nextState;
}
}, globalConfig, StoreModel.config);
}
function transformStore(transforms, StoreModel) {
return transforms.reduce(function (Store, transform) {
return transform(Store);
}, StoreModel);
}
function createStoreFromObject(alt, StoreModel, key) {
var storeInstance = undefined;
var StoreProto = createPrototype({}, alt, key, fn.assign({
getInstance: function getInstance() {
return storeInstance;
},
setState: function setState(nextState) {
doSetState(this, storeInstance, nextState);
}
}, StoreModel));
// bind the store listeners
/* istanbul ignore else */
if (StoreProto.bindListeners) {
_StoreMixin2['default'].bindListeners.call(StoreProto, StoreProto.bindListeners);
}
/* istanbul ignore else */
if (StoreProto.observe) {
_StoreMixin2['default'].bindListeners.call(StoreProto, StoreProto.observe(alt));
}
// bind the lifecycle events
/* istanbul ignore else */
if (StoreProto.lifecycle) {
fn.eachObject(function (eventName, event) {
_StoreMixin2['default'].on.call(StoreProto, eventName, event);
}, [StoreProto.lifecycle]);
}
// create the instance and fn.assign the public methods to the instance
storeInstance = fn.assign(new _AltStore2['default'](alt, StoreProto, StoreProto.state !== undefined ? StoreProto.state : {}, StoreModel), StoreProto.publicMethods, { displayName: key });
return storeInstance;
}
function createStoreFromClass(alt, StoreModel, key) {
var storeInstance = undefined;
var config = StoreModel.config;
// Creating a class here so we don't overload the provided store's
// prototype with the mixin behaviour and I'm extending from StoreModel
// so we can inherit any extensions from the provided store.
var Store = (function (_StoreModel) {
_inherits(Store, _StoreModel);
function Store() {
_classCallCheck(this, Store);
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_get(Object.getPrototypeOf(Store.prototype), 'constructor', this).apply(this, args);
}
return Store;
})(StoreModel);
createPrototype(Store.prototype, alt, key, {
type: 'AltStore',
getInstance: function getInstance() {
return storeInstance;
},
setState: function setState(nextState) {
doSetState(this, storeInstance, nextState);
}
});
for (var _len = arguments.length, argsForClass = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
argsForClass[_key - 3] = arguments[_key];
}
var store = new (_bind.apply(Store, [null].concat(argsForClass)))();
if (config.bindListeners) store.bindListeners(config.bindListeners);
if (config.datasource) store.registerAsync(config.datasource);
storeInstance = fn.assign(new _AltStore2['default'](alt, store, store.state !== undefined ? store.state : store, StoreModel), utils.getInternalMethods(StoreModel), config.publicMethods, { displayName: key });
return storeInstance;
}
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.getInternalMethods = getInternalMethods;
exports.warn = warn;
exports.uid = uid;
exports.formatAsConstant = formatAsConstant;
exports.dispatchIdentity = dispatchIdentity;
exports.fsa = fsa;
exports.dispatch = dispatch;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsFunctions = __webpack_require__(6);
var fn = _interopRequireWildcard(_utilsFunctions);
/*eslint-disable*/
var builtIns = Object.getOwnPropertyNames(NoopClass);
var builtInProto = Object.getOwnPropertyNames(NoopClass.prototype);
/*eslint-enable*/
function getInternalMethods(Obj, isProto) {
var excluded = isProto ? builtInProto : builtIns;
var obj = isProto ? Obj.prototype : Obj;
return Object.getOwnPropertyNames(obj).reduce(function (value, m) {
if (excluded.indexOf(m) !== -1) {
return value;
}
value[m] = obj[m];
return value;
}, {});
}
function warn(msg) {
/* istanbul ignore else */
/*eslint-disable*/
if (typeof console !== 'undefined') {
console.warn(new ReferenceError(msg));
}
/*eslint-enable*/
}
function uid(container, name) {
var count = 0;
var key = name;
while (Object.hasOwnProperty.call(container, key)) {
key = name + String(++count);
}
return key;
}
function formatAsConstant(name) {
return name.replace(/[a-z]([A-Z])/g, function (i) {
return i[0] + '_' + i[1].toLowerCase();
}).toUpperCase();
}
function dispatchIdentity(x) {
for (var _len = arguments.length, a = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
a[_key - 1] = arguments[_key];
}
this.dispatch(a.length ? [x].concat(a) : x);
}
function fsa(id, type, payload, details) {
return {
type: type,
payload: payload,
meta: _extends({
dispatchId: id
}, details),
id: id,
action: type,
data: payload,
details: details
};
}
function dispatch(id, actionObj, payload, alt) {
var data = actionObj.dispatch(payload);
if (data === undefined) return null;
var type = actionObj.id;
var namespace = type;
var name = type;
var details = { id: type, namespace: namespace, name: name };
var dispatchLater = function dispatchLater(x) {
return alt.dispatch(type, x, details);
};
if (fn.isFunction(data)) return data(dispatchLater, alt);
// XXX standardize this
return alt.dispatcher.dispatch(fsa(id, type, data, details));
}
/* istanbul ignore next */
function NoopClass() {}
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _utilsFunctions = __webpack_require__(6);
var fn = _interopRequireWildcard(_utilsFunctions);
var _transmitter = __webpack_require__(10);
var _transmitter2 = _interopRequireDefault(_transmitter);
var AltStore = (function () {
function AltStore(alt, model, state, StoreModel) {
var _this = this;
_classCallCheck(this, AltStore);
var lifecycleEvents = model.lifecycleEvents;
this.transmitter = (0, _transmitter2['default'])();
this.lifecycle = function (event, x) {
if (lifecycleEvents[event]) lifecycleEvents[event].push(x);
};
this.state = state;
this.alt = alt;
this.preventDefault = false;
this.displayName = model.displayName;
this.boundListeners = model.boundListeners;
this.StoreModel = StoreModel;
this.reduce = model.reduce || function (x) {
return x;
};
var output = model.output || function (x) {
return x;
};
this.emitChange = function () {
return _this.transmitter.push(output(_this.state));
};
var handleDispatch = function handleDispatch(f, payload) {
try {
return f();
} catch (e) {
if (model.handlesOwnErrors) {
_this.lifecycle('error', {
error: e,
payload: payload,
state: _this.state
});
return false;
}
throw e;
}
};
fn.assign(this, model.publicMethods);
// Register dispatcher
this.dispatchToken = alt.dispatcher.register(function (payload) {
_this.preventDefault = false;
_this.lifecycle('beforeEach', {
payload: payload,
state: _this.state
});
var actionHandlers = model.actionListeners[payload.action];
if (actionHandlers || model.otherwise) {
var result = undefined;
if (actionHandlers) {
result = handleDispatch(function () {
return actionHandlers.filter(Boolean).every(function (handler) {
return handler.call(model, payload.data, payload.action) !== false;
});
}, payload);
} else {
result = handleDispatch(function () {
return model.otherwise(payload.data, payload.action);
}, payload);
}
if (result !== false && !_this.preventDefault) _this.emitChange();
}
if (model.reduce) {
handleDispatch(function () {
var value = model.reduce(_this.state, payload);
if (value !== undefined) _this.state = value;
}, payload);
if (!_this.preventDefault) _this.emitChange();
}
_this.lifecycle('afterEach', {
payload: payload,
state: _this.state
});
});
this.lifecycle('init');
}
_createClass(AltStore, [{
key: 'listen',
value: function listen(cb) {
var _this2 = this;
if (!fn.isFunction(cb)) throw new TypeError('listen expects a function');
this.transmitter.subscribe(cb);
return function () {
return _this2.unlisten(cb);
};
}
}, {
key: 'unlisten',
value: function unlisten(cb) {
this.lifecycle('unlisten');
this.transmitter.unsubscribe(cb);
}
}, {
key: 'getState',
value: function getState() {
return this.StoreModel.config.getState.call(this, this.state);
}
}]);
return AltStore;
})();
exports['default'] = AltStore;
module.exports = exports['default'];
/***/ },
/* 10 */
/***/ function(module, exports) {
"use strict";
function transmitter() {
var subscriptions = [];
var unsubscribe = function unsubscribe(onChange) {
var id = subscriptions.indexOf(onChange);
if (id >= 0) subscriptions.splice(id, 1);
};
var subscribe = function subscribe(onChange) {
subscriptions.push(onChange);
var dispose = function dispose() {
return unsubscribe(onChange);
};
return { dispose: dispose };
};
var push = function push(value) {
subscriptions.forEach(function (subscription) {
return subscription(value);
});
};
return { subscribe: subscribe, push: push, unsubscribe: unsubscribe };
}
module.exports = transmitter;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _transmitter = __webpack_require__(10);
var _transmitter2 = _interopRequireDefault(_transmitter);
var _utilsFunctions = __webpack_require__(6);
var fn = _interopRequireWildcard(_utilsFunctions);
var StoreMixin = {
waitFor: function waitFor() {
for (var _len = arguments.length, sources = Array(_len), _key = 0; _key < _len; _key++) {
sources[_key] = arguments[_key];
}
if (!sources.length) {
throw new ReferenceError('Dispatch tokens not provided');
}
var sourcesArray = sources;
if (sources.length === 1) {
sourcesArray = Array.isArray(sources[0]) ? sources[0] : sources;
}
var tokens = sourcesArray.map(function (source) {
return source.dispatchToken || source;
});
this.dispatcher.waitFor(tokens);
},
exportAsync: function exportAsync(asyncMethods) {
this.registerAsync(asyncMethods);
},
registerAsync: function registerAsync(asyncDef) {
var _this = this;
var loadCounter = 0;
var asyncMethods = fn.isFunction(asyncDef) ? asyncDef(this.alt) : asyncDef;
var toExport = Object.keys(asyncMethods).reduce(function (publicMethods, methodName) {
var desc = asyncMethods[methodName];
var spec = fn.isFunction(desc) ? desc(_this) : desc;
var validHandlers = ['success', 'error', 'loading'];
validHandlers.forEach(function (handler) {
if (spec[handler] && !spec[handler].id) {
throw new Error(handler + ' handler must be an action function');
}
});
publicMethods[methodName] = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var state = _this.getInstance().getState();
var value = spec.local && spec.local.apply(spec, [state].concat(args));
var shouldFetch = spec.shouldFetch ? spec.shouldFetch.apply(spec, [state].concat(args))
/*eslint-disable*/
: value == null;
/*eslint-enable*/
var intercept = spec.interceptResponse || function (x) {
return x;
};
var makeActionHandler = function makeActionHandler(action, isError) {
return function (x) {
var fire = function fire() {
loadCounter -= 1;
action(intercept(x, action, args));
if (isError) throw x;
};
return _this.alt.trapAsync ? function () {
return fire();
} : fire();
};
};
// if we don't have it in cache then fetch it
if (shouldFetch) {
loadCounter += 1;
/* istanbul ignore else */
if (spec.loading) spec.loading(intercept(null, spec.loading, args));
return spec.remote.apply(spec, [state].concat(args)).then(makeActionHandler(spec.success), makeActionHandler(spec.error, 1));
}
// otherwise emit the change now
_this.emitChange();
return value;
};
return publicMethods;
}, {});
this.exportPublicMethods(toExport);
this.exportPublicMethods({
isLoading: function isLoading() {
return loadCounter > 0;
}
});
},
exportPublicMethods: function exportPublicMethods(methods) {
var _this2 = this;
fn.eachObject(function (methodName, value) {
if (!fn.isFunction(value)) {
throw new TypeError('exportPublicMethods expects a function');
}
_this2.publicMethods[methodName] = value;
}, [methods]);
},
emitChange: function emitChange() {
this.getInstance().emitChange();
},
on: function on(lifecycleEvent, handler) {
if (lifecycleEvent === 'error') this.handlesOwnErrors = true;
var bus = this.lifecycleEvents[lifecycleEvent] || (0, _transmitter2['default'])();
this.lifecycleEvents[lifecycleEvent] = bus;
return bus.subscribe(handler.bind(this));
},
bindAction: function bindAction(symbol, handler) {
if (!symbol) {
throw new ReferenceError('Invalid action reference passed in');
}
if (!fn.isFunction(handler)) {
throw new TypeError('bindAction expects a function');
}
if (handler.length > 1) {
throw new TypeError('Action handler in store ' + this.displayName + ' for ' + ((symbol.id || symbol).toString() + ' was defined with ') + 'two parameters. Only a single parameter is passed through the ' + 'dispatcher, did you mean to pass in an Object instead?');
}
// You can pass in the constant or the function itself
var key = symbol.id ? symbol.id : symbol;
this.actionListeners[key] = this.actionListeners[key] || [];
this.actionListeners[key].push(handler.bind(this));
this.boundListeners.push(key);
},
bindActions: function bindActions(actions) {
var _this3 = this;
fn.eachObject(function (action, symbol) {
var matchFirstCharacter = /./;
var assumedEventHandler = action.replace(matchFirstCharacter, function (x) {
return 'on' + x[0].toUpperCase();
});
if (_this3[action] && _this3[assumedEventHandler]) {
// If you have both action and onAction
throw new ReferenceError('You have multiple action handlers bound to an action: ' + (action + ' and ' + assumedEventHandler));
}
var handler = _this3[action] || _this3[assumedEventHandler];
if (handler) {
_this3.bindAction(symbol, handler);
}
}, [actions]);
},
bindListeners: function bindListeners(obj) {
var _this4 = this;
fn.eachObject(function (methodName, symbol) {
var listener = _this4[methodName];
if (!listener) {
throw new ReferenceError(methodName + ' defined but does not exist in ' + _this4.displayName);
}
if (Array.isArray(symbol)) {
symbol.forEach(function (action) {
_this4.bindAction(action, listener);
});
} else {
_this4.bindAction(symbol, listener);
}
}, [obj]);
}
};
exports['default'] = StoreMixin;
module.exports = exports['default'];
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
exports['default'] = makeAction;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _utilsFunctions = __webpack_require__(6);
var fn = _interopRequireWildcard(_utilsFunctions);
var _utilsAltUtils = __webpack_require__(8);
var utils = _interopRequireWildcard(_utilsAltUtils);
var AltAction = (function () {
function AltAction(alt, id, action, actions, actionDetails) {
_classCallCheck(this, AltAction);
this.id = id;
this._dispatch = action.bind(this);
this.actions = actions;
this.actionDetails = actionDetails;
this.alt = alt;
}
_createClass(AltAction, [{
key: 'dispatch',
value: function dispatch(data) {
this.dispatched = true;
this.alt.dispatch(this.id, data, this.actionDetails);
}
}]);
return AltAction;
})();
function makeAction(alt, namespace, name, implementation, obj) {
var id = utils.uid(alt._actionsRegistry, namespace + '.' + name);
alt._actionsRegistry[id] = 1;
var data = { id: id, namespace: namespace, name: name };
// Wrap the action so we can provide a dispatch method
var newAction = new AltAction(alt, id, implementation, obj, data);
var dispatch = function dispatch(payload) {
return alt.dispatch(id, payload, data);
};
// the action itself
var action = function action() {
newAction.dispatched = false;
var result = newAction._dispatch.apply(newAction, arguments);
// async functions that return promises should not be dispatched
if (!newAction.dispatched && result !== undefined && !fn.isPromise(result)) {
if (fn.isFunction(result)) {
result(dispatch, alt);
} else {
dispatch(result);
}
}
return result;
};
action.defer = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
setTimeout(function () {
newAction._dispatch.apply(null, args);
});
};
action.id = id;
action.data = data;
// ensure each reference is unique in the namespace
var container = alt.actions[namespace];
var namespaceId = utils.uid(container, name);
container[namespaceId] = action;
return action;
}
module.exports = exports['default'];
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _ = __webpack_require__(1);
var _2 = _interopRequireDefault(_);
var _utilsActionListeners = __webpack_require__(14);
var _utilsActionListeners2 = _interopRequireDefault(_utilsActionListeners);
var _utilsAltManager = __webpack_require__(15);
var _utilsAltManager2 = _interopRequireDefault(_utilsAltManager);
var _utilsDispatcherRecorder = __webpack_require__(16);
var _utilsDispatcherRecorder2 = _interopRequireDefault(_utilsDispatcherRecorder);
var _utilsAtomic = __webpack_require__(17);
var _utilsAtomic2 = _interopRequireDefault(_utilsAtomic);
var _utilsConnectToStores = __webpack_require__(19);
var _utilsConnectToStores2 = _interopRequireDefault(_utilsConnectToStores);
var _utilsChromeDebug = __webpack_require__(21);
var _utilsChromeDebug2 = _interopRequireDefault(_utilsChromeDebug);
var _utilsMakeFinalStore = __webpack_require__(18);
var _utilsMakeFinalStore2 = _interopRequireDefault(_utilsMakeFinalStore);
var _utilsWithAltContext = __webpack_require__(22);
var _utilsWithAltContext2 = _interopRequireDefault(_utilsWithAltContext);
var _AltContainer = __webpack_require__(23);
var _AltContainer2 = _interopRequireDefault(_AltContainer);
_2['default'].addons = {
ActionListeners: _utilsActionListeners2['default'],
AltContainer: _AltContainer2['default'],
AltManager: _utilsAltManager2['default'],
DispatcherRecorder: _utilsDispatcherRecorder2['default'],
atomic: _utilsAtomic2['default'],
chromeDebug: _utilsChromeDebug2['default'],
connectToStores: _utilsConnectToStores2['default'],
makeFinalStore: _utilsMakeFinalStore2['default'],
withAltContext: _utilsWithAltContext2['default']
};
exports['default'] = _2['default'];
module.exports = exports['default'];
/***/ },
/* 14 */
/***/ function(module, exports) {
/**
* ActionListeners(alt: AltInstance): ActionListenersInstance
*
* > Globally listen to individual actions
*
* If you need to listen to an action but don't want the weight of a store
* then this util is what you can use.
*
* Usage:
*
* ```js
* var actionListener = new ActionListeners(alt);
*
* actionListener.addActionListener(Action.ACTION_NAME, function (data) {
* // do something with data
* })
* ```
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function ActionListeners(alt) {
this.dispatcher = alt.dispatcher;
this.listeners = {};
}
/*
* addActionListener(symAction: symbol, handler: function): number
* Adds a listener to a specified action and returns the dispatch token.
*/
ActionListeners.prototype.addActionListener = function addActionListener(symAction, handler) {
var id = this.dispatcher.register(function (payload) {
/* istanbul ignore else */
if (symAction === payload.action) {
handler(payload.data, payload.details);
}
});
this.listeners[id] = true;
return id;
};
/*
* removeActionListener(id: number): undefined
* Removes the specified dispatch registration.
*/
ActionListeners.prototype.removeActionListener = function removeActionListener(id) {
delete this.listeners[id];
this.dispatcher.unregister(id);
};
/**
* Remove all listeners.
*/
ActionListeners.prototype.removeAllActionListeners = function removeAllActionListeners() {
Object.keys(this.listeners).forEach(this.removeActionListener.bind(this));
this.listeners = {};
};
exports["default"] = ActionListeners;
module.exports = exports["default"];
/***/ },
/* 15 */
/***/ function(module, exports) {
/**
* AltManager(Alt: AltClass): undefined
*
* > AltManager Util
*
* AltManager util allows for a developer to create multiple alt instances in
* their app. This is useful for building apps that encapsulates an alt instance
* inside of a outer parent. Popular examples include HipMunk flight search or
* Google Spreadsheets's multiple sheet tabs. This also allows for caching of
* client side instance if you need to store a new copy of an alt for each
* action.
*
* Usage:
*
* ```js
* var Alt = require('alt'); // Alt class, not alt instance
* var altManager = new AltManager(Alt);
*
* var altInstance = altManager.create('uniqueKeyName');
* altInstance.createAction(SomeAction);
* var someOtherOtherAlt = altManager.create('anotherKeyName');
* altManager.delete('uniqueKeyName');
*
* ```
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var AltManager = (function () {
function AltManager(Alt) {
_classCallCheck(this, AltManager);
this.Alt = Alt;
this.alts = {};
}
_createClass(AltManager, [{
key: 'create',
value: function create(altKey) {
if (this.get(altKey)) {
throw new ReferenceError('Alt key ' + altKey + ' already exists');
}
if (typeof altKey !== 'string') {
throw new TypeError('altKey must be a string');
}
this.alts[altKey] = new this.Alt();
return this.alts[altKey];
}
}, {
key: 'get',
value: function get(altKey) {
return this.alts[altKey];
}
// returns all alt instances
}, {
key: 'all',
value: function all() {
return this.alts;
}
}, {
key: 'findWhere',
value: function findWhere(regex) {
var results = {};
for (var i in this.alts) {
if (regex.exec(i) === null) {
continue;
}
results[i] = this.alts[i];
}
return results;
}
}, {
key: 'delete',
value: function _delete(altKey) {
if (!this.get(altKey)) {
return false;
}
delete this.alts[altKey];
return true;
}
}, {
key: 'getOrCreate',
value: function getOrCreate(altKey) {
var alt = this.get(altKey);
if (alt) {
return alt;
}
return this.create(altKey);
}
}]);
return AltManager;
})();
exports['default'] = AltManager;
module.exports = exports['default'];
/***/ },
/* 16 */
/***/ function(module, exports) {
/**
* DispatcherRecorder(alt: AltInstance): DispatcherInstance
*
* > Record and replay your actions at any point in time.
*
* This util allows you to record a set of dispatches which you can later
* replay at your convenience.
*
* Good for: Debugging, repeating, logging.
*
* Usage:
*
* ```js
* var recorder = new DispatcherRecorder(alt);
*
* // start recording
* recorder.record();
*
* // call a series of actions
*
* // stop recording
* recorder.stop();
*
* // replay the events that took place
* recorder.replay();
* ```
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function DispatcherRecorder(alt) {
var maxEvents = arguments.length <= 1 || arguments[1] === undefined ? Infinity : arguments[1];
this.alt = alt;
this.events = [];
this.dispatchToken = null;
this.maxEvents = maxEvents;
}
/**
* If recording started you get true, otherwise false since there's a recording
* in progress.
* record(): boolean
*/
DispatcherRecorder.prototype.record = function record() {
var _this = this;
if (this.dispatchToken) {
return false;
}
this.dispatchToken = this.alt.dispatcher.register(function (payload) {
if (_this.events.length < _this.maxEvents) {
_this.events.push(payload);
}
});
return true;
};
/**
* Stops the recording in progress.
* stop(): undefined
*/
DispatcherRecorder.prototype.stop = function stop() {
this.alt.dispatcher.unregister(this.dispatchToken);
this.dispatchToken = null;
};
/**
* Clear all events from memory.
* clear(): undefined
*/
DispatcherRecorder.prototype.clear = function clear() {
this.events = [];
};
/**
* (As|S)ynchronously replay all events that were recorded.
* replay(replayTime: ?number, done: ?function): undefined
*/
DispatcherRecorder.prototype.replay = function replay(replayTime, done) {
var alt = this.alt;
if (replayTime === void 0) {
this.events.forEach(function (payload) {
alt.dispatch(payload.action, payload.data);
});
}
var onNext = function onNext(payload, nextAction) {
return function () {
setTimeout(function () {
alt.dispatch(payload.action, payload.data);
nextAction();
}, replayTime);
};
};
var next = done || function () {};
var i = this.events.length - 1;
while (i >= 0) {
var _event = this.events[i];
next = onNext(_event, next);
i -= 1;
}
next();
};
/**
* Serialize all the events so you can pass them around or load them into
* a separate recorder.
* serializeEvents(): string
*/
DispatcherRecorder.prototype.serializeEvents = function serializeEvents() {
var events = this.events.map(function (event) {
return {
id: event.id,
action: event.action,
data: event.data || {}
};
});
return JSON.stringify(events);
};
/**
* Load serialized events into the recorder and overwrite the current events
* loadEvents(events: string): undefined
*/
DispatcherRecorder.prototype.loadEvents = function loadEvents(events) {
var parsedEvents = JSON.parse(events);
this.events = parsedEvents.map(function (event) {
return {
action: event.action,
data: event.data
};
});
return parsedEvents;
};
exports["default"] = DispatcherRecorder;
module.exports = exports["default"];
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
exports['default'] = atomic;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _makeFinalStore = __webpack_require__(18);
var _makeFinalStore2 = _interopRequireDefault(_makeFinalStore);
var _functions = __webpack_require__(6);
function makeAtomicClass(alt, StoreModel) {
var AtomicClass = (function (_StoreModel) {
_inherits(AtomicClass, _StoreModel);
function AtomicClass() {
_classCallCheck(this, AtomicClass);
_get(Object.getPrototypeOf(AtomicClass.prototype), 'constructor', this).call(this);
this.on('error', function () {
return alt.rollback();
});
}
return AtomicClass;
})(StoreModel);
AtomicClass.displayName = StoreModel.displayName || StoreModel.name;
return AtomicClass;
}
function makeAtomicObject(alt, StoreModel) {
StoreModel.lifecycle = StoreModel.lifecycle || {};
StoreModel.lifecycle.error = function () {
alt.rollback();
};
return StoreModel;
}
function atomic(alt) {
var finalStore = (0, _makeFinalStore2['default'])(alt);
finalStore.listen(function () {
return alt.takeSnapshot();
});
return function (StoreModel) {
return (0, _functions.isFunction)(StoreModel) ? makeAtomicClass(alt, StoreModel) : makeAtomicObject(alt, StoreModel);
};
}
module.exports = exports['default'];
/***/ },
/* 18 */
/***/ function(module, exports) {
/**
* makeFinalStore(alt: AltInstance): AltStore
*
* > Creates a `FinalStore` which is a store like any other except that it
* waits for all other stores in your alt instance to emit a change before it
* emits a change itself.
*
* Want to know when a particular dispatch has completed? This is the util
* you want.
*
* Good for: taking a snapshot and persisting it somewhere, saving data from
* a set of stores, syncing data, etc.
*
* Usage:
*
* ```js
* var FinalStore = makeFinalStore(alt);
*
* FinalStore.listen(function () {
* // all stores have now changed
* });
* ```
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = makeFinalStore;
function FinalStore() {
var _this = this;
this.dispatcher.register(function (payload) {
var stores = Object.keys(_this.alt.stores).reduce(function (arr, store) {
arr.push(_this.alt.stores[store].dispatchToken);
return arr;
}, []);
_this.waitFor(stores);
_this.setState({ payload: payload });
_this.emitChange();
});
}
function makeFinalStore(alt) {
return alt.FinalStore ? alt.FinalStore : alt.FinalStore = alt.createUnsavedStore(FinalStore);
}
module.exports = exports["default"];
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/**
* 'Higher Order Component' that controls the props of a wrapped
* component via stores.
*
* Expects the Component to have two static methods:
* - getStores(): Should return an array of stores.
* - getPropsFromStores(props): Should return the props from the stores.
*
* Example using old React.createClass() style:
*
* const MyComponent = React.createClass({
* statics: {
* getStores(props) {
* return [myStore]
* },
* getPropsFromStores(props) {
* return myStore.getState()
* }
* },
* render() {
* // Use this.props like normal ...
* }
* })
* MyComponent = connectToStores(MyComponent)
*
*
* Example using ES6 Class:
*
* class MyComponent extends React.Component {
* static getStores(props) {
* return [myStore]
* }
* static getPropsFromStores(props) {
* return myStore.getState()
* }
* render() {
* // Use this.props like normal ...
* }
* }
* MyComponent = connectToStores(MyComponent)
*
* A great explanation of the merits of higher order components can be found at
* http://bit.ly/1abPkrP
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(20);
var _react2 = _interopRequireDefault(_react);
var _functions = __webpack_require__(6);
function connectToStores(Spec) {
var Component = arguments.length <= 1 || arguments[1] === undefined ? Spec : arguments[1];
return (function () {
// Check for required static methods.
if (!(0, _functions.isFunction)(Spec.getStores)) {
throw new Error('connectToStores() expects the wrapped component to have a static getStores() method');
}
if (!(0, _functions.isFunction)(Spec.getPropsFromStores)) {
throw new Error('connectToStores() expects the wrapped component to have a static getPropsFromStores() method');
}
var StoreConnection = _react2['default'].createClass({
displayName: 'Stateful' + (Component.displayName || Component.name || 'Container'),
getInitialState: function getInitialState() {
return Spec.getPropsFromStores(this.props, this.context);
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.setState(Spec.getPropsFromStores(nextProps, this.context));
},
componentDidMount: function componentDidMount() {
var _this = this;
var stores = Spec.getStores(this.props, this.context);
this.storeListeners = stores.map(function (store) {
return store.listen(_this.onChange);
});
if (Spec.componentDidConnect) {
Spec.componentDidConnect(this.props, this.context);
}
},
componentWillUnmount: function componentWillUnmount() {
this.storeListeners.forEach(function (unlisten) {
return unlisten();
});
},
onChange: function onChange() {
this.setState(Spec.getPropsFromStores(this.props, this.context));
},
render: function render() {
return _react2['default'].createElement(Component, (0, _functions.assign)({}, this.props, this.state));
}
});
if (Component.contextTypes) {
StoreConnection.contextTypes = Component.contextTypes;
}
return StoreConnection;
})();
}
exports['default'] = connectToStores;
module.exports = exports['default'];
/***/ },
/* 20 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_20__;
/***/ },
/* 21 */
/***/ function(module, exports) {
/* global window */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = chromeDebug;
function chromeDebug(alt) {
if (typeof window !== 'undefined') window['alt.js.org'] = alt;
return alt;
}
module.exports = exports['default'];
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = withAltContext;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(20);
var _react2 = _interopRequireDefault(_react);
function withAltContext(flux) {
return function (Component) {
return _react2['default'].createClass({
childContextTypes: {
flux: _react2['default'].PropTypes.object
},
getChildContext: function getChildContext() {
return { flux: flux };
},
render: function render() {
return _react2['default'].createElement(Component, this.props);
}
});
};
}
module.exports = exports['default'];
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(24);
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
/*eslint-disable*/
/**
* AltContainer.
*
* There are many ways to use AltContainer.
*
* Using the `stores` prop.
*
* <AltContainer stores={{ FooStore: FooStore }}>
* children get this.props.FooStore.storeData
* </AltContainer>
*
* You can also pass in functions.
*
* <AltContainer stores={{ FooStore: function () { return { storeData: true } } }}>
* children get this.props.FooStore.storeData
* </AltContainer>
*
* Using the `store` prop.
*
* <AltContainer store={FooStore}>
* children get this.props.storeData
* </AltContainer>
*
* Passing in `flux` because you're using alt instances
*
* <AltContainer flux={flux}>
* children get this.props.flux
* </AltContainer>
*
* Using a custom render function.
*
* <AltContainer
* render={function (props) {
* return <div />;
* }}
* />
*
* Using the `transform` prop.
*
* <AltContainer
* stores={{ FooStore: FooStore, BarStore: BarStore }}
* transform={function(stores) {
* var FooStore = stores.FooStore;
* var BarStore = stores.BarStore;
* var products =
* FooStore.products
* .slice(0, 10)
* .concat(BarStore.products);
* return { products: products };
* }}
* >
* children get this.props.products
* </AltContainer>
*
* Full docs available at http://goatslacker.github.io/alt/
*/
'use strict';
var React = __webpack_require__(25);
var mixinContainer = __webpack_require__(26);
var assign = __webpack_require__(28).assign;
var AltContainer = React.createClass(assign({
displayName: 'AltContainer',
render: function render() {
return this.altRender('div');
}
}, mixinContainer(React)));
module.exports = AltContainer;
/***/ },
/* 25 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_25__;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
/*eslint-disable*/
'use strict';
var Subscribe = __webpack_require__(27);
var assign = __webpack_require__(28).assign;
function id(it) {
return it;
}
function getStateFromStore(store, props) {
return typeof store === 'function' ? store(props).value : store.getState();
}
function getStateFromKey(actions, props) {
return typeof actions === 'function' ? actions(props) : actions;
}
function mixinContainer(React) {
var cloneWithProps = React.addons.cloneWithProps;
return {
contextTypes: {
flux: React.PropTypes.object
},
childContextTypes: {
flux: React.PropTypes.object
},
getChildContext: function getChildContext() {
var flux = this.props.flux || this.context.flux;
return flux ? { flux: flux } : {};
},
getInitialState: function getInitialState() {
if (this.props.stores && this.props.store) {
throw new ReferenceError('Cannot define both store and stores');
}
return this.reduceState(this.props);
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.destroySubscriptions();
this.setState(this.reduceState(nextProps));
this.registerStores(nextProps);
},
componentDidMount: function componentDidMount() {
this.registerStores(this.props);
if (this.props.onMount) this.props.onMount(this.props, this.context);
},
componentWillUnmount: function componentWillUnmount() {
this.destroySubscriptions();
},
registerStores: function registerStores(props) {
var stores = props.stores;
Subscribe.create(this);
if (props.store) {
this.addSubscription(props.store);
} else if (props.stores) {
if (Array.isArray(stores)) {
stores.forEach(function (store) {
this.addSubscription(store);
}, this);
} else {
Object.keys(stores).forEach(function (formatter) {
this.addSubscription(stores[formatter]);
}, this);
}
}
},
destroySubscriptions: function destroySubscriptions() {
Subscribe.destroy(this);
},
getStateFromStores: function getStateFromStores(props) {
var stores = props.stores;
if (props.store) {
return getStateFromStore(props.store, props);
} else if (props.stores) {
// If you pass in an array of stores then we are just listening to them
// it should be an object then the state is added to the key specified
if (!Array.isArray(stores)) {
return Object.keys(stores).reduce(function (obj, key) {
obj[key] = getStateFromStore(stores[key], props);
return obj;
}, {});
}
} else {
return {};
}
},
getStateFromActions: function getStateFromActions(props) {
if (props.actions) {
return getStateFromKey(props.actions, props);
} else {
return {};
}
},
getInjected: function getInjected(props) {
if (props.inject) {
return Object.keys(props.inject).reduce(function (obj, key) {
obj[key] = getStateFromKey(props.inject[key], props);
return obj;
}, {});
} else {
return {};
}
},
reduceState: function reduceState(props) {
return assign({}, this.getStateFromStores(props), this.getStateFromActions(props), this.getInjected(props));
},
addSubscription: function addSubscription(store) {
if (typeof store === 'function') {
Subscribe.add(this, store(this.props).store, this.altSetState);
} else {
Subscribe.add(this, store, this.altSetState);
}
},
altSetState: function altSetState() {
this.setState(this.reduceState(this.props));
},
getProps: function getProps() {
var flux = this.props.flux || this.context.flux;
var transform = typeof this.props.transform === 'function' ? this.props.transform : id;
return transform(assign(flux ? { flux: flux } : {}, this.state));
},
shouldComponentUpdate: function shouldComponentUpdate() {
return this.props.shouldComponentUpdate ? this.props.shouldComponentUpdate(this.getProps()) : true;
},
altRender: function altRender(Node) {
var children = this.props.children;
// Custom rendering function
if (typeof this.props.render === 'function') {
return this.props.render(this.getProps());
} else if (this.props.component) {
return React.createElement(this.props.component, this.getProps());
}
// Does not wrap child in a div if we don't have to.
if (Array.isArray(children)) {
return React.createElement(Node, null, children.map(function (child, i) {
return cloneWithProps(child, assign({ key: i }, this.getProps()));
}, this));
} else if (children) {
return cloneWithProps(children, this.getProps());
} else {
return React.createElement(Node, this.getProps());
}
}
};
}
module.exports = mixinContainer;
/***/ },
/* 27 */
/***/ function(module, exports) {
'use strict';
var Subscribe = {
create: function create(context) {
context._AltMixinRegistry = context._AltMixinRegistry || [];
},
add: function add(context, store, handler) {
context._AltMixinRegistry.push(store.listen(handler));
},
destroy: function destroy(context) {
context._AltMixinRegistry.forEach(function (f) {
f();
});
context._AltMixinRegistry = [];
},
listeners: function listeners(context) {
return context._AltMixinRegistry;
}
};
module.exports = Subscribe;
/***/ },
/* 28 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.isPojo = isPojo;
exports.isPromise = isPromise;
exports.eachObject = eachObject;
exports.assign = assign;
var isFunction = function isFunction(x) {
return typeof x === 'function';
};
exports.isFunction = isFunction;
function isPojo(target) {
var Ctor = target.constructor;
return !!target && typeof target === 'object' && Object.prototype.toString.call(target) === '[object Object]' && isFunction(Ctor) && (Ctor instanceof Ctor || target.type === 'AltStore');
}
function isPromise(obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
function eachObject(f, o) {
o.forEach(function (from) {
Object.keys(Object(from)).forEach(function (key) {
f(key, from[key]);
});
});
}
function assign(target) {
for (var _len = arguments.length, source = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
source[_key - 1] = arguments[_key];
}
eachObject(function (key, value) {
return target[key] = value;
}, source);
return target;
}
/***/ }
/******/ ])
});
;
|
sreym/cdnjs
|
ajax/libs/alt/0.17.7/alt-with-addons.js
|
JavaScript
|
mit
| 83,357
|
"use strict";
exports.__esModule = true;
exports.default = function (context) {
var plugin = {
visitor: require("./visit").visitor
};
// Some presets manually call child presets, but fail to pass along the
// context object. Out of an abundance of caution, we verify that it
// exists first to avoid causing unnecessary breaking changes.
var version = context && context.version;
// The "name" property is not allowed in older versions of Babel (6.x)
// and will cause the plugin validator to throw an exception.
if (version && parseInt(version, 10) >= 7) {
plugin.name = "regenerator-transform";
}
return plugin;
};
|
hellokidder/js-studying
|
微信小程序/wxtest/node_modules/regenerator-transform/lib/index.js
|
JavaScript
|
mit
| 651
|
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPutListenerQueue
*/
'use strict';
var PooledClass = require("./PooledClass");
var ReactBrowserEventEmitter = require("./ReactBrowserEventEmitter");
var assign = require("./Object.assign");
function ReactPutListenerQueue() {
this.listenersToPut = [];
}
assign(ReactPutListenerQueue.prototype, {
enqueuePutListener: function(rootNodeID, propKey, propValue) {
this.listenersToPut.push({
rootNodeID: rootNodeID,
propKey: propKey,
propValue: propValue
});
},
putListeners: function() {
for (var i = 0; i < this.listenersToPut.length; i++) {
var listenerToPut = this.listenersToPut[i];
ReactBrowserEventEmitter.putListener(
listenerToPut.rootNodeID,
listenerToPut.propKey,
listenerToPut.propValue
);
}
},
reset: function() {
this.listenersToPut.length = 0;
},
destructor: function() {
this.reset();
}
});
PooledClass.addPoolingTo(ReactPutListenerQueue);
module.exports = ReactPutListenerQueue;
|
jeffro-/jeffro-.github.io
|
youreeverything/node_modules/react/lib/ReactPutListenerQueue.js
|
JavaScript
|
apache-2.0
| 1,326
|
define(function(){return{COLLAPSE_REVIEW_PANEL:"grading:collapse-review-panel",EXPAND_REVIEW_PANEL:"grading:expand-review-panel",COLLAPSE_GRADE_PANEL:"grading:collapse-grade-panel",EXPAND_GRADE_PANEL:"grading:expand-grade-panel"}});
|
parksandwildlife/learning
|
moodle/mod/assign/amd/build/grading_events.min.js
|
JavaScript
|
gpl-3.0
| 232
|
jQuery.keyboard.language.ru={language:"Русский",display:{a:"✔:Сохранить (Shift+Enter)",accept:"Сохранить:Сохранить (Shift+Enter)",alt:"РУС:Русская клавиатура",b:"←:Удалить символ слева",bksp:"⇦:Удалить символ слева",c:"✖:Отменить (Esc)",cancel:"Отменить:Отменить (Esc)",clear:"C:Очистить",combo:"ö:Toggle Combo Keys",dec:",:Decimal",e:"↵:Ввод",enter:"Ввод:Перевод строки",lock:"⇪ Lock:Caps Lock",s:"⇧:Верхний регистр",shift:"⇧:Верхний регистр",sign:"±:Сменить знак",space:"Пробел:",t:"⇥:Tab",tab:"⇥ Tab:Tab"},wheelMessage:"Use mousewheel to see other keys"};
|
wout/cdnjs
|
ajax/libs/virtual-keyboard/1.23.5/languages/ru.min.js
|
JavaScript
|
mit
| 768
|
/**
* Ajax Autocomplete for jQuery, version 1.2.2
* (c) 2013 Tomas Kirda
*
* Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
* For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/
*
*/
(function(d){"function"===typeof define&&define.amd?define(["jquery"],d):d(jQuery)})(function(d){function f(a,b){var c=function(){},c={autoSelectFirst:!1,appendTo:"body",serviceUrl:null,lookup:null,onSelect:null,width:"auto",minChars:1,maxHeight:300,deferRequestBy:0,params:{},formatResult:f.formatResult,delimiter:null,zIndex:9999,type:"GET",noCache:!1,onSearchStart:c,onSearchComplete:c,containerClass:"autocomplete-suggestions",tabDisabled:!1,lookupFilter:function(a,b,c){return-1!==a.value.toLowerCase().indexOf(c)},
paramName:"query",transformResult:function(a){return a.suggestions}};this.element=a;this.el=d(a);this.suggestions=[];this.badQueries=[];this.selectedIndex=-1;this.currentValue=this.element.value;this.intervalId=0;this.cachedResponse=[];this.onChange=this.onChangeInterval=null;this.isLocal=this.ignoreValueChange=!1;this.suggestionsContainer=null;this.options=d.extend({},c,b);this.classes={selected:"autocomplete-selected",suggestion:"autocomplete-suggestion"};this.initialize();this.setOptions(b)}var h=
{extend:function(a,b){return d.extend(a,b)},addEvent:function(a,b,c){if(a.addEventListener)a.addEventListener(b,c,!1);else if(a.attachEvent)a.attachEvent("on"+b,c);else throw Error("Browser doesn't support addEventListener or attachEvent");},removeEvent:function(a,b,c){a.removeEventListener?a.removeEventListener(b,c,!1):a.detachEvent&&a.detachEvent("on"+b,c)},createNode:function(a){var b=document.createElement("div");b.innerHTML=a;return b.firstChild}};f.utils=h;d.Autocomplete=f;f.formatResult=function(a,
b){var c="("+b.replace(RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\)","g"),"\\$1")+")";return a.value.replace(RegExp(c,"gi"),"<strong>$1</strong>")};f.prototype={killerFn:null,initialize:function(){var a=this,b="."+a.classes.suggestion,c=a.classes.selected,e=a.options,g;a.element.setAttribute("autocomplete","off");a.killerFn=function(b){0===d(b.target).closest("."+a.options.containerClass).length&&(a.killSuggestions(),a.disableKillerFn())};if(!e.width||"auto"===e.width)e.width=a.el.outerWidth();
a.suggestionsContainer=f.utils.createNode('<div class="'+e.containerClass+'" style="position: absolute; display: none;"></div>');g=d(a.suggestionsContainer);g.appendTo(e.appendTo).width(e.width);g.on("mouseover",b,function(){a.activate(d(this).data("index"))});g.on("mouseout",function(){a.selectedIndex=-1;g.children("."+c).removeClass(c)});g.on("click",b,function(){a.select(d(this).data("index"))});a.fixPosition();if(window.opera)a.el.on("keypress",function(b){a.onKeyPress(b)});else a.el.on("keydown",
function(b){a.onKeyPress(b)});a.el.on("keyup",function(b){a.onKeyUp(b)});a.el.on("blur",function(){a.onBlur()});a.el.on("focus",function(){a.fixPosition()})},onBlur:function(){this.enableKillerFn()},setOptions:function(a){var b=this.options;h.extend(b,a);if(this.isLocal=d.isArray(b.lookup))b.lookup=this.verifySuggestionsFormat(b.lookup);d(this.suggestionsContainer).css({"max-height":b.maxHeight+"px",width:b.width+"px","z-index":b.zIndex})},clearCache:function(){this.cachedResponse=[];this.badQueries=
[]},disable:function(){this.disabled=!0},enable:function(){this.disabled=!1},fixPosition:function(){var a;"body"===this.options.appendTo&&(a=this.el.offset(),d(this.suggestionsContainer).css({top:a.top+this.el.outerHeight()+"px",left:a.left+"px"}))},enableKillerFn:function(){d(document).on("click",this.killerFn)},disableKillerFn:function(){d(document).off("click",this.killerFn)},killSuggestions:function(){var a=this;a.stopKillSuggestions();a.intervalId=window.setInterval(function(){a.hide();a.stopKillSuggestions()},
300)},stopKillSuggestions:function(){window.clearInterval(this.intervalId)},onKeyPress:function(a){if(!this.disabled&&!this.visible&&40===a.keyCode&&this.currentValue)this.suggest();else if(!this.disabled&&this.visible){switch(a.keyCode){case 27:this.el.val(this.currentValue);this.hide();break;case 9:case 13:if(-1===this.selectedIndex){this.hide();return}this.select(this.selectedIndex);if(9===a.keyCode&&!1===this.options.tabDisabled)return;break;case 38:this.moveUp();break;case 40:this.moveDown();
break;default:return}a.stopImmediatePropagation();a.preventDefault()}},onKeyUp:function(a){var b=this;if(!b.disabled){switch(a.keyCode){case 38:case 40:return}clearInterval(b.onChangeInterval);if(b.currentValue!==b.el.val())if(0<b.options.deferRequestBy)b.onChangeInterval=setInterval(function(){b.onValueChange()},b.options.deferRequestBy);else b.onValueChange()}},onValueChange:function(){var a;clearInterval(this.onChangeInterval);this.currentValue=this.element.value;a=this.getQuery(this.currentValue);
this.selectedIndex=-1;this.ignoreValueChange?this.ignoreValueChange=!1:""===a||a.length<this.options.minChars?this.hide():this.getSuggestions(a)},getQuery:function(a){var b=this.options.delimiter;if(!b)return d.trim(a);a=a.split(b);return d.trim(a[a.length-1])},getSuggestionsLocal:function(a){var b=a.toLowerCase(),c=this.options.lookupFilter;return{suggestions:d.grep(this.options.lookup,function(d){return c(d,a,b)})}},getSuggestions:function(a){var b,c=this,e=c.options;(b=c.isLocal?c.getSuggestionsLocal(a):
c.cachedResponse[a])&&d.isArray(b.suggestions)?(c.suggestions=b.suggestions,c.suggest()):c.isBadQuery(a)||(e.onSearchStart.call(c.element,a),e.params[e.paramName]=a,d.ajax({url:e.serviceUrl,data:e.params,type:e.type,dataType:"text"}).done(function(b){c.processResponse(b);e.onSearchComplete.call(c.element,a)}))},isBadQuery:function(a){for(var b=this.badQueries,c=b.length;c--;)if(0===a.indexOf(b[c]))return!0;return!1},hide:function(){this.visible=!1;this.selectedIndex=-1;d(this.suggestionsContainer).hide()},
suggest:function(){if(0===this.suggestions.length)this.hide();else{var a=this.options.formatResult,b=this.getQuery(this.currentValue),c=this.classes.suggestion,e=this.classes.selected,g=d(this.suggestionsContainer),f="";d.each(this.suggestions,function(d,e){f+='<div class="'+c+'" data-index="'+d+'">'+a(e,b)+"</div>"});g.html(f).show();this.visible=!0;this.options.autoSelectFirst&&(this.selectedIndex=0,g.children().first().addClass(e))}},verifySuggestionsFormat:function(a){return a.length&&"string"===
typeof a[0]?d.map(a,function(a){return{value:a,data:null}}):a},processResponse:function(a){a=d.parseJSON(a);a.suggestions=this.verifySuggestionsFormat(this.options.transformResult(a));this.options.noCache||(this.cachedResponse[a[this.options.paramName]]=a,0===a.suggestions.length&&this.badQueries.push(a[this.options.paramName]));a[this.options.paramName]===this.getQuery(this.currentValue)&&(this.suggestions=a.suggestions,this.suggest())},activate:function(a){var b=this.classes.selected,c=d(this.suggestionsContainer),
e=c.children();c.children("."+b).removeClass(b);this.selectedIndex=a;return-1!==this.selectedIndex&&e.length>this.selectedIndex?(a=e.get(this.selectedIndex),d(a).addClass(b),a):null},select:function(a){var b=this.suggestions[a];b&&(this.el.val(b),this.ignoreValueChange=!0,this.hide(),this.onSelect(a))},moveUp:function(){-1!==this.selectedIndex&&(0===this.selectedIndex?(d(this.suggestionsContainer).children().first().removeClass(this.classes.selected),this.selectedIndex=-1,this.el.val(this.currentValue)):
this.adjustScroll(this.selectedIndex-1))},moveDown:function(){this.selectedIndex!==this.suggestions.length-1&&this.adjustScroll(this.selectedIndex+1)},adjustScroll:function(a){var b=this.activate(a),c,e;b&&(b=b.offsetTop,c=d(this.suggestionsContainer).scrollTop(),e=c+this.options.maxHeight-25,b<c?d(this.suggestionsContainer).scrollTop(b):b>e&&d(this.suggestionsContainer).scrollTop(b-this.options.maxHeight+25),this.el.val(this.getValue(this.suggestions[a].value)))},onSelect:function(a){var b=this.options.onSelect;
a=this.suggestions[a];this.el.val(this.getValue(a.value));d.isFunction(b)&&b.call(this.element,a)},getValue:function(a){var b=this.options.delimiter,c;if(!b)return a;c=this.currentValue;b=c.split(b);return 1===b.length?a:c.substr(0,c.length-b[b.length-1].length)+a}};d.fn.autocomplete=function(a,b){return this.each(function(){var c=d(this),e;if("string"===typeof a){if(e=c.data("autocomplete"),"function"===typeof e[a])e[a](b)}else e=new f(this,a),c.data("autocomplete",e)})}});
|
taydakov/cdnjs
|
ajax/libs/jquery.devbridge-autocomplete/1.2.2/jquery.autocomplete.min.js
|
JavaScript
|
mit
| 8,434
|
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $ */
define(["credits", "products"], function (credits, products) {
'use strict';
return {
purchaseProduct: function () {
var credit = credits.getCredits();
if (credit > 0) {
products.reserveProduct();
return true;
}
return false;
}
};
});
|
MatiasNAmendola/gnome-web
|
usr/lib/brackets/src/extensions/default/JavaScriptCodeHints/unittest-files/module-test-files/purchase.js
|
JavaScript
|
gpl-3.0
| 468
|
/**
* af.8tiles - Provides a WP8 theme and handles showing the menu
* Copyright 2012 - Intel
* This plugin is meant to be used inside App Framework UI
*/
/* global af*/
(function($) {
"use strict";
if (!$) {
throw "This plugin requires AFUi";
}
function wire8Tiles() {
$.ui.isWin8 = true;
if (!$.os.ie) return;
if (!$.ui.isSideMenuEnabled()) return;
$.ui.ready(function() {
if($.ui.tilesLoaded) return;
$.ui.tilesLoaded=true;
if(window.innerWidth>$.ui.handheldMinWidth) return true;
if ($.ui.slideSideMenu) $.ui.slideSideMenu = false;
//we need to make sure the menu button shows up in the bottom navbar
$.query("#afui #navbar footer").append("<a id='metroMenu' onclick='$.ui.toggleSideMenu()'>•••</a>");
var tmpAnchors = $.query("#afui #navbar").find("a").not(".button");
if (tmpAnchors.length > 0) {
tmpAnchors.data("ignore-pressed", "true").data("resetHistory", "true");
var width = parseFloat(100 / tmpAnchors.length);
tmpAnchors.css("width", width + "%");
}
var oldUpdate = $.ui.updateNavbarElements;
$.ui.updateNavbarElements = function() {
oldUpdate.apply($.ui, arguments);
if ($.query("#afui #navbar #metroMenu").length === 1) return;
$.query("#afui #navbar footer").append("<a id='metroMenu' onclick='$.ui.toggleSideMenu()'>•••</a>");
};
$.ui.isSideMenuOn = function() {
var menu = parseInt($.getCssMatrix($("#navbar")).f,10) < 0 ? true : false;
return this.isSideMenuEnabled() && menu;
};
$.ui.toggleRightSideMenu=function(force,callback,time) {
if ((!this.isAsideMenuEnabled()) || this.togglingAsideMenu) return;
var aside=true;
if(!aside&&!this.isSideMenuEnabled()) return;
if(!aside&&$.ui.splitview) return;
var that = this;
var menu=$("#menu");
var asideMenu= $.query("#aside_menu");
var els = $.query("#content, #header, #navbar");
var panelMask = $.query(".afui_panel_mask");
time = time || this.transitionTime;
var open = $("#aside_menu").css("display")==="block";
var toX=aside?"-"+that.sideMenuWidth:that.sideMenuWidth;
// add panel mask to block when side menu is open for phone devices
if(panelMask.length === 0 && window.innerWidth < $.ui.handheldMinWidth){
els.append("<div class='afui_panel_mask'></div>");
panelMask = $.query(".afui_panel_mask");
$(".afui_panel_mask").bind("click", function(){
$.ui.toggleSideMenu(false, null, null, aside);
});
}
//Here we need to check if we are toggling the left to right, or right to left
var menuPos=this.getSideMenuPosition();
if(open&&!aside&&menuPos<0)
open=false;
else if(open&&aside&&menuPos>0)
open=false;
if (force === 2 || (!open && ((force !== undefined && force !== false) || force === undefined))) {
this.togglingSideMenu = true;
if(!aside)
menu.show();
else
asideMenu.show();
that.css3animate(els, {
x: toX,
time: time,
complete: function(canceled) {
that.togglingSideMenu = false;
els.vendorCss("Transition", "");
if (callback) callback(canceled);
if(panelMask.length !== 0 && window.innerWidth < $.ui.handheldMinWidth){
panelMask.show();
}
}
});
} else if (force === undefined || (force !== undefined && force === false)) {
this.togglingSideMenu = true;
that.css3animate(els, {
x: "0px",
time: time,
complete: function(canceled) {
// els.removeClass("on");
els.vendorCss("Transition", "");
els.vendorCss("Transform", "");
that.togglingSideMenu = false;
if (callback) callback(canceled);
if(!$.ui.splitview)
menu.hide();
asideMenu.hide();
if(panelMask.length !== 0 && window.innerWidth < $.ui.handheldMinWidth){
panelMask.hide();
}
}
});
}
};
$.ui.toggleLeftSideMenu = function(force, callback) {
if (!this.isSideMenuEnabled() || this.togglingSideMenu) return;
this.togglingSideMenu = true;
var that = this;
var menu = $.query("#menu");
var els = $.query("#navbar");
var open = this.isSideMenuOn();
if (force === 2 || (!open && ((force !== undefined && force !== false) || force === undefined))) {
menu.show();
that.css3animate(els, {
y: "-150px",
time: $.ui.transitionTime,
complete: function() {
that.togglingSideMenu = false;
if (callback) callback(true);
}
});
that.css3animate(menu, {
y: "0px",
time: $.ui.transitionTime
});
} else if (force === undefined || (force !== undefined && force === false)) {
that.css3animate(els, {
y: "0",
time: $.ui.transitionTime,
complete: function() {
that.togglingSideMenu = false;
if (callback) callback(true);
menu.hide();
}
});
that.css3animate(menu, {
y: "150px",
time: $.ui.transitionTime
});
}
};
});
}
if (!$.ui) {
$(document).ready(function() {
wire8Tiles();
});
} else {
$.ui.ready(function(){
wire8Tiles();
});
}
})(af);
|
horacework/nutrDietWebApp
|
www/plugins/af.8tiles.js
|
JavaScript
|
mit
| 7,096
|
/*
Highmaps JS v1.0.1 (2014-06-12)
(c) 2011-2014 Torstein Honsi
License: www.highcharts.com/license
*/
(function(h){var j=h.Axis,y=h.Chart,p=h.Color,z=h.Legend,t=h.LegendSymbolMixin,u=h.Series,v=h.SVGRenderer,w=h.getOptions(),k=h.each,q=h.extend,A=h.extendClass,l=h.merge,m=h.pick,x=h.numberFormat,o=h.seriesTypes,r=h.wrap,n=function(){},s=h.ColorAxis=function(){this.isColorAxis=!0;this.init.apply(this,arguments)};q(s.prototype,j.prototype);q(s.prototype,{defaultColorAxisOptions:{lineWidth:0,gridLineWidth:1,tickPixelInterval:72,startOnTick:!0,endOnTick:!0,offset:0,marker:{animation:{duration:50},color:"gray",
width:0.01},labels:{overflow:"justify"},minColor:"#EFEFFF",maxColor:"#003875",tickLength:5},init:function(b,a){var d=b.options.legend.layout!=="vertical",c;c=l(this.defaultColorAxisOptions,{side:d?2:1,reversed:!d},a,{isX:d,opposite:!d,showEmpty:!1,title:null,isColor:!0});j.prototype.init.call(this,b,c);a.dataClasses&&this.initDataClasses(a);this.initStops(a);this.isXAxis=!0;this.horiz=d;this.zoomEnabled=!1},tweenColors:function(b,a,d){var c=a.rgba[3]!==1||b.rgba[3]!==1;return(c?"rgba(":"rgb(")+Math.round(a.rgba[0]+
(b.rgba[0]-a.rgba[0])*(1-d))+","+Math.round(a.rgba[1]+(b.rgba[1]-a.rgba[1])*(1-d))+","+Math.round(a.rgba[2]+(b.rgba[2]-a.rgba[2])*(1-d))+(c?","+(a.rgba[3]+(b.rgba[3]-a.rgba[3])*(1-d)):"")+")"},initDataClasses:function(b){var a=this,d=this.chart,c,e=0,g=this.options;this.dataClasses=c=[];this.legendItems=[];k(b.dataClasses,function(f,i){var h,f=l(f);c.push(f);if(!f.color)g.dataClassColor==="category"?(h=d.options.colors,f.color=h[e++],e===h.length&&(e=0)):f.color=a.tweenColors(p(g.minColor),p(g.maxColor),
i/(b.dataClasses.length-1))})},initStops:function(b){this.stops=b.stops||[[0,this.options.minColor],[1,this.options.maxColor]];k(this.stops,function(a){a.color=p(a[1])})},setOptions:function(b){j.prototype.setOptions.call(this,b);this.options.crosshair=this.options.marker;this.coll="colorAxis"},setAxisSize:function(){var b=this.legendSymbol,a=this.chart,d,c,e;if(b)this.left=d=b.attr("x"),this.top=c=b.attr("y"),this.width=e=b.attr("width"),this.height=b=b.attr("height"),this.right=a.chartWidth-d-e,
this.bottom=a.chartHeight-c-b,this.len=this.horiz?e:b,this.pos=this.horiz?d:c},toColor:function(b,a){var d,c=this.stops,e,g=this.dataClasses,f,i;if(g)for(i=g.length;i--;){if(f=g[i],e=f.from,c=f.to,(e===void 0||b>=e)&&(c===void 0||b<=c)){d=f.color;if(a)a.dataClass=i;break}}else{this.isLog&&(b=this.val2lin(b));d=1-(this.max-b)/(this.max-this.min||1);for(i=c.length;i--;)if(d>c[i][0])break;e=c[i]||c[i+1];c=c[i+1]||e;d=1-(c[0]-d)/(c[0]-e[0]||1);d=this.tweenColors(e.color,c.color,d)}return d},getOffset:function(){var b=
this.legendGroup,a=this.chart.axisOffset[this.side];if(b){j.prototype.getOffset.call(this);if(!this.axisGroup.parentGroup)this.axisGroup.add(b),this.gridGroup.add(b),this.labelGroup.add(b),this.added=!0;this.chart.axisOffset[this.side]=a}},setLegendColor:function(){var b,a=this.options;b=this.horiz?[0,0,1,0]:[0,0,0,1];this.legendColor={linearGradient:{x1:b[0],y1:b[1],x2:b[2],y2:b[3]},stops:a.stops||[[0,a.minColor],[1,a.maxColor]]}},drawLegendSymbol:function(b,a){var d=b.padding,c=b.options,e=this.horiz,
g=m(c.symbolWidth,e?200:12),f=m(c.symbolHeight,e?12:200),i=m(c.labelPadding,e?16:30),c=m(c.itemDistance,10);this.setLegendColor();a.legendSymbol=this.chart.renderer.rect(0,b.baseline-11,g,f).attr({zIndex:1}).add(a.legendGroup);a.legendSymbol.getBBox();this.legendItemWidth=g+d+(e?c:i);this.legendItemHeight=f+d+(e?i:0)},setState:n,visible:!0,setVisible:n,getSeriesExtremes:function(){var b;if(this.series.length)b=this.series[0],this.dataMin=b.valueMin,this.dataMax=b.valueMax},drawCrosshair:function(b,
a){var d=!this.cross,c=a&&a.plotX,e=a&&a.plotY,g,f=this.pos,i=this.len;if(a)g=this.toPixels(a.value),g<f?g=f-2:g>f+i&&(g=f+i+2),a.plotX=g,a.plotY=this.len-g,j.prototype.drawCrosshair.call(this,b,a),a.plotX=c,a.plotY=e,!d&&this.cross&&this.cross.attr({fill:this.crosshair.color}).add(this.labelGroup)},getPlotLinePath:function(b,a,d,c,e){return e?this.horiz?["M",e-4,this.top-6,"L",e+4,this.top-6,e,this.top,"Z"]:["M",this.left,e,"L",this.left-6,e+6,this.left-6,e-6,"Z"]:j.prototype.getPlotLinePath.call(this,
b,a,d,c)},update:function(b,a){k(this.series,function(a){a.isDirtyData=!0});j.prototype.update.call(this,b,a);this.legendItem&&(this.setLegendColor(),this.chart.legend.colorizeItem(this,!0))},getDataClassLegendSymbols:function(){var b=this,a=this.chart,d=this.legendItems,c=a.options.legend,e=c.valueDecimals,g=c.valueSuffix||"",f;d.length||k(this.dataClasses,function(c,h){var j=!0,l=c.from,m=c.to;f="";l===void 0?f="< ":m===void 0&&(f="> ");l!==void 0&&(f+=x(l,e)+g);l!==void 0&&m!==void 0&&(f+=" - ");
m!==void 0&&(f+=x(m,e)+g);d.push(q({chart:a,name:f,options:{},drawLegendSymbol:t.drawRectangle,visible:!0,setState:n,setVisible:function(){j=this.visible=!j;k(b.series,function(a){k(a.points,function(a){a.dataClass===h&&a.setVisible(j)})});a.legend.colorizeItem(this,j)}},c))});return d},name:""});r(y.prototype,"getAxes",function(b){var a=this.options.colorAxis;b.call(this);this.colorAxis=[];a&&new s(this,a)});r(z.prototype,"getAllItems",function(b){var a=[],d=this.chart.colorAxis[0];d&&(d.options.dataClasses?
a=a.concat(d.getDataClassLegendSymbols()):a.push(d),k(d.series,function(a){a.options.showInLegend=!1}));return a.concat(b.call(this))});h={pointAttrToOptions:{stroke:"borderColor","stroke-width":"borderWidth",fill:"color",dashstyle:"dashStyle"},pointArrayMap:["value"],axisTypes:["xAxis","yAxis","colorAxis"],optionalAxis:"colorAxis",trackerGroups:["group","markerGroup","dataLabelsGroup"],getSymbol:n,parallelArrays:["x","y","value"],translateColors:function(){var b=this,a=this.options.nullColor,d=this.colorAxis;
k(this.data,function(c){var e=c.value;if(e=e===null?a:d&&e!==void 0?d.toColor(e,c):c.color||b.color)c.color=e})}};r(v.prototype,"buildText",function(b,a){var d=a.styles&&a.styles.HcTextStroke;b.call(this,a);d&&a.applyTextStroke&&a.applyTextStroke(d)});v.prototype.Element.prototype.applyTextStroke=function(b){var a=this.element,d,c,b=b.split(" ");d=a.getElementsByTagName("tspan");c=a.firstChild;this.ySetter=this.xSetter;k([].slice.call(d),function(d,g){var f;g===0&&(d.setAttribute("x",a.getAttribute("x")),
(g=a.getAttribute("y"))!==null&&d.setAttribute("y",g));f=d.cloneNode(1);f.setAttribute("stroke",b[1]);f.setAttribute("stroke-width",b[0]);f.setAttribute("stroke-linejoin","round");a.insertBefore(f,c)})};w.plotOptions.heatmap=l(w.plotOptions.scatter,{animation:!1,borderWidth:0,nullColor:"#F8F8F8",dataLabels:{formatter:function(){return this.point.value},verticalAlign:"middle",crop:!1,overflow:!1,style:{color:"white",fontWeight:"bold",HcTextStroke:"1px rgba(0,0,0,0.5)"}},marker:null,tooltip:{pointFormat:"{point.x}, {point.y}: {point.value}<br/>"},
states:{normal:{animation:!0},hover:{brightness:0.2}}});o.heatmap=A(o.scatter,l(h,{type:"heatmap",pointArrayMap:["y","value"],hasPointSpecificOptions:!0,supportsDrilldown:!0,getExtremesFromAll:!0,init:function(){o.scatter.prototype.init.apply(this,arguments);this.pointRange=this.options.colsize||1;this.yAxis.axisPointRange=this.options.rowsize||1},translate:function(){var b=this.options,a=this.xAxis,d=this.yAxis;this.generatePoints();k(this.points,function(c){var e=(b.colsize||1)/2,g=(b.rowsize||
1)/2,f=Math.round(a.len-a.translate(c.x-e,0,1,0,1)),e=Math.round(a.len-a.translate(c.x+e,0,1,0,1)),h=Math.round(d.translate(c.y-g,0,1,0,1)),g=Math.round(d.translate(c.y+g,0,1,0,1));c.plotX=(f+e)/2;c.plotY=(h+g)/2;c.shapeType="rect";c.shapeArgs={x:Math.min(f,e),y:Math.min(h,g),width:Math.abs(e-f),height:Math.abs(g-h)}});this.translateColors();this.chart.hasRendered&&k(this.points,function(a){a.shapeArgs.fill=a.color})},drawPoints:o.column.prototype.drawPoints,animate:n,getBox:n,drawLegendSymbol:t.drawRectangle,
getExtremes:function(){u.prototype.getExtremes.call(this,this.valueData);this.valueMin=this.dataMin;this.valueMax=this.dataMax;u.prototype.getExtremes.call(this)}}))})(Highcharts);
|
tlan16/sushi-co
|
web/protected/controls/HiMap/lib/js/modules/heatmap.js
|
JavaScript
|
mit
| 7,994
|
CKEDITOR.plugins.setLang("colordialog","bn",{clear:"Clear",highlight:"Highlight",options:"Color Options",selected:"Selected Color",title:"Select color"});
|
AaronH92/mProve3.2
|
www/lib/ckeditor/plugins/colordialog/lang/bn.js
|
JavaScript
|
apache-2.0
| 157
|
var inst = require("../index").getInstance();
inst.applyConfig({ debug: true, filter: "debug" });
module.exports = inst.use("node-flick");
|
berkmancenter/spectacle
|
web/js/app/editor/node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/node-flick/debug.js
|
JavaScript
|
gpl-2.0
| 139
|
/*
YUI 3.16.0 (build 76f0e08)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('event-key', function (Y, NAME) {
/**
* Functionality to listen for one or more specific key combinations.
* @module event
* @submodule event-key
*/
var ALT = "+alt",
CTRL = "+ctrl",
META = "+meta",
SHIFT = "+shift",
trim = Y.Lang.trim,
eventDef = {
KEY_MAP: {
enter : 13,
space : 32,
esc : 27,
backspace: 8,
tab : 9,
pageup : 33,
pagedown : 34
},
_typeRE: /^(up|down|press):/,
_keysRE: /^(?:up|down|press):|\+(alt|ctrl|meta|shift)/g,
processArgs: function (args) {
var spec = args.splice(3,1)[0],
mods = Y.Array.hash(spec.match(/\+(?:alt|ctrl|meta|shift)\b/g) || []),
config = {
type: this._typeRE.test(spec) ? RegExp.$1 : null,
mods: mods,
keys: null
},
// strip type and modifiers from spec, leaving only keyCodes
bits = spec.replace(this._keysRE, ''),
chr, uc, lc, i;
if (bits) {
bits = bits.split(',');
config.keys = {};
// FIXME: need to support '65,esc' => keypress, keydown
for (i = bits.length - 1; i >= 0; --i) {
chr = trim(bits[i]);
// catch sloppy filters, trailing commas, etc 'a,,'
if (!chr) {
continue;
}
// non-numerics are single characters or key names
if (+chr == chr) {
config.keys[chr] = mods;
} else {
lc = chr.toLowerCase();
if (this.KEY_MAP[lc]) {
config.keys[this.KEY_MAP[lc]] = mods;
// FIXME: '65,enter' defaults keydown for both
if (!config.type) {
config.type = "down"; // safest
}
} else {
// FIXME: Character mapping only works for keypress
// events. Otherwise, it uses String.fromCharCode()
// from the keyCode, which is wrong.
chr = chr.charAt(0);
uc = chr.toUpperCase();
if (mods["+shift"]) {
chr = uc;
}
// FIXME: stupid assumption that
// the keycode of the lower case == the
// charCode of the upper case
// a (key:65,char:97), A (key:65,char:65)
config.keys[chr.charCodeAt(0)] =
(chr === uc) ?
// upper case chars get +shift free
Y.merge(mods, { "+shift": true }) :
mods;
}
}
}
}
if (!config.type) {
config.type = "press";
}
return config;
},
on: function (node, sub, notifier, filter) {
var spec = sub._extra,
type = "key" + spec.type,
keys = spec.keys,
method = (filter) ? "delegate" : "on";
// Note: without specifying any keyCodes, this becomes a
// horribly inefficient alias for 'keydown' (et al), but I
// can't abort this subscription for a simple
// Y.on('keypress', ...);
// Please use keyCodes or just subscribe directly to keydown,
// keyup, or keypress
sub._detach = node[method](type, function (e) {
var key = keys ? keys[e.which] : spec.mods;
if (key &&
(!key[ALT] || (key[ALT] && e.altKey)) &&
(!key[CTRL] || (key[CTRL] && e.ctrlKey)) &&
(!key[META] || (key[META] && e.metaKey)) &&
(!key[SHIFT] || (key[SHIFT] && e.shiftKey)))
{
notifier.fire(e);
}
}, filter);
},
detach: function (node, sub, notifier) {
sub._detach.detach();
}
};
eventDef.delegate = eventDef.on;
eventDef.detachDelegate = eventDef.detach;
/**
* <p>Add a key listener. The listener will only be notified if the
* keystroke detected meets the supplied specification. The
* specification is a string that is defined as:</p>
*
* <dl>
* <dt>spec</dt>
* <dd><code>[{type}:]{code}[,{code}]*</code></dd>
* <dt>type</dt>
* <dd><code>"down", "up", or "press"</code></dd>
* <dt>code</dt>
* <dd><code>{keyCode|character|keyName}[+{modifier}]*</code></dd>
* <dt>modifier</dt>
* <dd><code>"shift", "ctrl", "alt", or "meta"</code></dd>
* <dt>keyName</dt>
* <dd><code>"enter", "space", "backspace", "esc", "tab", "pageup", or "pagedown"</code></dd>
* </dl>
*
* <p>Examples:</p>
* <ul>
* <li><code>Y.on("key", callback, "press:12,65+shift+ctrl", "#my-input");</code></li>
* <li><code>Y.delegate("key", preventSubmit, "#forms", "enter", "input[type=text]");</code></li>
* <li><code>Y.one("doc").on("key", viNav, "j,k,l,;");</code></li>
* </ul>
*
* @event key
* @for YUI
* @param type {string} 'key'
* @param fn {function} the function to execute
* @param id {string|HTMLElement|collection} the element(s) to bind
* @param spec {string} the keyCode and modifier specification
* @param o optional context object
* @param args 0..n additional arguments to provide to the listener.
* @return {Event.Handle} the detach handle
*/
Y.Event.define('key', eventDef, true);
}, '3.16.0', {"requires": ["event-synthetic"]});
|
vousk/jsdelivr
|
files/yui/3.16.0/event-key/event-key.js
|
JavaScript
|
mit
| 6,214
|
// Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
// This work is free. You can redistribute it and/or modify it
// under the terms of the WTFPL, Version 2
// For more information see LICENSE.txt or http://www.wtfpl.net/
//
// For more information, the home page:
// http://pieroxy.net/blog/pages/lz-string/testing.html
//
// LZ-based compression algorithm, version 1.3.5
var LZString = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
_f : String.fromCharCode,
compressToBase64 : function (input) {
if (input == null) return "";
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = LZString.compress(input);
while (i < input.length*2) {
if (i%2==0) {
chr1 = input.charCodeAt(i/2) >> 8;
chr2 = input.charCodeAt(i/2) & 255;
if (i/2+1 < input.length)
chr3 = input.charCodeAt(i/2+1) >> 8;
else
chr3 = NaN;
} else {
chr1 = input.charCodeAt((i-1)/2) & 255;
if ((i+1)/2 < input.length) {
chr2 = input.charCodeAt((i+1)/2) >> 8;
chr3 = input.charCodeAt((i+1)/2) & 255;
} else
chr2=chr3=NaN;
}
i+=3;
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
LZString._keyStr.charAt(enc1) + LZString._keyStr.charAt(enc2) +
LZString._keyStr.charAt(enc3) + LZString._keyStr.charAt(enc4);
}
return output;
},
decompressFromBase64 : function (input) {
if (input == null) return "";
var output = "",
ol = 0,
output_,
chr1, chr2, chr3,
enc1, enc2, enc3, enc4,
i = 0, f=LZString._f;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = LZString._keyStr.indexOf(input.charAt(i++));
enc2 = LZString._keyStr.indexOf(input.charAt(i++));
enc3 = LZString._keyStr.indexOf(input.charAt(i++));
enc4 = LZString._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
if (ol%2==0) {
output_ = chr1 << 8;
if (enc3 != 64) {
output += f(output_ | chr2);
}
if (enc4 != 64) {
output_ = chr3 << 8;
}
} else {
output = output + f(output_ | chr1);
if (enc3 != 64) {
output_ = chr2 << 8;
}
if (enc4 != 64) {
output += f(output_ | chr3);
}
}
ol+=3;
}
return LZString.decompress(output);
},
compressToUTF16 : function (input) {
if (input == null) return "";
var output = "",
i,c,
current,
status = 0,
f = LZString._f;
input = LZString.compress(input);
for (i=0 ; i<input.length ; i++) {
c = input.charCodeAt(i);
switch (status++) {
case 0:
output += f((c >> 1)+32);
current = (c & 1) << 14;
break;
case 1:
output += f((current + (c >> 2))+32);
current = (c & 3) << 13;
break;
case 2:
output += f((current + (c >> 3))+32);
current = (c & 7) << 12;
break;
case 3:
output += f((current + (c >> 4))+32);
current = (c & 15) << 11;
break;
case 4:
output += f((current + (c >> 5))+32);
current = (c & 31) << 10;
break;
case 5:
output += f((current + (c >> 6))+32);
current = (c & 63) << 9;
break;
case 6:
output += f((current + (c >> 7))+32);
current = (c & 127) << 8;
break;
case 7:
output += f((current + (c >> 8))+32);
current = (c & 255) << 7;
break;
case 8:
output += f((current + (c >> 9))+32);
current = (c & 511) << 6;
break;
case 9:
output += f((current + (c >> 10))+32);
current = (c & 1023) << 5;
break;
case 10:
output += f((current + (c >> 11))+32);
current = (c & 2047) << 4;
break;
case 11:
output += f((current + (c >> 12))+32);
current = (c & 4095) << 3;
break;
case 12:
output += f((current + (c >> 13))+32);
current = (c & 8191) << 2;
break;
case 13:
output += f((current + (c >> 14))+32);
current = (c & 16383) << 1;
break;
case 14:
output += f((current + (c >> 15))+32, (c & 32767)+32);
status = 0;
break;
}
}
return output + f(current + 32);
},
decompressFromUTF16 : function (input) {
if (input == null) return "";
var output = "",
current,c,
status=0,
i = 0,
f = LZString._f;
while (i < input.length) {
c = input.charCodeAt(i) - 32;
switch (status++) {
case 0:
current = c << 1;
break;
case 1:
output += f(current | (c >> 14));
current = (c&16383) << 2;
break;
case 2:
output += f(current | (c >> 13));
current = (c&8191) << 3;
break;
case 3:
output += f(current | (c >> 12));
current = (c&4095) << 4;
break;
case 4:
output += f(current | (c >> 11));
current = (c&2047) << 5;
break;
case 5:
output += f(current | (c >> 10));
current = (c&1023) << 6;
break;
case 6:
output += f(current | (c >> 9));
current = (c&511) << 7;
break;
case 7:
output += f(current | (c >> 8));
current = (c&255) << 8;
break;
case 8:
output += f(current | (c >> 7));
current = (c&127) << 9;
break;
case 9:
output += f(current | (c >> 6));
current = (c&63) << 10;
break;
case 10:
output += f(current | (c >> 5));
current = (c&31) << 11;
break;
case 11:
output += f(current | (c >> 4));
current = (c&15) << 12;
break;
case 12:
output += f(current | (c >> 3));
current = (c&7) << 13;
break;
case 13:
output += f(current | (c >> 2));
current = (c&3) << 14;
break;
case 14:
output += f(current | (c >> 1));
current = (c&1) << 15;
break;
case 15:
output += f(current | c);
status=0;
break;
}
i++;
}
return LZString.decompress(output);
//return output;
},
//compress into uint8array (UCS-2 big endian format)
compressToUint8Array: function (uncompressed) {
var compressed = LZString.compress(uncompressed);
var buf=new Uint8Array(compressed.length*2); // 2 bytes per character
for (var i=0, TotalLen=compressed.length; i<TotalLen; i++) {
var current_value = compressed.charCodeAt(i);
buf[i*2] = current_value >>> 8;
buf[i*2+1] = current_value % 256;
}
return buf;
},
//decompress from uint8array (UCS-2 big endian format)
decompressFromUint8Array:function (compressed) {
if (compressed===null || compressed===undefined){
return LZString.decompress(compressed);
} else {
var buf=new Array(compressed.length/2); // 2 bytes per character
for (var i=0, TotalLen=buf.length; i<TotalLen; i++) {
buf[i]=compressed[i*2]*256+compressed[i*2+1];
}
return LZString.decompress(String.fromCharCode.apply(null, buf));
}
},
//compress into a string that is already URI encoded
compressToEncodedURIComponent: function (uncompressed) {
return LZString.compressToBase64(uncompressed).replace("=","$").replace("/","-");
},
//decompress from an output of compressToEncodedURIComponent
decompressFromEncodedURIComponent:function (compressed) {
if (compressed) compressed = compressed.replace("$","=").replace("-","/");
return LZString.decompressFromBase64(compressed);
},
compress: function (uncompressed) {
if (uncompressed == null) return "";
var i, value,
context_dictionary= {},
context_dictionaryToCreate= {},
context_c="",
context_wc="",
context_w="",
context_enlargeIn= 2, // Compensate for the first entry which should not count
context_dictSize= 3,
context_numBits= 2,
context_data_string="",
context_data_val=0,
context_data_position=0,
ii,
f=LZString._f;
for (ii = 0; ii < uncompressed.length; ii += 1) {
context_c = uncompressed.charAt(ii);
if (!Object.prototype.hasOwnProperty.call(context_dictionary,context_c)) {
context_dictionary[context_c] = context_dictSize++;
context_dictionaryToCreate[context_c] = true;
}
context_wc = context_w + context_c;
if (Object.prototype.hasOwnProperty.call(context_dictionary,context_wc)) {
context_w = context_wc;
} else {
if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {
if (context_w.charCodeAt(0)<256) {
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
}
value = context_w.charCodeAt(0);
for (i=0 ; i<8 ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
} else {
value = 1;
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1) | value;
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = 0;
}
value = context_w.charCodeAt(0);
for (i=0 ; i<16 ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
delete context_dictionaryToCreate[context_w];
} else {
value = context_dictionary[context_w];
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
// Add wc to the dictionary.
context_dictionary[context_wc] = context_dictSize++;
context_w = String(context_c);
}
}
// Output the code for w.
if (context_w !== "") {
if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {
if (context_w.charCodeAt(0)<256) {
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
}
value = context_w.charCodeAt(0);
for (i=0 ; i<8 ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
} else {
value = 1;
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1) | value;
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = 0;
}
value = context_w.charCodeAt(0);
for (i=0 ; i<16 ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
delete context_dictionaryToCreate[context_w];
} else {
value = context_dictionary[context_w];
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
}
context_enlargeIn--;
if (context_enlargeIn == 0) {
context_enlargeIn = Math.pow(2, context_numBits);
context_numBits++;
}
}
// Mark the end of the stream
value = 2;
for (i=0 ; i<context_numBits ; i++) {
context_data_val = (context_data_val << 1) | (value&1);
if (context_data_position == 15) {
context_data_position = 0;
context_data_string += f(context_data_val);
context_data_val = 0;
} else {
context_data_position++;
}
value = value >> 1;
}
// Flush the last char
while (true) {
context_data_val = (context_data_val << 1);
if (context_data_position == 15) {
context_data_string += f(context_data_val);
break;
}
else context_data_position++;
}
return context_data_string;
},
decompress: function (compressed) {
if (compressed == null) return "";
if (compressed == "") return null;
var dictionary = [],
next,
enlargeIn = 4,
dictSize = 4,
numBits = 3,
entry = "",
result = "",
i,
w,
bits, resb, maxpower, power,
c,
f = LZString._f,
data = {string:compressed, val:compressed.charCodeAt(0), position:32768, index:1};
for (i = 0; i < 3; i += 1) {
dictionary[i] = i;
}
bits = 0;
maxpower = Math.pow(2,2);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
switch (next = bits) {
case 0:
bits = 0;
maxpower = Math.pow(2,8);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
c = f(bits);
break;
case 1:
bits = 0;
maxpower = Math.pow(2,16);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
c = f(bits);
break;
case 2:
return "";
}
dictionary[3] = c;
w = result = c;
while (true) {
if (data.index > data.string.length) {
return "";
}
bits = 0;
maxpower = Math.pow(2,numBits);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
switch (c = bits) {
case 0:
bits = 0;
maxpower = Math.pow(2,8);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
dictionary[dictSize++] = f(bits);
c = dictSize-1;
enlargeIn--;
break;
case 1:
bits = 0;
maxpower = Math.pow(2,16);
power=1;
while (power!=maxpower) {
resb = data.val & data.position;
data.position >>= 1;
if (data.position == 0) {
data.position = 32768;
data.val = data.string.charCodeAt(data.index++);
}
bits |= (resb>0 ? 1 : 0) * power;
power <<= 1;
}
dictionary[dictSize++] = f(bits);
c = dictSize-1;
enlargeIn--;
break;
case 2:
return result;
}
if (enlargeIn == 0) {
enlargeIn = Math.pow(2, numBits);
numBits++;
}
if (dictionary[c]) {
entry = dictionary[c];
} else {
if (c === dictSize) {
entry = w + w.charAt(0);
} else {
return null;
}
}
result += entry;
// Add w+entry[0] to the dictionary.
dictionary[dictSize++] = w + entry.charAt(0);
enlargeIn--;
w = entry;
if (enlargeIn == 0) {
enlargeIn = Math.pow(2, numBits);
numBits++;
}
}
}
};
if( typeof module !== 'undefined' && module != null ) {
module.exports = LZString
}
|
fisherman1234/scratchpad-web
|
public/js/libs/lz-string.js
|
JavaScript
|
mit
| 20,374
|
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": {
"0": "AM",
"1": "PM"
},
"DAY": {
"0": "dimanche",
"1": "lundi",
"2": "mardi",
"3": "mercredi",
"4": "jeudi",
"5": "vendredi",
"6": "samedi"
},
"MONTH": {
"0": "janvier",
"1": "février",
"2": "mars",
"3": "avril",
"4": "mai",
"5": "juin",
"6": "juillet",
"7": "août",
"8": "septembre",
"9": "octobre",
"10": "novembre",
"11": "décembre"
},
"SHORTDAY": {
"0": "dim.",
"1": "lun.",
"2": "mar.",
"3": "mer.",
"4": "jeu.",
"5": "ven.",
"6": "sam."
},
"SHORTMONTH": {
"0": "janv.",
"1": "févr.",
"2": "mars",
"3": "avr.",
"4": "mai",
"5": "juin",
"6": "juil.",
"7": "août",
"8": "sept.",
"9": "oct.",
"10": "nov.",
"11": "déc."
},
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "€",
"DECIMAL_SEP": ",",
"GROUP_SEP": " ",
"PATTERNS": {
"0": {
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
"1": {
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(",
"negSuf": " \u00A4)",
"posPre": "",
"posSuf": " \u00A4"
}
}
},
"id": "fr",
"pluralCat": function (n) { if (n >= 0 && n <= 2 && n != 2) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
Laimiux/mydeatree
|
staticfiles/js/angular-1.1.4/i18n/angular-locale_fr.js
|
JavaScript
|
bsd-3-clause
| 2,156
|
var childProcess = require('child_process');
var execFile = childProcess.execFile;
module.exports = function(projectName, configPath) {
return new Promise(function(resolve, reject) {
execFile(configPath + projectName + ".sh", {
cwd: configPath
}, function(err, stdout, stderr) {
if (err) {
console.log(err)
reject(err);
}
console.log(stdout.toString())
resolve(true);
})
})
}
|
SANGET/uke
|
lib/deployment.js
|
JavaScript
|
isc
| 439
|
// lc2mode.js, copyright (c) by Simon Pratt
(function(CodeMirror) {
"use strict";
// Modified from the sample simplemode
CodeMirror.defineSimpleMode("lc2", {
start: [
{regex: /"(?:[^\\]|\\.)*?(?:"|$)/, token: "string"},
{regex: /(?:getc|out|puts|in|halt|add|and|nop|br|brn|brz|brp|brnp|brnz|brzp|brnzp|jmp|jmpr|jsr|jsrr|ld|ldi|ldr|lea|not|ret|rti|st|sti|str|trap)\b/,
token: "keyword"}, // instructions
{regex: /\.[^\s]+/, token: "atom"}, // assembly directive
{regex: /(?:\$|x|X)[a-f\d]+|#?\d+|(?:%|b|B)[01]+/,
token: "number"},
{regex: /;.*/, token: "comment"},
{regex: /(?:r\d|pc|ir)\b/, token: "variable-2"}, // registers
]
});
CodeMirror.defineMIME("text/x-lc2", "lc2");
CodeMirror.defineMIME("text/x-lc2", { name: "lc2" });
})(CodeMirror);
|
spratt/lc2.js
|
lc2mode.js
|
JavaScript
|
isc
| 887
|
var hapi = require('./fixtures/hapi-server');
var schemas = require('./fixtures/schemas');
var routes = require('./fixtures/routes');
var expect = require('chai').expect;
describe('Usage tests', function() {
describe('Default config usage', function() {
it('Should work as a plugin', function() {
return hapi.faker({
schemas: [schemas.hello]
})
.then(function(server) {
server.route(routes.plugin);
return server;
})
.then(function(server) {
return server.injectThen({
method: 'GET',
url: '/faker'
}).then(function(res) {
expect(res.result.shouldnot).to.be.equal(undefined);
expect(res.result.hello).to.be.an('string');
});
});
});
it('Should not intercept other requests', function() {
return hapi.faker({
schemas: [schemas.hello]
})
.then(function(server) {
server.route(routes.clean);
return server;
})
.then(function(server) {
return server.injectThen({
method: 'GET',
url: '/faker'
}).then(function(res) {
expect(res.result.should).to.be.equal('exists');
expect(res.result.hello).to.be.equal(undefined);
});
});
});
it('Should hook when configured', function() {
return hapi.faker({
schemas: [schemas.hello],
hooks: {
request: function(){
return false;
}
}
})
.then(function(server) {
server.route(routes.plugin);
return server;
})
.then(function(server) {
return server.injectThen({
method: 'GET',
url: '/faker'
}).then(function(res) {
expect(res.result.hello).to.be.equal(undefined);
});
});
});
it('Should work as a handler', function() {
return hapi.faker({
schemas: [schemas.hello]
})
.then(function(server) {
server.route(routes.handler);
return server;
})
.then(function(server) {
return server.injectThen({
method: 'GET',
url: '/faker'
}).then(function(res) {
expect(res.result.hello).to.be.an('string');
});
});
});
it('Should work as a function', function() {
return hapi.faker({
schemas: [schemas.hello]
})
.then(function(server) {
server.route(routes.function);
return server;
})
.then(function(server) {
return server.injectThen({
method: 'GET',
url: '/faker'
}).then(function(res) {
expect(res.result.hello).to.be.an('string');
});
});
});
});
});
|
alanhoff/node-hapi-faker
|
tests/usage-test.js
|
JavaScript
|
isc
| 2,926
|
import mod1091 from './mod1091';
var value=mod1091+1;
export default value;
|
MirekSz/webpack-es6-ts
|
app/mods/mod1092.js
|
JavaScript
|
isc
| 76
|
var express = require('express'),
nj = require('nunjucks');
var app = express();
app.get('/', function(req, res) {
var dev = req.query.dev;
if (!dev) dev = 1;
var ctx = {
DEV: dev,
tpl: req.query.tpl,
lang: req.query.lang
};
console.log(ctx);
res.send( nj.render('tpl/index.html', ctx) );
});
app.use( express.static('.') );
app.listen(3000);
|
gig177/plugin-nunjucks
|
server.js
|
JavaScript
|
isc
| 397
|
(function(d3, stubData) {
"use strict";
var margin = { top: 20, right: 20, bottom: 30, left: 80 },
width = 680 - margin.left - margin.right,
height = 230 - margin.top - margin.bottom;
var retirementOffset = 0;
var contributionOffset = 0;
var data = stubData(retirementOffset, contributionOffset);
d3.select("#later").on("click", function() {
retirementOffset += 3;
var data = stubData(retirementOffset, contributionOffset);
data.forEach(function(entry, index) {
renderChart(entry, index, retirementOffset, contributionOffset);
});
});
d3.select("#sooner").on("click", function() {
retirementOffset -= 3;
var data = stubData(retirementOffset, contributionOffset);
data.forEach(function(entry, index) {
renderChart(entry, index, retirementOffset, contributionOffset);
});
});
d3.select("#more").on("click", function() {
contributionOffset += 3;
var data = stubData(retirementOffset, contributionOffset);
data.forEach(function(entry, index) {
renderChart(entry, index, retirementOffset, contributionOffset);
});
});
d3.select("#less").on("click", function() {
contributionOffset -= 3;
var data = stubData(retirementOffset, contributionOffset);
data.forEach(function(entry, index) {
renderChart(entry, index, retirementOffset, contributionOffset);
});
});
function renderChart(entry, index, retirementOffset, contributionOffset) {
var lineData = entry.computed.Savings;
var x = d3.scale
.linear()
.range([0, width])
.domain(
d3.extent(lineData, function(d) {
return d.age;
})
);
var y = d3.scale
.linear()
.range([height, 0])
.domain([
0,
d3.max(lineData, function(d) {
return d.savings;
}),
]);
var xAxis = d3.svg
.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg
.axis()
.scale(y)
.orient("left");
var lineFunction = d3.svg
.line()
.x(function(d) {
return x(d.age);
})
.y(function(d) {
return y(d.savings);
});
var gigaTickFunction = d3.svg
.line()
.x(function(d) {
return x(entry.RetirementAge + retirementOffset - 1);
})
.y(function(d) {
if (d.age < entry.RetirementAge + retirementOffset) {
return y(d.savings);
}
});
var interpolation = d3.svg
.area()
.interpolate("linear")
.x(function(d) {
return x(d.age);
})
.y0(height)
.y1(function(d) {
return y(d.savings);
});
//d3.select("#entry" + index + ' svg').remove();
if (d3.select("#entry" + index + " svg") < 1) {
var svg = d3
.select("#entry" + index)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
} else {
var svg = d3.select("#entry" + index + " svg");
}
if (svg.selectAll(".area")[0].length < 1) {
svg
.append("path")
.attr("class", "area")
.attr("d", interpolation(lineData));
} else {
svg
.selectAll(".area")
.transition()
.duration(500)
.attr("d", interpolation(lineData));
}
if (svg.selectAll(".line.savings")[0].length < 1) {
svg
.append("path")
.attr("class", "line savings")
.attr("d", lineFunction(lineData))
.attr("fill", "none");
} else {
svg
.selectAll(".line.savings")
.transition()
.duration(500)
.attr("d", lineFunction(lineData));
}
if (svg.selectAll(".line.gigatick")[0].length < 1) {
svg
.append("g")
.attr("class", "line gigatick")
.attr("d", gigaTickFunction(lineData))
.attr("fill", "none");
} else {
svg
.selectAll(".line.gigatick")
.transition()
.duration(500)
.attr("d", gigaTickFunction(lineData));
}
if (svg.selectAll(".x.axis")[0].length < 1) {
svg
.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
} else {
svg
.selectAll(".x.axis")
.transition()
.duration(500)
.call(xAxis);
}
if (svg.selectAll(".y.axis")[0].length < 1) {
svg
.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Savings ($)");
} else {
svg
.selectAll(".y.axis")
.transition()
.duration(500)
.call(yAxis);
}
}
data.forEach(function(entry, index) {
renderChart(entry, index, retirementOffset, contributionOffset);
});
})(window.d3, stubData);
function stubData(retirementOffset, contributionOffset) {
var raw = window.rawData;
var lineData = raw.map(function(entry, index) {
var savings = [];
entry.computed.YearlyContribution =
(entry.GrossIncome / 100) *
Math.max(0, entry.ContributionRate + contributionOffset);
for (
var i = 0;
i < entry.computed.DurationUntilRetirement + retirementOffset;
i++
) {
savings.push({
age: entry.computed.UserAge + i,
savings: futureValue(
entry.AccountBalance + entry.computed.YearlyContribution * (i + 1),
1,
entry.RateOfReturn,
i + 1
),
});
}
var savingsSum = savings[savings.length - 1]
? savings[savings.length - 1].savings
: entry.AccountBalance;
var yearSavings;
var annuity = savingsSum / entry.RetirementDuration;
var desiredAnnuity = entry.AnnualIncomeGoal;
for (var j = 0; j < entry.RetirementDuration; j++) {
yearSavings = savings[i + j - 1] ? savings[i + j - 1].savings : 0;
savings.push({
age: entry.computed.UserAge + i + j,
savings: Math.max(
0,
futureValue(yearSavings - desiredAnnuity, 1, entry.RateOfReturn, 1)
),
});
}
entry.computed.Savings = savings;
return entry;
});
return lineData;
}
// https://helloacm.com/common-javascript-functions-for-financial-calculations/
/************************************************
* Future Value *
* fv = pv * (1 + (rate / freq))^periods *
* fv = Future Value *
* pv = Present Value *
* rate = interest rate (expressed as %) *
* freq = compounding frequency *
* periods = number of periods until maturity *
************************************************/
function futureValue(pv, freq, rate, periods) {
return pv * Math.pow(1 + rate / 100 / freq, periods);
}
|
ThibWeb/thibaudcolas
|
src/assets/data/area-chart-interaction/script.js
|
JavaScript
|
isc
| 7,068
|
export default {
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
test: /\.js$/,
}],
},
};
|
colinmeinke/svg-shapes
|
webpack.config.babel.js
|
JavaScript
|
isc
| 136
|
import AppDispatcher from '../dispatchers/app-dispatcher.js'
import TransloaditUpload from '../lib/transloadit'
let AttachmentActions = {
createUpload(file) {
AppDispatcher.dispatch({
actionType: 'UPLOAD_START',
file: file
})
new TransloaditUpload()
.uploadFile(file)
.then(function(upload) {
AppDispatcher.dispatch({
actionType: 'UPLOAD_COMPLETE',
payload: upload,
file: file
})
})
},
createAttachment() {
}
}
export default AttachmentActions
|
sprintly/sprintly-kanban
|
app/actions/attachment-actions.js
|
JavaScript
|
isc
| 548
|
/**
* @module lib/plugins/os
*/
'use strict';
/**
* @typedef {Object} AgentFacade
*/
var os = require('os');
var Promise = require('bluebird');
var os_plugin = {
priority: 100,
name: "core:os",
config: null,
pluginsApi: null,
/**
* @return {Promise}
*/
init: function () {
return Promise.resolve();
},
/**
* @return {Promise}
*/
boot: function () {
var self = this;
this.pluginsApi.onStatusCheck(function () {
self.reportOSStatus();
});
return Promise.resolve();
},
reportOSStatus: function () {
var extraData = {
uptime: os.uptime(),
loadavg: os.loadavg(),
totalmem: os.totalmem(),
freemem: os.freemem(),
cpuinfo: os.cpus()
};
this.pluginsApi.publishStatus(this, true, extraData);
}
};
module.exports = os_plugin;
|
vladbalmos/chiana-agent
|
agent/plugins/os/index.js
|
JavaScript
|
isc
| 835
|
System.register(["angular2/src/facade/lang", "angular2/src/dom/dom_adapter", "angular2/src/facade/collection", "angular2/src/core/zone/vm_turn_zone"], function($__export) {
"use strict";
var isBlank,
BaseException,
isPresent,
StringWrapper,
DOM,
List,
ListWrapper,
MapWrapper,
VmTurnZone,
BUBBLE_SYMBOL,
EventManager,
EventManagerPlugin,
DomEventsPlugin;
return {
setters: [function($__m) {
isBlank = $__m.isBlank;
BaseException = $__m.BaseException;
isPresent = $__m.isPresent;
StringWrapper = $__m.StringWrapper;
}, function($__m) {
DOM = $__m.DOM;
}, function($__m) {
List = $__m.List;
ListWrapper = $__m.ListWrapper;
MapWrapper = $__m.MapWrapper;
}, function($__m) {
VmTurnZone = $__m.VmTurnZone;
}],
execute: function() {
BUBBLE_SYMBOL = '^';
EventManager = $__export("EventManager", (function() {
var EventManager = function EventManager(plugins, zone) {
this._zone = zone;
this._plugins = plugins;
for (var i = 0; i < plugins.length; i++) {
plugins[i].manager = this;
}
};
return ($traceurRuntime.createClass)(EventManager, {
addEventListener: function(element, eventName, handler) {
var withoutBubbleSymbol = this._removeBubbleSymbol(eventName);
var plugin = this._findPluginFor(withoutBubbleSymbol);
plugin.addEventListener(element, withoutBubbleSymbol, handler, withoutBubbleSymbol != eventName);
},
addGlobalEventListener: function(target, eventName, handler) {
var withoutBubbleSymbol = this._removeBubbleSymbol(eventName);
var plugin = this._findPluginFor(withoutBubbleSymbol);
return plugin.addGlobalEventListener(target, withoutBubbleSymbol, handler, withoutBubbleSymbol != eventName);
},
getZone: function() {
return this._zone;
},
_findPluginFor: function(eventName) {
var plugins = this._plugins;
for (var i = 0; i < plugins.length; i++) {
var plugin = plugins[i];
if (plugin.supports(eventName)) {
return plugin;
}
}
throw new BaseException(("No event manager plugin found for event " + eventName));
},
_removeBubbleSymbol: function(eventName) {
return eventName[0] == BUBBLE_SYMBOL ? StringWrapper.substring(eventName, 1) : eventName;
}
}, {});
}()));
Object.defineProperty(EventManager, "parameters", {get: function() {
return [[assert.genericType(List, EventManagerPlugin)], [VmTurnZone]];
}});
Object.defineProperty(EventManager.prototype.addEventListener, "parameters", {get: function() {
return [[], [assert.type.string], [Function]];
}});
Object.defineProperty(EventManager.prototype.addGlobalEventListener, "parameters", {get: function() {
return [[assert.type.string], [assert.type.string], [Function]];
}});
Object.defineProperty(EventManager.prototype._findPluginFor, "parameters", {get: function() {
return [[assert.type.string]];
}});
Object.defineProperty(EventManager.prototype._removeBubbleSymbol, "parameters", {get: function() {
return [[assert.type.string]];
}});
EventManagerPlugin = $__export("EventManagerPlugin", (function() {
var EventManagerPlugin = function EventManagerPlugin() {
;
};
return ($traceurRuntime.createClass)(EventManagerPlugin, {
supports: function(eventName) {
return false;
},
addEventListener: function(element, eventName, handler, shouldSupportBubble) {
throw "not implemented";
},
addGlobalEventListener: function(element, eventName, handler, shouldSupportBubble) {
throw "not implemented";
}
}, {});
}()));
Object.defineProperty(EventManagerPlugin.prototype.supports, "parameters", {get: function() {
return [[assert.type.string]];
}});
Object.defineProperty(EventManagerPlugin.prototype.addEventListener, "parameters", {get: function() {
return [[], [assert.type.string], [Function], [assert.type.boolean]];
}});
Object.defineProperty(EventManagerPlugin.prototype.addGlobalEventListener, "parameters", {get: function() {
return [[], [assert.type.string], [Function], [assert.type.boolean]];
}});
DomEventsPlugin = $__export("DomEventsPlugin", (function($__super) {
var DomEventsPlugin = function DomEventsPlugin() {
$traceurRuntime.superConstructor(DomEventsPlugin).apply(this, arguments);
;
};
return ($traceurRuntime.createClass)(DomEventsPlugin, {
supports: function(eventName) {
return true;
},
addEventListener: function(element, eventName, handler, shouldSupportBubble) {
var outsideHandler = this._getOutsideHandler(shouldSupportBubble, element, handler, this.manager._zone);
this.manager._zone.runOutsideAngular((function() {
DOM.on(element, eventName, outsideHandler);
}));
},
addGlobalEventListener: function(target, eventName, handler, shouldSupportBubble) {
var element = DOM.getGlobalEventTarget(target);
var outsideHandler = this._getOutsideHandler(shouldSupportBubble, element, handler, this.manager._zone);
return this.manager._zone.runOutsideAngular((function() {
return DOM.onAndCancel(element, eventName, outsideHandler);
}));
},
_getOutsideHandler: function(shouldSupportBubble, element, handler, zone) {
return shouldSupportBubble ? DomEventsPlugin.bubbleCallback(element, handler, zone) : DomEventsPlugin.sameElementCallback(element, handler, zone);
}
}, {
sameElementCallback: function(element, handler, zone) {
return (function(event) {
if (event.target === element) {
zone.run((function() {
return handler(event);
}));
}
});
},
bubbleCallback: function(element, handler, zone) {
return (function(event) {
return zone.run((function() {
return handler(event);
}));
});
}
}, $__super);
}(EventManagerPlugin)));
Object.defineProperty(DomEventsPlugin.prototype.supports, "parameters", {get: function() {
return [[assert.type.string]];
}});
Object.defineProperty(DomEventsPlugin.prototype.addEventListener, "parameters", {get: function() {
return [[], [assert.type.string], [Function], [assert.type.boolean]];
}});
Object.defineProperty(DomEventsPlugin.prototype.addGlobalEventListener, "parameters", {get: function() {
return [[assert.type.string], [assert.type.string], [Function], [assert.type.boolean]];
}});
Object.defineProperty(DomEventsPlugin.prototype._getOutsideHandler, "parameters", {get: function() {
return [[assert.type.boolean], [], [Function], [VmTurnZone]];
}});
}
};
});
//# sourceMappingURL=event_manager.es6.map
//# sourceMappingURL=./event_manager.js.map
|
denzp/pacman
|
application/lib/angular2/src/render/dom/events/event_manager.js
|
JavaScript
|
isc
| 7,565
|
import _find from 'lodash-es/find';
import _omit from 'lodash-es/omit';
import {
event as d3_event,
select as d3_select
} from 'd3-selection';
import { t } from '../util/locale';
import { utilDetect } from '../util/detect';
import { services } from '../services';
import { svgIcon } from '../svg';
export function uiTagReference(tag) {
var taginfo = services.taginfo;
var tagReference = {};
var _button = d3_select(null);
var _body = d3_select(null);
var _loaded;
var _showing;
function findLocal(data) {
var locale = utilDetect().locale.toLowerCase();
var localized;
if (locale !== 'pt-br') { // see #3776, prefer 'pt' over 'pt-br'
localized = _find(data, function(d) {
return d.lang.toLowerCase() === locale;
});
if (localized) return localized;
}
// try the non-regional version of a language, like
// 'en' if the language is 'en-US'
if (locale.indexOf('-') !== -1) {
var first = locale.split('-')[0];
localized = _find(data, function(d) {
return d.lang.toLowerCase() === first;
});
if (localized) return localized;
}
// finally fall back to english
return _find(data, function(d) {
return d.lang.toLowerCase() === 'en';
});
}
function load(param) {
if (!taginfo) return;
_button
.classed('tag-reference-loading', true);
taginfo.docs(param, function show(err, data) {
var docs;
if (!err && data) {
docs = findLocal(data);
}
_body.html('');
if (!docs || !docs.title) {
if (param.hasOwnProperty('value')) {
load(_omit(param, 'value')); // retry with key only
} else {
_body
.append('p')
.attr('class', 'tag-reference-description')
.text(t('inspector.no_documentation_key'));
done();
}
return;
}
if (docs.image && docs.image.thumb_url_prefix) {
_body
.append('img')
.attr('class', 'tag-reference-wiki-image')
.attr('src', docs.image.thumb_url_prefix + '100' + docs.image.thumb_url_suffix)
.on('load', function() { done(); })
.on('error', function() { d3_select(this).remove(); done(); });
} else {
done();
}
_body
.append('p')
.attr('class', 'tag-reference-description')
.text(docs.description || t('inspector.documentation_redirect'));
_body
.append('a')
.attr('class', 'tag-reference-link')
.attr('target', '_blank')
.attr('tabindex', -1)
.attr('href', 'https://wiki.openstreetmap.org/wiki/' + docs.title)
.call(svgIcon('#iD-icon-out-link', 'inline'))
.append('span')
.text(t('inspector.reference'));
// Add link to info about "good changeset comments" - #2923
if (param.key === 'comment') {
_body
.append('a')
.attr('class', 'tag-reference-comment-link')
.attr('target', '_blank')
.attr('tabindex', -1)
.call(svgIcon('#iD-icon-out-link', 'inline'))
.attr('href', t('commit.about_changeset_comments_link'))
.append('span')
.text(t('commit.about_changeset_comments'));
}
});
}
function done() {
_loaded = true;
_button
.classed('tag-reference-loading', false);
_body
.classed('expanded', true)
.transition()
.duration(200)
.style('max-height', '200px')
.style('opacity', '1');
_showing = true;
}
function hide() {
_body
.transition()
.duration(200)
.style('max-height', '0px')
.style('opacity', '0')
.on('end', function () {
_body.classed('expanded', false);
});
_showing = false;
}
tagReference.button = function(selection) {
_button = selection.selectAll('.tag-reference-button')
.data([0]);
_button = _button.enter()
.append('button')
.attr('class', 'tag-reference-button')
.attr('title', t('icons.information'))
.attr('tabindex', -1)
.call(svgIcon('#iD-icon-inspect'))
.merge(_button);
_button
.on('click', function () {
d3_event.stopPropagation();
d3_event.preventDefault();
if (_showing) {
hide();
} else if (_loaded) {
done();
} else {
load(tag);
}
});
};
tagReference.body = function(selection) {
var tagid = tag.rtype || (tag.key + '-' + tag.value);
_body = selection.selectAll('.tag-reference-body')
.data([tagid], function(d) { return d; });
_body.exit()
.remove();
_body = _body.enter()
.append('div')
.attr('class', 'tag-reference-body')
.style('max-height', '0')
.style('opacity', '0')
.merge(_body);
if (_showing === false) {
hide();
}
};
tagReference.showing = function(_) {
if (!arguments.length) return _showing;
_showing = _;
return tagReference;
};
return tagReference;
}
|
ngageoint/hootenanny-ui
|
modules/ui/tag_reference.js
|
JavaScript
|
isc
| 6,017
|
// # Post Model
// [lib/index.js](index.html) > example/model/Post.js
'use strict';
var common = require('../lib/common.js');
require('../../lib/types/Collection.js');
require('../../lib/types/Text.js');
var Model = require('../../lib/types/Model.js');
var PostModel = Model.extend('PostModel');
module.exports = PostModel;
// TODO: add schema support to Model
PostModel.schema = {
author: { type: String },
children: { type: 'Collection' },
text: { type: 'Text' },
time: { type: Date }
};
common.configureCRDT(PostModel, {isServer: false});
|
rolandpoulter/murder
|
example/model/Post.js
|
JavaScript
|
isc
| 557
|
import {Router, Route, IndexRoute} from 'ReactRouter';
import './auth';
import './GlobalStyle';
import './Login';
import './NavigateMenu';
import './Applications';
import './Mounts';
import './EditMount';
import './Settings';
import './NotFound';
var body = document.createElement('div');
$(body).html('<div style="padding-top:20%;text-align:center">Loading...</div>');
$(body).css({height:'100%'});
$('body').append(body);
$('html').addClass(GlobalStyle);
auth.update().then(function() {
$(body).html('');
ReactDOM.render(<Router>
<Route path="/login" component={Login}/>
<Route path="/" component={NavigateMenu}>
<IndexRoute component={Applications}/>
<Route path="applications" component={Applications}/>
<Route path="mounts">
<IndexRoute component={Mounts}/>
<Route path=":id" component={EditMount}/>
</Route>
<Route path="settings" component={Settings}/>
<Route path="*" component={NotFound}/>
</Route>
</Router>, body);
});
window.notEmpty = function(obj) {
if (!obj)
return false;
if (Array.isArray(obj)) {
return obj.length > 0;
}
switch(typeof obj) {
case 'object':
return Object.keys(obj).length > 0
case 'string':
case 'number':
return !!obj;
}
throw new Error('Unable to check emptyness of type ' + (typeof obj));
};
window.forceArray = function(arr) {
if (!arr)
return [];
return Array.isArray(arr) ? arr : [arr];
};
|
davidaq/housekeeper
|
res/public/manager/index.js
|
JavaScript
|
isc
| 1,557
|
'use strict'
const chalk = require('chalk')
const checkpoint = require('../checkpoint')
const conventionalRecommendedBump = require('conventional-recommended-bump')
const figures = require('figures')
const fs = require('fs')
const DotGitignore = require('dotgitignore')
const path = require('path')
const presetLoader = require('../preset-loader')
const runLifecycleScript = require('../run-lifecycle-script')
const semver = require('semver')
const writeFile = require('../write-file')
const { resolveUpdaterObjectFromArgument } = require('../updaters')
let configsToUpdate = {}
async function Bump (args, version) {
// reset the cache of updated config files each
// time we perform the version bump step.
configsToUpdate = {}
if (args.skip.bump) return version
let newVersion = version
await runLifecycleScript(args, 'prerelease')
const stdout = await runLifecycleScript(args, 'prebump')
if (stdout && stdout.trim().length) args.releaseAs = stdout.trim()
const release = await bumpVersion(args.releaseAs, version, args)
if (!args.firstRelease) {
const releaseType = getReleaseType(args.prerelease, release.releaseType, version)
newVersion = semver.valid(releaseType) || semver.inc(version, releaseType, args.prerelease)
updateConfigs(args, newVersion)
} else {
checkpoint(args, 'skip version bump on first release', [], chalk.red(figures.cross))
}
await runLifecycleScript(args, 'postbump')
return newVersion
}
Bump.getUpdatedConfigs = function () {
return configsToUpdate
}
function getReleaseType (prerelease, expectedReleaseType, currentVersion) {
if (isString(prerelease)) {
if (isInPrerelease(currentVersion)) {
if (shouldContinuePrerelease(currentVersion, expectedReleaseType) ||
getTypePriority(getCurrentActiveType(currentVersion)) > getTypePriority(expectedReleaseType)
) {
return 'prerelease'
}
}
return 'pre' + expectedReleaseType
} else {
return expectedReleaseType
}
}
function isString (val) {
return typeof val === 'string'
}
/**
* if a version is currently in pre-release state,
* and if it current in-pre-release type is same as expect type,
* it should continue the pre-release with the same type
*
* @param version
* @param expectType
* @return {boolean}
*/
function shouldContinuePrerelease (version, expectType) {
return getCurrentActiveType(version) === expectType
}
function isInPrerelease (version) {
return Array.isArray(semver.prerelease(version))
}
const TypeList = ['major', 'minor', 'patch'].reverse()
/**
* extract the in-pre-release type in target version
*
* @param version
* @return {string}
*/
function getCurrentActiveType (version) {
const typelist = TypeList
for (let i = 0; i < typelist.length; i++) {
if (semver[typelist[i]](version)) {
return typelist[i]
}
}
}
/**
* calculate the priority of release type,
* major - 2, minor - 1, patch - 0
*
* @param type
* @return {number}
*/
function getTypePriority (type) {
return TypeList.indexOf(type)
}
function bumpVersion (releaseAs, currentVersion, args) {
return new Promise((resolve, reject) => {
if (releaseAs) {
return resolve({
releaseType: releaseAs
})
} else {
const presetOptions = presetLoader(args)
if (typeof presetOptions === 'object') {
if (semver.lt(currentVersion, '1.0.0')) presetOptions.preMajor = true
}
conventionalRecommendedBump({
debug: args.verbose && console.info.bind(console, 'conventional-recommended-bump'),
preset: presetOptions,
path: args.path,
tagPrefix: args.tagPrefix,
lernaPackage: args.lernaPackage
}, function (err, release) {
if (err) return reject(err)
else return resolve(release)
})
}
})
}
/**
* attempt to update the version number in provided `bumpFiles`
* @param args config object
* @param newVersion version number to update to.
* @return void
*/
function updateConfigs (args, newVersion) {
const dotgit = DotGitignore()
args.bumpFiles.forEach(function (bumpFile) {
const updater = resolveUpdaterObjectFromArgument(bumpFile)
if (!updater) {
return
}
const configPath = path.resolve(process.cwd(), updater.filename)
try {
if (dotgit.ignore(configPath)) return
const stat = fs.lstatSync(configPath)
if (!stat.isFile()) return
const contents = fs.readFileSync(configPath, 'utf8')
checkpoint(
args,
'bumping version in ' + updater.filename + ' from %s to %s',
[updater.updater.readVersion(contents), newVersion]
)
writeFile(
args,
configPath,
updater.updater.writeVersion(contents, newVersion)
)
// flag any config files that we modify the version # for
// as having been updated.
configsToUpdate[updater.filename] = true
} catch (err) {
if (err.code !== 'ENOENT') console.warn(err.message)
}
})
}
module.exports = Bump
|
conventional-changelog/standard-version
|
lib/lifecycles/bump.js
|
JavaScript
|
isc
| 5,015
|
/*
3.7.4 Error
Command: ERROR
Parameters: <error message>
The ERROR command is for use by servers when reporting a serious or
fatal error to its peers. It may also be sent from one server to
another but MUST NOT be accepted from any normal unknown clients.
Only an ERROR message SHOULD be used for reporting errors which occur
with a server-to-server link. An ERROR message is sent to the server
at the other end (which reports it to appropriate local users and
logs) and to appropriate local users and logs. It is not to be
passed onto any other servers by a server if it is received from a
server.
The ERROR message is also used before terminating a client
connection.
When a server sends a received ERROR message to its operators, the
message SHOULD be encapsulated inside a NOTICE message, indicating
that the client was not responsible for the error.
Numerics:
None.
Examples:
ERROR :Server *.fi already exists ; ERROR message to the other server
which caused this error.
NOTICE WiZ :ERROR from csd.bu.edu -- Server *.fi already exists
; Same ERROR message as above but
sent to user WiZ on the other server.
*/
|
burninggarden/pirc
|
tests/RFC2812/3._Message_Details/3.7_Miscellaneous_messages/3.7.4_Error.js
|
JavaScript
|
isc
| 1,310
|
import { actionReverse } from '../actions/reverse';
import { osmIsInterestingTag } from './tags';
// For fixing up rendering of multipolygons with tags on the outer member.
// https://github.com/openstreetmap/iD/issues/613
export function osmIsSimpleMultipolygonOuterMember(entity, graph) {
if (entity.type !== 'way' || Object.keys(entity.tags).filter(osmIsInterestingTag).length === 0)
return false;
var parents = graph.parentRelations(entity);
if (parents.length !== 1)
return false;
var parent = parents[0];
if (!parent.isMultipolygon() || Object.keys(parent.tags).filter(osmIsInterestingTag).length > 1)
return false;
var members = parent.members, member;
for (var i = 0; i < members.length; i++) {
member = members[i];
if (member.id === entity.id && member.role && member.role !== 'outer')
return false; // Not outer member
if (member.id !== entity.id && (!member.role || member.role === 'outer'))
return false; // Not a simple multipolygon
}
return parent;
}
export function osmSimpleMultipolygonOuterMember(entity, graph) {
if (entity.type !== 'way')
return false;
var parents = graph.parentRelations(entity);
if (parents.length !== 1)
return false;
var parent = parents[0];
if (!parent.isMultipolygon() || Object.keys(parent.tags).filter(osmIsInterestingTag).length > 1)
return false;
var members = parent.members, member, outerMember;
for (var i = 0; i < members.length; i++) {
member = members[i];
if (!member.role || member.role === 'outer') {
if (outerMember)
return false; // Not a simple multipolygon
outerMember = member;
}
}
if (!outerMember)
return false;
var outerEntity = graph.hasEntity(outerMember.id);
if (!outerEntity || !Object.keys(outerEntity.tags).filter(osmIsInterestingTag).length)
return false;
return outerEntity;
}
// Join `array` into sequences of connecting ways.
//
// Segments which share identical start/end nodes will, as much as possible,
// be connected with each other.
//
// The return value is a nested array. Each constituent array contains elements
// of `array` which have been determined to connect. Each consitituent array
// also has a `nodes` property whose value is an ordered array of member nodes,
// with appropriate order reversal and start/end coordinate de-duplication.
//
// Members of `array` must have, at minimum, `type` and `id` properties.
// Thus either an array of `osmWay`s or a relation member array may be
// used.
//
// If an member has a `tags` property, its tags will be reversed via
// `actionReverse` in the output.
//
// Incomplete members (those for which `graph.hasEntity(element.id)` returns
// false) and non-way members are ignored.
//
export function osmJoinWays(array, graph) {
var joined = [], member, current, nodes, first, last, i, how, what;
array = array.filter(function(member) {
return member.type === 'way' && graph.hasEntity(member.id);
});
function resolve(member) {
return graph.childNodes(graph.entity(member.id));
}
function reverse(member) {
return member.tags ? actionReverse(member.id, { reverseOneway: true })(graph).entity(member.id) : member;
}
while (array.length) {
member = array.shift();
current = [member];
current.nodes = nodes = resolve(member).slice();
joined.push(current);
while (array.length && nodes[0] !== nodes[nodes.length - 1]) {
first = nodes[0];
last = nodes[nodes.length - 1];
for (i = 0; i < array.length; i++) {
member = array[i];
what = resolve(member);
if (last === what[0]) {
how = nodes.push;
what = what.slice(1);
break;
} else if (last === what[what.length - 1]) {
how = nodes.push;
what = what.slice(0, -1).reverse();
member = reverse(member);
break;
} else if (first === what[what.length - 1]) {
how = nodes.unshift;
what = what.slice(0, -1);
break;
} else if (first === what[0]) {
how = nodes.unshift;
what = what.slice(1).reverse();
member = reverse(member);
break;
} else {
what = how = null;
}
}
if (!what)
break; // No more joinable ways.
how.apply(current, [member]);
how.apply(nodes, what);
array.splice(i, 1);
}
}
return joined;
}
|
1ec5/iD
|
modules/osm/multipolygon.js
|
JavaScript
|
isc
| 4,912
|
const TwitterPin = require('twitter-pin')
const Tweeter = require('fast-tweet')
const owo = require('@zuzak/owo')
const colors = require('irc').colors
let twitterPin
module.exports = {
onload: (bot) => {
twitterPin = TwitterPin(bot.config.get('twitter.keys.consumerKey'), bot.config.get('twitter.keys.consumerSecret'))
const getTwitterClient = (bot, user) => new Tweeter({
consumer_key: bot.config.get('twitter.keys.consumerKey'),
consumer_secret: bot.config.get('twitter.keys.consumerSecret'),
access_token_key: bot.config.get(`twitter.users.${user}.key`),
access_token_secret: bot.config.get(`twitter.users.${user}.secret`)
})
bot.tweet = async (user, payload) => {
const isAllowedToTweet = await bot.isNotDisabled()
if (!isAllowedToTweet) throw new Error('Bot disabled')
bot.log('debug', 'Passed speech check')
const client = getTwitterClient(bot, user)
const response = await client.tweet(payload)
if (bot.config.get('twitter.reportingChannel')) {
bot.notice(bot.config.get('twitter.reportingChannel'), [
colors.wrap('light_cyan', '@' + user),
' ',
colors.wrap('cyan', response.text),
' ',
colors.wrap('light_blue', 'https://twitter.com/' + user + '/statuses/' + response.id_str)
].join(''))
}
return response
}
bot.retweet = async (user, id) => {
const client = getTwitterClient(bot, user)
try {
return await client.post(`statuses/retweet/${id}`, { id, trim_user: true })
} catch (e) {
bot.log('error', 'RT error: ' + JSON.stringify(e))
throw e
}
}
},
commands: {
twitterauth: {
help: 'Get twitter authentication URL',
command: () => {
return new Promise((resolve, reject) => {
twitterPin.getUrl(function (err, url) {
if (err) return reject(err)
resolve(url)
})
})
}
},
pin: {
help: 'Authenticate with a Twitter PIN',
usage: ['pin'],
command: async (bot, msg) => {
const response = await new Promise((resolve, reject) => {
twitterPin.authorize(msg.args.pin, (err, result) => {
if (err) return reject(err)
resolve(result)
})
})
bot.config.set(`twitter.users.${response.screen_name}.key`, response.token)
bot.config.set(`twitter.users.${response.screen_name}.secret`, response.secret)
bot.say(msg.nick, JSON.stringify(response))
return 'authorized as ' + response.screen_name
}
},
retweet: {
privileged: true,
help: 'Retweets a tweet',
usage: ['id'],
command: async (bot, msg) => {
try {
return await bot.retweet(bot.config.get('twitter.tweetUser'), msg.args.id)
} catch (e) {
return `Error: ${JSON.stringify(e)}`
}
}
},
tweet: {
privileged: true,
help: 'Tweets a tweet',
command: async (bot, msg) => {
const user = bot.config.get('twitter.tweetUser')
if (!user) return 'tweeting disabled'
bot.log('silly', 'Tweeting...')
const tweet = await bot.tweet(user, { status: msg.body })
return 'https://twitter.com/statuses/' + tweet.id_str
}
}
},
events: {
newNews: async (bot, news) => {
if (!bot.config.has('twitter.newsUser')) return undefined
let user = bot.config.get('twitter.newsUser')
if (news.loud) {
user = bot.config.get('twitter.loudNewsUser')
bot.log('debug', 'Tweeting with loud news user')
}
if (!user) return 'tweeting disabled'
if (news.label && !news.label.toUpperCase().includes('BREAKING')) {
news.text = `${news.label}: ${news.text}`
}
let url = news.url
try {
url = new URL(url)
} catch (e) {
if (e.code === 'ERR_INVALID_URL') {
if (news.source) {
url = `\u2015 ${news.source}` // U+2015 - HORIZONTAL BAR
} else {
url = ''
}
} else {
throw e
}
}
await bot.tweet(user, { status: owo(news.text) + '\r\n' + url })
}
}
}
|
zuzakistan/civilservant
|
modules/twitter.js
|
JavaScript
|
isc
| 4,234
|
'use strict';
const url = require('url'),
qs = require('querystring'),
BrowserWindow = require('browser-window'),
shell = require('shell'),
_ = require('lodash'),
debug = require('debug')('electron-vk:auth');
const redirectUri = 'https://oauth.vk.com/blank.html';
let authWindow = null;
function auth (client_id) {
return new Promise(function (resolve) {
// todo load error handing
let token = null;
authWindow = new BrowserWindow({
width: 600,
height: 400,
type: 'splash',
webPreferences: {
nodeIntegration: false
}
});
authWindow.on('closed', function () {
debug('Authentication window has been closed');
authWindow = null;
resolve(token);
});
authWindow.webContents.on('new-window', function (e, url) {
e.preventDefault();
shell.openExternal(url);
});
authWindow.webContents.on('did-get-redirect-request', function (e, oldUrl, newUrl) {
if (newUrl.indexOf(redirectUri) !== 0)
return;
const hash = url.parse(newUrl).hash.substr(1);
token = _.get(qs.parse(hash), 'access_token');
debug('Received token', token);
authWindow.close();
});
authWindow.loadURL(url.format({
protocol: 'https',
host: 'oauth.vk.com',
pathname: 'authorize',
query: {
client_id: client_id,
scope: [ 'audio' ].join(','),
redirect_uri: redirectUri,
display: 'popup',
v: '5.41',
response_type: 'token'
}
}));
});
}
module.exports = auth;
|
v12/electron-vk-auth-demo
|
auth.js
|
JavaScript
|
isc
| 1,940
|
'use strict';
/**
* Custom implementation of a double ended queue.
*/
function Denque(array, options) {
var options = options || {};
this._head = 0;
this._tail = 0;
this._capacity = options.capacity;
this._capacityMask = 0x3;
this._list = new Array(4);
if (Array.isArray(array)) {
this._fromArray(array);
}
}
/**
* --------------
* PUBLIC API
* -------------
*/
/**
* Returns the item at the specified index from the list.
* 0 is the first element, 1 is the second, and so on...
* Elements at negative values are that many from the end: -1 is one before the end
* (the last element), -2 is two before the end (one before last), etc.
* @param index
* @returns {*}
*/
Denque.prototype.peekAt = function peekAt(index) {
var i = index;
// expect a number or return undefined
if ((i !== (i | 0))) {
return void 0;
}
var len = this.size();
if (i >= len || i < -len) return undefined;
if (i < 0) i += len;
i = (this._head + i) & this._capacityMask;
return this._list[i];
};
/**
* Alias for peekAt()
* @param i
* @returns {*}
*/
Denque.prototype.get = function get(i) {
return this.peekAt(i);
};
/**
* Returns the first item in the list without removing it.
* @returns {*}
*/
Denque.prototype.peek = function peek() {
if (this._head === this._tail) return undefined;
return this._list[this._head];
};
/**
* Alias for peek()
* @returns {*}
*/
Denque.prototype.peekFront = function peekFront() {
return this.peek();
};
/**
* Returns the item that is at the back of the queue without removing it.
* Uses peekAt(-1)
*/
Denque.prototype.peekBack = function peekBack() {
return this.peekAt(-1);
};
/**
* Returns the current length of the queue
* @return {Number}
*/
Object.defineProperty(Denque.prototype, 'length', {
get: function length() {
return this.size();
}
});
/**
* Return the number of items on the list, or 0 if empty.
* @returns {number}
*/
Denque.prototype.size = function size() {
if (this._head === this._tail) return 0;
if (this._head < this._tail) return this._tail - this._head;
else return this._capacityMask + 1 - (this._head - this._tail);
};
/**
* Add an item at the beginning of the list.
* @param item
*/
Denque.prototype.unshift = function unshift(item) {
if (arguments.length === 0) return this.size();
var len = this._list.length;
this._head = (this._head - 1 + len) & this._capacityMask;
this._list[this._head] = item;
if (this._tail === this._head) this._growArray();
if (this._capacity && this.size() > this._capacity) this.pop();
if (this._head < this._tail) return this._tail - this._head;
else return this._capacityMask + 1 - (this._head - this._tail);
};
/**
* Remove and return the first item on the list,
* Returns undefined if the list is empty.
* @returns {*}
*/
Denque.prototype.shift = function shift() {
var head = this._head;
if (head === this._tail) return undefined;
var item = this._list[head];
this._list[head] = undefined;
this._head = (head + 1) & this._capacityMask;
if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray();
return item;
};
/**
* Add an item to the bottom of the list.
* @param item
*/
Denque.prototype.push = function push(item) {
if (arguments.length === 0) return this.size();
var tail = this._tail;
this._list[tail] = item;
this._tail = (tail + 1) & this._capacityMask;
if (this._tail === this._head) {
this._growArray();
}
if (this._capacity && this.size() > this._capacity) {
this.shift();
}
if (this._head < this._tail) return this._tail - this._head;
else return this._capacityMask + 1 - (this._head - this._tail);
};
/**
* Remove and return the last item on the list.
* Returns undefined if the list is empty.
* @returns {*}
*/
Denque.prototype.pop = function pop() {
var tail = this._tail;
if (tail === this._head) return undefined;
var len = this._list.length;
this._tail = (tail - 1 + len) & this._capacityMask;
var item = this._list[this._tail];
this._list[this._tail] = undefined;
if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray();
return item;
};
/**
* Remove and return the item at the specified index from the list.
* Returns undefined if the list is empty.
* @param index
* @returns {*}
*/
Denque.prototype.removeOne = function removeOne(index) {
var i = index;
// expect a number or return undefined
if ((i !== (i | 0))) {
return void 0;
}
if (this._head === this._tail) return void 0;
var size = this.size();
var len = this._list.length;
if (i >= size || i < -size) return void 0;
if (i < 0) i += size;
i = (this._head + i) & this._capacityMask;
var item = this._list[i];
var k;
if (index < size / 2) {
for (k = index; k > 0; k--) {
this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask];
}
this._list[i] = void 0;
this._head = (this._head + 1 + len) & this._capacityMask;
} else {
for (k = size - 1 - index; k > 0; k--) {
this._list[i] = this._list[i = (i + 1 + len) & this._capacityMask];
}
this._list[i] = void 0;
this._tail = (this._tail - 1 + len) & this._capacityMask;
}
return item;
};
/**
* Remove number of items from the specified index from the list.
* Returns array of removed items.
* Returns undefined if the list is empty.
* @param index
* @param count
* @returns {array}
*/
Denque.prototype.remove = function remove(index, count) {
var i = index;
var removed;
var del_count = count;
// expect a number or return undefined
if ((i !== (i | 0))) {
return void 0;
}
if (this._head === this._tail) return void 0;
var size = this.size();
var len = this._list.length;
if (i >= size || i < -size || count < 1) return void 0;
if (i < 0) i += size;
if (count === 1 || !count) {
removed = new Array(1);
removed[0] = this.removeOne(i);
return removed;
}
if (i === 0 && i + count >= size) {
removed = this.toArray();
this.clear();
return removed;
}
if (i + count > size) count = size - i;
var k;
removed = new Array(count);
for (k = 0; k < count; k++) {
removed[k] = this._list[(this._head + i + k) & this._capacityMask];
}
i = (this._head + i) & this._capacityMask;
if (index + count === size) {
this._tail = (this._tail - count + len) & this._capacityMask;
for (k = count; k > 0; k--) {
this._list[i = (i + 1 + len) & this._capacityMask] = void 0;
}
return removed;
}
if (index === 0) {
this._head = (this._head + count + len) & this._capacityMask;
for (k = count - 1; k > 0; k--) {
this._list[i = (i + 1 + len) & this._capacityMask] = void 0;
}
return removed;
}
if (i < size / 2) {
this._head = (this._head + index + count + len) & this._capacityMask;
for (k = index; k > 0; k--) {
this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]);
}
i = (this._head - 1 + len) & this._capacityMask;
while (del_count > 0) {
this._list[i = (i - 1 + len) & this._capacityMask] = void 0;
del_count--;
}
if (index < 0) this._tail = i;
} else {
this._tail = i;
i = (i + count + len) & this._capacityMask;
for (k = size - (count + index); k > 0; k--) {
this.push(this._list[i++]);
}
i = this._tail;
while (del_count > 0) {
this._list[i = (i + 1 + len) & this._capacityMask] = void 0;
del_count--;
}
}
if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray();
return removed;
};
/**
* Native splice implementation.
* Remove number of items from the specified index from the list and/or add new elements.
* Returns array of removed items or empty array if count == 0.
* Returns undefined if the list is empty.
*
* @param index
* @param count
* @param {...*} [elements]
* @returns {array}
*/
Denque.prototype.splice = function splice(index, count) {
var i = index;
// expect a number or return undefined
if ((i !== (i | 0))) {
return void 0;
}
var size = this.size();
if (i < 0) i += size;
if (i > size) return void 0;
if (arguments.length > 2) {
var k;
var temp;
var removed;
var arg_len = arguments.length;
var len = this._list.length;
var arguments_index = 2;
if (!size || i < size / 2) {
temp = new Array(i);
for (k = 0; k < i; k++) {
temp[k] = this._list[(this._head + k) & this._capacityMask];
}
if (count === 0) {
removed = [];
if (i > 0) {
this._head = (this._head + i + len) & this._capacityMask;
}
} else {
removed = this.remove(i, count);
this._head = (this._head + i + len) & this._capacityMask;
}
while (arg_len > arguments_index) {
this.unshift(arguments[--arg_len]);
}
for (k = i; k > 0; k--) {
this.unshift(temp[k - 1]);
}
} else {
temp = new Array(size - (i + count));
var leng = temp.length;
for (k = 0; k < leng; k++) {
temp[k] = this._list[(this._head + i + count + k) & this._capacityMask];
}
if (count === 0) {
removed = [];
if (i != size) {
this._tail = (this._head + i + len) & this._capacityMask;
}
} else {
removed = this.remove(i, count);
this._tail = (this._tail - leng + len) & this._capacityMask;
}
while (arguments_index < arg_len) {
this.push(arguments[arguments_index++]);
}
for (k = 0; k < leng; k++) {
this.push(temp[k]);
}
}
return removed;
} else {
return this.remove(i, count);
}
};
/**
* Soft clear - does not reset capacity.
*/
Denque.prototype.clear = function clear() {
this._head = 0;
this._tail = 0;
};
/**
* Returns true or false whether the list is empty.
* @returns {boolean}
*/
Denque.prototype.isEmpty = function isEmpty() {
return this._head === this._tail;
};
/**
* Returns an array of all queue items.
* @returns {Array}
*/
Denque.prototype.toArray = function toArray() {
return this._copyArray(false);
};
/**
* -------------
* INTERNALS
* -------------
*/
/**
* Fills the queue with items from an array
* For use in the constructor
* @param array
* @private
*/
Denque.prototype._fromArray = function _fromArray(array) {
for (var i = 0; i < array.length; i++) this.push(array[i]);
};
/**
*
* @param fullCopy
* @returns {Array}
* @private
*/
Denque.prototype._copyArray = function _copyArray(fullCopy) {
var newArray = [];
var list = this._list;
var len = list.length;
var i;
if (fullCopy || this._head > this._tail) {
for (i = this._head; i < len; i++) newArray.push(list[i]);
for (i = 0; i < this._tail; i++) newArray.push(list[i]);
} else {
for (i = this._head; i < this._tail; i++) newArray.push(list[i]);
}
return newArray;
};
/**
* Grows the internal list array.
* @private
*/
Denque.prototype._growArray = function _growArray() {
if (this._head) {
// copy existing data, head to end, then beginning to tail.
this._list = this._copyArray(true);
this._head = 0;
}
// head is at 0 and array is now full, safe to extend
this._tail = this._list.length;
this._list.length <<= 1;
this._capacityMask = (this._capacityMask << 1) | 1;
};
/**
* Shrinks the internal list array.
* @private
*/
Denque.prototype._shrinkArray = function _shrinkArray() {
this._list.length >>>= 1;
this._capacityMask >>>= 1;
};
module.exports = Denque;
|
pVelocity/pvserverhelper
|
node_modules/denque/index.js
|
JavaScript
|
isc
| 11,542
|
angular.module( 'smartHousing' ).controller( 'signinCtrl', function( $scope, $rootScope, auth, $location ){
$scope.signin = function ( user ){
auth.signin( user )
.success( function ( response ){
$rootScope.$broadcast( 'userLogged', response );
$location.path( '/home' );
})
.error( function ( response ){
$rootScope.$broadcast( 'errorMessage', response.errmsg );
console.log( response );
});
}
});
|
lcnascimento/smart-housing
|
web/app/js/controllers/signinCtrl.js
|
JavaScript
|
mit
| 539
|
var should = require('should')
var Store = require('../../../lib/store')
describe('LDAP Client: Exec', function() {
var store
before(function() {
store = new Store({
type: 'ldap',
url: 'ldap://0.0.0.0:1389',
base: 'dc=test',
user: 'cn=root',
password: 'secret',
autoSave: true
})
store.Model('User', function() {
this.attribute('username')
})
store.Model('Ou', function() {
this.rdnPrefix('ou')
})
})
it('get all user objects of the root ou', function() {
return store.ready(function() {
var User = store.Model('User')
return User.recursive(false).exec(function(users) {
users.length.should.be.equal(2)
})
})
})
it('user object has standard attributes', function() {
return store.ready(function() {
var User = store.Model('User')
return User.recursive(false).exec(function(users) {
var user = users[0]
user.dn.should.endWith('dc=test')
user.objectClass.should.be.eql(['user'])
})
})
})
it('get all user objects!', function() {
return store.ready(function() {
var User = store.Model('User')
return User.exec(function(users) {
users.length.should.be.above(4)
})
})
})
it('get all user objects of another ou', function() {
return store.ready(function() {
var User = store.Model('User')
return User.searchRoot('ou=others, dc=test').exec(function(users) {
users.length.should.be.equal(2)
})
})
})
it('do a find on a not existing user object', function() {
return store.ready(function() {
var User = store.Model('User')
return User.find('ou=others, dc=test').exec(function(user) {
should.not.exist(user)
})
})
})
})
|
PhilWaldmann/openrecord
|
test/ldap/client/exec-test.js
|
JavaScript
|
mit
| 1,805
|
/**
* This file/module contains all configuration for the build process.
*/
module.exports = {
/**
* The `build_dir` folder is where our projects are compiled during
* development and the `compile_dir` folder is where our app resides once it's
* completely built.
*/
build_dir: 'build',
compile_dir: 'bin',
/**
* This is a collection of file patterns that refer to our app code (the
* stuff in `src/`). These file paths are used in the configuration of
* build tasks. `js` is all project javascript, less tests. `ctpl` contains
* our reusable components' (`src/common`) template HTML files, while
* `atpl` contains the same, but for our app's code. `html` is just our
* main HTML file, `less` is our main stylesheet, `unit` contains our
* app's unit tests, `fixture` contains $http data fixtures, and `scenario`
* contains our app's e2e tests.
*/
app_files: {
js: [ 'src/**/*.js', '!src/**/*.spec.js', '!src/**/*.fixture.js', '!src/**/*.scenario.js' ],
jsunit: [ 'src/**/*.spec.js' ],
jsfixture: [ 'src/**/*.fixture.js' ],
jsscenario: [ 'src/**/*.scenario.js' ],
coffee: [ 'src/**/*.coffee', '!src/**/*.spec.coffee', '!src/**/*.fixture.coffee', '!src/**/*.scenario.coffee' ],
coffeeunit: [ 'src/**/*.spec.coffee' ],
coffeefixture: [ 'src/**/*.fixture.coffee' ],
coffeescenario: [ 'src/**/*.scenario.coffee' ],
atpl: [ 'src/app/**/*.tpl.html' ],
ctpl: [ 'src/common/**/*.tpl.html' ],
html: [ 'src/index.html' ],
less: ['src/less/app.less']
},
/**
* This is the same as `app_files`, except it contains patterns that
* reference vendor code (`vendor/`) that we need to place into the build
* process somewhere. While the `app_files` property ensures all
* standardized files are collected for compilation, it is the user's job
* to ensure non-standardized (i.e. vendor-related) files are handled
* appropriately in `vendor_files.js`.
*
* The `vendor_files.js` property holds files to be automatically
* concatenated and minified with our project source files.
*
* The `vendor_files.css` property holds any CSS files to be automatically
* included in our app.
*
* The `vendor_files.dev` property holds any JS files to be included for
* development only.
*
*/
vendor_files: {
js: [
'vendor/jquery/dist/jquery.min.js',
'vendor/bootstrap/dist/js/bootstrap.min.js',
'vendor/angular/angular.js',
'vendor/angular-ui-router/release/angular-ui-router.js',
'vendor/angular-sanitize/angular-sanitize.js',
'vendor/angular-translate/angular-translate.js',
'vendor/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
'vendor/angular-translate-storage-local/angular-translate-storage-local.js',
'vendor/angular-bootstrap/ui-bootstrap-tpls.min.js'
],
css: [
],
dev: [
'vendor/angular-mocks/angular-mocks.js'
]
}
};
|
ng-blog/ng-blog
|
build.config.js
|
JavaScript
|
mit
| 2,978
|
var AppRouter = Backbone.Router.extend({
routes:{
"appointments/:id":"show"
},
show: function(id){
console.log("heyo we're in show with id %d", +id);
}
});
Backbone.history.start({pushState:true});
var router = new AppRouter();
router.navigate("appointments/1",{trigger:true})
|
tonycaovn/AnatomyOfBackbone
|
level7/challenge4/application.js
|
JavaScript
|
mit
| 295
|
beforeEach(() => {
jest.resetModules();
});
afterEach(() => {
jest.resetModules();
});
function setupDummyJQueryForModal(callback) {
global.$ = global.jQuery = function dummyJQueryForModal(html) {
return {
_html: html,
html: function() {
return null;
},
eq: function(index) {
return this;
},
find: function(selector) {
return this;
},
click: function() {
},
appendTo: function(target) {
return this;
},
modal: function() {
expect(this._html).toBe(html);
callback(html);
}
}
}
}
test('BS3 is detected when modal version starts with 3', function() {
var Q = require("serenity-core").Q;
var passedHtml;
setupDummyJQueryForModal(function(html) {
passedHtml = html;
});
try {
global.$.fn = {
modal: {
Constructor: {
VERSION: '3.3.1'
}
}
}
Q.alert("hello");
expect(passedHtml).not.toBeNull();
var idx1 = passedHtml.indexOf('class="close"');
var idx2 = passedHtml.indexOf('<h5');
expect(idx1).toBeGreaterThan(-1);
expect(idx2).toBeGreaterThan(idx1);
}
finally {
delete global.$;
delete global.jQuery;
}
});
test('BS4 is detected when modal version does not exist', function() {
var Q = require("serenity-core").Q;
var passedHtml;
setupDummyJQueryForModal(function(html) {
passedHtml = html;
});
try {
global.$.fn = {
modal: {
}
}
Q.alert("hello");
expect(passedHtml).not.toBeNull();
var idx1 = passedHtml.indexOf('class="close"');
var idx2 = passedHtml.indexOf('<h5');
expect(idx1).toBeGreaterThan(-1);
expect(idx2).toBeGreaterThan(-1);
expect(idx1).toBeGreaterThan(idx2);
}
finally {
delete global.$;
delete global.fn;
}
});
test('BS4 is detected when modal version is something other than 3', function() {
var Q = require("serenity-core").Q;
var passedHtml;
setupDummyJQueryForModal(function(html) {
passedHtml = html;
});
try {
global.$.fn = {
modal: {
Constructor: {
VERSION: '4.1.0'
}
}
}
Q.alert("hello");
expect(passedHtml).not.toBeNull();
var idx1 = passedHtml.indexOf('class="close"');
var idx2 = passedHtml.indexOf('<h5');
expect(idx1).toBeGreaterThan(-1);
expect(idx2).toBeGreaterThan(-1);
expect(idx1).toBeGreaterThan(idx2);
}
finally {
delete global.$;
delete global.fn;
}
});
|
volkanceylan/Serenity
|
Serenity.Scripts/Tests/CoreLib/Q/Q.Dialogs-bs3-4-detection.test.js
|
JavaScript
|
mit
| 3,098
|
define( {
// EXTENSION.
EXTENSION_NAME: "SFTP Upload",
// MENUS
UPLOAD_MENU_NAME: "Postavi preko SFTP",
DOWNLOAD_MENU_NAME: "Preuzmi sa servera",
// GENERAL.
YES: "Da",
NO: "Ne",
OK: "U redu",
CANCEL: "Prekid",
UPLOAD: "Postavi",
SKIP: "Preskoci",
// TOOLBAR.
SERVER_SETUP: "Postavke servera",
UPLOAD_ALL: "Postavi sve",
SKIP_ALL: "Preskoci sve",
// SETTINGS DIALOG.
SETTINGS_DIALOG_TITLE: "SFTP Postavke",
SETTINGS_DIALOG_TYPE: "Vrsta",
SETTINGS_DIALOG_TYPE_FTP: "FTP",
SETTINGS_DIALOG_TYPE_SFTP: "SFTP(SSH)",
SETTINGS_DIALOG_HOST: "Host",
SETTINGS_DIALOG_PORT: "Port",
SETTINGS_DIALOG_USERNAME: "Korisnicko Ime",
SETTINGS_DIALOG_PASSWORD: "Lozinka",
SETTINGS_DIALOG_RSAMSG: "Lokacija RSA Kljuca",
SETTINGS_DIALOG_PATH: "Lokacija na serveru",
SETTINGS_UPLOAD_ON_SAVE: "Postavljanje prilikom spremanja"
} );
|
bigeyex/brackets-sftp-upload
|
nls/hr/Strings.js
|
JavaScript
|
mit
| 923
|
'use strict';
// See https://github.com/alexmingoia/koa-resource-router/
var Resource = require('koa-resource-router');
var bodyParser = require('koa-bodyparser');
var product = require('./controllers/product');
export default function(app) {
var router = app.router;
var auth = app.auth;
var products = new Resource('products', {
// GET /products
index: async function() {
await product.list(this);
},
// GET /products/new
new: async function() {
await product.get(this);
},
// POST /products
create: async function() {
await product.create(this);
},
// GET /products/:id
show: async function() {
await product.get(this);
},
// GET /products/:id/edit
edit: async function() {
await product.get(this);
},
// PUT /products/:id
update: async function() {
await product.update(this);
},
// DELETE /products/:id
destroy: async function() {
await product.close(this);
}
});
app.use(products.middleware());
app.use(bodyParser());
return app;
}
|
kristianmandrup/cartling
|
products/src/routes.js
|
JavaScript
|
mit
| 1,081
|
// import DS from 'ember-data';
// export default DS.FixtureAdapter.extend({
// });
export { default } from 'ember-data-fixture-adapter'
|
MichaelBoselowitz/chess
|
app/adapters/application.js
|
JavaScript
|
mit
| 139
|
'use strict';
/* global requirejs */
requirejs.config({
shim: {
},
paths: {
},
modules: [
{
name: 'main'
}
]
});
|
keobrien/Railay
|
www/modules/config.js
|
JavaScript
|
mit
| 127
|
var expect = require('chai').expect
, loaders = require('../..');
describe('jsr-loader:', function() {
it('should load command file', function(done) {
done();
})
});
|
freeformsystems/jsr-loader
|
test/spec/loader.js
|
JavaScript
|
mit
| 179
|
jQuery(document).on('click', '.triggerLink', function() {
document.getElementById(jQuery(this).find('a.actionLink').attr('id')).click();
});
jQuery(document).on('click', '.triggerClick:not( input, label)', function() {
document.getElementById(jQuery(this).find('.clickMe').attr('id')).click();
});
|
UKMNorge/UKMdelta
|
src/UKMNorge/DeltaBundle/Resources/public/js/triggerlink.js
|
JavaScript
|
mit
| 306
|
'use strict';
exports = module.exports = function(models) {
return {
profile: require('./profile')(models),
tool: require('./tool')(models),
directory: require('./directory')(models)
};
};
|
SIB-Colombia/cygnus
|
src/app/services/index.js
|
JavaScript
|
mit
| 198
|
/*
* XPath.js - Pure JavaScript implementation of XPath 2.0 parser and evaluator
*
* Copyright (c) 2012 Sergey Ilinsky
* Dual licensed under the MIT and GPL licenses.
*
*
*/
function cAdditiveExpr(oExpr) {
this.left = oExpr;
this.items = [];
};
cAdditiveExpr.prototype.left = null;
cAdditiveExpr.prototype.items = null;
//
var hAdditiveExpr_operators = {};
hAdditiveExpr_operators['+'] = function(oLeft, oRight, oContext) {
var sOperator = '',
bReverse = false;
if (fXSAnyAtomicType_isNumeric(oLeft)) {
if (fXSAnyAtomicType_isNumeric(oRight))
sOperator = "numeric-add";
}
else
if (oLeft instanceof cXSDate) {
if (oRight instanceof cXSYearMonthDuration)
sOperator = "add-yearMonthDuration-to-date";
else
if (oRight instanceof cXSDayTimeDuration)
sOperator = "add-dayTimeDuration-to-date";
}
else
if (oLeft instanceof cXSYearMonthDuration) {
if (oRight instanceof cXSDate) {
sOperator = "add-yearMonthDuration-to-date";
bReverse = true;
}
else
if (oRight instanceof cXSDateTime) {
sOperator = "add-yearMonthDuration-to-dateTime";
bReverse = true;
}
else
if (oRight instanceof cXSYearMonthDuration)
sOperator = "add-yearMonthDurations";
}
else
if (oLeft instanceof cXSDayTimeDuration) {
if (oRight instanceof cXSDate) {
sOperator = "add-dayTimeDuration-to-date";
bReverse = true;
}
else
if (oRight instanceof cXSTime) {
sOperator = "add-dayTimeDuration-to-time";
bReverse = true;
}
else
if (oRight instanceof cXSDateTime) {
sOperator = "add-dayTimeDuration-to-dateTime";
bReverse = true;
}
else
if (oRight instanceof cXSDayTimeDuration)
sOperator = "add-dayTimeDurations";
}
else
if (oLeft instanceof cXSTime) {
if (oRight instanceof cXSDayTimeDuration)
sOperator = "add-dayTimeDuration-to-time";
}
else
if (oLeft instanceof cXSDateTime) {
if (oRight instanceof cXSYearMonthDuration)
sOperator = "add-yearMonthDuration-to-dateTime";
else
if (oRight instanceof cXSDayTimeDuration)
sOperator = "add-dayTimeDuration-to-dateTime";
}
// Call operator function
if (sOperator)
return hStaticContext_operators[sOperator].call(oContext, bReverse ? oRight : oLeft, bReverse ? oLeft : oRight);
//
throw new cException("XPTY0004"
//->Debug
, "Arithmetic operator is not defined for provided arguments"
//<-Debug
); // Arithmetic operator is not defined for arguments of types ({type1}, {type2})
};
hAdditiveExpr_operators['-'] = function (oLeft, oRight, oContext) {
var sOperator = '';
if (fXSAnyAtomicType_isNumeric(oLeft)) {
if (fXSAnyAtomicType_isNumeric(oRight))
sOperator = "numeric-subtract";
}
else
if (oLeft instanceof cXSDate) {
if (oRight instanceof cXSDate)
sOperator = "subtract-dates";
else
if (oRight instanceof cXSYearMonthDuration)
sOperator = "subtract-yearMonthDuration-from-date";
else
if (oRight instanceof cXSDayTimeDuration)
sOperator = "subtract-dayTimeDuration-from-date";
}
else
if (oLeft instanceof cXSTime) {
if (oRight instanceof cXSTime)
sOperator = "subtract-times";
else
if (oRight instanceof cXSDayTimeDuration)
sOperator = "subtract-dayTimeDuration-from-time";
}
else
if (oLeft instanceof cXSDateTime) {
if (oRight instanceof cXSDateTime)
sOperator = "subtract-dateTimes";
else
if (oRight instanceof cXSYearMonthDuration)
sOperator = "subtract-yearMonthDuration-from-dateTime";
else
if (oRight instanceof cXSDayTimeDuration)
sOperator = "subtract-dayTimeDuration-from-dateTime";
}
else
if (oLeft instanceof cXSYearMonthDuration) {
if (oRight instanceof cXSYearMonthDuration)
sOperator = "subtract-yearMonthDurations";
}
else
if (oLeft instanceof cXSDayTimeDuration) {
if (oRight instanceof cXSDayTimeDuration)
sOperator = "subtract-dayTimeDurations";
}
// Call operator function
if (sOperator)
return hStaticContext_operators[sOperator].call(oContext, oLeft, oRight);
//
throw new cException("XPTY0004"
//->Debug
, "Arithmetic operator is not defined for provided arguments"
//<-Debug
); // Arithmetic operator is not defined for arguments of types ({type1}, {type2})
};
// Static members
function fAdditiveExpr_parse (oLexer, oStaticContext) {
var oExpr;
if (oLexer.eof() ||!(oExpr = fMultiplicativeExpr_parse(oLexer, oStaticContext)))
return;
if (!(oLexer.peek() in hAdditiveExpr_operators))
return oExpr;
// Additive expression
var oAdditiveExpr = new cAdditiveExpr(oExpr),
sOperator;
while ((sOperator = oLexer.peek()) in hAdditiveExpr_operators) {
oLexer.next();
if (oLexer.eof() ||!(oExpr = fMultiplicativeExpr_parse(oLexer, oStaticContext)))
throw new cException("XPST0003"
//->Debug
, "Expected second operand in additive expression"
//<-Debug
);
oAdditiveExpr.items.push([sOperator, oExpr]);
}
return oAdditiveExpr;
};
// Public members
cAdditiveExpr.prototype.evaluate = function (oContext) {
var oLeft = fFunction_sequence_atomize(this.left.evaluate(oContext), oContext);
if (!oLeft.length)
return [];
// Assert cardinality
fFunctionCall_assertSequenceCardinality(oContext, oLeft, '?'
//->Debug
, "first operand of '" + this.items[0][0] + "'"
//<-Debug
);
var vLeft = oLeft[0];
if (vLeft instanceof cXSUntypedAtomic)
vLeft = cXSDouble.cast(vLeft); // cast to xs:double
for (var nIndex = 0, nLength = this.items.length, oRight, vRight; nIndex < nLength; nIndex++) {
oRight = fFunction_sequence_atomize(this.items[nIndex][1].evaluate(oContext), oContext);
if (!oRight.length)
return [];
// Assert cardinality
fFunctionCall_assertSequenceCardinality(oContext, oRight, '?'
//->Debug
, "first operand of '" + this.items[nIndex][0] + "'"
//<-Debug
);
vRight = oRight[0];
if (vRight instanceof cXSUntypedAtomic)
vRight = cXSDouble.cast(vRight); // cast to xs:double
vLeft = hAdditiveExpr_operators[this.items[nIndex][0]](vLeft, vRight, oContext);
}
return [vLeft];
};
|
mezohe/glekitufa
|
ircbot/node_modules/jquery-xpath/src/xpath.js/src/expressions/arithmetic/AdditiveExpr.js
|
JavaScript
|
mit
| 6,132
|
Typograf.rule({
name: 'common/punctuation/exclamation',
index: 1150,
handler: function(text) {
return text
.replace(/(^|[^!])!{2}($|[^!])/, '$1!$2')
.replace(/(^|[^!])!{4}($|[^!])/, '$1!!!$2');
}
});
|
abusabir/typograf
|
src/rules/common/punctuation/exclamation.js
|
JavaScript
|
mit
| 248
|
x = [1, 2, 3,];
|
forivall/tacoscript
|
specs/core/base-literals/array/assign-array-literal-multi-trailing-comma/expected.t.js
|
JavaScript
|
mit
| 16
|
module.exports = {
/**
* Run these tasks when activating this migration. See
* https://github.com/sprtus/engineer for more information on
* Engineer tasks.
*/
up(engineer) {
// HTML field
engineer.web.fields.addXml(`
<Field
Type="HTML"
Name="TestHTMLField"
StaticName="TestHTMLField"
DisplayName="TestHTMLField"
Description="A test HTML field"
Group="_Test Site Fields"
RichText="TRUE"
RichTextMode="FullHtml"
Required="FALSE"
SourceID="http://schemas.microsoft.com/sharepoint/v3">
</Field>
`);
// Image field
engineer.web.fields.addXml(`
<Field
Type="Image"
Name="TestImageField"
StaticName="TestImageField"
DisplayName="TestImageField"
Description="A test Image field"
Group="_Test Site Fields"
RichText="TRUE"
RichTextMode="FullHtml"
Required="FALSE"
SourceID="http://schemas.microsoft.com/sharepoint/v3">
</Field>
`);
// Link field
engineer.web.fields.addXml(`
<Field
Type="Link"
Name="TestLinkField"
StaticName="TestLinkField"
DisplayName="TestLinkField"
Description="A test Link field"
Group="_Test Site Fields"
RichText="TRUE"
RichTextMode="ThemeHtml"
Required="FALSE"
SourceID="http://schemas.microsoft.com/sharepoint/v3">
</Field>
`);
// SummaryLinks field
engineer.web.fields.addXml(`
<Field
Type="SummaryLinks"
Name="TestSummaryLinksField"
StaticName="TestSummaryLinksField"
DisplayName="TestSummaryLinksField"
Description="A test SummaryLinks field"
Group="_Test Site Fields"
RichText="TRUE"
RichTextMode="FullHtml"
Required="FALSE"
SourceID="http://schemas.microsoft.com/sharepoint/v3">
</Field>
`);
},
/**
* Run these tasks when rolling back this migration. See
* https://github.com/sprtus/engineer for more information on
* Engineer tasks.
*/
down(engineer) {
// Delete fields
engineer.web.fields.getByTitle('TestHTMLField').delete();
engineer.web.fields.getByTitle('TestImageField').delete();
engineer.web.fields.getByTitle('TestLinkField').delete();
engineer.web.fields.getByTitle('TestSummaryLinksField').delete();
},
};
|
oldrivercreative/engineer
|
test/migrations/20171012203540-create-publishing-fields.js
|
JavaScript
|
mit
| 2,415
|
'use strict';
/**
* Module dependencies
*/
var path = require('path'),
config = require(path.resolve('./config/config'));
/**
* Orgs module init function.
*/
module.exports = function (app, db) {
};
|
shahthepro/ngowebapp
|
modules/orgs/server/config/orgs.server.config.js
|
JavaScript
|
mit
| 208
|
class toolsObject {
/**
* @syntax parseObject(srt)
* @param {String} srt
* @returns {Object | Boolean false}
*/
static parseObject(srt) {
try {
var obj = JSON.parse(srt);
if (obj === "" || !obj)
return false;
} catch (e) {
return false;
}
;
return obj;
}
};
export class natifStorage {
/**
* @syntax setObject(key,obj,type)
* @param {String} key
* @param {Object | Object Array || String } obj
* @param {String (optional)"{}"|"[]"} type
* @returns {Boolean}
*/
static setObject(key, obj, type) {
if (typeof key === "number")
key = key.toString();
switch (typeof obj) {
case "number":
obj = obj.toString();
case "string":
try {
var obj = JSON.parse(obj);
} catch (e) {
return false;
}
;
break;
case "object":
break;
default:
return false;
break;
}
if (typeof key === "string") {
switch (type) {
case "[]":
obj = Object.prototype.toString.call(obj) === "[object Array]" ? obj : [];
break;
case "{}":
obj = Object.prototype.toString.call(obj) === "[object Object]" || obj ? obj : {};
break;
default:
break;
}
try {
localStorage.setItem(key, JSON.stringify(obj));
return true;
} catch (e) {
return false;
}
} else
return false;
}
/**
* @syntax getObject(key,type)
* @param {String} key
* @param {String (optional)"{}"|"[]"} type
* @returns {Boolean}
*/
static getObject(key, type) {
if (typeof key === "number")
key = key.toString();
if (typeof key === "string") {
var obj;
var item = localStorage.getItem(key);
obj = toolsObject.parseObject(item);
if (obj === false) {
switch (Object.prototype.toString.call(item)) {
case "[object Array]":
obj = [];
break;
default:
obj = {};
break;
}
}
switch (type) {
case "[]":
obj = Object.prototype.toString.call(obj) === "[object Array]" ? obj : [];
break;
case "{}":
obj = Object.prototype.toString.call(obj) === "[object Object]" ? obj : {};
break;
default:
break;
}
return obj;
} else
return false;
}
}
|
gaetanV/javascript_libraries
|
src/natif/natifStorage.js
|
JavaScript
|
mit
| 3,065
|
'use strict';
(function(undefined) {
var clone = require('clone');
var validators = {
'*': function() {
return true;
},
'array': function(o) {
return o instanceof Array;
},
'function': function(o) {
return typeof o === 'function';
},
'hash': function(o) {
return Object.prototype.toString.call(o) === '[object Object]';
},
'string': function(o) {
return Object.prototype.toString.call(o) === '[object String]';
},
'number': function(o) {
return !(o === null || isNaN(o));
},
'p-number': function(o) {
return validators['number'](o) && o > 0;
},
'n-number': function(o) {
return validators['number'](o) && o < 0;
},
'nn-number': function(o) {
return validators['number'](o) && o >= 0;
},
'np-number': function(o) {
return validators['number'](o) && o <= 0;
},
'int': function(o) {
return o == parseInt(o);
},
'n-int': function(o) {
return o == parseInt(o) && o < 0;
},
'p-int': function(o) {
return o == parseInt(o) && o > 0;
},
'nn-int': function(o) {
return o == parseInt(o) && o >= 0;
},
'np-int': function(o) {
return o == parseInt(o) && o <= 0;
},
'decimal': function(o) {
return o == parseFloat(o);
},
'n-decimal': function(o) {
return o == parseFloat(o) && o < 0;
},
'p-decimal': function(o) {
return o == parseFloat(o) && o > 0;
},
'nn-decimal': function(o) {
return o == parseFloat(o) && o >= 0;
},
'np-decimal': function(o) {
return o == parseFloat(o) && o <= 0;
}
};
function getPcs(list) {
// possible configurations
var pcs = [];
pcs.push([]);
list.forEach(function(item) {
var _pcs = [];
pcs.forEach(function(pc, j) {
for (var i = 0; i < item.types.length; i++) _pcs.push(pc.slice());
});
_pcs.forEach(function(pc, i) {
var type = item.types[i % item.types.length];
pc.push({
__id: item.__id,
name: item.name,
type: type,
validator: validators[type]
});
});
if (item.optional) {
pcs = pcs.concat(_pcs);
} else {
pcs = _pcs;
}
});
return pcs;
}
function match(pcs, args) {
var res = [];
pcs.filter(function(pc) {
return pc.length === args.length;
}).forEach(function(pc) {
for (var i = 0; i < pc.length; i++)
if (!pc[i].validator(args[i]))
return;
res.push(pc);
});
return res;
}
function getDecree(list) {
var pcs = getPcs(list.map(function(item, i) {
item.__id = i;
if (!item.types) item.types = [item.type || '*'];
item.types = item.types.map(function(type) {
type = type.toLowerCase();
if (!validators[type]) throw Error('Unkown type ' + type);
return type;
});
return item;
}));
return function(args, success, error) {
args = Array.prototype.slice.call(args, 0);
var matchedPcs = match(pcs, args);
if (matchedPcs.length === 1) {
var mpc = matchedPcs[0];
var _args = [];
list.forEach(function(item) {
for (var i = 0; i < mpc.length; i++) {
if (mpc[i].__id === item.__id) {
_args.push(args[i]);
return;
}
}
_args.push(clone(item.default));
});
success.apply(null, _args);
} else if (matchedPcs.length === 0) {
var errs = [
"Unkown arguments configuration",
Array.prototype.slice.call(args, 0)
];
if (validators['function'](error)) return error(Error(errs));
throw Error(errs);
} else {
var errs = ["Arguments ambiguity"];
for (var i = 0; i < matchedPcs.length - 1; i++) {
var mpc1 = matchedPcs[i];
for (var j = i + 1; j < matchedPcs.length; j++) {
var mpc2 = matchedPcs[j];
for (var k = 0; k < mpc1.length; k++) {
if (mpc1[k].__id !== mpc2[k].__id &&
mpc1[k].validator(args[k]) === mpc2[k].validator(args[k])) {
var mpc1name = mpc1[k].name || "declaration " + mpc1[k].__id,
mpc2name = mpc2[k].name || "declaration " + mpc2[k].__id;
var err = "Argument " + k + " matches both " + mpc1name + " (" + mpc1[k].type + ") and " + mpc2name + " (" + mpc2[k].type + ")";
errs.push(err);
}
}
}
}
if (validators['function'](error)) return error(Error(errs));
throw Error(errs);
}
};
}
module.exports = getDecree;
})(void 0);
|
jBachalo/node_kinect
|
examples/color-feed-browser-lwip-hack/node_modules/lwip/node_modules/decree/index.js
|
JavaScript
|
mit
| 5,760
|
define([
'angular',
'app',
'lodash',
'require',
'components/panelmeta'
], function (angular, app, _, require, PanelMeta) {
'use strict';
var module = angular.module('grafana.panels.text', []);
app.useModule(module);
var converter;
module.controller('text', [
'$scope',
'templateSrv',
'$sce',
'panelSrv',
function ($scope, templateSrv, $sce, panelSrv) {
$scope.panelMeta = new PanelMeta({ description: 'A static text panel that can use plain text, markdown, or (sanitized) HTML' });
$scope.panelMeta.addEditorTab('Edit text', 'app/panels/text/editor.html');
// Set and populate defaults
var _d = {
title: 'default title',
mode: 'markdown',
content: '',
style: {}
};
_.defaults($scope.panel, _d);
$scope.init = function () {
panelSrv.init($scope);
$scope.ready = false;
$scope.$on('refresh', $scope.render);
$scope.render();
};
$scope.render = function () {
if ($scope.panel.mode === 'markdown') {
$scope.renderMarkdown($scope.panel.content);
} else if ($scope.panel.mode === 'html') {
$scope.updateContent($scope.panel.content);
} else if ($scope.panel.mode === 'text') {
$scope.renderText($scope.panel.content);
}
};
$scope.renderText = function (content) {
content = content.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<').replace(/\n/g, '<br/>');
$scope.updateContent(content);
};
$scope.renderMarkdown = function (content) {
var text = content.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<');
if (converter) {
$scope.updateContent(converter.makeHtml(text));
} else {
require(['./lib/showdown'], function (Showdown) {
converter = new Showdown.converter();
$scope.updateContent(converter.makeHtml(text));
});
}
};
$scope.updateContent = function (html) {
try {
$scope.content = $sce.trustAsHtml(templateSrv.replace(html));
} catch (e) {
console.log('Text panel error: ', e);
$scope.content = $sce.trustAsHtml(html);
}
if (!$scope.$$phase) {
$scope.$digest();
}
};
$scope.openEditor = function () {
};
$scope.init();
}
]);
});
|
mabotech/maboss
|
public/dashboard/tmp/app/panels/text/module.js
|
JavaScript
|
mit
| 2,442
|
version https://git-lfs.github.com/spec/v1
oid sha256:d3cdfdabbdb7e7b49f0ad530c69414a6ef491d041485f858eb30fc8e606d9ca3
size 1085
|
yogeshsaroya/new-cdnjs
|
ajax/libs/xregexp/2.0.0/matchrecursive.min.js
|
JavaScript
|
mit
| 129
|
function Character(x, y, drawx, drawy, width, height, speed, image)
{
this.x = x;
this.y = y;
this.drawx = drawx;
this.drawy = drawy;
this.width = width;
this.height = height;
this.speed = speed;
this.character = image;
this.Draw = function()
{
context.drawImage(this.character, this.drawx, this.drawy, 50, 50,
this.x, this.y, 50, 50);
};
this.Update = function()
{
if (player.x>this.x)
{
this.x+=this.speed;
this.drawx=0;
this.drawy=150;
}
else if (player.x<this.x)
{
this.x-=this.speed;
this.drawx=0;
this.drawy=100;
}
if (player.y>this.y)
{
this.y+=this.speed;
this.drawx=0;
this.drawy=0;
}
else if (player.y<this.y)
{
this.y-=this.speed;
this.drawx=0;
this.drawy=50;
}
};
}
|
tflovorn/Zombies
|
js/character.js
|
JavaScript
|
mit
| 1,009
|
/*jshint node:true*/
'use strict';
module.exports = function( env, appConfig ) {
// return { APP: {
// // Here you can pass flags/options to your application instance
// // when it is created
// ion {
// theme:'md';
// }
// }
// };
let theme = 'ios'; // auto: md; wp; ios
if ('ion' in appConfig) {
if(appConfig.ion.theme){
theme = appConfig.ion.theme;
}
}
return {
ion: {
theme:theme
}
};
};
|
aalasolutions/ember-ion
|
config/environment.js
|
JavaScript
|
mit
| 478
|
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/inherits";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
function _createForOfIteratorHelper(o) { if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) { var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var it, normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
import { YAMLSemanticError } from '../../errors';
import { toJSON as _toJSON } from '../../toJSON';
import { YAMLMap } from '../../schema/Map';
import { Pair } from '../../schema/Pair';
import { Scalar } from '../../schema/Scalar';
import { YAMLSeq } from '../../schema/Seq';
import { createPairs, parsePairs } from './pairs';
export var YAMLOMap = /*#__PURE__*/function (_YAMLSeq) {
_inherits(YAMLOMap, _YAMLSeq);
var _super = _createSuper(YAMLOMap);
function YAMLOMap() {
var _this;
_classCallCheck(this, YAMLOMap);
_this = _super.call(this);
_defineProperty(_assertThisInitialized(_this), "add", YAMLMap.prototype.add.bind(_assertThisInitialized(_this)));
_defineProperty(_assertThisInitialized(_this), "delete", YAMLMap.prototype.delete.bind(_assertThisInitialized(_this)));
_defineProperty(_assertThisInitialized(_this), "get", YAMLMap.prototype.get.bind(_assertThisInitialized(_this)));
_defineProperty(_assertThisInitialized(_this), "has", YAMLMap.prototype.has.bind(_assertThisInitialized(_this)));
_defineProperty(_assertThisInitialized(_this), "set", YAMLMap.prototype.set.bind(_assertThisInitialized(_this)));
_this.tag = YAMLOMap.tag;
return _this;
}
_createClass(YAMLOMap, [{
key: "toJSON",
value: function toJSON(_, ctx) {
var map = new Map();
if (ctx && ctx.onCreate) ctx.onCreate(map);
var _iterator = _createForOfIteratorHelper(this.items),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var pair = _step.value;
var key = void 0,
value = void 0;
if (pair instanceof Pair) {
key = _toJSON(pair.key, '', ctx);
value = _toJSON(pair.value, key, ctx);
} else {
key = _toJSON(pair, '', ctx);
}
if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys');
map.set(key, value);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return map;
}
}]);
return YAMLOMap;
}(YAMLSeq);
_defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap');
function parseOMap(doc, cst) {
var pairs = parsePairs(doc, cst);
var seenKeys = [];
var _iterator2 = _createForOfIteratorHelper(pairs.items),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var key = _step2.value.key;
if (key instanceof Scalar) {
if (seenKeys.includes(key.value)) {
var msg = 'Ordered maps must not include duplicate keys';
throw new YAMLSemanticError(cst, msg);
} else {
seenKeys.push(key.value);
}
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return Object.assign(new YAMLOMap(), pairs);
}
function createOMap(schema, iterable, ctx) {
var pairs = createPairs(schema, iterable, ctx);
var omap = new YAMLOMap();
omap.items = pairs.items;
return omap;
}
export var omap = {
identify: function identify(value) {
return value instanceof Map;
},
nodeClass: YAMLOMap,
default: false,
tag: 'tag:yaml.org,2002:omap',
resolve: parseOMap,
createNode: createOMap
};
|
ealbertos/dotfiles
|
vscode.symlink/extensions/janne252.fontawesome-autocomplete-1.1.2/node_modules/yaml/browser/dist/tags/yaml-1.1/omap.js
|
JavaScript
|
mit
| 5,938
|
'use strict';
module.exports = {
options : {
layoutdir : '<%= paths.src %>/layouts',
partials : [
'<%= paths.src %>/partials/**/*.hbs'
],
data : [
'<%= paths.src %>/data/*.{json,yml}'
],
flatten : true
},
pages : {
src : [
'<%= paths.src %>/emails/*.hbs'
],
dest : '<%= paths.dist %>/'
}
};
|
binhqd/grunt-email-templates
|
grunt/options/assemble.js
|
JavaScript
|
mit
| 353
|
var coffee = require('coffee-react')
module.exports = {
process: function(src, path) {
if (path.match(/\.coffee/)) {
return coffee.compile(src, { bare: true })
}
return src
}
}
|
usirin/jest-utils
|
lib/preprocessors/coffee-react.js
|
JavaScript
|
mit
| 201
|
(function() {
var SETTINGS_GRAVITY = 0.07,
SETTINGS_FPS = 30,
SETTINGS_BALL_NUM = 1,
SETTINGS_BOUND_X = 0.13,
SETTINGS_BOUND_Y = 1.04,
SETTINGS_ACCELEROMETER_RELOAD_FREQ = 100,
SETTINGS_PADDLE_ACCEL = 2.8,
SETTINGS_POINT = 1000,
SETTINGS_POINT_SILVER = 200,
SETTINGS_POINT_GOLD = 3000000;
var GAMESTATE_STOP = 0,
GAMESTATE_PLAY = 1;
//var accelerationWatch = null;
var imgPath = {
'ball' : 'img/ball.png',
'paddle' : 'img/paddle.png',
'block_red' : 'img/block_red.png',
'block_green' : 'img/block_green.png',
'block_blue' : 'img/block_blue.png',
'block_silver' : 'img/block_silver.png',
'block_gold' : 'img/block_gold.png'
};
var BB = {
stage: new PIXI.Stage(0x000000),
renderer: null,
screenSize: null,
paddle: null,
balls: [],
blocks: [],
score: 0,
scoreLabel: null,
accelLabel: null,
isMouseDown: false,
// Create blocks map
setMap: function() {
var blockMap = [
[null, null, null, null, null, 'blue', null, null, null, null],
[null, null, null, null, 'red', 'red', 'blue', null, null, null],
[null, null, null, 'red', 'red', null, null, 'blue', null, null],
[null, null, 'red', 'red', null, null, null, null, 'blue', null],
[null, 'red', 'red', null, null, 'gold', null, null, 'silver', 'silver'],
[null, null, 'red', 'red', null, null, null, 'silver', 'silver', null],
[null, null, null, 'red', 'red', null, 'silver', 'silver', null, null],
[null, null, null, null, 'silver', 'silver', 'silver', null, null, null],
[null, null, null, null, null, 'silver', null, null, null, null]
];
for(j = 0; j < blockMap.length; j++) {
for(i = 0; i < blockMap[j].length; i++) {
if(blockMap[j][i] !== null) {
var block = BB.addBlock(10 + (30 * i), 80 + (12 * j), blockMap[j][i]);
}
}
}
},
/**
* @param {int} x
* @param {int} y
* @param {String} color red,blue,silver,gold
* @return {Object} block
**/
addBlock: function(x, y, color) {
switch (color) {
case "red":
case "blue":
var point = SETTINGS_POINT;
break;
case "silver":
var point = SETTINGS_POINT_SILVER;
break;
case "gold":
var point = SETTINGS_POINT_GOLD;
break;
default:
var point = SETTINGS_POINT;
color = "red";
break;
}
var texture = PIXI.Texture.fromImage(imgPath["block_" + color], false);
var block = new PIXI.Sprite(texture);
block.anchor.x = 0.5;
block.anchor.y = 0.5;
block.position.x = x;
block.position.y = y;
block.width = 30;
block.height = 12;
block.point = point;
BB.stage.addChild(block);
BB.blocks.push(block);
return block;
},
// Create a ball and add it to PIXI.Stage
addBall: function() {
var texture = PIXI.Texture.fromImage(imgPath["ball"], false);
var ball = new PIXI.Sprite(texture);
ball.anchor.x = 0.5;
ball.anchor.y = 0.5;
ball.position.x = parseInt(BB.renderer.width * 0.5);
ball.position.y = 200;
ball.width = 10;
ball.height = 10;
ball.delta = {
'x' : Math.random() - 0.5,
'y' : -0.4
};
BB.stage.addChild(ball);
BB.balls.push(ball);
},
// Create a paddle and add it to PIXI.Stage
addPaddle: function() {
var texture = PIXI.Texture.fromImage(imgPath["paddle"], false);
BB.paddle = new PIXI.Sprite(texture);
BB.paddle.anchor.x = 0.5;
BB.paddle.anchor.y = 0.5;
BB.paddle.position.x = parseInt(BB.renderer.width * 0.5);
BB.paddle.position.y = BB.renderer.height - 60;
BB.paddle.width = 60;
BB.paddle.height = 10;
BB.paddle.accel = 0;
BB.paddle.delta = {
'x' : Math.random() - 0.5,
'y' : -3.8
};
BB.stage.addChild(BB.paddle);
},
/**
* Add points to current score
* @param {int} val points to add
*/
addScore: function(val) {
BB.score += parseInt(val);
BB.scoreLabel.setText(BB.score);
},
/**
* Set score
* @param {int} val new score
*/
setScore: function(val) {
BB.score = val;
BB.scoreLabel.setText(BB.score);
},
/**
* callback for PhoneGap Acceleration Watch
* @param {Object} a a.x, a.y, a.z
*/
updateAcceleration: function(a) {
var accelText = "", ac = a.x.toFixed(2);
if(a.x > 0) accelText = '+' + String(ac);
else accelText = String(ac);
// Use parameter x to move paddle
if (BB.paddle !== null) {
if (BB.paddle.accel / ac > 2.0) {
} else if (BB.paddle.accel / ac > 0) {
BB.paddle.accel += ac * SETTINGS_PADDLE_ACCEL;
} else {
BB.paddle.accel = ac * SETTINGS_PADDLE_ACCEL;
}
}
BB.accelLabel.setText(accelText);
},
// Reset current game and start new one
reset: function() {
//Reset (remove all children in the stage if exists)
for (var i = BB.stage.children.length - 1; i >= 0; i--) {
BB.stage.removeChildAt(i);
}
BB.balls = [];
BB.blocks = [];
BB.setMap();
for (var i = 0; i < SETTINGS_BALL_NUM; i++) {
BB.addBall();
}
BB.addPaddle();
var resetLabel = new PIXI.Text("RESET", {font: "24px/1.2 vt", fill: "red"});
resetLabel.position.x = 18;
resetLabel.position.y = BB.renderer.height - 52;
BB.stage.addChild(resetLabel);
resetLabel.buttonMode = true;
resetLabel.interactive = true;
resetLabel.click = resetLabel.tap = function(data) {
BB.reset();
};
setTimeout(function() {
resetLabel.setText("RESET"); //for Android
}, 1000, resetLabel);
var rankingLabel = new PIXI.Text("RANKING", {font: "24px/1.2 vt", fill: "red"});
rankingLabel.position.x = 80;
rankingLabel.position.y = BB.renderer.height - 52;
BB.stage.addChild(rankingLabel);
rankingLabel.buttonMode = true;
rankingLabel.interactive = true;
rankingLabel.click = rankingLabel.tap = function(data) {
ncmbController.showRanking();
};
setTimeout(function() {
rankingLabel.setText("RANKING"); //for Android
}, 1000, rankingLabel);
var label = new PIXI.Text("SCORE:", {font: "24px/1.2 vt", fill: "red"});
label.position.x = 20;
label.position.y = 20;
BB.stage.addChild(label);
setTimeout(function() {
label.setText("SCORE:"); //for Android
}, 1000, label);
BB.scoreLabel = new PIXI.Text("0", {font: "24px/1.2 vt", fill: "white"});
BB.scoreLabel.position.x = 90;
BB.scoreLabel.position.y = 20;
BB.stage.addChild(BB.scoreLabel);
BB.setScore(0);
/*
var label = new PIXI.Text("ACCEL:", {font: "24px/1.2 vt", fill: "red"});
label.position.x = 160;
label.position.y = 20;
BB.stage.addChild(label);
label.setText("ACCEL:"); //for Android
BB.accelLabel = new PIXI.Text("0", {font: "24px/1.2 vt", fill: "white"});
BB.accelLabel.position.x = 230;
BB.accelLabel.position.y = 20;
BB.stage.addChild(BB.accelLabel);
*/
BB.gameState = GAMESTATE_PLAY;
},
/**
* Check whether the ball hits the object
* @param {PIXI.Sprite} ball
* @param {PIXI.Sprite} obj target object
*/
isBallHit: function(ball, obj) {
return (ball.position.x > (obj.position.x - (obj.width * 0.5))) &&
(ball.position.x < (obj.position.x + (obj.width * 0.5))) &&
(ball.position.y > (obj.position.y - (obj.height * 0.5))) &&
(ball.position.y < (obj.position.y + (obj.height * 0.5)));
},
// Game Over
endGame: function() {
BB.gameState = GAMESTATE_STOP;
vibrate();
ncmbController.sendScore(BB.score);
},
// Game Clear
clearGame: function() {
// if(typeof navigator.notification !== 'undefined') navigator.notification.alert("Cleared!", function(){}, "Congraturations");
// else alert("Cleared!");
BB.gameState = GAMESTATE_STOP;
ncmbController.sendScore(BB.score);
}
}
function init() {
// Accelerometer
/*
if (typeof navigator.accelerometer !== 'undefined' && !accelerationWatch) {
accelerationWatch = navigator.accelerometer.watchAcceleration(
BB.updateAcceleration,
function(ex) {
alert("accel fail (" + ex.name + ": " + ex.message + ")");
},
{frequency: SETTINGS_ACCELEROMETER_RELOAD_FREQ}
);
}
*/
BB.screenSize = setBound();
ncmbController.init();
BB.renderer = (getUa() === "Android") ? new PIXI.CanvasRenderer(BB.screenSize.width, BB.screenSize.height) : new PIXI.autoDetectRenderer(BB.screenSize.width, BB.screenSize.height),
BB.renderer.transparent = false;
document.body.appendChild(BB.renderer.view);
setScale(BB.screenSize);
BB.reset();
// Event listeners to control the paddle
window.addEventListener("touchmove", function(e) {
BB.paddle.position.x = e.touches[0].clientX / BB.screenSize.zoom;
});
window.addEventListener("mousedown", function(e) {
BB.isMouseDown = true;
});
window.addEventListener("mouseup", function(e) {
BB.isMouseDown = false;
});
window.addEventListener("mousemove", function(e) {
if(BB.isMouseDown) BB.paddle.position.x = e.clientX;
});
window.addEventListener("keydown", function(e) {
switch (e.which) {
case 37:
BB.paddle.position.x -= 4;
BB.paddle.accel += (SETTINGS_PADDLE_ACCEL * 0.1);
break;
case 39:
BB.paddle.position.x += 4;
BB.paddle.accel -= (SETTINGS_PADDLE_ACCEL * 0.1);
break;
case 38:
BB.paddle.position.y -= 1;
break;
}
});
requestAnimFrame(animate);
}
// Render callback
function animate() {
if (BB.gameState === GAMESTATE_PLAY) {
//Move the paddle
BB.paddle.position.x -= BB.paddle.accel;
if (BB.paddle.position.x - (BB.paddle.width * 0.5) < 0) {
BB.paddle.position.x = BB.paddle.width * 0.5;
BB.paddle.accel = 0;
} else if (BB.paddle.position.x + (BB.paddle.width * 0.5) > BB.renderer.width) {
BB.paddle.position.x = BB.renderer.width - (BB.paddle.width * 0.5);
BB.paddle.accel = 0;
}
//Move balls
for (var i = BB.balls.length - 1; i >= 0; i--) {
var ball = BB.balls[i];
ball.position.x += ball.delta.x;
if ((ball.position.x > BB.renderer.width) || (ball.position.x < 0)) {
ball.delta.x *= -1;
}
ball.delta.y += SETTINGS_GRAVITY;
ball.y += ball.delta.y;
if (ball.y < 0) {
ball.y = 0;
ball.delta.y *= -1;
} else if (ball.y > BB.renderer.height + 40) {
BB.stage.removeChild(ball);
BB.balls.splice(i, 1);
if (BB.balls.length <= 0) {
BB.endGame();
}
continue;
}
// Ball&Paddle hit detection
if (BB.isBallHit(ball, BB.paddle)) {
ball.delta.x += -1 * SETTINGS_BOUND_X * (BB.paddle.position.x - ball.position.x);
ball.delta.y *= -1 * SETTINGS_BOUND_Y;
}
//Ball&blocks hit detection
for(var j = BB.blocks.length - 1; j >= 0; j--) {
var block = BB.blocks[j];
if(BB.isBallHit(ball, block)) {
BB.addScore(block.point);
ball.delta.y *= -1;
if ((ball.position.x < 4 + block.position.x - (block.width * 0.5)) || (ball.position.x > -4 + block.position.x + (block.width * 0.5))) {
ball.delta.x *= -1; //ball hits side of the block
}
BB.stage.removeChild(block);
BB.blocks.splice(j, 1);
if (BB.blocks.length <= 0) {
BB.clearGame();
}
}
}
}
}
requestAnimFrame(animate);
BB.renderer.render(BB.stage);
}
window.onload = function() {
if(getUa() === false) init();
else document.addEventListener("deviceready", init, false);
}
function setScale(bound) {
switch (getUa()) {
case "Android":
case "iPad":
case "iPhone":
document.getElementsByTagName("canvas")[0].style["-webkit-transform"] = "scale(" + bound.zoom + "," + bound.zoom + ")";
break;
default:
break;
}
return bound;
}
function setBound() {
var bound = {
width: 320,
height: 460,
zoom: 1
};
switch (getUa()) {
case "Android":
case "iPad":
case "iPhone":
bound.height = screen.availHeight * (bound.width / screen.availWidth);
bound.zoom = screen.availWidth / bound.width;
break;
default:
bound.height = window.innerHeight;
break;
}
return bound;
}
function vibrate(duration) {
if (typeof duration === 'undefined') duration = 500;
if (typeof navigator.notification !== 'undefined') navigator.notification.vibrate(duration);
}
function getUa() {
if ((navigator.userAgent.indexOf('iPhone') > 0 && navigator.userAgent.indexOf('iPad') == -1) || navigator.userAgent.indexOf('iPod') > 0 ) {
return 'iPhone';
} else if(navigator.userAgent.indexOf('iPad') > 0) {
return 'iPad';
} else if(navigator.userAgent.indexOf('Android') > 0) {
return 'Android';
} else return false;
}
})();
|
NIFTYCloud-mbaas/brakeout_ranking
|
www/js/main.js
|
JavaScript
|
mit
| 15,289
|
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
var dotenv = require('dotenv');
dotenv.load();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.post('/save', routes.save);
app.get('/viewcard/:id', routes.viewcard);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
//set email function. will be called when the database check() function is ran which will check
//the database to see if any cards need to be sent
function email(to, from, name, message, id) {
//send to card receipient
var sendgrid = require('sendgrid')(process.env.SENDGRID_USERNAME, process.env.SENDGRID_PASSWORD);
sendgrid.send({
to: to,
from: 'ecards@imkev.in',
subject: from + ' has sent you an eCard',
text: message + ' \n \n \n View your card online at: ' + process.env.BASE_URL + '/viewcard/'+id
}, function(success, message) {
if (!success) {
console.log(message);
}
})
//send to card creator to let them know it's been delivered
sendgrid.send({
to: from,
from: 'ecards@imkev.in',
subject: 'Your eCard has been delivered to ' + to,
text: 'Here\'s what they received: \n \n' + message + ' \n \n \n View your card online at: ' + process.env.BASE_URL + '/viewcard/'+id
}, function(success, message) {
if (!success) {
console.log(message);
}
})
}
//checks to see if there's any new cards to send. Main function of app.
function check() {
var date = new Date;
var currentMonth = date.getMonth()+1;
var currentDay = date.getDate();
var currentYear = date.getYear();
var today = currentMonth+'/'+currentDay; //sets today to day/month
var uristring =
process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
process.env.MONGODB_NAME;
var mongoose = require('mongoose');
var db = mongoose.createConnection(uristring);
console.log('Checking for entries that haven\'t been sent. \n || Time: ' + date.getHours() + ':' + date.getMinutes() + ' \n || date || ' + currentMonth +'/'+currentDay + ' \n || --------------------------');
db.once('open', function() {
var greetingSchema = new mongoose.Schema({
toName: String,
toEmail: String,
toSend: String,
fromName: String,
fromEmail: String,
message: String,
cardType: String,
sent: Boolean
});
var Greeting = db.model('Greeting', greetingSchema);
//loops through the database to see if any cards need to be sent today. If so, it will send them and change the sent flag in the to true
Greeting.find(function(err, greeting){
for(i = 0; i<greeting.length; i++) {
if (String(greeting[i].toSend) == String(today) && greeting[i].sent == false) {
//if a card has been found with today's date and hasn't been sent, it will send it and update the flag parameter to true, bypassing it in the future.
email(greeting[i].toEmail, greeting[i].fromEmail, greeting[i].toName, greeting[i].message, greeting[i].id);
var query = { sent: 'false', toSend: greeting[i].toSend }; //query param for db updating
Greeting.update(query, { sent: 'true' }, function(err, res) {
})
}
}
});
}); //db connection
mongoose.connection.close()
};
//will run check() every so often // what the minutes variable is set to
var minutes = 1.3, the_interval = minutes * 60 * 1000;
console.log('Checking for new messages every: ' + minutes + ' minutes');
setInterval(function() {
check();
}, the_interval);
|
kevinchandler/eCards
|
app.js
|
JavaScript
|
mit
| 4,092
|
const webpack = require('webpack');
const path = require('path');
const os = require('os');
const DashboardPlugin = require('webpack-dashboard/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const autoprefixer = require('autoprefixer');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const OfflinePlugin = require('offline-plugin');
const nodeEnv = process.env.NODE_ENV || 'development';
const isProduction = nodeEnv === 'production';
const jsSourcePath = path.join(__dirname, './frontend');
const buildPath = path.join(__dirname, './public');
const imgPath = path.join(__dirname, './frontend/assets/img');
const iconPath = path.join(__dirname, './source/assets/icons');
const sourcePath = path.join(__dirname, './frontend');
const isWin = os.platform() === 'win32';
const globalLessPath = isWin
? /frontend\\less/
: new RegExp(path.join('frontend', 'less'));
function createWebpackConfig(name, entryName, outputName) {
// Common plugins
const plugins = [
//new BundleAnalyzerPlugin(),
new CleanWebpackPlugin([buildPath]),
new CopyWebpackPlugin([
{from: imgPath + '/logo.ico', to: buildPath + '/logo.ico'},
{from: jsSourcePath + '/manifest.json', to: buildPath + '/manifest.json'}
]),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'assets/js/vendor-[hash].js',
minChunks(module) {
const context = module.context;
return context && context.indexOf('node_modules') >= 0;
},
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv),
},
}),
new webpack.NamedModulesPlugin(),
new HtmlWebpackPlugin({
template: path.join(sourcePath, 'index.html'),
path: buildPath,
filename: name + '.html'
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer({
browsers: [
'last 3 version',
'ie >= 10',
],
}),
],
context: sourcePath,
},
})
];
// Common rules
const rules = [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, './frontend'),
path.resolve(__dirname, './node_modules/url-regex'),
path.resolve(__dirname, './node_modules/react-proptypes-url-validator')
],
use: {
loader: 'babel-loader',
options: {
cacheDirectory: path.join(__dirname, './tmp/cache/webpack')
}
}
},
{
test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader?name=assets/fonts/[name].[ext]'
},
{
test: /\.(png|gif|jpg|svg)$/,
// include: imgPath,
loader: 'file-loader?name=assets/img/[name].[ext]'
}
];
const extractVendorsCss = new ExtractTextPlugin('style-vendors-[hash].css');
const extractCss = new ExtractTextPlugin('style-[hash].css');
if (isProduction) {
// Production plugins
plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
},
parallel: {
cache: path.join(__dirname, './tmp/cache/webpack/uglify'),
workers: 4
},
output: {
comments: false,
}
}),
extractVendorsCss,
extractCss
);
rules.push(
{
test: /\.css$/,
use: extractVendorsCss.extract({
use: [
{
loader: 'cache-loader',
options: {
cacheDirectory: path.join(__dirname, '../../tmp/cache/webpack/css')
}
},
'css-loader?minimize',
'postcss-loader'
],
fallback: 'style-loader'
})
},
{
test: /\.less$/,
include: globalLessPath,
use: extractCss.extract({
use: [
{
loader: 'cache-loader',
options: {
cacheDirectory: path.join(__dirname, '../../tmp/cache/webpack/less')
}
},
'css-loader?minimize',
'postcss-loader',
'less-loader'
],
fallback: 'style-loader'
})
},
{
test: /\.less$/,
exclude: globalLessPath,
use: extractCss.extract({
use: [
{
loader: 'cache-loader',
options: {
cacheDirectory: path.join(__dirname, '../../tmp/cache/webpack/less-global')
}
},
'css-loader?modules,minimize,localIdentName="[hash:base64:6]"',
'postcss-loader',
'less-loader'
],
fallback: 'style-loader'
})
}
);
} else {
// Development plugins
plugins.push(
new webpack.HotModuleReplacementPlugin(),
new DashboardPlugin()
);
// Development rules
rules.push(
{
test: /\.css$/,
loader: [
{
loader: 'cache-loader',
options: {
cacheDirectory: path.join(__dirname, '../../tmp/cache/webpack/dev-css')
}
},
'style-loader',
'css-loader'
]
},
{
test: /\.less$/,
include: globalLessPath,
loader: [
{
loader: 'cache-loader',
options: {
cacheDirectory: path.join(__dirname, '../../tmp/cache/webpack/dev-less')
}
},
'style-loader',
'css-loader',
'less-loader'
]
},
{
test: /\.less$/,
exclude: globalLessPath,
loader: [
{
loader: 'cache-loader',
options: {
cacheDirectory: path.join(__dirname, '../../tmp/cache/webpack/dev-less-global')
}
},
'style-loader',
'css-loader?modules&importLoaders=1'
+ '&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
'less-loader'
]
}
);
}
if (isProduction && name === 'index') {
plugins.push(new OfflinePlugin({
ServiceWorker: {
events: true
},
AppCache: {
events: true
}
}));
}
return {
name: name,
devtool: isProduction ? false : 'source-map',
context: jsSourcePath,
entry: {
js: [entryName + '.js'],
},
output: {
path: buildPath,
publicPath: '/',
filename: `assets/js/${outputName}-[hash].js`,
},
module: {
rules,
},
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.js'],
modules: [
path.resolve(__dirname, 'node_modules'),
jsSourcePath,
],
},
plugins,
devServer: {
contentBase: isProduction ? buildPath : sourcePath,
historyApiFallback: true,
port: 3003,
compress: isProduction,
inline: !isProduction,
hot: !isProduction,
host: '0.0.0.0'
}
};
}
// module.exports = createWebpackConfig('index', './admin', 'admin');
// module.exports = createWebpackConfig('index', './app', 'app');
module.exports = [
createWebpackConfig('index', './app', 'app'),
createWebpackConfig('admin', './admin', 'admin')
];
|
apostolidhs/wiregoose
|
webpack.config.js
|
JavaScript
|
mit
| 7,775
|
/* TODO! Make JS refactoring to make code more modular */
function Renderer(parameters) {
var innerContent = parameters.content;
function renderTranslate() {
return showTranslationMode(innerContent);
}
function renderPlay() {
return showPlayMode(innerContent);
}
return {
renderTranslateMode: renderTranslate,
renderPlayMode: renderPlay
};
}
function PageRenderer() {
// Header
function drawHeader(content) {
if (content === undefined) {
return;
}
var translation_title = $('#translation-title');
if (content.length > 1) {
translation_title.removeClass('invisible');
}
else {
translation_title.addClass('invisible');
}
}
function eraseHeader() {
var translation_title = $('#translation-title');
translation_title.addClass('invisible');
}
// Body
function eraseBody() {
var translation_choice = $("#translation-choice");
translation_choice.empty();
translation_choice.remove(".space1percent");
}
// eraseAll
function eraseAll() {
eraseHeader();
eraseBody();
}
// Loader
function drawLoader() {
$('.translation-loader').removeClass('hidden');
}
function eraseLoader() {
$('.translation-loader').addClass('hidden');
}
return {
header: {
draw: drawHeader,
erase: eraseHeader
},
body: {
erase: eraseBody
},
page: {
erase: eraseAll
},
loader: {
draw: drawLoader,
erase: eraseLoader
}
};
}
function PlayModeRenderer() {
var pageRenderer = new PageRenderer();
function drawBody(content) {
/*TODO Implement it*/
}
function drawPage(content) {
pageRenderer.header.draw(content);
drawBody(content);
}
return {
page: {
draw: drawPage,
erase: pageRenderer.page.erase
}
};
}
// TODO: Implement!
function TranslateModeRenderer() {
var pageRenderer = new PageRenderer();
function drawVisualization() {
/*TODO Implement it*/
}
function drawBody(content) {
/*TODO Implement it*/
}
/*TODO Think about it more rigorously*/
function drawPage(paramaters) {
var content = paramaters.content;
pageRenderer.header.draw(content);
// TODO Change these methods to non-dummy one
drawBody(content);
drawVisualization();
}
return {
page: {
draw: drawPage,
erase: pageRenderer.page.erase
}
};
}
function TranslationsFormatter(parameters) {
var innerContent = parameters.content;
function Formatter(parameters) {
var innerContent = parameters.content;
function swap(parameters) {
var index1 = parameters.index1,
index2 = parameters.index2;
if (innerContent.hasOwnProperty(index1) && innerContent.hasOwnProperty(index2)) {
var temp = innerContent[index1];
innerContent[index1] = innerContent[index2];
innerContent[index2] = temp;
}
}
function filterEmpty() {
var cleanedContent = [];
for (var prop in innerContent) {
if (innerContent.hasOwnProperty(prop) &&
innerContent[prop].hasOwnProperty('translation') &&
innerContent[prop]['translation'] !== "") {
cleanedContent.push(innerContent[prop]);
}
}
innerContent = cleanedContent;
}
function shuffleTranslations() {
var NUM_SWAPS = 10;
for (var num_swap = 0; num_swap < NUM_SWAPS; ++num_swap) {
var index1 = Math.floor(Math.random() * innerContent.length),
index2 = Math.floor(Math.random() * innerContent.length);
swap({index1: index1, index2: index2});
}
}
function getContent() {
return innerContent;
}
return {
filter: filterEmpty,
shuffle: shuffleTranslations,
get: getContent
}
}
function formatContent() {
var formatter = new Formatter({content: innerContent});
formatter.shuffle();
formatter.filter();
return formatter.get();
}
return {
format: formatContent
};
}
function ImagePathGenerator() {
/**
* @return {string}
*/
function generateImagePath(parameters) {
var company = (parameters.company === undefined) ? "" : parameters.company,
color = (parameters.color === undefined) ? "" : "_" + parameters.color;
var IMAGE_PATH = "/static/image/",
IMAGE_EXTENSION = ".png",
DEFAULT_IMAGE_NAME = "question_mark",
AVAILABLE_TRANSLATORS = ["google", "tilde", "ut"];
for (var prop in AVAILABLE_TRANSLATORS) {
if (AVAILABLE_TRANSLATORS.hasOwnProperty(prop) && company === AVAILABLE_TRANSLATORS[prop]) {
return IMAGE_PATH + company + color + IMAGE_EXTENSION;
}
}
return IMAGE_PATH + DEFAULT_IMAGE_NAME + IMAGE_EXTENSION;
}
return {
generate: generateImagePath
};
}
function ContentGenerator(parameters) {
var innerContent = parameters.content;
var imagePathGenerator = new ImagePathGenerator();
function generateTranslationRows() {
for (var prop in innerContent) {
if (innerContent.hasOwnProperty(prop)) {
generateTranslationRow(prop);
}
}
}
function generateTranslationRow(prop) {
var imagePath = ((innerContent.length > 1) ?
imagePathGenerator.generate({}) :
imagePathGenerator.generate({company: innerContent[prop]['translator']}));
var parameters = {
imagePath: imagePath,
translationText: innerContent[prop]['translation']
};
generateTranslationRowAsHTML(parameters);
}
function generateTranslationRowAsHTML(parameters) {
var imagePath = parameters.imagePath,
translationText = parameters.translationText,
additionalClass = parameters.additionalClass === undefined ? "" : parameters.additionalClass;
CreateTranslationRow(imagePath, translationText, additionalClass);
}
return {
generate: generateTranslationRows
};
}
/*TODO Refactor this function*/
function CreateTranslationRow(image_path, translation_text, extra_class) {
var translation_div = document.createElement('div'),
image_div = $(document.createElement('div')).addClass("col-lg-1 col-md-1 col-sm-1 col-xs-1 container-img" +
" pointer"),
text_div = $(document.createElement('div')).addClass("col-lg-offset-1 col-lg-11" +
" col-md-offset-1 col-md-11" +
" col-sm-offset-1 col-sm-11" +
" col-xs-offset-1 col-xs-11" +
" translation-text pointer container-text" + " " + extra_class),
image = $(document.createElement('img')).addClass("img-responsive"); // icon-max-size
if ($.inArray("google", image_path)) {
image.addClass("google-size");
}
// Add image + translation
$(translation_div).addClass("row margin-left-10px");
$(image).attr("src", image_path);
$(text_div).text(translation_text);
$(image).appendTo(image_div);
$(translation_div).append(image_div);
$(translation_div).append(text_div);
var translation_choice = $("#translation-choice");
translation_choice.append(translation_div);
// Add space
var space_div = document.createElement('div');
$(space_div).addClass("space7percent");
translation_choice.append(space_div);
}
function showPlayMode(content) {
var renderer = new PlayModeRenderer();
renderer.page.erase();
var formatter = new TranslationsFormatter({content: content});
content = formatter.format();
renderer.page.draw(content);
var contentGenerator = new ContentGenerator({content: content});
contentGenerator.generate();
return content;
}
function showTranslationMode(content) {
var renderer = new TranslateModeRenderer();
renderer.page.erase();
var formatter = new TranslationsFormatter({content: content});
content = formatter.format();
renderer.page.draw(content);
var contentGenerator = new ContentGenerator({content: content});
contentGenerator.generate();
return content;
}
/*TODO Refactor this code and adapt to modular architecture*/
function ShowTranslatorsBasedOnTranslation(content, position) {
var pageRenderer = new PageRenderer();
pageRenderer.page.erase();
var imagePathGenerator = new ImagePathGenerator();
for (var index in content) {
if (Number(index) === position) {
var image_path = imagePathGenerator.generate({company: content[index].translator});
if (content.length > 1) {
CreateTranslationRow(image_path, content[index].translation, "general-info");
}
else {
CreateTranslationRow(image_path, content[index].translation, "general-text-info");
}
}
else {
var image_path = imagePathGenerator.generate({company: content[index].translator, color: "grey"});
CreateTranslationRow(image_path, content[index].translation, "");
}
}
}
function UserInterfaceHandler(parameters) {
var sourceText = parameters.sourceText,
translateTo = parameters.translateTo,
translateFrom = parameters.translateFrom;
function sendIntoTranslationMode() {
send('/translate');
}
function sendIntoPlayMode() {
send('/play');
}
function removeListeners() {
var elements = document.getElementsByClassName("pointer");
for (var i = 0; i < elements.length; i++) {
elements[i].removeEventListener('click',
function () {
},
false);
}
}
function addListeners(content) {
var elements = document.getElementsByClassName("pointer");
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click',
function () {
var parameters = {this: this, content: content};
var userInputProcessor = new UserInputProcessor(parameters);
removeListeners();
},
false);
}
}
function UserInputProcessor(parameters) {
var self = parameters.this,
content = parameters.content;
var position = -1;
findClickedTranslationPosition();
highlightTranslationBasedUserInput();
saveUserClickedTranslation();
function findClickedTranslationPosition() {
var clickedRow = $(self).parent(),
rows = $('#translation-choice').find('div.row');
$.each(rows, function (index, row) {
if (clickedRow.is(row)) {
position = index;
}
});
}
function highlightTranslationBasedUserInput() {
ShowTranslatorsBasedOnTranslation(content, position);
}
function saveUserClickedTranslation() {
var requestObject = composeRequestObject();
sendRequestObject();
function composeRequestObject() {
var requestObject = {};
for (var prop in content) {
if (content.hasOwnProperty(prop) &&
content[prop].hasOwnProperty('translator') &&
content[prop].hasOwnProperty('translation')) {
requestObject[content[prop]['translator']] = content[prop]['translation'];
}
}
requestObject['best_translator'] = content[position]['translator'];
return requestObject;
}
function sendRequestObject() {
/*TODO Check if this check is required*/
if (content.length > 1) {
$.ajax({
url: '/',
data: JSON.stringify(requestObject, null, '\t'),
type: 'POST',
contentType: 'application/json;charset=UTF-8',
success: function (response) {
console.info("Application has stored chosen translation successfully.");
},
error: function (error) {
console.warn("Application has failed to store chosen translation.");
}
});
}
}
}
}
function send(url) {
// Remove spaces, tabs, newlines and etc. from the beginning and end of the string
if ($.trim(sourceText).length > 0) {
var pageRenderer = new PageRenderer();
pageRenderer.loader.draw();
$.ajax({
url: url,
type: 'GET',
data: {
from: translateFrom,
to: translateTo,
q: sourceText
},
cache: false,
success: function (response) {
var response_object = JSON.parse(response);
var translations = response_object["translations"];
var renderer = new Renderer({content: translations});
if (url === '/play') {
var content = renderer.renderPlayMode();
pageRenderer.loader.erase();
addListeners.call(this, content);
var playModeRenderer = new PlayModeRenderer();
playModeRenderer.page.draw(content);
}
else {
var content = renderer.renderTranslateMode();
pageRenderer.loader.erase();
var translationModeRenderer = new PlayModeRenderer();
translationModeRenderer.page.draw(content);
}
},
error: function (error) {
console.warn("We are sorry. The application error has occurred.");
pageRenderer.loader.erase();
}
});
}
}
return {
initiateTranslationModeFlow: sendIntoTranslationMode,
initiatePlayModeFlow: sendIntoPlayMode
};
}
function CreateRequestObject() {
var translateFrom = $('.translate-from').attr('name'),
translateTo = $('.translate-to').attr('name'),
sourceText = $('textarea').val();
return {
translateFrom: translateFrom,
translateTo: translateTo,
sourceText: sourceText
}
}
$(function () {
$('#playButton').click(function() {
var requestObject = new CreateRequestObject();
var handler = new UserInterfaceHandler(requestObject);
handler.initiatePlayModeFlow();
});
});
$(function () {
$('#translateButton').click(function() {
var requestObject = new CreateRequestObject();
var handler = new UserInterfaceHandler(requestObject);
handler.initiateTranslationModeFlow();
});
});
$(document).ready(function () {
var max_text_length = 500;
$('#translation-textarea-char-counter').html("0/" + max_text_length.toString());
$('#translation-textarea').keyup(function () {
var text_length = $('#translation-textarea').val().length;
$('#translation-textarea-char-counter').html(text_length.toString() + "/" + max_text_length.toString());
});
});
|
ChameleonTartu/neurotolge
|
static/js/translations_interface.js
|
JavaScript
|
mit
| 16,133
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M6 20h10.78l-10-10H6zm6.44-10L18 15.56V10z" opacity=".3" /><path d="M8.9 6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2h-4.66l2 2H18v5.56l2 2V10c0-1.1-.9-2-2-2h-1V6c0-2.76-2.24-5-5-5-2.32 0-4.26 1.59-4.82 3.74L8.9 6.46V6zM4.41 4.81L3 6.22l2.04 2.04C4.42 8.6 4 9.25 4 10v10c0 1.1.9 2 2 2h12.78l1 1 1.41-1.41L4.41 4.81zM6 20V10h.78l10 10H6z" /></React.Fragment>
, 'NoEncryptionTwoTone');
|
kybarg/material-ui
|
packages/material-ui-icons/src/NoEncryptionTwoTone.js
|
JavaScript
|
mit
| 520
|
"use strict";
const expect = require("expect.js"),
chainable= require("../index");
describe("Chainable", function() {
let C1, C2, O1, O2;
before(function () {
O1 = {
add (value, addend) { return value + (addend || 0); },
sum () { return Array.prototype.slice.call(arguments).reduce((a, b) => a + b, 0); },
time (a = 1, b = 1) {return a * b;},
print (value, prefix, suffix) { return (prefix || "") + value + (suffix || ""); }
};
C1 = chainable(O1);
O2 = {
hello: "hi",
toArray(...args) {
return args;
},
push(arr = [], el) {
arr.push(el);
return arr;
},
each(arr, cb) {
return arr.map(cb);
}
};
C2 = chainable(O2);
});
describe("test on interface on chainable functions", function () {
it("can access original methods", function () {
expect(C1.add._origin == O1.add).to.be(true);
expect(C1.sum._origin == O1.sum).to.be(true);
expect(C1.print._origin == O1.print).to.be(true);
expect(C2.toArray._origin == O2.toArray).to.be(true);
});
it("can access original properties", function() {
expect(C2.hello._origin == O2.hello).to.be(true);
});
it("has register function", function() {
expect(C2.register).to.be.a("function");
});
it("has def function", function() {
expect(C2.def).to.be.a("function");
});
});
describe("test on chain and evaluate it", function () {
it("can chain and call with no value", function () {
expect(C1.add(2).time(2).value()).to.be(4);
expect(C1.add(2).sum(1, 3, 4).value()).to.be(10);
expect(C2.toArray(2).push(2).push(4).each(v => v * 3).value()).to.eql([6, 6, 12]);
});
it("can chain and call with single value, honor the value passed in with value()", function () {
expect(C1.add.time(2).value(3)).to.be(6);
expect(C1.add(2).time(2).print().value(0)).to.be("4");
expect(C2.toArray(2).push(2).push(4).each(v => v * 3).value(1)).to.eql([3, 6, 6, 12]);
});
it("can chain and call with multiple values", function () {
expect(C1.sum.value(1, 2, 3)).to.be(6);
expect(C1.sum.add(2).time.time.time(2).value(1, 2, 3)).to.be(16);
expect(C2.toArray.value(1, 2, 3)).to.eql([1, 2, 3]);
});
});
describe("test on chain on invalid props", function () {
it("can chain and call with multiple invalid values", function () {
expect(C1.dd.ddddd.ddddd).to.be.ok;
expect(C1.dd.ddddd.ddddd.def()).to.be(chainable.CONSTANTS.errors.NO_VALID_METHOD_PROPERTY);
});
it("can chain and call with mixed invalid and valid values", function () {
expect(C1.dd.add.ddddd.def() + "").to.be(`[{"name":"add"}]`);
});
});
describe("test on register", function () {
it("can register with valid name and function", function () {
C1.register("minus", function(value, minus) {
return value - minus;
});
expect(C1.add(2).minus(1).value(5)).to.be(6);
});
it("can register with valid function with name", function () {
C1.register(function divide(value, divideBy) {
return value / divideBy;
});
expect(C1.add(2).minus(1).divide(2).value(5)).to.be(3);
});
it("invalid register", function() {
expect(C1.register).withArgs(function(){}).to.throwException(chainable.CONSTANTS.errors.REGISTER_FUNCTION_NAME);
});
});
describe("def retrieve", function(){
it("can retrieve def with all valid methods", function() {
let def1 = C1.add(2, 3).time().time(2).def();
expect(def1 + "").to.be(`[{"name":"add","args":[2,3]},{"name":"time","args":[]},{"name":"time","args":[2]}]`);
expect(def1[0].fn === O1.add).to.be(true);
expect(def1[0].args).to.eql([2, 3]);
let def2 = C1.add.time(2).print.time.time.add.minus.divide.def();
expect(def2 + "").to.be(`[{"name":"add"},{"name":"time","args":[2]},{"name":"print"},{"name":"time"},{"name":"time"},{"name":"add"},{"name":"minus"},{"name":"divide"}]`);
expect(def2[4].fn === O1.time).to.be(true);
});
it("can retrieve def with invalid methods", function() {
let def = C1.add(2, 3).dd.ddd.dd.time(2).def();
expect(def.length).to.be(2);
expect(def + "").to.be(`[{"name":"add","args":[2,3]},{"name":"time","args":[2]}]`);
});
})
describe("serialize and deserialize", function(){
it("can serialize with valid methods", function() {
expect(C1.add(2, 3).dd.ddd.dd.time.time(2).serialize()).to.be(`add(2,3).time.time(2)`);
});
it("can serialize with invalid methods(ignore automatically)", function() {
let str = C1.minus(10, 3).dd.ddd.dd.time.time(2).serialize();
expect(C1.deserialize(str).value()).to.be(14);
});
})
});
|
CanisLycaon/chainable
|
tests/main.js
|
JavaScript
|
mit
| 4,789
|
'use strict'
const Router = require('express').Router
const passport = require('passport')
const config = require('../../config')
const logger = require('../../logger')
const models = require('../../models')
const authRouter = module.exports = Router()
// serialize and deserialize
passport.serializeUser(function (user, done) {
logger.info('serializeUser: ' + user.id)
return done(null, user.id)
})
passport.deserializeUser(function (id, done) {
models.User.findOne({
where: {
id: id
}
}).then(function (user) {
// Don't die on non-existent user
if (user == null) {
return done(null, false, { message: 'Invalid UserID' })
}
logger.info('deserializeUser: ' + user.id)
return done(null, user)
}).catch(function (err) {
logger.error(err)
return done(err, null)
})
})
if (config.isFacebookEnable) authRouter.use(require('./facebook'))
if (config.isTwitterEnable) authRouter.use(require('./twitter'))
if (config.isGitHubEnable) authRouter.use(require('./github'))
if (config.isGitLabEnable) authRouter.use(require('./gitlab'))
if (config.isMattermostEnable) authRouter.use(require('./mattermost'))
if (config.isDropboxEnable) authRouter.use(require('./dropbox'))
if (config.isGoogleEnable) authRouter.use(require('./google'))
if (config.isLDAPEnable) authRouter.use(require('./ldap'))
if (config.isSAMLEnable) authRouter.use(require('./saml'))
if (config.isOAuth2Enable) authRouter.use(require('./oauth2'))
if (config.isEmailEnable) authRouter.use(require('./email'))
if (config.isOpenIDEnable) authRouter.use(require('./openid'))
// logout
authRouter.get('/logout', function (req, res) {
if (config.debug && req.isAuthenticated()) {
logger.debug('user logout: ' + req.user.id)
}
req.logout()
res.redirect(config.serverURL + '/')
})
|
Yukaii/hackmd
|
lib/web/auth/index.js
|
JavaScript
|
mit
| 1,809
|
import React from "react";
const HelloWorld_Python = () => (
<div>
<h3>Hello World</h3>
</div>
);
export { HelloWorld_Python };
|
EdwardRees/EdwardRees.github.io
|
static/programming-tutorials-backup/src/languages/python/lessons/HelloWorld_Python.js
|
JavaScript
|
mit
| 138
|
import React, { Component } from 'react';
import AlbumSelector from './AlbumSelector.js';
import '../css/ActionBar.css';
// Action Bar
export default class ActionBar extends Component {
propTypes: { updateSelectedAlbum: React.PropTypes.func }
updateSelectedAlbum(album) {
this.props.updateSelectedAlbum(album);
}
render() {
var additionalActionBarClass = this.props.additionalClass ? this.props.additionalClass : "";
return (
<div className={"action-bar " + additionalActionBarClass}>
{(() => {
if(this.props.addAvailable) {
return <div className="col">
<AddToAlbumButton/>
</div>
}
return null;
})()}
{(() => {
if(this.props.albums.length > 0) {
return <div className="col">
<AlbumSelector updateSelectedAlbum={this.updateSelectedAlbum.bind(this)} albums={this.props.albums} text="View Album" showAll="true"/>
</div>;
}
return null;
})()}
</div>
);
}
}
// Add-to-album button
class AddToAlbumButton extends Component {
render() {
return (
<button type="button" className="btn" data-toggle="modal" data-target="#albumManagerOverlay">
Add to Album
</button>
)
}
}
|
TiffanyLeeRusso/mypictures
|
src/jsx/ActionBar.js
|
JavaScript
|
mit
| 1,335
|
var exec = require('cordova/exec');
/**
* Constructor
*/
function ListViewAlert() {
}
ListViewAlert.prototype.show = function(title, thelist, cb) {
var list = [].concat(title, thelist);
return exec(cb, failureCallback, 'ListViewAlert', 'ListViewAlert', list);
};
function failureCallback(err) {
console.log("ListViewAlert.js failed: " + err);
}
/**
* Load ListViewAlert
*/
var listViewAlert = new ListViewAlert();
module.exports = listViewAlert;
|
mgerlach-klick/cordova-android-listview-alert
|
www/ListViewAlert.js
|
JavaScript
|
mit
| 461
|
import React from 'react'
import { Icon, Step } from 'semantic-ui-react'
const StepExampleUnstackable = () => (
<Step.Group unstackable>
<Step>
<Icon name='plane' />
<Step.Content>
<Step.Title>Shipping</Step.Title>
<Step.Description>Choose your shipping options</Step.Description>
</Step.Content>
</Step>
<Step active>
<Icon name='dollar' />
<Step.Content>
<Step.Title>Billing</Step.Title>
<Step.Description>Enter billing information</Step.Description>
</Step.Content>
</Step>
<Step disabled>
<Icon name='info circle' />
<Step.Content>
<Step.Title>Confirm Order</Step.Title>
<Step.Description>Verify order details</Step.Description>
</Step.Content>
</Step>
</Step.Group>
)
export default StepExampleUnstackable
|
Semantic-Org/Semantic-UI-React
|
docs/src/examples/elements/Step/Variations/StepExampleUnstackable.js
|
JavaScript
|
mit
| 843
|
module.exports = {
config: {
type: 'bar',
data: {
datasets: [{
data: [1, 2, 3],
}],
labels: ['Long long label 1', 'Label2', 'Label3']
},
options: {
indexAxis: 'y',
scales: {
y: {
position: 'left',
ticks: {
mirror: true,
crossAlign: 'center',
},
},
}
}
},
options: {
spriteText: true,
canvas: {
height: 256,
width: 512
}
}
};
|
chartjs/Chart.js
|
test/fixtures/core.scale/crossAlignment/mirror-cross-align-left-center.js
|
JavaScript
|
mit
| 491
|
'use strict';
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var foldl = require('foldl');
/**
* Expose `Blueshift` integration.
*/
var Blueshift = module.exports = integration('Blueshift')
.global('blueshift')
.global('_blueshiftid')
.option('apiKey', '')
.option('retarget', false)
.tag('<script src="https://cdn.getblueshift.com/blueshift.js">');
/**
* Initialize.
*
* Documentation: http://getblueshift.com/documentation
*
* @api public
*/
Blueshift.prototype.initialize = function() {
window.blueshift = window.blueshift || [];
/* eslint-disable */
window.blueshift.load=function(a){window._blueshiftid=a;var d=function(a){return function(){blueshift.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track","click", "pageload", "capture", "retarget"];for(var f=0;f<e.length;f++)blueshift[e[f]]=d(e[f])};
/* eslint-enable */
window.blueshift.load(this.options.apiKey);
this.load(this.ready);
};
/**
* Loaded?
*
* @api private
* @return {boolean}
*/
Blueshift.prototype.loaded = function() {
return !!(window.blueshift && window._blueshiftid);
};
/**
* Page.
*
* @api public
* @param {Page} page
*/
Blueshift.prototype.page = function(page) {
if (this.options.retarget) window.blueshift.retarget();
var properties = page.properties();
properties._bsft_source = 'segment.com';
properties.customer_id = this.analytics.user().id();
properties.anonymousId = this.analytics.user().anonymousId();
properties.category = page.category();
properties.name = page.name();
window.blueshift.pageload(removeBlankAttributes(properties));
};
/**
* Trait Aliases.
*/
var traitAliases = {
created: 'created_at'
};
/**
* Identify.
*
* @api public
* @param {Identify} identify
*/
Blueshift.prototype.identify = function(identify) {
if (!identify.userId() && !identify.anonymousId()) {
return this.debug('user id required');
}
var traits = identify.traits(traitAliases);
traits._bsft_source = 'segment.com';
traits.customer_id = identify.userId();
traits.anonymousId = identify.anonymousId();
window.blueshift.identify(removeBlankAttributes(traits));
};
/**
* Track.
*
* @api public
* @param {Track} track
*/
Blueshift.prototype.track = function(track) {
var properties = track.properties();
properties._bsft_source = 'segment.com';
properties.customer_id = this.analytics.user().id();
properties.anonymousId = this.analytics.user().anonymousId();
window.blueshift.track(track.event(), removeBlankAttributes(properties));
};
/**
* Alias.
*
* @param {Alias} alias
*/
Blueshift.prototype.alias = function(alias) {
window.blueshift.track('alias', removeBlankAttributes({
_bsft_source: 'segment.com',
customer_id: alias.userId(),
previous_customer_id: alias.previousId(),
anonymousId: alias.anonymousId()
}));
};
/**
* Filters null/undefined values from an object, returning a new object.
*
* @api private
* @param {Object} obj
* @return {Object}
*/
function removeBlankAttributes(obj) {
return foldl(function(results, val, key) {
if (val !== null && val !== undefined) results[key] = val;
return results;
}, {}, obj);
}
|
ruemic/analytics.js-integration-blueshift
|
lib/index.js
|
JavaScript
|
mit
| 3,231
|
/**
* Created by Artiom on 11/05/2016.
*/
myApp.controller('ofertasCtrl', ['$scope', 'catalogoFactory', 'sucursalesFactory', 'ofertasFactory', '$q', 'FileUploader',
function($scope, catalogoFactory, sucursalesFactory, ofertasFactory, $q, FileUploader){
$scope.imageSelected = false;
$scope.oferta = {
titulo: '',
descripcion: '',
fecha: {
desde: new Date(),
hasta: new Date()
},
producto: '',
edades: {
desde: 0,
hasta: 99
},
sexo: '',
sucursales: [],
etiquetas: []
};
$scope.uploader = new FileUploader({
alias: 'oferta',
url: 'http://localhost:3002/ofertas/nueva/imagen/',
removeAfterUpload: true
});
$scope.datePopUp = [
{opened: false, format: 'dd/MM/yyyy', options: {formatYear: 'yyyy', startingDay: 1}},
{opened: false, format: 'dd/MM/yyyy', options: {formatYear: 'yyyy', startingDay: 1}}
];
$scope.abrirCalendar = function(index){
$scope.datePopUp[index].opened = !$scope.datePopUp[index].opened
};
$scope.getProductos = function(val){
var deferred = $q.defer();
var param = {
nombre: val
};
catalogoFactory.obtenerProductos(param, function(response){
if (response.statusText == 'OK'){
deferred.resolve(response.data);
} else {
deferred.reject();
}
});
return deferred.promise;
};
$scope.buscarSucursales = function(val){
var deferred = $q.defer();
var param = {
nombre: val
};
sucursalesFactory.obtenerSucursales(param, function(response){
if (response.statusText == 'OK'){
deferred.resolve(response.data);
} else {
deferred.reject();
}
});
return deferred.promise;
};
$scope.fileSelect = function(files){
if (files.length > 0){
var file = files[0];
var reader = new FileReader();
$scope.uploader.clearQueue();
$scope.uploader.addToQueue(file);
reader.onload = function(event){
var imagen = new Image();
imagen.src = event.target.result;
imagen.onload = function() {
context.drawImage(imagen, 0, 0, 150, imagesService.getImageProportion(imagen, 150));
$scope.imageSelected = true;
};
};
reader.readAsDataURL(file);
}
};
$scope.uploader.onSuccessItem = function(item, response, status, headers){
$scope.oferta = {
titulo: '',
descripcion: '',
fecha: {
desde: new Date(),
hasta: new Date()
},
producto: '',
edades: {
desde: 0,
hasta: 99
},
sexo: '',
sucursales: [],
etiquetas: []
};
$scope.imageSelected = false;
$scope.$broadcast('uploadFinish');
};
$scope.guardarOferta = function(){
ofertasFactory.guardarOferta($scope.oferta, function(response){
if (response.statusText == 'OK'){
if ($scope.uploader.queue.length > 0){
var fileItem = $scope.uploader.queue[0];
fileItem.url = fileItem.url + response.data._id;
$scope.uploader.uploadAll();
} else {
$scope.oferta = {
titulo: '',
descripcion: '',
fecha: {
desde: new Date(),
hasta: new Date()
},
producto: '',
edades: {
desde: 0,
hasta: 99
},
sexo: '',
sucursales: [],
etiquetas: []
};
}
}
})
}
}]);
|
tioma/publicidadCliente
|
app/ofertas/ofertas.js
|
JavaScript
|
mit
| 3,263
|
var request = require('request');
var url = 'http://provenance.mit.edu:8080/time';
request(url,function(error,response,body){
console.log(body);
});
|
1125f16/compuxo
|
documents/lecture_04/code/02.js
|
JavaScript
|
mit
| 157
|
'use strict';
module.exports = function (str, options) {
if (typeof str !== 'string') {
throw new TypeError('taghash expects a string');
}
options = options || {};
options.href = options.href || 'https://twitter.com/hashtag/';
if (!(/#/g).test(str)) {
return str;
}
var hashes = str.match(/[^|\s]?#[\d\w]+/g);
if (!hashes) {
return str;
}
var s = str;
hashes.forEach(function (item) {
var hash = item.slice(1);
// ignore tags that have a double "##"
if (hash.substring(0, 1) !== '#') {
s = s.replace(item, '<a href="' + options.href + '' + hash + '">' + item + '</a>');
}
});
return s;
};
|
radiovisual/taghash
|
index.js
|
JavaScript
|
mit
| 718
|
import { fuzzyLessThan } from '../src/math-toolbox'
describe('Fuzzy less than', () => {
it('Expect fuzzy 10.55 < 10.50 with epsilon 0.15 to be true', () => {
expect(fuzzyLessThan(10.55, 10.50, 0.15)).toBe(true)
})
it('Expect fuzzy 10.5 < 10.55 with epsilon 0.05 to be true', () => {
expect(fuzzyLessThan(10.55, 10.55, 0.05)).toBe(true)
})
})
|
terkelg/math-toolbox
|
test/fuzzy-less-than.test.js
|
JavaScript
|
mit
| 360
|
import messages from 'ringcentral-integration/modules/Conference/messages';
export default {
[messages.requireAditionalNumbers]: 'Veuillez sélectionner les autres numéros à composer.'
};
// @key: @#@"[messages.requireAditionalNumbers]"@#@ @source: @#@"Please select the additional dial-in numbers."@#@
|
u9520107/ringcentral-js-widget
|
packages/ringcentral-widgets/components/ConferenceAlert/i18n/fr-CA.js
|
JavaScript
|
mit
| 309
|
const merge = require('webpack-merge');
const webpack = require('webpack');
const baseWebpackConfig = require('./webpack.base');
const path = require('path');
const projectRoot = path.resolve(__dirname, './');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = merge(baseWebpackConfig, {
output: {
path: projectRoot + '/assets',
filename: '[name].[hash].package.js'
},
plugins: [
new ExtractTextPlugin({
filename: '[name].[hash].package.css',
allChunks: true,
}),
new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
mangle: {
keep_fnames: true
}
}),
new webpack.LoaderOptionsPlugin({
htmlLoader: {
minimize: false // workaround for ng2
}
}),
new webpack.DefinePlugin({
__IN_DEBUG__: JSON.stringify(false)
}),
],
});
|
jasonraimondi/command-query
|
templates/_base/webpack.prod.js
|
JavaScript
|
mit
| 892
|
function CountedLockableContainer() { this.initialize.apply(this, arguments); };
(function(Parent) {
'use strict';
var _MSG_MAX_COUNT_REACHED =
'The maximum amount of tolerable key mismatches are reached';
function _addKeyMismatchCount() { this._keyMismatchCount++; };
function _hasReachedMaxKeyMismatchCount() {
return this.keyMismatchCount() >= this._MAX_KEY_MISMATCH_COUNT;
};
CountedLockableContainer.prototype = Object.create(Parent);
CountedLockableContainer.prototype.constructor = CountedLockableContainer;
CountedLockableContainer.prototype.initialize =
function(key, maxKeyMismatchCount) {
Parent.initialize.call(this, key);
this._MAX_KEY_MISMATCH_COUNT = maxKeyMismatchCount;
};
CountedLockableContainer.prototype.tryUnlock = function(key, errback) {
if (_hasReachedMaxKeyMismatchCount.call(this)) {
return errback(_MSG_MAX_COUNT_REACHED);
}
this._tryUnlock(key, errback);
};
CountedLockableContainer.prototype.keyMismatchCount = function() {
return this._keyMismatchCount;
};
CountedLockableContainer.prototype._initCaches = function() {
Parent._initCaches.call(this);
this._resetKeyMismatchCount();
};
CountedLockableContainer.prototype._tryUnlock = function(key, errback) {
if (!this._isCorrectKey(key)) _addKeyMismatchCount.call(this);
Parent.tryUnlock.call(this, key, errback);
if (!_hasReachedMaxKeyMismatchCount.call(this)) return;
errback(_MSG_MAX_COUNT_REACHED);
};
CountedLockableContainer.prototype._resetKeyMismatchCount = function() {
this._keyMismatchCount = 0;
};
CountedLockableContainerUnitTest(CountedLockableContainer.prototype);
})(LockableContainer.prototype);
|
Double-X/Lockable-Container
|
js/prototype/countedLockableContainerPrototype.js
|
JavaScript
|
mit
| 1,837
|
'use strict';
module.exports = function(sequelize, DataTypes) {
const groupDestInfo = sequelize.define('groupDestInfo', {
_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
}
}, {
timestamps: false,
classMethods: {
associate: function(models) {
groupDestInfo.belongsTo(models.group);
}
}
});
return groupDestInfo;
};
|
marybethsnodgrass/rescuerailroad
|
server/models/groupDestInfo.js
|
JavaScript
|
mit
| 454
|
/**
* Class Name: MF Framework for browsers
* Experimental environment for creating web applications
* based on REST. Just to learn.
*
* Based on backbone
*
* @author Francesc Requesens
* @version 0.9 2014-12-08
* @dependences jQuery > 1.10
*
*/
(function(){
'use strict';
//Creem variable principal assignada a window
var MF = window.MF = {};
//Version
MF.VERSION = '0.9';
//Connection Class
MF.Connection = MFConnectionJQuery;
/**
* Model Method
*/
var Model = MF.Model = function(options) {
var self = this;
//Defaults - Options
var defaults = {
url : '',
id : 0,
content : null,
schema : {},
transformURLs : null
};
var preOptions = $.extend(true, defaults, self.constructor.prototype || {});
var options = $.extend(false, self.constructor.prototype, options || {});
//Public methods link
self.init = init;
self.destroy = destroy;
self.setUrlRoot = setUrlRoot;
self.get = get;
self.fetch = fetch;
self.setContent = setContent;
self.add = add;
self.update = update;
self.remove = remove;
self.sync = sync;
//Local
var urlRoot = self.urlRoot;
var subcollections = self.constructor.subcollections || [];
self.url = options.url;
self.id = options.id;
self.content = options.content;
self.schema = options.schema;
self.transformURLs = options.transformURLs;
self.lastModified = null;
self.lastSync = null;
//Call init
init();
//Public Methods
//Initialize data
function init(){
//Prepare url - Per no tenir problemes amb la barra final.
if (self.content && self.content.id){
self.id = parseInt(self.content.id);
self.url = urlRoot + self.id + '/';
}
else if (self.id)
self.url = urlRoot + self.id + '/';
else if (self.url) {
self.id = self.url.match(/\d*(\/?)$/)[0];
if (isNaN(self.id))
self.id = self.url.match(/\d*$/)[0];
self.url = self.url? self.url.replace('//', '/') : '';
//If is necessary transform URLs
// Es pot donar el cas que un model es genera a partir d'altres
// models o colleccions però la definició s'ha fet a l'inici.
if(self.transformURLs)
for (var tfk in self.transformURLs){
var rg = new RegExp("/:" + tfk + "/?", 'i');
self.url = self.url.replace(rg,"/"+self.transformURLs[tfk]+"/");
}
//Internal collections (subcollections)
// TODO Limitar la recursivitat
if (subcollections && self.id)
_subcollections(subcollections);
};
function destroy(){
self = {};
};
function setUrlRoot(url){
urlRoot = self.urlRoot = url;
return urlRoot;
};
//Get - Returns itself
// Si no té les dades, les va a buscar pel mètode fetch
function get(_options){
if (!self.url) throw "No url defined";
if (!self.id) self.id = self.url.match(/\d*$/)[0];
var _defaults = {
async : true,
callback : function(){}
};
var _options = $.extend(_defaults, _options || {});
var callback = _options.callback;
if (!self.content)
fetch(_options);
else if (callback && typeof callback === 'function')
callback(self);
};
//Fetch
// Agafa del servidor les dades i les sincronitza
function fetch(_options){
if (!self.url) throw "No url defined";
if (!self.id) self.id = self.url.match(/\d*$/)[0];
var _defaults = {
async : true,
callback : function(){}
};
var _options = $.extend(_defaults, _options || {});
var async = _options.async;
var callback = _options.callback;
var dataObj = new MF.Connection(self.url);
dataObj.init(async, function(rData){
self.content = rData;
self.id = rData.id;
self.lastSync = new Date();
if (callback && typeof callback === 'function')
callback(self);
});
};
//SoftAdd
// Insereix les dades a l'objecte però no les desa al servidor
function setContent(data){
self.content = data;
};
//Add
// Fa un POST de les dades al Servidor
function add(_options){
var _defaults = {
data : {},
async : true,
callback: function(){}
};
var _options = $.extend(_defaults, _options || {});
setContent(_options.data);
sync({
async : _options.async,
callback : _options.callback
});
};
//Update
// Actualitza les dades (PUT) al servidor i es retorna ell mateix
function update(_options){
var _defaults = {
data : {},
async : true,
callback: function(){}
};
var _options = $.extend(_defaults, _options || {});
//Save previous Model
self.prevcontent = $.extend(false, self.content, {});
setContent(_options.data);
sync({
async : _options.async,
callback : _options.callback
});
};
//Remove
// Elimina l'element del servidor. No retorna res is ha anat bé.
function remove(callback, async){
var dataObj = new MF.Connection(self.url);
if (!async) async = true;
dataObj.remove(async, function(rData){
if (callback && typeof callback === 'function')
callback(rData);
if (rData.status > 299)
return false;
else destroy();
});
};
//Sync
// Sincronitza les dades del model amb el servidor
function sync(_options){
var _defaults = {
async : true,
callback: function(){}
};
var _options = $.extend(_defaults, _options || {});
var async = _options.async;
var callback = _options.callback;
var type = '';
var url = self.id? self.url : self.urlRoot;
if(!self.id) type = 'post';
else type = 'put';
var dataObj = new MF.Connection(url);
dataObj[type](async, JSON.stringify(self.content), function(rData){
if (rData.status > 299) {
//Cagada TOTAL!
if (callback && typeof callback === 'function')
callback(rData);
return false;
}
self.content = rData;
self.lastSync = new Date();
//Update subcollections
if (type == 'post') {
self.id = rData.id;
self.url = self.urlRoot + self.id + '/';
if (self.constructor.subcollections)
_subcollections(self.constructor.subcollections);
}
//Callback
if (callback && typeof callback === 'function') callback(self);
});
};
function _subcollections(subcollections){
for (var i=0; i < subcollections.length; i++) {
var regInitSlash = /^\//;
var url_subcollection, urlRoot_subcollection;
var subcollection = subcollections[i];
if (regInitSlash.test(subcollection.url_part))
url_subcollection = subcollection.url_part;
else
url_subcollection = self.url + '/' + subcollection.url_part;
url_subcollection = url_subcollection.replace('//', '/');
urlRoot_subcollection = url_subcollection + '/';
urlRoot_subcollection = urlRoot_subcollection.replace('//', '/');
self[subcollection.name] = new MF.Collection({
url: url_subcollection,
model : Model.extend({
urlRoot : urlRoot_subcollection,
subcollections: subcollection.subcollections,
attributes : subcollection.attributes
})
});
var collection = self[subcollection.name];
if(subcollection.field_content && self.content){
//self[subcollection.name].count = self.content[subcollection.field_content].length;
var arrResults = [];
if (arrResults = subcollection.field_content.match(/([a-zA-Z]+)\.([a-zA-Z]+)/))
self[subcollection.name].massiveAdd(self.content[arrResults[1]][arrResults[2]]);
else
self[subcollection.name].massiveAdd(self.content[subcollection.field_content]);
}
};
};
};
//Add collection to model
Model.addCollection = function(_options){
var _defaults = {
name : "",
url_part : ""
};
var collection = $.extend(_defaults, _options || {});
if (!this.subcollections) this.subcollections = [];
this.subcollections.push(collection);
return collection.name;
};
/**
* Collection Method
*/
var Collection = MF.Collection = function(options) {
var self = this;
//Defaults - Options
var defaults = {
url : '',
model : null,
isolateModel : false,
items_name : 'results',
transformURLs : null
};
var options = $.extend(defaults, options || {});
//Public methods
self.init = init;
self.destroy = destroy;
self.get = get;
self.fetch = fetch;
self.create = create;
self.massiveAdd = massiveAdd;
self.add = add;
self.update = update;
self.remove = remove;
self.isDuplicate = isDuplicate;
self.reset = reset;
self.setUrlRoot = setUrlRoot;
self.search = search;
//"Local"
self.url = options.url;
var items_name = self.items_name = options.items_name;
self.transformURLs = options.transformURLs;
self[items_name] = [];
//MODEL
if (options.isolateModel)
var SelfModel = options.model.extend();
else
var SelfModel = options.model;
self.model = SelfModel;
init();
//Public Methods
function init(){
if (!self.url)
return false;
//Transform URLs
if(self.transformURLs) {
for (var tfk in self.transformURLs){
var rg = new RegExp("/:" + tfk + "/?", 'i');
SelfModel.prototype.urlRoot = SelfModel.prototype.urlRoot.replace(rg,"/"+self.transformURLs[tfk]+"/");
}
}
};
function destroy(){
self = {};
};
function setUrlRoot(url){
SelfModel.urlRoot = url;
};
function get (_options) {
var _defaults = {
key : 'id',
identifier : 0,
async : true,
params: '',
success: function(){},
error: function(){}
};
var _options = $.extend(_defaults, _options || {});
var key = _options.key;
var identifier = _options.identifier;
var async = _options.async;
var success = _options.success;
if (identifier)
var model = _getModel(key, identifier, async, success);
else {
if (!self[items_name].length)
fetch(_options);
else if (success && typeof success === 'function')
success(self);
}
};
function fetch (_options) {
var _defaults = {
async : true,
params: '',
success: function(){},
error: function(){}
};
var _options = $.extend(_defaults, _options || {});
var async = _options.async;
var params = _options.params;
var success = _options.success;
var error = _options.error;
reset();
if (!self.url) urlError();
var dataObj = new MF.Connection(self.url + (params? '?' + params : ''));
dataObj.init(async, function(rData){
if (rData.status > 299){
if (error && typeof error === 'function') error(rData);
return false;
}
var items = rData[items_name];
if (!items) return false;
// Add items to collection
massiveAdd(items);
self.count = rData.count;
self.next = rData.next;
self.previous = rData.previous;
if (success && typeof success === 'function') success(self);
});
};
//Add
// Adds a Model object to collection
function add (model){
if (model.constructor === SelfModel){
self[items_name].push(model);
self.count = self[items_name].length;
}
};
//Massive add
// Adds multiple models to collection
function massiveAdd (items){
for (var i = 0; i < items.length; i++){
var model = new SelfModel({ content : items[i], transformURLs:self.transformURLs });
add(model);
}
};
//Create
// Creates a Model object and adds to collection
function create(_options){
var model = new SelfModel();
var _defaults = {
data : {},
async : true,
callback: function(){}
};
var _options = $.extend(_defaults, _options || {});
var data = _options.data;
var async = _options.async;
var callback = _options.callback;
//TODO SYNC!!!
model.add({
async : async,
data : data,
callback :function(rData){
if (rData.status > 299){
callback(rData);
return false;
}
add(model);
callback(model);
}
});
};
//Update - TODO
// Method sync on model makes the same...
// Actualiza un objecte Model d'una collecció
function update(identifier, data, callback){
var index = _getModelIndex(identifier);
if (index < 0) throw "Not found";
};
//Remove
// Elimina un objecte Model d'una collecció
function remove(identifier, callback){
var index = _getModelIndex(identifier);
if (index < 0) {
if (callback && typeof callback === 'function')
callback({status: 999});
return false;
}
var item = self[items_name][index];
item.remove(function(rData){
if (rData.status > 299){
callback(rData);
return false;
}
self[items_name].pop(index);
if (callback && typeof callback === 'function')
callback(rData);
});
};
//Is duplicate
//Check if item exists on collection
function isDuplicate(key, value, callback){
ret = false;
for (var i = 0; i < self.items.length; i++){
if (value == self.items[i].content[key]){
ret = parseInt(self.items[i].id);
break;
}
}
if (callback && typeof callback === 'function')
callback(ret);
else return ret;
};
//Reset
// Reset collection
function reset(){
self[items_name] = [];
};
//Search
// Returns a list of elements from collection that their key can
// contains a value
function search(_options) {
var _defaults = {
keys: ['name'],
value: '',
callback: null,
};
var _options = $.extend(_defaults, _options || {});
var keys = _options.keys;
//Prepare for search (remove accents, upper case)
var value = _options.value.mfRemoveAccents().toUpperCase();
var callback = _options.callback;
var items = self[items_name];
var arrResults = [];
if (!items.length) return false; //Fer saltar un error molaria més.
for (var i = 0; i < items.length; i++) {
for (var j = 0; j < keys.length; j++) {
var arrKeys = keys[j].split('.');
//Anem a trobar el camp a fer la cerca
var field = items[i].content;
for (var k = 0; k < arrKeys.length; k++) {
field = field[arrKeys[k]];
};
//Cerca.
// Si és un número o boolean per igualació
// Si és string per "indexOf"
// Si és una altra cosa... res de res
switch(typeof value){
case 'boolean':
case 'number':
if (field == value)
arrResults.push(items[i]);
break;
case 'string':
if (field.mfRemoveAccents().toUpperCase().indexOf(value) >= 0)
arrResults.push(items[i]);
break;
}
};
};
//Return
if (callback && typeof callback === 'function')
callback(arrResults);
else
return arrResults;
};
//Private Methods
//_getModel
//Gets Model object
function _getModel(key, value, async, callback){
if (key == 'id') {
var index = _getModelIndex(value);
if (index >= 0)
callback(self[items_name][index]);
else {
var model = new SelfModel({id : value});
model.get({
async : async,
callback : function(){
add(model);
callback(model);
}
});
}
}
else {
//Agafa el primer valor... Hauria de poder retornar més d'un
//valor si es dóna el cas.
var index = _getModelIndexByKey(key, value)[0];
if (index >= 0)
callback(self[items_name][index]);
}
return true;
};
//_getModelIndex
//Gets model position from collection
function _getModelIndex(id) {
var items = self[items_name];
if (items.length)
for (var i = 0; i < items.length; i++)
if (items[i].id == id)
return i;
return -1;
};
//_getModelIndexByKey
//Dóna les posicions en un array a la llista dels models segons un camp
//Pot fer cerques en una clau de subnivell. Només un.
function _getModelIndexByKey(key, value) {
var items = self[items_name];
var arrResults = [];
var arrKeys = key.split('.');
if (items.length)
for (var i = 0; i < items.length; i++)
if ((arrKeys.length < 2 && items[i].content[key] == value) ||
(arrKeys.length == 2 && items[i].content[arrKeys[0]][arrKeys[1]] == value)
)
arrResults.push(i);
return arrResults;
};
};
/**
* Controller Method - jQuery Plugin creator
*/
var Controllers = MF.Controllers = function(name, o) {
;(function($) {
o.options = $.extend(o.options, {});
//Create plugin
$.fn[name] = function(options) {
//Clone object
var defaults = JSON.parse(JSON.stringify(o.options));
// method calling
if( typeof options == 'string') {
var args = Array.prototype.slice.call(arguments, 1);
var res;
this.each(function() {
var obj = $.data(this, name);
if(obj && $.isFunction(obj[options])) {
var r = obj[options].apply(obj, args);
if(res === undefined) res = r;
if(options == 'destroy') $.removeData(this, name);
}
else if(obj && obj[options]) res = obj[options];
});
if(res !== undefined)
return res;
return this;
}
options = $.extend(defaults, options || {});
this.each(function(i, _element) {
var element = $(_element);
var obj = new o.ClassController(element, options);
element.data(name, obj);
obj.init();
});
return this;
};
})(jQuery);
};
//Extend
//Clona un element i el retorna amb les propietats que s'han volgut
//modificar. Ideal per a crear objectes Model nous
//var extend = function(protoProps, staticProps) {
var extend = function(protoProps) {
var parent = this;
var child = function(){
return parent.apply(this, arguments);
};
//$.extend(child, parent, staticProps);
$.extend(child, parent);
//Create new element
var Substitute = function(){ this.constructor = child; };
Substitute.prototype = parent.prototype;
child.prototype = new Substitute;
if (protoProps)
$.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
return child;
};
//Assign to function
Model.extend = extend;
//Guid - Create Unique id
var guid = MF.Guid = (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
}).call(this);
|
elpeix/mf
|
source/mf.js
|
JavaScript
|
mit
| 18,390
|
var classparray =
[
[ "parray", "classparray.html#a242d42278b59d5817cf4bb3a1ea791a8", null ],
[ "parray", "classparray.html#a9c668440db7d451c2dde6a9c6a9caa3f", null ],
[ "parray", "classparray.html#ae82b2eeccaf4bed4d3e6de2978a0d134", null ],
[ "parray", "classparray.html#a705c34ed20a0cfc28f6aefcac3393fc7", null ],
[ "begin", "classparray.html#a02e4d11e38a51c2d3264b21c783d99b2", null ],
[ "data", "classparray.html#a0a1a3b16f9061ae1c09c262e5cc614f5", null ],
[ "end", "classparray.html#aa24077fc9bd9ed811188ad0a52964781", null ],
[ "operator()", "classparray.html#a5c6bd9638a40f2457ad8e01a004c353e", null ],
[ "operator()", "classparray.html#ad41cbbaf159d7431af23a3751c5ac415", null ],
[ "operator()", "classparray.html#a822d244e794af5d49923bba426d6fd9d", null ],
[ "operator()", "classparray.html#a1170773ce1ec9edcda55eef62b17e3d5", null ],
[ "operator()", "classparray.html#ac7d2e64c388e0a56cdbb55a5c920d2e2", null ],
[ "operator()", "classparray.html#af0f48b7040ded084074c3865aa464113", null ],
[ "operator[]", "classparray.html#a4549713b7694d53de9b97ea3f77af0d4", null ],
[ "size", "classparray.html#a4bd4c769c82a796b17bf92bc6ee85bae", null ]
];
|
mabur/gal
|
documentation/html/classparray.js
|
JavaScript
|
mit
| 1,211
|
var _ = require('lodash');
var querystring = require('querystring');
var RouteParser = require('route-parser');
var EventEmitter = require('events').EventEmitter;
var cancellableNextTick = require('cancellable-next-tick');
if (process.browser){
var History = require('html5-history');
var routers = [];
History.Adapter.bind(window, 'statechange', function(){
_.forEach(routers, function(router){
router._update(window.document.location.pathname + window.document.location.search, true);
});
});
}
var route_parser_cache = {};
var getRouteParser = function(pattern){
if (pattern in route_parser_cache){
return route_parser_cache[pattern];
}
try {
return route_parser_cache[pattern] = new RouteParser(pattern);
} catch (error){
throw new Error('Could not parse url pattern "' + pattern + '": ' + error.message);
}
};
/**
* Mutable observable abstraction of url as route with parameters
* @example
var router = new ObsRouter({
home: '/',
blog: '/blog(/tag/:tag)(/:slug)',
contact: '/contact'
}, {
initialEmit: true,
bindToWindow: false,
url: '/?foo=bar'
});
console.log(router.url, router.name, router.params, router.routes);
// -> '/?foo=bar' 'home' {foo: 'bar'} {home: {foo: 'bar'}, blog: null, contact: null}
* @class ObsRouter
* @param {Object} patterns Pathname patterns keyed by route names.
* @param {Object} [options] Options
* @param {Boolean} [options.initialEmit=false] If true, events will be emitted after nextTick, unless emitted earlier due to changes, ensuring that events are emitted at least once.
* @param {Boolean} [options.bindToWindow=true] Bind to document location if running in browser
* @param {string} [options.url=""] Initial url. If binding to document loctation then this is ignored.
*/
var ObsRouter = function(patterns, options) {
var self = this;
if (!(typeof patterns=='object')){throw new Error('ObsRouter constructor expects patterns object as first argument')}
options = options || {};
EventEmitter.call(self);
if (process.browser){
//bind to window by default
self._bindToWindow = 'bindToWindow' in options ? options.bindToWindow : true;
if (self._bindToWindow){
// add to module-scoped list of routers
routers.push(self);
// override any url input with window location
options.url = window.document.location.pathname + window.document.location.search;
}
}
// initialise state
self.patterns = patterns;
self.name = null;
self.params = {};
self.routes = {};
_.forEach(_.keys(self.patterns), function(route){
self.routes[route] = null;
});
// normalise state
self._update(options.url || '', false);
// implement initialEmit option
if (options.initialEmit){
var cancel = cancellableNextTick(function(){
self._emit();
});
self.once('url', cancel);
}
};
ObsRouter.prototype = _.create(EventEmitter.prototype);
ObsRouter.prototype._update = function(url, emit){
var self = this;
if (url == self.url){return;}
self.old_url = self.url;
self.old_name = self.name;
self.old_params = self.params;
self.url = url;
self.name = self.urlToRoute(self.url, self.params = {});
if (self.old_name){
self.routes[self.old_name] = null;
}
if (self.name){
self.routes[self.name] = self.params;
}
if (emit){
self._emit();
}
};
ObsRouter.prototype._emit = function(){
var self = this;
self.emit('url', self.url, self.old_url);
self.emit('route', self.name, self.params, self.old_name, self.old_params);
if (self.old_name && (self.old_name !== self.name)){
self.emit(self.old_name, null);
}
if (self.name){
self.emit(self.name, self.params);
}
};
/**
* Uses History.replaceState to change url to new url and updates route name + params + routes
* Replacing rather than pushing means the browser's user can not get to the previous state with the back button.
* @param {string} url The new url
*/
ObsRouter.prototype.replaceUrl = function(url){
var self = this;
if (process.browser && self._bindToWindow){
History.replaceState({}, window.document.title, url);
} else {
self._update(url, true);
}
};
/**
* Uses History.pushState to change url to new url and updates route name + params + routes
* Pushing rather than replacing means the browser's user can get to the previous state with the back button.
* @param {string} url The new url
*/
ObsRouter.prototype.pushUrl = function(url){
var self = this;
if (process.browser && self._bindToWindow){
History.pushState({}, window.document.title, url);
} else {
self._update(url, true);
}
};
/**
* Uses History.replaceState to change the url to new url and updates route name + params + routes
* Replacing rather than pushing means the browser's user can not get to the previous state with the back button.
* @param {string} [name=this.name] The new route name
* @param {Object} [params={}] The new parameters
* @param {Boolean} [extend_params=false] Extend parameters rather than replacing them.
*/
ObsRouter.prototype.replaceRoute = function(name, params, extend_params){
var self = this;
self.replaceUrl(self.routeToUrl(name, params, extend_params));
};
/**
* Uses History.pushState to change the route name + params to new route name + params and updates url + routes
* Pushing rather than replacing means the browser's user can get to the previous state with the back button.
* @param {string} [name=this.name] The new route name
* @param {Object} [params={}] The new parameters
* @param {Boolean} [extend_params=false] Extend parameters rather than replacing them.
*/
ObsRouter.prototype.pushRoute = function(name, params, extend_params){
var self = this;
self.pushUrl(self.routeToUrl(name, params, extend_params));
};
/**
* Converts a route (name & params) to a url
* @example
* // simple example
*
* var url = router.routeToUrl('blog', {slug: 'Why_I_love_Russian_girls', page: 82});
* console.log(url); // -> /blog/Why_I_love_Russian_girls?page=82
*
* // cool example using extend_params=true
*
* console.log(router.params); // -> {tags: 'sexy'}
* var url = router.routeToUrl('blog', {filter: 'graphic'}, true);
* console.log(url); // -> '/blog/tags/sexy?filter=graphic'
* @param {string} [name=this.name] Route name
* @param {Object} [params={}] Route parameters
* @param {Boolean} [extend_params=false] Extend parameters rather than replacing them.
* @returns {string} Url
*/
ObsRouter.prototype.routeToUrl = function(name, params, extend_params){
var self = this;
var _name = name || self.name;
var _params = _.assign({}, extend_params ? self.params : {}, params || {});
return ObsRouter.routeToUrl(self.patterns, _name, _params);
};
/**
* Converts a url to a name & params.
* The optional params argument is used to pass back the arguments, and only the name is `return`ed.
* @example
* var route_params = {};
* var route_name = router.urlToRoute('/blog', route_params);
* console.log(route_name, route_params);
* // -> blog {tag: undefined, slug: undefined}
* @param {string} url Url to convert.
* @param {Object} [params] Parameters object to populate.
* @returns {string|null} Route name or null if no route matched
*/
ObsRouter.prototype.urlToRoute = function(url, params){
return ObsRouter.urlToRoute(this.patterns, url, params);
};
/**
* Cleanup method to be called when you're done with your ObsRouter instance.
*/
ObsRouter.prototype.destroy = function(){
var self = this;
self.removeAllListeners();
if (process.browser && self._bindToWindow){
routers = _.without(routers, self);
};
};
/**
* Converts a route (name & params) to a url, given patterns
* @param {Object} patterns Pathname patterns keyed by route names
* @param {string} name Route name
* @param {Object} [params={}] Route parameters
* @returns {string} Url
*/
ObsRouter.routeToUrl = function(patterns, name, params){
params = params || {};
var route_parser = getRouteParser(patterns[name]);
var path = route_parser.reverse(params);
if (path===false){
throw new Error('Missing required parameter')
}
for (var _name in patterns){
if (_name == name){break;}
if (getRouteParser(patterns[_name]).match(path)){
throw new Error('Found unreachable route. Path ' + path + ' for route ' + name
+ ' (params: ' + JSON.stringify(params) + ') also matches route ' + _name
+ '! Maybe you need to change the order of the patterns?');
}
}
var pathname_params = route_parser.match(path);
var query_params = {};
_.forEach(params, function(value, key){
if (!(key in pathname_params)){
query_params[key] = value;
}
});
return path + (JSON.stringify(query_params)=='{}' ? '' : '?' + querystring.encode(query_params));
};
/**
* Converts a url to a name & params, given patterns
* The optional params argument is used to pass back the arguments, and only the name is `return`ed.
* @param {Object} patterns Pathname patterns keyed by route names
* @param {string} url Url to convert.
* @param {Object} [params] Parameters object to populate.
* @returns {string|null} Route name or null if no route matched
*/
ObsRouter.urlToRoute = function(patterns, url, params){
var self = this;
var name = null;
_.find(patterns, function(pattern, _name){
var pathname_params = getRouteParser(pattern).match(url);
if (pathname_params){
if (typeof params=='object'){
var index = url.indexOf('?');
var query_params = index == -1 ? {} : querystring.decode(url.slice(index+1));
_.assign(params, query_params, pathname_params);
}
name = _name;
return true;
}
});
return name;
};
module.exports = ObsRouter;
|
zenflow/obs-router
|
lib/index.js
|
JavaScript
|
mit
| 9,774
|
/* */
(function(process) {
var optimist = require("../index");
var path = require("path");
var test = require("tap").test;
var $0 = 'node ./' + path.relative(process.cwd(), __filename);
test('short boolean', function(t) {
var parse = optimist.parse(['-b']);
t.same(parse, {
b: true,
_: [],
$0: $0
});
t.same(typeof parse.b, 'boolean');
t.end();
});
test('long boolean', function(t) {
t.same(optimist.parse(['--bool']), {
bool: true,
_: [],
$0: $0
});
t.end();
});
test('bare', function(t) {
t.same(optimist.parse(['foo', 'bar', 'baz']), {
_: ['foo', 'bar', 'baz'],
$0: $0
});
t.end();
});
test('short group', function(t) {
t.same(optimist.parse(['-cats']), {
c: true,
a: true,
t: true,
s: true,
_: [],
$0: $0
});
t.end();
});
test('short group next', function(t) {
t.same(optimist.parse(['-cats', 'meow']), {
c: true,
a: true,
t: true,
s: 'meow',
_: [],
$0: $0
});
t.end();
});
test('short capture', function(t) {
t.same(optimist.parse(['-h', 'localhost']), {
h: 'localhost',
_: [],
$0: $0
});
t.end();
});
test('short captures', function(t) {
t.same(optimist.parse(['-h', 'localhost', '-p', '555']), {
h: 'localhost',
p: 555,
_: [],
$0: $0
});
t.end();
});
test('long capture sp', function(t) {
t.same(optimist.parse(['--pow', 'xixxle']), {
pow: 'xixxle',
_: [],
$0: $0
});
t.end();
});
test('long capture eq', function(t) {
t.same(optimist.parse(['--pow=xixxle']), {
pow: 'xixxle',
_: [],
$0: $0
});
t.end();
});
test('long captures sp', function(t) {
t.same(optimist.parse(['--host', 'localhost', '--port', '555']), {
host: 'localhost',
port: 555,
_: [],
$0: $0
});
t.end();
});
test('long captures eq', function(t) {
t.same(optimist.parse(['--host=localhost', '--port=555']), {
host: 'localhost',
port: 555,
_: [],
$0: $0
});
t.end();
});
test('mixed short bool and capture', function(t) {
t.same(optimist.parse(['-h', 'localhost', '-fp', '555', 'script.js']), {
f: true,
p: 555,
h: 'localhost',
_: ['script.js'],
$0: $0
});
t.end();
});
test('short and long', function(t) {
t.same(optimist.parse(['-h', 'localhost', '-fp', '555', 'script.js']), {
f: true,
p: 555,
h: 'localhost',
_: ['script.js'],
$0: $0
});
t.end();
});
test('no', function(t) {
t.same(optimist.parse(['--no-moo']), {
moo: false,
_: [],
$0: $0
});
t.end();
});
test('multi', function(t) {
t.same(optimist.parse(['-v', 'a', '-v', 'b', '-v', 'c']), {
v: ['a', 'b', 'c'],
_: [],
$0: $0
});
t.end();
});
test('comprehensive', function(t) {
t.same(optimist.parse(['--name=meowmers', 'bare', '-cats', 'woo', '-h', 'awesome', '--multi=quux', '--key', 'value', '-b', '--bool', '--no-meep', '--multi=baz', '--', '--not-a-flag', 'eek']), {
c: true,
a: true,
t: true,
s: 'woo',
h: 'awesome',
b: true,
bool: true,
key: 'value',
multi: ['quux', 'baz'],
meep: false,
name: 'meowmers',
_: ['bare', '--not-a-flag', 'eek'],
$0: $0
});
t.end();
});
test('nums', function(t) {
var argv = optimist.parse(['-x', '1234', '-y', '5.67', '-z', '1e7', '-w', '10f', '--hex', '0xdeadbeef', '789']);
t.same(argv, {
x: 1234,
y: 5.67,
z: 1e7,
w: '10f',
hex: 0xdeadbeef,
_: [789],
$0: $0
});
t.same(typeof argv.x, 'number');
t.same(typeof argv.y, 'number');
t.same(typeof argv.z, 'number');
t.same(typeof argv.w, 'string');
t.same(typeof argv.hex, 'number');
t.same(typeof argv._[0], 'number');
t.end();
});
test('flag boolean', function(t) {
var parse = optimist(['-t', 'moo']).boolean(['t']).argv;
t.same(parse, {
t: true,
_: ['moo'],
$0: $0
});
t.same(typeof parse.t, 'boolean');
t.end();
});
test('flag boolean value', function(t) {
var parse = optimist(['--verbose', 'false', 'moo', '-t', 'true']).boolean(['t', 'verbose']).default('verbose', true).argv;
t.same(parse, {
verbose: false,
t: true,
_: ['moo'],
$0: $0
});
t.same(typeof parse.verbose, 'boolean');
t.same(typeof parse.t, 'boolean');
t.end();
});
test('flag boolean default false', function(t) {
var parse = optimist(['moo']).boolean(['t', 'verbose']).default('verbose', false).default('t', false).argv;
t.same(parse, {
verbose: false,
t: false,
_: ['moo'],
$0: $0
});
t.same(typeof parse.verbose, 'boolean');
t.same(typeof parse.t, 'boolean');
t.end();
});
test('boolean groups', function(t) {
var parse = optimist(['-x', '-z', 'one', 'two', 'three']).boolean(['x', 'y', 'z']).argv;
t.same(parse, {
x: true,
y: false,
z: true,
_: ['one', 'two', 'three'],
$0: $0
});
t.same(typeof parse.x, 'boolean');
t.same(typeof parse.y, 'boolean');
t.same(typeof parse.z, 'boolean');
t.end();
});
test('newlines in params', function(t) {
var args = optimist.parse(['-s', "X\nX"]);
t.same(args, {
_: [],
s: "X\nX",
$0: $0
});
args = optimist.parse(["--s=X\nX"]);
t.same(args, {
_: [],
s: "X\nX",
$0: $0
});
t.end();
});
test('strings', function(t) {
var s = optimist(['-s', '0001234']).string('s').argv.s;
t.same(s, '0001234');
t.same(typeof s, 'string');
var x = optimist(['-x', '56']).string('x').argv.x;
t.same(x, '56');
t.same(typeof x, 'string');
t.end();
});
test('stringArgs', function(t) {
var s = optimist([' ', ' ']).string('_').argv._;
t.same(s.length, 2);
t.same(typeof s[0], 'string');
t.same(s[0], ' ');
t.same(typeof s[1], 'string');
t.same(s[1], ' ');
t.end();
});
test('slashBreak', function(t) {
t.same(optimist.parse(['-I/foo/bar/baz']), {
I: '/foo/bar/baz',
_: [],
$0: $0
});
t.same(optimist.parse(['-xyz/foo/bar/baz']), {
x: true,
y: true,
z: '/foo/bar/baz',
_: [],
$0: $0
});
t.end();
});
test('alias', function(t) {
var argv = optimist(['-f', '11', '--zoom', '55']).alias('z', 'zoom').argv;
;
t.equal(argv.zoom, 55);
t.equal(argv.z, argv.zoom);
t.equal(argv.f, 11);
t.end();
});
test('multiAlias', function(t) {
var argv = optimist(['-f', '11', '--zoom', '55']).alias('z', ['zm', 'zoom']).argv;
;
t.equal(argv.zoom, 55);
t.equal(argv.z, argv.zoom);
t.equal(argv.z, argv.zm);
t.equal(argv.f, 11);
t.end();
});
test('boolean default true', function(t) {
var argv = optimist.options({sometrue: {
boolean: true,
default: true
}}).argv;
t.equal(argv.sometrue, true);
t.end();
});
test('boolean default false', function(t) {
var argv = optimist.options({somefalse: {
boolean: true,
default: false
}}).argv;
t.equal(argv.somefalse, false);
t.end();
});
test('nested dotted objects', function(t) {
var argv = optimist(['--foo.bar', '3', '--foo.baz', '4', '--foo.quux.quibble', '5', '--foo.quux.o_O', '--beep.boop']).argv;
t.same(argv.foo, {
bar: 3,
baz: 4,
quux: {
quibble: 5,
o_O: true
}
});
t.same(argv.beep, {boop: true});
t.end();
});
test('boolean and alias with chainable api', function(t) {
var aliased = ['-h', 'derp'];
var regular = ['--herp', 'derp'];
var opts = {herp: {
alias: 'h',
boolean: true
}};
var aliasedArgv = optimist(aliased).boolean('herp').alias('h', 'herp').argv;
var propertyArgv = optimist(regular).boolean('herp').alias('h', 'herp').argv;
var expected = {
herp: true,
h: true,
'_': ['derp'],
'$0': $0
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias with options hash', function(t) {
var aliased = ['-h', 'derp'];
var regular = ['--herp', 'derp'];
var opts = {herp: {
alias: 'h',
boolean: true
}};
var aliasedArgv = optimist(aliased).options(opts).argv;
var propertyArgv = optimist(regular).options(opts).argv;
var expected = {
herp: true,
h: true,
'_': ['derp'],
'$0': $0
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias using explicit true', function(t) {
var aliased = ['-h', 'true'];
var regular = ['--herp', 'true'];
var opts = {herp: {
alias: 'h',
boolean: true
}};
var aliasedArgv = optimist(aliased).boolean('h').alias('h', 'herp').argv;
var propertyArgv = optimist(regular).boolean('h').alias('h', 'herp').argv;
var expected = {
herp: true,
h: true,
'_': [],
'$0': $0
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and --x=true', function(t) {
var parsed = optimist(['--boool', '--other=true']).boolean('boool').argv;
t.same(parsed.boool, true);
t.same(parsed.other, 'true');
parsed = optimist(['--boool', '--other=false']).boolean('boool').argv;
t.same(parsed.boool, true);
t.same(parsed.other, 'false');
t.end();
});
})(require("process"));
|
taylorzane/aurelia-firebase
|
jspm_packages/npm/optimist@0.3.7/test/parse.js
|
JavaScript
|
mit
| 9,740
|
import React from 'react';
import { string, node } from 'prop-types';
import classNames from 'classnames';
const TileSubtitle = ({ children, className, ...rest }) => {
return (
<p className={classNames('tile-subtitle', className)} {...rest}>
{children}
</p>
);
};
/**
* TileSubtitle property types.
*/
TileSubtitle.propTypes = {
className: string,
children: node
};
/**
* TileSubtitle default properties.
*/
TileSubtitle.defaultProps = {};
export default TileSubtitle;
|
Landish/react-spectre-css
|
src/components/TileSubtitle/TileSubtitle.js
|
JavaScript
|
mit
| 499
|
/* global describe it before */
var expect = require('expect.js')
describe('Test div position', function () {
before(function () {
var div = document.createElement('div')
div.id = 'foobar'
div.style.position = 'absolute'
div.style.top = '16px'
div.style.left = '320px'
document.body.appendChild(div)
})
it('should find a div at the right position', function () {
var div = document.querySelector('#foobar')
expect(div).to.be.an(window.HTMLDivElement)
var box = div.getClientRects()[0]
expect(box.top).to.be(16)
expect(box.left).to.be(320)
})
})
|
nodys/kawa
|
test/fixtures/divpos.test.js
|
JavaScript
|
mit
| 601
|
#!/usr/bin/env node
var yargs = require('yargs')
var fs = require('fs')
var githubNewRepo = require('../github-new-repo')
var argv = yargs
.usage('$0 - Create a new github repository')
.default('t', process.env.GITHUB_TOKEN)
.describe('t', 'Github token')
.alias('t', 'token')
.demand('n')
.describe('n', 'Repository name')
.alias('n', 'name')
.default('d', false)
.describe('d', 'Repository description')
.alias('d', 'desc')
.version(function () {
return fs.readFileSync('../package.json').version
})
.wrap(null)
.argv
githubNewRepo(argv.token, argv.name, argv.desc)
.then(function (data) {
console.log(JSON.stringify(data, null, 2))
process.exit(0)
})
.catch(function (e) {
console.log(e.message)
process.exit(1)
})
|
reggi/node-reggi
|
bin/github-new-repo.js
|
JavaScript
|
mit
| 775
|
KiddoPaint.Colors.Palette = {};
KiddoPaint.Colors.Current = {};
KiddoPaint.Colors.Palette.Blank = ['rgba(0, 0, 0, 0)'];
KiddoPaint.Colors.Palette.Bright = ['rgb(255,0,0)', 'rgb(255,255,0)', 'rgb(0,255,0)', 'rgb(0,0,255)', 'rgb(0,255,255)', 'rgb(255,0,255)'];
// these are len(pal)=32
KiddoPaint.Colors.Palette.Basic = [
'rgb(0, 0, 0)',
'rgb(255, 255, 255)',
'rgb(32, 32, 32)',
'rgb(64, 64, 64)',
'rgb(128, 128, 128)',
'rgb(192, 192, 192)',
// red
'rgb(128, 0, 0)',
'rgb(255, 0, 0)',
// yellow
'rgb(128, 128, 0)',
'rgb(255, 255, 1)',
// green
'rgb(0, 64, 64)',
'rgb(0, 100, 0)',
'rgb(0, 128, 0)',
'rgb(0, 255, 0)',
// cyan
'rgb(0, 128, 128)',
//lcyan
'rgb(128, 255, 255)',
//blue
'rgb(0, 0, 128)',
'rgb(0, 0, 255)',
//dblue
'rgb(0, 64, 128)',
//lblue
'rgb(0, 128, 255)',
//dpurple
'rgb(128, 0, 255)',
//lpurple
'rgb(128, 128, 255)',
//magenta
'rgb(128, 0, 128)',
'rgb(255, 0, 255)',
//redpink
'rgb(128, 0, 64)',
'rgb(255, 0, 128)',
//brown
'rgb(73, 61, 38)',
'rgb(136, 104, 67)',
//brown
'rgb(128, 64, 0)',
//lorange
'rgb(255, 128, 64)',
//orange
'rgb(225, 135, 0)',
'rgb(255, 195, 30)'
];
// https://lospec.com/palette-list/endesga-32
KiddoPaint.Colors.Palette.Endesga = ['rgb(24,20,37)', 'rgb(255,255,255)', 'rgb(190,74,47)', 'rgb(215,118,67)', 'rgb(234,212,170)', 'rgb(228,166,114)', 'rgb(184,111,80)', 'rgb(115,62,57)', 'rgb(62,39,49)', 'rgb(162,38,51)', 'rgb(228,59,68)', 'rgb(247,118,34)', 'rgb(254,174,52)', 'rgb(254,231,97)', 'rgb(99,199,77)', 'rgb(62,137,72)', 'rgb(38,92,66)', 'rgb(25,60,62)', 'rgb(18,78,137)', 'rgb(0,153,219)', 'rgb(44,232,245)', 'rgb(192,203,220)', 'rgb(139,155,180)', 'rgb(90,105,136)', 'rgb(58,68,102)', 'rgb(38,43,68)', 'rgb(255,0,68)', 'rgb(104,56,108)', 'rgb(181,80,136)', 'rgb(246,117,122)', 'rgb(232,183,150)', 'rgb(194,133,105)'];
// https://lospec.com/palette-list/dawnbringer-32
KiddoPaint.Colors.Palette.DawnBringer = ['rgb(0, 0, 0)', 'rgb(255, 255, 255)', 'rgb( 34 , 32 ,52 )', 'rgb( 69 , 40 ,60 )', 'rgb( 102 , 57 ,49 )', 'rgb( 143 , 86 ,59 )', 'rgb( 223 , 113 ,38 )', 'rgb( 217 , 160 ,102 )', 'rgb( 238 , 195 ,154 )', 'rgb( 251 , 242 ,54 )', 'rgb( 153 , 229 ,80 )', 'rgb( 106 , 190 ,48 )', 'rgb( 55 , 148 ,110 )', 'rgb( 75 , 105 ,47 )', 'rgb( 82 , 75 ,36 )', 'rgb( 50 , 60 ,57 )', 'rgb( 63 , 63 ,116 )', 'rgb( 48 , 96 ,130 )', 'rgb( 91 , 110 ,225 )', 'rgb( 99 , 155 ,255 )', 'rgb( 95 , 205 ,228 )', 'rgb( 203 , 219 ,252 )', 'rgb( 155 , 173 ,183 )', 'rgb( 132 , 126 ,135 )', 'rgb( 105 , 106 ,106 )', 'rgb( 89 , 86 ,82 )', 'rgb( 118 , 66 ,138 )', 'rgb( 172 , 50 ,50 )', 'rgb( 217 , 87 ,99 )', 'rgb( 215 , 123 ,186 )', 'rgb( 143 , 151 ,74 )', 'rgb( 138 , 111 ,48 )'];
// http://medialab.github.io/iwanthue/
KiddoPaint.Colors.Palette.Pastels = ["#84dcce", "#e8a2bd", "#9dd9b3", "#e5b8e7", "#d2f5c1", "#b8abe1", "#e0d59c", "#87afd9", "#f0b097", "#7cdfea", "#f7abb0", "#5cbbb7", "#cc9dc6", "#aed09e", "#f3daff", "#baab79", "#acd6ff", "#c5a780", "#5bb8cf", "#d1a189", "#acf9ff", "#c1a4b0", "#c8fff6", "#9eadbf", "#fffbe2", "#a6ada7", "#e5fff7", "#a7af93", "#dfe5ff", "#ffdfcb", "#fff5f8", "#ffe3ed"];
KiddoPaint.Colors.Palette.Pinks = ["#d170e6", "#984060", "#9d6fe8", "#e02f87", "#6d4bba", "#ea90b4", "#8a4bc8", "#e9a6db", "#9935b8", "#ba749c", "#b032a2", "#d6a5f2", "#b32c7c", "#a78ad1", "#af3b70", "#785bae", "#e969a2", "#72619d", "#db49af", "#864b6f", "#e97ad3", "#704889", "#c1589b", "#76409a", "#9a4876", "#9c52b5", "#8c588c", "#9c3d92", "#ba76b1", "#8c468c", "#b672c7", "#9166aa"];
KiddoPaint.Colors.Palette.Blues = ["#52e2ff", "#0065cd", "#83fae3", "#0e59ac", "#01ecf1", "#6d91fd", "#5cc4b1", "#596fbb", "#41ebff", "#0065a6", "#8df0fd", "#6b7abc", "#00988c", "#91a6ff", "#02c0c2", "#8cb0ff", "#46adb2", "#007cc5", "#02d8fd", "#476c9c", "#5ed5ff", "#006994", "#a3bdff", "#00a6c5", "#9ba6dd", "#69cae1", "#57b1ff", "#009dc4", "#6ec0ff", "#588cbb", "#00aeeb", "#0098dc"];
KiddoPaint.Colors.Palette.Greyscale = ['rgb(0, 0, 0)', 'rgb(8, 8, 8)', 'rgb(16, 16, 16)', 'rgb(24, 24, 24)', 'rgb(32, 32, 32)', 'rgb(40, 40, 40)', 'rgb(48, 48, 48)', 'rgb(56, 56, 56)', 'rgb(64, 64, 64)', 'rgb(72, 72, 72)', 'rgb(80, 80, 80)', 'rgb(88, 88, 88)', 'rgb(96, 96, 96)', 'rgb(104, 104, 104)', 'rgb(112, 112, 112)', 'rgb(120, 120, 120)', 'rgb(128, 128, 128)', 'rgb(136, 136, 136)', 'rgb(144, 144, 144)', 'rgb(152, 152, 152)', 'rgb(160, 160, 160)', 'rgb(168, 168, 168)', 'rgb(176, 176, 176)', 'rgb(184, 184, 184)', 'rgb(192, 192, 192)', 'rgb(200, 200, 200)', 'rgb(208, 208, 208)', 'rgb(216, 216, 216)', 'rgb(224, 224, 224)', 'rgb(232, 232, 232)', 'rgb(242, 242, 242)', 'rgb(255, 255, 255)'];
// https://coolors.co/gradient-palette/88ffff-ff44ff?number=30
KiddoPaint.Colors.Palette.CyanMagenta = ["#22FFFF", "#44FFFF", "#2AF7FF", "#31F0FF", "#39E8FF", "#40E1FF", "#48D9FF", "#50D1FF", "#57CAFF", "#5FC2FF", "#67BAFF", "#6EB3FF", "#76ABFF", "#7DA4FF", "#859CFF", "#8D94FF", "#948DFF", "#9C85FF", "#A47DFF", "#AB76FF", "#B36EFF", "#BA67FF", "#C25FFF", "#CA57FF", "#D150FF", "#D948FF", "#E140FF", "#E839FF", "#F031FF", "#F72AFF", "#FF88FF", "#FF22FF"];
KiddoPaint.Colors.All = [KiddoPaint.Colors.Palette.Basic,
KiddoPaint.Colors.Palette.DawnBringer,
KiddoPaint.Colors.Palette.Endesga,
KiddoPaint.Colors.Palette.Pastels,
KiddoPaint.Colors.Palette.Pinks,
KiddoPaint.Colors.Palette.Blues,
KiddoPaint.Colors.Palette.CyanMagenta,
KiddoPaint.Colors.Palette.Greyscale
]
KiddoPaint.Colors.Current.PaletteNumber = 0;
KiddoPaint.Colors.Current.Palette = KiddoPaint.Colors.All[KiddoPaint.Colors.Current.PaletteNumber];
KiddoPaint.Colors.rainbowPalette = function() {
var rpal = [];
if (KiddoPaint.Colors.Current.PaletteNumber == 0) {
rpal = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'violet'];
} else {
const cpal = KiddoPaint.Colors.currentPalette();
const offset = KiddoPaint.Colors.Current.PaletteNumber % 2;
rpal.push(cpal[0 + offset]);
rpal.push(cpal[4 + offset]);
rpal.push(cpal[8 + offset]);
rpal.push(cpal[12 + offset]);
rpal.push(cpal[16 + offset]);
rpal.push(cpal[20 + offset]);
rpal.push(cpal[30 + offset]);
}
return rpal;
}
KiddoPaint.Colors.currentPalette = function() {
return KiddoPaint.Colors.All[KiddoPaint.Colors.Current.PaletteNumber];
}
KiddoPaint.Colors.nextPalette = function() {
KiddoPaint.Colors.Current.PaletteNumber += 1;
if (KiddoPaint.Colors.Current.PaletteNumber >= KiddoPaint.Colors.All.length) {
KiddoPaint.Colors.Current.PaletteNumber = 0;
}
KiddoPaint.Colors.Current.Palette = KiddoPaint.Colors.All[KiddoPaint.Colors.Current.PaletteNumber];
return KiddoPaint.Colors.Current.Palette;
}
KiddoPaint.Colors.nextColor = function() {
return KiddoPaint.Colors.Palette.Bright[KiddoPaint.Display.step % KiddoPaint.Colors.Palette.Bright.length];
}
KiddoPaint.Colors.randomColor = function() {
return KiddoPaint.Colors.Palette.Bright[Math.floor(Math.random() * KiddoPaint.Colors.Palette.Bright.length)];
}
KiddoPaint.Colors.Current.colorStep = 0;
KiddoPaint.Colors.getAndIncColorStep = function() {
KiddoPaint.Colors.Current.colorStep += 1;
return KiddoPaint.Colors.Current.colorStep;
}
KiddoPaint.Colors.nextAllColor = function() {
var pal = KiddoPaint.Colors.currentPalette();
return pal[KiddoPaint.Colors.getAndIncColorStep() % pal.length];
}
KiddoPaint.Colors.randomAllColor = function() {
var pal = KiddoPaint.Colors.currentPalette();
return pal[Math.floor(Math.random() * pal.length)];
}
function getColorIndicesForCoord(x, y, width) {
var red = y * (width * 4) + x * 4;
return [red, red + 1, red + 2, red + 3];
}
|
vikrum/kiddopaint
|
js/util/colors.js
|
JavaScript
|
mit
| 7,892
|
import Router from 'koa-router';
import controller from '../controllers/passport';
import config from 'config/server';
let providers = config.authentification.providers;
let router = new Router();
let strategies = Object.keys(providers);
router.get('login', '/login', controller.login);
router.get('register', '/register', controller.register);
strategies.forEach( medium => {
router.get('passport.login.' + medium, '/login/:medium/', controller.authentificate);
router.get('passport.login.' + medium + '.cb', '/login/:medium/callback', controller.authentificateCB);
router.get('passport.logout', '/logout', controller.logout );
});
router.get('get_token', '/mytoken/', controller.getToken);
module.exports = router;
|
tilap/piggy
|
src/app/web/server/routers/passport.js
|
JavaScript
|
mit
| 729
|
import React from 'react';
import styled from 'styled-components';
const RadioLabel = styled.label`
display: inline-block;
cursor: pointer;
position: relative;
padding-left: 25px;
margin-right: 15px;
font-size: 13px;
font-weight: bold;
color: #44413D;
&:before {
content: "";
display: inline-block;
border-radius: 8px;
width: 16px;
height: 16px;
margin-right: 10px;
position: absolute;
left: 0;
bottom: 1px;
background-color: #aaa;
box-shadow: inset 0px 2px 3px 0px rgba(68, 65, 61, .3), 0px 1px 0px 0px rgba(180, 176, 172, .8);
}
`;
const RadioInput = styled.input`
display: none;
&:checked + label::before {
content: '\\2022';
color: #44413D;
font-size: 30px;
text-align: center;
line-height: 18px;
}
`;
class RadioGroup extends React.Component {
render() {
return (<div>
{this.props.items.map((item, i) => {
return (<span>
<RadioInput id={ item } type="radio" name={this.props.name} value={ item } onChange={this.props.onChange} />
<RadioLabel htmlFor={ item }>{ item }</RadioLabel>
</span>)
})}
</div> )
}
}
export default RadioGroup;
|
sepro/React-Gallery
|
src/js/components/radiobuttons.js
|
JavaScript
|
mit
| 1,382
|