code
stringlengths 2
1.05M
|
---|
var Parser = require('jsonparse')
, Stream = require('stream').Stream
, through = require('through')
/*
the value of this.stack that creationix's jsonparse has is weird.
it makes this code ugly, but his problem is way harder that mine,
so i'll forgive him.
*/
exports.parse = function (path) {
var parser = new Parser()
var stream = through(function (chunk) {
if('string' === typeof chunk) {
if (process.browser) {
var buf = new Array(chunk.length)
for (var i = 0; i < chunk.length; i++) buf[i] = chunk.charCodeAt(i)
chunk = new Int32Array(buf)
} else {
chunk = new Buffer(chunk)
}
}
parser.write(chunk)
},
function (data) {
if(data)
stream.write(data)
stream.queue(null)
})
if('string' === typeof path)
path = path.split('.').map(function (e) {
if (e === '*')
return true
else if (e === '') // '..'.split('.') returns an empty string
return {recurse: true}
else
return e
})
var count = 0, _key
if(!path || !path.length)
path = null
parser.onValue = function () {
if (!this.root && this.stack.length == 1)
stream.root = this.value
if(! path) return
var i = 0 // iterates on path
var j = 0 // iterates on stack
while (i < path.length) {
var key = path[i]
var c
j++
if (key && !key.recurse) {
c = (j === this.stack.length) ? this : this.stack[j]
if (!c) return
if (! check(key, c.key)) return
i++
} else {
i++
var nextKey = path[i]
if (! nextKey) return
while (true) {
c = (j === this.stack.length) ? this : this.stack[j]
if (!c) return
if (check(nextKey, c.key)) { i++; break}
j++
}
}
}
if (j !== this.stack.length) return
count ++
stream.queue(this.value[this.key])
delete this.value[this.key]
}
parser._onToken = parser.onToken;
parser.onToken = function (token, value) {
parser._onToken(token, value);
if (this.stack.length === 0) {
if (stream.root) {
if(!path)
stream.queue(stream.root)
stream.emit('root', stream.root, count)
count = 0;
stream.root = null;
}
}
}
parser.onError = function (err) {
stream.emit('error', err)
}
return stream
}
function check (x, y) {
if ('string' === typeof x)
return y == x
else if (x && 'function' === typeof x.exec)
return x.exec(y)
else if ('boolean' === typeof x)
return x
else if ('function' === typeof x)
return x(y)
return false
}
exports.stringify = function (op, sep, cl) {
if (op === false){
op = ''
sep = '\n'
cl = ''
} else if (op == null) {
op = '[\n'
sep = '\n,\n'
cl = '\n]\n'
}
//else, what ever you like
var stream
, first = true
, anyData = false
stream = through(function (data) {
anyData = true
var json = JSON.stringify(data)
if(first) { first = false ; stream.queue(op + json)}
else stream.queue(sep + json)
},
function (data) {
if(!anyData)
stream.queue(op)
stream.queue(cl)
stream.queue(null)
})
return stream
}
exports.stringifyObject = function (op, sep, cl) {
if (op === false){
op = ''
sep = '\n'
cl = ''
} else if (op == null) {
op = '{\n'
sep = '\n,\n'
cl = '\n}\n'
}
//else, what ever you like
var stream = new Stream ()
, first = true
, anyData = false
stream = through(function (data) {
anyData = true
var json = JSON.stringify(data[0]) + ':' + JSON.stringify(data[1])
if(first) { first = false ; stream.queue(op + json)}
else stream.queue(sep + json)
},
function (data) {
if(!anyData) stream.queue(op)
stream.queue(cl)
stream.queue(null)
})
return stream
}
|
/*!
* jQuery UI Accordion 1.9.2
* http://jqueryui.com
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/accordion/
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function( $, undefined ) {
var uid = 0,
hideProps = {},
showProps = {};
hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
showProps.height = showProps.paddingTop = showProps.paddingBottom =
showProps.borderTopWidth = showProps.borderBottomWidth = "show";
$.widget( "ui.accordion", {
version: "1.9.2",
options: {
active: 0,
animate: {},
collapsible: false,
event: "click",
header: "> li > :first-child,> :not(li):even",
heightStyle: "auto",
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
},
// callbacks
activate: null,
beforeActivate: null
},
_create: function() {
var accordionId = this.accordionId = "ui-accordion-" +
(this.element.attr( "id" ) || ++uid),
options = this.options;
this.prevShow = this.prevHide = $();
this.element.addClass( "ui-accordion ui-widget ui-helper-reset" );
this.headers = this.element.find( options.header )
.addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" );
this._hoverable( this.headers );
this._focusable( this.headers );
this.headers.next()
.addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
.hide();
// don't allow collapsible: false and active: false / null
if ( !options.collapsible && (options.active === false || options.active == null) ) {
options.active = 0;
}
// handle negative values
if ( options.active < 0 ) {
options.active += this.headers.length;
}
this.active = this._findActive( options.active )
.addClass( "ui-accordion-header-active ui-state-active" )
.toggleClass( "ui-corner-all ui-corner-top" );
this.active.next()
.addClass( "ui-accordion-content-active" )
.show();
this._createIcons();
this.refresh();
// ARIA
this.element.attr( "role", "tablist" );
this.headers
.attr( "role", "tab" )
.each(function( i ) {
var header = $( this ),
headerId = header.attr( "id" ),
panel = header.next(),
panelId = panel.attr( "id" );
if ( !headerId ) {
headerId = accordionId + "-header-" + i;
header.attr( "id", headerId );
}
if ( !panelId ) {
panelId = accordionId + "-panel-" + i;
panel.attr( "id", panelId );
}
header.attr( "aria-controls", panelId );
panel.attr( "aria-labelledby", headerId );
})
.next()
.attr( "role", "tabpanel" );
this.headers
.not( this.active )
.attr({
"aria-selected": "false",
tabIndex: -1
})
.next()
.attr({
"aria-expanded": "false",
"aria-hidden": "true"
})
.hide();
// make sure at least one header is in the tab order
if ( !this.active.length ) {
this.headers.eq( 0 ).attr( "tabIndex", 0 );
} else {
this.active.attr({
"aria-selected": "true",
tabIndex: 0
})
.next()
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
}
this._on( this.headers, { keydown: "_keydown" });
this._on( this.headers.next(), { keydown: "_panelKeyDown" });
this._setupEvents( options.event );
},
_getCreateEventData: function() {
return {
header: this.active,
content: !this.active.length ? $() : this.active.next()
};
},
_createIcons: function() {
var icons = this.options.icons;
if ( icons ) {
$( "<span>" )
.addClass( "ui-accordion-header-icon ui-icon " + icons.header )
.prependTo( this.headers );
this.active.children( ".ui-accordion-header-icon" )
.removeClass( icons.header )
.addClass( icons.activeHeader );
this.headers.addClass( "ui-accordion-icons" );
}
},
_destroyIcons: function() {
this.headers
.removeClass( "ui-accordion-icons" )
.children( ".ui-accordion-header-icon" )
.remove();
},
_destroy: function() {
var contents;
// clean up main element
this.element
.removeClass( "ui-accordion ui-widget ui-helper-reset" )
.removeAttr( "role" );
// clean up headers
this.headers
.removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
.removeAttr( "role" )
.removeAttr( "aria-selected" )
.removeAttr( "aria-controls" )
.removeAttr( "tabIndex" )
.each(function() {
if ( /^ui-accordion/.test( this.id ) ) {
this.removeAttribute( "id" );
}
});
this._destroyIcons();
// clean up content panels
contents = this.headers.next()
.css( "display", "" )
.removeAttr( "role" )
.removeAttr( "aria-expanded" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-labelledby" )
.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" )
.each(function() {
if ( /^ui-accordion/.test( this.id ) ) {
this.removeAttribute( "id" );
}
});
if ( this.options.heightStyle !== "content" ) {
contents.css( "height", "" );
}
},
_setOption: function( key, value ) {
if ( key === "active" ) {
// _activate() will handle invalid values and update this.options
this._activate( value );
return;
}
if ( key === "event" ) {
if ( this.options.event ) {
this._off( this.headers, this.options.event );
}
this._setupEvents( value );
}
this._super( key, value );
// setting collapsible: false while collapsed; open first panel
if ( key === "collapsible" && !value && this.options.active === false ) {
this._activate( 0 );
}
if ( key === "icons" ) {
this._destroyIcons();
if ( value ) {
this._createIcons();
}
}
// #5332 - opacity doesn't cascade to positioned elements in IE
// so we need to add the disabled class to the headers and panels
if ( key === "disabled" ) {
this.headers.add( this.headers.next() )
.toggleClass( "ui-state-disabled", !!value );
}
},
_keydown: function( event ) {
if ( event.altKey || event.ctrlKey ) {
return;
}
var keyCode = $.ui.keyCode,
length = this.headers.length,
currentIndex = this.headers.index( event.target ),
toFocus = false;
switch ( event.keyCode ) {
case keyCode.RIGHT:
case keyCode.DOWN:
toFocus = this.headers[ ( currentIndex + 1 ) % length ];
break;
case keyCode.LEFT:
case keyCode.UP:
toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
break;
case keyCode.SPACE:
case keyCode.ENTER:
this._eventHandler( event );
break;
case keyCode.HOME:
toFocus = this.headers[ 0 ];
break;
case keyCode.END:
toFocus = this.headers[ length - 1 ];
break;
}
if ( toFocus ) {
$( event.target ).attr( "tabIndex", -1 );
$( toFocus ).attr( "tabIndex", 0 );
toFocus.focus();
event.preventDefault();
}
},
_panelKeyDown : function( event ) {
if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
$( event.currentTarget ).prev().focus();
}
},
refresh: function() {
var maxHeight, overflow,
heightStyle = this.options.heightStyle,
parent = this.element.parent();
if ( heightStyle === "fill" ) {
// IE 6 treats height like minHeight, so we need to turn off overflow
// in order to get a reliable height
// we use the minHeight support test because we assume that only
// browsers that don't support minHeight will treat height as minHeight
if ( !$.support.minHeight ) {
overflow = parent.css( "overflow" );
parent.css( "overflow", "hidden");
}
maxHeight = parent.height();
this.element.siblings( ":visible" ).each(function() {
var elem = $( this ),
position = elem.css( "position" );
if ( position === "absolute" || position === "fixed" ) {
return;
}
maxHeight -= elem.outerHeight( true );
});
if ( overflow ) {
parent.css( "overflow", overflow );
}
this.headers.each(function() {
maxHeight -= $( this ).outerHeight( true );
});
this.headers.next()
.each(function() {
$( this ).height( Math.max( 0, maxHeight -
$( this ).innerHeight() + $( this ).height() ) );
})
.css( "overflow", "auto" );
} else if ( heightStyle === "auto" ) {
maxHeight = 0;
this.headers.next()
.each(function() {
maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
})
.height( maxHeight );
}
},
_activate: function( index ) {
var active = this._findActive( index )[ 0 ];
// trying to activate the already active panel
if ( active === this.active[ 0 ] ) {
return;
}
// trying to collapse, simulate a click on the currently active header
active = active || this.active[ 0 ];
this._eventHandler({
target: active,
currentTarget: active,
preventDefault: $.noop
});
},
_findActive: function( selector ) {
return typeof selector === "number" ? this.headers.eq( selector ) : $();
},
_setupEvents: function( event ) {
var events = {};
if ( !event ) {
return;
}
$.each( event.split(" "), function( index, eventName ) {
events[ eventName ] = "_eventHandler";
});
this._on( this.headers, events );
},
_eventHandler: function( event ) {
var options = this.options,
active = this.active,
clicked = $( event.currentTarget ),
clickedIsActive = clicked[ 0 ] === active[ 0 ],
collapsing = clickedIsActive && options.collapsible,
toShow = collapsing ? $() : clicked.next(),
toHide = active.next(),
eventData = {
oldHeader: active,
oldPanel: toHide,
newHeader: collapsing ? $() : clicked,
newPanel: toShow
};
event.preventDefault();
if (
// click on active header, but not collapsible
( clickedIsActive && !options.collapsible ) ||
// allow canceling activation
( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
return;
}
options.active = collapsing ? false : this.headers.index( clicked );
// when the call to ._toggle() comes after the class changes
// it causes a very odd bug in IE 8 (see #6720)
this.active = clickedIsActive ? $() : clicked;
this._toggle( eventData );
// switch classes
// corner classes on the previously active header stay after the animation
active.removeClass( "ui-accordion-header-active ui-state-active" );
if ( options.icons ) {
active.children( ".ui-accordion-header-icon" )
.removeClass( options.icons.activeHeader )
.addClass( options.icons.header );
}
if ( !clickedIsActive ) {
clicked
.removeClass( "ui-corner-all" )
.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
if ( options.icons ) {
clicked.children( ".ui-accordion-header-icon" )
.removeClass( options.icons.header )
.addClass( options.icons.activeHeader );
}
clicked
.next()
.addClass( "ui-accordion-content-active" );
}
},
_toggle: function( data ) {
var toShow = data.newPanel,
toHide = this.prevShow.length ? this.prevShow : data.oldPanel;
// handle activating a panel during the animation for another activation
this.prevShow.add( this.prevHide ).stop( true, true );
this.prevShow = toShow;
this.prevHide = toHide;
if ( this.options.animate ) {
this._animate( toShow, toHide, data );
} else {
toHide.hide();
toShow.show();
this._toggleComplete( data );
}
toHide.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
toHide.prev().attr( "aria-selected", "false" );
// if we're switching panels, remove the old header from the tab order
// if we're opening from collapsed state, remove the previous header from the tab order
// if we're collapsing, then keep the collapsing header in the tab order
if ( toShow.length && toHide.length ) {
toHide.prev().attr( "tabIndex", -1 );
} else if ( toShow.length ) {
this.headers.filter(function() {
return $( this ).attr( "tabIndex" ) === 0;
})
.attr( "tabIndex", -1 );
}
toShow
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
})
.prev()
.attr({
"aria-selected": "true",
tabIndex: 0
});
},
_animate: function( toShow, toHide, data ) {
var total, easing, duration,
that = this,
adjust = 0,
down = toShow.length &&
( !toHide.length || ( toShow.index() < toHide.index() ) ),
animate = this.options.animate || {},
options = down && animate.down || animate,
complete = function() {
that._toggleComplete( data );
};
if ( typeof options === "number" ) {
duration = options;
}
if ( typeof options === "string" ) {
easing = options;
}
// fall back from options to animation in case of partial down settings
easing = easing || options.easing || animate.easing;
duration = duration || options.duration || animate.duration;
if ( !toHide.length ) {
return toShow.animate( showProps, duration, easing, complete );
}
if ( !toShow.length ) {
return toHide.animate( hideProps, duration, easing, complete );
}
total = toShow.show().outerHeight();
toHide.animate( hideProps, {
duration: duration,
easing: easing,
step: function( now, fx ) {
fx.now = Math.round( now );
}
});
toShow
.hide()
.animate( showProps, {
duration: duration,
easing: easing,
complete: complete,
step: function( now, fx ) {
fx.now = Math.round( now );
if ( fx.prop !== "height" ) {
adjust += fx.now;
} else if ( that.options.heightStyle !== "content" ) {
fx.now = Math.round( total - toHide.outerHeight() - adjust );
adjust = 0;
}
}
});
},
_toggleComplete: function( data ) {
var toHide = data.oldPanel;
toHide
.removeClass( "ui-accordion-content-active" )
.prev()
.removeClass( "ui-corner-top" )
.addClass( "ui-corner-all" );
// Work around for rendering bug in IE (#5421)
if ( toHide.length ) {
toHide.parent()[0].className = toHide.parent()[0].className;
}
this._trigger( "activate", null, data );
}
});
// DEPRECATED
if ( $.uiBackCompat !== false ) {
// navigation options
(function( $, prototype ) {
$.extend( prototype.options, {
navigation: false,
navigationFilter: function() {
return this.href.toLowerCase() === location.href.toLowerCase();
}
});
var _create = prototype._create;
prototype._create = function() {
if ( this.options.navigation ) {
var that = this,
headers = this.element.find( this.options.header ),
content = headers.next(),
current = headers.add( content )
.find( "a" )
.filter( this.options.navigationFilter )
[ 0 ];
if ( current ) {
headers.add( content ).each( function( index ) {
if ( $.contains( this, current ) ) {
that.options.active = Math.floor( index / 2 );
return false;
}
});
}
}
_create.call( this );
};
}( jQuery, jQuery.ui.accordion.prototype ) );
// height options
(function( $, prototype ) {
$.extend( prototype.options, {
heightStyle: null, // remove default so we fall back to old values
autoHeight: true, // use heightStyle: "auto"
clearStyle: false, // use heightStyle: "content"
fillSpace: false // use heightStyle: "fill"
});
var _create = prototype._create,
_setOption = prototype._setOption;
$.extend( prototype, {
_create: function() {
this.options.heightStyle = this.options.heightStyle ||
this._mergeHeightStyle();
_create.call( this );
},
_setOption: function( key ) {
if ( key === "autoHeight" || key === "clearStyle" || key === "fillSpace" ) {
this.options.heightStyle = this._mergeHeightStyle();
}
_setOption.apply( this, arguments );
},
_mergeHeightStyle: function() {
var options = this.options;
if ( options.fillSpace ) {
return "fill";
}
if ( options.clearStyle ) {
return "content";
}
if ( options.autoHeight ) {
return "auto";
}
}
});
}( jQuery, jQuery.ui.accordion.prototype ) );
// icon options
(function( $, prototype ) {
$.extend( prototype.options.icons, {
activeHeader: null, // remove default so we fall back to old values
headerSelected: "ui-icon-triangle-1-s"
});
var _createIcons = prototype._createIcons;
prototype._createIcons = function() {
if ( this.options.icons ) {
this.options.icons.activeHeader = this.options.icons.activeHeader ||
this.options.icons.headerSelected;
}
_createIcons.call( this );
};
}( jQuery, jQuery.ui.accordion.prototype ) );
// expanded active option, activate method
(function( $, prototype ) {
prototype.activate = prototype._activate;
var _findActive = prototype._findActive;
prototype._findActive = function( index ) {
if ( index === -1 ) {
index = false;
}
if ( index && typeof index !== "number" ) {
index = this.headers.index( this.headers.filter( index ) );
if ( index === -1 ) {
index = false;
}
}
return _findActive.call( this, index );
};
}( jQuery, jQuery.ui.accordion.prototype ) );
// resize method
jQuery.ui.accordion.prototype.resize = jQuery.ui.accordion.prototype.refresh;
// change events
(function( $, prototype ) {
$.extend( prototype.options, {
change: null,
changestart: null
});
var _trigger = prototype._trigger;
prototype._trigger = function( type, event, data ) {
var ret = _trigger.apply( this, arguments );
if ( !ret ) {
return false;
}
if ( type === "beforeActivate" ) {
ret = _trigger.call( this, "changestart", event, {
oldHeader: data.oldHeader,
oldContent: data.oldPanel,
newHeader: data.newHeader,
newContent: data.newPanel
});
} else if ( type === "activate" ) {
ret = _trigger.call( this, "change", event, {
oldHeader: data.oldHeader,
oldContent: data.oldPanel,
newHeader: data.newHeader,
newContent: data.newPanel
});
}
return ret;
};
}( jQuery, jQuery.ui.accordion.prototype ) );
// animated option
// NOTE: this only provides support for "slide", "bounceslide", and easings
// not the full $.ui.accordion.animations API
(function( $, prototype ) {
$.extend( prototype.options, {
animate: null,
animated: "slide"
});
var _create = prototype._create;
prototype._create = function() {
var options = this.options;
if ( options.animate === null ) {
if ( !options.animated ) {
options.animate = false;
} else if ( options.animated === "slide" ) {
options.animate = 300;
} else if ( options.animated === "bounceslide" ) {
options.animate = {
duration: 200,
down: {
easing: "easeOutBounce",
duration: 1000
}
};
} else {
options.animate = options.animated;
}
}
_create.call( this );
};
}( jQuery, jQuery.ui.accordion.prototype ) );
}
})( jQuery );
|
/**
* @fileoverview Abstraction of JavaScript source code.
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const TokenStore = require("../token-store"),
Traverser = require("./traverser"),
astUtils = require("../ast-utils"),
lodash = require("lodash");
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
/**
* Validates that the given AST has the required information.
* @param {ASTNode} ast The Program node of the AST to check.
* @throws {Error} If the AST doesn't contain the correct information.
* @returns {void}
* @private
*/
function validate(ast) {
if (!ast.tokens) {
throw new Error("AST is missing the tokens array.");
}
if (!ast.comments) {
throw new Error("AST is missing the comments array.");
}
if (!ast.loc) {
throw new Error("AST is missing location information.");
}
if (!ast.range) {
throw new Error("AST is missing range information");
}
}
/**
* Finds a JSDoc comment node in an array of comment nodes.
* @param {ASTNode[]} comments The array of comment nodes to search.
* @param {int} line Line number to look around
* @returns {ASTNode} The node if found, null if not.
* @private
*/
function findJSDocComment(comments, line) {
if (comments) {
for (let i = comments.length - 1; i >= 0; i--) {
if (comments[i].type === "Block" && comments[i].value.charAt(0) === "*") {
if (line - comments[i].loc.end.line <= 1) {
return comments[i];
}
break;
}
}
}
return null;
}
/**
* Check to see if its a ES6 export declaration
* @param {ASTNode} astNode - any node
* @returns {boolean} whether the given node represents a export declaration
* @private
*/
function looksLikeExport(astNode) {
return astNode.type === "ExportDefaultDeclaration" || astNode.type === "ExportNamedDeclaration" ||
astNode.type === "ExportAllDeclaration" || astNode.type === "ExportSpecifier";
}
/**
* Merges two sorted lists into a larger sorted list in O(n) time
* @param {Token[]} tokens The list of tokens
* @param {Token[]} comments The list of comments
* @returns {Token[]} A sorted list of tokens and comments
*/
function sortedMerge(tokens, comments) {
const result = [];
let tokenIndex = 0;
let commentIndex = 0;
while (tokenIndex < tokens.length || commentIndex < comments.length) {
if (commentIndex >= comments.length || tokenIndex < tokens.length && tokens[tokenIndex].range[0] < comments[commentIndex].range[0]) {
result.push(tokens[tokenIndex++]);
} else {
result.push(comments[commentIndex++]);
}
}
return result;
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Represents parsed source code.
* @param {string} text - The source code text.
* @param {ASTNode} ast - The Program node of the AST representing the code. This AST should be created from the text that BOM was stripped.
* @constructor
*/
function SourceCode(text, ast) {
validate(ast);
/**
* The flag to indicate that the source code has Unicode BOM.
* @type boolean
*/
this.hasBOM = (text.charCodeAt(0) === 0xFEFF);
/**
* The original text source code.
* BOM was stripped from this text.
* @type string
*/
this.text = (this.hasBOM ? text.slice(1) : text);
/**
* The parsed AST for the source code.
* @type ASTNode
*/
this.ast = ast;
/**
* The source code split into lines according to ECMA-262 specification.
* This is done to avoid each rule needing to do so separately.
* @type string[]
*/
this.lines = [];
this.lineStartIndices = [0];
const lineEndingPattern = astUtils.createGlobalLinebreakMatcher();
let match;
/*
* Previously, this was implemented using a regex that
* matched a sequence of non-linebreak characters followed by a
* linebreak, then adding the lengths of the matches. However,
* this caused a catastrophic backtracking issue when the end
* of a file contained a large number of non-newline characters.
* To avoid this, the current implementation just matches newlines
* and uses match.index to get the correct line start indices.
*/
while ((match = lineEndingPattern.exec(this.text))) {
this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1], match.index));
this.lineStartIndices.push(match.index + match[0].length);
}
this.lines.push(this.text.slice(this.lineStartIndices[this.lineStartIndices.length - 1]));
this.tokensAndComments = sortedMerge(ast.tokens, ast.comments);
// create token store methods
const tokenStore = new TokenStore(ast.tokens, ast.comments);
for (const methodName of TokenStore.PUBLIC_METHODS) {
this[methodName] = tokenStore[methodName].bind(tokenStore);
}
// don't allow modification of this object
Object.freeze(this);
Object.freeze(this.lines);
}
/**
* Split the source code into multiple lines based on the line delimiters
* @param {string} text Source code as a string
* @returns {string[]} Array of source code lines
* @public
*/
SourceCode.splitLines = function(text) {
return text.split(astUtils.createGlobalLinebreakMatcher());
};
SourceCode.prototype = {
constructor: SourceCode,
/**
* Gets the source code for the given node.
* @param {ASTNode=} node The AST node to get the text for.
* @param {int=} beforeCount The number of characters before the node to retrieve.
* @param {int=} afterCount The number of characters after the node to retrieve.
* @returns {string} The text representing the AST node.
*/
getText(node, beforeCount, afterCount) {
if (node) {
return this.text.slice(Math.max(node.range[0] - (beforeCount || 0), 0),
node.range[1] + (afterCount || 0));
}
return this.text;
},
/**
* Gets the entire source text split into an array of lines.
* @returns {Array} The source text as an array of lines.
*/
getLines() {
return this.lines;
},
/**
* Retrieves an array containing all comments in the source code.
* @returns {ASTNode[]} An array of comment nodes.
*/
getAllComments() {
return this.ast.comments;
},
/**
* Gets all comments for the given node.
* @param {ASTNode} node The AST node to get the comments for.
* @returns {Object} The list of comments indexed by their position.
* @public
*/
getComments(node) {
let leadingComments = node.leadingComments || [];
const trailingComments = node.trailingComments || [];
/*
* espree adds a "comments" array on Program nodes rather than
* leadingComments/trailingComments. Comments are only left in the
* Program node comments array if there is no executable code.
*/
if (node.type === "Program") {
if (node.body.length === 0) {
leadingComments = node.comments;
}
}
return {
leading: leadingComments,
trailing: trailingComments
};
},
/**
* Retrieves the JSDoc comment for a given node.
* @param {ASTNode} node The AST node to get the comment for.
* @returns {ASTNode} The BlockComment node containing the JSDoc for the
* given node or null if not found.
* @public
*/
getJSDocComment(node) {
let parent = node.parent;
switch (node.type) {
case "ClassDeclaration":
case "FunctionDeclaration":
if (looksLikeExport(parent)) {
return findJSDocComment(parent.leadingComments, parent.loc.start.line);
}
return findJSDocComment(node.leadingComments, node.loc.start.line);
case "ClassExpression":
return findJSDocComment(parent.parent.leadingComments, parent.parent.loc.start.line);
case "ArrowFunctionExpression":
case "FunctionExpression":
if (parent.type !== "CallExpression" && parent.type !== "NewExpression") {
while (parent && !parent.leadingComments && !/Function/.test(parent.type) && parent.type !== "MethodDefinition" && parent.type !== "Property") {
parent = parent.parent;
}
return parent && (parent.type !== "FunctionDeclaration") ? findJSDocComment(parent.leadingComments, parent.loc.start.line) : null;
} else if (node.leadingComments) {
return findJSDocComment(node.leadingComments, node.loc.start.line);
}
// falls through
default:
return null;
}
},
/**
* Gets the deepest node containing a range index.
* @param {int} index Range index of the desired node.
* @returns {ASTNode} The node if found or null if not found.
*/
getNodeByRangeIndex(index) {
let result = null,
resultParent = null;
const traverser = new Traverser();
traverser.traverse(this.ast, {
enter(node, parent) {
if (node.range[0] <= index && index < node.range[1]) {
result = node;
resultParent = parent;
} else {
this.skip();
}
},
leave(node) {
if (node === result) {
this.break();
}
}
});
return result ? Object.assign({ parent: resultParent }, result) : null;
},
/**
* Determines if two tokens have at least one whitespace character
* between them. This completely disregards comments in making the
* determination, so comments count as zero-length substrings.
* @param {Token} first The token to check after.
* @param {Token} second The token to check before.
* @returns {boolean} True if there is only space between tokens, false
* if there is anything other than whitespace between tokens.
*/
isSpaceBetweenTokens(first, second) {
const text = this.text.slice(first.range[1], second.range[0]);
return /\s/.test(text.replace(/\/\*.*?\*\//g, ""));
},
/**
* Converts a source text index into a (line, column) pair.
* @param {number} index The index of a character in a file
* @returns {Object} A {line, column} location object with a 0-indexed column
*/
getLocFromIndex(index) {
if (typeof index !== "number") {
throw new TypeError("Expected `index` to be a number.");
}
if (index < 0 || index > this.text.length) {
throw new RangeError(`Index out of range (requested index ${index}, but source text has length ${this.text.length}).`);
}
/*
* For an argument of this.text.length, return the location one "spot" past the last character
* of the file. If the last character is a linebreak, the location will be column 0 of the next
* line; otherwise, the location will be in the next column on the same line.
*
* See getIndexFromLoc for the motivation for this special case.
*/
if (index === this.text.length) {
return { line: this.lines.length, column: this.lines[this.lines.length - 1].length };
}
/*
* To figure out which line rangeIndex is on, determine the last index at which rangeIndex could
* be inserted into lineIndices to keep the list sorted.
*/
const lineNumber = lodash.sortedLastIndex(this.lineStartIndices, index);
return { line: lineNumber, column: index - this.lineStartIndices[lineNumber - 1] };
},
/**
* Converts a (line, column) pair into a range index.
* @param {Object} loc A line/column location
* @param {number} loc.line The line number of the location (1-indexed)
* @param {number} loc.column The column number of the location (0-indexed)
* @returns {number} The range index of the location in the file.
*/
getIndexFromLoc(loc) {
if (typeof loc !== "object" || typeof loc.line !== "number" || typeof loc.column !== "number") {
throw new TypeError("Expected `loc` to be an object with numeric `line` and `column` properties.");
}
if (loc.line <= 0) {
throw new RangeError(`Line number out of range (line ${loc.line} requested). Line numbers should be 1-based.`);
}
if (loc.line > this.lineStartIndices.length) {
throw new RangeError(`Line number out of range (line ${loc.line} requested, but only ${this.lineStartIndices.length} lines present).`);
}
const lineStartIndex = this.lineStartIndices[loc.line - 1];
const lineEndIndex = loc.line === this.lineStartIndices.length ? this.text.length : this.lineStartIndices[loc.line];
const positionIndex = lineStartIndex + loc.column;
/*
* By design, getIndexFromLoc({ line: lineNum, column: 0 }) should return the start index of
* the given line, provided that the line number is valid element of this.lines. Since the
* last element of this.lines is an empty string for files with trailing newlines, add a
* special case where getting the index for the first location after the end of the file
* will return the length of the file, rather than throwing an error. This allows rules to
* use getIndexFromLoc consistently without worrying about edge cases at the end of a file.
*/
if (
loc.line === this.lineStartIndices.length && positionIndex > lineEndIndex ||
loc.line < this.lineStartIndices.length && positionIndex >= lineEndIndex
) {
throw new RangeError(`Column number out of range (column ${loc.column} requested, but the length of line ${loc.line} is ${lineEndIndex - lineStartIndex}).`);
}
return positionIndex;
}
};
module.exports = SourceCode;
|
MessageFormat.locale.ko=function(n){return "other"}
|
YUI.add('plugin', function(Y) {
/**
* Provides the base Plugin class, which plugin developers should extend, when creating custom plugins
*
* @module plugin
*/
/**
* The base class for all Plugin instances.
*
* @class Plugin.Base
* @extends Base
* @param {Object} config Configuration object with property name/value pairs.
*/
function Plugin(config) {
Plugin.superclass.constructor.apply(this, arguments);
}
/**
* Object defining the set of attributes supported by the Plugin.Base class
*
* @property Plugin.Base.ATTRS
* @type Object
* @static
*/
Plugin.ATTRS = {
/**
* The plugin's host object.
*
* @attribute host
* @writeonce
* @type Plugin.Host
*/
host : {
writeOnce: true
}
};
/**
* The string identifying the Plugin.Base class. Plugins extending
* Plugin.Base should set their own NAME value.
*
* @property Plugin.Base.NAME
* @type String
* @static
*/
Plugin.NAME = 'plugin';
/**
* The name of the property the the plugin will be attached to
* when plugged into a Plugin Host. Plugins extending Plugin.Base,
* should set their own NS value.
*
* @property Plugin.NS
* @type String
* @static
*/
Plugin.NS = 'plugin';
Y.extend(Plugin, Y.Base, {
/**
* The list of event handles for event listeners or AOP injected methods
* applied by the plugin to the host object.
*
* @property _handles
* @private
* @type Array
* @value null
*/
_handles: null,
/**
* Initializer lifecycle implementation.
*
* @method initializer
* @param {Object} config Configuration object with property name/value pairs.
*/
initializer : function(config) {
this._handles = [];
},
/**
* Destructor lifecycle implementation.
*
* Removes any event listeners or injected methods applied by the Plugin
*
* @method destructor
*/
destructor: function() {
// remove all handles
if (this._handles) {
for (var i = 0, l = this._handles.length; i < l; i++) {
this._handles[i].detach();
}
}
},
/**
* Listens for the "on" moment of events fired by the host,
* or injects code "before" a given method on the host.
*
* @method doBefore
*
* @param sFn {String} The event to listen for, or method to inject logic before.
* @param fn {Function} The handler function. For events, the "on" moment listener. For methods, the function to execute before the given method is executed.
* @param context {Object} An optional context to call the handler with. The default context is the plugin instance.
* @return handle {EventHandle} The detach handle for the handler.
*/
doBefore: function(sFn, fn, context) {
var host = this.get("host"),
handle;
context = context || this;
if (sFn in host) { // method
handle = Y.Do.before(fn, host, sFn, context);
} else if (host.on) { // event
handle = host.on(sFn, fn, context);
}
this._handles.push(handle);
return handle;
},
/**
* Listens for the "after" moment of events fired by the host,
* or injects code "after" a given method on the host.
*
* @method doAfter
*
* @param sFn {String} The event to listen for, or method to inject logic after.
* @param fn {Function} The handler function. For events, the "after" moment listener. For methods, the function to execute after the given method is executed.
* @param context {Object} An optional context to call the handler with. The default context is the plugin instance.
* @return handle {EventHandle} The detach handle for the handler.
*/
doAfter: function(sFn, fn, context) {
var host = this.get("host"),
handle;
context = context || this;
if (sFn in host) { // method
handle = Y.Do.after(fn, host, sFn, context);
} else if (host.after) { // event
handle = host.after(sFn, fn, context);
}
this._handles.push(handle);
return handle;
},
toString: function() {
return this.constructor.NAME + '[' + this.constructor.NS + ']';
}
});
Y.namespace("Plugin").Base = Plugin;
}, '@VERSION@' ,{requires:['base']});
|
;
(function($) {
$.fn.highchartTable = function() {
var allowedGraphTypes = ['column', 'line', 'area', 'spline', 'pie'];
var getCallable = function (table, attribute) {
var callback = $(table).data(attribute);
if (typeof callback != 'undefined') {
var infosCallback = callback.split('.');
var callable = window[infosCallback[0]];
for(var i = 1, infosCallbackLength = infosCallback.length; i < infosCallbackLength; i++) {
callable = callable[infosCallback[i]];
}
return callable;
}
};
this.each(function() {
var table = $(this);
var $table = $(table);
var nbYaxis = 1;
// Retrieve graph title from the table caption
var captions = $('caption', table);
var graphTitle = captions.length ? $(captions[0]).text() : '';
var graphContainer;
if ($table.data('graph-container-before') != 1) {
// Retrieve where the graph must be displayed from the graph-container attribute
var graphContainerSelector = $table.data('graph-container');
if (!graphContainerSelector) {
throw "graph-container data attribute is mandatory";
}
if (graphContainerSelector[0] === '#' || graphContainerSelector.indexOf('..')===-1) {
// Absolute selector path
graphContainer = $(graphContainerSelector);
} else {
var referenceNode = table;
var currentGraphContainerSelector = graphContainerSelector;
while (currentGraphContainerSelector.indexOf('..')!==-1) {
currentGraphContainerSelector = currentGraphContainerSelector.replace(/^.. /, '');
referenceNode = referenceNode.parent();
}
graphContainer = $(currentGraphContainerSelector, referenceNode);
}
if (graphContainer.length !== 1) {
throw "graph-container is not available in this DOM or available multiple times";
}
graphContainer = graphContainer[0];
} else {
$table.before('<div></div>');
graphContainer = $table.prev();
graphContainer = graphContainer[0];
}
// Retrieve graph type from graph-type attribute
var globalGraphType = $table.data('graph-type');
if (!globalGraphType) {
throw "graph-type data attribute is mandatory";
}
if ($.inArray(globalGraphType, allowedGraphTypes) == -1) {
throw "graph-container data attribute must be one of " + allowedGraphTypes.join(', ');
}
var stackingType = $table.data('graph-stacking');
if (!stackingType) {
stackingType = 'normal';
}
var dataLabelsEnabled = $table.data('graph-datalabels-enabled');
var isGraphInverted = $table.data('graph-inverted') == 1;
// Retrieve series titles
var ths = $('thead th', table);
var columns = [];
var vlines = [];
var skippedColumns = 0;
var graphIsStacked = false;
ths.each(function(indexTh, th) {
var $th = $(th);
var columnScale = $th.data('graph-value-scale');
var serieGraphType = $th.data('graph-type');
if($.inArray(serieGraphType, allowedGraphTypes) == -1) {
serieGraphType = globalGraphType;
}
var serieStackGroup = $th.data('graph-stack-group');
if(serieStackGroup) {
graphIsStacked = true;
}
var serieDataLabelsEnabled = $th.data('graph-datalabels-enabled');
if (typeof serieDataLabelsEnabled == 'undefined') {
serieDataLabelsEnabled = dataLabelsEnabled;
}
var yaxis = $th.data('graph-yaxis');
if (typeof yaxis != 'undefined' && yaxis == '1') {
nbYaxis = 2;
}
var isColumnSkipped = $th.data('graph-skip') == 1;
if (isColumnSkipped)
{
skippedColumns = skippedColumns + 1;
}
var thGraphConfig = {
libelle: $th.text(),
skip: isColumnSkipped,
indexTd: indexTh - skippedColumns - 1,
color: $th.data('graph-color'),
visible: !$th.data('graph-hidden'),
yAxis: typeof yaxis != 'undefined' ? yaxis : 0,
dashStyle: $th.data('graph-dash-style') || 'solid',
dataLabelsEnabled: serieDataLabelsEnabled == 1,
dataLabelsColor: $th.data('graph-datalabels-color') || $table.data('graph-datalabels-color')
};
var vlinex = $th.data('graph-vline-x');
if (typeof vlinex == 'undefined') {
thGraphConfig.scale = typeof columnScale != 'undefined' ? parseFloat(columnScale) : 1;
thGraphConfig.graphType = serieGraphType == 'column' && isGraphInverted ? 'bar' : serieGraphType;
thGraphConfig.stack = serieStackGroup;
thGraphConfig.unit = $th.data('graph-unit');
columns[indexTh] = thGraphConfig;
} else {
thGraphConfig.x = vlinex;
thGraphConfig.height = $th.data('graph-vline-height');
thGraphConfig.name = $th.data('graph-vline-name');
vlines[indexTh] = thGraphConfig;
}
});
var series = [];
$(columns).each(function(indexColumn, column) {
if(indexColumn!=0 && !column.skip) {
var serieConfig = {
name: column.libelle + (column.unit ? ' (' + column.unit + ')' : ''),
data: [],
type: column.graphType,
stack: column.stack,
color: column.color,
visible: column.visible,
yAxis: column.yAxis,
dashStyle: column.dashStyle,
marker: {
enabled: false
},
dataLabels: {
enabled: column.dataLabelsEnabled,
color: column.dataLabelsColor,
align: $table.data('graph-datalabels-align') || (globalGraphType == 'column' && isGraphInverted == 1 ? undefined : 'center')
}
};
if(column.dataLabelsEnabled) {
var callableSerieDataLabelsFormatter = getCallable(table, 'graph-datalabels-formatter');
if (callableSerieDataLabelsFormatter) {
serieConfig.dataLabels.formatter = function () {
return callableSerieDataLabelsFormatter(this.y);
};
}
}
series.push(serieConfig);
}
});
$(vlines).each(function(indexColumn, vline) {
if (typeof vline != 'undefined' && !vline.skip) {
series.push({
name: vline.libelle,
data: [{x: vline.x, y:0, name: vline.name}, {x:vline.x, y:vline.height, name: vline.name}],
type: 'spline',
color: vline.color,
visible: vline.visible,
marker: {
enabled: false
}
});
}
});
var xValues = [];
var callablePoint = getCallable(table, 'graph-point-callback');
var isGraphDatetime = $table.data('graph-xaxis-type') == 'datetime';
var rows = $('tbody:first tr', table);
rows.each(function(indexRow, row) {
if (!!$(row).data('graph-skip')) {
return;
}
var tds = $('td', row);
tds.each(function(indexTd, td) {
var cellValue;
var column = columns[indexTd];
if (column.skip) {
return;
}
var $td = $(td);
if (indexTd==0) {
cellValue = $td.text();
xValues.push(cellValue);
} else {
var rawCellValue = $td.text();
var serie = series[column.indexTd];
if (rawCellValue.length==0) {
if (!isGraphDatetime) {
serie.data.push(null);
}
} else {
var cleanedCellValue = rawCellValue.replace(/ /g, '').replace(/,/, '.');
cellValue = Math.round(parseFloat(cleanedCellValue) * column.scale * 100) / 100;
var dataGraphX = $td.data('graph-x');
if (isGraphDatetime) {
dataGraphX = $('td', $(row)).first().text();
var date = parseDate(dataGraphX);
dataGraphX = date.getTime() - date.getTimezoneOffset()*60*1000;
}
var tdGraphName = $td.data('graph-name');
var serieDataItem = {
name: typeof tdGraphName != 'undefined' ? tdGraphName : rawCellValue,
y: cellValue,
x: dataGraphX //undefined if no x defined in table
};
if (callablePoint) {
serieDataItem.events = {
click: function () {
return callablePoint(this);
}
};
}
if (column.graphType === 'pie') {
if ($td.data('graph-item-highlight')) {
serieDataItem.sliced = 1;
}
}
var tdGraphItemColor = $td.data('graph-item-color');
if (typeof tdGraphItemColor != 'undefined') {
serieDataItem.color = tdGraphItemColor;
}
serie.data.push(serieDataItem);
}
}
});
});
var yAxisConfig = [];
var yAxisNum;
for (yAxisNum=1 ; yAxisNum <= nbYaxis ; yAxisNum++) {
var yAxisConfigCurrentAxis = {
title: {
text: typeof $table.data('graph-yaxis-'+yAxisNum+'-title-text') != 'undefined' ? $table.data('graph-yaxis-'+yAxisNum+'-title-text') : null
},
max: typeof $table.data('graph-yaxis-'+yAxisNum+'-max') != 'undefined' ? $table.data('graph-yaxis-'+yAxisNum+'-max') : null,
min: typeof $table.data('graph-yaxis-'+yAxisNum+'-min') != 'undefined' ? $table.data('graph-yaxis-'+yAxisNum+'-min') : null,
reversed: $table.data('graph-yaxis-'+yAxisNum+'-reversed') == '1',
opposite: $table.data('graph-yaxis-'+yAxisNum+'-opposite') == '1',
tickInterval: $table.data('graph-yaxis-'+yAxisNum+'-tick-interval') || null,
labels: {
rotation: $table.data('graph-yaxis-'+yAxisNum+'-rotation') || 0
},
startOnTick: $table.data('graph-yaxis-'+yAxisNum+'-start-on-tick') !== "0",
endOnTick: $table.data('graph-yaxis-'+yAxisNum+'-end-on-tick') !== "0",
stackLabels : {
enabled: $table.data('graph-yaxis-'+yAxisNum+'-stacklabels-enabled') == '1'
},
gridLineInterpolation: $table.data('graph-yaxis-'+yAxisNum+'-grid-line-interpolation') || null
};
var callableYAxisFormatter = getCallable(table, 'graph-yaxis-'+yAxisNum+'-formatter-callback');
if (callableYAxisFormatter) {
yAxisConfigCurrentAxis.labels.formatter = function () {
return callableYAxisFormatter(this.value);
};
}
yAxisConfig.push(yAxisConfigCurrentAxis);
}
var defaultColors = [
'#4572A7',
'#AA4643',
'#89A54E',
'#80699B',
'#3D96AE',
'#DB843D',
'#92A8CD',
'#A47D7C',
'#B5CA92'
];
var colors = [];
var themeColors = typeof Highcharts.theme != 'undefined' && typeof Highcharts.theme.colors != 'undefined' ? Highcharts.theme.colors : [];
var lineShadow = $table.data('graph-line-shadow');
var lineWidth = $table.data('graph-line-width') || 2;
for(var i=0; i<9; i++) {
var dataname = 'graph-color-' + (i+1);
colors.push(typeof $table.data(dataname) != 'undefined' ? $table.data(dataname) : typeof themeColors[i] != 'undefined' ? themeColors[i] : defaultColors[i]);
}
var marginTop = $table.data('graph-margin-top');
var marginRight = $table.data('graph-margin-right');
var marginBottom = $table.data('graph-margin-bottom');
var marginLeft = $table.data('graph-margin-left');
var xAxisLabelsEnabled = $table.data('graph-xaxis-labels-enabled');
var xAxisLabelStyle = {};
var xAxisLabelFontSize = $table.data('graph-xaxis-labels-font-size');
if (typeof xAxisLabelFontSize != 'undefined')
{
xAxisLabelStyle.fontSize = xAxisLabelFontSize;
}
var highChartConfig = {
colors: colors,
chart: {
renderTo: graphContainer,
inverted: isGraphInverted,
marginTop: typeof marginTop != 'undefined' ? marginTop : null,
marginRight: typeof marginRight != 'undefined' ? marginRight : null,
marginBottom: typeof marginBottom != 'undefined' ? marginBottom : null,
marginLeft: typeof marginLeft != 'undefined' ? marginLeft : null,
spacingTop: $table.data('graph-spacing-top') || 10,
height: $table.data('graph-height') || null,
zoomType: $table.data('graph-zoom-type') || null,
polar: $table.data('graph-polar') || null
},
title: {
text: graphTitle
},
subtitle: {
text: $table.data('graph-subtitle-text') || ''
},
legend: {
enabled: $table.data('graph-legend-disabled') != '1',
layout: $table.data('graph-legend-layout') || 'horizontal',
symbolWidth: $table.data('graph-legend-width') || 30,
x: $table.data('graph-legend-x') || 15,
y: $table.data('graph-legend-y') || 0
},
xAxis: {
categories: ($table.data('graph-xaxis-type') != 'datetime') ? xValues : undefined,
type: ($table.data('graph-xaxis-type') == 'datetime') ? 'datetime' : undefined,
reversed: $table.data('graph-xaxis-reversed') == '1',
opposite: $table.data('graph-xaxis-opposite') == '1',
showLastLabel: typeof $table.data('graph-xaxis-show-last-label') != 'undefined' ? $table.data('graph-xaxis-show-last-label') : true,
tickInterval: $table.data('graph-xaxis-tick-interval') || null,
dateTimeLabelFormats: { //by default, we display the day and month on the datetime graphs
second: '%e. %b',
minute: '%e. %b',
hour: '%e. %b',
day: '%e. %b',
week: '%e. %b',
month: '%e. %b',
year: '%e. %b'
},
labels:
{
rotation: $table.data('graph-xaxis-rotation') || 0,
align: $table.data('graph-xaxis-align') || 'center',
enabled: typeof xAxisLabelsEnabled != 'undefined' ? xAxisLabelsEnabled : true,
style: xAxisLabelStyle
},
startOnTick: $table.data('graph-xaxis-start-on-tick'),
endOnTick: $table.data('graph-xaxis-end-on-tick'),
min: getXAxisMinMax(table, 'min'),
max: getXAxisMinMax(table, 'max'),
alternateGridColor: $table.data('graph-xaxis-alternateGridColor') || null,
title: {
text: $table.data('graph-xaxis-title-text') || null
},
gridLineWidth: $table.data('graph-xaxis-gridLine-width') || 0,
gridLineDashStyle: $table.data('graph-xaxis-gridLine-style') || 'ShortDot',
tickmarkPlacement: $table.data('graph-xaxis-tickmark-placement') || 'between',
lineWidth: $table.data('graph-xaxis-line-width') || 0
},
yAxis: yAxisConfig,
tooltip: {
formatter: function() {
if ($table.data('graph-xaxis-type') == 'datetime') {
return '<b>'+ this.series.name +'</b><br/>'+ Highcharts.dateFormat('%e. %b', this.x) +' : '+ this.y;
} else {
var xValue = typeof xValues[this.point.x] != 'undefined' ? xValues[this.point.x] : this.point.x;
if (globalGraphType === 'pie') {
return '<strong>' + this.series.name + '</strong><br />' + xValue + ' : ' + this.point.y;
}
return '<strong>' + this.series.name + '</strong><br />' + xValue + ' : ' + this.point.name;
}
}
},
credits: {
enabled: false
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
lineWidth: lineWidth
},
area: {
lineWidth: lineWidth,
shadow: typeof lineShadow != 'undefined' ? lineShadow : true,
fillOpacity: $table.data('graph-area-fillOpacity') || 0.75
},
pie: {
allowPointSelect: true,
dataLabels: {
enabled: true
},
showInLegend: $table.data('graph-pie-show-in-legend') == '1',
size: '80%'
},
series: {
animation: false,
stickyTracking : false,
stacking: graphIsStacked ? stackingType : null,
groupPadding: $table.data('graph-group-padding') || 0
}
},
series: series,
exporting: {
filename: graphTitle.replace(/ /g, '_'),
buttons: {
exportButton: {
menuItems: null,
onclick: function() {
this.exportChart();
}
}
}
}
};
$table.trigger('highchartTable.beforeRender', highChartConfig);
new Highcharts.Chart(highChartConfig);
});
//for fluent api
return this;
};
var getXAxisMinMax = function(table, minOrMax) {
var value = $(table).data('graph-xaxis-'+minOrMax);
if (typeof value != 'undefined') {
if ($(table).data('graph-xaxis-type') == 'datetime') {
var date = parseDate(value);
return date.getTime() - date.getTimezoneOffset()*60*1000;
}
return value;
}
return null;
};
var parseDate = function(datetime) {
var calculatedateInfos = datetime.split(' ');
var dateDayInfos = calculatedateInfos[0].split('-');
var min = null;
var hour = null;
// If hour and minute are available in the datetime string
if(calculatedateInfos[1]) {
var dateHourInfos = calculatedateInfos[1].split(':');
min = parseInt(dateHourInfos[0], 10);
hour = parseInt(dateHourInfos[1], 10);
}
return new Date(parseInt(dateDayInfos[0], 10), parseInt(dateDayInfos[1], 10)-1, parseInt(dateDayInfos[2], 10), min, hour);
};
})(jQuery);
|
var g_iteration = 0;
function FindProxyForURL(url, host) {
alert('iteration: ' + g_iteration++);
var ips = [
myIpAddress(),
dnsResolve(''),
dnsResolveEx('host1'),
dnsResolve('host2'),
dnsResolve('host3'),
myIpAddress(),
dnsResolve('host3'),
dnsResolveEx('host1'),
myIpAddress(),
dnsResolve('host2'),
dnsResolveEx('host6'),
myIpAddressEx(),
dnsResolve('host1'),
];
for (var i = 0; i < ips.length; ++i) {
// Stringize everything.
ips[i] = '' + ips[i];
}
var proxyHost = ips.join('-');
proxyHost = proxyHost.replace(/[^0-9a-zA-Z.-]/g, '_');
return "PROXY " + proxyHost + ":99";
}
|
tinyMCE.addI18n('sl.simple',{"cleanup_desc":"Pre\u010disti kodo","redo_desc":"Uveljavi (Ctrl+Y)","undo_desc":"Razveljavi (Ctrl+Z)","numlist_desc":"Na\u0161tevanje","bullist_desc":"Alineje","striketrough_desc":"Pre\u010drtano","underline_desc":"Pod\u010drtano (Ctrl+U)","italic_desc":"Po\u0161evno (Ctrl+I)","bold_desc":"Krepko (Ctrl+B)"});
|
Template.configureLoginServiceDialogForTwitter.helpers({
siteUrl: function () {
// Twitter doesn't recognize localhost as a domain name
return Meteor.absoluteUrl({replaceLocalhost: true});
}
});
Template.configureLoginServiceDialogForTwitter.fields = function () {
return [
{property: 'consumerKey', label: 'API key'},
{property: 'secret', label: 'API secret'}
];
};
|
var _ = require('lodash'),
Promise = require('bluebird'),
cheerio = require('cheerio'),
crypto = require('crypto'),
downsize = require('downsize'),
RSS = require('rss'),
url = require('url'),
config = require('../../../config'),
api = require('../../../api'),
filters = require('../../../filters'),
generate,
generateFeed,
getFeedXml,
feedCache = {};
function isPaginated(req) {
return req.route.path.indexOf(':page') !== -1;
}
function isTag(req) {
return req.route.path.indexOf('/' + config.routeKeywords.tag + '/') !== -1;
}
function isAuthor(req) {
return req.route.path.indexOf('/' + config.routeKeywords.author + '/') !== -1;
}
function handleError(next) {
return function (err) {
return next(err);
};
}
function getOptions(req, pageParam, slugParam) {
var options = {};
if (pageParam) { options.page = pageParam; }
if (isTag(req)) { options.tag = slugParam; }
if (isAuthor(req)) { options.author = slugParam; }
options.include = 'author,tags,fields';
return options;
}
function getData(options) {
var ops = {
title: api.settings.read('title'),
description: api.settings.read('description'),
permalinks: api.settings.read('permalinks'),
results: api.posts.browse(options)
};
return Promise.props(ops).then(function (result) {
var titleStart = options.tags ? result.results.meta.filters.tags[0].name + ' - ' :
options.author ? result.results.meta.filters.author.name + ' - ' : '';
return {
title: titleStart + result.title.settings[0].value,
description: result.description.settings[0].value,
permalinks: result.permalinks.settings[0],
results: result.results
};
});
}
function getBaseUrl(req, slugParam) {
var baseUrl = config.paths.subdir;
if (isTag(req)) {
baseUrl += '/' + config.routeKeywords.tag + '/' + slugParam + '/rss/';
} else if (isAuthor(req)) {
baseUrl += '/' + config.routeKeywords.author + '/' + slugParam + '/rss/';
} else {
baseUrl += '/rss/';
}
return baseUrl;
}
function processUrls(html, siteUrl, itemUrl) {
var htmlContent = cheerio.load(html, {decodeEntities: false});
// convert relative resource urls to absolute
['href', 'src'].forEach(function (attributeName) {
htmlContent('[' + attributeName + ']').each(function (ix, el) {
var baseUrl,
attributeValue,
parsed;
el = htmlContent(el);
attributeValue = el.attr(attributeName);
// if URL is absolute move on to the next element
try {
parsed = url.parse(attributeValue);
if (parsed.protocol) {
return;
}
} catch (e) {
return;
}
// compose an absolute URL
// if the relative URL begins with a '/' use the blog URL (including sub-directory)
// as the base URL, otherwise use the post's URL.
baseUrl = attributeValue[0] === '/' ? siteUrl : itemUrl;
// prevent double subdirectories
if (attributeValue.indexOf(config.paths.subdir) === 0) {
attributeValue = attributeValue.replace(config.paths.subdir, '');
}
// prevent double slashes
if (baseUrl.slice(-1) === '/' && attributeValue[0] === '/') {
attributeValue = attributeValue.substr(1);
}
attributeValue = baseUrl + attributeValue;
el.attr(attributeName, attributeValue);
});
});
return htmlContent;
}
getFeedXml = function (path, data) {
var dataHash = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex');
if (!feedCache[path] || feedCache[path].hash !== dataHash) {
// We need to regenerate
feedCache[path] = {
hash: dataHash,
xml: generateFeed(data)
};
}
return feedCache[path].xml;
};
generateFeed = function (data) {
var feed = new RSS({
title: data.title,
description: data.description,
generator: 'Ghost ' + data.version,
feed_url: data.feedUrl,
site_url: data.siteUrl,
ttl: '60',
custom_namespaces: {
content: 'http://purl.org/rss/1.0/modules/content/',
media: 'http://search.yahoo.com/mrss/'
}
});
data.results.posts.forEach(function (post) {
var itemUrl = config.urlFor('post', {post: post, permalinks: data.permalinks, secure: data.secure}, true),
htmlContent = processUrls(post.html, data.siteUrl, itemUrl),
item = {
title: post.title,
description: post.meta_description || downsize(htmlContent.html(), {words: 50}),
guid: post.uuid,
url: itemUrl,
date: post.published_at,
categories: _.pluck(post.tags, 'name'),
author: post.author ? post.author.name : null,
custom_elements: []
},
imageUrl;
if (post.image) {
imageUrl = config.urlFor('image', {image: post.image, secure: data.secure}, true);
// Add a media content tag
item.custom_elements.push({
'media:content': {
_attr: {
url: imageUrl,
medium: 'image'
}
}
});
// Also add the image to the content, because not all readers support media:content
htmlContent('p').first().before('<img src="' + imageUrl + '" />');
htmlContent('img').attr('alt', post.title);
}
item.custom_elements.push({
'content:encoded': {
_cdata: htmlContent.html()
}
});
feed.item(item);
});
return filters.doFilter('rss.feed', feed).then(function (feed) {
return feed.xml();
});
};
generate = function (req, res, next) {
// Initialize RSS
var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1,
slugParam = req.params.slug,
baseUrl = getBaseUrl(req, slugParam),
options = getOptions(req, pageParam, slugParam);
// No negative pages, or page 1
if (isNaN(pageParam) || pageParam < 1 || (pageParam === 1 && isPaginated(req))) {
return res.redirect(baseUrl);
}
return getData(options).then(function (data) {
var maxPage = data.results.meta.pagination.pages;
// If page is greater than number of pages we have, redirect to last page
if (pageParam > maxPage) {
return res.redirect(baseUrl + maxPage + '/');
}
data.version = res.locals.safeVersion;
data.siteUrl = config.urlFor('home', {secure: req.secure}, true);
data.feedUrl = config.urlFor({relativeUrl: baseUrl, secure: req.secure}, true);
data.secure = req.secure;
return getFeedXml(req.route.path, data).then(function (feedXml) {
res.set('Content-Type', 'text/xml; charset=UTF-8');
res.send(feedXml);
});
}).catch(handleError(next));
};
module.exports = generate;
|
(function() {
var Bacon, BufferingSource, Bus, CompositeUnsubscribe, ConsumingSource, DepCache, Desc, Dispatcher, End, Error, Event, EventStream, Initial, Next, None, Observable, Property, PropertyDispatcher, Some, Source, UpdateBarrier, addPropertyInitValueToStream, assert, assertArray, assertEventStream, assertFunction, assertNoArguments, assertString, cloneArray, compositeUnsubscribe, containsDuplicateDeps, convertArgsToFunction, describe, end, eventIdCounter, findDeps, flatMap_, former, idCounter, initial, isArray, isFieldKey, isFunction, isObservable, latterF, liftCallback, makeFunction, makeFunctionArgs, makeFunction_, makeObservable, makeSpawner, next, nop, partiallyApplied, recursionDepth, registerObs, spys, toCombinator, toEvent, toFieldExtractor, toFieldKey, toOption, toSimpleExtractor, withDescription, withMethodCallSupport, _, _ref,
__slice = [].slice,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Bacon = {
toString: function() {
return "Bacon";
}
};
Bacon.version = '0.7.18';
Bacon.fromBinder = function(binder, eventTransformer) {
if (eventTransformer == null) {
eventTransformer = _.id;
}
return new EventStream(describe(Bacon, "fromBinder", binder, eventTransformer), function(sink) {
var unbind, unbinder, unbound;
unbound = false;
unbind = function() {
if (typeof unbinder !== "undefined" && unbinder !== null) {
if (!unbound) {
unbinder();
}
return unbound = true;
}
};
unbinder = binder(function() {
var args, event, reply, value, _i, _len;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
value = eventTransformer.apply(null, args);
if (!(isArray(value) && _.last(value) instanceof Event)) {
value = [value];
}
reply = Bacon.more;
for (_i = 0, _len = value.length; _i < _len; _i++) {
event = value[_i];
reply = sink(event = toEvent(event));
if (reply === Bacon.noMore || event.isEnd()) {
if (unbinder != null) {
unbind();
} else {
Bacon.scheduler.setTimeout(unbind, 0);
}
return reply;
}
}
return reply;
});
return unbind;
});
};
Bacon.$ = {
asEventStream: function(eventName, selector, eventTransformer) {
var _ref;
if (isFunction(selector)) {
_ref = [selector, null], eventTransformer = _ref[0], selector = _ref[1];
}
return withDescription(this.selector || this, "asEventStream", eventName, Bacon.fromBinder((function(_this) {
return function(handler) {
_this.on(eventName, selector, handler);
return function() {
return _this.off(eventName, selector, handler);
};
};
})(this), eventTransformer));
}
};
if ((_ref = typeof jQuery !== "undefined" && jQuery !== null ? jQuery : typeof Zepto !== "undefined" && Zepto !== null ? Zepto : null) != null) {
_ref.fn.asEventStream = Bacon.$.asEventStream;
}
Bacon.fromEventTarget = function(target, eventName, eventTransformer) {
var sub, unsub, _ref1, _ref2, _ref3, _ref4;
sub = (_ref1 = target.addEventListener) != null ? _ref1 : (_ref2 = target.addListener) != null ? _ref2 : target.bind;
unsub = (_ref3 = target.removeEventListener) != null ? _ref3 : (_ref4 = target.removeListener) != null ? _ref4 : target.unbind;
return withDescription(Bacon, "fromEventTarget", target, eventName, Bacon.fromBinder(function(handler) {
sub.call(target, eventName, handler);
return function() {
return unsub.call(target, eventName, handler);
};
}, eventTransformer));
};
Bacon.fromPromise = function(promise, abort) {
return withDescription(Bacon, "fromPromise", promise, Bacon.fromBinder(function(handler) {
promise.then(handler, function(e) {
return handler(new Error(e));
});
return function() {
if (abort) {
return typeof promise.abort === "function" ? promise.abort() : void 0;
}
};
}, (function(value) {
return [value, end()];
})));
};
Bacon.noMore = ["<no-more>"];
Bacon.more = ["<more>"];
Bacon.later = function(delay, value) {
return withDescription(Bacon, "later", delay, value, Bacon.sequentially(delay, [value]));
};
Bacon.sequentially = function(delay, values) {
var index;
index = 0;
return withDescription(Bacon, "sequentially", delay, values, Bacon.fromPoll(delay, function() {
var value;
value = values[index++];
if (index < values.length) {
return value;
} else if (index === values.length) {
return [value, end()];
} else {
return end();
}
}));
};
Bacon.repeatedly = function(delay, values) {
var index;
index = 0;
return withDescription(Bacon, "repeatedly", delay, values, Bacon.fromPoll(delay, function() {
return values[index++ % values.length];
}));
};
Bacon.spy = function(spy) {
return spys.push(spy);
};
spys = [];
registerObs = function(obs) {
var spy, _i, _len, _results;
if (spys.length) {
if (!registerObs.running) {
try {
registerObs.running = true;
_results = [];
for (_i = 0, _len = spys.length; _i < _len; _i++) {
spy = spys[_i];
_results.push(spy(obs));
}
return _results;
} finally {
delete registerObs.running;
}
}
}
};
withMethodCallSupport = function(wrapped) {
return function() {
var args, context, f, methodName;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (typeof f === "object" && args.length) {
context = f;
methodName = args[0];
f = function() {
return context[methodName].apply(context, arguments);
};
args = args.slice(1);
}
return wrapped.apply(null, [f].concat(__slice.call(args)));
};
};
liftCallback = function(desc, wrapped) {
return withMethodCallSupport(function() {
var args, f, stream;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
stream = partiallyApplied(wrapped, [
function(values, callback) {
return f.apply(null, __slice.call(values).concat([callback]));
}
]);
return withDescription.apply(null, [Bacon, desc, f].concat(__slice.call(args), [Bacon.combineAsArray(args).flatMap(stream)]));
});
};
Bacon.fromCallback = liftCallback("fromCallback", function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return Bacon.fromBinder(function(handler) {
makeFunction(f, args)(handler);
return nop;
}, (function(value) {
return [value, end()];
}));
});
Bacon.fromNodeCallback = liftCallback("fromNodeCallback", function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return Bacon.fromBinder(function(handler) {
makeFunction(f, args)(handler);
return nop;
}, function(error, value) {
if (error) {
return [new Error(error), end()];
}
return [value, end()];
});
});
Bacon.fromPoll = function(delay, poll) {
return withDescription(Bacon, "fromPoll", delay, poll, Bacon.fromBinder((function(handler) {
var id;
id = Bacon.scheduler.setInterval(handler, delay);
return function() {
return Bacon.scheduler.clearInterval(id);
};
}), poll));
};
Bacon.interval = function(delay, value) {
if (value == null) {
value = {};
}
return withDescription(Bacon, "interval", delay, value, Bacon.fromPoll(delay, function() {
return next(value);
}));
};
Bacon.constant = function(value) {
return new Property(describe(Bacon, "constant", value), function(sink) {
sink(initial(value));
sink(end());
return nop;
});
};
Bacon.never = function() {
return withDescription(Bacon, "never", Bacon.fromArray([]));
};
Bacon.once = function(value) {
return withDescription(Bacon, "once", value, Bacon.fromArray([value]));
};
Bacon.fromArray = function(values) {
assertArray(values);
values = cloneArray(values);
return new EventStream(describe(Bacon, "fromArray", values), function(sink) {
var reply, unsubd, value;
unsubd = false;
reply = Bacon.more;
while ((reply !== Bacon.noMore) && !unsubd) {
if (_.empty(values)) {
sink(end());
reply = Bacon.noMore;
} else {
value = values.splice(0, 1)[0];
reply = sink(toEvent(value));
}
}
return function() {
return unsubd = true;
};
});
};
Bacon.mergeAll = function() {
var streams;
streams = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (isArray(streams[0])) {
streams = streams[0];
}
if (streams.length) {
return new EventStream(describe.apply(null, [Bacon, "mergeAll"].concat(__slice.call(streams))), function(sink) {
var ends, sinks, smartSink;
ends = 0;
smartSink = function(obs) {
return function(unsubBoth) {
return obs.subscribeInternal(function(event) {
var reply;
if (event.isEnd()) {
ends++;
if (ends === streams.length) {
return sink(end());
} else {
return Bacon.more;
}
} else {
reply = sink(event);
if (reply === Bacon.noMore) {
unsubBoth();
}
return reply;
}
});
};
};
sinks = _.map(smartSink, streams);
return compositeUnsubscribe.apply(null, sinks);
});
} else {
return Bacon.never();
}
};
Bacon.zipAsArray = function() {
var streams;
streams = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (isArray(streams[0])) {
streams = streams[0];
}
return withDescription.apply(null, [Bacon, "zipAsArray"].concat(__slice.call(streams), [Bacon.zipWith(streams, function() {
var xs;
xs = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return xs;
})]));
};
Bacon.zipWith = function() {
var f, streams, _ref1;
f = arguments[0], streams = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (!isFunction(f)) {
_ref1 = [f, streams[0]], streams = _ref1[0], f = _ref1[1];
}
streams = _.map((function(s) {
return s.toEventStream();
}), streams);
return withDescription.apply(null, [Bacon, "zipWith", f].concat(__slice.call(streams), [Bacon.when(streams, f)]));
};
Bacon.groupSimultaneous = function() {
var s, sources, streams;
streams = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (streams.length === 1 && isArray(streams[0])) {
streams = streams[0];
}
sources = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = streams.length; _i < _len; _i++) {
s = streams[_i];
_results.push(new BufferingSource(s));
}
return _results;
})();
return withDescription.apply(null, [Bacon, "groupSimultaneous"].concat(__slice.call(streams), [Bacon.when(sources, (function() {
var xs;
xs = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return xs;
}))]));
};
Bacon.combineAsArray = function() {
var index, s, sources, stream, streams, _i, _len;
streams = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (streams.length === 1 && isArray(streams[0])) {
streams = streams[0];
}
for (index = _i = 0, _len = streams.length; _i < _len; index = ++_i) {
stream = streams[index];
if (!(isObservable(stream))) {
streams[index] = Bacon.constant(stream);
}
}
if (streams.length) {
sources = (function() {
var _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = streams.length; _j < _len1; _j++) {
s = streams[_j];
_results.push(new Source(s, true, s.subscribeInternal));
}
return _results;
})();
return withDescription.apply(null, [Bacon, "combineAsArray"].concat(__slice.call(streams), [Bacon.when(sources, (function() {
var xs;
xs = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return xs;
})).toProperty()]));
} else {
return Bacon.constant([]);
}
};
Bacon.onValues = function() {
var f, streams, _i;
streams = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), f = arguments[_i++];
return Bacon.combineAsArray(streams).onValues(f);
};
Bacon.combineWith = function() {
var f, streams;
f = arguments[0], streams = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return withDescription.apply(null, [Bacon, "combineWith", f].concat(__slice.call(streams), [Bacon.combineAsArray(streams).map(function(values) {
return f.apply(null, values);
})]));
};
Bacon.combineTemplate = function(template) {
var applyStreamValue, combinator, compile, compileTemplate, constantValue, current, funcs, mkContext, setValue, streams;
funcs = [];
streams = [];
current = function(ctxStack) {
return ctxStack[ctxStack.length - 1];
};
setValue = function(ctxStack, key, value) {
return current(ctxStack)[key] = value;
};
applyStreamValue = function(key, index) {
return function(ctxStack, values) {
return setValue(ctxStack, key, values[index]);
};
};
constantValue = function(key, value) {
return function(ctxStack) {
return setValue(ctxStack, key, value);
};
};
mkContext = function(template) {
if (isArray(template)) {
return [];
} else {
return {};
}
};
compile = function(key, value) {
var popContext, pushContext;
if (isObservable(value)) {
streams.push(value);
return funcs.push(applyStreamValue(key, streams.length - 1));
} else if (value === Object(value) && typeof value !== "function" && !(value instanceof RegExp) && !(value instanceof Date)) {
pushContext = function(key) {
return function(ctxStack) {
var newContext;
newContext = mkContext(value);
setValue(ctxStack, key, newContext);
return ctxStack.push(newContext);
};
};
popContext = function(ctxStack) {
return ctxStack.pop();
};
funcs.push(pushContext(key));
compileTemplate(value);
return funcs.push(popContext);
} else {
return funcs.push(constantValue(key, value));
}
};
compileTemplate = function(template) {
return _.each(template, compile);
};
compileTemplate(template);
combinator = function(values) {
var ctxStack, f, rootContext, _i, _len;
rootContext = mkContext(template);
ctxStack = [rootContext];
for (_i = 0, _len = funcs.length; _i < _len; _i++) {
f = funcs[_i];
f(ctxStack, values);
}
return rootContext;
};
return withDescription(Bacon, "combineTemplate", template, Bacon.combineAsArray(streams).map(combinator));
};
Bacon.retry = function(options) {
var delay, isRetryable, maxRetries, retries, retry, source;
if (!isFunction(options.source)) {
throw "'source' option has to be a function";
}
source = options.source;
retries = options.retries || 0;
maxRetries = options.maxRetries || retries;
delay = options.delay || function() {
return 0;
};
isRetryable = options.isRetryable || function() {
return true;
};
retry = function(context) {
var delayedRetry, nextAttemptOptions;
nextAttemptOptions = {
source: source,
retries: retries - 1,
maxRetries: maxRetries,
delay: delay,
isRetryable: isRetryable
};
delayedRetry = function() {
return Bacon.retry(nextAttemptOptions);
};
return Bacon.later(delay(context)).filter(false).concat(Bacon.once().flatMap(delayedRetry));
};
return withDescription(Bacon, "retry", options, source().flatMapError(function(e) {
if (isRetryable(e) && retries > 0) {
return retry({
error: e,
retriesDone: maxRetries - retries
});
} else {
return Bacon.once(new Bacon.Error(e));
}
}));
};
eventIdCounter = 0;
Event = (function() {
function Event() {
this.id = ++eventIdCounter;
}
Event.prototype.isEvent = function() {
return true;
};
Event.prototype.isEnd = function() {
return false;
};
Event.prototype.isInitial = function() {
return false;
};
Event.prototype.isNext = function() {
return false;
};
Event.prototype.isError = function() {
return false;
};
Event.prototype.hasValue = function() {
return false;
};
Event.prototype.filter = function() {
return true;
};
Event.prototype.inspect = function() {
return this.toString();
};
Event.prototype.log = function() {
return this.toString();
};
return Event;
})();
Next = (function(_super) {
__extends(Next, _super);
function Next(valueF) {
Next.__super__.constructor.call(this);
if (isFunction(valueF)) {
this.value = _.cached(valueF);
} else {
this.value = _.always(valueF);
}
}
Next.prototype.isNext = function() {
return true;
};
Next.prototype.hasValue = function() {
return true;
};
Next.prototype.fmap = function(f) {
var value;
value = this.value;
return this.apply(function() {
return f(value());
});
};
Next.prototype.apply = function(value) {
return new Next(value);
};
Next.prototype.filter = function(f) {
return f(this.value());
};
Next.prototype.toString = function() {
return _.toString(this.value());
};
Next.prototype.log = function() {
return this.value();
};
return Next;
})(Event);
Initial = (function(_super) {
__extends(Initial, _super);
function Initial() {
return Initial.__super__.constructor.apply(this, arguments);
}
Initial.prototype.isInitial = function() {
return true;
};
Initial.prototype.isNext = function() {
return false;
};
Initial.prototype.apply = function(value) {
return new Initial(value);
};
Initial.prototype.toNext = function() {
return new Next(this.value);
};
return Initial;
})(Next);
End = (function(_super) {
__extends(End, _super);
function End() {
return End.__super__.constructor.apply(this, arguments);
}
End.prototype.isEnd = function() {
return true;
};
End.prototype.fmap = function() {
return this;
};
End.prototype.apply = function() {
return this;
};
End.prototype.toString = function() {
return "<end>";
};
return End;
})(Event);
Error = (function(_super) {
__extends(Error, _super);
function Error(error) {
this.error = error;
}
Error.prototype.isError = function() {
return true;
};
Error.prototype.fmap = function() {
return this;
};
Error.prototype.apply = function() {
return this;
};
Error.prototype.toString = function() {
return "<error> " + _.toString(this.error);
};
return Error;
})(Event);
idCounter = 0;
Observable = (function() {
function Observable(desc) {
this.flatMapError = __bind(this.flatMapError, this);
this.id = ++idCounter;
withDescription(desc, this);
}
Observable.prototype.onValue = function() {
var f;
f = makeFunctionArgs(arguments);
return this.subscribe(function(event) {
if (event.hasValue()) {
return f(event.value());
}
});
};
Observable.prototype.onValues = function(f) {
return this.onValue(function(args) {
return f.apply(null, args);
});
};
Observable.prototype.onError = function() {
var f;
f = makeFunctionArgs(arguments);
return this.subscribe(function(event) {
if (event.isError()) {
return f(event.error);
}
});
};
Observable.prototype.onEnd = function() {
var f;
f = makeFunctionArgs(arguments);
return this.subscribe(function(event) {
if (event.isEnd()) {
return f();
}
});
};
Observable.prototype.errors = function() {
return withDescription(this, "errors", this.filter(function() {
return false;
}));
};
Observable.prototype.filter = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return convertArgsToFunction(this, f, args, function(f) {
return withDescription(this, "filter", f, this.withHandler(function(event) {
if (event.filter(f)) {
return this.push(event);
} else {
return Bacon.more;
}
}));
});
};
Observable.prototype.takeWhile = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return convertArgsToFunction(this, f, args, function(f) {
return withDescription(this, "takeWhile", f, this.withHandler(function(event) {
if (event.filter(f)) {
return this.push(event);
} else {
this.push(end());
return Bacon.noMore;
}
}));
});
};
Observable.prototype.endOnError = function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (f == null) {
f = true;
}
return convertArgsToFunction(this, f, args, function(f) {
return withDescription(this, "endOnError", this.withHandler(function(event) {
if (event.isError() && f(event.error)) {
this.push(event);
return this.push(end());
} else {
return this.push(event);
}
}));
});
};
Observable.prototype.take = function(count) {
if (count <= 0) {
return Bacon.never();
}
return withDescription(this, "take", count, this.withHandler(function(event) {
if (!event.hasValue()) {
return this.push(event);
} else {
count--;
if (count > 0) {
return this.push(event);
} else {
if (count === 0) {
this.push(event);
}
this.push(end());
return Bacon.noMore;
}
}
}));
};
Observable.prototype.map = function() {
var args, p;
p = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (p instanceof Property) {
return p.sampledBy(this, former);
} else {
return convertArgsToFunction(this, p, args, function(f) {
return withDescription(this, "map", f, this.withHandler(function(event) {
return this.push(event.fmap(f));
}));
});
}
};
Observable.prototype.mapError = function() {
var f;
f = makeFunctionArgs(arguments);
return withDescription(this, "mapError", f, this.withHandler(function(event) {
if (event.isError()) {
return this.push(next(f(event.error)));
} else {
return this.push(event);
}
}));
};
Observable.prototype.mapEnd = function() {
var f;
f = makeFunctionArgs(arguments);
return withDescription(this, "mapEnd", f, this.withHandler(function(event) {
if (event.isEnd()) {
this.push(next(f(event)));
this.push(end());
return Bacon.noMore;
} else {
return this.push(event);
}
}));
};
Observable.prototype.doAction = function() {
var f;
f = makeFunctionArgs(arguments);
return withDescription(this, "doAction", f, this.withHandler(function(event) {
if (event.hasValue()) {
f(event.value());
}
return this.push(event);
}));
};
Observable.prototype.skip = function(count) {
return withDescription(this, "skip", count, this.withHandler(function(event) {
if (!event.hasValue()) {
return this.push(event);
} else if (count > 0) {
count--;
return Bacon.more;
} else {
return this.push(event);
}
}));
};
Observable.prototype.skipDuplicates = function(isEqual) {
if (isEqual == null) {
isEqual = function(a, b) {
return a === b;
};
}
return withDescription(this, "skipDuplicates", this.withStateMachine(None, function(prev, event) {
if (!event.hasValue()) {
return [prev, [event]];
} else if (event.isInitial() || prev === None || !isEqual(prev.get(), event.value())) {
return [new Some(event.value()), [event]];
} else {
return [prev, []];
}
}));
};
Observable.prototype.skipErrors = function() {
return withDescription(this, "skipErrors", this.withHandler(function(event) {
if (event.isError()) {
return Bacon.more;
} else {
return this.push(event);
}
}));
};
Observable.prototype.withStateMachine = function(initState, f) {
var state;
state = initState;
return withDescription(this, "withStateMachine", initState, f, this.withHandler(function(event) {
var fromF, newState, output, outputs, reply, _i, _len;
fromF = f(state, event);
newState = fromF[0], outputs = fromF[1];
state = newState;
reply = Bacon.more;
for (_i = 0, _len = outputs.length; _i < _len; _i++) {
output = outputs[_i];
reply = this.push(output);
if (reply === Bacon.noMore) {
return reply;
}
}
return reply;
}));
};
Observable.prototype.scan = function(seed, f, options) {
var acc, f_, resultProperty, subscribe;
if (options == null) {
options = {};
}
f_ = toCombinator(f);
f = options.lazyF ? f_ : function(x, y) {
return f_(x(), y());
};
acc = toOption(seed).map(function(x) {
return _.always(x);
});
subscribe = (function(_this) {
return function(sink) {
var initSent, reply, sendInit, unsub;
initSent = false;
unsub = nop;
reply = Bacon.more;
sendInit = function() {
if (!initSent) {
return acc.forEach(function(valueF) {
initSent = true;
reply = sink(new Initial(valueF));
if (reply === Bacon.noMore) {
unsub();
return unsub = nop;
}
});
}
};
unsub = _this.subscribeInternal(function(event) {
var next, prev;
if (event.hasValue()) {
if (initSent && event.isInitial()) {
return Bacon.more;
} else {
if (!event.isInitial()) {
sendInit();
}
initSent = true;
prev = acc.getOrElse(function() {
return void 0;
});
next = _.cached(function() {
return f(prev, event.value);
});
acc = new Some(next);
if (options.eager) {
next();
}
return sink(event.apply(next));
}
} else {
if (event.isEnd()) {
reply = sendInit();
}
if (reply !== Bacon.noMore) {
return sink(event);
}
}
});
UpdateBarrier.whenDoneWith(resultProperty, sendInit);
return unsub;
};
})(this);
return resultProperty = new Property(describe(this, "scan", seed, f), subscribe);
};
Observable.prototype.fold = function(seed, f, options) {
return withDescription(this, "fold", seed, f, this.scan(seed, f, options).sampledBy(this.filter(false).mapEnd().toProperty()));
};
Observable.prototype.zip = function(other, f) {
if (f == null) {
f = Array;
}
return withDescription(this, "zip", other, Bacon.zipWith([this, other], f));
};
Observable.prototype.diff = function(start, f) {
f = toCombinator(f);
return withDescription(this, "diff", start, f, this.scan([start], function(prevTuple, next) {
return [next, f(prevTuple[0], next)];
}).filter(function(tuple) {
return tuple.length === 2;
}).map(function(tuple) {
return tuple[1];
}));
};
Observable.prototype.flatMap = function() {
return flatMap_(this, makeSpawner(arguments));
};
Observable.prototype.flatMapFirst = function() {
return flatMap_(this, makeSpawner(arguments), true);
};
Observable.prototype.flatMapWithConcurrencyLimit = function() {
var args, limit;
limit = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return withDescription.apply(null, [this, "flatMapWithConcurrencyLimit", limit].concat(__slice.call(args), [flatMap_(this, makeSpawner(args), false, limit)]));
};
Observable.prototype.flatMapLatest = function() {
var f, stream;
f = makeSpawner(arguments);
stream = this.toEventStream();
return withDescription(this, "flatMapLatest", f, stream.flatMap(function(value) {
return makeObservable(f(value)).takeUntil(stream);
}));
};
Observable.prototype.flatMapError = function(fn) {
return withDescription(this, "flatMapError", fn, this.mapError(function(err) {
return new Bacon.Error(err);
}).flatMap(function(x) {
if (x instanceof Bacon.Error) {
return fn(x.error);
} else {
return Bacon.once(x);
}
}));
};
Observable.prototype.flatMapConcat = function() {
return withDescription.apply(null, [this, "flatMapConcat"].concat(__slice.call(arguments), [this.flatMapWithConcurrencyLimit.apply(this, [1].concat(__slice.call(arguments)))]));
};
Observable.prototype.bufferingThrottle = function(minimumInterval) {
return withDescription(this, "bufferingThrottle", minimumInterval, this.flatMapConcat(function(x) {
return Bacon.once(x).concat(Bacon.later(minimumInterval).filter(false));
}));
};
Observable.prototype.not = function() {
return withDescription(this, "not", this.map(function(x) {
return !x;
}));
};
Observable.prototype.log = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
this.subscribe(function(event) {
return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log.apply(console, __slice.call(args).concat([event.log()])) : void 0 : void 0;
});
return this;
};
Observable.prototype.slidingWindow = function(n, minValues) {
if (minValues == null) {
minValues = 0;
}
return withDescription(this, "slidingWindow", n, minValues, this.scan([], (function(window, value) {
return window.concat([value]).slice(-n);
})).filter((function(values) {
return values.length >= minValues;
})));
};
Observable.prototype.combine = function(other, f) {
var combinator;
combinator = toCombinator(f);
return withDescription(this, "combine", other, f, Bacon.combineAsArray(this, other).map(function(values) {
return combinator(values[0], values[1]);
}));
};
Observable.prototype.decode = function(cases) {
return withDescription(this, "decode", cases, this.combine(Bacon.combineTemplate(cases), function(key, values) {
return values[key];
}));
};
Observable.prototype.awaiting = function(other) {
return withDescription(this, "awaiting", other, Bacon.groupSimultaneous(this, other).map(function(_arg) {
var myValues, otherValues;
myValues = _arg[0], otherValues = _arg[1];
return otherValues.length === 0;
}).toProperty(false).skipDuplicates());
};
Observable.prototype.name = function(name) {
this.toString = function() {
return name;
};
return this;
};
Observable.prototype.withDescription = function() {
return describe.apply(null, arguments).apply(this);
};
return Observable;
})();
Observable.prototype.reduce = Observable.prototype.fold;
Observable.prototype.assign = Observable.prototype.onValue;
flatMap_ = function(root, f, firstOnly, limit) {
var deps, result;
deps = [root];
result = new EventStream(describe(root, "flatMap" + (firstOnly ? "First" : ""), f), function(sink) {
var checkEnd, checkQueue, composite, queue, spawn;
composite = new CompositeUnsubscribe();
queue = [];
spawn = function(event) {
var child;
child = makeObservable(f(event.value()));
deps.push(child);
DepCache.invalidate();
return composite.add(function(unsubAll, unsubMe) {
return child.subscribeInternal(function(event) {
var reply;
if (event.isEnd()) {
_.remove(child, deps);
DepCache.invalidate();
checkQueue();
checkEnd(unsubMe);
return Bacon.noMore;
} else {
if (event instanceof Initial) {
event = event.toNext();
}
reply = sink(event);
if (reply === Bacon.noMore) {
unsubAll();
}
return reply;
}
});
});
};
checkQueue = function() {
var event;
event = queue.splice(0, 1)[0];
if (event) {
return spawn(event);
}
};
checkEnd = function(unsub) {
unsub();
if (composite.empty()) {
return sink(end());
}
};
composite.add(function(__, unsubRoot) {
return root.subscribeInternal(function(event) {
if (event.isEnd()) {
return checkEnd(unsubRoot);
} else if (event.isError()) {
return sink(event);
} else if (firstOnly && composite.count() > 1) {
return Bacon.more;
} else {
if (composite.unsubscribed) {
return Bacon.noMore;
}
if (limit && composite.count() > limit) {
return queue.push(event);
} else {
return spawn(event);
}
}
});
});
return composite.unsubscribe;
});
result.internalDeps = function() {
return deps;
};
return result;
};
EventStream = (function(_super) {
__extends(EventStream, _super);
function EventStream(desc, subscribe) {
var dispatcher;
if (isFunction(desc)) {
subscribe = desc;
desc = [];
}
EventStream.__super__.constructor.call(this, desc);
assertFunction(subscribe);
dispatcher = new Dispatcher(subscribe);
this.subscribeInternal = dispatcher.subscribe;
this.subscribe = UpdateBarrier.wrappedSubscribe(this);
this.hasSubscribers = dispatcher.hasSubscribers;
registerObs(this);
}
EventStream.prototype.delay = function(delay) {
return withDescription(this, "delay", delay, this.flatMap(function(value) {
return Bacon.later(delay, value);
}));
};
EventStream.prototype.debounce = function(delay) {
return withDescription(this, "debounce", delay, this.flatMapLatest(function(value) {
return Bacon.later(delay, value);
}));
};
EventStream.prototype.debounceImmediate = function(delay) {
return withDescription(this, "debounceImmediate", delay, this.flatMapFirst(function(value) {
return Bacon.once(value).concat(Bacon.later(delay).filter(false));
}));
};
EventStream.prototype.throttle = function(delay) {
return withDescription(this, "throttle", delay, this.bufferWithTime(delay).map(function(values) {
return values[values.length - 1];
}));
};
EventStream.prototype.bufferWithTime = function(delay) {
return withDescription(this, "bufferWithTime", delay, this.bufferWithTimeOrCount(delay, Number.MAX_VALUE));
};
EventStream.prototype.bufferWithCount = function(count) {
return withDescription(this, "bufferWithCount", count, this.bufferWithTimeOrCount(void 0, count));
};
EventStream.prototype.bufferWithTimeOrCount = function(delay, count) {
var flushOrSchedule;
flushOrSchedule = function(buffer) {
if (buffer.values.length === count) {
return buffer.flush();
} else if (delay !== void 0) {
return buffer.schedule();
}
};
return withDescription(this, "bufferWithTimeOrCount", delay, count, this.buffer(delay, flushOrSchedule, flushOrSchedule));
};
EventStream.prototype.buffer = function(delay, onInput, onFlush) {
var buffer, delayMs, reply;
if (onInput == null) {
onInput = (function() {});
}
if (onFlush == null) {
onFlush = (function() {});
}
buffer = {
scheduled: false,
end: null,
values: [],
flush: function() {
var reply;
this.scheduled = false;
if (this.values.length > 0) {
reply = this.push(next(this.values));
this.values = [];
if (this.end != null) {
return this.push(this.end);
} else if (reply !== Bacon.noMore) {
return onFlush(this);
}
} else {
if (this.end != null) {
return this.push(this.end);
}
}
},
schedule: function() {
if (!this.scheduled) {
this.scheduled = true;
return delay((function(_this) {
return function() {
return _this.flush();
};
})(this));
}
}
};
reply = Bacon.more;
if (!isFunction(delay)) {
delayMs = delay;
delay = function(f) {
return Bacon.scheduler.setTimeout(f, delayMs);
};
}
return withDescription(this, "buffer", this.withHandler(function(event) {
buffer.push = this.push;
if (event.isError()) {
reply = this.push(event);
} else if (event.isEnd()) {
buffer.end = event;
if (!buffer.scheduled) {
buffer.flush();
}
} else {
buffer.values.push(event.value());
onInput(buffer);
}
return reply;
}));
};
EventStream.prototype.merge = function(right) {
var left;
assertEventStream(right);
left = this;
return withDescription(left, "merge", right, Bacon.mergeAll(this, right));
};
EventStream.prototype.toProperty = function(initValue) {
if (arguments.length === 0) {
initValue = None;
}
return withDescription(this, "toProperty", initValue, this.scan(initValue, latterF, {
lazyF: true
}));
};
EventStream.prototype.toEventStream = function() {
return this;
};
EventStream.prototype.sampledBy = function(sampler, combinator) {
return withDescription(this, "sampledBy", sampler, combinator, this.toProperty().sampledBy(sampler, combinator));
};
EventStream.prototype.concat = function(right) {
var left;
left = this;
return new EventStream(describe(left, "concat", right), function(sink) {
var unsubLeft, unsubRight;
unsubRight = nop;
unsubLeft = left.subscribeInternal(function(e) {
if (e.isEnd()) {
return unsubRight = right.subscribeInternal(sink);
} else {
return sink(e);
}
});
return function() {
unsubLeft();
return unsubRight();
};
});
};
EventStream.prototype.takeUntil = function(stopper) {
var endMarker;
endMarker = {};
return withDescription(this, "takeUntil", stopper, Bacon.groupSimultaneous(this.mapEnd(endMarker), stopper.skipErrors()).withHandler(function(event) {
var data, reply, value, _i, _len, _ref1;
if (!event.hasValue()) {
return this.push(event);
} else {
_ref1 = event.value(), data = _ref1[0], stopper = _ref1[1];
if (stopper.length) {
return this.push(end());
} else {
reply = Bacon.more;
for (_i = 0, _len = data.length; _i < _len; _i++) {
value = data[_i];
if (value === endMarker) {
reply = this.push(end());
} else {
reply = this.push(next(value));
}
}
return reply;
}
}
}));
};
EventStream.prototype.skipUntil = function(starter) {
var started;
started = starter.take(1).map(true).toProperty(false);
return withDescription(this, "skipUntil", starter, this.filter(started));
};
EventStream.prototype.skipWhile = function() {
var args, f, ok;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
ok = false;
return convertArgsToFunction(this, f, args, function(f) {
return withDescription(this, "skipWhile", f, this.withHandler(function(event) {
if (ok || !event.hasValue() || !f(event.value())) {
if (event.hasValue()) {
ok = true;
}
return this.push(event);
} else {
return Bacon.more;
}
}));
});
};
EventStream.prototype.holdWhen = function(valve) {
var putToHold, releaseHold, valve_;
valve_ = valve.startWith(false);
releaseHold = valve_.filter(function(x) {
return !x;
});
putToHold = valve_.filter(_.id);
return withDescription(this, "holdWhen", valve, this.filter(false).merge(valve_.flatMapConcat((function(_this) {
return function(shouldHold) {
if (!shouldHold) {
return _this.takeUntil(putToHold);
} else {
return _this.scan([], (function(xs, x) {
return xs.concat(x);
}), {
eager: true
}).sampledBy(releaseHold).take(1).flatMap(Bacon.fromArray);
}
};
})(this))));
};
EventStream.prototype.startWith = function(seed) {
return withDescription(this, "startWith", seed, Bacon.once(seed).concat(this));
};
EventStream.prototype.withHandler = function(handler) {
var dispatcher;
dispatcher = new Dispatcher(this.subscribeInternal, handler);
return new EventStream(describe(this, "withHandler", handler), dispatcher.subscribe);
};
return EventStream;
})(Observable);
Property = (function(_super) {
__extends(Property, _super);
function Property(desc, subscribe, handler) {
if (isFunction(desc)) {
handler = subscribe;
subscribe = desc;
desc = [];
}
Property.__super__.constructor.call(this, desc);
assertFunction(subscribe);
if (handler === true) {
this.subscribeInternal = subscribe;
} else {
this.subscribeInternal = new PropertyDispatcher(this, subscribe, handler).subscribe;
}
this.subscribe = UpdateBarrier.wrappedSubscribe(this);
registerObs(this);
}
Property.prototype.sampledBy = function(sampler, combinator) {
var lazy, result, samplerSource, stream, thisSource;
if (combinator != null) {
combinator = toCombinator(combinator);
} else {
lazy = true;
combinator = function(f) {
return f();
};
}
thisSource = new Source(this, false, this.subscribeInternal, lazy);
samplerSource = new Source(sampler, true, sampler.subscribeInternal, lazy);
stream = Bacon.when([thisSource, samplerSource], combinator);
result = sampler instanceof Property ? stream.toProperty() : stream;
return withDescription(this, "sampledBy", sampler, combinator, result);
};
Property.prototype.sample = function(interval) {
return withDescription(this, "sample", interval, this.sampledBy(Bacon.interval(interval, {})));
};
Property.prototype.changes = function() {
return new EventStream(describe(this, "changes"), (function(_this) {
return function(sink) {
return _this.subscribeInternal(function(event) {
if (!event.isInitial()) {
return sink(event);
}
});
};
})(this));
};
Property.prototype.withHandler = function(handler) {
return new Property(describe(this, "withHandler", handler), this.subscribeInternal, handler);
};
Property.prototype.toProperty = function() {
assertNoArguments(arguments);
return this;
};
Property.prototype.toEventStream = function() {
return new EventStream(describe(this, "toEventStream"), (function(_this) {
return function(sink) {
return _this.subscribeInternal(function(event) {
if (event.isInitial()) {
event = event.toNext();
}
return sink(event);
});
};
})(this));
};
Property.prototype.and = function(other) {
return withDescription(this, "and", other, this.combine(other, function(x, y) {
return x && y;
}));
};
Property.prototype.or = function(other) {
return withDescription(this, "or", other, this.combine(other, function(x, y) {
return x || y;
}));
};
Property.prototype.delay = function(delay) {
return this.delayChanges("delay", delay, function(changes) {
return changes.delay(delay);
});
};
Property.prototype.debounce = function(delay) {
return this.delayChanges("debounce", delay, function(changes) {
return changes.debounce(delay);
});
};
Property.prototype.throttle = function(delay) {
return this.delayChanges("throttle", delay, function(changes) {
return changes.throttle(delay);
});
};
Property.prototype.delayChanges = function() {
var desc, f, _i;
desc = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), f = arguments[_i++];
return withDescription.apply(null, [this].concat(__slice.call(desc), [addPropertyInitValueToStream(this, f(this.changes()))]));
};
Property.prototype.takeUntil = function(stopper) {
var changes;
changes = this.changes().takeUntil(stopper);
return withDescription(this, "takeUntil", stopper, addPropertyInitValueToStream(this, changes));
};
Property.prototype.startWith = function(value) {
return withDescription(this, "startWith", value, this.scan(value, function(prev, next) {
return next;
}));
};
Property.prototype.bufferingThrottle = function() {
var _ref1;
return (_ref1 = Property.__super__.bufferingThrottle.apply(this, arguments)).bufferingThrottle.apply(_ref1, arguments).toProperty();
};
return Property;
})(Observable);
convertArgsToFunction = function(obs, f, args, method) {
var sampled;
if (f instanceof Property) {
sampled = f.sampledBy(obs, function(p, s) {
return [p, s];
});
return method.apply(sampled, [
function(_arg) {
var p, s;
p = _arg[0], s = _arg[1];
return p;
}
]).map(function(_arg) {
var p, s;
p = _arg[0], s = _arg[1];
return s;
});
} else {
f = makeFunction(f, args);
return method.apply(obs, [f]);
}
};
addPropertyInitValueToStream = function(property, stream) {
var justInitValue;
justInitValue = new EventStream(describe(property, "justInitValue"), function(sink) {
var unsub, value;
value = null;
unsub = property.subscribeInternal(function(event) {
if (event.hasValue()) {
value = event;
}
return Bacon.noMore;
});
UpdateBarrier.whenDoneWith(justInitValue, function() {
if (value != null) {
sink(value);
}
return sink(end());
});
return unsub;
});
return justInitValue.concat(stream).toProperty();
};
Dispatcher = (function() {
function Dispatcher(subscribe, handleEvent) {
var done, ended, prevError, pushIt, pushing, queue, removeSub, subscriptions, unsubscribeFromSource, waiters;
if (subscribe == null) {
subscribe = function() {
return nop;
};
}
subscriptions = [];
queue = [];
pushing = false;
ended = false;
this.hasSubscribers = function() {
return subscriptions.length > 0;
};
prevError = null;
unsubscribeFromSource = nop;
removeSub = function(subscription) {
return subscriptions = _.without(subscription, subscriptions);
};
waiters = null;
done = function() {
var w, ws, _i, _len, _results;
if (waiters != null) {
ws = waiters;
waiters = null;
_results = [];
for (_i = 0, _len = ws.length; _i < _len; _i++) {
w = ws[_i];
_results.push(w());
}
return _results;
}
};
pushIt = function(event) {
var reply, sub, success, tmp, _i, _len;
if (!pushing) {
if (event === prevError) {
return;
}
if (event.isError()) {
prevError = event;
}
success = false;
try {
pushing = true;
tmp = subscriptions;
for (_i = 0, _len = tmp.length; _i < _len; _i++) {
sub = tmp[_i];
reply = sub.sink(event);
if (reply === Bacon.noMore || event.isEnd()) {
removeSub(sub);
}
}
success = true;
} finally {
pushing = false;
if (!success) {
queue = [];
}
}
success = true;
while (queue.length) {
event = queue.shift();
this.push(event);
}
done(event);
if (this.hasSubscribers()) {
return Bacon.more;
} else {
unsubscribeFromSource();
return Bacon.noMore;
}
} else {
queue.push(event);
return Bacon.more;
}
};
this.push = (function(_this) {
return function(event) {
return UpdateBarrier.inTransaction(event, _this, pushIt, [event]);
};
})(this);
if (handleEvent == null) {
handleEvent = function(event) {
return this.push(event);
};
}
this.handleEvent = (function(_this) {
return function(event) {
if (event.isEnd()) {
ended = true;
}
return handleEvent.apply(_this, [event]);
};
})(this);
this.subscribe = (function(_this) {
return function(sink) {
var subscription, unsubSrc;
if (ended) {
sink(end());
return nop;
} else {
assertFunction(sink);
subscription = {
sink: sink
};
subscriptions.push(subscription);
if (subscriptions.length === 1) {
unsubSrc = subscribe(_this.handleEvent);
unsubscribeFromSource = function() {
unsubSrc();
return unsubscribeFromSource = nop;
};
}
assertFunction(unsubscribeFromSource);
return function() {
removeSub(subscription);
if (!_this.hasSubscribers()) {
return unsubscribeFromSource();
}
};
}
};
})(this);
}
return Dispatcher;
})();
PropertyDispatcher = (function(_super) {
__extends(PropertyDispatcher, _super);
function PropertyDispatcher(p, subscribe, handleEvent) {
var current, currentValueRootId, ended, push;
PropertyDispatcher.__super__.constructor.call(this, subscribe, handleEvent);
current = None;
currentValueRootId = void 0;
push = this.push;
subscribe = this.subscribe;
ended = false;
this.push = (function(_this) {
return function(event) {
if (event.isEnd()) {
ended = true;
}
if (event.hasValue()) {
current = new Some(event);
currentValueRootId = UpdateBarrier.currentEventId();
}
return push.apply(_this, [event]);
};
})(this);
this.subscribe = (function(_this) {
return function(sink) {
var dispatchingId, initSent, maybeSubSource, reply, valId;
initSent = false;
reply = Bacon.more;
maybeSubSource = function() {
if (reply === Bacon.noMore) {
return nop;
} else if (ended) {
sink(end());
return nop;
} else {
return subscribe.apply(this, [sink]);
}
};
if (current.isDefined && (_this.hasSubscribers() || ended)) {
dispatchingId = UpdateBarrier.currentEventId();
valId = currentValueRootId;
if (!ended && valId && dispatchingId && dispatchingId !== valId) {
UpdateBarrier.whenDoneWith(p, function() {
if (currentValueRootId === valId) {
return sink(initial(current.get().value()));
}
});
return maybeSubSource();
} else {
UpdateBarrier.inTransaction(void 0, _this, (function() {
return reply = sink(initial(current.get().value()));
}), []);
return maybeSubSource();
}
} else {
return maybeSubSource();
}
};
})(this);
}
return PropertyDispatcher;
})(Dispatcher);
Bus = (function(_super) {
__extends(Bus, _super);
function Bus() {
var ended, guardedSink, sink, subscribeAll, subscribeInput, subscriptions, unsubAll, unsubscribeInput;
sink = void 0;
subscriptions = [];
ended = false;
guardedSink = (function(_this) {
return function(input) {
return function(event) {
if (event.isEnd()) {
unsubscribeInput(input);
return Bacon.noMore;
} else {
return sink(event);
}
};
};
})(this);
unsubAll = function() {
var sub, _i, _len, _results;
_results = [];
for (_i = 0, _len = subscriptions.length; _i < _len; _i++) {
sub = subscriptions[_i];
_results.push(typeof sub.unsub === "function" ? sub.unsub() : void 0);
}
return _results;
};
subscribeInput = function(subscription) {
return subscription.unsub = subscription.input.subscribeInternal(guardedSink(subscription.input));
};
unsubscribeInput = function(input) {
var i, sub, _i, _len;
for (i = _i = 0, _len = subscriptions.length; _i < _len; i = ++_i) {
sub = subscriptions[i];
if (sub.input === input) {
if (typeof sub.unsub === "function") {
sub.unsub();
}
subscriptions.splice(i, 1);
return;
}
}
};
subscribeAll = (function(_this) {
return function(newSink) {
var subscription, _i, _len, _ref1;
sink = newSink;
_ref1 = cloneArray(subscriptions);
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
subscription = _ref1[_i];
subscribeInput(subscription);
}
return unsubAll;
};
})(this);
Bus.__super__.constructor.call(this, describe(Bacon, "Bus"), subscribeAll);
this.plug = (function(_this) {
return function(input) {
var sub;
if (ended) {
return;
}
sub = {
input: input
};
subscriptions.push(sub);
if ((sink != null)) {
subscribeInput(sub);
}
return function() {
return unsubscribeInput(input);
};
};
})(this);
this.push = (function(_this) {
return function(value) {
return typeof sink === "function" ? sink(next(value)) : void 0;
};
})(this);
this.error = (function(_this) {
return function(error) {
return typeof sink === "function" ? sink(new Error(error)) : void 0;
};
})(this);
this.end = (function(_this) {
return function() {
ended = true;
unsubAll();
return typeof sink === "function" ? sink(end()) : void 0;
};
})(this);
}
return Bus;
})(EventStream);
Source = (function() {
function Source(obs, sync, subscribe, lazy) {
this.obs = obs;
this.sync = sync;
this.subscribe = subscribe;
this.lazy = lazy != null ? lazy : false;
this.queue = [];
if (this.subscribe == null) {
this.subscribe = this.obs.subscribeInternal;
}
this.toString = this.obs.toString;
}
Source.prototype.markEnded = function() {
return this.ended = true;
};
Source.prototype.consume = function() {
if (this.lazy) {
return _.always(this.queue[0]);
} else {
return this.queue[0];
}
};
Source.prototype.push = function(x) {
return this.queue = [x];
};
Source.prototype.mayHave = function() {
return true;
};
Source.prototype.hasAtLeast = function() {
return this.queue.length;
};
Source.prototype.flatten = true;
return Source;
})();
ConsumingSource = (function(_super) {
__extends(ConsumingSource, _super);
function ConsumingSource() {
return ConsumingSource.__super__.constructor.apply(this, arguments);
}
ConsumingSource.prototype.consume = function() {
return this.queue.shift();
};
ConsumingSource.prototype.push = function(x) {
return this.queue.push(x);
};
ConsumingSource.prototype.mayHave = function(c) {
return !this.ended || this.queue.length >= c;
};
ConsumingSource.prototype.hasAtLeast = function(c) {
return this.queue.length >= c;
};
ConsumingSource.prototype.flatten = false;
return ConsumingSource;
})(Source);
BufferingSource = (function(_super) {
__extends(BufferingSource, _super);
function BufferingSource(obs) {
this.obs = obs;
BufferingSource.__super__.constructor.call(this, this.obs, true, this.obs.subscribeInternal);
}
BufferingSource.prototype.consume = function() {
var values;
values = this.queue;
this.queue = [];
return function() {
return values;
};
};
BufferingSource.prototype.push = function(x) {
return this.queue.push(x());
};
BufferingSource.prototype.hasAtLeast = function() {
return true;
};
return BufferingSource;
})(Source);
Source.isTrigger = function(s) {
if (s instanceof Source) {
return s.sync;
} else {
return s instanceof EventStream;
}
};
Source.fromObservable = function(s) {
if (s instanceof Source) {
return s;
} else if (s instanceof Property) {
return new Source(s, false);
} else {
return new ConsumingSource(s, true);
}
};
describe = function() {
var args, context, method;
context = arguments[0], method = arguments[1], args = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
if ((context || method) instanceof Desc) {
return context || method;
} else {
return new Desc(context, method, args);
}
};
findDeps = function(x) {
if (isArray(x)) {
return _.flatMap(findDeps, x);
} else if (isObservable(x)) {
return [x];
} else if (x instanceof Source) {
return [x.obs];
} else {
return [];
}
};
Desc = (function() {
function Desc(context, method, args) {
this.context = context;
this.method = method;
this.args = args;
}
Desc.prototype.apply = function(obs) {
var deps, that;
that = this;
deps = _.cached((function() {
return findDeps([that.context].concat(that.args));
}));
obs.internalDeps = obs.internalDeps || deps;
obs.dependsOn = DepCache.dependsOn;
obs.deps = deps;
obs.toString = (function() {
return _.toString(that.context) + "." + _.toString(that.method) + "(" + _.map(_.toString, that.args) + ")";
});
obs.inspect = function() {
return obs.toString();
};
obs.desc = (function() {
return {
context: that.context,
method: that.method,
args: that.args
};
});
return obs;
};
return Desc;
})();
withDescription = function() {
var desc, obs, _i;
desc = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), obs = arguments[_i++];
return describe.apply(null, desc).apply(obs);
};
Bacon.when = function() {
var f, i, index, ix, len, needsBarrier, pat, patSources, pats, patterns, resultStream, s, sources, triggerFound, usage, _i, _j, _len, _len1, _ref1;
patterns = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (patterns.length === 0) {
return Bacon.never();
}
len = patterns.length;
usage = "when: expecting arguments in the form (Observable+,function)+";
assert(usage, len % 2 === 0);
sources = [];
pats = [];
i = 0;
while (i < len) {
patSources = _.toArray(patterns[i]);
f = patterns[i + 1];
pat = {
f: (isFunction(f) ? f : (function() {
return f;
})),
ixs: []
};
triggerFound = false;
for (_i = 0, _len = patSources.length; _i < _len; _i++) {
s = patSources[_i];
index = _.indexOf(sources, s);
if (!triggerFound) {
triggerFound = Source.isTrigger(s);
}
if (index < 0) {
sources.push(s);
index = sources.length - 1;
}
_ref1 = pat.ixs;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
ix = _ref1[_j];
if (ix.index === index) {
ix.count++;
}
}
pat.ixs.push({
index: index,
count: 1
});
}
assert("At least one EventStream required", triggerFound || (!patSources.length));
if (patSources.length > 0) {
pats.push(pat);
}
i = i + 2;
}
if (!sources.length) {
return Bacon.never();
}
sources = _.map(Source.fromObservable, sources);
needsBarrier = (_.any(sources, function(s) {
return s.flatten;
})) && (containsDuplicateDeps(_.map((function(s) {
return s.obs;
}), sources)));
return resultStream = new EventStream(describe.apply(null, [Bacon, "when"].concat(__slice.call(patterns))), function(sink) {
var cannotMatch, cannotSync, ends, match, nonFlattened, part, triggers;
triggers = [];
ends = false;
match = function(p) {
var _k, _len2, _ref2;
_ref2 = p.ixs;
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
i = _ref2[_k];
if (!sources[i.index].hasAtLeast(i.count)) {
return false;
}
}
return true;
};
cannotSync = function(source) {
return !source.sync || source.ended;
};
cannotMatch = function(p) {
var _k, _len2, _ref2;
_ref2 = p.ixs;
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
i = _ref2[_k];
if (!sources[i.index].mayHave(i.count)) {
return true;
}
}
};
nonFlattened = function(trigger) {
return !trigger.source.flatten;
};
part = function(source) {
return function(unsubAll) {
var flush, flushLater, flushWhileTriggers;
flushLater = function() {
return UpdateBarrier.whenDoneWith(resultStream, flush);
};
flushWhileTriggers = function() {
var functions, p, reply, trigger, _k, _len2;
if (triggers.length > 0) {
reply = Bacon.more;
trigger = triggers.pop();
for (_k = 0, _len2 = pats.length; _k < _len2; _k++) {
p = pats[_k];
if (match(p)) {
functions = (function() {
var _l, _len3, _ref2, _results;
_ref2 = p.ixs;
_results = [];
for (_l = 0, _len3 = _ref2.length; _l < _len3; _l++) {
i = _ref2[_l];
_results.push(sources[i.index].consume());
}
return _results;
})();
reply = sink(trigger.e.apply(function() {
var fun, values;
values = (function() {
var _l, _len3, _results;
_results = [];
for (_l = 0, _len3 = functions.length; _l < _len3; _l++) {
fun = functions[_l];
_results.push(fun());
}
return _results;
})();
return p.f.apply(p, values);
}));
if (triggers.length && needsBarrier) {
triggers = _.filter(nonFlattened, triggers);
}
if (reply === Bacon.noMore) {
return reply;
} else {
return flushWhileTriggers();
}
}
}
} else {
return Bacon.more;
}
};
flush = function() {
var reply;
reply = flushWhileTriggers();
if (ends) {
ends = false;
if (_.all(sources, cannotSync) || _.all(pats, cannotMatch)) {
reply = Bacon.noMore;
sink(end());
}
}
if (reply === Bacon.noMore) {
unsubAll();
}
return reply;
};
return source.subscribe(function(e) {
var reply;
if (e.isEnd()) {
ends = true;
source.markEnded();
flushLater();
} else if (e.isError()) {
reply = sink(e);
} else {
source.push(e.value);
if (source.sync) {
triggers.push({
source: source,
e: e
});
if (needsBarrier || UpdateBarrier.hasWaiters()) {
flushLater();
} else {
flush();
}
}
}
if (reply === Bacon.noMore) {
unsubAll();
}
return reply || Bacon.more;
});
};
};
return compositeUnsubscribe.apply(null, (function() {
var _k, _len2, _results;
_results = [];
for (_k = 0, _len2 = sources.length; _k < _len2; _k++) {
s = sources[_k];
_results.push(part(s));
}
return _results;
})());
});
};
containsDuplicateDeps = function(observables, state) {
var checkObservable;
if (state == null) {
state = [];
}
checkObservable = function(obs) {
var deps;
if (Bacon._.contains(state, obs)) {
return true;
} else {
deps = obs.internalDeps();
if (deps.length) {
state.push(obs);
return Bacon._.any(deps, checkObservable);
} else {
state.push(obs);
return false;
}
}
};
return Bacon._.any(observables, checkObservable);
};
Bacon.update = function() {
var i, initial, lateBindFirst, patterns;
initial = arguments[0], patterns = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
lateBindFirst = function(f) {
return function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return function(i) {
return f.apply(null, [i].concat(args));
};
};
};
i = patterns.length - 1;
while (i > 0) {
if (!(patterns[i] instanceof Function)) {
patterns[i] = (function(x) {
return function() {
return x;
};
})(patterns[i]);
}
patterns[i] = lateBindFirst(patterns[i]);
i = i - 2;
}
return withDescription.apply(null, [Bacon, "update", initial].concat(__slice.call(patterns), [Bacon.when.apply(Bacon, patterns).scan(initial, (function(x, f) {
return f(x);
}))]));
};
compositeUnsubscribe = function() {
var ss;
ss = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return new CompositeUnsubscribe(ss).unsubscribe;
};
CompositeUnsubscribe = (function() {
function CompositeUnsubscribe(ss) {
var s, _i, _len;
if (ss == null) {
ss = [];
}
this.unsubscribe = __bind(this.unsubscribe, this);
this.unsubscribed = false;
this.subscriptions = [];
this.starting = [];
for (_i = 0, _len = ss.length; _i < _len; _i++) {
s = ss[_i];
this.add(s);
}
}
CompositeUnsubscribe.prototype.add = function(subscription) {
var ended, unsub, unsubMe;
if (this.unsubscribed) {
return;
}
ended = false;
unsub = nop;
this.starting.push(subscription);
unsubMe = (function(_this) {
return function() {
if (_this.unsubscribed) {
return;
}
ended = true;
_this.remove(unsub);
return _.remove(subscription, _this.starting);
};
})(this);
unsub = subscription(this.unsubscribe, unsubMe);
if (!(this.unsubscribed || ended)) {
this.subscriptions.push(unsub);
}
_.remove(subscription, this.starting);
return unsub;
};
CompositeUnsubscribe.prototype.remove = function(unsub) {
if (this.unsubscribed) {
return;
}
if ((_.remove(unsub, this.subscriptions)) !== void 0) {
return unsub();
}
};
CompositeUnsubscribe.prototype.unsubscribe = function() {
var s, _i, _len, _ref1;
if (this.unsubscribed) {
return;
}
this.unsubscribed = true;
_ref1 = this.subscriptions;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
s = _ref1[_i];
s();
}
this.subscriptions = [];
return this.starting = [];
};
CompositeUnsubscribe.prototype.count = function() {
if (this.unsubscribed) {
return 0;
}
return this.subscriptions.length + this.starting.length;
};
CompositeUnsubscribe.prototype.empty = function() {
return this.count() === 0;
};
return CompositeUnsubscribe;
})();
Bacon.CompositeUnsubscribe = CompositeUnsubscribe;
Some = (function() {
function Some(value) {
this.value = value;
}
Some.prototype.getOrElse = function() {
return this.value;
};
Some.prototype.get = function() {
return this.value;
};
Some.prototype.filter = function(f) {
if (f(this.value)) {
return new Some(this.value);
} else {
return None;
}
};
Some.prototype.map = function(f) {
return new Some(f(this.value));
};
Some.prototype.forEach = function(f) {
return f(this.value);
};
Some.prototype.isDefined = true;
Some.prototype.toArray = function() {
return [this.value];
};
Some.prototype.inspect = function() {
return "Some(" + this.value + ")";
};
Some.prototype.toString = function() {
return this.inspect();
};
return Some;
})();
None = {
getOrElse: function(value) {
return value;
},
filter: function() {
return None;
},
map: function() {
return None;
},
forEach: function() {},
isDefined: false,
toArray: function() {
return [];
},
inspect: function() {
return "None";
},
toString: function() {
return this.inspect();
}
};
DepCache = (function() {
var collectDeps, dependsOn, flatDeps, invalidate;
flatDeps = {};
dependsOn = function(b) {
var myDeps;
myDeps = flatDeps[this.id];
if (!myDeps) {
myDeps = flatDeps[this.id] = {};
collectDeps(this, this);
}
return myDeps[b.id];
};
collectDeps = function(orig, o) {
var dep, _i, _len, _ref1, _results;
_ref1 = o.internalDeps();
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
dep = _ref1[_i];
flatDeps[orig.id][dep.id] = true;
_results.push(collectDeps(orig, dep));
}
return _results;
};
invalidate = function() {
return flatDeps = {};
};
return {
invalidate: invalidate,
dependsOn: dependsOn
};
})();
UpdateBarrier = (function() {
var afterTransaction, afters, currentEventId, findIndependent, flush, hasWaiters, inTransaction, independent, invalidateDeps, rootEvent, waiters, whenDoneWith, wrappedSubscribe;
rootEvent = void 0;
waiters = [];
afters = [];
afterTransaction = function(f) {
if (rootEvent) {
return afters.push(f);
} else {
return f();
}
};
independent = function(waiter) {
return !_.any(waiters, (function(other) {
return waiter.obs.dependsOn(other.obs);
}));
};
whenDoneWith = function(obs, f) {
if (rootEvent) {
return waiters.push({
obs: obs,
f: f
});
} else {
return f();
}
};
findIndependent = function() {
while (!independent(waiters[0])) {
waiters.push(waiters.splice(0, 1)[0]);
}
return waiters.splice(0, 1)[0];
};
flush = function() {
var _results;
_results = [];
while (waiters.length) {
_results.push(findIndependent().f());
}
return _results;
};
invalidateDeps = DepCache.invalidate;
inTransaction = function(event, context, f, args) {
var result;
if (rootEvent) {
return f.apply(context, args);
} else {
rootEvent = event;
try {
result = f.apply(context, args);
flush();
} finally {
rootEvent = void 0;
while (afters.length) {
f = afters.splice(0, 1)[0];
f();
}
invalidateDeps();
}
return result;
}
};
currentEventId = function() {
if (rootEvent) {
return rootEvent.id;
} else {
return void 0;
}
};
wrappedSubscribe = function(obs) {
return function(sink) {
var doUnsub, unsub, unsubd;
unsubd = false;
doUnsub = function() {};
unsub = function() {
unsubd = true;
return doUnsub();
};
doUnsub = obs.subscribeInternal(function(event) {
return afterTransaction(function() {
var reply;
if (!unsubd) {
reply = sink(event);
if (reply === Bacon.noMore) {
return unsub();
}
}
});
});
return unsub;
};
};
hasWaiters = function() {
return waiters.length > 0;
};
return {
whenDoneWith: whenDoneWith,
hasWaiters: hasWaiters,
inTransaction: inTransaction,
currentEventId: currentEventId,
wrappedSubscribe: wrappedSubscribe
};
})();
Bacon.EventStream = EventStream;
Bacon.Property = Property;
Bacon.Observable = Observable;
Bacon.Bus = Bus;
Bacon.Initial = Initial;
Bacon.Next = Next;
Bacon.End = End;
Bacon.Error = Error;
nop = function() {};
latterF = function(_, x) {
return x();
};
former = function(x, _) {
return x;
};
initial = function(value) {
return new Initial(_.always(value));
};
next = function(value) {
return new Next(_.always(value));
};
end = function() {
return new End();
};
toEvent = function(x) {
if (x instanceof Event) {
return x;
} else {
return next(x);
}
};
cloneArray = function(xs) {
return xs.slice(0);
};
assert = function(message, condition) {
if (!condition) {
throw message;
}
};
assertEventStream = function(event) {
if (!(event instanceof EventStream)) {
throw "not an EventStream : " + event;
}
};
assertFunction = function(f) {
return assert("not a function : " + f, isFunction(f));
};
isFunction = function(f) {
return typeof f === "function";
};
isArray = function(xs) {
return xs instanceof Array;
};
isObservable = function(x) {
return x instanceof Observable;
};
assertArray = function(xs) {
if (!isArray(xs)) {
throw "not an array : " + xs;
}
};
assertNoArguments = function(args) {
return assert("no arguments supported", args.length === 0);
};
assertString = function(x) {
if (typeof x !== "string") {
throw "not a string : " + x;
}
};
partiallyApplied = function(f, applied) {
return function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return f.apply(null, applied.concat(args));
};
};
makeSpawner = function(args) {
if (args.length === 1 && isObservable(args[0])) {
return _.always(args[0]);
} else {
return makeFunctionArgs(args);
}
};
makeFunctionArgs = function(args) {
args = Array.prototype.slice.call(args);
return makeFunction_.apply(null, args);
};
makeFunction_ = withMethodCallSupport(function() {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (isFunction(f)) {
if (args.length) {
return partiallyApplied(f, args);
} else {
return f;
}
} else if (isFieldKey(f)) {
return toFieldExtractor(f, args);
} else {
return _.always(f);
}
});
makeFunction = function(f, args) {
return makeFunction_.apply(null, [f].concat(__slice.call(args)));
};
makeObservable = function(x) {
if (isObservable(x)) {
return x;
} else {
return Bacon.once(x);
}
};
isFieldKey = function(f) {
return (typeof f === "string") && f.length > 1 && f.charAt(0) === ".";
};
Bacon.isFieldKey = isFieldKey;
toFieldExtractor = function(f, args) {
var partFuncs, parts;
parts = f.slice(1).split(".");
partFuncs = _.map(toSimpleExtractor(args), parts);
return function(value) {
var _i, _len;
for (_i = 0, _len = partFuncs.length; _i < _len; _i++) {
f = partFuncs[_i];
value = f(value);
}
return value;
};
};
toSimpleExtractor = function(args) {
return function(key) {
return function(value) {
var fieldValue;
if (value == null) {
return void 0;
} else {
fieldValue = value[key];
if (isFunction(fieldValue)) {
return fieldValue.apply(value, args);
} else {
return fieldValue;
}
}
};
};
};
toFieldKey = function(f) {
return f.slice(1);
};
toCombinator = function(f) {
var key;
if (isFunction(f)) {
return f;
} else if (isFieldKey(f)) {
key = toFieldKey(f);
return function(left, right) {
return left[key](right);
};
} else {
return assert("not a function or a field key: " + f, false);
}
};
toOption = function(v) {
if (v instanceof Some || v === None) {
return v;
} else {
return new Some(v);
}
};
_ = {
indexOf: Array.prototype.indexOf ? function(xs, x) {
return xs.indexOf(x);
} : function(xs, x) {
var i, y, _i, _len;
for (i = _i = 0, _len = xs.length; _i < _len; i = ++_i) {
y = xs[i];
if (x === y) {
return i;
}
}
return -1;
},
indexWhere: function(xs, f) {
var i, y, _i, _len;
for (i = _i = 0, _len = xs.length; _i < _len; i = ++_i) {
y = xs[i];
if (f(y)) {
return i;
}
}
return -1;
},
head: function(xs) {
return xs[0];
},
always: function(x) {
return function() {
return x;
};
},
negate: function(f) {
return function(x) {
return !f(x);
};
},
empty: function(xs) {
return xs.length === 0;
},
tail: function(xs) {
return xs.slice(1, xs.length);
},
filter: function(f, xs) {
var filtered, x, _i, _len;
filtered = [];
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
if (f(x)) {
filtered.push(x);
}
}
return filtered;
},
map: function(f, xs) {
var x, _i, _len, _results;
_results = [];
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
_results.push(f(x));
}
return _results;
},
each: function(xs, f) {
var key, value, _results;
_results = [];
for (key in xs) {
value = xs[key];
_results.push(f(key, value));
}
return _results;
},
toArray: function(xs) {
if (isArray(xs)) {
return xs;
} else {
return [xs];
}
},
contains: function(xs, x) {
return _.indexOf(xs, x) !== -1;
},
id: function(x) {
return x;
},
last: function(xs) {
return xs[xs.length - 1];
},
all: function(xs, f) {
var x, _i, _len;
if (f == null) {
f = _.id;
}
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
if (!f(x)) {
return false;
}
}
return true;
},
any: function(xs, f) {
var x, _i, _len;
if (f == null) {
f = _.id;
}
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
if (f(x)) {
return true;
}
}
return false;
},
without: function(x, xs) {
return _.filter((function(y) {
return y !== x;
}), xs);
},
remove: function(x, xs) {
var i;
i = _.indexOf(xs, x);
if (i >= 0) {
return xs.splice(i, 1);
}
},
fold: function(xs, seed, f) {
var x, _i, _len;
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
seed = f(seed, x);
}
return seed;
},
flatMap: function(f, xs) {
return _.fold(xs, [], (function(ys, x) {
return ys.concat(f(x));
}));
},
cached: function(f) {
var value;
value = None;
return function() {
if (value === None) {
value = f();
f = null;
}
return value;
};
},
toString: function(obj) {
var ex, internals, key, value;
try {
recursionDepth++;
if (obj == null) {
return "undefined";
} else if (isFunction(obj)) {
return "function";
} else if (isArray(obj)) {
if (recursionDepth > 5) {
return "[..]";
}
return "[" + _.map(_.toString, obj).toString() + "]";
} else if (((obj != null ? obj.toString : void 0) != null) && obj.toString !== Object.prototype.toString) {
return obj.toString();
} else if (typeof obj === "object") {
if (recursionDepth > 5) {
return "{..}";
}
internals = (function() {
var _results;
_results = [];
for (key in obj) {
if (!__hasProp.call(obj, key)) continue;
value = (function() {
try {
return obj[key];
} catch (_error) {
ex = _error;
return ex;
}
})();
_results.push(_.toString(key) + ":" + _.toString(value));
}
return _results;
})();
return "{" + internals + "}";
} else {
return obj;
}
} finally {
recursionDepth--;
}
}
};
recursionDepth = 0;
Bacon._ = _;
Bacon.scheduler = {
setTimeout: function(f, d) {
return setTimeout(f, d);
},
setInterval: function(f, i) {
return setInterval(f, i);
},
clearInterval: function(id) {
return clearInterval(id);
},
now: function() {
return new Date().getTime();
}
};
if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
define([], function() {
return Bacon;
});
this.Bacon = Bacon;
} else if (typeof module !== "undefined" && module !== null) {
module.exports = Bacon;
Bacon.Bacon = Bacon;
} else {
this.Bacon = Bacon;
}
}).call(this);
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require_tree .
|
YUI.add('arraylist-filter', function(Y) {
/**
* Collection utilities beyond what is provided in the YUI core
* @module collection
* @submodule arraylist-filter
*/
/**
* Adds filter method to ArrayList prototype
*/
Y.mix(Y.ArrayList.prototype, {
/**
* <p>Create a new ArrayList (or augmenting class instance) from a subset
* of items as determined by the boolean function passed as the
* argument. The original ArrayList is unchanged.</p>
*
* <p>The validator signature is <code>validator( item )</code>.</p>
*
* @method filter
* @param { Function } validator Boolean function to determine in or out.
* @return { ArrayList } New instance based on who passed the validator.
* @for ArrayList
*/
filter: function(validator) {
var items = [];
Y.Array.each(this._items, function(item, i) {
item = this.item(i);
if (validator(item)) {
items.push(item);
}
}, this);
return new this.constructor(items);
}
});
}, '@VERSION@' ,{requires:['arraylist']});
|
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[3],
host: match[4],
port: match[6],
path: match[7]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = aParsedUrl.scheme + "://";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@"
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
function join(aRoot, aPath) {
var url;
if (aPath.match(urlRegexp)) {
return aPath;
}
if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
url.path = aPath;
return urlGenerate(url);
}
return aRoot.replace(/\/$/, '') + '/' + aPath;
}
exports.join = join;
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function relative(aRoot, aPath) {
aRoot = aRoot.replace(/\/$/, '');
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0
? aPath.substr(aRoot.length + 1)
: aPath;
}
exports.relative = relative;
});
|
// Backbone.Marionette v0.8.4
//
// Copyright (C)2012 Derick Bailey, Muted Solutions, LLC
// Distributed Under MIT License
//
// Documentation and Full License Available at:
// http://github.com/derickbailey/backbone.marionette
Backbone.Marionette = (function(Backbone, _, $){
var Marionette = {};
Marionette.version = "0.8.4";
// Marionette.View
// ---------------
// The core view type that other Marionette views extend from.
Marionette.View = Backbone.View.extend({
// Get the template or template id/selector for this view
// instance. You can set a `template` attribute in the view
// definition or pass a `template: "whatever"` parameter in
// to the constructor options. The `template` can also be
// a function that returns a selector string.
getTemplateSelector: function(){
var template;
// Get the template from `this.options.template` or
// `this.template`. The `options` takes precedence.
if (this.options && this.options.template){
template = this.options.template;
} else {
template = this.template;
}
// check if it's a function and execute it, if it is
if (_.isFunction(template)){
template = template.call(this);
}
return template;
},
// Serialize the model or collection for the view. If a model is
// found, `.toJSON()` is called. If a collection is found, `.toJSON()`
// is also called, but is used to populate an `items` array in the
// resulting data. If both are found, defaults to the model.
// You can override the `serializeData` method in your own view
// definition, to provide custom serialization for your view's data.
serializeData: function(){
var data;
if (this.model) {
data = this.model.toJSON();
}
else if (this.collection) {
data = { items: this.collection.toJSON() };
}
data = this.mixinTemplateHelpers(data);
return data;
},
// Mix in template helper methods. Looks for a
// `templateHelpers` attribute, which can either be an
// object literal, or a function that returns an object
// literal. All methods and attributes from this object
// are copies to the object passed in.
mixinTemplateHelpers: function(target){
target = target || {};
var templateHelpers = this.templateHelpers;
if (_.isFunction(templateHelpers)){
templateHelpers = templateHelpers.call(this);
}
return _.extend(target, templateHelpers);
},
// Configure `triggers` to forward DOM events to view
// events. `triggers: {"click .foo": "do:foo"}`
configureTriggers: function(){
if (!this.triggers) { return; }
var triggers = this.triggers;
var that = this;
var triggerEvents = {};
// Allow `triggers` to be configured as a function
if (_.isFunction(triggers)){ triggers = triggers.call(this); }
// Configure the triggers, prevent default
// action and stop propagation of DOM events
_.each(triggers, function(value, key){
triggerEvents[key] = function(e){
if (e && e.preventDefault){ e.preventDefault(); }
if (e && e.stopPropagation){ e.stopPropagation(); }
that.trigger(value);
}
});
return triggerEvents;
},
delegateEvents: function(events){
events = events || this.events;
if (_.isFunction(events)){ events = events.call(this)}
var combinedEvents = {};
var triggers = this.configureTriggers();
_.extend(combinedEvents, events, triggers);
Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
},
// Default `close` implementation, for removing a view from the
// DOM and unbinding it. Regions will call this method
// for you. You can specify an `onClose` method in your view to
// add custom code that is called after the view is closed.
close: function(){
if (this.beforeClose) { this.beforeClose(); }
this.unbindAll();
this.remove();
if (this.onClose) { this.onClose(); }
this.trigger('close');
this.unbind();
}
});
// Item View
// ---------
// A single item view implementation that contains code for rendering
// with underscore.js templates, serializing the view's model or collection,
// and calling several methods on extended views, such as `onRender`.
Marionette.ItemView = Marionette.View.extend({
constructor: function(){
var args = slice.call(arguments);
Marionette.View.prototype.constructor.apply(this, args);
_.bindAll(this, "render");
this.initialEvents();
},
// Configured the initial events that the item view
// binds to. Override this method to prevent the initial
// events, or to add your own initial events.
initialEvents: function(){
if (this.collection){
this.bindTo(this.collection, "reset", this.render, this);
}
},
// Render the view, defaulting to underscore.js templates.
// You can override this in your view definition.
render: function(){
var that = this;
var deferredRender = $.Deferred();
var beforeRenderDone = function() {
that.trigger("before:render", that);
that.trigger("item:before:render", that);
var deferredData = that.serializeData();
$.when(deferredData).then(dataSerialized);
}
var dataSerialized = function(data){
var asyncRender = that.renderHtml(data);
$.when(asyncRender).then(templateRendered);
}
var templateRendered = function(html){
that.$el.html(html);
callDeferredMethod(that.onRender, onRenderDone, that);
}
var onRenderDone = function(){
that.trigger("render", that);
that.trigger("item:rendered", that);
deferredRender.resolve();
}
callDeferredMethod(this.beforeRender, beforeRenderDone, this);
return deferredRender.promise();
},
// Render the data for this item view in to some HTML.
// Override this method to replace the specific way in
// which an item view has it's data rendered in to html.
renderHtml: function(data) {
var template = this.getTemplateSelector();
return Marionette.Renderer.render(template, data);
},
// Override the default close event to add a few
// more events that are triggered.
close: function(){
this.trigger('item:before:close');
Marionette.View.prototype.close.apply(this, arguments);
this.trigger('item:closed');
}
});
// Collection View
// ---------------
// A view that iterates over a Backbone.Collection
// and renders an individual ItemView for each model.
Marionette.CollectionView = Marionette.View.extend({
constructor: function(){
Marionette.View.prototype.constructor.apply(this, arguments);
_.bindAll(this, "addItemView", "render");
this.initialEvents();
},
// Configured the initial events that the collection view
// binds to. Override this method to prevent the initial
// events, or to add your own initial events.
initialEvents: function(){
if (this.collection){
this.bindTo(this.collection, "add", this.addChildView, this);
this.bindTo(this.collection, "remove", this.removeItemView, this);
this.bindTo(this.collection, "reset", this.render, this);
}
},
// Handle a child item added to the collection
addChildView: function(item){
var ItemView = this.getItemView();
return this.addItemView(item, ItemView);
},
// Loop through all of the items and render
// each of them with the specified `itemView`.
render: function(){
var that = this;
var deferredRender = $.Deferred();
var promises = [];
var ItemView = this.getItemView();
if (this.beforeRender) { this.beforeRender(); }
this.trigger("collection:before:render", this);
this.closeChildren();
if (this.collection) {
this.collection.each(function(item){
var promise = that.addItemView(item, ItemView);
promises.push(promise);
});
}
deferredRender.done(function(){
if (this.onRender) { this.onRender(); }
this.trigger("collection:rendered", this);
});
$.when.apply(this, promises).then(function(){
deferredRender.resolveWith(that);
});
return deferredRender.promise();
},
// Retrieve the itemView type, either from `this.options.itemView`
// or from the `itemView` in the object definition. The "options"
// takes precedence.
getItemView: function(){
var itemView = this.options.itemView || this.itemView;
if (!itemView){
var err = new Error("An `itemView` must be specified");
err.name = "NoItemViewError";
throw err;
}
return itemView;
},
// Render the child item's view and add it to the
// HTML for the collection view.
addItemView: function(item, ItemView){
var that = this;
var view = this.buildItemView(item, ItemView);
this.bindTo(view, "all", function(){
// get the args, prepend the event name
// with "itemview:" and insert the child view
// as the first event arg (after the event name)
var args = slice.call(arguments);
args[0] = "itemview:" + args[0];
args.splice(1, 0, view);
that.trigger.apply(that, args);
});
this.storeChild(view);
this.trigger("item:added", view);
var viewRendered = view.render();
$.when(viewRendered).then(function(){
that.appendHtml(that, view);
});
return viewRendered;
},
// Build an `itemView` for every model in the collection.
buildItemView: function(item, ItemView){
var view = new ItemView({
model: item
});
return view;
},
// Remove the child view and close it
removeItemView: function(item){
var view = this.children[item.cid];
if (view){
view.close();
delete this.children[item.cid];
}
this.trigger("item:removed", view);
},
// Append the HTML to the collection's `el`.
// Override this method to do something other
// then `.append`.
appendHtml: function(collectionView, itemView){
collectionView.$el.append(itemView.el);
},
// Store references to all of the child `itemView`
// instances so they can be managed and cleaned up, later.
storeChild: function(view){
if (!this.children){
this.children = {};
}
this.children[view.model.cid] = view;
},
// Handle cleanup and other closing needs for
// the collection of views.
close: function(){
this.trigger("collection:before:close");
this.closeChildren();
Marionette.View.prototype.close.apply(this, arguments);
this.trigger("collection:closed");
},
closeChildren: function(){
if (this.children){
_.each(this.children, function(childView){
childView.close();
});
}
}
});
// Composite View
// --------------
// Used for rendering a branch-leaf, hierarchical structure.
// Extends directly from CollectionView and also renders an
// an item view as `modelView`, for the top leaf
Marionette.CompositeView = Marionette.CollectionView.extend({
constructor: function(options){
Marionette.CollectionView.apply(this, arguments);
this.itemView = this.getItemView();
},
// Retrieve the `itemView` to be used when rendering each of
// the items in the collection. The default is to return
// `this.itemView` or Marionette.CompositeView if no `itemView`
// has been defined
getItemView: function(){
return this.itemView || this.constructor;
},
// Renders the model once, and the collection once. Calling
// this again will tell the model's view to re-render itself
// but the collection will not re-render.
render: function(){
var that = this;
var compositeRendered = $.Deferred();
var modelIsRendered = this.renderModel();
$.when(modelIsRendered).then(function(html){
that.$el.html(html);
that.trigger("composite:model:rendered");
that.trigger("render");
var collectionIsRendered = that.renderCollection();
$.when(collectionIsRendered).then(function(){
compositeRendered.resolve();
});
});
compositeRendered.done(function(){
that.trigger("composite:rendered");
});
return compositeRendered.promise();
},
// Render the collection for the composite view
renderCollection: function(){
var collectionDeferred = Marionette.CollectionView.prototype.render.apply(this, arguments);
collectionDeferred.done(function(){
this.trigger("composite:collection:rendered");
});
return collectionDeferred.promise();
},
// Render an individual model, if we have one, as
// part of a composite view (branch / leaf). For example:
// a treeview.
renderModel: function(){
var data = {};
data = this.serializeData();
var template = this.getTemplateSelector();
return Marionette.Renderer.render(template, data);
}
});
// Region
// ------
// Manage the visual regions of your composite application. See
// http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
Marionette.Region = function(options){
this.options = options || {};
_.extend(this, options);
if (!this.el){
var err = new Error("An 'el' must be specified");
err.name = "NoElError";
throw err;
}
if (this.initialize){
this.initialize.apply(this, arguments);
}
};
_.extend(Marionette.Region.prototype, Backbone.Events, {
// Displays a backbone view instance inside of the region.
// Handles calling the `render` method for you. Reads content
// directly from the `el` attribute. Also calls an optional
// `onShow` and `close` method on your view, just after showing
// or just before closing the view, respectively.
show: function(view, appendMethod){
this.ensureEl();
this.close();
this.open(view, appendMethod);
this.currentView = view;
},
ensureEl: function(){
if (!this.$el || this.$el.length === 0){
this.$el = this.getEl(this.el);
}
},
// Override this method to change how the region finds the
// DOM element that it manages. Return a jQuery selector object.
getEl: function(selector){
return $(selector);
},
// Internal method to render and display a view. Not meant
// to be called from any external code.
open: function(view, appendMethod){
var that = this;
appendMethod = appendMethod || "html";
$.when(view.render()).then(function () {
that.$el[appendMethod](view.el);
if (view.onShow) { view.onShow(); }
if (that.onShow) { that.onShow(view); }
view.trigger("show");
that.trigger("view:show", view);
});
},
// Close the current view, if there is one. If there is no
// current view, it does nothing and returns immediately.
close: function(){
var view = this.currentView;
if (!view){ return; }
if (view.close) { view.close(); }
this.trigger("view:closed", view);
delete this.currentView;
},
// Attach an existing view to the region. This
// will not call `render` or `onShow` for the new view,
// and will not replace the current HTML for the `el`
// of the region.
attachView: function(view){
this.currentView = view;
}
});
// Layout
// ------
// Formerly known as Composite Region.
//
// Used for managing application layouts, nested layouts and
// multiple regions within an application or sub-application.
//
// A specialized view type that renders an area of HTML and then
// attaches `Region` instances to the specified `regions`.
// Used for composite view management and sub-application areas.
Marionette.Layout = Marionette.ItemView.extend({
constructor: function () {
this.vent = new Backbone.Marionette.EventAggregator();
Backbone.Marionette.ItemView.apply(this, arguments);
this.regionManagers = {};
},
render: function () {
this.initializeRegions();
return Backbone.Marionette.ItemView.prototype.render.call(this, arguments);
},
close: function () {
this.closeRegions();
Backbone.Marionette.ItemView.prototype.close.call(this, arguments);
},
// Initialize the regions that have been defined in a
// `regions` attribute on this layout. The key of the
// hash becomes an attribute on the layout object directly.
// For example: `regions: { menu: ".menu-container" }`
// will product a `layout.menu` object which is a region
// that controls the `.menu-container` DOM element.
initializeRegions: function () {
var that = this;
_.each(this.regions, function (selector, name) {
var regionManager = new Backbone.Marionette.Region({
el: selector,
getEl: function(selector){
return that.$(selector);
}
});
that.regionManagers[name] = regionManager;
that[name] = regionManager;
});
},
// Close all of the regions that have been opened by
// this layout. This method is called when the layout
// itself is closed.
closeRegions: function () {
var that = this;
_.each(this.regionManagers, function (manager, name) {
manager.close();
delete that[name];
});
this.regionManagers = {};
}
});
// AppRouter
// ---------
// Reduce the boilerplate code of handling route events
// and then calling a single method on another object.
// Have your routers configured to call the method on
// your object, directly.
//
// Configure an AppRouter with `appRoutes`.
//
// App routers can only take one `controller` object.
// It is recommended that you divide your controller
// objects in to smaller peices of related functionality
// and have multiple routers / controllers, instead of
// just one giant router and controller.
//
// You can also add standard routes to an AppRouter.
Marionette.AppRouter = Backbone.Router.extend({
constructor: function(options){
Backbone.Router.prototype.constructor.call(this, options);
if (this.appRoutes){
var controller = this.controller;
if (options && options.controller) {
controller = options.controller;
}
this.processAppRoutes(controller, this.appRoutes);
}
},
processAppRoutes: function(controller, appRoutes){
var method, methodName;
var route, routesLength, i;
var routes = [];
var router = this;
for(route in appRoutes){
if (appRoutes.hasOwnProperty(route)){
routes.unshift([route, appRoutes[route]]);
}
}
routesLength = routes.length;
for (i = 0; i < routesLength; i++){
route = routes[i][0];
methodName = routes[i][1];
method = controller[methodName];
if (!method){
var msg = "Method '" + methodName + "' was not found on the controller";
var err = new Error(msg);
err.name = "NoMethodError";
throw err;
}
method = _.bind(method, controller);
router.route(route, methodName, method);
}
}
});
// Composite Application
// ---------------------
// Contain and manage the composite application as a whole.
// Stores and starts up `Region` objects, includes an
// event aggregator as `app.vent`
Marionette.Application = function(options){
this.initCallbacks = new Marionette.Callbacks();
this.vent = new Marionette.EventAggregator();
_.extend(this, options);
};
_.extend(Marionette.Application.prototype, Backbone.Events, {
// Add an initializer that is either run at when the `start`
// method is called, or run immediately if added after `start`
// has already been called.
addInitializer: function(initializer){
this.initCallbacks.add(initializer);
},
// kick off all of the application's processes.
// initializes all of the regions that have been added
// to the app, and runs all of the initializer functions
start: function(options){
this.trigger("initialize:before", options);
this.initCallbacks.run(this, options);
this.trigger("initialize:after", options);
this.trigger("start", options);
},
// Add regions to your app.
// Accepts a hash of named strings or Region objects
// addRegions({something: "#someRegion"})
// addRegions{{something: Region.extend({el: "#someRegion"}) });
addRegions: function(regions){
var regionValue, regionObj, region;
for(region in regions){
if (regions.hasOwnProperty(region)){
regionValue = regions[region];
if (typeof regionValue === "string"){
regionObj = new Marionette.Region({
el: regionValue
});
} else {
regionObj = new regionValue();
}
this[region] = regionObj;
}
}
}
});
// BindTo: Event Binding
// ---------------------
// BindTo facilitates the binding and unbinding of events
// from objects that extend `Backbone.Events`. It makes
// unbinding events, even with anonymous callback functions,
// easy.
//
// Thanks to Johnny Oshika for this code.
// http://stackoverflow.com/questions/7567404/backbone-js-repopulate-or-recreate-the-view/7607853#7607853
Marionette.BindTo = {
// Store the event binding in array so it can be unbound
// easily, at a later point in time.
bindTo: function (obj, eventName, callback, context) {
context = context || this;
obj.on(eventName, callback, context);
if (!this.bindings) { this.bindings = []; }
var binding = {
obj: obj,
eventName: eventName,
callback: callback,
context: context
}
this.bindings.push(binding);
return binding;
},
// Unbind from a single binding object. Binding objects are
// returned from the `bindTo` method call.
unbindFrom: function(binding){
binding.obj.off(binding.eventName, binding.callback);
this.bindings = _.reject(this.bindings, function(bind){return bind === binding});
},
// Unbind all of the events that we have stored.
unbindAll: function () {
var that = this;
// The `unbindFrom` call removes elements from the array
// while it is being iterated, so clone it first.
var bindings = _.map(this.bindings, _.identity);
_.each(bindings, function (binding, index) {
that.unbindFrom(binding);
});
}
};
// Callbacks
// ---------
// A simple way of managing a collection of callbacks
// and executing them at a later point in time, using jQuery's
// `Deferred` object.
Marionette.Callbacks = function(){
this.deferred = $.Deferred();
this.promise = this.deferred.promise();
};
_.extend(Marionette.Callbacks.prototype, {
// Add a callback to be executed. Callbacks added here are
// guaranteed to execute, even if they are added after the
// `run` method is called.
add: function(callback){
this.promise.done(function(context, options){
callback.call(context, options);
});
},
// Run all registered callbacks with the context specified.
// Additional callbacks can be added after this has been run
// and they will still be executed.
run: function(context, options){
this.deferred.resolve(context, options);
}
});
// Event Aggregator
// ----------------
// A pub-sub object that can be used to decouple various parts
// of an application through event-driven architecture.
Marionette.EventAggregator = function(options){
_.extend(this, options);
};
_.extend(Marionette.EventAggregator.prototype, Backbone.Events, Marionette.BindTo, {
// Assumes the event aggregator itself is the
// object being bound to.
bindTo: function(eventName, callback, context){
return Marionette.BindTo.bindTo.call(this, this, eventName, callback, context);
}
});
// Template Cache
// --------------
// Manage templates stored in `<script>` blocks,
// caching them for faster access.
Marionette.TemplateCache = {
templates: {},
loaders: {},
// Get the specified template by id. Either
// retrieves the cached version, or loads it
// from the DOM.
get: function(templateId){
var that = this;
var templateRetrieval = $.Deferred();
var cachedTemplate = this.templates[templateId];
if (cachedTemplate){
templateRetrieval.resolve(cachedTemplate);
} else {
var loader = this.loaders[templateId];
if(loader) {
templateRetrieval = loader;
} else {
this.loaders[templateId] = templateRetrieval;
this.loadTemplate(templateId, function(template){
delete that.loaders[templateId];
that.templates[templateId] = template;
templateRetrieval.resolve(template);
});
}
}
return templateRetrieval.promise();
},
// Load a template from the DOM, by default. Override
// this method to provide your own template retrieval,
// such as asynchronous loading from a server.
loadTemplate: function(templateId, callback){
var template = $(templateId).html();
// Make sure we have a template before trying to compile it
if (!template || template.length === 0){
var msg = "Could not find template: '" + templateId + "'";
var err = new Error(msg);
err.name = "NoTemplateError";
throw err;
}
template = this.compileTemplate(template);
callback.call(this, template);
},
// Pre-compile the template before caching it. Override
// this method if you do not need to pre-compile a template
// (JST / RequireJS for example) or if you want to change
// the template engine used (Handebars, etc).
compileTemplate: function(rawTemplate){
return _.template(rawTemplate);
},
// Clear templates from the cache. If no arguments
// are specified, clears all templates:
// `clear()`
//
// If arguments are specified, clears each of the
// specified templates from the cache:
// `clear("#t1", "#t2", "...")`
clear: function(){
var i;
var length = arguments.length;
if (length > 0){
for(i=0; i<length; i++){
delete this.templates[arguments[i]];
}
} else {
this.templates = {};
}
}
};
// Renderer
// --------
// Render a template with data by passing in the template
// selector and the data to render.
Marionette.Renderer = {
// Render a template with data. The `template` parameter is
// passed to the `TemplateCache` object to retrieve the
// actual template. Override this method to provide your own
// custom rendering and template handling for all of Marionette.
render: function(template, data){
var that = this;
var asyncRender = $.Deferred();
var templateRetrieval = Marionette.TemplateCache.get(template);
$.when(templateRetrieval).then(function(template){
var html = that.renderTemplate(template, data);
asyncRender.resolve(html);
});
return asyncRender.promise();
},
// Default implementation uses underscore.js templates. Override
// this method to use your own templating engine.
renderTemplate: function(template, data){
var html = template(data);
return html;
}
};
// Modules
// -------
// The "Modules" object builds modules on an
// object that it is attached to. It should not be
// used on it's own, but should be attached to
// another object that will define modules.
Marionette.Modules = {
// Add modules to the application, providing direct
// access to your applicaiton object, Backbone,
// Marionette, jQuery and Underscore as parameters
// to a callback function.
module: function(moduleNames, moduleDefinition){
var moduleName, module, moduleOverride;
var parentModule = this;
var parentApp = this;
var moduleNames = moduleNames.split(".");
// Loop through all the parts of the module definition
var length = moduleNames.length;
for(var i = 0; i < length; i++){
var isLastModuleInChain = (i === length-1);
// Get the module name, and check if it exists on
// the current parent already
moduleName = moduleNames[i];
module = parentModule[moduleName];
// Create a new module if we don't have one already
if (!module){
module = new Marionette.Application();
}
// Check to see if we need to run the definition
// for the module. Only run the definition if one
// is supplied, and if we're at the last segment
// of the "Module.Name" chain.
if (isLastModuleInChain && moduleDefinition){
moduleOverride = moduleDefinition(module, parentApp, Backbone, Marionette, jQuery, _);
// If we have a module override, use it instead.
if (moduleOverride){
module = moduleOverride;
}
}
// If the defined module is not what we are
// currently storing as the module, replace it
if (parentModule[moduleName] !== module){
parentModule[moduleName] = module;
}
// Reset the parent module so that the next child
// in the list will be added to the correct parent
parentModule = module;
}
// Return the last module in the definition chain
return module;
}
};
// Helpers
// -------
// For slicing `arguments` in functions
var slice = Array.prototype.slice;
// Copy the `extend` function used by Backbone's classes
var extend = Marionette.View.extend;
Marionette.Region.extend = extend;
Marionette.Application.extend = extend;
// Copy the `modules` feature on to the `Application` object
Marionette.Application.prototype.module = Marionette.Modules.module;
// Copy the features of `BindTo` on to these objects
_.extend(Marionette.View.prototype, Marionette.BindTo);
_.extend(Marionette.Application.prototype, Marionette.BindTo);
_.extend(Marionette.Region.prototype, Marionette.BindTo);
// A simple wrapper method for deferring a callback until
// after another method has been called, passing the
// results of the first method to the second. Uses jQuery's
// deferred / promise objects, and $.when/then to make it
// work.
var callDeferredMethod = function(fn, callback, context){
var promise;
if (fn) { promise = fn.call(context); }
$.when(promise).then(callback);
}
return Marionette;
})(Backbone, _, window.jQuery || window.Zepto || window.ender);
|
'use strict';
const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const schema = new mongoose.Schema({
accessCode: {
type: String,
unique: true,
},
gameData: String,
turn: {
type: String,
default: 'red',
},
});
const Game = mongoose.model('Game', schema);
module.exports = Game;
|
var
_ = require('lodash'),
assert = require('assert'),
net = require('net'),
stream = require('stream'),
util = require('util')
;
var AnalyzerOutput = module.exports = function AnalyzerOutput(opts)
{
assert(opts && _.isObject(opts), 'you must pass an options object');
assert(opts.host && _.isString(opts.host), 'you must pass a `host` option');
assert(opts.port && _.isNumber(opts.port), 'you must pass a `port` option');
stream.Writable.call(this, { objectMode: true });
this.options = opts;
this.backlog = [];
this.output = new JSONOutputStream();
this.connect();
};
util.inherits(AnalyzerOutput, stream.Writable);
AnalyzerOutput.prototype.client = null; // client for data sink
AnalyzerOutput.prototype.backlog = null;
AnalyzerOutput.prototype.ready = false;
AnalyzerOutput.prototype.retries = 0;
AnalyzerOutput.prototype.connect = function connect()
{
if (this.ready) return;
if (this.client)
{
this.client.removeAllListeners();
this.output.unpipe();
this.client = null;
}
this.client = net.connect(this.options.port, this.options.host);
this.output.pipe(this.client);
this.client.on('connect', this.onConnect.bind(this));
this.client.on('error', this.onError.bind(this));
this.client.on('close', this.onClose.bind(this));
};
AnalyzerOutput.prototype.destroy = function destroy()
{
if (!this.client) return;
this.output.unpipe();
this.client.removeAllListeners();
this.client.end();
this.client = null;
};
AnalyzerOutput.prototype.onConnect = function onConnect()
{
this.retries = 0;
while (this.backlog.length)
this._write(this.backlog.shift());
this.ready = true;
};
AnalyzerOutput.prototype.onError = function onError(err)
{
this.ready = false;
this.retries++;
setTimeout(this.connect.bind(this), this.nextBackoff());
};
AnalyzerOutput.prototype.onClose = function onClose()
{
this.ready = false;
this.retries++;
setTimeout(this.connect.bind(this), this.nextBackoff());
};
AnalyzerOutput.prototype._write = function _write(event, encoding, callback)
{
this.output.write(JSON.stringify(event) + '\n', encoding, callback);
};
AnalyzerOutput.prototype.toString = function toString()
{
return '[ analyzer @ ' + this.options.path + ' ]';
};
AnalyzerOutput.prototype.nextBackoff = function nextBackoff()
{
return Math.min((Math.random() + 1) * 10 * Math.pow(2, this.retries), 60000);
};
function JSONOutputStream()
{
stream.Transform.call(this);
this._readableState.objectMode = false;
this._writableState.objectMode = true;
}
util.inherits(JSONOutputStream, stream.Transform);
JSONOutputStream.prototype._transform = function _transformOut(object, encoding, callback)
{
this.push(object);
callback();
};
|
import express from 'express';
import moment from 'moment';
const router = express.Router();
const vehicleTypes = {
c: 'CAR',
b: 'BIKE',
m: 'MOTORBIKE'
};
const prices = [
12.0, 5.5, 3.9, 0
];
let payments = [];
function randPrice() {
return prices[Math.floor(Math.random() * prices.length)];
}
// get info about vehicle
router.get('/vehicle/:vehicleId', (req, res) => {
const date = moment();
const data = {
vehicle: {
id: req.params.vehicleId,
type: vehicleTypes[req.params.vehicleId[0].toLocaleLowerCase()],
daySlots: {
today: { date: date.format('YYYY-MM-DD'), price: randPrice() },
tomorrow: { date: date.add(1, 'day').format('YYYY-MM-DD'), price: randPrice() },
yesterday: { date: date.add(-2, 'day').format('YYYY-MM-DD'), price: randPrice() }
}
}
};
res.json(data);
});
// create a payment
router.post('/vehicle/:vehicleId/payment', (req, res) => {
let data = {
payment: {
vehicleId: req.body.vehicleId,
accountNumber: req.body.accountNumber,
amount: req.body.amount,
date: req.body.date,
state: 'OK'
},
errorCode: 0
};
console.log('PAYMENTS', payments);
if (req.body.cardSecurityCode === '1234') {
data = {
payment: {},
errorCode: 1
};
} if (payments.filter((el) => {
return el.vehicleId === data.payment.vehicleId && el.date === data.payment.date;
}).length !== 0) {
data = {
payment: {},
errorCode: 2
};
} else {
payments.push(data.payment);
}
res.json(data);
});
export default router;
|
'use strict'
module.exports = require('./out/lib/graph')
|
/**
* Logger
*/
const Logger = module.exports = {
info: function(name, message) {
console.log('[' + name.toUpperCase() + '] ' + message);
},
warning: function(message) {
console.log('[WARN]: ' + message);
},
error: function(message) {
console.log('[ERROR]: ' + message);
}
};
|
var each = require('async-each')
function MultiForage (localforage) {
if (!(this instanceof MultiForage)) {
return new MultiForage(localforage)
}
this._localforage = localforage
}
MultiForage.prototype.setItems = function (items, cb) {
var self = this
each(Object.keys(items), function (key, cb) {
self._localforage.setItem(key, items[key], cb)
}, cb)
return self
}
MultiForage.prototype.getItems = function (keys, cb) {
var self = this
var items = {}
each(keys, function (key, cb) {
self._localforage.getItem(key, function (err, item) {
if (err) return cb(err)
items[key] = item
cb()
})
}, function (err) {
if (err) return cb(err)
cb(null, items)
})
return self
}
MultiForage.prototype.removeItems = function (keys, cb) {
var self = this
each(keys, function (key, cb) {
self._localforage.removeItem(key, cb)
}, cb)
return self
}
module.exports = MultiForage
|
/* eslint no-shadow: 0 */
'use strict';
var test = require('tap').test,
// fs = require('fs'),
// path = require('path'),
geojsonhint = require('geojsonhint'),
MapboxClient = require('../lib/services/directions');
test('MapboxClient#getDirections', function(t) {
t.test('typecheck', function(t) {
var client = new MapboxClient(process.env.MapboxAccessToken);
t.ok(client);
t.throws(function() {
client.getDirections(null);
});
t.throws(function() {
client.getDirections(1, function() {});
});
t.throws(function() {
client.getDirections('foo', 1, function() {});
});
t.throws(function() {
client.getDirections('foo', 1);
});
t.end();
});
t.test('no options', function(t) {
var client = new MapboxClient(process.env.MapboxAccessToken);
t.ok(client);
client.getDirections([
{ latitude: 33.6875431, longitude: -95.4431142 },
{ latitude: 33.6875431, longitude: -95.4831142 }
], function(err, results) {
t.ifError(err);
t.deepEqual(geojsonhint.hint(results.origin), [], 'origin is valid');
t.end();
});
});
t.test('all options', function(t) {
var client = new MapboxClient(process.env.MapboxAccessToken);
t.ok(client);
client.getDirections([
{ latitude: 33.6875431, longitude: -95.4431142 },
{ latitude: 33.6875431, longitude: -95.4831142 }
], {
profile: 'mapbox.walking',
instructions: 'html',
alternatives: false,
geometry: 'polyline'
}, function(err, results) {
t.ifError(err);
t.deepEqual(geojsonhint.hint(results.origin), [], 'origin is valid');
t.end();
});
});
t.end();
});
|
const dotenv = require('dotenv').config({ silent: process.env.NODE_ENV === 'production' });
const db = require('./db');
const initServer = require('./server');
initServer().listen(process.env.PORT || 3000, () => {
console.log('Server is up!');
db.init();
});
|
function main(res) {
return (res.view);
}
exports.main = main;
|
var
express = require('express');
var app = express();
|
'use strict';
var _ = require('lodash');
var h = require('heroku-cli-util');
function Postgres (heroku) {
this.heroku = heroku;
}
function isProductionDB(db) {
let type = db.type || db.plan.name;
let plan = type.split(':')[1];
return !_.includes(['dev', 'basic', 'hobby-dev', 'hobby-basic'], plan);
}
Postgres.prototype = {
migrateDB: function (fromConfig, fromDB, toConfig, toDB) {
return this.attachmentFor(toDB)
.then(this.waitForDB())
.then(this.startTransfer(fromConfig, fromDB, toConfig, toDB))
.then(this.waitForTransfer(toDB.app.name));
},
attachmentFor: function (db) {
if (db.name.startsWith('heroku-postgresql-')) {
// non-shareable addon
return this.heroku.request({
method: 'GET',
path: `/apps/${db.app.name}/attachments`,
headers: {'Accept': 'application/vnd.heroku+json; version=2' }
})
.then(function (attachments) {
return _.find(attachments, function (attachment) {
return attachment.uuid === db.id;
}).resource;
});
} else {
return Promise.resolve(db);
}
},
waitForDB: function () {
let svc = this;
return function (db) {
if (!isProductionDB(db)) {
// do not wait for non-production dbs
return Promise.resolve(db);
}
return svc.heroku.request({
method: 'GET',
host: `postgres-api.heroku.com`,
path: `/client/v11/databases/${db.name}/wait_status`
})
.then(function (response) {
process.stdout.write(`Status: ${response.message}\r`);
if (response['waiting?']) {
return new Promise(function (resolve) {
setTimeout(function () {
return resolve(svc.waitForDB()(db));
}, 5000);
});
} else {
console.log(`Status: ${h.color.yellow(response.message)}`);
return db;
}
});
};
},
databaseName: function (db) {
return db.config_vars.map(function (config_var) {
let match = config_var.match(/(.*)_URL/);
return match && match[1];
}).find((name) => name);
},
startTransfer: function (fromConfig, fromDB, toConfig, toDB) {
let fromName = this.databaseName(fromDB);
let toName = this.databaseName(toDB);
let fromURL = fromConfig[`${fromName}_URL`];
let toURL = toConfig[`${toName}_URL`];
return function (db) {
console.log(`Transferring ${h.color.cyan(fromDB.app.name)}:${h.color.magenta(fromName)} to ${h.color.cyan(toDB.app.name)}:${h.color.magenta(toName)}...`);
return this.heroku.request({
method: 'POST',
host: isProductionDB(db) ? 'postgres-api.heroku.com' : 'postgres-starter-api.heroku.com',
path: `/client/v11/databases/${db.name}/transfers`,
body: {
from_url: fromURL,
from_name: fromName,
to_url: toURL,
to_name: toName
}
});
}.bind(this);
},
waitForTransfer: function (app) {
let svc = this;
return function (start) {
return svc.heroku.request({
method: 'GET',
host: `postgres-api.heroku.com`,
path: `/client/v11/apps/${app}/transfers/${start.uuid}`
})
.then(function (response) {
if (response.finished_at) {
console.log('Progress: done ');
} else {
let processed = Math.round(response.processed_bytes/1024/1024);
let total = Math.round(response.source_bytes/1024/1024);
process.stdout.write('Progress: ' + h.color.yellow(`${processed}MB/${total}MB`) + '\r');
return new Promise(function (resolve) {
setTimeout(function () {
return resolve(svc.waitForTransfer(app)(start));
}, 5000);
});
}
})
.catch(function (err) {
console.error();
h.error(err);
return new Promise(function (resolve) {
setTimeout(function () {
return resolve(svc.waitForTransfer(app)(start));
}, 5000);
});
});
};
}
};
module.exports = Postgres;
|
import AbstractRestClient from 'ima-plugin-rest-client/dist/AbstractRestClient';
import Configurator from 'ima-plugin-rest-client/dist/Configurator';
import HalsonLinkGenerator from './HalsonLinkGenerator';
import HalsonResponsePostProcessor from './HalsonResponsePostProcessor';
/**
* The REST API client for the HAL+JSON REST API.
*/
export default class HalsonRestClient extends AbstractRestClient {
/**
* Initializes the HALSON REST API client.
*
* @param {HttpAgent} httpAgent The IMA HTTP agent used for communication
* with the REST API.
* @param {Configurator} configurator URL to the REST API root.
* @param {RequestPreProcessor[]} preProcessors The request pre-processors.
* @param {ResponsePostProcessor[]} postProcessors The response
* post-processors. The response will be processed by the
* {@linkcode HalsonResponsePostProcessor} before it will be passed
* to the provided post-processors.
*/
constructor(httpAgent, configurator, preProcessors = [],
postProcessors = []) {
super(
httpAgent,
configurator,
new HalsonLinkGenerator(),
preProcessors,
[new HalsonResponsePostProcessor()].concat(postProcessors)
);
}
}
|
'use strict';
var ParamSpec = require ('../grokible.paramSpec');
var expect = require ('chai').expect;
var TestExpect = require ('../grokible.testExpect');
var Exception = require ('../grokible.exception');
var Exceptions = require ('../grokible.exceptions');
var ArgException = Exceptions.ArgException;
var QueryParamException = Exceptions.QueryParamException;
describe ("ParamSpec", function () {
describe ("constructor (args, spec)", function () {
var args = { weight: 205.2 };
var spec = { weight: { type: 'number', default: 10.2 } };
it ("should set arg and spec", function () {
var ps = ParamSpec (args, spec);
var args2 = ps.getArgs ();
expect ('weight' in args2).to.be.true;
expect (args2 ['weight']).to.equal (205.2);
var spec2 = ps.getSpec ();
expect ('weight' in spec2).to.be.true;
expect (spec2 ['weight']['type']).to.equal ('number');
expect (spec2 ['weight']['default']).to.equal (10.2);
});
});
describe ("get (number)", function () {
var args = { weight: 205.2 };
var spec = { weight: { type: 'number', default: 10.2 } };
it ("should get number weight if it exists, else default",
function () {
var ps = ParamSpec (args, spec);
var x = ps.get ('weight');
expect (x).to.equal (205.2);
ps.setArgsUsingArgsOrContext ({});
x = ps.get ('weight');
expect (x).to.equal (10.2);
});
});
describe ("get (string) for number spec", function () {
var args = { weight: '205.2' };
var spec = { weight: { type: 'number', default: '10.2' } };
it ("should get and convert string to num if exists, else default",
function () {
var ps = ParamSpec (args, spec);
var x = ps.get ('weight');
expect (x).to.equal (205.2);
ps.setArgsUsingArgsOrContext ({});
x = ps.get ('weight');
expect (x).to.equal (10.2);
});
});
describe ("get (string), for integer spec", function () {
var args = { age: '10' };
var spec = { age: { type: 'integer', default: 20 } };
it ("should get and convert string to int if exists, else default",
function () {
var ps = ParamSpec (args, spec);
var x = ps.get ('age');
expect (x).to.equal (10);
ps.setArgsUsingArgsOrContext ({});
x = ps.get ('age');
expect (x).to.equal (20);
});
});
describe ("get (missing-arg-with-default-in-spec)", function () {
var args = { };
var spec = { missing_but_defaulted: { type: 'integer', default: 21 } };
var ps = ParamSpec (args, spec);
var x = ps.get ('missing_but_defaulted');
expect (x).to.equal (21);
});
describe ("get (missing-arg-with-default-undef-in-spec)", function () {
var args = { };
var spec = { missing_but_defaulted_undef: { type: 'integer',
default: undefined } };
var ps = ParamSpec (args, spec);
var x = ps.get ('missing_but_defaulted_undef');
expect (x).to.equal (undefined);
});
describe ("get (missing-arg)", function () {
var args = { };
var spec = { missing: { type: 'integer' } };
it ("should throw exception if missing arg", function () {
var ps = ParamSpec (args, spec);
TestExpect.throws (function () {
var x = ps.get ('missing');
}, ArgException, /No arg found named/);
});
});
describe ("get (missing-arg)", function () {
var args = { };
var spec = { missing: { type: 'integer' } };
it ("should throw passed exception type if missing arg", function () {
var opt = { exception: QueryParamException };
var ps = ParamSpec (args, spec, opt);
TestExpect.throws (function () {
var x = ps.get ('missing')
}, QueryParamException, /No arg found named/);
});
});
describe ("get (missing-spec)", function () {
var args = { othermissing: 'foobar' };
var spec = { missing: { type: 'integer' } };
it ("should throw exception if missing spec", function () {
var ps = ParamSpec (args, spec);
TestExpect.throws (function () {
var x = ps.get ('othermissing');
}, ArgException, /No spec 'othermissing'/);
});
});
describe ("get (flag)", function () {
var args = { debug: "" }; // this.query will bring flag in as ""
var spec = { debug: { type: 'flag' } };
it ("should return true if present", function () {
var ps = ParamSpec (args, spec);
var x = ps.get ('debug');
expect (x).to.be.true;
});
it ("should return false if not present", function () {
var args = {};
var ps = ParamSpec (args, spec);
var x = ps.get ('debug');
expect (x).to.be.false;
});
});
});
|
/* eslint global-require:0 */
"use strict";
const path = require("path");
const gulp = require("gulp");
const util = require("gulp-util");
const webpack = require("webpack");
const webpackStream = require("webpack-stream");
const notify = require("gulp-notify");
const plumber = require("gulp-plumber");
const gulpIf = require("gulp-if");
notify.logLevel(0);
const errorHandler = notify.onError();
const getConfig = function (baseDir, production) {
if (production) {
return require(`${baseDir}/webpack.production.config.js`);
} else {
return require(`${baseDir}/webpack.development.config.js`);
}
};
gulp.task("webpack", () => {
const production = util.env.production;
const watching = util.env.watching;
const baseDir = util.env["base-dir"];
const staticDir = util.env["static-dir"];
const scriptsDir = util.env["scripts-dir"];
const src = `${scriptsDir}/main.js`;
const dest = `${staticDir}/javascript/`;
const config = getConfig(baseDir, production);
config.eslint = { configFile: path.join(scriptsDir, ".eslintrc") };
return gulp.src(src)
.pipe(gulpIf(watching, plumber({ errorHandler })))
.pipe(webpackStream(config, webpack))
.pipe(gulp.dest(dest));
});
|
/* jshint node:true */
/* global MergeXML, describe, it, before, after, beforeEach, afterEach, expect */
'use strict';
describe('Instantiating object ', function() {
var merger;
it('works', function() {
merger = new MergeXML();
expect(merger).to.be.an('object');
});
});
describe('Adding source', function() {
var merger, a, b;
it('strings works', function() {
merger = new MergeXML();
a = '<a/>';
b = '<b/>';
expect(merger.AddSource(a)).to.not.equal(false);
expect(merger.AddSource(b)).to.not.equal(false);
});
});
describe('Merging XML sources', function() {
var merger, a, b;
describe('with option join = undefined', function() {
// TODO
});
describe('with option join = false', function() {
it('succeeds if sources have a common root name', function() {
merger = new MergeXML({
join: false
});
a = '<r><a/></r>';
b = '<r><b/></r>';
merger.AddSource(a);
merger.AddSource(b);
expect(merger.Get(1).trim()).to.equal('<r><a/><b/></r>');
});
it('fails to merge second source if sources do not have a common root name', function() {
merger = new MergeXML({
join: false
});
a = '<a/>';
b = '<b/>';
merger.AddSource(a);
merger.AddSource(b);
expect(merger.Get(1).trim()).to.equal('<a/>');
});
});
describe('with option updn = true or undefined', function() {
var merger, a, b;
it('merges sources by nodeName', function() {
merger = new MergeXML({
updn: true
});
a = '<a>' +
'<c>s1</c>' +
'<c>s3</c>' +
'</a>';
b = '<a>' +
'<c>s1</c>' +
'<b>s2</b>' +
'<c>s4</c>' +
'</a>';
merger.AddSource(a);
merger.AddSource(b);
expect(merger.Get(1).trim()).to.equal('<a><c>s1</c><c>s4</c><b>s2</b></a>');
merger = new MergeXML();
merger.AddSource(a);
merger.AddSource(b);
expect(merger.Get(1).trim()).to.equal('<a><c>s1</c><c>s4</c><b>s2</b></a>');
});
});
describe('with option updn = false', function() {
var merger, a, b;
it('merges sources by node position, discarding nodeName', function() {
merger = new MergeXML({
updn: false
});
a = '<a>' +
'<c>s1</c>' +
'<c>s3</c>' +
'</a>';
b = '<a>' +
'<c>s1</c>' +
'<b>s2</b>' +
'<c>s4</c>' +
'</a>';
merger.AddSource(a);
merger.AddSource(b);
expect(merger.Get(1).trim()).to.equal('<a><c>s1</c><c>s2</c><c>s4</c></a>');
});
});
describe('with namespaced attributes', function() {
var merger;
var ns = 'https://github.com/enketo/merge-xml';
it('correctly adds namespaced attributes from second source', function() {
merger = new MergeXML({
join: false
});
a = '<a>' +
'<c>s1</c>' +
'</a>';
b = '<a xmlns:enk="' + ns + '">' +
'<c enk:custom="something">s2</c>' +
'</a>';
merger.AddSource(a);
merger.AddSource(b);
expect(merger.error.code).to.equal('');
expect(merger.error.text).to.equal('');
expect(merger.Get(1).trim()).to.equal('<a xmlns:enk="' + ns + '"><c enk:custom="something">s2</c></a>');
// in IE11 and below, merger.Get(0) returns an ActiveXObject we use the internal "Query" function
expect(merger.Query('//c').attributes[0].localName).to.equal('custom'); // fails in IE because
expect(merger.Query('//c').attributes[0].namespaceURI).to.equal(ns);
})
})
describe('with sources that have and do not have a UTF encoding declaration', function() {
var merger;
var a = '<?xml version="1.0"?>' +
'<a><c>s1</c></a>';
var b = '<?xml version="1.0" encoding="UTF-8"?>' +
'<a><c>s2</c></a>';
it('undeclared and UTF-8', function() {
merger = new MergeXML({
join: false
});
merger.AddSource(a);
merger.AddSource(b);
expect(merger.error.code).to.equal('');
expect(merger.error.text).to.equal('');
expect(merger.Get(1)).to.contain('<a><c>s2</c></a>');
});
it('UTF8 and undeclared', function() {
merger = new MergeXML({
join: false
});
merger.AddSource(b);
merger.AddSource(a);
expect(merger.error.code).to.equal('');
expect(merger.error.text).to.equal('');
expect(merger.Get(1)).to.contain('<a><c>s1</c></a>');
});
});
});
|
import { select as d3_select } from 'd3-selection';
import { uiModal } from './modal';
export function uiLoading(context) {
let _modalSelection = d3_select(null);
let _message = '';
let _blocking = false;
let loading = (selection) => {
_modalSelection = uiModal(selection, _blocking);
let loadertext = _modalSelection.select('.content')
.classed('loading-modal', true)
.append('div')
.attr('class', 'modal-section fillL');
loadertext
.append('img')
.attr('class', 'loader')
.attr('src', context.imagePath('loader-white.gif'));
loadertext
.append('h3')
.html(_message);
_modalSelection.select('button.close')
.attr('class', 'hide');
return loading;
};
loading.message = function(val) {
if (!arguments.length) return _message;
_message = val;
return loading;
};
loading.blocking = function(val) {
if (!arguments.length) return _blocking;
_blocking = val;
return loading;
};
loading.close = () => {
_modalSelection.remove();
};
loading.isShown = () => {
return _modalSelection && !_modalSelection.empty() && _modalSelection.node().parentNode;
};
return loading;
}
|
/*
257 RPL_ADMINLOC1
":<admin info>"
- When replying to an ADMIN message, a server
is expected to use replies RPL_ADMINME
through to RPL_ADMINEMAIL and provide a text
message with each. For RPL_ADMINLOC1 a
description of what city, state and country
the server is in is expected, followed by
details of the institution (RPL_ADMINLOC2)
and finally the administrative contact for the
server (an email address here is REQUIRED)
in RPL_ADMINEMAIL.
*/
|
'use strict'
var validate = require('aproba')
var renderTemplate = require('./render-template.js')
var wideTruncate = require('./wide-truncate')
var stringWidth = require('string-width')
module.exports = function (theme, width, completed) {
validate('ONN', [theme, width, completed])
if (completed < 0) completed = 0
if (completed > 1) completed = 1
if (width <= 0) return ''
var sofar = Math.round(width * completed)
var rest = width - sofar
var template = [
{type: 'complete', value: repeat(theme.complete, sofar), length: sofar},
{type: 'remaining', value: repeat(theme.remaining, rest), length: rest}
]
return renderTemplate(width, template, theme)
}
// lodash's way of repeating
function repeat (string, width) {
var result = ''
var n = width
do {
if (n % 2) {
result += string
}
n = Math.floor(n / 2)
/* eslint no-self-assign: 0 */
string += string
} while (n && stringWidth(result) < width)
return wideTruncate(result, width)
}
|
var express = require('express');
var router = express.Router();
var kittehs = require('../data/kittehs.json');
var fs = require('fs');
var path = require('path');
/* GET kittehs listing. */
router.get('/:id?', function(req, res, next) {
if (req.params.id !== undefined) {
res.send(kittehs[req.params.id]);
} else {
res.send(kittehs);
}
});
/* POST creates an kitteh and adds it to the json file */
router.post('/', function(req, res, next) {
// req.body comes from $.ajax data
var newKitteh = {
name: req.body.name,
type: req.body.type
};
// push the new element to the array
kittehs.push(newKitteh);
// stringify it so that it will write to the array correctly
var string = JSON.stringify(kittehs);
// This is the path the file is in
var filePath = path.join(__dirname, '../data/kittehs.json');
// write the stringified version to the file
fs.writeFile(filePath, string, function(err) {
if (err) {
// if there is an error, "next" middleware will handle it.
// Next in our case is the error handler in app.js
next(err);
} else {
// it's all good! Send the object back.
res.send(newKitteh);
}
});
});
// export the router
module.exports = router;
|
/* "ANSI graphics" editor object
by echicken -at- bbs.electronicchicken.com
Embed an ANSI graphics editor in an application.
See xtrn/syncwall/ for a demo, or try the following sample code:
Working example:
load("ansiedit.js");
console.clear(LIGHTGRAY);
var ansiEdit = new ANSIEdit(
{ 'x' : 1,
'y' : 1,
'width' : console.screen_columns,
'height' : console.screen_rows
}
);
ansiEdit.open();
while(!js.terminated) {
var userInput = console.inkey(K_NONE, 5);
if(ascii(userInput) == 27)
break;
ansiEdit.getcmd(userInput);
}
ansiEdit.close();
console.clear(LIGHTGRAY);
Instantiation:
Where 'options' is an object with the following properties:
- 'x', X coordinate of top left corner of editor (number) (required)
- 'y', Y coordinate of top left corner of editor (number) (required)
- 'width', Width of the editor (number) (required)
- 'height', Height of the editor (number) (required)
- 'attr', Default attributes (number) (optional) (LIGHTGRAY)
- 'parentFrame', Frame object this a child of (Frame) (optional)
- 'vScroll', Vertical scrolling (boolean) (optional) (false)
- 'hScroll', Horizontal scrolling (boolean) (optional) (false)
- 'showPosition', Show position readout (boolean) (optional) (false)
- 'menuHeading', Menu heading (string) (optional) ("ANSI Editor Menu")
var ansiEdit = new ANSIEdit(options);
Properties:
.menu
An instance of Tree (see exec/load/tree.js for usage)
Use this to add items to the <TAB> menu
Methods:
.open() (void)
Initialize the editor and display it.
If nesting the editor inside of a parent Frame object, this must
be called after [parentFrame].open().
.close() (void)
Close the editor and remove it from display.
.clear() (void)
Clear the contents of the editor.
.getcmd(string) (object)
Handle already-received user input, where 'string' should be a
single character/keypress, eg. the return value of console.inkey().
Returns an object with the following properties:
- 'x', The x coordinate of the cursor (number)
- 'y', The y coordinate of the cursor (number)
- 'ch' - The character that was drawn (string) or false if none
- or "CLEAR" if the editor was cleared
- 'attr' - The console attributes (color, intensity) at this position
.putChar({'x' : number, 'y' : number, 'ch' : string, 'attr' : number}) (void)
Put character 'ch' at 'x' and 'y' with attributes 'attr'.
.cycle() (void)
This is called automatically from ANSIEdit.getcmd(). It refreshes
the editor's frames, places the console cursor where it should be,
and updates the cursor position display. If your editor is nested
inside another frame or you are moving the cursor outside of the
editor, you may need to call this directly.
To do:
- Block cut/copy/paste operations
- "iCe colors"? Meh.
- Blink attr? (I don't think it works with frame.js presently.)
Support:
- Post a message to 'echicken' in Synchronet Javascript on DOVE-Net
- Find me in #synchronet on irc.synchro.net
- Send an email to echicken -at- bbs.electronicchicken.com
*/
load("sbbsdefs.js");
load("frame.js");
load("tree.js");
load("funclib.js");
load("event-timer.js");
const characterSets = [
[ 49, 50, 51, 52, 53, 54, 55, 56, 57, 48 ],
[ 218, 191, 192, 217, 196, 179, 195, 180, 193, 194 ],
[ 201, 187, 200, 188, 205, 186, 204, 185, 202, 203 ],
[ 213, 184, 212, 190, 205, 179, 198, 181, 207, 209 ],
[ 214, 183, 211, 189, 196, 199, 199, 182, 208, 210 ],
[ 197, 206, 216, 215, 128, 129, 130, 131, 132, 133 ],
[ 176, 177, 178, 219, 223, 220, 221, 222, 254, 134 ],
[ 135, 136, 137, 138, 139, 140, 141, 142, 143, 144 ],
[ 145, 146, 147, 148, 149, 150, 151, 152, 153, 154 ],
[ 155, 156, 157, 158, 159, 160, 161, 162, 163, 164 ],
[ 165, 166, 167, 168, 171, 172, 173, 174, 175, 224 ],
[ 225, 226, 227, 228, 229, 230, 231, 232, 233, 234 ],
[ 235, 236, 237, 238, 239, 240, 241, 242, 243, 244 ],
[ 245, 246, 247, 248, 249, 250, 251, 252, 253, 253 ]
];
// Map sbbsdefs.js console attributes to values usable in ANSI sequences
const attrMap = {};
attrMap[HIGH] = 1;
attrMap[BLINK] = 5;
attrMap[BLACK] = 30;
attrMap[RED] = 31;
attrMap[GREEN] = 32;
attrMap[BROWN] = 33;
attrMap[BLUE] = 34;
attrMap[MAGENTA] = 35;
attrMap[CYAN] = 36;
attrMap[LIGHTGRAY] = 37;
attrMap[DARKGRAY] = 30;
attrMap[LIGHTRED] = 31;
attrMap[LIGHTGREEN] = 32;
attrMap[YELLOW] = 33;
attrMap[LIGHTBLUE] = 34;
attrMap[LIGHTMAGENTA] = 35;
attrMap[LIGHTCYAN] = 36;
attrMap[WHITE] = 37;
attrMap[BG_BLACK] = 40;
attrMap[BG_RED] = 41;
attrMap[BG_GREEN] = 42;
attrMap[BG_BROWN] = 43;
attrMap[BG_BLUE] = 44;
attrMap[BG_MAGENTA] = 45;
attrMap[BG_CYAN] = 46;
attrMap[BG_LIGHTGRAY] = 47;
var ANSIEdit = function(options) {
var tree,
frames = {},
self = this;
var state = {
attr : (typeof options.attr != 'number') ? LIGHTGRAY : options.attr,
inMenu : false,
cursor : { 'x' : 1, 'y' : 1 },
lastCursor : { 'x' : 0, 'y' : 0 },
charSet : 6,
timer : new Timer(),
cursor_event : null
};
var settings = {
vScroll : typeof options.vScroll != 'boolean' ? false : options.vScroll,
hScroll : typeof options.hScroll != 'boolean' ? false : options.hScroll,
showPosition : typeof options.showPosition != 'boolean' ? false : true,
menuHeading : (
typeof options.menuHeading != 'string'
? 'ANSI Editor'
: options.menuHeading
)
};
function initFrames() {
if (typeof options.canvas_width !== 'number') options.canvas_width = options.width;
if (typeof options.canvas_height !== 'number') options.canvas_height = options.height - 1;
frames.top = new Frame(
options.x,
options.y,
options.width,
options.height,
BG_BLUE|LIGHTGRAY,
options.parentFrame
);
frames.top.checkbounds = false;
if (options.width > options.canvas_width) {
var cx = options.x + Math.floor((options.width - options.canvas_width) / 2)
} else {
var cx = frames.top.x
}
if (options.height - 1 > options.canvas_height) {
var cy = options.y + Math.floor((options.height - options.canvas_height) / 2)
} else {
var cy = frames.top.y;
}
frames.canvas = new Frame(
cx, cy,
options.canvas_width, options.canvas_height,
LIGHTGRAY, frames.top
);
frames.canvas.v_scroll = settings.vScroll;
frames.canvas.h_scroll = settings.hScroll;
frames.cursor = new Frame(frames.canvas.x, frames.canvas.y, 1, 1, BG_BLACK|WHITE, frames.canvas);
frames.cursor.putmsg(ascii(219));
state.cursor_event = state.timer.addEvent(
500, true, function () {
if (frames.cursor.is_open) {
frames.cursor.close();
} else {
frames.cursor.open();
}
}
)
frames.charSet = new Frame(
frames.top.x, frames.top.y + frames.top.height - 1,
frames.top.width, 1,
state.attr, frames.top
);
if (settings.showPosition) {
frames.position = new Frame(
frames.charSet.x + frames.charSet.width + 1, frames.charSet.y,
frames.top.width - frames.charSet.width - 1, 1,
state.attr, frames.top
);
}
frames.menu = new Frame(
Math.floor((frames.top.width - 28) / 2), frames.top.y + 1,
28, frames.top.height - 2,
BG_BLUE|WHITE, frames.top
);
frames.menu.center(settings.menuHeading);
frames.menu.gotoxy(1, frames.menu.height);
frames.menu.center('Press <TAB> to exit');
frames.subMenu = new Frame(
frames.menu.x + 1,
frames.menu.y + 1,
frames.menu.width - 2,
frames.menu.height - 2,
WHITE,
frames.menu
);
}
function move_cursor(x, y) {
state.cursor_event.lastrun = Date.now();
frames.cursor.open();
frames.cursor.moveTo(x, y);
}
function initMenu() {
tree = new Tree(frames.subMenu);
tree.colors.fg = WHITE;
tree.colors.lfg = WHITE;
tree.colors.lbg = BG_CYAN;
tree.colors.tfg = LIGHTCYAN;
tree.colors.xfg = LIGHTCYAN;
tree.addItem('Color Palette', setColour);
var charSetTree = tree.addTree('Choose Character Set');
characterSets.forEach(
function (e, i) {
var line = e.map(function (ee) { return ascii(ee); });
charSetTree.addItem(line.join(" "), drawCharSet, i);
}
);
var downloadTree = tree.addTree('Download this ANSI');
downloadTree.addItem(' Binary', download, 'bin');
downloadTree.addItem(' ASCII', download, 'ascii');
downloadTree.addItem(' ANSI', download, 'ansi');
tree.addItem('Clear the Canvas', self.clear);
tree.open();
}
function setColour() {
state.attr = colorPicker(
frames.top.x + Math.floor((frames.top.width - 36) / 2), //frames.menu.x - 4,
frames.top.y + Math.floor((frames.top.height - 6) / 2),
frames.menu,
state.attr
);
drawCharSet();
return 'DONE'; // wat?
}
function drawCharSet(n) {
if (typeof n != 'undefined') state.charSet = n;
frames.charSet.attr = state.attr;
frames.charSet.clear();
characterSets[state.charSet].forEach(
function (e, i) {
frames.charSet.putmsg(((i+1)%10) + ':' + ascii(e) + ' ');
}
);
frames.charSet.putmsg('<TAB> menu');
return 'DONE'; // wat?
}
function saveAscii() {
var lines = [];
log(frames.canvas.data_width);
for (var y = 0; y < frames.canvas.data_height; y++) {
var line = "";
for (var x = 0; x < frames.canvas.data_width; x++) {
var ch = frames.canvas.getData(x, y);
line += (
(typeof ch.ch == 'undefined' || ch.ch == '') ? ' ' : ch.ch
);
}
lines.push(line);
}
var fn = system.data_dir + format('user/%04u.asc', user.number);
var f = new File(fn);
f.open('w');
f.writeAll(lines);
f.close();
return fn;
}
function saveAnsi() {
var fgmask = (1<<0)|(1<<1)|(1<<2)|(1<<3);
var bgmask = (1<<4)|(1<<5)|(1<<6);
var lines = [], fg = 7, bg = 0, hi = 0;
var line = format('%s[%s;%s;%sm', ascii(27), hi, fg, bg);
for (var y = 0; y < frames.canvas.data_height; y++) {
if (y > 0) line = '';
var blanks = 0;
for (var x = 0; x < frames.canvas.data_width; x++) {
var ch = frames.canvas.getData(x, y);
if (typeof ch.attr != 'undefined') {
var sequence = [];
if ((ch.attr&fgmask) != fg) {
fg = (ch.attr&fgmask);
if (fg > 7 && hi == 0) {
hi = 1;
sequence.push(hi);
} else if (fg < 8 && hi == 1) {
hi = 0;
sequence.push(hi);
}
sequence.push(attrMap[fg]);
}
if ((ch.attr&bgmask) != bg) {
bg = (ch.attr&bgmask);
sequence.push((bg == 0) ? 40 : attrMap[bg]);
}
sequence = format('%s[%sm', ascii(27), sequence.join(';'));
if (sequence.length > 3) line += sequence;
}
if (typeof ch.ch == 'undefined') {
blanks++;
} else {
if (blanks > 0) {
line += ascii(27) + '[' + blanks + 'C';
blanks = 0;
}
line += ch.ch;
}
}
lines.push(line);
}
var fn = system.data_dir + format('user/%04u.ans', user.number);
var f = new File(fn);
f.open('w');
f.writeAll(lines);
f.close();
return fn;
}
function saveBin() {
var f = system.data_dir + format('user/%04u.bin', user.number);
frames.canvas.screenShot(f, false);
return f;
}
function download(type) {
switch (type) {
case 'bin':
var f = saveBin();
break;
case 'ansi':
var f = saveAnsi();
break;
case 'ascii':
var f = saveAscii();
break;
default:
break;
}
if (typeof f != 'undefined') {
console.clear(LIGHTGRAY);
bbs.send_file(f, user.download_protocol);
if (typeof frames.top.parent != "undefined") {
frames.top.parent.invalidate();
} else {
frames.top.invalidate();
}
}
return 'DONE'; // wat?
}
function raiseMenu() {
state.inMenu = true;
frames.menu.top();
}
function lowerMenu() {
state.inMenu = false;
frames.menu.bottom();
self.cycle(true);
}
this.open = function() {
initFrames();
initMenu();
this.menu = tree; // Allow people to add menu items to an editor
frames.top.open();
frames.menu.bottom();
drawCharSet();
state.cursor.x = frames.canvas.x;
state.cursor.y = frames.canvas.y;
}
this.close = function() {
tree.close();
frames.top.close();
if (typeof frames.top.parent != 'undefined') {
frames.top.parent.invalidate();
}
frames.top.delete();
}
this.clear = function() {
frames.canvas.clear();
state.cursor.x = frames.canvas.x;
state.cursor.y = frames.canvas.y;
return 'CLEAR';
}
this.putChar = function(ch) {
// Hacky workaround for something broken in Frame.scroll()
if (frames.canvas.data_height > frames.canvas.height &&
frames.canvas.offset.y > 0
) {
frames.canvas.refresh();
}
if (frames.canvas.data_width > frames.canvas.width &&
frames.canvas.offset.x > 0
) {
frames.canvas.refresh();
}
frames.canvas.setData(
typeof ch.x == 'undefined' ? state.cursor.x - frames.canvas.x : ch.x,
typeof ch.y == 'undefined' ? state.cursor.y - frames.canvas.y : ch.y,
ch.ch,
typeof ch.attr == 'undefined' ? state.attr : ch.attr
);
if (typeof ch.x != 'undefined') {
this.cycle(true);
return;
}
var ret = {
x : state.cursor.x - frames.canvas.x,
y : state.cursor.y - frames.canvas.y,
ch : ch.ch,
attr : state.attr
};
if (settings.hScroll ||
state.cursor.x < frames.canvas.x + frames.canvas.width - 1
) {
state.cursor.x++;
move_cursor(state.cursor.x, state.cursor.y);
}
if (settings.hScroll &&
state.cursor.x - frames.canvas.offset.x > frames.canvas.width
) {
frames.canvas.scroll(1, 0);
}
return ret;
}
this.getcmd = function(userInput) {
if (userInput == "\x09") {
if (state.inMenu) {
state.cursor_event.pause = false;
state.inMenu = false;
lowerMenu();
} else {
state.cursor_event.pause = true;
frames.cursor.close();
state.inMenu = true;
raiseMenu();
}
} else if(state.inMenu) {
var ret = tree.getcmd(userInput);
if (ret == 'DONE' || ret == 'CLEAR') lowerMenu();
if (ret == 'CLEAR') {
var retval = {
x : state.cursor.x - frames.canvas.x,
y : state.cursor.y - frames.canvas.y,
ch : 'CLEAR',
attr : state.attr
}
}
} else if (
userInput.search(/\r/) >= 0 &&
(state.cursor.y < frames.canvas.y + frames.canvas.height - 1 || settings.vScroll)
) {
state.cursor.y++;
state.cursor.x = frames.canvas.x;
move_cursor(state.cursor.x, state.cursor.y);
if (state.cursor.y - frames.canvas.offset.y > frames.canvas.height) {
// I don't know why I need to do this, especially not after looking at Frame.scroll()
// but vertical Frame.scroll() won't work unless I do this
if (typeof frames.canvas.data[state.cursor.y - frames.canvas.y] == 'undefined') {
frames.canvas.setData(
state.cursor.x - frames.canvas.x,
state.cursor.y - frames.canvas.y,
'',
0
);
}
frames.canvas.scroll();
}
} else if (userInput == '\x08' && state.cursor.x > frames.canvas.x) {
state.cursor.x--;
var retval = this.putChar({ ch : '' });
state.cursor.x--;
move_cursor(state.cursor.x, state.cursor.y);
} else if (userInput == '\x7F') {
var retval = this.putChar({ ch : ' ' });
state.cursor.x--;
move_cursor(state.cursor.x, state.cursor.y);
} else if (userInput.match(/[0-9]/) !== null) {
userInput = (userInput == 0) ? 9 : userInput - 1;
var retval = this.putChar(
{ ch : ascii(characterSets[state.charSet][userInput]) }
);
} else if(userInput.match(/[\x20-\x7E]/) !== null) {
var retval = this.putChar({ ch : userInput });
} else {
switch (userInput) {
case KEY_UP:
if (state.cursor.y > frames.canvas.y) {
state.cursor.y--;
move_cursor(state.cursor.x, state.cursor.y);
}
if (settings.vScroll &&
frames.canvas.offset.y > 0 &&
state.cursor.y == frames.canvas.offset.y
) {
frames.canvas.scroll(0, -1);
}
break;
case KEY_DOWN:
if (settings.vScroll ||
state.cursor.y < frames.canvas.y + frames.canvas.height - 1
) {
state.cursor.y++;
move_cursor(state.cursor.x, state.cursor.y);
}
if (settings.vScroll &&
state.cursor.y - frames.canvas.offset.y > frames.canvas.height
) {
// I don't know why I need to do this, especially not after looking at Frame.scroll()
// but vertical Frame.scroll() won't work unless I do this
if (typeof frames.canvas.data[state.cursor.y - frames.canvas.y] == 'undefined') {
frames.canvas.setData(
state.cursor.x - frames.canvas.x,
state.cursor.y - frames.canvas.y,
'',
0
);
}
frames.canvas.scroll();
}
break;
case KEY_LEFT:
if (state.cursor.x > frames.canvas.x) {
state.cursor.x--;
move_cursor(state.cursor.x, state.cursor.y);
}
if (settings.hScroll &&
frames.canvas.offset.x > 0 &&
state.cursor.x == frames.canvas.offset.x
) {
frames.canvas.scroll(-1, 0);
}
break;
case KEY_RIGHT:
if (settings.hScroll ||
state.cursor.x < frames.canvas.x + frames.canvas.width - 1
) {
state.cursor.x++;
move_cursor(state.cursor.x, state.cursor.y);
}
if (settings.hScroll &&
state.cursor.x - frames.canvas.offset.x > frames.canvas.width
) {
// Hacky hack to populate entire frame data matrix
// Horizontal Frame.scroll() doesn't otherwise work in this situation
for (var y = 0; y <= state.cursor.y - frames.canvas.y; y++) {
if (typeof frames.canvas.data[state.cursor.y - frames.canvas.y] == 'undefined') {
frames.canvas.setData(
state.cursor.x - frames.canvas.x, y, '', 0
);
}
for (var x = 0; x <= state.cursor.x - frames.canvas.x; x++) {
if (typeof frames.canvas.data[y][x] == 'undefined') {
frames.canvas.setData(x, y, '', 0);
}
}
}
frames.canvas.scroll(1, 0);
}
break;
case KEY_HOME:
state.cursor.x = frames.canvas.x;
move_cursor(state.cursor.x, state.cursor.y);
break;
case KEY_END:
state.cursor.x = frames.canvas.data_width;
move_cursor(state.cursor.x, state.cursor.y);
break;
default:
break;
}
}
this.cycle();
return (
typeof retval != 'undefined'
? retval
: { x : state.cursor.x - frames.canvas.x,
y : state.cursor.y - frames.canvas.y,
ch : false,
attr : state.attr
}
);
}
this.cycle = function() {
state.timer.cycle();
if (typeof options.parentFrame == 'undefined') frames.top.cycle();
if (state.cursor.x != state.lastCursor.x ||
state.cursor.y != state.lastCursor.y
) {
for (var c in state.cursor) state.lastCursor[c] = state.cursor[c];
if (!settings.showPosition) return;
frames.position.clear();
frames.position.attr = state.attr;
frames.position.putmsg(
format('(%s:%s)', state.cursor.x, state.cursor.y)
);
}
}
this.save_bin = function (fn) {
var f = new File(fn);
f.open('wb');
for (var y = 0; y < frames.canvas.height; y++) {
for (var x = 0; x < frames.canvas.width; x++) {
var ch = frames.canvas.getData(x, y);
f.write(ch.ch ? ch.ch : ' ');
f.writeBin(ch.attr ? ch.attr : 0, 1);
}
}
f.close();
}
this.flip_x = function () {
frames.canvas.flipX();
}
this.flip_y = function () {
frames.canvas.flipY();
}
}
|
export default class ChromeWrapper {
constructor(chrome) {
this._chrome = chrome;
}
getURL(url) {
return this._chrome.extension.getURL(url);
}
get(chromeStorageKey) {
return new Promise(resolve => {
this._chrome.storage.sync.get(chromeStorageKey, (storeObject) =>
resolve(storeObject[chromeStorageKey])
)
});
}
set(keyValuePair) {
return new Promise((resolve) => {
this._chrome.storage.sync.set(keyValuePair);
resolve();
})
}
}
|
'use strict';
test(() => {
assert_equals(document.currentFragment, document.querySelector('#test-8-3-nested'));
}, 'Fixture 8-3 see document.currentFragment - fragment8-3');
|
var iframe = document.querySelector('#iframe-soundcloud');
iframe.src = '//w.soundcloud.com/player/?url=http://api.soundcloud.com';
var widget = SC.Widget(iframe);
widget.load('https://soundcloud.com/tennisinc', {
'auto_play': 1
});
|
import { expect } from 'chai';
import { default as decorator } from '../../lib/decorators/devices.js';
describe('deviceDecorator', () => {
var config = {
remotes: [
{
name: 'test-remote-1',
codes: {
BTN_1: '0x001',
BTN_2: '0x002',
BTN_3: '0x003'
}
},
{
name: 'test-remote-2',
codes: {
BTN_4: '0x004',
BTN_5: '0x005',
BTN_6: '0x006'
}
}
]
}
var output;
beforeEach(() => {
output = decorator(config);
});
it('should cherry pick the remote name', () => {
expect(output[0].name).to.eql('test-remote-1');
expect(output[1].name).to.eql('test-remote-2');
});
it('should have a list of buttons for each remote', () => {
expect(output[0].codes).to.eql([ 'BTN_1', 'BTN_2', 'BTN_3' ]);
expect(output[1].codes).to.eql([ 'BTN_4', 'BTN_5', 'BTN_6' ]);
});
});
|
// @flow
import path from 'path';
import fs from 'fs';
import { parseString } from 'xml2js';
const ANDROID_STRINGS_FILE = path.join(
'android',
'app',
'src',
'main',
'res',
'values',
'strings.xml',
);
const androidStringsFileContent = fs.readFileSync(ANDROID_STRINGS_FILE);
// eslint-disable-next-line import/no-mutable-exports
let appName = '';
parseString(androidStringsFileContent, (e?: Error, json?: Object) => {
if (e) {
console.error(e);
}
if (json && json.resources && json.resources.string && Array.isArray(json.resources.string)) {
appName = json.resources.string.find(string => string.$.name === 'app_name')._;
}
});
export default appName;
|
const _ = require('lodash');
const user = require('../controllers/user.js');
const errHandlerFactory = res => {
return err => {
console.error('route error', err.message);
res.status(500);
res.json(err);
}
};
const respond = res => body => {
if (!body.result && !body.found) {
res.status(404);
return Promise.resolve(res.json({err: 'Not found'}));
}
return Promise.resolve(res.json(body));
};
module.exports = {
http: app => {
app.get('/users', (req, res) => {
user.get(req.query)
.then(respond(res))
.catch( errHandlerFactory(res) )
});
app.get('/users/:id', (req, res) => {
user.get(_.assign({id: req.params.id}, req.query))
.then(respond(res))
.catch( errHandlerFactory(res) )
});
app.post('/users', (req, res) => {
user.create(req.body)
.then(respond(res))
.catch( errHandlerFactory(res) )
});
app.put('/users/:id', (req, res) => {
user.update(req.body)
.then(respond(res))
.catch( errHandlerFactory(res) )
});
app.del('/users/:id', (req, res) => {
user.delete(req.params.id)
.then(respond(res))
.catch( errHandlerFactory(res) )
});
},
ws: io => {
const nsp = io.of('/users');
nsp.on('connection', socket => {
user.watch(socket.handshake.query)
.then(cursor => {
cursor.each((err, data) => {
if (!data) return;
if (data.state) return socket.emit('state', data);
socket.emit('record', data);
});
});
});
}
};
|
const React = require('react');
const ReactTestUtils = require('react-addons-test-utils');
const assert = require('assert');
const {
base: { Actionable },
bootstrap: { Actionable: BootstrapActionable }
} = require('..');
const actionable = {
summary: 'An actionable summary'
};
describe('Actionable', () => {
it('should render summary', () => {
const component = ReactTestUtils.renderIntoDocument(
<Actionable actionable={actionable} />
);
const div = ReactTestUtils.findRenderedDOMComponentWithTag(component, 'div');
assert.equal(
div.textContent,
'An actionable summary'
);
});
it('should render as bootstrap list-group-item', () => {
const component = ReactTestUtils.renderIntoDocument(
<BootstrapActionable actionable={actionable} />
);
const node = ReactTestUtils.findRenderedDOMComponentWithTag(component, 'li');
assert.equal(
node.textContent,
'An actionable summary'
);
assert(node.classList.contains('list-group-item'));
});
it('should respond to doubleclick', () => {
let clicked;
function handler() {
clicked = true;
}
const component = ReactTestUtils.renderIntoDocument(
<BootstrapActionable actionable={actionable} onDoubleClick={handler} />
);
const node = ReactTestUtils.findRenderedDOMComponentWithTag(component, 'li');
ReactTestUtils.Simulate.doubleClick(node);
assert(clicked);
});
});
|
function Ship(fillColor, strokeColor) {
this.angle = 0; // theta
this.angleVelocity = 0; // theta velocity
this.fillColor = fillColor; // body color
this.strokeColor = strokeColor; // perimeter color
}
/**
* changes angle by angleVelocity
*/
Ship.prototype.update = function() {
this.angle += this.angleVelocity;
this.angleVelocity *= 0.7;
};
/**
* shoots a lazer
* pushes it to bullets array
*/
Ship.prototype.shoot = function(bullets) {
bullets.push(new Lazer(-this.angle + PI, 0, 5));
};
/**
* changes the angleVelocity based upon acceleration
*/
Ship.prototype.rotate = function(acceleration) {
this.angleVelocity += acceleration;
};
/**
* draws the ship
*/
Ship.prototype.draw = function() {
fill(this.fillColor);
strokeWeight(2);
stroke(this.strokeColor);
push(); // save translations & rotations
translate(width / 2, height / 2); // draw relative to the center
rotate(this.angle); // draw relative to the angle of the ship
/* draw triangle */
beginShape();
vertex(0, -30);
vertex(15, 15);
vertex(-15, 15);
endShape(CLOSE);
pop(); // revert translations & rotations
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:3d3e3f1a9122d1afd367a8bb595f7a9daa87d006a673773c6ae62c787b72df8e
size 637
|
define(['services/logger'], function (logger) {
var license = {
title: 'License',
description: 'Photos, source code and articles published on this website, that are not explicitly mentioned otherwise, are licensed under <a target="_blank" href="http://creativecommons.org/licenses/by-nc/3.0/deed.en_US">Creative Commons Attribution-NonCommercial 3.0 Unported</a> license.',
terms: [
{ term: 'Attribution' },
{ term: 'Non-Commercial' }
],
creativeCommons: '<a rel="license" target="_blank" href="http://creativecommons.org/licenses/by-nc/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="./Content/images/cc_attribution_nocommercial_88x31.png" /></a>',
additionalTerms: [
{ term: 'If any section of this website mentions it\'s own licensing terms, that will override the terms mentioned here.' }
],
info: 'If you would like to have a higher quality version of any photo published on this website, please <a href="#contact">contact me</a>.',
thirdParty: {
heading: 'Third Party Licenses',
description: 'This website uses the following awesome libraries:',
libraries: [
{ library: 'Durandal JS', license: 'MIT', url: 'https://github.com/BlueSpire/Durandal/blob/master/License.txt' },
{ library: 'Knockout JS', license: 'MIT', url: 'https://github.com/knockout/knockout/blob/master/LICENSE' },
{ library: 'Bootstrap', license: 'Apache', url: 'https://github.com/twbs/bootstrap/blob/master/LICENSE' },
{ library: 'Isotope', license: 'MIT / Commercial', url: 'http://isotope.metafizzy.co/license.html' },
{ library: 'Require JS', license: 'MIT / "New" BSD', url: 'https://github.com/jrburke/requirejs/blob/master/LICENSE' },
{ library: 'Lazy Load Plugin for JQuery', license: 'MIT', url: 'https://github.com/tuupola/jquery_lazyload#license' },
{ library: 'fancyBox', license: 'MIT', url: 'http://www.fancyapps.com/fancybox/#license' }
],
},
activate: activate
};
return license;
function activate() {
}
});
|
/* jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function (defaults) {
var app = new EmberApp(defaults, {
// Add options here
sassOptions: {
includePaths: [
'bower_components/materialize/sass'
]
}
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
return app.toTree();
};
|
// @flow
import React from 'react'
import { TouchableOpacity, Text } from 'react-native'
import styles from './Styles/FullButtonStyle'
import ExamplesRegistry from '../Services/ExamplesRegistry'
// Example
ExamplesRegistry.add('Full Button', () =>
<FullButton
text='Hey there'
onPress={() => window.alert('Full Button Pressed!')}
/>
);
type FullButtonProps = {
text: string,
onPress: () => void,
styles?: Object
}
export default class FullButton extends React.Component {
props: FullButtonProps;
render () {
return (
<TouchableOpacity style={[styles.button, this.props.styles]} onPress={this.props.onPress}>
<Text style={styles.buttonText}>{this.props.text && this.props.text.toUpperCase()}</Text>
</TouchableOpacity>
)
}
}
|
function floor(x, y) { return Math.floor(x, y); }
function max(x, y) { return Math.max(x, y); }
function min(x, y) { return Math.min(x, y); }
function swap(arr, x, y) { var t = arr[x]; arr[x] = arr[y]; arr[y] = t; }
function heapify(arr, cmp) {
if (!cmp) throw "missing cmp";
var len = arr.length;
for (i = floor(len/2); 0 <= i; i--) {
heapshift(arr, cmp, i);
}
return arr;
}
function heapshift(arr, cmp, i){
if (!cmp) throw "missing cmp";
var len = arr.length;
var x; // holds index to swap
while (i <= floor(len/2)) {
var left = 2*i+1, right = left + 1;
x = right < len && 0 < cmp(arr[left], arr[right])
? right
: left < len
? left: null;
if (x && 0 < cmp(arr[i], arr[x])) {
swap(arr, i, x);
i = x;
}
else break;
}
}
function heappop(arr, cmp) {
if (!cmp) throw "missing cmp";
var len = arr.length;
if (!len) throw "empty heap";
if (len == 1){
return arr.shift();
}
var x = arr[0];
arr[0] = arr.pop();
heapshift(arr, cmp, 0);
return x;
}
function heappush(arr, x, cmp) {
if (!cmp) throw "missing cmp";
arr.push(x);
var i = arr.length-1;
while (i > 0) {
var parent = floor((i-1) / 2);
if (0 < cmp(arr[parent], arr[i])) {
swap(arr, parent, i);
i = parent;
}
else break;
}
return arr;
}
function Heap(cmp) {
this.cmp = cmp || function(a, b) {return a - b;};
this.arr = [];
}
Heap.prototype = {
heapify: function(){ return heapify(this.arr, this.cmp); },
push: function(x) { return heappush(this.arr, x, this.cmp); },
pop: function() { return heappop(this.arr, this.cmp); }
}
// test
function testheap() {
var arr = [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
var h = new Heap;
arr.forEach(function(x) {h.push(x);});
console.log(h);
console.log(h.pop(),h.pop(),h.pop(),h.pop(),h.pop(),
h.pop(),h.pop(),h.pop(),h.pop(),h.pop(),
h.pop(),h.pop(),h.pop(),h.pop(),h.pop());
try {h.pop();}
catch(e) { console.log(e); }
console.log("done with object testing");
function testcmp (x, y){return x-y;}
console.log(
heapify(arr, testcmp));
console.log(
heappush(arr, 16, testcmp));
console.log(
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp),
heappop(arr, testcmp)
);
}
|
/*global defineSuite*/
defineSuite([
'Renderer/loadCubeMap',
'Core/Cartesian3',
'Core/defined',
'Core/PrimitiveType',
'Renderer/Buffer',
'Renderer/BufferUsage',
'Renderer/DrawCommand',
'Renderer/ShaderProgram',
'Renderer/VertexArray',
'Specs/createContext',
'ThirdParty/when'
], function(
loadCubeMap,
Cartesian3,
defined,
PrimitiveType,
Buffer,
BufferUsage,
DrawCommand,
ShaderProgram,
VertexArray,
createContext,
when) {
"use strict";
/*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,fail*/
var context;
beforeAll(function() {
context = createContext();
});
afterAll(function() {
context.destroyForSpecs();
});
it('loads a cube map', function() {
return loadCubeMap(context, {
positiveX : './Data/Images/Green.png',
negativeX : './Data/Images/Blue.png',
positiveY : './Data/Images/Green.png',
negativeY : './Data/Images/Blue.png',
positiveZ : './Data/Images/Green.png',
negativeZ : './Data/Images/Blue.png'
}).then(function(cm) {
expect(cm.width).toEqual(1);
expect(cm.height).toEqual(1);
var vs = 'attribute vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }';
var fs =
'uniform samplerCube u_texture;' +
'uniform mediump vec3 u_direction;' +
'void main() { gl_FragColor = textureCube(u_texture, normalize(u_direction)); }';
var sp = ShaderProgram.fromCache({
context : context,
vertexShaderSource : vs,
fragmentShaderSource : fs,
attributeLocations : {
position : 0
}
});
sp.allUniforms.u_texture.value = cm;
var va = new VertexArray({
context : context,
attributes : [{
vertexBuffer : Buffer.createVertexBuffer({
context : context,
typedArray : new Float32Array([0, 0, 0, 1]),
usage : BufferUsage.STATIC_DRAW
}),
componentsPerAttribute : 4
}]
});
var command = new DrawCommand({
primitiveType : PrimitiveType.POINTS,
shaderProgram : sp,
vertexArray : va
});
// +X is green
sp.allUniforms.u_direction.value = new Cartesian3(1, 0, 0);
command.execute(context);
expect(context.readPixels()).toEqual([0, 255, 0, 255]);
// -X is blue
sp.allUniforms.u_direction.value = new Cartesian3(-1, 0, 0);
command.execute(context);
expect(context.readPixels()).toEqual([0, 0, 255, 255]);
// +Y is green
sp.allUniforms.u_direction.value = new Cartesian3(0, 1, 0);
command.execute(context);
expect(context.readPixels()).toEqual([0, 255, 0, 255]);
// -Y is blue
sp.allUniforms.u_direction.value = new Cartesian3(0, -1, 0);
command.execute(context);
expect(context.readPixels()).toEqual([0, 0, 255, 255]);
// +Z is green
sp.allUniforms.u_direction.value = new Cartesian3(0, 0, 1);
command.execute(context);
expect(context.readPixels()).toEqual([0, 255, 0, 255]);
// -Z is blue
sp.allUniforms.u_direction.value = new Cartesian3(0, 0, -1);
command.execute(context);
expect(context.readPixels()).toEqual([0, 0, 255, 255]);
sp.destroy();
va.destroy();
cm.destroy();
});
});
it('calls error function when positiveX does not exist', function() {
return loadCubeMap(context, {
positiveX : 'not.found',
negativeX : './Data/Images/Blue.png',
positiveY : './Data/Images/Blue.png',
negativeY : './Data/Images/Blue.png',
positiveZ : './Data/Images/Blue.png',
negativeZ : './Data/Images/Blue.png'
}).then(function(cubeMap) {
fail('should not be called');
}).otherwise(function() {
});
});
it('calls error function when negativeX does not exist', function() {
return loadCubeMap(context, {
positiveX : './Data/Images/Blue.png',
negativeX : 'not.found',
positiveY : './Data/Images/Blue.png',
negativeY : './Data/Images/Blue.png',
positiveZ : './Data/Images/Blue.png',
negativeZ : './Data/Images/Blue.png'
}).then(function(cubeMap) {
fail('should not be called');
}).otherwise(function() {
});
});
it('calls error function when positiveY does not exist', function() {
return loadCubeMap(context, {
positiveX : './Data/Images/Blue.png',
negativeX : './Data/Images/Blue.png',
positiveY : 'not.found',
negativeY : './Data/Images/Blue.png',
positiveZ : './Data/Images/Blue.png',
negativeZ : './Data/Images/Blue.png'
}).then(function(cubeMap) {
fail('should not be called');
}).otherwise(function() {
});
});
it('calls error function when negativeY does not exist', function() {
return loadCubeMap(context, {
positiveX : './Data/Images/Blue.png',
negativeX : './Data/Images/Blue.png',
positiveY : './Data/Images/Blue.png',
negativeY : 'not.found',
positiveZ : './Data/Images/Blue.png',
negativeZ : './Data/Images/Blue.png'
}).then(function(cubeMap) {
fail('should not be called');
}).otherwise(function() {
});
});
it('calls error function when positiveZ does not exist', function() {
return loadCubeMap(context, {
positiveX : './Data/Images/Blue.png',
negativeX : './Data/Images/Blue.png',
positiveY : './Data/Images/Blue.png',
negativeY : './Data/Images/Blue.png',
positiveZ : 'not.found',
negativeZ : './Data/Images/Blue.png'
}).then(function(cubeMap) {
fail('should not be called');
}).otherwise(function() {
});
});
it('calls error function when negativeZ does not exist', function() {
return loadCubeMap(context, {
positiveX : './Data/Images/Blue.png',
negativeX : './Data/Images/Blue.png',
positiveY : './Data/Images/Blue.png',
negativeY : './Data/Images/Blue.png',
positiveZ : './Data/Images/Blue.png',
negativeZ : 'not.found'
}).then(function(cubeMap) {
fail('should not be called');
}).otherwise(function() {
});
});
it('throws without a context', function() {
expect(function() {
loadCubeMap(undefined);
}).toThrowDeveloperError();
});
it('throws without urls', function() {
expect(function() {
loadCubeMap(context);
}).toThrowDeveloperError();
});
it('throws without positiveX', function() {
expect(function() {
loadCubeMap(context, {
negativeX : 'any.image',
positiveY : 'any.image',
negativeY : 'any.image',
positiveZ : 'any.image',
negativeZ : 'any.image'
});
}).toThrowDeveloperError();
});
it('throws without negativeX', function() {
expect(function() {
loadCubeMap(context, {
positiveX : 'any.image',
positiveY : 'any.image',
negativeY : 'any.image',
positiveZ : 'any.image',
negativeZ : 'any.image'
});
}).toThrowDeveloperError();
});
it('throws without positiveY', function() {
expect(function() {
loadCubeMap(context, {
positiveX : 'any.image',
negativeX : 'any.image',
negativeY : 'any.image',
positiveZ : 'any.image',
negativeZ : 'any.image'
});
}).toThrowDeveloperError();
});
it('throws without negativeY', function() {
expect(function() {
loadCubeMap(context, {
positiveX : 'any.image',
negativeX : 'any.image',
positiveY : 'any.image',
positiveZ : 'any.image',
negativeZ : 'any.image'
});
}).toThrowDeveloperError();
});
it('throws without positiveZ', function() {
expect(function() {
loadCubeMap(context, {
positiveX : 'any.image',
negativeX : 'any.image',
positiveY : 'any.image',
negativeY : 'any.image',
negativeZ : 'any.image'
});
}).toThrowDeveloperError();
});
it('throws without negativeZ', function() {
expect(function() {
loadCubeMap(context, {
positiveX : 'any.image',
negativeX : 'any.image',
positiveY : 'any.image',
negativeY : 'any.image',
positiveZ : 'any.image'
});
}).toThrowDeveloperError();
});
}, 'WebGL');
|
#!/usr/bin/env node
var mkdirp = require('yeoman-generator/node_modules/mkdirp')
var path = require('path')
var del = require('del')
var win32 = process.platform === 'win32'
var homeDir = process.env[ win32? 'USERPROFILE' : 'HOME']
// USERPROFILE 文件销毁
del([path.join(homeDir, '.generator-lego')], {force:true})
|
module.exports = function(grunt) {
"use strict";
grunt.registerTask( "init", [ "mkdir" ] );
grunt.registerTask( "default", [ "clean", "src", "uglify", "scss", "bytesize" ] );
grunt.registerTask( "mdzr", [ "modernizr:dist" ] );
grunt.registerTask( "lint", [ "jshint", "lintspaces" ] );
grunt.registerTask( "src", [ "lint", "concat", "usebanner" ] );
grunt.registerTask( "scss", [ "sass", "postcss", "cssmin" ] );
grunt.registerTask( "test", [ "qunit" ] );
grunt.registerTask( "deploy", [ "default", "gh-pages" ] );
};
|
// provide tests or parts of tests that are commonly performed.
var testUtility = {};
|
var http = require('http'),
parser = require('libxml-to-js'),
parse_util = require('./parse-util'),
log4js = require('log4js'),
logger = log4js.getLogger('proxy'),
// Requirement in using MassDOT service that client can only make a request at most every 10 seconds.
delay = 10000,
delayTimer = 0,
queue = [],
processing = false,
Request = {
options: undefined,
parseDelegate: undefined,
deferred: undefined,
execute: function() {
var self = this;
logger.info(self.options.path);
http.get( self.options, function( http_res ) {
var data = '';
http_res.on('data', function(chunk) {
data += chunk;
})
.on('end', function() {
parser( data, self.parseDelegate(self.deferred) );
});
})
.on('error', function(e) {
self.deferred( JSON.stringify({error:e.message}) );
});
}
};
// http://onemoredigit.com/post/1527191998/extending-objects-in-node-js
Object.defineProperty(Object.prototype, "extend", {
enumerable: false,
value: function(from) {
var props = Object.getOwnPropertyNames(from);
var dest = this;
props.forEach(function(name) {
var destination = Object.getOwnPropertyDescriptor(from, name);
Object.defineProperty(dest, name, destination);
});
return this;
}
});
function loadNext() {
clearTimeout( delayTimer );
if( queue.length > 0 ) {
logger.debug( 'Request being processed...' );
processing = true;
queue.shift().execute();
delayTimer = setTimeout( loadNext, delay );
}
else {
processing = false;
}
}
function queueRequest( options, parseDelegate, deferred ) {
queue[queue.length] = Object.create(Request).extend({
options: options,
parseDelegate: parseDelegate,
deferred: deferred
});
if( !processing ) {
logger.debug( 'Processing freed up for request.' );
loadNext();
}
else {
logger.debug( 'Request delayed...' + delayTimer + 'ms' );
}
}
exports.parse_util = parse_util;
exports.requestData = function( options, parseDelegate, deferred ) {
logger.debug( 'New request for data...' + options );
queueRequest(options, parseDelegate, deferred);
};
|
import Phaser from 'phaser';
import Dungeon from 'backstab/Dungeon';
export default class Preload extends Phaser.Scene {
constructor() {
super('preload');
}
init() {
this.assetsReady = false;
}
preload() {
this.load.image('tileset', 'assets/tileset.png');
this.load.atlas(
'characters',
'assets/characters.png',
'assets/characters.json',
);
}
create() {
this.assetsReady = true;
}
update() {
// Wait until all sound effects have been decoded into memory.
if (this.assetsReady) {
const dungeon = new Dungeon();
dungeon.descend();
this.scene.start('DungeonLevel', dungeon);
}
}
}
|
App.Routing = Backbone.Router.extend({
/*
Example code from node-backbone
routes:{
"":"list",
"list":"list",
"employees/:id":"employeeDetails",
"employees/:id/reports":"directReports"
},
initialize:function () {
$('.back').live('click', function(event) {
window.history.back();
return false;
});
this.firstPage = true;
this.searchResults = new EmployeeCollection();
},
list:function () {
this.changePage(new EmployeeListPage({model: this.searchResults}));
},
employeeDetails:function (id) {
var employee = new Employee({_id:id});
var self = this;
employee.fetch({
success:function (data) {
self.changePage(new EmployeeView({model:data}));
}
});
},
directReports:function (id) {
var employee = new Employee({_id:id});
employee.reports.fetch();
this.changePage(new DirectReportPage({model:employee.reports}));
},
changePage:function (page) {
$(page.el).attr('data-role', 'page');
page.render();
$('body').append($(page.el));
var transition = $.mobile.defaultPageTransition;
// We don't want to slide the first page
if (this.firstPage) {
transition = 'none';
this.firstPage = false;
}
$.mobile.changePage($(page.el), {changeHash:false, transition: transition});
}
*/
});
|
import Scene from './Scene'
describe('(Models) Scene', () => {
it('Should create instance', () => {
const instance = new Scene()
expect(instance).to.be.ok
})
it('Should set default value', () => {
const instance = new Scene()
expect(instance.get('id')).to.eql(0)
expect(instance.get('name')).to.eql('Scene')
})
it('Should set value by constructor', () => {
const instance = new Scene({
id: 1,
name: 'hoge'
})
expect(instance.get('id')).to.eql(1)
expect(instance.get('name')).to.eql('hoge')
})
it('Should set name', () => {
let instance = new Scene()
expect(instance.get('name')).to.eql('Scene')
instance = instance.setName('name')
expect(instance.get('name')).to.eql('name')
instance = instance.setName('another name')
expect(instance.get('name')).to.eql('another name')
instance = instance.setName('')
expect(instance.get('name')).to.eql('')
})
})
|
//
// The Grunt configuration file for this application.
//
// Grunt is a build and task runner system: it compiles
// javascript templates, minifies CSS, even runs a local
// server.
//
// For more info, see http://gruntjs.com/
//
'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
return connect.static(require('path').resolve(dir));
};
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to match all subfolders:
// 'test/spec/**/*.js'
// templateFramework: 'lodash'
module.exports = function (grunt) {
// show elapsed time at the end
require('time-grunt')(grunt);
// load all grunt tasks
require('load-grunt-tasks')(grunt);
// configurable paths
var yeomanConfig = {
app: 'app',
dist: 'dist'
};
grunt.initConfig({
yeoman: yeomanConfig,
watch: {
options: {
nospawn: true
},
coffee: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.coffee'],
tasks: ['coffee:dist']
},
coffeeTest: {
files: ['test/spec/{,*/}*.coffee'],
tasks: ['coffee:test']
},
compass: {
files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['compass']
},
livereload: {
options: {
livereload: LIVERELOAD_PORT
},
files: [
'<%= yeoman.app %>/*.html',
'{.tmp,<%= yeoman.app %>}/styles/{,*/}*.css',
'{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}'
]
},
jst: {
files: [
'<%= yeoman.app %>/scripts/templates/*.ejs'
],
tasks: ['jst']
}
},
connect: {
options: {
port: 9000,
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app)
];
}
}
},
test: {
options: {
middleware: function (connect) {
return [
mountFolder(connect, '.tmp'),
mountFolder(connect, 'test'),
mountFolder(connect, yeomanConfig.app)
];
}
}
},
dist: {
options: {
middleware: function (connect) {
return [
mountFolder(connect, yeomanConfig.dist)
];
}
}
}
},
open: {
server: {
path: 'http://localhost:<%= connect.options.port %>'
}
},
clean: {
dist: ['.tmp', '<%= yeoman.dist %>/*'],
server: '.tmp'
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js',
'!<%= yeoman.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
mocha: {
all: {
options: {
run: true,
urls: ['http://localhost:<%= connect.options.port %>/index.html']
}
}
},
coffee: {
dist: {
files: [{
// rather than compiling multiple files here you should
// require them into your main .coffee file
expand: true,
cwd: '<%= yeoman.app %>/scripts',
src: '{,*/}*.coffee',
dest: '.tmp/scripts',
ext: '.js'
}]
},
test: {
files: [{
expand: true,
cwd: 'test/spec',
src: '{,*/}*.coffee',
dest: '.tmp/spec',
ext: '.js'
}]
}
},
compass: {
options: {
sassDir: '<%= yeoman.app %>/styles',
cssDir: '.tmp/styles',
imagesDir: '<%= yeoman.app %>/images',
javascriptsDir: '<%= yeoman.app %>/scripts',
fontsDir: '<%= yeoman.app %>/styles/fonts',
importPath: '<%= yeoman.app %>/bower_components',
relativeAssets: true
},
dist: {},
server: {
options: {
debugInfo: true
}
}
},
// compile the Handlebars templates to JST files
// For more info on JST https://code.google.com/p/trimpath/wiki/JavaScriptTemplates
handlebars: {
compile: {
options: {
// the namespace to which the precompiled templates will be assigned
namespace: 'JST' // access the templates via window.JST['path/to/template']
//wrapped: 'true'
},
files: {
// path.to.target.compiled.file : path.to.source.files
'.tmp/scripts/templates.js': ['<%= yeoman.app %>/templates/**/*.handlebars']
}
}
},
// not enabled since usemin task does concat and uglify
// check index.html to edit your build targets
// enable this task if you prefer defining your build targets here
/*uglify: {
dist: {}
},*/
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>'
}
},
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
dirs: ['<%= yeoman.dist %>']
}
},
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
// minify the CSS files, combine into a single file
// must be run *after* compass has compiled the .sass into .css
cssmin: {
dist: {
files: {
'<%= yeoman.dist %>/styles/main.css': [
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/styles/{,*/}*.css'
],
// styles for inside the iframe of the wysihtml5 rich text editor
'<%= yeoman.dist %>/styles/editor/editor.css': ['.tmp/styles/editor/editor.css']
}
}
},
htmlmin: {
dist: {
options: {
/*removeCommentsFromCDATA: true,
// https://github.com/yeoman/grunt-usemin/issues/44
//collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeOptionalTags: true*/
},
files: [{
expand: true,
cwd: '<%= yeoman.app %>',
src: '*.html',
dest: '<%= yeoman.dist %>'
}]
}
},
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,txt}',
'.htaccess',
'images/{,*/}*.{webp,gif}',
'fonts/{,*/}*.{svg,eot,ttf,woff,html,js,css}',
'scripts/vendor/wysihtml5*.js',
'php/firsts.php'
]
}]
}
},
bower: {
all: {
rjsConfig: '<%= yeoman.app %>/scripts/main.js'
}
},
// Use 'rev' task together with yeoman/grunt-usemin for cache busting of static files.
// Allows the files to be cached forever by the browser.
// Will rename files to stuff like becff3a.main.js
rev: {
dist: {
files: {
src: [
// ignore the wysihtml5*.js files, which are admin-only
// and loaded dynamically in javascript
'<%= yeoman.dist %>/scripts/{,*/}!(wysihtml5)*.js',
// ignore the CSS files in styles/editor/, which are admin-only
// and loaded dynamically in javascript
'<%= yeoman.dist %>/styles/{,*/}!(stylesheet|editor)*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
}
}
});
// Grunt task for precompiling Handlebars templates
// For more info on Handlebars precompilation: http://handlebarsjs.com/precompilation.html
grunt.loadNpmTasks('grunt-contrib-handlebars');
grunt.registerTask('createDefaultTemplate', function () {
grunt.file.write('.tmp/scripts/templates.js', 'this.JST = this.JST || {};');
});
grunt.registerTask('server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
} else if (target === 'test') {
return grunt.task.run([
'clean:server',
'coffee',
'createDefaultTemplate',
'jst',
'compass:server',
'connect:test:keepalive'
]);
}
grunt.task.run([
'clean:server',
'coffee:dist',
'createDefaultTemplate',
'compass:server',
'connect:livereload',
'open',
'watch'
]);
});
grunt.registerTask('test', [
'clean:server',
'coffee',
'createDefaultTemplate',
'compass',
'connect:test',
'mocha'
]);
// build production version of app
grunt.registerTask('build', [
'clean:dist',
'coffee',
'createDefaultTemplate',
'handlebars',
'compass:dist',
'useminPrepare',
'imagemin',
'htmlmin',
'concat',
'cssmin',
'uglify',
'copy',
'rev',
'usemin'
]);
grunt.registerTask('default', [
'jshint',
'test',
'build'
]);
};
|
import fetch from 'isomorphic-fetch'
import { apiUrlConfig } from '../../utils/config'
const API_URL = apiUrlConfig + 'api/'
// ------------------------------------
// Constants
// ------------------------------------
export const GET_JURUSAN_START = 'GET_JURUSAN_START'
export const GET_JURUSAN_SUCCESS = 'GET_JURUSAN_SUCCESS'
export const GET_JURUSAN_BY_ID_START = 'GET_JURUSAN_BY_ID_START'
export const GET_JURUSAN_BY_ID_SUCCESS = 'GET_JURUSAN_BY_ID_SUCCESS'
export const ADD_JURUSAN_START = 'ADD_JURUSAN_START'
export const ADD_JURUSAN_SUCCESS = 'ADD_JURUSAN_SUCCESS'
export const UPDATE_JURUSAN_START = 'UPDATE_JURUSAN_START'
export const UPDATE_JURUSAN_SUCCESS = 'UPDATE_JURUSAN_SUCCESS'
// ------------------------------------
// Actions
// ------------------------------------
// ------------------------------------
// Actions Get mahasiswa data
// ------------------------------------
function getJurusanStart () {
return {
type: GET_JURUSAN_START
}
}
function getJurusanFinish (result) {
return {
type: GET_JURUSAN_SUCCESS,
data: result
}
}
export function getJurusan () {
return (dispatch) => {
dispatch(getJurusanStart())
return fetch(API_URL + 'jurusan', {
method: 'get',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-access-token': window.localStorage.getItem('auth-key')
}
})
.then((response) => response.json())
.then((json) => dispatch(getJurusanFinish(json)))
}
}
// ------------------------------------
// Actions Get Jurusan data By Id
// ------------------------------------
function getJurusanByIdStart () {
return {
type: GET_JURUSAN_BY_ID_START
}
}
function getJurusanByIdFinish (result) {
return {
type: GET_JURUSAN_BY_ID_SUCCESS,
data: result
}
}
export function getJurusanById (id) {
return (dispatch) => {
dispatch(getJurusanByIdStart())
return fetch(API_URL + 'jurusan/' + id, {
method: 'get',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-access-token': window.localStorage.getItem('auth-key')
}
})
.then((response) => response.json())
.then((json) => dispatch(getJurusanByIdFinish(json)))
}
}
// ------------------------------------
// Actions insert jurusan data
// ------------------------------------
function addJurusanStart () {
return {
type: ADD_JURUSAN_START
}
}
function addJurusanFinish (result) {
console.log(result)
return {
type: ADD_JURUSAN_SUCCESS,
data: result
}
}
export function addJurusan (jurusan) {
return (dispatch) => {
dispatch(addJurusanStart())
return fetch(API_URL + 'jurusan', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(jurusan)
})
.then((response) => response.json())
.then((json) => dispatch(addJurusanFinish(json)))
}
}
// ------------------------------------
// Actions update jurusan data
// ------------------------------------
function updateJurusanStart () {
return {
type: UPDATE_JURUSAN_START
}
}
function updateJurusanFinish (result) {
console.log(result)
return {
type: UPDATE_JURUSAN_SUCCESS,
data: result
}
}
export function updateJurusan (kode, jurusan) {
return (dispatch) => {
dispatch(updateJurusanStart())
return fetch(API_URL + 'jurusan/' + kode, {
method: 'put',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(jurusan)
})
.then((response) => response.json())
.then((json) => dispatch(updateJurusanFinish(json)))
}
}
// ------------------------------------
// Reducer
// ------------------------------------
let initialState = {
isLoading: false
}
export default function jurusanReducers (state = initialState, action) {
switch (action.type) {
case GET_JURUSAN_START:
return Object.assign({}, state, {
isLoadingData: true
})
case GET_JURUSAN_SUCCESS:
return Object.assign({}, state, {
isLoadingData: false,
data: action.data
})
case GET_JURUSAN_BY_ID_START:
return Object.assign({}, state, {
isLoadingData: true
})
case GET_JURUSAN_BY_ID_SUCCESS:
return Object.assign({}, state, {
isLoadingData: false,
data: action.data
})
case ADD_JURUSAN_START:
return Object.assign({}, state, {
isLoadingData: true
})
case ADD_JURUSAN_SUCCESS:
return Object.assign({}, state, {
isLoadingData: false,
data: action.data
})
case UPDATE_JURUSAN_START:
return Object.assign({}, state, {
isLoadingData: true
})
case UPDATE_JURUSAN_SUCCESS:
return Object.assign({}, state, {
isLoadingData: false,
data: action.data
})
default:
return state
}
}
|
export default {
documents: [],
users: []
};
|
import DataFetcher from '../../lib/DataFetcher';
import { Module } from '../../lib/di';
import { selector } from '../../lib/selector';
import Enum from '../../lib/Enum';
import { actionTypeGenerator } from '../../lib/actionTypeGenerator';
import { isEnded, removeInboundRingOutLegs } from '../../lib/callLogHelpers';
import debounce from '../../lib/debounce';
import { getDataReducer } from './getPresenceReducer';
import subscriptionFilters from '../../enums/subscriptionFilters';
import dndStatus from './dndStatus';
import { presenceStatus } from '../../enums/presenceStatus.enum';
import proxify from '../../lib/proxy/proxify';
import ensureExist from '../../lib/ensureExist';
const presenceRegExp = /.*\/presence(\?.*)?/;
const detailedPresenceRegExp = /.*\/presence\?detailedTelephonyState=true&sipData=true/;
@Module({
deps: [
'RolesAndPermissions',
'ConnectivityMonitor',
{ dep: 'Storage', optional: true },
{ dep: 'PresenceOptions', optional: true },
],
})
export default class Presence extends DataFetcher {
constructor({
detailed = true,
fetchRemainingDelay = 2000,
ttl = 62 * 1000,
polling = false,
pollingInterval = 3 * 60 * 1000,
connectivityMonitor,
rolesAndPermissions,
...options
}) {
super({
...options,
polling,
ttl,
pollingInterval,
getDataReducer,
fetchFunction: async () => {
const endpoint = this._detailed
? subscriptionFilters.detailedPresence
: subscriptionFilters.presence;
const data = (await this._client.service
.platform()
.get(endpoint)).json();
return data;
},
subscriptionFilters: [
detailed
? subscriptionFilters.detailedPresence
: subscriptionFilters.presence,
],
subscriptionHandler: (message) => {
const regExp = this._detailed ? detailedPresenceRegExp : presenceRegExp;
if (regExp.test(message.event) && message.body) {
if (message.body.sequence) {
if (message.body.sequence < this.sequence) {
return;
}
}
const { body } = message;
this.store.dispatch({
data: body,
type: this.actionTypes.notification,
lastDndStatus: this.dndStatus,
timestamp: Date.now(),
});
/**
* as pointed out by Igor in https://jira.ringcentral.com/browse/PLA-33391,
* when the real calls count larger than the active calls returned by the pubnub,
* we need to pulling the calls manually.
*/
const { activeCalls = [], totalActiveCalls = 0 } = body;
if (activeCalls.length !== totalActiveCalls) {
this._fetchRemainingCalls();
}
}
},
readyCheckFn: () =>
this._rolesAndPermissions.ready && this._connectivityMonitor.ready,
});
this._detailed = true;
this._connectivityMonitor = this::ensureExist(
connectivityMonitor,
'connectivityMonitor',
);
this._rolesAndPermissions = this::ensureExist(
rolesAndPermissions,
'rolesAndPermissions',
);
this._fetchRemainingCalls = debounce(
() => this.fetchData(),
fetchRemainingDelay,
);
}
get _name() {
return 'presence';
}
get _actionTypes() {
return new Enum(
[
...Object.keys(super._actionTypes),
...actionTypeGenerator('update'),
'notification',
],
this._name,
);
}
async _onStateChange() {
if (this._shouldInit()) {
this._connectivity = this._connectivityMonitor.connectivity;
}
super._onStateChange();
if (
this.ready &&
this._connectivityMonitor &&
this._connectivityMonitor.ready &&
this._connectivity !== this._connectivityMonitor.connectivity
) {
this._connectivity = this._connectivityMonitor.connectivity;
// fetch data on regain connectivity
if (this._connectivity && this._hasPermission) {
this.fetchData();
}
}
}
@proxify
async _update(params) {
if (!this._rolesAndPermissions.hasEditPresencePermission) {
return;
}
try {
const { ownerId } = this._auth;
const platform = this._client.service.platform();
const response = await platform.put(
'/account/~/extension/~/presence',
params,
);
const data = response.json();
if (ownerId === this._auth.ownerId) {
this.store.dispatch({
type: this.actionTypes.updateSuccess,
data,
lastDndStatus: this.dndStatus,
});
}
} catch (error) {
this.store.dispatch({
type: this.actionTypes.updateError,
error,
});
throw error;
}
}
_getUpdateStatusParams(userStatusParams) {
const params = {
dndStatus: this.dndStatus,
userStatus: userStatusParams,
};
if (
params.dndStatus !== dndStatus.takeAllCalls &&
params.dndStatus !== dndStatus.doNotAcceptDepartmentCalls
) {
params.dndStatus = this.lastNotDisturbDndStatus || dndStatus.takeAllCalls;
}
return params;
}
async setAvailable() {
if (
this.userStatus === presenceStatus.available &&
this.dndStatus !== dndStatus.doNotAcceptAnyCalls
) {
return;
}
const params = this._getUpdateStatusParams(presenceStatus.available);
await this._update(params);
}
async setBusy() {
if (
this.userStatus === presenceStatus.busy &&
this.dndStatus !== dndStatus.doNotAcceptAnyCalls
) {
return;
}
const params = this._getUpdateStatusParams(presenceStatus.busy);
await this._update(params);
}
async setDoNotDisturb() {
if (this.dndStatus === dndStatus.doNotAcceptAnyCalls) {
return;
}
const params = {
dndStatus: dndStatus.doNotAcceptAnyCalls,
};
await this._update(params);
}
async setInvisible() {
if (
this.userStatus === presenceStatus.offline &&
this.dndStatus !== dndStatus.doNotAcceptAnyCalls
) {
return;
}
const params = this._getUpdateStatusParams(presenceStatus.offline);
await this._update(params);
}
async setPresence(presenceData) {
switch (presenceData) {
case presenceStatus.available:
await this.setAvailable();
break;
case presenceStatus.busy:
await this.setBusy();
break;
case dndStatus.doNotAcceptAnyCalls:
await this.setDoNotDisturb();
break;
case presenceStatus.offline:
await this.setInvisible();
break;
default:
await this.setAvailable();
break;
}
}
async toggleAcceptCallQueueCalls() {
const params = {
userStatus: this.userStatus,
};
if (this.dndStatus === dndStatus.takeAllCalls) {
params.dndStatus = dndStatus.doNotAcceptDepartmentCalls;
} else if (this.dndStatus === dndStatus.doNotAcceptDepartmentCalls) {
params.dndStatus = dndStatus.takeAllCalls;
}
if (params.dndStatus) {
await this._update(params);
}
}
/**
* @override
* @description make sure data returns object so that the property getters
* will not fail.
* @returns {Object}
*/
get data() {
return super.data || {};
}
get sequence() {
return this.data.sequence;
}
@selector
activeCalls = [() => this.data.activeCalls, (calls) => calls || []];
@selector
calls = [
() => this.activeCalls,
(activeCalls) =>
removeInboundRingOutLegs(activeCalls).filter((call) => !isEnded(call)),
];
@selector
sessionIdList = [
() => this.calls,
(calls) => calls.map((call) => call.sessionId),
];
get telephonyStatus() {
return this.data.telephonyStatus;
}
get dndStatus() {
return this.data.dndStatus;
}
get lastNotDisturbDndStatus() {
return this.data.lastNotDisturbDndStatus;
}
get userStatus() {
return this.data.userStatus;
}
get presenceStatus() {
return this.data.presenceStatus;
}
get meetingStatus() {
return this.data.meetingStatus;
}
get presenceOption() {
// available
if (
this.data.userStatus === presenceStatus.available &&
this.data.dndStatus !== dndStatus.doNotAcceptAnyCalls
) {
return presenceStatus.available;
}
// busy
if (
this.data.userStatus === presenceStatus.busy &&
this.data.dndStatus !== dndStatus.doNotAcceptAnyCalls
) {
return presenceStatus.busy;
}
// doNotDisturb
if (this.data.dndStatus === dndStatus.doNotAcceptAnyCalls) {
return dndStatus.doNotAcceptAnyCalls;
}
// invisible
if (
this.data.userStatus === presenceStatus.offline &&
this.data.dndStatus !== dndStatus.doNotAcceptAnyCalls
) {
return presenceStatus.offline;
}
return presenceStatus.available;
}
get _hasPermission() {
return this._rolesAndPermissions.hasPresencePermission;
}
}
|
/**
+-------------------------------------------------------------------
* jQuery ThinkBox - 弹出层插件 - http://zjzit.cn/thinkbox
+-------------------------------------------------------------------
* @version 1.0.0 beta
* @since 2012.09.25
* @author 麦当苗儿 <zuojiazi.cn@gmail.com>
* @github https://github.com/Aoiujz/ThinkBox.git
+-------------------------------------------------------------------
*/
(function($){
/* 弹出层默认选项 */
var defaults = {
'title' : null, // 弹出层标题
'fixed' : true, // 是否使用固定定位(fixed)而不是绝对定位(absolute),固定定位的对话框不受浏览器滚动条影响。IE6不支持固定定位,其永远表现为绝对定位。
'center' : true, // 对话框是否屏幕中心显示
'clone' : true, // 是否对弹出内容克隆
'x' : 0, // 对话框 x 坐标。 当 center 属性为 true 时此属性无效
'y' : 0, // 对话框 y 坐标。 当 center 属性为 true 时此属性无效
'modal' : true, // 对话框是否设置为模态。设置为 true 将显示遮罩背景,禁止其他事件触发
'modalClose' : true, // 点击模态背景是否关闭弹出层
'resize' : true, // 是否在窗口大小改变时重新定位弹出层位置
'unload' : true, // 隐藏后是否卸载
'close' : '[关闭]', // 关闭按钮显示文字,留空则不显示关闭按钮
'escHide' : true, // 按ESC是否关闭弹出层
'delayClose' : 0, // 延时自动关闭弹出层 0表示不自动关闭
'drag' : false, // 点击标题框是否允许拖动
'display' : true, // 是否在创建后立即显示
'width' : '', // 弹出层内容区域宽度 空表示自适应
'height' : '', // 弹出层内容区域高度 空表示自适应
'dataEle' : '', // 弹出层绑定到的元素,设置此属性的弹出层只允许同时存在一个
'locate' : ['left', 'top'], //弹出层位置属性
'show' : ['fadeIn', 'normal'], //显示效果
'hide' : ['fadeOut', 'normal'], //关闭效果
'button' : [], //工具栏按钮
'style' : 'default', //弹出层样式
'titleChange' : undefined, //分组标题切换后的回调方法
'beforeShow' : undefined, //显示前的回调方法
'afterShow' : undefined, //显示后的回调方法
'afterHide' : undefined, //隐藏后的回调方法
'beforeUnload': undefined, //卸载前的回调方法
'afterDrag' : undefined //拖动停止后的回调方法
};
/* 弹出层层叠高度 */
var zIndex = 2012;
/* 当前选中的弹出层对象 */
var current = null;
/* 弹出层容器 */
var wrapper = ['<div class="ThinkBox-wrapper" style="position:absolute;width: auto">', //弹出层外层容器
'<table cellspacing="0" cellpadding="0" border="0" style="width: auto">', //使用表格,可以做到良好的宽高自适应,而且方便做圆角样式
'<tr>',
'<td class="box-top-left"></td>', //左上角
'<td class="box-top"></td>', //上边
'<td class="box-top-right"></td>', //右上角
'</tr>',
'<tr>',
'<td class="box-left"></td>', //左边
'<td class="ThinkBox-inner"></td>', //弹出层inner
'<td class="box-right"></td>', //右边
'</tr>',
'<tr>',
'<td class="box-bottom-left"></td>', //左下角
'<td class="box-bottom"></td>', //下边
'<td class="box-bottom-right"></td>', //右下角
'</tr>',
'</table>',
'</div>'].join('');
/* 弹出层标题栏 */
var titleBar = ['<tr class="ThinkBox-title">',
'<td class="box-title-left"></td>', //标题栏左边
'<td class="ThinkBox-title-inner"></td>', //标题栏inner
'<td class="box-title-right"></td>', //标题栏右边
'</tr>'].join('');
/* 弹出层按钮工具栏 */
var toolsBar = ['<tr class="ThinkBox-tools">',
'<td class="box-tools-left"></td>', //工具栏左边
'<td class="ThinkBox-tools-inner"></td>', //工具栏inner
'<td class="box-tools-right"></td>', //工具栏右边
'</tr>'].join('');
/* 页面DOM和window分别对应的JQUERY对象 */
var _doc = $(document), _win = $(window);
/**
* 构造方法,用于实例化一个新的弹出层对象
+----------------------------------------------------------
* element 弹出层内容元素
* options 弹出层选项
+----------------------------------------------------------
*/
var ThinkBox = function(element, options){
var self = this, visible = false, modal = null;
var options = $.extend({}, defaults, options || {});
var box = $(wrapper).addClass('ThinkBox-' + options.style).data('ThinkBox', this); //创建弹出层容器
options.dataEle && $(options.dataEle).data('ThinkBox', this); //缓存弹出层,防止弹出多个
//给box绑定事件
box.hover(function(){_fire.call(self, options.mouseover)},function(){_fire.call(self, options.mouseout)})
.mousedown(function(event){_setCurrent();event.stopPropagation()})
.click(function(event){event.stopPropagation()});
_setContent(element || '<div></div>'); //设置内容
options.title !== null && _setupTitleBar(); // 安装标题栏
options.button.length && _setupToolsBar();
options.close && _setupCloseBtn(); // 安装关闭按钮
box.css('display', 'none').appendTo('body'); //放入body
var left = box.find('.box-left');
left.append($('<div/>').css('width', left.width())); //左边添加空DIV防止拖动出浏览器时左边不显示
//隐藏弹出层
this.hide = _hide;
//显示弹出层
this.show = _show;
//如果当前显示则隐藏,如果当前隐藏则显示
this.toggle = function(){visible ? self.hide() : self.show()};
// 获取弹出层内容对象
this.getContent = function(){return $('.ThinkBox-content', box)};
//动态添加内容
this.setContent = function(content){
_setContent(content);
_setLocate(); //设置弹出层显示位置
return self;
};
//动态设置标题
this.setTitle = _setTitle;
//获取内容区域的尺寸
this.getSize = _getSize;
//动态改变弹出层内容区域的大小
this.setSize = function(width, height){
$('.ThinkBox-inner', box).css({'width' : width, 'height' : height});
};
//设置弹出层fixed属性
options.fixed && ($.browser.msie && $.browser.version < 7 ? options.fixed = false : box.css('position', 'fixed'));
_setLocate(); //设置弹出层显示位置
options.resize && _win.resize(function(){_setLocate()});
// 按ESC键关闭弹出层
self.escHide = options.escHide;
//显示弹出层
options.display && _show();
/* 显示弹出层 */
function _show() {
if(visible) return self;
// 安装模态背景
options.modal && _setupModal();
_fire.call(self, options.beforeShow); //调用显示之前回调函数
switch(options.show[0]){
case 'slideDown':
box.stop(true, true).slideDown(options.show[1], _);
break;
case 'fadeIn':
box.stop(true, true).fadeIn(options.show[1], _);
break;
default:
box.show(options.show[1], _);
}
visible = true;
_setCurrent();
return self;
function _(){
options.delayClose && $.isNumeric(options.delayClose) && setTimeout(_hide, options.delayClose);
_fire.call(self, options.afterShow);
}
};
/* 隐藏弹出层 */
function _hide() {
if(!visible) return self;
modal && modal.fadeOut('normal',function(){$(this).remove();modal = null});
switch(options.hide[0]){
case 'slideUp':
box.stop(true, true).slideUp(options.hide[1], _);
break;
case 'fadeOut':
box.stop(true, true).fadeOut(options.hide[1], _);
break;
default:
box.hide(options.hide[1], _);
}
return self;
function _() {
visible = false;
_fire.call(self, options.afterHide); //隐藏后的回调方法
options.unload && _unload();
}
}
/* 安装标题栏 */
function _setupTitleBar() {
var bar = $(titleBar);
var title = $('.ThinkBox-title-inner', bar);
if (options.drag) {
title.addClass('ThinkBox-draging');
title[0].onselectstart = function() {return false}; //禁止选中文字
title[0].unselectable = 'on'; // 禁止获取焦点
title[0].style.MozUserSelect = 'none'; // 禁止火狐选中文字
_drag(title);
}
$('tr', box).first().after(bar);
_setTitle(options.title);
}
/* 设置标题 */
function _setTitle(title){
var titleInner = $('.ThinkBox-title-inner', box).empty();
if($.isArray(title) || $.isPlainObject(title)){
$.each(title, function(i, _title){
$('<span>' + _title + '</span>').data('key', i)
.click(function(event){
var _this = $(this);
if(!_this.hasClass('selected')){
titleInner.find('span.selected').removeClass('selected');
_this.addClass('selected');
_fire.call(_this, options.titleChange);
}
})
.mousedown(function(event){event.stopPropagation()})
.mouseup(function(event){event.stopPropagation()})
.appendTo(titleInner);
});
} else {
titleInner.append('<span>' + title + '</span>');
}
}
/* 安装工具栏 */
function _setupToolsBar() {
var bar = $(toolsBar);
var tools = $('.ThinkBox-tools-inner', bar);
var button = null;
$.each(options.button, function(k, v){
button = $('<span/>').addClass('ThinkBox-button ' + v[0]).html(v[1])
.click(function(){_fire.call(self, v[2])})
.hover(function(){$(this).addClass('hover')}, function(){$(this).removeClass('hover')})
.appendTo(tools);
})
$('tr', box).last().before(bar);
}
/* 安装关闭按钮 */
function _setupCloseBtn(){
$('<span/>').addClass('ThinkBox-close').html(options.close)
.click(function(event){self.hide();event.stopPropagation()})
.mousedown(function(event){event.stopPropagation()})
.appendTo($('.ThinkBox-inner', box));
}
/* 安装模态背景 */
function _setupModal(){
if($.browser.msie){ //解决IE通过 $(documemt).width()获取到的宽度含有滚动条宽度的BUG
_doc.width = function(){return document.documentElement.scrollWidth};
_doc.height = function(){return document.documentElement.scrollHeight};
}
modal = $('<div class="ThinkBox-modal-blackout" style="position:absolute;left:0;top:0"></div>')
.addClass('ThinkBox-modal-blackout-' + options.style)
.css({
'zIndex' : zIndex++,
'width' : _doc.width(),
'height' : _doc.height()
})
.click(function(event){
options.modalClose && current && current.hide();
event.stopPropagation();
})
.mousedown(function(event){event.stopPropagation()})
.appendTo($('body'));
_win.resize(function() {
modal && modal.css({'width' : '', 'height' : ''}).css({'width' : _doc.width(), 'height' : _doc.height()});
});
}
/* 设置弹出层容器中的内容 */
function _setContent(content) {
var content = $('<div/>')
.addClass('ThinkBox-content')
.append((options.clone ? $(content).clone(true, true) : $(content)).show());
$('.ThinkBox-content', box).remove(); // 卸载原容器中的内容
$('.ThinkBox-inner', box)
.css({'width' : options.width, 'height' : options.height}) // 设置弹出层内容的宽和高
.append(content); // 添加新内容
}
/* 设置弹出层初始位置 */
function _setLocate(){
options.center ?
_moveToCenter() :
_moveTo(
$.isNumeric(options.x) ? options.x : ($.isFunction(options.x) ? options.x.call($(options.dataEle)) : 0),
$.isNumeric(options.y) ? options.y : ($.isFunction(options.y) ? options.y.call($(options.dataEle)) : 0)
);
}
/* 拖动弹出层 */
function _drag(title){
var draging = null;
_doc.mousemove(function(event){
draging && box.css({left: event.pageX - draging[0], top: event.pageY - draging[1]});
});
title.mousedown(function(event) {
var offset = box.offset();
if(options.fixed){
offset.left -= _win.scrollLeft();
offset.top -= _win.scrollTop();
}
draging = [event.pageX - offset.left, event.pageY - offset.top];
}).mouseup(function() {
draging = null;
_fire.call(self, options.afterDrag); //拖动后的回调函数
});
}
/* 移动弹出层到屏幕中心 */
function _moveToCenter() {
var s = _getSize(),
v = viewport(),
o = box.css('position') == 'fixed' ? [0, 0] : [v.left, v.top],
x = o[0] + v.width / 2,
y = o[1] + v.height / 2;
_moveTo(x - s[0] / 2, y - s[1] / 2);
}
/* 移动弹出层到指定的坐标 */
function _moveTo(x, y) {
$.isNumeric(x) && (options.locate[0] == 'left' ? box.css({'left' : x}) : box.css({'right' : x}));
$.isNumeric(y) && (options.locate[1] == 'top' ? box.css({'top' : y}) : box.css({'bottom' : y}));
}
/* 获取弹出层的尺寸 */
function _getSize(){
if(visible)
return [box.width(), box.height()];
else {
box.css({'visibility': 'hidden', 'display': 'block'});
var size = [box.width(), box.height()];
box.css('display', 'none').css('visibility', 'visible');
return size;
}
}
/* 卸载弹出层容器 */
function _unload(){
_fire.call(self, options.beforeUnload); //卸载前的回调方法
box.remove();
options.dataEle && $(options.dataEle).removeData('ThinkBox');
}
/* 设置为当前选中的弹出层对象 */
function _setCurrent(){
current = self;
_toTop.call(box);
}
}; //END ThinkBox
/* 调整Z轴到最上层 */
function _toTop(){
this.css({'zIndex': zIndex++});
}
/* 获取屏幕可视区域的大小和位置 */
function viewport(){
return $.extend(
{'width' : _win.width(), 'height' : _win.height()},
{'left' : _win.scrollLeft(), 'top' : _win.scrollTop()}
);
}
/* 调用回调函数 */
function _fire(event){
$.isFunction(event) && event.call(this);
}
/* 删除options中不必要的参数 */
function _delOptions(opt, options){
$.each(opt, function() {
if (this in options) delete options[this];
});
}
_doc.mousedown(function(){current = null})
.keypress(function(event){current && current.escHide && event.keyCode == 27 && current.hide()});
/**
* 创建一个新的弹出层对象
+----------------------------------------------------------
* element 弹出层内容元素
* options 弹出层选项
+----------------------------------------------------------
*/
$.ThinkBox = function(element, options){
if($.isPlainObject(options) && options.dataEle){
var data = $(options.dataEle).data('ThinkBox');
if(data) return options.display === false ? data : data.show();
}
return new ThinkBox(element, options);
}
/**
+----------------------------------------------------------
* 弹出层内置扩展
+----------------------------------------------------------
*/
$.extend($.ThinkBox, {
// 以一个URL加载内容并以ThinBox对话框的形式展现
load : function(url, opt){
var options = {'clone' : false, 'loading' : '加载中...', 'type' : 'GET', 'dataType' : 'text', 'cache' : false, 'parseData':undefined, 'onload': undefined},self;
$.extend(options, opt || {});
var parseData = options.parseData, onload = options.onload, loading = options.loading, url = url.split(/\s+/);
var ajax = {
'data' : options.data,
'type' : options.type,
'dataType': options.dataType,
'cache' : options.cache,
'success' : function(data) {
url[1] && (data = $(data).find(url[1]));
$.isFunction(parseData) && (data = parseData.call(options.dataEle, data));
self.setContent(data); //设置内容并显示弹出层
_fire.call(self, onload); //调用onload回调函数
loading || self.show(); //没有loading状态则直接显示弹出层
}
};
//删除ThinkBox不需要的参数
_delOptions(['data', 'type', 'cache', 'dataType', 'parseData', 'onload', 'loading'], options);
self = loading ? $.ThinkBox('<div class="ThinkBox-load-loading">' + loading + '</div>', options) : $.ThinkBox('<div/>', $.extend({}, options, {'display' : false}));
//if(!self.getContent().children().is('.ThinkBox-load-loading')) return self; //防止发起多次不必要的请求
$.ajax(url[0], ajax);
return self;
},
// 弹出一个iframe
'iframe' : function(url, opt){
var options = {'width' : 500, 'height' : 400, 'scrolling' : 'no', 'onload' : undefined}, self;
$.extend(options, opt || {});
var onload = options.onload;
var iframe = $('<iframe/>').attr({'width' : options.width, 'height' : options.height, 'frameborder' : 0, 'scrolling' : options.scrolling, 'src' : url})
.load(function(){_fire.call(self, onload)});
_delOptions(['width', 'height', 'scrolling', 'onload'], options);//删除不必要的信息
self = $.ThinkBox(iframe, options);
return self;
},
// 提示框 可以配合ThinkPHP的ajaxReturn
'tips' : function(msg, type, opt){
switch(type){
case 0: type = 'error'; break;
case 1: type = 'success'; break;
}
var html = '<div class="ThinkBox-tips ThinkBox-' + type + '">' + msg + '</div>';
var options = {'modalClose' : false, 'escHide' : false, 'unload' : true, 'close' : false, 'delayClose' : 1000};
$.extend(options, opt || {});
return $.ThinkBox(html, options);
},
// 成功提示框
'success' : function(msg, opt){
return this.tips(msg, 'success', opt);
},
// 错误提示框
'error' : function(msg, opt){
return this.tips(msg, 'error', opt);
},
// 数据加载
'loading' : function(msg, opt){
var options = opt || {};
options.delayClose = 0;
return this.tips(msg, 'loading', options);
},
//消息框
'msg' : function(msg, opt){
var options = {
'drag' : false, 'escHide' : false, 'delayClose' : 0, 'center':false, 'title' : '消息',
'x' : 0, 'y' : 0, 'locate' : ['right', 'bottom'], 'show' : ['slideDown', 'slow'], 'hide' : ['slideUp', 'slow']
};
$.extend(options, opt || {});
var html = $('<div/>').addClass('ThinkBox-msg').html(msg);
return $.ThinkBox(html, options);
},
//提示框
'alert' : function(msg, opt) {
var options = {'title' : '提示', 'modal' : false, 'modalClose' : false, 'unload' : false},
button = ['ok', '确定', undefined];
$.extend(options, opt || {});
(typeof options.okVal != 'undefined') && (button[1] = options.okVal);
$.isFunction(options.ok) && (button[2] = options.ok);
//删除ThinkBox不需要的参数
_delOptions(['okVal', 'ok'], options);
if( typeof options.button == 'undefined' )
options.button = [button];
var html = $('<div/>').addClass('ThinkBox-alert').html(msg);
return $.ThinkBox(html, options);
},
//确认框
'confirm' : function(msg, opt){
var options = {'title' : '确认', 'modal' : false, 'modalClose' : false},
button = [['ok', '确定', undefined],['cancel', '取消', undefined]];
$.extend(options, opt || {});
(typeof options.okVal != 'undefined') && (button[0][1] = options.okVal);
(typeof options.cancelVal != 'undefined') && (button[1][1] = options.cancelVal);
$.isFunction(options.ok) && (button[0][2] = options.ok);
$.isFunction(options.cancel) && (button[1][2] = options.cancel);
//删除ThinkBox不需要的参数
_delOptions(['okVal', 'ok', 'cancelVal', 'cancel'], options);
options.button = button;
var html = $('<div/>').addClass('ThinkBox-confirm').html(msg);
return $.ThinkBox(html, options);
},
//弹出层内部获取弹出层对象
'get' : function(selector){
return $(selector).closest('.ThinkBox-wrapper').data('ThinkBox');
}
});
$.fn.ThinkBox = function(opt){
if(opt == 'get') return $(this).data('ThinkBox');
return this.each(function(){
var self = $(this);
var box = self.data('ThinkBox');
switch(opt){
case 'show':
box && box.show();
break;
case 'hide':
box && box.hide();
break;
case 'toggle':
box && box.toggle();
break;
default:
var options = {'title' : self.attr('title'), 'dataEle' : this, 'fixed' : false, 'center': false, 'modal' : false, 'drag' : false};
opt = $.isPlainObject(opt) ? opt : {};
$.extend(options, {
'x' : function(){return $(this).offset().left},
'y' : function(){return $(this).offset().top + $(this).outerHeight()}
}, opt);
if(options.event){
var event = options.event;
delete options.event;
if(event == 'hover'){
var outClose = options.boxOutClose || false, delayShow = options.delayShow || 0, timeout1 = null, timeout2 = null;
_delOptions(['boxOutClose', 'delayShow'], options);
options.mouseover = function(){if(timeout2){clearTimeout(timeout2);timeout2 = null}};
options.mouseout = function(){this.hide()};
self.hover(
function(){timeout1 = timeout1 || setTimeout(function(){_.call(self, options)}, delayShow)},
function(){
if(timeout1){clearTimeout(timeout1); timeout1 = null}
outClose ? timeout2 = timeout2 || setTimeout(function(){timeout2 = null; self.ThinkBox('hide')}, 50) : self.ThinkBox('hide');
}
);
} else {
self.bind(event, function(){
_.call(self, options);
return false;
});
}
} else {
_.call(self, options);
}
}
});
function _(options){
var href = this.attr('think-href') || this.attr('href');
if(href.substr(0, 1) == '#'){
$.ThinkBox(href, options);
} else if(href.substr(0, 7) == 'http://' || href.substr(0, 8) == 'https://'){
$.ThinkBox.iframe(href, options);
} else {
$.ThinkBox.load(href, options);
}
}
}
})(jQuery);
|
import querystring from 'querystring';
import httpStatus from 'http-status';
function makeError (code, message) {
var err = new Error(message || httpStatus[code]);
err.statusCode = code;
return err;
}
export default function (passport, activeServices, token, callbackURLs) {
return {
socialAuth: function (req, res, next) {
var provider = req.params.provider;
if (!activeServices[provider]) {
return next();
}
passport.authenticate(provider, {scope: activeServices[provider].scope})(req, res, next);
},
socialAuthCallback: function (req, res, next) {
var provider = req.params.provider;
if (!activeServices[provider]) {
return next();
}
passport.authenticate(provider, function (err, user) {
if (err) {
return next(makeError(httpStatus.INTERNAL_SERVER_ERROR, err.message));
}
if (!user) {
return res.redirect(callbackURLs.failure);
}
token.generate(user, function (err, result) {
if (err) {
return next(makeError(httpStatus.INTERNAL_SERVER_ERROR, err.message));
}
res.redirect(callbackURLs.success + '?' + querystring.stringify({token: JSON.stringify(result)}));
});
})(req, res, next);
}
};
}
|
import {
difference,
every,
find,
get,
isEqual,
keyBy,
keys,
map,
mapValues,
pick,
sum,
} from "lodash/fp";
import { markSampleUploaded, uploadFileToUrlWithRetries } from "~/api";
import { logAnalyticsEvent } from "~/api/analytics";
import { postWithCSRF } from "./core";
export const MAX_MARK_SAMPLE_RETRIES = 10;
export const exponentialDelayWithJitter = tryCount => {
// ~13 sec, ~46 sec, ~158 sec, ... -> ~115 minutes.
// Derived via eyeballing. Adjust based on user feedback.
const delay = ((tryCount + Math.random()) * 10) ** 3.5 + 10000;
return new Promise(resolve => setTimeout(resolve, delay));
};
export const bulkUploadBasespace = ({ samples, metadata }) =>
bulkUploadWithMetadata(samples, metadata);
export const bulkUploadRemote = ({ samples, metadata }) =>
bulkUploadWithMetadata(samples, metadata);
export const initiateBulkUploadLocalWithMetadata = async ({
samples,
metadata,
callbacks = {
onCreateSamplesError: null,
},
}) => {
// Only upload these fields from the sample.
const processedSamples = map(
pick([
"alignment_config_name",
"alignment_scalability",
"clearlabs",
"client",
"dag_vars",
"do_not_process",
"host_genome_id",
"input_files_attributes",
"max_input_fragments",
"medaka_model",
"name",
"pipeline_branch",
"pipeline_execution_strategy",
"project_id",
"s3_preload_result_path",
"subsample",
"technology",
"wetlab_protocol",
"workflows",
]),
samples
);
// Process extra options
processedSamples.forEach(processedSample => {
if (
"alignment_scalability" in processedSample &&
processedSample["alignment_scalability"] === "true"
) {
processedSample["dag_vars"] = JSON.stringify({
NonHostAlignment: { alignment_scalability: true },
});
}
});
let response;
try {
// Creates the Sample objects and assigns a presigned S3 URL so we can upload the sample files to S3 via the URL
response = await bulkUploadWithMetadata(processedSamples, metadata);
} catch (e) {
callbacks.onCreateSamplesError &&
callbacks.onCreateSamplesError([e], map("name", samples));
return;
}
// It's possible that a subset of samples errored out, but other ones can still be uploaded.
if (response.errors.length > 0) {
callbacks.onCreateSamplesError &&
callbacks.onCreateSamplesError(
response.errors,
response.errored_sample_names
);
}
// The samples created from the network response (response.samples) does not contain the files that need to be upload to S3.
// They contain information pertaining to the sample itself (metadata) as well as presigned S3 URL links
// The sample files that need to be uploaded to S3 are in the samples argument passed into initiateBulkUploadLocalWithMetadata
// So we need to fetch the files from samples argument and copy them over to response.samples where they're later uploaded to S3 via uploadSampleFilesToPresignedURL
response.samples.forEach(
createdSample =>
(createdSample["filesToUpload"] = get(
"files",
find({ name: createdSample.name }, samples)
))
);
return response.samples;
};
export const uploadSampleFilesToPresignedURL = ({
samples,
callbacks = {
onSampleUploadProgress: null,
onSampleUploadError: null,
onSampleUploadSuccess: null,
onMarkSampleUploadedError: null,
},
}) => {
// Store the upload progress of file names, so we can track when
// everything is done.
const fileNamesToProgress = {};
const markedUploaded = {};
const sampleNamesToFiles = mapValues("filesToUpload", keyBy("name", samples));
// This function needs access to fileNamesToProgress.
const onFileUploadSuccess = async (sample, sampleId) => {
const sampleFiles = sampleNamesToFiles[sample.name];
// If every file for this sample is uploaded, mark it as uploaded.
if (
!markedUploaded[sample.name] &&
every(file => fileNamesToProgress[file.name] === 1, sampleFiles)
) {
markedUploaded[sample.name] = true;
let tryCount = 0;
while (true) {
try {
await markSampleUploaded(sampleId);
callbacks.onSampleUploadSuccess &&
callbacks.onSampleUploadSuccess(sample);
break;
} catch (_) {
tryCount++;
if (tryCount === MAX_MARK_SAMPLE_RETRIES) {
callbacks.onMarkSampleUploadedError &&
callbacks.onMarkSampleUploadedError(sample);
break;
}
await exponentialDelayWithJitter(tryCount);
}
}
}
};
// Calculate the current sample upload percentage.
const getSampleUploadPercentage = sample => {
const sampleFiles = sample.input_files.map(inputFileAttributes => {
return sampleNamesToFiles[sample.name][inputFileAttributes.name];
});
const sampleFileUploadProgress = map(
file => ({
percentage: fileNamesToProgress[file.name] || null,
size: file.size,
}),
sampleFiles
);
const uploadedSize = sum(
map(
progress => (progress.percentage || 0) * progress.size,
sampleFileUploadProgress
)
);
const totalSize = sum(
map(progress => progress.size, sampleFileUploadProgress)
);
return uploadedSize / totalSize;
};
const heartbeatInterval = startUploadHeartbeat(map("id", samples));
// Need to keep track of "finalized file names" to indicate when the batch is complete.
const finalizedFileNames = {};
const onFileNameFinalized = fileName => {
finalizedFileNames[fileName] = true;
if (
isEqual(keys(finalizedFileNames).sort(), keys(fileNamesToProgress).sort())
) {
clearInterval(heartbeatInterval);
logAnalyticsEvent("Uploads_batch-heartbeat_completed", {
sampleIds: map("id", samples),
});
}
};
samples.forEach(sample => {
const files = sampleNamesToFiles[sample.name];
sample.input_files.map(inputFileAttributes => {
const file = files[inputFileAttributes.name];
const url = inputFileAttributes.presigned_url;
uploadFileToUrlWithRetries(file, url, {
onUploadProgress: e => {
const percent = e.loaded / e.total;
fileNamesToProgress[file.name] = percent;
if (callbacks.onSampleUploadProgress) {
const uploadedPercentage = getSampleUploadPercentage(sample);
callbacks.onSampleUploadProgress(sample, uploadedPercentage);
}
},
onSuccess: () => {
fileNamesToProgress[file.name] = 1;
onFileNameFinalized(file.name);
onFileUploadSuccess(sample, sample.id);
},
onError: error => {
fileNamesToProgress[file.name] = 0;
onFileNameFinalized(file.name);
callbacks.onSampleUploadError &&
callbacks.onSampleUploadError(sample, error);
},
});
});
});
};
// Bulk-upload samples (both local and remote), with metadata.
const bulkUploadWithMetadata = async (samples, metadata) => {
const response = await postWithCSRF(
`/samples/bulk_upload_with_metadata.json`,
{
samples,
metadata,
client: "web",
}
);
// Add the errored sample names to the response.
if (response.errors.length > 0) {
const erroredSampleNames = difference(
map("name", samples),
map("name", response.samples)
);
return {
...response,
errored_sample_names: erroredSampleNames,
};
}
return response;
};
// Local uploads go directly from the browser to S3, so we don't know if an upload was interrupted.
// Ping a heartbeat periodically to say the browser is actively uploading the samples.
export const startUploadHeartbeat = async sampleIds => {
const sendHeartbeat = () =>
logAnalyticsEvent("Uploads_batch-heartbeat_sent", { sampleIds });
sendHeartbeat(); // Send first heartbeat immediately so we know it is working
const minutes = 10; // Picked arbitrarily, adjust as needed.
const milliseconds = minutes * 60 * 10000;
return setInterval(sendHeartbeat, milliseconds);
};
|
'use strict';
/* global it */
/* global describe */
var expect = require('chai').expect;
//FIND A BETTER TEST DATA
var fakeSchema = {
number : {type : Number},
date : {type : Date},
hash : {type : String},
};
var fakeData = [
{ number : 11, date : new Date('2001-12-21'), hash : 'Hash'}
];
var mongooseSchema = { schema : { tree : fakeSchema}};
describe('The mongoose schema plugin', function(){
var mongooseExporter = require('../lib/mongoose_schema');
var exclude = [ 'hash', 'salt' ];
it('gets the column row, excluding unneccessary columns', function(){
var res = mongooseExporter.columns(mongooseSchema, exclude);
res.forEach(function(excluded){
expect(exclude.indexOf(excluded.name)).to.equal(-1);
});
});
it('gets column name and formatters for basic field types', function(){
var res = mongooseExporter.columns(mongooseSchema, exclude);
expect(res.length).to.equal(2);
expect(res[0].name).to.equal('number');
expect(res[1].name).to.equal('date');
});
it('does not complain if the type is defined in an object or not', function(){
var fakeSchema2 = {
number : Number,
date : Date,
hash : String,
};
var mongooseSchema2 = { schema : { tree : fakeSchema2}};
var res = mongooseExporter.columns(mongooseSchema2, exclude);
res.forEach(function(excluded){
expect(exclude.indexOf(excluded.name)).to.equal(-1);
});
});
});
describe('The row generator', function(){
var csvResponse = require('../index.js');
var userCsvResponse = csvResponse(mongooseSchema, 'mongoose');
it('generates the first row', function(){
var cols = userCsvResponse(fakeData)[0];
expect(cols).to.deep.equal(['number', 'date', 'hash']);
});
it('correctly applies formatters', function(){
var row = userCsvResponse(fakeData)[1];
expect(row).to.deep.equal(['11', '2001-12-21T00:00:00.000Z', 'Hash']);
});
it('handles null/undefined fields returning an empty string', function(){
var fakeSchema = {
'undefined' : {type : Number},
'null' : {type : Date},
'false' : {type : Boolean},
'emptystring' : { type : String},
'negative' : { type : Number}
};
var fakeData = [
{'undefined' : undefined, 'null' : null, 'false' : false, emptystring: '', negative : -1}
];
var mongooseSchema = { schema : { tree : fakeSchema}};
var userCsvResponse = csvResponse(mongooseSchema, 'mongoose');
var row = userCsvResponse(fakeData)[1];
expect(row).to.deep.equal(['', '', 'false','', '-1']);
});
/* by simple array I mean NO nested schemas */
/* simple arrays containing complex objects should be suppressed via exclude, or a formatter
* should be provided
* */
it('handles simple arrays', function(){
var fakeSchema = {
'array' : Array,
};
var fakeData = [
{'array' : ['pizza', 'mafia', 'mandolino', 'disagio'] }
];
var mongooseSchema = { schema : { tree : fakeSchema}};
var userCsvResponse = csvResponse(mongooseSchema, 'mongoose');
var row = userCsvResponse(fakeData)[1];
expect(row).to.deep.equal(['pizza,mafia,mandolino,disagio']);
});
function ObjectId(str){
this.str = str;
this.toHexString = function(){ return this.str; };
}
it('handles ObjectIDs', function(){
var fakeSchema = {
'_id' : ObjectId,
};
var fakeData = [
{'_id' : new ObjectId('552547c574ab294654d06c9a') }
];
var mongooseSchema = { schema : { tree : fakeSchema}};
var userCsvResponse = csvResponse(mongooseSchema, 'mongoose');
var row = userCsvResponse(fakeData)[1];
expect(row).to.deep.equal(['552547c574ab294654d06c9a']);
});
it('flattens objects', function(){
var fakeSchema = {
'prop' : {
'subprop' : String,
'what' : { 'hey' : Number }
}
};
var fakeData = [
{'prop' : {
'subprop' : 'gorgonzola',
'what' : { 'hey' : 666 }
}
}
];
var mongooseSchema = { schema : { tree : fakeSchema}};
var userCsvResponse = csvResponse(mongooseSchema, 'mongoose');
var result = userCsvResponse(fakeData);
expect(result).to.deep.equal([ [ 'prop.subprop', 'prop.what.hey' ], [ 'gorgonzola', '666' ] ]);
});
});
|
import pad from 'lodash/padStart';
import get from 'lodash/get';
import { crossComponentTranslator, createTranslator, formatList } from 'kolibri.utils.i18n';
import PageStatus from 'kolibri.coreVue.components.PageStatus';
import coreStringsMixin from 'kolibri.coreVue.mixins.commonCoreStrings';
import { STATUSES } from '../modules/classSummary/constants';
import { VERBS } from '../views/common/status/constants';
import { translations } from '../views/common/status/statusStrings';
import { coachStrings } from '../views/common/commonCoachStrings';
const FieldsMixinStrings = createTranslator('FieldsMixinStrings', {
allLearners: 'All learners',
recipientType: {
message: 'Assigned to',
context: 'Column header for the quiz report exported as CSV',
},
groupsAndIndividuals: {
message: 'Both individual learners and groups',
context:
'One of the options in the quiz report exported as CSV indicating that a quiz or a lesson has been assigned to both individual learners and groups.',
},
wholeClass: 'Whole class',
questionsCorrect: {
message: 'Questions answered correctly',
context: 'Column header for the quiz report exported as CSV',
},
questionsTotal: 'Total questions',
questionsAnswered: 'Answered questions',
});
const VERB_MAP = {
[STATUSES.notStarted]: VERBS.notStarted,
[STATUSES.started]: VERBS.started,
[STATUSES.helpNeeded]: VERBS.needHelp,
[STATUSES.completed]: VERBS.completed,
};
const coreStrings = coreStringsMixin.methods.coreString;
const examStrings = crossComponentTranslator(PageStatus);
/*
* Common CSV export fields and formats
*/
/**
* @param {String|Number} interval
* @return {string}
*/
function padTime(interval) {
return pad(interval, 2, '0');
}
export function avgScore(quiz = false) {
return [
{
name: coachStrings.$tr(quiz ? 'avgQuizScoreLabel' : 'avgScoreLabel'),
key: 'avgScore',
format(row) {
if (!row.avgScore && row.avgScore !== 0) {
return '';
}
return coachStrings.$tr('percentage', { value: row.avgScore });
},
},
];
}
export function helpNeeded() {
return [
{
name: coachStrings.$tr('helpNeededLabel'),
key: 'helpNeeded',
format: row => row.total - row.correct,
},
{
name: FieldsMixinStrings.$tr('allLearners'),
key: 'all',
format: row => row.total,
},
];
}
export function lastActivity() {
return [
{
name: coachStrings.$tr('lastActivityLabel'),
key: 'lastActivity',
format(row) {
if (!row[this.key]) {
return '';
}
return row[this.key].toISOString();
},
},
];
}
export function learnerProgress(key = 'status') {
return [
{
name: coreStrings('progressLabel'),
key,
format(row) {
const value = get(row, key);
const strings = translations.learnerProgress[VERB_MAP[value]];
return strings.$tr('labelShort', { count: 1 });
},
},
];
}
export function list(key, label) {
return [
{
name: coachStrings.$tr(label),
key,
format(row) {
const value = get(row, key);
if (value && value.length) {
return formatList(value);
}
return '';
},
},
];
}
export function name(label = 'nameLabel') {
return [
{
name: coachStrings.$tr(label),
key: 'name',
},
];
}
export function recipients(className) {
return [
{
name: FieldsMixinStrings.$tr('recipientType'),
key: 'recipientType',
format(row) {
const { recipientNames = [] } = row;
if (recipientNames.length === 0 && row.hasAssignments) {
return FieldsMixinStrings.$tr('wholeClass');
} else {
const numGroups = get(row, 'groupNames.length', -1);
// If there are more recipients than groups, then there must be some individual learners
return recipientNames.length > numGroups
? FieldsMixinStrings.$tr('groupsAndIndividuals') // At least one individual recipient
: coachStrings.$tr('groupsLabel'); // Groups only
}
},
},
{
name: coachStrings.$tr('recipientsLabel'),
key: 'groupNames',
format(row) {
const { recipientNames = [] } = row;
if (recipientNames.length === 0 && row.hasAssignments) {
return className || FieldsMixinStrings.$tr('wholeClass');
} else {
return formatList(recipientNames);
}
},
},
];
}
export function score() {
return [
{
name: coachStrings.$tr('scoreLabel'),
key: 'score',
format: row => {
if (!row.statusObj.score && row.statusObj.score !== 0) {
return '';
}
return coachStrings.$tr('percentage', { value: row.statusObj.score });
},
},
];
}
export function tally() {
return [
{
name: examStrings.$tr('notStartedLabel'),
key: 'tally.notStarted',
},
{
name: coachStrings.$tr('startedLabel'),
key: 'tally.started',
},
{
name: coreStrings('completedLabel'),
key: 'tally.completed',
},
{
name: coachStrings.$tr('helpNeededLabel'),
key: 'tally.helpNeeded',
},
];
}
export function timeSpent(key, label = 'timeSpentLabel') {
return [
{
name: coachStrings.$tr(label),
key,
format(row) {
const value = get(row, key);
const timeSpent = parseInt(value, 10);
if (!timeSpent) {
return '';
}
const hours = Math.floor(timeSpent / 3600);
const minutes = Math.floor((timeSpent - hours * 3600) / 60);
const seconds = timeSpent - hours * 3600 - minutes * 60;
return `${padTime(hours)}:${padTime(minutes)}:${padTime(seconds)}`;
},
},
];
}
export function title() {
return [
{
name: coachStrings.$tr('titleLabel'),
key: 'title',
},
];
}
export function quizQuestionsAnswered(quiz) {
return [
{
name: FieldsMixinStrings.$tr('questionsAnswered'),
key: 'quizQuestionsAnswered',
format(row) {
return get(row, 'statusObj.num_answered');
},
},
{
name: FieldsMixinStrings.$tr('questionsCorrect'),
key: 'quizQuestionsAnswered',
format(row) {
return get(row, 'statusObj.num_correct');
},
},
{
name: FieldsMixinStrings.$tr('questionsTotal'),
key: 'quizQuestionsTotal',
format() {
return quiz.question_count;
},
},
];
}
|
var cordova = require('cordova'),
ThermalCordova= require('./ThermalCordova');
module.exports = {
ToUpper: function (successCallback, errorCallback, strInput) {
var upperCase = strInput[0].toUpperCase();
if(upperCase != "") {
successCallback(upperCase);
}
else {
errorCallback(upperCase);
}
}
};
require("cordova/exec/proxy").add("ThermalCordova", module.exports);
|
#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var semver = require('semver')
var proc = require('child_process')
var pick = require('object.pick')
var extend = require('xtend/mutable')
var deepEqual = require('deep-equal')
var find = require('findit')
var minimist = require('minimist')
var parallel = require('run-parallel')
var allShims = require('./shims')
var coreList = require('./coreList')
var browser = require('./browser')
var pkgPath = path.join(process.cwd(), 'package.json')
var pkg = require(pkgPath)
var hackFiles = require('./pkg-hacks')
var argv = minimist(process.argv.slice(2), {
alias: {
i: 'install',
e: 'hack',
h: 'help'
}
})
if (argv.help) {
runHelp()
process.exit(0)
} else {
run()
}
function run () {
var toShim
if (argv.install) {
if (argv.install === true) {
toShim = coreList
} else {
toShim = argv.install.split(',')
.map(function (name) {
return name.trim()
})
}
} else {
toShim = coreList
}
if (toShim.indexOf('stream') !== -1) {
toShim.push(
'_stream_transform',
'_stream_readable',
'_stream_writable',
'_stream_duplex',
'_stream_passthrough',
'readable-stream'
)
}
if (toShim.indexOf('crypto') !== -1) {
toShim.push('react-native-randombytes')
}
if (argv.install) {
installShims(toShim, function (err) {
if (err) throw err
runHacks()
})
} else {
runHacks()
}
function runHacks () {
hackPackageJSONs(toShim, function (err) {
if (err) throw err
if (argv.hack) {
if (argv.hack === true) hackFiles()
else hackFiles([].concat(argv.hack))
}
})
}
}
function installShims (modulesToShim, done) {
var shimPkgNames = modulesToShim.map(function (m) {
return browser[m] || m
}).filter(function (shim) {
return !/^_/.test(shim) && shim.indexOf('/') === -1
})
var existence = []
parallel(shimPkgNames.map(function (name) {
var modPath = path.resolve('./node_modules/' + name)
return function (cb) {
fs.exists(modPath, function (exists) {
if (!exists) return cb()
var install = true
var pkgJson = require(modPath + '/package.json')
if (/^git\:\/\//.test(pkgJson._resolved)) {
var hash = allShims[name].split('#')[1]
if (hash && pkgJson.gitHead.indexOf(hash) === 0) {
install = false
}
} else {
var existingVer = pkgJson.version
if (semver.satisfies(existingVer, allShims[name])) {
install = false
}
}
if (!install) {
console.log('not reinstalling ' + name)
shimPkgNames.splice(shimPkgNames.indexOf(name), 1)
}
cb()
})
}
}), function (err) {
if (err) throw err
if (!shimPkgNames.length) {
return finish()
}
var installLine = 'npm install --save '
shimPkgNames.forEach(function (name) {
if (allShims[name].indexOf('/') === -1) {
console.log('installing from npm', name)
installLine += name + '@' + allShims[name]
} else {
// github url
console.log('installing from github', name)
installLine += allShims[name].match(/([^\/]+\/[^\/]+)$/)[1]
}
pkg.dependencies[name] = allShims[name]
installLine += ' '
})
fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), function (err) {
if (err) throw err
proc.execSync(installLine, {
cwd: process.cwd(),
env: process.env,
stdio: 'inherit'
})
finish()
})
console.log('installing:', installLine)
function finish () {
copyShim(done)
}
})
}
function copyShim (cb) {
fs.exists('./shim.js', function (exists) {
if (exists) return cb()
fs.readFile(path.join(__dirname, 'shim.js'), { encoding: 'utf8' }, function (err, contents) {
if (err) return cb(err)
fs.writeFile('./shim.js', contents, cb)
})
})
}
function hackPackageJSONs (modules, done) {
fixPackageJSON(modules, './package.json', true)
var finder = find('./node_modules')
finder.on('file', function (file) {
if (path.basename(file) !== 'package.json') return
fixPackageJSON(modules, file, true)
})
finder.once('end', done)
}
function fixPackageJSON (modules, file, overwrite) {
if (file.split(path.sep).indexOf('react-native') >= 0) return
fs.readFile(path.resolve(file), { encoding: 'utf8' }, function (err, contents) {
if (err) throw err
// var browser = pick(baseBrowser, modules)
var pkgJson
try {
pkgJson = JSON.parse(contents)
} catch (err) {
console.warn('failed to parse', file)
return
}
// if (shims[pkgJson.name]) {
// console.log('skipping', pkgJson.name)
// return
// }
// if (pkgJson.name === 'readable-stream') debugger
var orgBrowser = pkgJson['react-native'] || pkgJson.browser || pkgJson.browserify || {}
if (typeof orgBrowser === 'string') {
orgBrowser = {}
orgBrowser[pkgJson.main || 'index.js'] = pkgJson['react-native'] || pkgJson.browser || pkgJson.browserify
}
var depBrowser = extend({}, orgBrowser)
for (var p in browser) {
if (modules.indexOf(p) === -1) continue
if (!(p in orgBrowser)) {
depBrowser[p] = browser[p]
} else {
if (!overwrite && orgBrowser[p] !== browser[p]) {
console.log('not overwriting mapping', p, orgBrowser[p])
} else {
depBrowser[p] = browser[p]
}
}
}
modules.forEach(function (p) {
if (depBrowser[p] === false) {
console.log('removing browser exclude', file, p)
delete depBrowser[p]
}
})
if (!deepEqual(orgBrowser, depBrowser)) {
pkgJson.browser = pkgJson['react-native'] = depBrowser
delete pkgJson.browserify
fs.writeFile(file, JSON.stringify(pkgJson, null, 2), rethrow)
}
})
}
function rethrow (err) {
if (err) throw err
}
function runHelp () {
console.log(function () {
/*
Usage:
rn-nodeify --install dns,stream,http,https
rn-nodeify --install # installs all core shims
rn-nodeify --hack # run all package-specific hacks
rn-nodeify --hack rusha,fssync # run some package-specific hacks
Options:
-h --help show usage
-e, --hack run package-specific hacks (list or leave blank to run all)
-i, --install install shims (list or leave blank to install all)
Please report bugs! https://github.com/mvayngrib/rn-nodeify/issues
*/
}.toString().split(/\n/).slice(2, -2).join('\n'))
process.exit(0)
}
|
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import { Provider } from 'react-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
injectTapEventPlugin();
import store from './store';
import App from './containers/AppContainer';
import Home from './components/Home';
import Details from './components/Details';
import './styles/css/index.css';
render(
<MuiThemeProvider>
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="/details/:leagueID" component={Details}/>
</Route>
</Router>
</Provider>
</MuiThemeProvider>,
document.getElementById('root')
);
|
const chai = require('chai');
const lab = require('lab').script();
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const proxy = require('proxyquire');
const expect = chai.expect;
chai.use(sinonChai);
exports.lab = lab;
lab.describe('Membership transport model', () => {
const sandbox = sinon.sandbox.create();
const transport = {
delete: sandbox.stub(),
post: sandbox.stub(),
};
const transportFactory = sandbox.stub().returns(transport);
const fn = proxy('../../../web/lib/models/membership.js', {
'../transports/http': transportFactory,
});
lab.afterEach(done => {
sandbox.reset();
done();
});
lab.describe('DELETE', () => {
lab.afterEach(done => {
sandbox.reset();
done();
});
lab.test('it should proxy the DELETE call', async () => {
transport.delete.resolves([]);
await fn.delete('1', { soft: true });
expect(transportFactory).to.have.been.calledWith({
baseUrl: 'http://clubs:3000/',
json: true,
});
expect(transport.delete).to.have.been.calledWith('members/1', {
body: { soft: true },
});
});
});
lab.describe('POST', () => {
lab.afterEach(done => {
sandbox.reset();
done();
});
lab.test('it should proxy the POST call', async () => {
transport.post.resolves([]);
await fn.create('u1', 'd1', 'mentor');
expect(transport.post).to.have.been.calledWith('clubs/d1/members', {
body: {
userId: 'u1',
userType: 'mentor',
},
});
});
});
});
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
import {Grid, Row} from 'react-bootstrap';
function Footer() {
return (
<div className={s.footer}>
<Grid bsStyle>
<Row>
© 2012-2016 Impulset
</Row>
</Grid>
</div>
);
}
export default withStyles(s)(Footer);
|
const localizedLanguageMap = {
de: 'Deutsch',
'de-DE': 'Deutsch',
'en-US': 'English',
'en-AU': 'English (Australia)',
es: 'Español',
'es-ES': 'Español (España)',
fr: 'Français',
'fr-FR': 'Français',
it: 'Italiano',
'it-IT': 'Italiano',
ja: '日本語',
'ja-JP': '日本語',
ko: '한국어',
'ko-KR': '한국어',
nl: 'Nederlands',
'nl-NL': 'Nederlands',
pl: 'Polski',
'pl-PL': 'Polski',
pt: 'Português',
'pt-BR': 'Português',
ru: 'Русский',
'ru-RU': 'Русский',
th: 'ไทย',
'th-TH': 'ไทย',
tr: 'Türkçe',
'tr-TR': 'Türkçe',
};
export default localizedLanguageMap;
|
'use strict'
const Container = require('../../').Container
module.exports = function () {
// Example of using a post-constructor to resolve a cyclic dependency
class A {
static constitute () { return [ Container ] }
constructor (container) {
// Assigning b in a post-constructor allows both objects to be constructed
// first, resolving the cyclic dependency.
//
// Note that the post-constructor still runs synchronously, before this
// object is returned to any third-party consumers.
container.schedulePostConstructor(function (b) {
this.b = b
}, [ B ])
}
}
class B {
static constitute () { return [ A ] }
constructor (a) {
this.a = a
}
}
return { A, B }
}
|
var gulp = require('gulp'),
rename = require('gulp-rename'),
cleanCSS = require('gulp-clean-css'),
autoprefixer = require('gulp-autoprefixer'),
uglify = require('gulp-uglify'),
sass = require('gulp-sass'),
watch = require('gulp-watch'),
imagemin = require('gulp-imagemin'),
sourcemaps = require('gulp-sourcemaps');
var paths = {
styles: 'assets/scss/main.css',
scripts: 'assets/js/**/*.js',
images: 'assets/images/**/*'
};
//scss to css, minify styles
gulp.task('styles', function() {
return gulp.src(paths.styles)
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.init())
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 9', 'opera 12.1'))
.pipe(cleanCSS())
.pipe(sourcemaps.write())
.pipe(rename('../styles/style.min.css'))
.pipe(gulp.dest('build/styles'));
});
//js minify
gulp.task('scripts', function () {
return gulp.src(paths.scripts)
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(rename({suffix: '.min'}))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build/js'));
});
//optimize images
gulp.task('images', function() {
return gulp.src(paths.images)
.pipe(imagemin({optimizationLevel: 5}))
.pipe(gulp.dest('build/images'));
});
// Rerun the task when a file changes
gulp.task('watch', function() {
gulp.watch(paths.scripts, ['scripts']);
gulp.watch('assets/scss/**', ['styles']);
gulp.watch('assets/images/**', ['images']);
});
// The default task (called when you run `gulp` from cli)
gulp.task('default', ['watch', 'scripts', 'images', 'styles']);
|
import { Iterable } from 'immutable'
export default function isImmutable(value) {
return (Iterable.isIterable(value) || (!!value && !!value['@@data']))
}
|
var fs = require('fs');
fs.stat('input.text',function (err, stats) {
if(err){
console.log("Error:"+err);
}
console.log(stats);
console.log(stats.isFile()); //是否为文件
console.log(stats.isDirectory()); // 是否为目录
console.log(stats.isBlockDevice()); //是否为块设备
console.log(stats.isCharacterDevice()); //是否为字符设备
console.log(stats.isSymbolicLink()); //是否为软连接
console.log(stats.isFIFO()); //是否为FIFO,FIFO是UNIX中的一种特殊类型的命令管道。
console.log(stats.isSocket()); //是否为socket
})
|
'use strict';
describe('lib/formatters', sandbox(function () {
var formatters = require('../../lib/formatters');
describe('.camelcase(string)', function () {
it('camel-cases underscore-delimited strings', function () {
formatters.camelcase('my_file_name')
.should.equal('myFileName');
});
it('uppercases first character if prefixed with an underscore', function () {
formatters.camelcase('_my_file_name')
.should.equal('MyFileName');
});
it('camel-cases hyphen-delimited strings', function () {
formatters.camelcase('my-file-name')
.should.equal('myFileName');
});
it('uppercases first character if prefixed with a hyphen', function () {
formatters.camelcase('-my-file-name')
.should.equal('MyFileName');
});
it('doesn\'t interpret special characters as separators', function () {
formatters.camelcase('!my@file&name%with/special=characters')
.should.equal('!my@file&name%with/special=characters');
});
it('doesn\'t interpret numbers as separators', function () {
formatters.camelcase('1my2file3name4with5numbers')
.should.equal('1my2file3name4with5numbers');
});
it('doesn\'t format file extensions', function () {
formatters.camelcase('my.filename')
.should.equal('my');
});
});
describe('.underscore(string)', function () {
it('replaces hyphens with underscores', function () {
formatters.underscore('my-file-name')
.should.equal('my_file_name');
});
it('replaces whitespace with underscores', function () {
formatters.underscore('my file name')
.should.equal('my_file_name');
});
it('doesn\'t format file extensions', function () {
formatters.underscore('my.filename')
.should.equal('my');
});
});
}));
|
(function() {
"use strict";
function Board(placements) {
if (placements) {
this.placements = placements;
} else {
this.clear();
}
this.scores = [0, 0];
}
Board.size = 4;
Board.sizeCubed = 64;
Board.prototype.setPlacements = function(placements) {
var newPieces = false;
for (var i = 0; i < Board.sizeCubed; i++) {
if (placements[i] && this.placements[i] != placements[i]) {
newPieces = true;
}
this.placements[i] = placements[i];
}
return newPieces;
}
Board.prototype.clear = function() {
this.placements = [];
for (var i = 0; i < Board.sizeCubed; i++) {
this.placements[i] = 0;
}
this.scores = [0, 0];
}
Board.prototype.placementsToString = function() {
return this.placements.join('');
}
Board.prototype.placePiece = function(poleId, playerId) {
var x = Math.floor(poleId / Board.size),
z = poleId % Board.size;
for (var y = 0; y < Board.size; y++) {
var placementId = this.placementId(x, y, z);
if (this.placements[placementId] == 0) {
this.placements[placementId] = playerId;
return [x, y, z];
}
}
return null;
}
Board.prototype.placementId = function(x, y, z) {
return x + Board.size * (y + Board.size * z);
}
Board.prototype.placementAt = function(x, y, z) {
return this.placements[this.placementId(x, y, z)];
}
Board.prototype.scoreLine = function(point, deltas) {
var player = this.placementAt.apply(this, point);
if (!player) return;
for (var i = 1; i < Board.size; i++) {
point[0] += deltas[0];
point[1] += deltas[1];
point[2] += deltas[2];
if (this.placementAt.apply(this, point) != player) {
return;
}
}
this.scores[player - 1] += 1;
}
Board.prototype.score = function() {
var x, y, z, points = [];
this.scores = [0, 0];
// "vectors"
this.scoreLine([0, 0, 0], [1, 1, 1]);
this.scoreLine([Board.size - 1, 0, 0], [-1, 1, 1]);
this.scoreLine([0, Board.size - 1, 0], [ 1, -1, 1]);
this.scoreLine([0, 0, Board.size - 1], [ 1, 1, -1]);
// verticals
for (x = 0; x < Board.size; x++) {
for (z = 0; z < Board.size; z++) {
this.scoreLine([x, 0, z], [0, 1, 0]);
}
}
// diagonal verticals
for (x = 0; x < Board.size; x++) {
this.scoreLine([x, 0, 0], [0, 1, 1]);
this.scoreLine([x, Board.size - 1, 0], [0, -1, 1]);
}
for (z = 0; z < Board.size; z++) {
this.scoreLine([0, 0, z], [1, 1, 0]);
this.scoreLine([0, Board.size - 1, z], [1, -1, 0]);
}
for (y = 0; y < Board.size; y++) {
// diagonal horizontals
this.scoreLine([0, y, 0], [1, 0, 1]);
this.scoreLine([Board.size - 1, y, 0], [-1, 0, 1]);
// non-diagonal horizontals
for (x = 0; x < Board.size; x++) {
this.scoreLine([x, y, 0], [0, 0, 1]);
}
for (z = 0; z < Board.size; z++) {
this.scoreLine([0, y, z], [1, 0, 0]);
}
}
}
if (typeof(exports) == "undefined") {
window.Board = Board;
} else {
exports.Board = Board;
}
})();
|
'use strict';
const gulp = require('gulp');
const fs = require('fs');
const gulpLoadPlugins = require('gulp-load-plugins');
const del = require('del');
const path = require('path');
const runSequence = require('run-sequence');
const babelify = require('babelify');
const connect = require('gulp-connect');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const $ = gulpLoadPlugins();
const clientDistFolder = 'dist/';
gulp.task('clean', del.bind(null, ['dist/*']));
gulp.task('scss', [], () => {
return gulp.src(['./src/scss/vplyr.scss'])
.pipe($.changed('dist/', {
extension: '.css'
}))
.pipe($.plumber())
.pipe($.sourcemaps.init())
.pipe($.sass().on('error', $.sass.logError))
.pipe($.autoprefixer({
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR']
}))
.pipe($.sourcemaps.write())
.pipe(gulp.dest(clientDistFolder))
.pipe($.connect.reload());
})
function doBundle(b) {
return b.bundle()
.on('error', console.error.bind(console))
.pipe(source('vplyr.js')) //将常规流转换为包含Stream的vinyl对象,并且重命名
.pipe(buffer())
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(clientDistFolder))
.pipe($.connect.reload())
}
gulp.task('scripts', [], function () {
let b = browserify({
entries: './src/js/index.js',
standalone: 'vPlayer',
debug: true,
transform: ['babelify', 'browserify-versionify'],
plugin: ['browserify-derequire']
});
return doBundle(b);
});
gulp.task('watch', [], () => {
connect.server({
livereload: true,
port: 8088
});
gulp.watch(['src/js/**/*.js'], ['scripts'])
gulp.watch(['src/scss/**/*.scss'], ['scss'])
})
gulp.task('default', ['clean', 'scss', 'scripts', 'watch']);
gulp.task('build:minify:js', () => {
let options = {
sourceMap: true,
sourceMapIncludeSources: true,
sourceMapRoot: './src/',
mangle: true,
compress: {
sequences: true,
dead_code: true,
conditionals: true,
booleans: true,
unused: true,
if_return: true,
join_vars: true
}
};
return gulp.src('dist/vplyr.js')
.pipe($.rename({ extname: '.min.js' }))
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.uglify(options))
.on('error', console.error.bind(console))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest('./dist/'));
})
gulp.task('build:minify:css', () => {
return gulp.src(['dist/vplyr.css'])
.pipe($.rename({ extname: '.min.css' }))
.pipe($.cleanCss({
advanced: false,
compatibility: 'ie7',
}))
.pipe(gulp.dest('./dist/'));
})
gulp.task('build', ['clean', 'scss', 'scripts'], function () {
runSequence('build:minify:js', 'build:minify:css');
});
|
/**
* Class FriendController
* Prints HTML templates to AngularJS using different layouts (empty, main, main_admin, etc...)
* @property {Array} auth authorization of methods (index, list, etc...)
* @property {Object} req ExpressJS request object (req)
* @property {Object} res ExpressJS response object (res)
*/
function FriendController() {
//this.auth = ['index', 'list', 'view', 'new', 'edit', 'delete'];
this.auth = [];
}
FriendController.prototype.index = function() {
this.res.render('friend/index.html',{
layout:'layout/empty.html'
});
};
FriendController.prototype.view = function() {
this.res.render('friend/index.html',{
layout:'layout/empty.html'
});
};
/**
* Module exports
*/
module.exports = new FriendController();
|
/* eslint-disable react/sort-comp, react/no-multi-comp, react/destructuring-assignment */
import React, { PureComponent, isValidElement } from 'react';
import PropTypes from 'prop-types';
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import cx from 'classnames';
import { Portal } from 'react-portal';
import Text from './Text';
import styles from './ToolTip.css';
const isBrowser = () => typeof window === 'object';
const getPositionByBounds = (position, offset, bounds) => {
const key = `${position}-${offset}`;
if (!isBrowser()) {
return {
top: 0,
left: 0,
};
}
switch (key) {
case 'top-none':
return {
top: bounds.top + window.pageYOffset,
left: bounds.width / 2 + bounds.left + window.pageXOffset,
};
case 'top-start':
return {
top: bounds.top + window.pageYOffset,
left: bounds.left + window.pageXOffset,
};
case 'top-end':
return {
top: bounds.top + window.pageYOffset,
left: bounds.width + bounds.left + window.pageXOffset,
};
case 'right-none':
return {
top: bounds.height / 2 + bounds.top + window.pageYOffset,
left: bounds.width + bounds.left + window.pageXOffset,
};
case 'right-start':
return {
top: bounds.top + window.pageYOffset,
left: bounds.width + bounds.left + window.pageXOffset,
};
case 'right-end':
return {
top: bounds.height + bounds.top + window.pageYOffset,
left: bounds.width + bounds.left + window.pageXOffset,
};
case 'bottom-none':
return {
top: bounds.height + bounds.top + window.pageYOffset,
left: bounds.width / 2 + bounds.left + window.pageXOffset,
};
case 'bottom-start':
return {
top: bounds.height + bounds.top + window.pageYOffset,
left: bounds.left + window.pageXOffset,
};
case 'bottom-end':
return {
top: bounds.height + bounds.top + window.pageYOffset,
left: bounds.width + bounds.left + window.pageXOffset,
};
case 'left-none':
return {
top: bounds.height / 2 + bounds.top + window.pageYOffset,
left: bounds.left + window.pageXOffset,
};
case 'left-start':
return {
top: bounds.top + window.pageYOffset,
left: bounds.left + window.pageXOffset,
};
case 'left-end':
return {
top: bounds.height + bounds.top + window.pageYOffset,
left: bounds.left + window.pageXOffset,
};
default:
return {
top: 0,
left: 0,
};
}
};
const ANIMATION_TIMEOUT = 200;
class ToolTip extends PureComponent {
state = {
openOrigin: undefined, // 'click' or 'hover'
showTooltip: false,
portalOpen: false,
};
constructor(props) {
super(props);
if (props.closeOnClick) {
// eslint-disable-next-line no-console
console.warn('closeOnClick is deprecated. Please use closeOnClickInside instead.');
}
}
onWindowChange = () => {
if (this.onWindowChangeTimeout) {
clearTimeout(this.onWindowChangeTimeout);
}
if (this.state.showTooltip) {
this.onWindowChangeTimeout = setTimeout(() => {
if (this.mounted) {
this.forceUpdate();
}
}, 10);
}
};
componentDidMount = () => {
this.mounted = true;
if (isBrowser()) {
window.addEventListener('resize', this.onWindowChange);
window.addEventListener('orientationchange', this.onWindowChange);
window.addEventListener('scroll', this.onWindowChange, true);
window.addEventListener('mousedown', this.onDocumentClick, true);
window.addEventListener('touchstart', this.onDocumentClick);
}
// tooltip position can be calculated only after first render, thus re-render
if (this.props.show) {
this.setState({ portalOpen: true, showTooltip: true });
}
};
componentDidUpdate(prevProps) {
if (prevProps.show && !this.props.show) {
this.close();
} else if (!prevProps.show && this.props.show) {
this.open();
}
}
componentWillUnmount = () => {
this.mounted = false;
if (this.hideTimeout) {
clearTimeout(this.hideTimeout);
}
if (this.onWindowChangeTimeout) {
clearTimeout(this.onWindowChangeTimeout);
}
if (isBrowser()) {
window.removeEventListener('resize', this.onWindowChange);
window.removeEventListener('orientationchange', this.onWindowChange);
window.removeEventListener('scroll', this.onWindowChange);
window.removeEventListener('click', this.onDocumentClick, true);
window.removeEventListener('touchstart', this.onDocumentClick);
}
};
close = (callback) => {
const { onCloseStart, onClose } = this.props;
if (this.hideTimeout) {
clearTimeout(this.hideTimeout);
}
if (this.openTimeout) {
clearTimeout(this.openTimeout);
}
if (this.mounted && this.state.showTooltip) {
this.setState({ showTooltip: false });
}
onCloseStart();
this.hideTimeout = setTimeout(() => {
if (this.mounted) {
this.setState({ portalOpen: false }, () => onClose());
}
if (typeof callback === 'function') {
callback();
}
}, ANIMATION_TIMEOUT);
};
open = (openOrigin) => {
const { onOpenStart, onOpen } = this.props;
if (this.hideTimeout) {
clearTimeout(this.hideTimeout);
}
onOpenStart(openOrigin);
// first open portal, then show tooltip to make
// animations work
this.setState({ openOrigin, portalOpen: true }, () => {
this.setState({ showTooltip: true });
// Fires when tooltip finishes animation
this.openTimeout = setTimeout(() => onOpen(openOrigin), ANIMATION_TIMEOUT);
});
};
onClick = (event) => {
const { onClick, showOn } = this.props;
if (showOn !== 'click' && showOn !== 'hoverAndClick') {
return;
}
if (
this.state.showTooltip &&
this.state.openOrigin === 'click' &&
this.node.contains(event.target)
) {
this.close();
} else if (!this.state.showTooltip || this.state.openOrigin !== 'click') {
this.open('click');
}
if (onClick) {
onClick(event);
}
};
onDocumentClick = (e) => {
const { showOn, closeOnClickOutside, onClickOutside } = this.props;
if (
this.mounted &&
this.tooltip &&
!this.tooltip.contains(e.target) &&
!this.node.contains(e.target)
) {
if (closeOnClickOutside && showOn !== 'controlled') {
this.close();
}
onClickOutside({
closeTooltip: this.close,
event: e,
});
}
};
handleClickInside = (e) => {
const {
closeOnClick,
showOn,
closeOnClickInside,
onClickInside,
stopEventPropagationOnClickInside,
} = this.props;
if (stopEventPropagationOnClickInside) {
e.stopPropagation();
}
if ((closeOnClick || closeOnClickInside) && showOn !== 'controlled') {
this.close();
}
onClickInside();
};
beforePortalClose = (DOMNode, removeFromDOM) => {
this.close(removeFromDOM);
};
onMouseEnter = () => {
const { showOn } = this.props;
if (showOn !== 'hover' && showOn !== 'hoverAndClick') {
return;
}
if (!this.state.showTooltip && !this.state.portalOpen) {
this.open('hover');
}
};
onMouseLeave = () => {
const { showOn } = this.props;
if (showOn !== 'hover' && showOn !== 'hoverAndClick') {
return;
}
if (this.state.showTooltip && this.state.openOrigin === 'hover') {
this.close();
}
};
getPosition = () => {
if (this.node) {
const { offset, position } = this.props;
const bounds = this.node.getBoundingClientRect();
return getPositionByBounds(position, offset, bounds);
}
return {
top: 0,
left: 0,
};
};
render() {
const {
children,
className,
contentClassName,
contentStyle,
enabled,
position,
offset,
showArrow,
content,
style,
zIndex,
arrowOffsetPercentage,
} = this.props;
if (!enabled) {
return typeof children === 'string' ? (
<span className={className}>{children}</span>
) : (
children
);
}
const { showTooltip, portalOpen } = this.state;
let contentElement;
if (typeof content === 'string') {
contentElement = (
<div style={{ padding: 5 }}>
<Text nowrap>{content}</Text>
</div>
);
} else if (!isValidElement(content) && typeof content === 'function') {
contentElement = content({ closeTooltip: this.close });
} else {
contentElement = content;
}
const arrowStyle = {};
if (arrowOffsetPercentage) {
if (position === 'top' || position === 'bottom') {
arrowStyle[
offset === 'start' || offset === 'none' ? 'left' : 'right'
] = `${arrowOffsetPercentage}%`;
} else if (position === 'left' || position === 'right') {
arrowStyle[
offset === 'start' || offset === 'none' ? 'top' : 'bottom'
] = `${arrowOffsetPercentage}%`;
}
}
return (
<span
className={cx(styles.root, className)}
style={style}
onClick={this.onClick}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
ref={(node) => {
this.node = node;
}}
>
<Portal isOpened={portalOpen} beforeClose={this.beforePortalClose}>
<TransitionGroup>
{!!portalOpen && !!showTooltip && (
<CSSTransition
key="tooltip"
timeout={ANIMATION_TIMEOUT}
classNames={{
enter: styles[`transition-enter-${position}`],
enterActive: styles[`transition-enterActive-${position}`],
exit: styles[`transition-leave-${position}`],
exitActive: styles[`transition-leaveActive-${position}`],
}}
>
<span
ref={(node) => {
this.tooltip = node;
}}
key="tooltip"
className={cx(
styles.tooltipContainer,
styles[`position-${position}`],
styles[`offset-${offset}`],
contentClassName,
)}
onClick={this.handleClickInside}
style={{
position: 'absolute',
bottom: 'auto',
right: 'auto',
...this.getPosition(),
zIndex,
}}
>
<div className={styles.innerContent}>
<div className={styles.content} style={contentStyle}>
{contentElement}
</div>
{!!showArrow && <div className={styles.arrow} style={arrowStyle} />}
</div>
</span>
</CSSTransition>
)}
</TransitionGroup>
</Portal>
{children}
</span>
);
}
}
ToolTip.propTypes = {
className: PropTypes.string,
children: PropTypes.node,
closeOnClick: PropTypes.bool,
closeOnClickInside: PropTypes.bool,
closeOnClickOutside: PropTypes.bool,
content: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
contentClassName: PropTypes.string,
contentStyle: PropTypes.object,
enabled: PropTypes.bool.isRequired,
position: PropTypes.oneOf(['left', 'right', 'top', 'bottom']),
offset: PropTypes.oneOf(['start', 'end', 'none']),
arrowOffsetPercentage: PropTypes.number,
showArrow: PropTypes.bool,
showOn: PropTypes.oneOf(['hover', 'click', 'hoverAndClick', 'controlled']),
show: PropTypes.bool,
style: PropTypes.object,
zIndex: PropTypes.number,
onClick: PropTypes.func,
onOpenStart: PropTypes.func.isRequired,
onOpen: PropTypes.func.isRequired,
onCloseStart: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
onClickOutside: PropTypes.func.isRequired,
onClickInside: PropTypes.func.isRequired,
stopEventPropagationOnClickInside: PropTypes.bool,
};
ToolTip.defaultProps = {
closeOnClickInside: false,
closeOnClickOutside: true,
enabled: true,
position: 'top',
offset: 'none',
showArrow: true,
showOn: 'hover',
onOpen: () => null,
onClose: () => null,
onOpenStart: () => null,
onCloseStart: () => null,
onClickOutside: () => null,
onClickInside: () => null,
stopEventPropagationOnClickInside: true,
};
export default ToolTip;
|
var xtend = require('xtend');
var debug = require('debug')('mongo-heartbeat');
var error = require('debug')('mongo-heartbeat');
error.log = console.error.bind(console);
var cb = require('cb');
var EventEmitter = require('events').EventEmitter;
var defaults = {
timeout: 10000,
interval: 5000,
tolerance: 1
};
function Pinger(db, options) {
if (!(this instanceof Pinger)){
return new Pinger(db, options);
}
EventEmitter.call(this);
this._current_failures = 0;
this._db = db;
this._options = xtend(defaults, options || {});
this._recurseCheck();
}
Pinger.prototype = Object.create(EventEmitter.prototype);
Pinger.prototype._check = function check(callback) {
var db = this._db;
var self = this;
function fail (err) {
self.stop();
error(err.message);
return callback(err);
}
var start = Date.now();
db.command({ ping: 1 }, cb(function (err) {
// _current_failures will restart if was healthy in previous cases
self._current_failures = err ? (self._current_failures + 1) : 0;
if (err) {
var error = err;
if (err instanceof cb.TimeoutError) {
if (self._current_failures === 1) {
error = new Error('the command didn\'t respond in ' + self._options.timeout + 'ms');
} else {
error = new Error('the command didn\'t respond in ' + self._options.timeout + 'ms after ' + self._current_failures + ' attempts');
}
}
if (self._current_failures >= self._options.tolerance) {
return fail(error);
} else {
self.emit('failed', error);
return callback();
}
}
self.emit('heartbeat', { delay: Date.now() - start });
debug('heartbeat');
return callback();
}).timeout(this._options.timeout));
};
Pinger.prototype._recurseCheck = function () {
var self = this;
if (self._stop) return;
setTimeout(function () {
self._check(function (err) {
if (err) {
return self.emit('error', err);
}
self._recurseCheck();
});
}, this._options.interval);
};
Pinger.prototype.stop = function () {
this._stop = true;
};
module.exports = Pinger;
|
$(document).ready(function() {
$.getJSON('http://orderharmony.cloudcontrolled.com/index.php', function(data) {
//First add all the rows
$('#products').append('<ul class="thumbnails" id="products-list"></ul>');
//Add All the products
$.each(data.products, function(key, val) {
//Add product holder
$('#products-list').append('<li class="span4" id="product-'+key+'"></li>');
var product = $('#product-'+key);
//Add product content
product.append(' \
<div class="class="thumbnail"> \
<div class="caption"> \
<h5>'+val.product.name+'</h5> \
</div> \
<img src="http://placehold.it/360x268" alt=""> \
<div class="caption" style="height: 150px;"> \
<p>'+ val.product.description +' </p> \
<p> \
<a href="javascript:;" onclick="simpleCart.add( \'name='+ val.product.name +'\' , \'price=35.95\' , \'quantity=1\' );" class="btn btn-success"> \
<i class="icon-plus-sign icon-white"></i> Add \
</a> \
</p> \
</div> \
<div>');
});
//Remove the loader
$('#products-loader').remove();
$('#products-loader-header').remove();
})
.error(function() { alert("error"); });
});
|
/*
*--------------------------------------------------------------------
* jQuery-Plugin "weekcalc -config.js-"
* Version: 3.0
* Copyright (c) 2016 TIS
*
* Released under the MIT License.
* http://tis2010.jp/license.txt
* -------------------------------------------------------------------
*/
jQuery.noConflict();
(function($,PLUGIN_ID){
"use strict";
var vars={
calculationtable:null,
fieldinfos:{}
};
var functions={
fieldsort:function(layout){
var codes=[];
$.each(layout,function(index,values){
switch (values.type)
{
case 'ROW':
$.each(values.fields,function(index,values){
/* exclude spacer */
if (!values.elementId) codes.push(values.code);
});
break;
case 'GROUP':
$.merge(codes,functions.fieldsort(values.layout));
break;
case 'SUBTABLE':
$.each(values.fields,function(index,values){
/* exclude spacer */
if (!values.elementId) codes.push(values.code);
});
break;
}
});
return codes;
},
reloadweekoption:function(row,callback){
/* clear rows */
var target=$('select#week',row);
if (target.val())
{
var fieldinfo=vars.fieldinfos[target.val()];
var options=[];
if (fieldinfo.type!='SINGLE_LINE_TEXT')
{
options=[fieldinfo.options.length];
$.each(fieldinfo.options,function(key,values){
options[values.index]=values.label;
});
for (var i=0;i<7;i++)
{
$('select#weekoption'+i.toString(),row).empty();
for (var i2=0;i2<options.length;i2++) $('select#weekoption'+i.toString(),row).append($('<option>').attr('value',options[i2]).text(options[i2]));
}
$('.week',row).show();
}
else $('.week',row).hide();
}
else $('.week',row).hide();
if (callback) callback();
}
};
/*---------------------------------------------------------------
initialize fields
---------------------------------------------------------------*/
kintone.api(kintone.api.url('/k/v1/app/form/layout',true),'GET',{app:kintone.app.getId()},function(resp){
var sorted=functions.fieldsort(resp.layout);
/* get fieldinfo */
kintone.api(kintone.api.url('/k/v1/app/form/fields',true),'GET',{app:kintone.app.getId()},function(resp){
var config=kintone.plugin.app.getConfig(PLUGIN_ID);
vars.fieldinfos=$.fieldparallelize(resp.properties);
$.each(sorted,function(index){
if (sorted[index] in vars.fieldinfos)
{
var fieldinfo=vars.fieldinfos[sorted[index]];
/* check field type */
switch (fieldinfo.type)
{
case 'DATE':
case 'DATETIME':
$('select#date').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label));
break;
case 'DROP_DOWN':
case 'RADIO_BUTTON':
$('select#week').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label));
break;
case 'SINGLE_LINE_TEXT':
$('select#week').append($('<option>').attr('value',fieldinfo.code).text(fieldinfo.label));
break;
}
}
});
/* initialize valiable */
vars.calculationtable=$('.calculations').adjustabletable({
add:'img.add',
del:'img.del',
addcallback:function(row){
$('.week',row).hide();
$('select#week',row).on('change',function(){functions.reloadweekoption(row);});
}
});
var row=null;
var calculations=[];
if (Object.keys(config).length!==0)
{
calculations=JSON.parse(config['calculation']);
if (config['bulk']=='1') $('input#bulk').prop('checked',true);
$.each(calculations,function(index){
if (index>0) vars.calculationtable.addrow();
row=vars.calculationtable.rows.last();
$('select#date',row).val(calculations[index].date);
$('select#week',row).val(calculations[index].week);
if (vars.fieldinfos[calculations[index].week].type!='SINGLE_LINE_TEXT')
{
functions.reloadweekoption(row,function(){
for (var i=0;i<7;i++) $('select#weekoption'+i.toString(),row).val(calculations[index].weekoption[i]);
$('.week',row).show();
});
}
else $('.week',row).hide();
});
}
else $('.week',row).hide();
},function(error){});
},function(error){});
/*---------------------------------------------------------------
button events
---------------------------------------------------------------*/
$('button#submit').on('click',function(e){
var error=false;
var row=null;
var config=[];
var calculations=[];
var weekoption=[];
var week=[
'日曜日',
'月曜日',
'火曜日',
'水曜日',
'木曜日',
'金曜日',
'土曜日'
];
/* check values */
for (var i=0;i<vars.calculationtable.rows.length;i++)
{
row=vars.calculationtable.rows.eq(i);
weekoption=[];
if (!$('select#date',row).val()) continue;
if (!$('select#week',row).val()) continue;
if (vars.fieldinfos[$('select#date',row).val()].tablecode!=vars.fieldinfos[$('select#week',row).val()].tablecode)
{
swal('Error!','テーブル内フィールドの指定は同一テーブルにして下さい。','error');
return;
}
if (vars.fieldinfos[$('select#week',row).val()].type!='SINGLE_LINE_TEXT')
{
var type=(vars.fieldinfos[$('select#week',row).val()].type=='DROP_DOWN')?'ドロップダウン':'ラジオボタン';
for (var i2=0;i2<7;i2++)
{
if (!$('select#weekoption'+i2.toString(),row).val())
{
swal('Error!',type+'フィールドで設定された'+week[i2]+'に該当する項目を指定して下さい。','error');
return;
}
weekoption.push($('select#weekoption'+i2.toString(),row).val());
}
}
calculations.push({
date:$('select#date',row).val(),
week:$('select#week',row).val(),
weekoption:weekoption
});
}
/* setup config */
config['bulk']=($('input#bulk').prop('checked'))?'1':'0';
config['calculation']=JSON.stringify(calculations);
/* save config */
kintone.plugin.app.setConfig(config);
});
$('button#cancel').on('click',function(e){
history.back();
});
})(jQuery,kintone.$PLUGIN_ID);
|
import {Schema} from 'mongoose'
const TagSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'Users'
}
}, {timestamps: true})
export default TagSchema
|
var classCSF_1_1Zpt_1_1Rendering_1_1AbstractSourceInfo =
[
[ "AbstractSourceInfo", "classCSF_1_1Zpt_1_1Rendering_1_1AbstractSourceInfo.html#a91536c9ac26ad0955d63806106ac9c89", null ],
[ "Equals", "classCSF_1_1Zpt_1_1Rendering_1_1AbstractSourceInfo.html#a147de92e6587e6f19755db7a41484ab2", null ],
[ "Equals", "classCSF_1_1Zpt_1_1Rendering_1_1AbstractSourceInfo.html#ac7dabb449a73cf663d187e1f725dd469", null ],
[ "Equals", "classCSF_1_1Zpt_1_1Rendering_1_1AbstractSourceInfo.html#a152bcc9be8f02878723da8fee70b5929", null ],
[ "GetContainer", "classCSF_1_1Zpt_1_1Rendering_1_1AbstractSourceInfo.html#a3780e2ccf09775935f29705c22aeb8db", null ],
[ "GetHashCode", "classCSF_1_1Zpt_1_1Rendering_1_1AbstractSourceInfo.html#a3ef086b6befd842e26682820eae0955b", null ],
[ "GetRelativeName", "classCSF_1_1Zpt_1_1Rendering_1_1AbstractSourceInfo.html#ac248f652c6db712ee1a852bec31c2806", null ],
[ "FullName", "classCSF_1_1Zpt_1_1Rendering_1_1AbstractSourceInfo.html#a021c3ec288f3cd6ddd3761986beccb06", null ]
];
|
'use strict';
const Support = require('../support'),
DataTypes = require('../../../lib/data-types'),
expectsql = Support.expectsql,
current = Support.sequelize,
sql = current.dialect.QueryGenerator;
if (current.dialect.name === 'mysql') {
describe(Support.getTestDialectTeaser('SQL'), () => {
describe('addColumn', () => {
const Model = current.define('users', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
}
}, { timestamps: false });
it('properly generate alter queries', () => {
return expectsql(sql.addColumnQuery(Model.getTableName(), 'level_id', current.normalizeAttribute({
type: DataTypes.FLOAT,
allowNull: false
})), {
mysql: 'ALTER TABLE `users` ADD `level_id` FLOAT NOT NULL;'
});
});
it('properly generate alter queries for foreign keys', () => {
return expectsql(sql.addColumnQuery(Model.getTableName(), 'level_id', current.normalizeAttribute({
type: DataTypes.INTEGER,
references: {
model: 'level',
key: 'id'
},
onUpdate: 'cascade',
onDelete: 'cascade'
})), {
mysql: 'ALTER TABLE `users` ADD `level_id` INTEGER, ADD CONSTRAINT `users_level_id_foreign_idx` FOREIGN KEY (`level_id`) REFERENCES `level` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;'
});
});
it('properly generate alter queries with FIRST', () => {
return expectsql(sql.addColumnQuery(Model.getTableName(), 'test_added_col_first', current.normalizeAttribute({
type: DataTypes.STRING,
first: true
})), {
mysql: 'ALTER TABLE `users` ADD `test_added_col_first` VARCHAR(255) FIRST;'
});
});
});
});
}
|
/*
* seqex: api/program/ProgramExecutor.js
* Program Executor logic for the seqex program api
*
* Copyright (c) 2013 Jon Brule
* Licensed under the MIT license.
*/
'use strict';
function ProgramExecutor(program) {
this.program = program;
this.running = false;
this.devices = {};
}
var error = function(type, message) {
var error = new Error(message);
error.type = type;
return error;
};
var parseDevices = function(program) {
return program.devices;
};
ProgramExecutor.prototype.isRunning = function() {
return this.running;
};
ProgramExecutor.prototype.startProgram = function(success, failure) {
if (!this.isRunning()) {
this.running = true;
this.devices = parseDevices(this.program);
console.log(this.devices);
success('startProgramExecutor(' + this.program.id + ')');
} else {
failure(error('ALREADY_STARTED', 'Program Id (' + this.program.id + ') is already running.'));
}
};
ProgramExecutor.prototype.stopProgram = function(success, failure) {
if (this.isRunning()) {
this.running = false;
success('stopProgramExecutor(' + this.program.id + ')');
} else {
failure(error('NOT_RUNNING', 'Program Id (' + this.program.id + ') is not running.'));
}
};
// export the class
module.exports = ProgramExecutor;
|
require(
['view/Main', 'util/Prototypes', 'util/Util'],
function(Main, Prototypes, Util) {
$(document).ready(function() {
Util.sendHeartbeat();
setInterval(Util.sendHeartbeat,60000);
var main = new Main({projectId:window.projectId});
$(document.body).append(main.el);
});
}
);
|
import AttrRecognizer from './attribute';
import {
DIRECTION_ALL,
DIRECTION_HORIZONTAL,
DIRECTION_VERTICAL,
DIRECTION_NONE,
DIRECTION_UP,
DIRECTION_DOWN,
DIRECTION_LEFT,
DIRECTION_RIGHT
} from '../inputjs/input-consts';
import { STATE_BEGAN } from '../recognizerjs/recognizer-consts';
import { TOUCH_ACTION_PAN_X,TOUCH_ACTION_PAN_Y } from '../touchactionjs/touchaction-Consts';
import directionStr from '../recognizerjs/direction-str';
/**
* @private
* Pan
* Recognized when the pointer is down and moved in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
export default class PanRecognizer extends AttrRecognizer {
constructor(options = {}) {
super({
event: 'pan',
threshold: 10,
pointers: 1,
direction: DIRECTION_ALL,
...options,
});
this.pX = null;
this.pY = null;
}
getTouchAction() {
let { options:{ direction } } = this;
let actions = [];
if (direction & DIRECTION_HORIZONTAL) {
actions.push(TOUCH_ACTION_PAN_Y);
}
if (direction & DIRECTION_VERTICAL) {
actions.push(TOUCH_ACTION_PAN_X);
}
return actions;
}
directionTest(input) {
let { options } = this;
let hasMoved = true;
let { distance } = input;
let { direction } = input;
let x = input.deltaX;
let y = input.deltaY;
// lock to axis?
if (!(direction & options.direction)) {
if (options.direction & DIRECTION_HORIZONTAL) {
direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
hasMoved = x !== this.pX;
distance = Math.abs(input.deltaX);
} else {
direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
hasMoved = y !== this.pY;
distance = Math.abs(input.deltaY);
}
}
input.direction = direction;
return hasMoved && distance > options.threshold && direction & options.direction;
}
attrTest(input) {
return AttrRecognizer.prototype.attrTest.call(this, input) && // replace with a super call
(this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
}
emit(input) {
this.pX = input.deltaX;
this.pY = input.deltaY;
let direction = directionStr(input.direction);
if (direction) {
input.additionalEvent = this.options.event + direction;
}
super.emit(input);
}
}
|
require('../nodash').install(GLOBAL);
var assert = require('../util/assert');
describe('Objects', function () {
it('keys', function () {
var ks = keys({ a: 3, b: 2, c: 1 });
assert.deepEqual(0, difference(ks, "abc").length);
assert.deepEqual([ 'c' ], difference(ks, "ab"));
});
[
undefined,
null,
1,
true,
Math.PI,
[],
{},
[ 1, 2, 3 ],
{ a: [], b: [ 4, 5, 6 ]}
]
.forEach(function (data) {
it('clone /w ' + data, function () {
assert.deepEqual(data, clone(data));
});
});
it('values', function () {
assert.deepEqual([ 1, 1, 1], values({ a: 1, b: 1, c: 1 }));
});
});
|
/*
* Lazy Line Painter - Path Object
* Generated using 'SVG to Lazy Line Converter'
*
* http://lazylinepainter.info
* Copyright 2013, Cam O'Connell
*
*/
var pfObj = {
"portfolio": {
"strokepath": [
{
"path": "M 99.174723,174.23256 C 89.149051,166.968 65.673155,145.82454 55.429981,135.58137 42.999936,123.15132 35.740825,113.79487 25.168207,103.22225 c -0.599243,-0.59924 2.996215,-5.99243 4.793945,-7.79016 4.538819,-4.538819 4.602124,-5.800609 9.587889,-10.786373 2.106267,-2.106268 7.716482,-9.440534 8.988646,-11.984861 2.149503,-4.299006 6.521172,-9.817011 9.587887,-12.883726 1.012727,-1.012727 14.702975,-1.595006 16.179562,-1.498108 0,0 10.341993,0.167618 13.183347,0.299621 10.098958,0.469174 55.318457,-0.02683 59.924297,1.198487 3.59674,0.956865 25.39069,39.634923 31.16065,44.94323 0.16868,0.15518 -6.14252,6.74175 -6.59168,7.19091 l -22.47162,22.47162 c -9.05179,9.05179 -28.54469,21.59962 -34.45646,26.66631 -3.56757,3.0576 -4.54023,4.83985 -7.79017,8.08978 -2.38609,2.3861 -3.92732,2.46618 -7.790156,5.39319",
"duration": 1800
},
{
"path": "m 24.568964,103.82149 c 46.386251,0.39932 102.781806,1.19849 152.806976,1.19849",
"duration": 600
},
{
"path": "M 89.586835,59.477509 C 79.104167,74.486302 67.155784,95.391526 59.325061,105.01998 c -0.652497,0.80229 5.058546,10.01093 5.99243,11.98486 4.793944,10.13286 27.37774,44.32482 32.059502,56.02922",
"duration": 600
},
{
"path": "m 117.45163,59.177885 c 0.1615,6.85613 23.94297,36.405186 27.86481,45.542465 1.30746,3.04617 -5.91638,11.30983 -7.49055,13.7826 -3.14928,4.947 -4.02632,5.59006 -7.49053,10.78637 -7.47293,11.20941 -23.11893,34.94197 -29.96215,44.04436",
"duration": 600
},
{
"path": "m 154.6047,144.57002 c -0.4648,6.24979 -1.6788,12.40341 -8.08978,16.17956 -1.85578,1.09308 5.63893,-1.66431 9.28827,1.19849 0,0 4.79394,0 7.1909,3.59545 1.24576,1.86864 -3.30968,-6.27818 3.89509,-11.68524 0.23337,-0.23337 3.25972,-3.62802 2.99622,-3.59545 -7.27114,0.89886 -9.78459,6.62399 -15.2807,-5.69281 z",
"duration": 600
},
{
"path": "m 30.261774,42.998324 c 1.882432,5.184243 -1.666779,9.964697 -4.793945,12.883726 0,0 3.827694,-0.02246 4.793945,0.299621 2.467327,0.822443 1.588534,0.644458 3.89508,1.79773 0.57372,0.286861 6.160224,3.295837 5.692808,3.295837 -2.055319,0 -2.553908,-10.460948 3.595458,-12.584104 2.829386,-0.976886 -6.989736,1.841887 -12.883724,-6.891295",
"duration": 600
}
],
"dimensions": {
"width": 200,
"height": 200
}
}
};
/*
Setup and Paint your lazyline!
*/
$(document).ready(function(){
$('#portfolio').lazylinepainter(
{
"svgData": pfObj,
"strokeWidth": 2,
"strokeColor": "#e09b99"
}).lazylinepainter('paint');
});
|
"use strict";
// validate that the parameter looks like a block
function validateBlock(block) {
return (
block !== null &&
typeof block !== "undefined" &&
!(block instanceof Error) &&
!block.error &&
block.hash &&
block.parentHash &&
block.number
);
}
module.exports = validateBlock;
|
'use strict';
var express = require('express');
var controller = require('./courses.controller');
var router = express.Router();
router.get('/', controller.index);
module.exports = router;
|
PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t \xA0a-gi-z0-9]+/,null,"\t \xa0abcdefgijklmnopqrstuvwxyz0123456789"],[PR.PR_PUNCTUATION,/^[=*~\^\[\]]+/,null,"=*~^[]"]],[["lang-wiki.meta",/(?:^^|\r\n?|\n)(#[a-z]+)\b/],[PR.PR_LITERAL,/^(?:[A-Z][a-z][a-z0-9]+[A-Z][a-z][a-zA-Z0-9]+)\b/],["lang-",/^\{\{\{([\s\S]+?)\}\}\}/],["lang-",/^`([^\r\n`]+)`/],[PR.PR_STRING,/^https?:\/\/[^\/?#\s]*(?:\/[^?#\s]*)?(?:\?[^#\s]*)?(?:#\S*)?/i],[PR.PR_PLAIN,/^(?:\r\n|[\s\S])[^#=*~^A-Zh\{`\[\r\n]*/]]),["wiki"]),PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_KEYWORD,/^#[a-z]+/i,null,"#"]],[]),["wiki.meta"]);
|
angular.module('meteor-running-auth').controller("RegisterCtrl",
function ($meteor, $state) {
}
);
|
goog.provide('ol.renderer.dom.Layer');
goog.require('goog.dom');
goog.require('ol.layer.Layer');
goog.require('ol.renderer.Layer');
/**
* @constructor
* @extends {ol.renderer.Layer}
* @param {ol.renderer.Map} mapRenderer Map renderer.
* @param {ol.layer.Layer} layer Layer.
* @param {!Element} target Target.
*/
ol.renderer.dom.Layer = function(mapRenderer, layer, target) {
goog.base(this, mapRenderer, layer);
/**
* @type {!Element}
* @protected
*/
this.target = target;
};
goog.inherits(ol.renderer.dom.Layer, ol.renderer.Layer);
/**
* @return {!Element} Target.
*/
ol.renderer.dom.Layer.prototype.getTarget = function() {
return this.target;
};
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
;(function() {
"use strict";
require("BaseController").init({
siteName: "8tracks",
playPause: "#player_play_button",
play: "#player_play_button",
pause: "#player_pause_button",
playNext: "#player_skip_button",
mute: ".volume-mute",
like: ".mix-like.inactive",
dislike: ".mix-like.active",
song: "li.track.now_playing div.title_container div.title_artist span.t",
artist: "li.track.now_playing div.title_container div.title_artist span.a"
});
})();
},{"BaseController":2}],2:[function(require,module,exports){
;(function() {
"use strict";
var BaseController = function() { return this; };
var sk_log = require("../modules/SKLog.js");
BaseController.prototype.init = function(options) {
this.name = document.location.hostname;
this.siteName = options.siteName || null;
// Ensure music controller only loaded once
document.mutetabPlayerList = document.mutetabPlayerList || {};
if (document.mutetabPlayerList.hasOwnProperty(this.siteName))
return;
document.mutetabPlayerList[this.siteName] = true;
this.selectors = {
//** Properties **//
playPause: (options.playPause || null),
play: (options.play || null),
pause: (options.pause || null),
playNext: (options.playNext || null),
playPrev: (options.playPrev || null),
mute: (options.mute || null),
like: (options.like || null),
dislike: (options.dislike || null),
iframe: (options.iframe || null),
//** States **//
playState: (options.playState || null),
pauseState: (options.pauseState || null),
// ** Song Change Observer **//
songChange: (options.songChange || null),
//** Song Info **//
song: (options.song || null),
artist: (options.artist || null)
};
// Optional. Style of play and pause buttons when they are NOT in use
// EX: When a play button is in use, css class "playing" is added
// In that case, set playStyle to "playing"
this.playStyle = options.playStyle || null;
this.pauseStyle = options.pauseStyle || null;
// Previous player state, used to check vs current player state to see if anything changed
this.oldState = {};
// Set to true if the play/pause buttons share the same element
this.buttonSwitch = options.buttonSwitch || false;
// Default listener sends actions to main document
this.attachListeners();
// Set to true if the tab should be hidden from the popup unless it has a playPause element shown
this.hidePlayer = options.hidePlayer || false;
chrome.runtime.sendMessage({created: true}, function() {
sk_log("Told BG we are created");
});
sk_log("SK content script loaded");
document.addEventListener("streamkeys-test-loaded", function() {
sk_log("loaded");
});
};
BaseController.prototype.doc = function() {
var useFrameSelector = (this.selectors.iframe && document.querySelector(this.selectors.iframe).tagName === "IFRAME");
return (useFrameSelector) ? document.querySelector(this.selectors.iframe).contentWindow.document : document;
};
/**
* Inject a script into the current document
* @param {String} file.url - /relative/path/to/script
* @param {String} file.script - plaintext script as a string
*/
BaseController.prototype.injectScript = function(file) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
if(file.url) {script.setAttribute("src", chrome.extension.getURL(file.url));}
if(file.script) {script.innerHTML = file.script;}
(document.head || document.documentElement).appendChild(script);
};
/**
* Click inside document
* @param {String} opts.selectorButton - css selector for button to click
* @param {String} opts.action - name of action to log to console for debugging purposes
* @param {String} [opts.selectorFrame] - css selector for iframe to send clicks to
*/
BaseController.prototype.click = function(opts) {
opts = opts || {};
if(opts.selectorButton === null) {
sk_log("disabled", opts.action);
return;
}
try {
this.doc().querySelector(opts.selectorButton).click();
sk_log(opts.action);
} catch(e) {
sk_log("Element not found for click.", opts.selectorButton, true);
}
// Update the player state after a click
this.updatePlayerState();
};
BaseController.prototype.playPause = function() {
if(this.selectors.play !== null && this.selectors.pause !== null) {
if(this.isPlaying()) {
this.click({action: "playPause", selectorButton: this.selectors.pause, selectorFrame: this.selectors.iframe});
} else {
this.click({action: "playPause", selectorButton: this.selectors.play, selectorFrame: this.selectors.iframe});
}
} else {
this.click({action: "playPause", selectorButton: this.selectors.playPause, selectorFrame: this.selectors.iframe});
}
};
BaseController.prototype.playNext = function() {
this.click({action: "playNext", selectorButton: this.selectors.playNext, selectorFrame: this.selectors.iframe});
};
BaseController.prototype.playPrev = function() {
this.click({action: "playPrev", selectorButton: this.selectors.playPrev, selectorFrame: this.selectors.iframe});
};
BaseController.prototype.stop = function() {
if(this.isPlaying()) this.playPause();
};
BaseController.prototype.mute = function() {
this.click({action: "mute", selectorButton: this.selectors.mute, selectorFrame: this.selectors.iframe});
};
BaseController.prototype.like = function() {
this.click({action: "like", selectorButton: this.selectors.like, selectorFrame: this.selectors.iframe});
};
BaseController.prototype.dislike = function() {
this.click({action: "dislike", selectorButton: this.selectors.dislike, selectorFrame: this.selectors.iframe});
};
/**
* Attempts to check if the site is playing anything
* @return {Boolean} true if site is currently playing
*/
BaseController.prototype.isPlaying = function() {
var playEl = this.doc().querySelector(this.selectors.play),
playPauseEl = this.doc().querySelector(this.selectors.playPause),
isPlaying = false;
if(this.buttonSwitch) {
// If playEl does not exist then it is currently playing
isPlaying = (playEl === null);
} else {
// Check for play/pause style overrides
if(this.playStyle) {
// Check if the class list contains the class that is only active when play button is playing
isPlaying = playPauseEl.classList.contains(this.playStyle);
} else if(this.pauseStyle && this.selectors.pause) {
var pauseEl = this.doc().querySelector(this.selectors.pause);
isPlaying = pauseEl.classList.contains(this.pauseStyle);
} else {
// Check if the pause element exists
if(this.selectors.playState) {
isPlaying = (this.doc().querySelector(this.selectors.playState) !== null);
}
// Hack to get around sometimes not being able to read css properties that are not inline
else if(playEl) {
var displayStyle = "none";
if (playEl.currentStyle) {
displayStyle = playEl.currentStyle.display;
} else if (window.getComputedStyle) {
displayStyle = window.getComputedStyle(playEl, null).getPropertyValue("display");
}
isPlaying = (displayStyle == "none");
} else {
return null;
}
}
}
return isPlaying;
};
/**
* Gets the current state of the music player and passes data to background page (and eventually popup)
*/
BaseController.prototype.updatePlayerState = function() {
if(this.checkPlayer) this.checkPlayer();
var newState = this.getStateData();
if(JSON.stringify(newState) !== JSON.stringify(this.oldState)) {
sk_log("Player state change");
this.oldState = newState;
chrome.runtime.sendMessage({
action: "update_player_state",
stateData: newState
});
}
};
/**
* Gets an object containing the current player state data
* @return {{song: {String}, artist: {String}, isPlaying: {Boolean}, siteName: {String}}}
*/
BaseController.prototype.getStateData = function() {
return {
song: this.getSongData(this.selectors.song),
artist: this.getSongData(this.selectors.artist),
isPlaying: this.isPlaying(),
siteName: this.siteName,
canDislike: !!(this.selectors.dislike && this.doc().querySelector(this.selectors.dislike)),
canPlayPrev: !!(this.selectors.playPrev && this.doc().querySelector(this.selectors.playPrev)),
canPlayPause: !!(
(this.selectors.playPause && this.doc().querySelector(this.selectors.playPause)) ||
(this.selectors.play && this.doc().querySelector(this.selectors.play)) ||
(this.selectors.pause && this.doc().querySelector(this.selectors.pause))
),
canPlayNext: !!(this.selectors.playNext && this.doc().querySelector(this.selectors.playNext)),
canLike: !!(this.selectors.like && this.doc().querySelector(this.selectors.like)),
hidePlayer: this.hidePlayer
};
};
/**
* Gets the text value from a song data selector
* @param {String} selector - selector for song data
* @return {*} song data if element is found, null otherwise
*/
BaseController.prototype.getSongData = function(selector) {
if(!selector) return null;
var dataEl = this.doc().querySelector(selector);
if(dataEl && dataEl.textContent) {
return dataEl.textContent;
}
return null;
};
/**
* Checks if a BaseController property is set. Used for testing.
* @param {String} property - name of property to check for
*/
BaseController.prototype.getProperty = function(property) {
if(this[property]) sk_log(property);
else sk_log("Property not found.", property, true);
};
/**
* Callback for request from background page
*/
BaseController.prototype.doRequest = function(request, sender, response) {
if(typeof request !== "undefined") {
if(request.action === "playPause") this.playPause();
if(request.action === "playNext") this.playNext();
if(request.action === "playPrev") this.playPrev();
if(request.action === "stop") this.stop();
if(request.action === "mute") this.mute();
if(request.action === "like") this.like();
if(request.action === "dislike") this.dislike();
if(request.action === "getPlayerState") {
var newState = this.getStateData();
this.oldState = newState;
response(newState);
}
}
};
/**
* Callback for request from tester
*/
BaseController.prototype.doTestRequest = function(e) {
if(e.detail) {
if(e.detail === "playPause" || e.detail === "playNext" || e.detail === "playPrev" || e.detail === "stop" || e.detail === "mute" || e.detail === "like"|| e.detail === "dislike" ) {
this.doRequest({action: e.detail});
}
if(e.detail == "songName") this.test_getSongData(this.selectors.song);
if(e.detail == "artistName") this.test_getSongData(this.selectors.artist);
if(e.detail == "siteName") this.getProperty("siteName");
if(e.detail == "isPlaying") this.isPlaying();
}
};
/**
* Process a test request to get song data
* @param {String} selector - query selector for song data text
*/
BaseController.prototype.test_getSongData = function(selector) {
var songData = this.getSongData(selector);
if(songData) {
sk_log("Song data: ", songData);
} else {
sk_log("Song data not found.", {}, true);
}
};
/**
* Setup listeners for extension messages and test requests. Initialize the playerState interval
*/
BaseController.prototype.attachListeners = function() {
// Listener for requests from background page
chrome.runtime.onMessage.addListener(this.doRequest.bind(this));
// Listener for requests from tests
document.addEventListener("streamkeys-test", this.doTestRequest.bind(this));
// Update the popup player state intermittently
setInterval(this.updatePlayerState.bind(this), 200);
sk_log("Attached listener for ", this);
};
module.exports = new BaseController();
})();
},{"../modules/SKLog.js":3}],3:[function(require,module,exports){
;(function() {
"use strict";
/**
* Log messages to console with prepended message. Also dispatches a JS event
* to interact with tests
* @param msg {String} message to log
* @param [obj] {Object} object to dump with message
* @param [err] {Boolean} TRUE if the message is an error
*/
module.exports = function(msg, obj, err) {
if(msg) {
obj = obj || "";
if(err) {
//console.error("STREAMKEYS-ERROR: " + msg, obj);
msg = "ERROR: " + msg;
} else {
//console.log("STREAMKEYS-INFO: " + msg, obj);
}
document.dispatchEvent(new CustomEvent("streamkeys-test-response", {detail: msg}));
}
};
})();
},{}]},{},[1]);
|
{
this.x = args.x;
this.y = args.y;
this.z = args.z;
this.a = args.a;
this.h = args.h;
}
|
'use strict';
var util = require('util'),
Store = require('../base'),
_ = require('lodash'),
debug = require('debug')('saga:revisionGuardStore:redis'),
uuid = require('node-uuid').v4,
ConcurrencyError = require('../../errors/concurrencyError'),
jsondate = require('jsondate'),
async = require('async'),
redis = require('redis');
function Redis(options) {
Store.call(this, options);
var defaults = {
host: 'localhost',
port: 6379,
prefix: 'readmodel_revision',
max_attempts: 1
};
_.defaults(options, defaults);
if (options.url) {
var url = require('url').parse(options.url);
if (url.protocol === 'redis:') {
if (url.auth) {
var userparts = url.auth.split(":");
options.user = userparts[0];
if (userparts.length === 2) {
options.password = userparts[1];
}
}
options.host = url.hostname;
options.port = url.port;
if (url.pathname) {
options.db = url.pathname.replace("/", "", 1);
}
}
}
this.options = options;
}
util.inherits(Redis, Store);
_.extend(Redis.prototype, {
connect: function (callback) {
var self = this;
var options = this.options;
this.client = new redis.createClient(options.port || options.socket, options.host, options);
this.prefix = options.prefix;
var calledBack = false;
if (options.password) {
this.client.auth(options.password, function(err) {
if (err && !calledBack && callback) {
calledBack = true;
if (callback) callback(err, self);
return;
}
if (err) throw err;
});
}
if (options.db) {
this.client.select(options.db);
}
this.client.on('end', function () {
self.disconnect();
});
this.client.on('error', function (err) {
console.log(err);
if (calledBack) return;
calledBack = true;
if (callback) callback(null, self);
});
this.client.on('connect', function () {
if (options.db) {
self.client.send_anyways = true;
self.client.select(options.db);
self.client.send_anyways = false;
}
self.emit('connect');
if (calledBack) return;
calledBack = true;
if (callback) callback(null, self);
});
},
disconnect: function (callback) {
if (this.client) {
this.client.end();
}
this.emit('disconnect');
if (callback) callback(null, this);
},
getNewId: function(callback) {
this.client.incr('nextItemId:' + this.prefix, function(err, id) {
if (err) {
return callback(err);
}
callback(null, id.toString());
});
},
get: function (id, callback) {
if (!id || !_.isString(id)) {
var err = new Error('Please pass a valid id!');
debug(err);
return callback(err);
}
this.client.get(this.options.prefix + ':' + id, function (err, entry) {
if (err) {
return callback(err);
}
if (!entry) {
return callback(null, null);
}
try {
entry = jsondate.parse(entry.toString());
} catch (error) {
if (callback) callback(error);
return;
}
callback(null, entry.revision);
});
},
set: function (id, revision, oldRevision, callback) {
if (!id || !_.isString(id)) {
var err = new Error('Please pass a valid id!');
debug(err);
return callback(err);
}
if (!revision || !_.isNumber(revision)) {
var err = new Error('Please pass a valid revision!');
debug(err);
return callback(err);
}
var key = this.options.prefix + ':' + id;
var self = this;
this.client.watch(key, function (err) {
if (err) {
return callback(err);
}
self.get(id, function (err, rev) {
if (err) {
debug(err);
if (callback) callback(err);
return;
}
if (rev && rev !== oldRevision) {
self.client.unwatch(function (err) {
if (err) {
debug(err);
}
err = new ConcurrencyError();
debug(err);
if (callback) {
callback(err);
}
});
return;
}
self.client.multi([['set'].concat([key, JSON.stringify({ revision: revision })])]).exec(function (err, replies) {
if (err) {
debug(err);
if (callback) {
callback(err);
}
return;
}
if (!replies || replies.length === 0 || _.find(replies, function (r) {
return r !== 'OK'
})) {
var err = new ConcurrencyError();
debug(err);
if (callback) {
callback(err);
}
return;
}
if (callback) {
callback(null);
}
});
});
});
},
clear: function (callback) {
var self = this;
async.parallel([
function (callback) {
self.client.del('nextItemId:' + self.options.prefix, callback);
},
function (callback) {
self.client.keys(self.options.prefix + ':*', function(err, keys) {
if (err) {
return callback(err);
}
async.each(keys, function (key, callback) {
self.client.del(key, callback);
}, callback);
});
}
], function (err) {
if (err) {
debug(err);
}
if (callback) callback(err);
});
}
});
module.exports = Redis;
|
/**
* https://github.com/shannonmoeller/gulp-hb
* @param gulp
* @param $
* @param config
* @returns {Function}
*/
module.exports = function (gulp, $, config) {
return function () {
$.handlebarsLayouts.register($.hb.handlebars);
// pass data from gulp.config.js to handlebar-templates
var templateData = {
title: config.meta.title,
jquery: config.js.jquery,
zepto: config.js.zepto,
modernizr: config.js.modernizr,
ogSite_name: config.meta.opengraph.site_name,
ogUrl: config.meta.opengraph.url,
ogDescription: config.meta.opengraph.description,
ogImage: config.meta.opengraph.image,
ogType: config.meta.opengraph.type,
ogLocale: config.meta.opengraph.locale,
twitter: config.meta.twitter.insert,
twitterTitle: config.meta.twitter.data.title,
twitterDescription: config.meta.twitter.data.description,
twitterCreator: config.meta.twitter.data.creator,
twitterUrl: config.meta.twitter.data.url,
twitterImage: config.meta.twitter.data.image
};
var hbStream = $.hb()
// Partials
.partials(config.pathSource + '/pages/partials/**/*.{hbs,js}')
// Helpers
.helpers(require('handlebars-layouts'))
.helpers(config.pathSource + '/pages/helpers/**/*.js')
// Data
.data(config.pathSource + '/data/**/*.{js,json}');
return gulp
// compile all .hbs files except for partials:
.src([config.pathSource + '/pages/**/*.hbs', '!' + config.pathSource + '/pages/partials/*.hbs', '!' + config.pathSource + '/pages/partials/components/*.hbs', '!' + config.pathSource + '/pages/partials/elements/*.hbs', '!' + config.pathSource + '/pages/partials/modules/*.hbs' ])
.pipe(hbStream)
// rename every file from hbs to html
.pipe($.rename({
extname: ".html"
}))
.pipe(gulp.dest(config.pathDist));
};
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.