code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
(function () { 'use strict'; angular.module('components.tabs') .component('tabs', { templateUrl: 'components/tabs/tabs.html', controller: 'TabsController', bindings: { classes: '@?', selected: '<?' }, transclude: true }) .component('tab', { templateUrl: 'components/tabs/tab.html', controller: 'TabController', bindings: { label: '@' }, require: { tabs: '^^' }, transclude: true }); })();
boozallen/projectjellyfish
app/assets/javascripts/app/components/tabs/tabs.component.js
JavaScript
apache-2.0
514
window.locales = window.locales || {}; window.locales["de"] = { _error_check: "muss sein", _error_unknown_locale: "unbekannte Sprache -> setze zurück auf standardmäßig vorgegebene Sprache:", _help_at_start_1: "Willkommen zu getstarted.js - entwickelt von @ThomasGreiner", _help_at_start_2: "Geben Sie einfach ein Kommando unterhalb ein, um die Grundlagen zu entdecken, was Sie mit JavaScript tun können.", _help_at_start_3: "Hier ist ein Beispiel, womit Sie sich das BODY Element holen können:", _help_at_start_4: "entdecken Sie alle Möglichkeiten hier:", _info_BODY: "das primäre Seitenelement", _info_different: "ein anderer Typ sein", _info_HTML: "die ganze Seite", _info_HTMLElement: "ein HTML Element (z.B. <b></b> oder <div></div>)", _info_IMG: "ein Bild Element", _info_NodeList: "eine Liste von HTML Elementen (z.B. <b></b> oder <div></div>)", _info_none: "(keine Beschreibung vorhanden für dieses Element)", _info_string: "Text", _msg_more: "das ist", hide_help_at_start: "verstecke_hilfe_beim_start", set_locale: "sprache_festlegen", about_getstarted: "ueber_getstarted", contact_developer: "entwickler_kontaktieren", show_examples: "beispiele_zeigen", add: "fuege_hinzu", and_create_new_element_to_page_that_is: "und_erstelle_neues_element_in_der_seite_vom_typ", existing_element_to_page: "vorhandenes_element_zur_seite", change: "aendere", class_of_element: "class_von_element", content_of: "inhalt_von", each_element: "jedem_element", element: "element", id_of_element: "id_von_element", name_of_element: "name_von_element", text: "text", visibility_of_element_to: "sichtbarkeit_von_element_zu", hidden: "versteckt", the_opposite: "gegenteil", visible: "sichtbar", find_out: "finde_heraus", if_text: "ob_text", contains: "enthaelt", ends_with: "endet_mit", starts_with:"beginnt_mit", more_about_element: "mehr_ueber_element", get: "hole", element_that: "element_mit", has_class: "class", has_id: "id", has_name: "name", is: "typ", elements_that: "elemente_mit", are: "typ", have_class: "class", have_name: "name", have_id: "id", entire_page: "ganze_seite", help: "hilfe", remove: "entferne", when: "wenn", element_is: "element_ist", clicked: "geklickt" }
ThomasGreiner/getstarted.js
_locales/de.js
JavaScript
artistic-2.0
2,357
//Convenient comparisons Compare = { Equal: function(o){ return o == this; }, StrictEqual: function(o){ return o === this; }, NotEqual: function(o){ return o != this; }, StrictNotEqual: function(o){ return o !== this; }, GreaterThan: function(o){ return o > this; }, GreaterThanOrEqual: function(o){ return o >= this; }, LessThan: function(o){ return o < this; }, LessThanOrEqual: function(o){ return o <= this; } } //Colour Colour.Clear = function(){ return new Colour(0, 0, 0, 0); }; Object.defineProperty(Colour.prototype, "hex", { get: function(){ return "#" + [this.r, this.g, this.b].map(function(c){ var h = Math.round(255 * c).toString(16); return h.length == 1 ? "0" + h : h; }).join(""); } }); Colour.prototype.opacity = function(a){ return new Colour(this.r, this.g, this.b, a); } function Colour(r, g, b, a) { this.r = r == undefined ? 0 : r; this.g = g == undefined ? 0 : g; this.b = b == undefined ? 0 : b; this.a = a == undefined ? 1 : a; } //Array Array.prototype.each = function(callback, args){ var array = this; for (var loop = 0, count = array.length; loop < count; loop++) { callback.apply(array[loop], args); } };
ScrimpyCat/SkateFinder
lib/assets/javascripts/common.js
JavaScript
bsd-2-clause
1,364
/** * Created by shuyi.wu on 2015/4/1. */ 'use strict'; var gulp = require('gulp'), uglify = require('gulp-uglify'), rename = require('gulp-rename'), del = require('del'), webpack = require('gulp-webpack'); gulp.task('compileES6', function () { return gulp.src('./assets/js-es6/functions.js') .pipe(webpack({ module: { loaders: [ {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'} ] } })) .pipe(rename('build.js')) .pipe(gulp.dest('./assets/js/')); }); gulp.task('watch-compileES6', function () { return gulp.src('./assets/js-es6/functions.js') .pipe(webpack({ watch: true, module: { loaders: [ {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'} ] } })) .pipe(rename('build.js')) .pipe(gulp.dest('./assets/js/')); }); gulp.task('min', ['compileES6'], function () { return gulp.src('./assets/js/build.js') .pipe(uglify()) .pipe(rename('build.min.js')) .pipe(gulp.dest('./assets/js/')); }); gulp.task('clean', function (cb) { del('./assets/js/**', cb); }); gulp.task('default', ['clean', 'min']);
wushuyi/CSSFilters
gulpfile.js
JavaScript
bsd-2-clause
1,314
var pyraminxHeuristic = null; var MIN_PYRAMINX_LENGTH = 6; var PYRAMINX_HEURISTIC_DEPTH = 7; function pyraminxState() { if (pyraminxHeuristic === null) { pyraminxHeuristic = new pyraminx.EdgesHeuristic(PYRAMINX_HEURISTIC_DEPTH); } while (true) { var solution = pyraminx.solve(pyraminx.randomState(), pyraminxHeuristic); if (solution.length < MIN_PYRAMINX_LENGTH) { continue; } var tipMoves = pyraminx.randomTipMoves(); var solutionStr = pyraminx.movesToString(solution); if (tipMoves !== '') { return solutionStr + ' ' + tipMoves; } else { return solutionStr; } } }
unixpickle/puzzle.js
scrambler/pyraminx.js
JavaScript
bsd-2-clause
629
var path = require("path"); module.exports = { mouseposition: path.join(__dirname, "web", "client", "examples", "mouseposition", "app"), scalebar: path.join(__dirname, "web", "client", "examples", "scalebar", "app"), layertree: path.join(__dirname, "web", "client", "examples", "layertree", "app"), "3dviewer": path.join(__dirname, "web", "client", "examples", "3dviewer", "app"), queryform: path.join(__dirname, "web", "client", "examples", "queryform", "app"), featuregrid: path.join(__dirname, "web", "client", "examples", "featuregrid", "app"), print: path.join(__dirname, "web", "client", "examples", "print", "app"), login: path.join(__dirname, "web", "client", "examples", "login", "app"), plugins: path.join(__dirname, "web", "client", "examples", "plugins", "app"), rasterstyler: path.join(__dirname, "web", "client", "examples", "rasterstyler", "app") // this example is not linked and seems to cause a big slow down with uglyfyplugin. disabled temporary // styler: path.join(__dirname, "web", "client", "examples", "styler", "app") };
nmco/MapStore2
examples.js
JavaScript
bsd-2-clause
1,095
/** * @module ol/control/Zoom */ import {inherits} from '../index.js'; import {listen} from '../events.js'; import EventType from '../events/EventType.js'; import Control from '../control/Control.js'; import {CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js'; import {easeOut} from '../easing.js'; /** * @typedef {Object} Options * @property {number} [duration=250] Animation duration in milliseconds. * @property {string} [className='ol-zoom'] CSS class name. * @property {string|Element} [zoomInLabel='+'] Text label to use for the zoom-in * button. Instead of text, also an element (e.g. a `span` element) can be used. * @property {string|Element} [zoomOutLabel='-'] Text label to use for the zoom-out button. * Instead of text, also an element (e.g. a `span` element) can be used. * @property {string} [zoomInTipLabel='Zoom in'] Text label to use for the button tip. * @property {string} [zoomOutTipLabel='Zoom out'] Text label to use for the button tip. * @property {number} [delta=1] The zoom delta applied on each click. * @property {Element|string} [target] Specify a target if you want the control to be * rendered outside of the map's viewport. */ /** * @classdesc * A control with 2 buttons, one for zoom in and one for zoom out. * This control is one of the default controls of a map. To style this control * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. * * @constructor * @extends {ol.control.Control} * @param {module:ol/control/Zoom~Options=} opt_options Zoom options. * @api */ const Zoom = function(opt_options) { const options = opt_options ? opt_options : {}; const className = options.className !== undefined ? options.className : 'ol-zoom'; const delta = options.delta !== undefined ? options.delta : 1; const zoomInLabel = options.zoomInLabel !== undefined ? options.zoomInLabel : '+'; const zoomOutLabel = options.zoomOutLabel !== undefined ? options.zoomOutLabel : '\u2212'; const zoomInTipLabel = options.zoomInTipLabel !== undefined ? options.zoomInTipLabel : 'Zoom in'; const zoomOutTipLabel = options.zoomOutTipLabel !== undefined ? options.zoomOutTipLabel : 'Zoom out'; const inElement = document.createElement('button'); inElement.className = className + '-in'; inElement.setAttribute('type', 'button'); inElement.title = zoomInTipLabel; inElement.appendChild( typeof zoomInLabel === 'string' ? document.createTextNode(zoomInLabel) : zoomInLabel ); listen(inElement, EventType.CLICK, Zoom.prototype.handleClick_.bind(this, delta)); const outElement = document.createElement('button'); outElement.className = className + '-out'; outElement.setAttribute('type', 'button'); outElement.title = zoomOutTipLabel; outElement.appendChild( typeof zoomOutLabel === 'string' ? document.createTextNode(zoomOutLabel) : zoomOutLabel ); listen(outElement, EventType.CLICK, Zoom.prototype.handleClick_.bind(this, -delta)); const cssClasses = className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL; const element = document.createElement('div'); element.className = cssClasses; element.appendChild(inElement); element.appendChild(outElement); Control.call(this, { element: element, target: options.target }); /** * @type {number} * @private */ this.duration_ = options.duration !== undefined ? options.duration : 250; }; inherits(Zoom, Control); /** * @param {number} delta Zoom delta. * @param {Event} event The event to handle * @private */ Zoom.prototype.handleClick_ = function(delta, event) { event.preventDefault(); this.zoomByDelta_(delta); }; /** * @param {number} delta Zoom delta. * @private */ Zoom.prototype.zoomByDelta_ = function(delta) { const map = this.getMap(); const view = map.getView(); if (!view) { // the map does not have a view, so we can't act // upon it return; } const currentResolution = view.getResolution(); if (currentResolution) { const newResolution = view.constrainResolution(currentResolution, delta); if (this.duration_ > 0) { if (view.getAnimating()) { view.cancelAnimations(); } view.animate({ resolution: newResolution, duration: this.duration_, easing: easeOut }); } else { view.setResolution(newResolution); } } }; export default Zoom;
gingerik/ol3
src/ol/control/Zoom.js
JavaScript
bsd-2-clause
4,367
import $ from '../core'; import { userAgent } from '../../common/navigator'; $.os = (() => { const match = userAgent.match($.regexp.os); const mobile = (/mobile/i).test(userAgent); const os = RegExp.$1.toLowerCase(); if($.device.idevice){ return 'ios'; } if(os === 'blackberry' && mobile){ return 'bbmobile'; } if(os === 'macintosh'){ return 'osx'; } return os; })(); export default $;
dysfunc/eleven
src/query/support/os.js
JavaScript
bsd-2-clause
424
// This file was procedurally generated from the following sources: // - src/dstr-assignment/obj-id-init-assignment-missing.case // - src/dstr-assignment/default/assignment-expr.template /*--- description: If the Initializer is present and v is undefined, the Initializer should be evaluated and the result assigned to the target reference (no corresponding property defined). (AssignmentExpression) esid: sec-variable-statement-runtime-semantics-evaluation es6id: 13.3.2.4 features: [destructuring-binding] flags: [generated] info: | VariableDeclaration : BindingPattern Initializer 1. Let rhs be the result of evaluating Initializer. 2. Let rval be GetValue(rhs). 3. ReturnIfAbrupt(rval). 4. Return the result of performing BindingInitialization for BindingPattern passing rval and undefined as arguments. ---*/ var x; var result; var vals = {}; result = { x = 1 } = vals; assert.sameValue(x, 1); assert.sameValue(result, vals);
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/assignment/dstr-obj-id-init-assignment-missing.js
JavaScript
bsd-2-clause
963
var assert = require("should"); var exec = require('child_process').exec; var restify = require('restify'); var boplishHost = exec(__dirname + '/../run.js --bootstrap ws://chris.ac:5000 --port 10000', function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); describe('BOPlish Emulation Host test', function() { this.timeout(5000); var restClient; it('should create client', function() { restClient = restify.createJsonClient({ url: 'http://localhost:10000', version: '*' }); }); var peerId; it('should start Peer', function(done) { restClient.post('/peer', function(err, req, res, obj) { assert.ifError(err); peerId = obj.id; peerId.should.not.be.empty; done(); }); }); it('should list Peer Ids Peer', function(done) { restClient.get('/peers', function(err, req, res, obj) { assert.ifError(err); obj.should.containEql(peerId); done(); }); }); it('should get Peer status', function(done) { restClient.get('/peer' + '/' + peerId, function(err, req, res, obj) { assert.ifError(err); obj.id.should.not.be.empty; obj.started.should.not.be.empty; obj.bootstrapNode.should.not.be.empty; done(); }); }); it('should stop Peer', function(done) { restClient.del('/peer' + '/' + peerId, function(err, req, res, obj) { assert.ifError(err); obj.id.should.not.be.empty; obj.status.should.equal('killed'); done(); }); }); it('should stop all Peers', function(done) { var peerId1, peerId2; restClient.post('/peer', function(err, req, res, obj) { assert.ifError(err); peerId1 = obj.id; restClient.post('/peer', function(err, req, res, obj) { assert.ifError(err); peerId2 = obj.id; restClient.del('/killAll', function(err, req, res, obj) { restClient.get('/listAllIds', function(err, req, res, obj) { assert.ifError(err); obj.should.be.empty; done(); }); }); }); }); }); it('should get Host status', function(done) { restClient.get('/status', function(err, req, res, obj) { assert.ifError(err); obj.startDate.should.not.be.empty; obj.bootstrapNode.should.not.be.empty; obj.numberOfPeers.should.equal(0); done(); }); }); it('should request log handler'); after(function() { boplishHost.kill(); }); });
boplish/node-client
test/test.js
JavaScript
bsd-2-clause
2,382
// Copyright (c) 2016, Matt Godbolt // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. const BaseCompiler = require('../base-compiler'), _ = require('underscore'), path = require('path'), argumentParsers = require("./argument-parsers"); class RustCompiler extends BaseCompiler { constructor(info, env) { super(info, env); this.compiler.supportsIntel = true; this.compiler.supportsIrView = true; this.compiler.irArg = ['--emit', 'llvm-ir']; } getSharedLibraryPathsAsArguments() { return []; } optionsForFilter(filters, outputFilename, userOptions) { let options = ['-C', 'debuginfo=1', '-o', this.filename(outputFilename)]; let userRequestedEmit = _.any(userOptions, opt => opt.indexOf("--emit") > -1); //TODO: Binary not supported (?) if (!filters.binary) { if (!userRequestedEmit) { options = options.concat('--emit', 'asm'); } if (filters.intel) options = options.concat('-Cllvm-args=--x86-asm-syntax=intel'); } options = options.concat(['--crate-type', 'rlib']); return options; } // Override the IR file name method for rustc because the output file is different from clang. getIrOutputFilename(inputFilename) { return this.getOutputFilename(path.dirname(inputFilename), this.outputFilebase) .replace('.s', '.ll'); } getArgumentParser() { return argumentParsers.Rust; } isCfgCompiler(/*compilerVersion*/) { return true; } } module.exports = RustCompiler;
mattgodbolt/compiler-explorer
lib/compilers/rust.js
JavaScript
bsd-2-clause
2,909
/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Version 3.0.0 */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else { // Browser globals factory(jQuery); } }(function ($) { $.fn.bgiframe = function(s) { s = $.extend({ top : 'auto', // auto == borderTopWidth left : 'auto', // auto == borderLeftWidth width : 'auto', // auto == offsetWidth height : 'auto', // auto == offsetHeight opacity : true, src : 'javascript:false;', conditional : /MSIE 6.0/.test(navigator.userAgent) // expresion or function. return false to prevent iframe insertion }, s); // wrap conditional in a function if it isn't already if (!$.isFunction(s.conditional)) { var condition = s.conditional; s.conditional = function() { return condition; }; } var $iframe = $('<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+ 'style="display:block;position:absolute;z-index:-1;"/>'); return this.each(function() { var $this = $(this); if ( s.conditional(this) === false ) { return; } var existing = $this.children('iframe.bgiframe'); var $el = existing.length === 0 ? $iframe.clone() : existing; $el.css({ 'top': s.top == 'auto' ? ((parseInt($this.css('borderTopWidth'),10)||0)*-1)+'px' : prop(s.top), 'left': s.left == 'auto' ? ((parseInt($this.css('borderLeftWidth'),10)||0)*-1)+'px' : prop(s.left), 'width': s.width == 'auto' ? (this.offsetWidth + 'px') : prop(s.width), 'height': s.height == 'auto' ? (this.offsetHeight + 'px') : prop(s.height), 'opacity': s.opacity === true ? 0 : undefined }); if ( existing.length === 0 ) { $this.prepend($el); } }); }; // old alias $.fn.bgIframe = $.fn.bgiframe; function prop(n) { return n && n.constructor === Number ? n + 'px' : n; } }));
yeatmanlab/OsREAD
classes/artifacts/AppForLiteracy/exploded/AppForLiteracy-0.1.war/assets/jquery/jquery.bgiframe.unminified.js
JavaScript
bsd-2-clause
2,388
Clazz.declarePackage ("J.shape"); Clazz.load (["J.shape.AtomShape"], "J.shape.Halos", ["JU.BSUtil", "$.C"], function () { c$ = Clazz.decorateAsClass (function () { this.colixSelection = 2; this.bsHighlight = null; this.colixHighlight = 10; Clazz.instantialize (this, arguments); }, J.shape, "Halos", J.shape.AtomShape); Clazz.defineMethod (c$, "initState", function () { this.translucentAllowed = false; }); Clazz.overrideMethod (c$, "setProperty", function (propertyName, value, bs) { if ("translucency" === propertyName) return; if ("argbSelection" === propertyName) { this.colixSelection = JU.C.getColix ((value).intValue ()); return; }if ("argbHighlight" === propertyName) { this.colixHighlight = JU.C.getColix ((value).intValue ()); return; }if ("highlight" === propertyName) { this.bsHighlight = value; return; }if (propertyName === "deleteModelAtoms") { JU.BSUtil.deleteBits (this.bsHighlight, bs); }this.setPropAS (propertyName, value, bs); }, "~S,~O,JU.BS"); Clazz.overrideMethod (c$, "setModelVisibilityFlags", function (bs) { var bsSelected = (this.vwr.getSelectionHaloEnabled (false) ? this.vwr.bsA () : null); for (var i = this.ac; --i >= 0; ) { var isVisible = bsSelected != null && bsSelected.get (i) || (this.mads != null && this.mads[i] != 0); this.setShapeVisibility (this.atoms[i], isVisible); } }, "JU.BS"); Clazz.overrideMethod (c$, "getShapeState", function () { return this.vwr.getShapeState (this); }); });
bas-rustenburg/jsmol-local
j2s/J/shape/Halos.js
JavaScript
bsd-2-clause
1,435
(function(){ var b_prepared = false; var prep_pos = { x: 0, y: 0 }; var b_dragging = false; var current_params = {}; var current_element = false; var placeholder = false; var old_style = {}; var drag_offset = { x: 0, y: 0 }; glyph.dragInit = function( container, params ) { if ( !container ) return; if ( typeof container == 'string' ) container = glyph.id( container ); if ( !params ) params = {}; params.group = params.group || ''; params.templates = params.templates || false; params.axis = params.axis || 'both'; container.dragparams = params; }; glyph.ready( function() { var draggable = glyph.sel( '.glyph_draggable' ); for ( var i = 0; i < draggable.length; i++ ) { var params = draggable[i].getAttribute( 'glyph-dragparams' ); if ( params ) params = eval( '(' + params + ')' ); glyph.dragInit( draggable[i], params ); } }); function dragMouseMove( e ) { if ( e.button !== 0 ) return; if ( b_prepared ) { if ( current_params.safezone ) if ( glyph.mouseDist( prep_pos ) < current_params.safezone ) return; b_prepared = false; b_dragging = true; var el = current_element; if ( current_params.templates ) { current_element = el.cloneNode( true ); el.parentNode.appendChild( current_element ); } drag_offset.x = glyph.mousePos.x - glyph.bounds( el ).left; drag_offset.y = glyph.mousePos.y - glyph.bounds( el ).top; old_style.width = current_element.style.width || ''; old_style.height = current_element.style.height || ''; current_element.style.width = glyph.bounds( el ).width + 'px'; current_element.style.height = glyph.bounds( el ).height + 'px'; placeholder = el.cloneNode( true ); glyph.addClass( placeholder, 'glyph_drag-placeholder' ); glyph.insertAfter( placeholder, el ); old_style.position = current_element.style.position || ''; old_style.left = current_element.style.left || ''; old_style.top = current_element.style.top || ''; old_style.zIndex = current_element.style.zIndex || ''; current_element.style.position = 'absolute'; current_element.style.zIndex = '999'; glyph.addClass( current_element, 'glyph_drag-active' ); } if ( b_dragging ) { window.getSelection().removeAllRanges(); var axis = current_params.axis; if ( axis == 'both' || axis == 'x' ) current_element.style.left = glyph.mousePos.x - drag_offset.x + glyph.pageScroll().left + 'px'; if ( axis == 'both' || axis == 'y' ) current_element.style.top = glyph.mousePos.y - drag_offset.y + glyph.pageScroll().top + 'px'; var pos = glyph.mousePos; if ( axis == 'x' ) pos.y = glyph.offset( current_element ).top + current_element.offsetHeight / 2; if ( axis == 'y' ) pos.x = glyph.offset( current_element ).left + current_element.offsetWidth / 2; glyph.forEach( glyph.sel('.glyph_draggable'), function( group, j ) { if ( group.dragparams.group != current_params.group ) return; if ( !glyph.isUnderPos( group, pos ) ) return; glyph.forEach( group.children, function( el, i ) { if ( el == current_element || el == placeholder ) return; if ( glyph.hasClass( el, 'glyph_drag-frozen' ) ) return; if ( glyph.isUnderPos( el, pos ) ) { var mouseOffset = glyph.mouseOffset( el ); var scootXa = mouseOffset.x < el.offsetWidth / 2; var scootXb = mouseOffset.x > el.offsetWidth - el.offsetWidth / 2; var scootYa = mouseOffset.y < el.offsetHeight / 2; var scootYb = mouseOffset.y > el.offsetHeight - el.offsetHeight / 2; if ( glyph.hasClass( el, 'glyph_drag-lockbottom' ) ) { if ( scootYa ) scootYb = true; if ( scootXa ) scootXb = true; scootYa = false; scootXa = false; } if ( glyph.hasClass( el, 'glyph_drag-locktop' ) ) { if ( scootYb ) scootYa = true; if ( scootXb ) scootXa = true; scootYb = false; scootXb = false; } if ( axis == 'both' || axis == 'x' ) { if ( scootXa ) glyph.insertAfter( placeholder, el ); else if ( scootXb ) glyph.insertBefore( placeholder, el ); } else if ( axis == 'both' || axis == 'y' ) { if ( scootYa ) glyph.insertAfter( placeholder, el ); else if ( scootYb ) glyph.insertBefore( placeholder, el ); } return; } } ); } ); } } glyph.event( window, 'mousemove', dragMouseMove ); function dragMouseDown( e ) { if ( e.button !== 0 ) return; if ( b_dragging ) return; var el = e.target; var parentMatch = glyph.matchParents( el, '.glyph_draggable' ); if ( parentMatch !== false ) { var match = glyph.matchParents( el, '.glyph_draggable', -1 ); if ( !glyph.matches( match, '.glyph_drag-disabled' ) ) { b_prepared = true; prep_pos = glyph.mousePos; current_element = match; current_params = parentMatch.dragparams; } } } glyph.event( window, 'mousedown', dragMouseDown ); function dragMouseUp( e ) { if ( e.button !== 0 ) return; if ( b_prepared ) b_prepared = false; if ( b_dragging ) { b_prepared = false; b_dragging = false; current_element.style.width = old_style.width; current_element.style.height = old_style.height; current_element.style.position = old_style.position; current_element.style.left = old_style.left; current_element.style.top = old_style.top; current_element.style.zIndex = old_style.zIndex; glyph.removeClass( current_element, 'glyph_drag-active' ); glyph.insertAfter( current_element, placeholder ); glyph.remove( placeholder ); } } glyph.event( window, 'mouseup', dragMouseUp ); }());
DougTy/glyph
src/glyph/tools/drag-n-drop.js
JavaScript
bsd-2-clause
5,652
// This file was procedurally generated from the following sources: // - src/spread/sngl-err-obj-unresolvable.case // - src/spread/error/array.template /*--- description: Object Spread operator results in error when using an unresolvable reference (Array initializer) esid: sec-runtime-semantics-arrayaccumulation es6id: 12.2.5.2 features: [object-spread] flags: [generated] info: | SpreadElement : ...AssignmentExpression 1. Let spreadRef be the result of evaluating AssignmentExpression. 2. Let spreadObj be ? GetValue(spreadRef). 3. Let iterator be ? GetIterator(spreadObj). 4. Repeat a. Let next be ? IteratorStep(iterator). b. If next is false, return nextIndex. c. Let nextValue be ? IteratorValue(next). d. Let status be CreateDataProperty(array, ToString(ToUint32(nextIndex)), nextValue). e. Assert: status is true. f. Let nextIndex be nextIndex + 1. Pending Runtime Semantics: PropertyDefinitionEvaluation PropertyDefinition:...AssignmentExpression 1. Let exprValue be the result of evaluating AssignmentExpression. 2. Let fromValue be GetValue(exprValue). 3. ReturnIfAbrupt(fromValue). 4. Let excludedNames be a new empty List. 5. Return CopyDataProperties(object, fromValue, excludedNames). ---*/ assert.throws(ReferenceError, function() { [{...unresolvableReference}]; });
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/array/spread-err-sngl-err-obj-unresolvable.js
JavaScript
bsd-2-clause
1,393
//index.js //获取应用实例 let User = new wx.BaaS.TableObject(1997) let user = User.create() var query = new wx.BaaS.Query() var app = getApp() Page({ data: { motto: 'Hello World', userInfo: {}, pages: [ 'logs', 'weatherDemo', 'calculatorDemo', 'moviesDemo', 'articlesDemo', ], user }, //事件处理函数 bindPageViewTap: function(e) { let page = e.currentTarget.dataset.page wx.navigateTo({ url: `../${page}/${page}` }) }, fetchUserId: function(openid) { query.compare('openid', '=', openid) User.setQuery(query).find().then( (res) => { let objects = res.objects let total = res.meta.total_count console.log(res) console.log('fetchUserId: ', undefined ? total === 0 : objects[0]._id) if(total === 0) { console.log('need save') } else if(total === 1) { return objects[0].openid } else { // error return null } }, (err) => { console.log(err) return null }) }, saveUserInfo: function(openid) { let userData = { openid: openid } user.set(userData).save().then( (res) => { console.log('saved......... user data') }, (err) => { console.log('failed.........') }) }, onLoad: function () { console.log('onLoad') var that = this //调用应用实例的方法获取全局数据 app.getUserInfo(function(userInfo){ //更新数据 that.setData({ userInfo:userInfo }) that.saveUserInfo(userInfo.openid) }) }, })
sharkspeed/dororis
platforms/weixin/miniapp/miniapp_1_minapp/firstApp/pages/index/index.js
JavaScript
bsd-2-clause
1,608
/* * These two features seemed out of place everywhere else so I stuck them in here. * My plan is for UI.js to manage further user interaction * I'm going to incorporate sliders to customize visualizations in real time */ // called when play button overlay is clicked; plays audio+runs render() var play = function() { $(document.getElementById('play')).fadeOut('normal', function() { $(this).remove(); }); // starts the audio source.start(0); /** onAudio(callback) ** callback() : audio-sensitive visualizer data ** @array : frequency data array ** @boost : data array scalar ** @newData : alerts render() to new data */ onAudio(function(array, boost){ render.array = array; render.boost = boost; render.newData = true; }); render(); }; var onAudio = function(cb){ sourceJs.onaudioprocess = function(e) { var array = new Uint8Array(analyser.frequencyBinCount); analyser.getByteFrequencyData(array); var boost = 0; for (var i = 0; i < array.length; i++) { boost += array[i]; } boost = boost/ array.length; if(cb && boost>.1) cb(array, boost); }; };
DodekaHydra/arcane.gl
js/src/UI.js
JavaScript
bsd-2-clause
1,232
"use strict"; /** * @var jaegerhut [Object] Badge icons, one for each policy */ const jaegerhut = { 0: { name: "allowall", colour: "#D84A4A", text: chrome.i18n.getMessage("policyAllowAll") }, 1: { name: "relaxed", colour: "#559FE6", text: chrome.i18n.getMessage("policyRelaxed") }, 2: { name: "filtered", colour: "#73AB55", text: chrome.i18n.getMessage("policyFiltered") }, 3: { name: "blockall", colour: "#26272A", text: chrome.i18n.getMessage("policyBlockAll") }, undefined: { name: "undefined", colour: "#6F7072" } }; /** * @var tabInfo [Object] Holds data about the tab * obtained from the background process */ let tabInfo = {}; /** * @var port [Object] A connection Port that allows message exchanging */ let port; /* * Basic nodes for building the interface */ const nodeHost = document.createElement("div"); const nodeCheckbox = document.createElement("input"); const nodeDetails = document.createElement("label"); const nodeWebsocket = document.createElement("div"); const nodeFrames = document.createElement("div"); const nodeSubdomain = document.createElement("span"); const nodeDomain = document.createElement("span"); const nodeNumber = document.createElement("label"); const nodeResource = document.createElement("a"); const nodeHostsList = document.createElement("div"); nodeHost.className = "host blocked"; nodeDetails.className = "details"; nodeWebsocket.className = "websocket"; nodeFrames.className = "frames"; nodeSubdomain.className = "subdomain"; nodeDomain.className = "domain"; nodeNumber.className = "number"; nodeResource.className = "resource"; nodeHostsList.className = "hosts"; nodeHostsList.id = "f0"; nodeCheckbox.type = "checkbox"; nodeNumber.title = chrome.i18n.getMessage("seeResources"); nodeResource.target = "_blank"; /** * @brief Set and save an exception rule for that script * * Fired whenever the user changes the checkbox of a rule. * This will set and save the rule according to what the * user has chosen. * * @param e [Event] Event interface on the checkbox change event */ function setScriptRule(e) { const input = e.target; let info = tabInfo; const frameID = parseInt(input.dataset.frameid, 10); if (frameID > 0) { info = tabInfo.frames[frameID]; } const msg = { type: 0, private: tabInfo.private, site: [], rule: {} }; switch (parseInt(document.getElementById("settings").dataset.scope, 10)) { // page case 3: msg.site[2] = info.page; // site - fallthrough case 2: msg.site[1] = info.subdomain; // domain - fallthrough case 1: msg.site[0] = info.domain; // global - fallthrough default: } const domain = input.dataset.domain; const subdomain = input.dataset.subdomain; msg.rule[domain] = { rule: null, urls: {} }; msg.rule[domain].urls[subdomain] = { // in the DOM true means checked which means allow // in the settings true means block rule: !input.checked, urls: {} }; // The background script deals with it because the popup process will die on close port.postMessage(msg); } /** * @brief Open dropdown to choose frame policy * * Opens an overlay div to choose a new policy for a frame. * This is fired when clicking on a hat (Jaegerhut) * * @param e [Event] Event interface on the clicked Jaegerhut */ function openFramePolicy(e) { const frameid = e.target.parentNode.dataset.frameid; const policy = parseInt(e.target.dataset.policy, 10); const dropdown = document.getElementById("frame-edit"); const pos = e.target.getBoundingClientRect().y - 30; dropdown.dataset.frameid = frameid; dropdown.dataset.hidden = false; dropdown.style = `top:${pos}px`; dropdown.dataset.scope = 1; dropdown.dataset.policy = policy; } /** * @brief Close frame policy dropdown * * Closes the overlay div where you choose a new policy for a frame. */ function closeFramePolicy() { document.getElementById("frame-edit").dataset.hidden = true; } /** * @brief Build resource list in the DOM * * Injects nodes to display the list of resources that the page * contains. Also attaches events to the elements to allow * manipulation of the settings. * * @param frameid [Number] id of the frame being built */ function buildList(frameID) { const elemMainNode = document.getElementById(`f${frameID}`); let frame = tabInfo; if (frameID > 0) { frame = tabInfo.frames[frameID]; } Object.entries(frame.scripts).sort().forEach((domainData) => { const domain = domainData[0]; Object.entries(domainData[1]).sort().forEach((subdomainData) => { const subdomain = subdomainData[0]; const resources = subdomainData[1]; const elemHost = nodeHost.cloneNode(false); const elemCheckbox = nodeCheckbox.cloneNode(false); const elemDetails = nodeDetails.cloneNode(false); const elemWebsocket = nodeWebsocket.cloneNode(false); const elemFrames = nodeFrames.cloneNode(false); const elemSubdomain = nodeSubdomain.cloneNode(false); const elemDomain = nodeDomain.cloneNode(false); const elemNumber = nodeNumber.cloneNode(false); elemDetails.appendChild(elemWebsocket); elemDetails.appendChild(elemFrames); elemDetails.appendChild(elemSubdomain); elemDetails.appendChild(elemDomain); elemHost.appendChild(elemCheckbox); elemHost.appendChild(elemDetails); elemHost.appendChild(elemNumber); elemMainNode.appendChild(elemHost); const hostID = `${subdomain}${domain}${frameID}`; elemCheckbox.id = hostID; elemDetails.htmlFor = hostID; elemSubdomain.innerHTML = `<span>${subdomain}${((subdomain.length > 0) ? "." : "")}</span>`; elemDomain.innerHTML = `<span>${domain}</span>`; elemNumber.innerText = resources.length; // if the text is larger than the area, we display a tooltip if (elemSubdomain.scrollWidth > elemSubdomain.clientWidth || elemDomain.scrollWidth > elemDomain.clientWidth) { elemHost.title = `${elemSubdomain.textContent}${domain}`; } // save script exception elemCheckbox.addEventListener("change", setScriptRule, false); // add data to checkbox elemCheckbox.dataset.frameid = frameID; elemCheckbox.dataset.domain = domain; elemCheckbox.dataset.subdomain = subdomain; // input that controls the script list visibility const openList = nodeCheckbox.cloneNode(false); openList.id = `list_${hostID}`; elemNumber.htmlFor = `list_${hostID}`; elemMainNode.appendChild(openList); // element that holds the list of elements from that host const resourcesList = document.createElement("div"); resourcesList.className = "resources"; elemMainNode.appendChild(resourcesList); let frames = 0; let websockets = 0; // populate scripts list // script can be a websocket or frame resources.forEach((script) => { if (!script.blocked) { elemCheckbox.checked = true; // remove blocked class elemHost.className = "host"; } const url = `${script.protocol}${elemSubdomain.textContent}${domain}${script.name}${script.query}`; const elemResource = nodeResource.cloneNode(false); elemResource.innerText = script.name.match(/[^/]*.$/); elemResource.title = url; elemResource.href = url; // websocket if (script.protocol === "wss://" || script.protocol === "ws://") { elemResource.className = "resource haswebsocket"; elemWebsocket.className = "websocket haswebsocket"; elemWebsocket.title = `\n${chrome.i18n.getMessage("tooltipWebsockets", (++websockets).toString())}`; } // if frameid exists it's a frame // otherwise it's a normal script/websocket if (script.frameid === undefined) { resourcesList.appendChild(elemResource); } else { const policy = jaegerhut[tabInfo.frames[script.frameid].policy]; const elemFrameDiv = document.createElement("div"); elemFrameDiv.className = "frame"; elemFrameDiv.dataset.frameid = script.frameid; elemFrames.className = "frames hasframe"; elemFrames.title = chrome.i18n.getMessage("tooltipFrames", (++frames).toString()); const elemPolicy = document.createElement("img"); elemPolicy.src = `/images/${policy.name}38.png`; elemPolicy.className = "frame-policy"; elemPolicy.title = policy.text; elemPolicy.dataset.policy = tabInfo.frames[script.frameid].policy; elemPolicy.addEventListener("click", openFramePolicy); const elemNumberFrame = nodeNumber.cloneNode(false); elemNumberFrame.htmlFor = `frame${script.frameid}`; elemNumberFrame.innerText = Object.keys(tabInfo.frames[script.frameid].scripts).length; elemFrameDiv.appendChild(elemPolicy); elemFrameDiv.appendChild(elemResource); elemFrameDiv.appendChild(elemNumberFrame); resourcesList.appendChild(elemFrameDiv); const elemCheckboxFrame = nodeCheckbox.cloneNode(false); elemCheckboxFrame.id = `frame${script.frameid}`; resourcesList.appendChild(elemCheckboxFrame); const resourcesListFrame = document.createElement("div"); resourcesListFrame.className = `resources ${policy.name}`; resourcesListFrame.id = `f${script.frameid}`; resourcesList.appendChild(resourcesListFrame); buildList(script.frameid); } elemFrames.title = `${elemFrames.title}${elemWebsocket.title}`; }); }); }); } /** * @brief Sets and build the popup UI * * Define main classes and then call the script list builder. */ function startUI() { const error = document.getElementById("error"); const settings = document.getElementById("settings"); settings.replaceChild(nodeHostsList.cloneNode(false), document.getElementById("f0")); settings.removeAttribute("hidden"); error.hidden = true; const blocked = tabInfo.policy ? tabInfo.allowonce ? "(T) " : `(${tabInfo.blocked}) ` : ""; document.title = `${blocked}ScriptJäger`; document.getElementById("jaegerhut").href = `images/${jaegerhut[tabInfo.policy].name}38.png`; document.getElementById("jaegerfarbe").content = jaegerhut[tabInfo.policy].colour; let skip = false; switch (tabInfo.protocol) { case "https://": case "http://": break; case "chrome://": case "chrome-extension://": skip = "errorInternal"; break; case "file://": if (!tabInfo.policy) { skip = "errorFile"; } break; default: skip = "errorInternal"; } document.body.className = jaegerhut[tabInfo.policy].name; if (skip !== false) { error.innerText = chrome.i18n.getMessage(skip); error.removeAttribute("hidden"); settings.hidden = true; return; } // policy button reflects current policy settings.dataset.policy = tabInfo.policy; const allowonce = document.getElementById("allowonce"); // Allow once is turned on if (tabInfo.allowonce === true) { allowonce.title = chrome.i18n.getMessage("policyAllowOnceDisable"); allowonce.className = "allowonce"; } // Allow once is turned off else { allowonce.title = chrome.i18n.getMessage("policyAllowOnce"); allowonce.className = ""; } buildList(0); } /** * @brief Get info about tab * * When opening the popup we request the info about the * page scripts and create the DOM nodes with this info * * @param tabs [Array] Contains info about the current tab */ chrome.tabs.query({currentWindow: true, active: true}, (tabs) => { port = chrome.runtime.connect({name: tabs[0].id.toString(10)}); /** * @brief Perform actions acording to message * * The background script will send the info we need * * Child 'type' will contain the type of the request * * @param msg [Object] Contains type and data for the action * * @note Each request has different msg children/info * * 0 (Re)Build UI - Whenever the UI has to be completely updated * - data [Object] Tab info, a children of background tabStorage * * 1 Update interface * * 2 Response of allowed/blocked list for relaxed/filtered * - tabid [Number] id of the requested tab * - scripts [Array] Contains the url and the rule * - name [String] DOM ID of the script * - blocked [Boolean] Whether that level will be blocked */ port.onMessage.addListener((msg) => { console.log(msg); if (msg.type === 0) { // save tab info in variable tabInfo = msg.data; startUI(); return; } if (msg.type === 1) { return; } // msg.type === 2 // check if the user has not changed tab if (msg.tabid === tabInfo.tabid) { msg.scripts.forEach((domain) => { document.getElementById(domain.name).checked = !domain.blocked; }); } }); }); /** * @brief Save new policy * * Send to background process to save new policy for the specific scope * * @param policy [Number] Policy to save * @param scope [Number] Where to change rule, e.g. domain, global * @param frameid [Number] Frame where the policy change is being done */ function changePolicy(policy, scope, frameid) { const msg = { type: 0, private: tabInfo.private, site: [], rule: policy }; let frame = tabInfo; if (frameid > 0) { frame = tabInfo.frames[frameid]; } switch (scope) { // page case 3: msg.site[2] = frame.page; // site - fallthrough case 2: msg.site[1] = frame.subdomain; // domain - fallthrough case 1: msg.site[0] = frame.domain; // global - fallthrough default: } port.postMessage(msg); } /** * @brief Enable listeners when the DOM has loaded * * When the DOM is loaded we can attach the events to manipulate * the preferences. */ function enableListeners() { document.getElementById("settings").addEventListener("click", closeFramePolicy, true); document.getElementById("cancel").addEventListener("click", closeFramePolicy); document.getElementById("preferences").addEventListener("click", (e) => { e.stopPropagation(); chrome.runtime.openOptionsPage(); }); // allow once document.getElementById("allowonce").addEventListener("click", (e) => { e.stopPropagation(); port.postMessage({ type: 1, tabId: tabInfo.tabid, allow: !tabInfo.allowonce }); }); document.querySelectorAll(".scopes").forEach((scopes) => { scopes.addEventListener("click", (e) => { e.target.parentNode.parentNode.dataset.scope = e.target.dataset.value; }); }); document.querySelectorAll(".policies").forEach((policies) => { policies.addEventListener("click", (e) => { const target = (e.target.tagName === "IMG") ? e.target.parentNode : e.target; const frame = target.parentNode.parentNode.dataset; const policy = parseInt(target.dataset.value, 10); const scope = parseInt(frame.scope, 10); frame.policy = policy; changePolicy(policy, scope, frame.frameid); if (frame.frameid > 0) { document.getElementById(`f${frame.frameid}`).className = `resources ${jaegerhut[frame.policy].name}`; } else { document.body.className = jaegerhut[frame.policy].name; } // change all inputs to checked (allowed) or unchecked (blocked) if (policy === 0 || policy === 3) { document.querySelectorAll(`#f${frame.frameid} > .script > input`).forEach((checkbox) => { checkbox.checked = !policy; }); return; } // request list of blocked and allowed scripts from background script port.postMessage({ type: 2, policy: policy, tabid: tabInfo.tabid, frameid: frame.frameid, window: tabInfo.window, }); }); }); } /** * @brief Translate and attach events * * This will translate the page and attach the events to the nodes. */ document.addEventListener("DOMContentLoaded", () => { const template = document.body.innerHTML; // translate the page document.body.innerHTML = template.replace(/__MSG_(\w+)__/g, (a, b) => { return chrome.i18n.getMessage(b); }); // allow resizable width on webpanel if (document.location.search === "?webpanel") { document.body.style = "width: 100%"; } enableListeners(); });
An-dz/ScriptJaeger
popup.js
JavaScript
bsd-2-clause
15,799
var struct_grape_f_s_1_1___performance_operation = [ [ "_PerformanceOperation", "struct_grape_f_s_1_1___performance_operation.html#a9251cc499a0ab5c9d2fe2762ca2eb7a2", null ], [ "FillProc", "struct_grape_f_s_1_1___performance_operation.html#ac8a4badb2cb3594ba22870efc8d68434", null ], [ "ToString", "struct_grape_f_s_1_1___performance_operation.html#a742c658271c3f69f124539db6e0c3f89", null ], [ "ToString", "struct_grape_f_s_1_1___performance_operation.html#ad3427b318ecbca0944f3bf326abf4de5", null ], [ "identifier", "struct_grape_f_s_1_1___performance_operation.html#ab66edf64c9e08ae157f5f592ccd9bf95", null ], [ "operation", "struct_grape_f_s_1_1___performance_operation.html#af6cedcbc967016a023da9b2348216b2c", null ], [ "values", "struct_grape_f_s_1_1___performance_operation.html#a14e15664f2ea761afbe217b00162ece7", null ] ];
crurik/GrapeFS
Doxygen/html/struct_grape_f_s_1_1___performance_operation.js
JavaScript
bsd-2-clause
859
import template from './popup.html'; import controller from './popup.controller.js'; import './popup.less'; export default { restrict: 'E', bindings: {}, template, controller, controllerAs: 'vm' };
ffan-fe/fancyui
example/app/components/popup/popup.component.js
JavaScript
bsd-2-clause
209
'use strict'; var React = require('react-native'); var {StyleSheet, PixelRatio, Platform} = React; var styles = StyleSheet.create({ container: { flex:1, paddingTop: 70, backgroundColor: '#F7F7F7', }, row: { flexDirection: 'row', backgroundColor:'white', borderRadius: 0, borderWidth: 0, borderTopWidth: 1 / PixelRatio.get(), borderColor: '#d6d7da', padding:10, alignItems: 'center' }, categoryLabel: { fontSize: 15, textAlign: 'left', left: 10, padding:10, fontWeight:'bold', }, lastRow: { flexDirection: 'row', backgroundColor:'white', borderRadius: 0, borderWidth: 0, borderTopWidth: 1 / PixelRatio.get(), borderBottomWidth: 1 / PixelRatio.get(), borderColor: '#d6d7da', padding:10, alignItems: 'center' }, rowLabel: { left:10, flex:1, fontSize:15, }, rowInput: { fontSize:15, flex:1, height:(Platform.OS=='ios') ? 30 : 50 }, messageItem: { padding:10, paddingRight:20, fontSize:15 }, messageBar: { backgroundColor:'white', flexDirection:'row', left:0, right:0, height:55 }, message: { left:10, right:10, fontSize:15, flex:1, height:30 }, button: { backgroundColor: 'white', padding: 15, borderColor: '#eeeeee', borderWidth:1, borderBottomWidth: 1 / PixelRatio.get(), marginTop:20, borderRadius:10, width:300, marginRight:20, marginLeft:20, alignSelf: 'center' }, sendButton: { justifyContent: 'center', width:80 }, navBar: { backgroundColor: '#0db0d9' }, loadingContainer: { position: 'absolute', top:0, bottom:0, left:0, right:0, backgroundColor:'black', opacity:0.7, justifyContent: 'center', alignItems: 'center' }, loading: { width:70, borderRadius: 6, height:70, justifyContent: 'center', alignItems: 'center', backgroundColor:'white' } }); module.exports = styles;
karanth/react-native-xmpp-mam
XmppDemo/components/styles.js
JavaScript
bsd-2-clause
2,381
import * as Error from '../error'; import * as Ast from './ast'; import * as ScopeHandler from './scopeHandler'; import * as TypeSystem from './typeSystem'; const evaluateBlock = (scope, ast) => { return ast.map((expr) => { return evaluateExpression(scope, expr); }); }; const evaluateExpression = (scope, astExpr) => { let output; switch(astExpr.node) { case 'LETDEFINITION': output = handleLetDefinition(scope, astExpr); break; case 'FUNCTIONDEFINITION': output = handleFunctionDefinition(scope, astExpr); break; case 'BODY': output = handleBody(scope, astExpr); break; case 'VARIABLE': output = handleVariable(scope, astExpr); break; case 'LAMBDA': output = handleLambda(scope, astExpr); break; case 'IF': output = handleIf(scope, astExpr); break; case 'IFELSE': output = handleIfElse(scope, astExpr); break; case 'APPLICATION': output = handleApplicationExpression(scope, astExpr); break; case 'BOOLEAN': output = astExpr; break; case 'UNDEFINED': output = astExpr; break; case 'NUMBER': output = astExpr; break; case 'STRING': output = astExpr; break; case 'SYMBOL': output = astExpr; break; case 'NOTE': output = astExpr; break; case 'BEAT': output = astExpr; break; case 'LIST': output = handleList(scope, astExpr); break; case 'MAP': output = handleMap(scope, astExpr); break; case 'MAPPAIR': output = handleMapPair(scope, astExpr); break; default: throw Error.create( Error.types.invalidAST, `AST Expression not valid: ${astExpr.node}` ); } return output; }; const handleLetDefinition = (scope, define) => { const defName = define.name; const defValue = evaluateExpression(scope, define.expression); ScopeHandler.set(scope, defName, defValue); return defValue; }; const handleFunctionDefinition = (scope, funcDef) => { const name = funcDef.name; const argNames = funcDef.argNames; const argTypes = funcDef.argTypes; const body = funcDef.body; const func = Ast.Func(argNames, argTypes, body); ScopeHandler.set(scope, name, func); return func; }; const handleBody = (scope, body) => { evaluateBlock(scope, body.definitions); return evaluateBlock(scope, body.expressions); }; const handleVariable = (scope, variable) => { return ScopeHandler.get(scope, variable.name); }; const handleLambda = (scope, lambda) => { return Ast.Closure( lambda.argNames, lambda.argTypes, lambda.body, scope ); }; const handleIf = (scope, ifNode) => { const predicate = evaluateExpression(scope, ifNode.predicate); let value; if (predicate === true || predicate !== 0) { value = evaluateBlock(scope, ifNode.expression); } else { value = false; } return value; }; const handleIfElse = (scope, ifElse) => { const predicate = evaluateExpression(scope, ifElse.predicate); let value; if (predicate === true || predicate !== 0) { value = evaluateBlock(scope, ifElse.trueExpression); } else { value = evaluateBlock(scope, ifElse.falseExpression); } return value; }; const handleApplicationExpression = (scope, application) => { const target = evaluateExpression(scope, application.target); const applicationArgs = application.args; const evaluatedArgs = applicationArgs.map((arg) => { return evaluateExpression(scope, arg); }); return handleApplication(scope, target, evaluatedArgs); }; const handleApplication = (scope, application, evaluatedArgs) => { if (!TypeSystem.checkFunctionTypes(application, evaluatedArgs)) { throw Error.create( Error.types.type, `Invalid types in application` ); } let result; switch (application.node) { case 'FUNCTION': result = handleFunction( scope, application, evaluatedArgs ); break; case 'BUILTIN': result = handleBuiltIn( scope, application, evaluatedArgs ); break; case 'CLOSURE': result = handleFunction( application.scope, application, evaluatedArgs ); break; default: throw Error.create( Error.types.application, `Application node not valid: ${application.node}` ); } return result; }; const handleFunction = (scope, func, functionArgs) => { const functionArgNames = func.argNames; const functionBody = func.body; if (functionArgs.length !== functionArgNames.length) { throw Error.create( Error.types.application, 'Incorrect argument number' ); } let childScope = ScopeHandler.createChildScope(scope); for (let i = 0; i < functionArgNames.length; i += 1) { ScopeHandler.set(childScope, functionArgNames[i], functionArgs[i]); } return evaluateExpression(childScope, functionBody); }; const handleBuiltIn = (scope, builtIn, functionArgs) => { const func = builtIn.func; if (functionArgs.length !== func.length) { throw Error.create( Error.types.application, 'Incorrect argument number' ); } const childScope = ScopeHandler.createChildScope(scope); // function args have already been evaluated return func.apply(childScope, functionArgs); }; const handleList = (scope, list) => { return Ast.List( list.values.map((lExp) => { return evaluateExpression(scope, lExp); }) ); }; const handleMap = (scope, map) => { return Ast.Map( map.entries.map((mExp) => { return evaluateExpression(scope, mExp); }) ); }; const handleMapPair = (scope, pair) => { return { k: evaluateExpression(scope, pair.key), v: evaluateExpression(scope, pair.value) }; }; // scope is a dictionary, stored in and passed in by the Core export const evaluate = (scope, ast) => { evaluateBlock(scope, ast); }; export const apply = (scope, closure, args) => { handleApplication(scope, closure, args); };
rumblesan/whorl
src/app/language/interpreter.js
JavaScript
bsd-2-clause
6,470
(function ($) { $(document).ready(function () { var config = window._lbconfig || {}, $uacLiveBlog = $('#uacLiveBlog') .width(Math.max(100, config.width)) .liveUpdateUi({ postId: config.postId, url: config.updateUrl, toolbarEnabled: false, tweetButtons: false, tagsEnabled: false, imageExpandEnabled: false, thumbnailDimensions: { height: 100, width: 100 }, postLimit: 3, pollInterval: 5, linkParams: config.trackingCode, height: Math.max(100, config.height) }); }); }(jQuery));
aol/jquery-liveupdate
src/liveupdate-uac.js
JavaScript
bsd-2-clause
572
/** Copyright (c) 2010 Dennis Hotson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function() { jQuery.fn.springy = function(params) { var graph = this.graph = params.graph || new Springy.Graph(); var nodeFont = "16px Verdana, sans-serif"; var edgeFont = "8px Verdana, sans-serif"; var stiffness = params.stiffness || 400.0; var repulsion = params.repulsion || 400.0; var damping = params.damping || 0.5; var minEnergyThreshold = params.minEnergyThreshold || 0.00001; var nodeSelected = params.nodeSelected || null; var nodeImages = {}; var edgeLabelsUpright = true; var canvas = this[0]; var ctx = canvas.getContext("2d"); var layout = this.layout = new Springy.Layout.ForceDirected(graph, stiffness, repulsion, damping, minEnergyThreshold); // calculate bounding box of graph layout.. with ease-in var currentBB = layout.getBoundingBox(); var targetBB = {bottomleft: new Springy.Vector(-2, -2), topright: new Springy.Vector(2, 2)}; // auto adjusting bounding box Springy.requestAnimationFrame(function adjust() { targetBB = layout.getBoundingBox(); // current gets 20% closer to target every iteration currentBB = { bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft) .divide(10)), topright: currentBB.topright.add( targetBB.topright.subtract(currentBB.topright) .divide(10)) }; Springy.requestAnimationFrame(adjust); }); // convert to/from screen coordinates var toScreen = function(p) { var size = currentBB.topright.subtract(currentBB.bottomleft); var sx = p.subtract(currentBB.bottomleft).divide(size.x).x * canvas.width; var sy = p.subtract(currentBB.bottomleft).divide(size.y).y * canvas.height; return new Springy.Vector(sx, sy); }; var fromScreen = function(s) { var size = currentBB.topright.subtract(currentBB.bottomleft); var px = (s.x / canvas.width) * size.x + currentBB.bottomleft.x; var py = (s.y / canvas.height) * size.y + currentBB.bottomleft.y; return new Springy.Vector(px, py); }; // half-assed drag and drop var selected = null; var nearest = null; var dragged = null; // jQuery(canvas).click(function(e) { // var pos = jQuery(this).offset(); // var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top}); // selected = layout.nearest(p); // }); jQuery(canvas).mousedown(function(e) { var pos = jQuery(this).offset(); var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top}); nearest = dragged = layout.nearest(p); if (dragged.node) { dragged.point.m = 10000.0; } renderer.start(); }); // Basic double click handler jQuery(canvas).dblclick(function(e) { var pos = jQuery(this).offset(); var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top}); var selected = layout.nearest(p); var node = selected.node; if (node && nodeSelected) { nodeSelected(node); } if (node && node.data && node.data.ondoubleclick) { node.data.ondoubleclick(); } renderer.start(); }); jQuery(canvas).mousemove(function(e) { var pos = jQuery(this).offset(); var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top}); nearest = layout.nearest(p); if (dragged !== null && dragged.node !== null) { dragged.point.p.x = p.x; dragged.point.p.y = p.y; } renderer.start(); }); jQuery(window).bind('mouseup',function(e) { dragged = null; }); var getTextWidth = function(node) { var text = (node.data.label !== undefined) ? node.data.label : node.id; if (node._width && node._width[text]) return node._width[text]; ctx.save(); ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont; var width = ctx.measureText(text).width; ctx.restore(); node._width || (node._width = {}); node._width[text] = width; return width; }; var getTextHeight = function(node) { return 16; // In a more modular world, this would actually read the font size, but I think leaving it a constant is sufficient for now. // If you change the font size, I'd adjust this too. }; var getImageWidth = function(node) { var width = (node.data.image.width !== undefined) ? node.data.image.width : nodeImages[node.data.image.src].object.width; return width; } var getImageHeight = function(node) { var height = (node.data.image.height !== undefined) ? node.data.image.height : nodeImages[node.data.image.src].object.height; return height; } Springy.Node.prototype.getHeight = function() { var height; if (this.data.image == undefined) { height = getTextHeight(this); } else { if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) { height = getImageHeight(this); } else {height = 10;} } return height; } Springy.Node.prototype.getWidth = function() { var width; if (this.data.image == undefined) { width = getTextWidth(this); } else { if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) { width = getImageWidth(this); } else {width = 10;} } return width; } var renderer = this.renderer = new Springy.Renderer(layout, function clear() { ctx.clearRect(0,0,canvas.width,canvas.height); }, function drawEdge(edge, p1, p2) { var x1 = toScreen(p1).x; var y1 = toScreen(p1).y; var x2 = toScreen(p2).x; var y2 = toScreen(p2).y; var direction = new Springy.Vector(x2-x1, y2-y1); var normal = direction.normal().normalise(); var from = graph.getEdges(edge.source, edge.target); var to = graph.getEdges(edge.target, edge.source); var total = from.length + to.length; // Figure out edge's position in relation to other edges between the same nodes var n = 0; for (var i=0; i<from.length; i++) { if (from[i].id === edge.id) { n = i; } } //change default to 10.0 to allow text fit between edges var spacing = 12.0; // Figure out how far off center the line should be drawn var offset = normal.multiply(-((total - 1) * spacing)/2.0 + (n * spacing)); var paddingX = 6; var paddingY = 6; var s1 = toScreen(p1).add(offset); var s2 = toScreen(p2).add(offset); var boxWidth = edge.target.getWidth() + paddingX; var boxHeight = edge.target.getHeight() + paddingY; var intersection = intersect_line_box(s1, s2, {x: x2-boxWidth/2.0, y: y2-boxHeight/2.0}, boxWidth, boxHeight); if (!intersection) { intersection = s2; } var stroke = (edge.data.color !== undefined) ? edge.data.color : '#000000'; var arrowWidth; var arrowLength; var weight = (edge.data.weight !== undefined) ? edge.data.weight : 1.0; ctx.lineWidth = Math.max(weight * 2, 0.1); arrowWidth = 1 + ctx.lineWidth; arrowLength = 8; var directional = (edge.data.directional !== undefined) ? edge.data.directional : true; // line var lineEnd; if (directional) { lineEnd = intersection.subtract(direction.normalise().multiply(arrowLength * 0.5)); } else { lineEnd = s2; } ctx.strokeStyle = stroke; ctx.beginPath(); ctx.moveTo(s1.x, s1.y); ctx.lineTo(lineEnd.x, lineEnd.y); ctx.stroke(); // arrow if (directional) { ctx.save(); ctx.fillStyle = stroke; ctx.translate(intersection.x, intersection.y); ctx.rotate(Math.atan2(y2 - y1, x2 - x1)); ctx.beginPath(); ctx.moveTo(-arrowLength, arrowWidth); ctx.lineTo(0, 0); ctx.lineTo(-arrowLength, -arrowWidth); ctx.lineTo(-arrowLength * 0.8, -0); ctx.closePath(); ctx.fill(); ctx.restore(); } // label if (edge.data.label !== undefined) { text = edge.data.label ctx.save(); ctx.textAlign = "center"; ctx.textBaseline = "top"; ctx.font = (edge.data.font !== undefined) ? edge.data.font : edgeFont; ctx.fillStyle = stroke; var angle = Math.atan2(s2.y - s1.y, s2.x - s1.x); var displacement = -8; if (edgeLabelsUpright && (angle > Math.PI/2 || angle < -Math.PI/2)) { displacement = 8; angle += Math.PI; } var textPos = s1.add(s2).divide(2).add(normal.multiply(displacement)); ctx.translate(textPos.x, textPos.y); ctx.rotate(angle); ctx.fillText(text, 0,-2); ctx.restore(); } }, function drawNode(node, p) { var s = toScreen(p); ctx.save(); // Pulled out the padding aspect sso that the size functions could be used in multiple places // These should probably be settable by the user (and scoped higher) but this suffices for now var paddingX = 6; var paddingY = 6; var contentWidth = node.getWidth(); var contentHeight = node.getHeight(); var boxWidth = contentWidth + paddingX; var boxHeight = contentHeight + paddingY; // clear background ctx.clearRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight); // fill background if (selected !== null && selected.node !== null && selected.node.id === node.id) { ctx.fillStyle = node.data.selectedBackgroundColor || params.selectedBackgroundColor || "#FFFFE0"; } else { ctx.fillStyle = node.data.backgroundColor || params.backgroundColor || "#FFFFFF"; } ctx.fillRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight); if (node.data.image == undefined) { ctx.textAlign = "left"; ctx.textBaseline = "top"; ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont; ctx.fillStyle = (node.data.color !== undefined) ? node.data.color : "#000000"; var text = (node.data.label !== undefined) ? node.data.label : node.id; ctx.fillText(text, s.x - contentWidth/2, s.y - contentHeight/2); } else { // Currently we just ignore any labels if the image object is set. One might want to extend this logic to allow for both, or other composite nodes. var src = node.data.image.src; // There should probably be a sanity check here too, but un-src-ed images aren't exaclty a disaster. if (src in nodeImages) { if (nodeImages[src].loaded) { // Our image is loaded, so it's safe to draw ctx.drawImage(nodeImages[src].object, s.x - contentWidth/2, s.y - contentHeight/2, contentWidth, contentHeight); } }else{ // First time seeing an image with this src address, so add it to our set of image objects // Note: we index images by their src to avoid making too many duplicates nodeImages[src] = {}; var img = new Image(); nodeImages[src].object = img; img.addEventListener("load", function () { // HTMLImageElement objects are very finicky about being used before they are loaded, so we set a flag when it is done nodeImages[src].loaded = true; }); img.src = src; } } ctx.restore(); } ); renderer.start(); // helpers for figuring out where to draw arrows function intersect_line_line(p1, p2, p3, p4) { var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y)); // lines are parallel if (denom === 0) { return false; } var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom; var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom; if (ua < 0 || ua > 1 || ub < 0 || ub > 1) { return false; } return new Springy.Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y)); } function intersect_line_box(p1, p2, p3, w, h) { var tl = {x: p3.x, y: p3.y}; var tr = {x: p3.x + w, y: p3.y}; var bl = {x: p3.x, y: p3.y + h}; var br = {x: p3.x + w, y: p3.y + h}; var result; if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right if (result = intersect_line_line(p1, p2, br, bl)) { return result; } // bottom if (result = intersect_line_line(p1, p2, bl, tl)) { return result; } // left return false; } return this; } })();
aisman64/peoplecounter
server/pub/lib/springy/springyui.js
JavaScript
bsd-3-clause
12,743
function loadTxt() { document.getElementById("btnClose").value = "chiudi"; } function writeTitle() { document.write("<title>Anteprima</title>") }
techvn/webstore
public/assets/backend/system/upload-file/editor/scripts/language/it-IT/preview.js
JavaScript
bsd-3-clause
169
suite('a11y', function() { test('dialog has role="dialog"', function() { var dialog = fixture('basic'); assert.equal(dialog.getAttribute('role'), 'dialog', 'has role="dialog"'); }); });
fuzzdota/chromeapp-native-messaging-sample
app/bower_components/paper-dialog/test/paper-dialog.html.0.js
JavaScript
bsd-3-clause
243
(function(){ d3.timeline = function(){ var itemHeight = 20, height = null, width = 1000; function chart(selection){ selection.each(function(data){ var groups = grouping(data), levels = d3.sum(d3.values(groups).map(function(d){ return d.length; })), margin = {top: 20, right: 15, bottom: 50, left: 150}, x = d3.time.scale().range([margin.left, width]).domain([ d3.min(data, start), d3.max(data, end) ]), xAxis = d3.svg.axis().scale(x).orient('bottom').tickSize(6, 0, 0); if (!height) { height = itemHeight * levels + margin.top + margin.bottom; } else { itemHeight = (height- margin.top +- margin.bottom)/levels; } selection.selectAll('svg').remove(); var svg = selection.append('svg:svg') .attr('width', width) .attr('height', height); svg.append('defs').append('clipPath') .attr('id', 'clip') .append('rect') .attr('width', width-margin.left) .attr('height', height) .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var last = 0, current = 0; var items = svg.selectAll('g.itemGroup') .data(d3.entries(groups)) .enter().append('g') .attr("class","itemGroup") .attr("transform", function(d,i){ current = last; last += d.value.length*itemHeight; return "translate(" + 0 + "," + (margin.top + current) + ")"; }); items.append('line') .attr('x1', margin.left) .attr('y1', 0) .attr('x2', width) .attr('y2', 0) .attr('stroke', 'lightgrey'); items.append('text') .text(function(d) { return d.key; }) .attr('x', margin.left-10) .attr('y', 0) .attr('dy', function(d) { return (d.value.length * itemHeight)/2; }) .attr('text-anchor', 'end') .attr('class', 'groupText'); svg.append('g') .attr('transform', 'translate(0,' + (itemHeight * (levels+1)) + ')') .attr('class', 'focus axis date') .call(xAxis); var itemsClip = svg.append('g') .attr('clip-path', 'url(#clip)') update(); function update(){ var rects = itemsClip.selectAll('rect') .data(data, function(d){return d.__id;}) .attr('x', function(d) { return x(start(d)); }) .attr('width', function(d) { return x(end(d)) - x(start(d)); }) rects.enter().append('rect') .attr('x', function(d) { return x(start(d)); }) .attr('y', function(d,i) { return itemHeight * d.__level + margin.top; }) .attr('width', function(d) { return x(end(d)) - x(start(d)); }) .attr('height', itemHeight) .attr('class', function(d) { return 'focusItem'; }) rects.exit().remove(); } }) } function grouping(data){ var level = id = 0; return d3.nest() .key(group) .rollup(function(g) { var l, levels = []; g.forEach(function(item,i){ l=0; while(overlap(item, levels[l])) l++; if (!levels[l]) levels[l] = []; item.__level = l+level; item.__id = id++; levels[l].push(item); }) level++; return levels; }) .map(data) } function overlap(item, g) { if (!g) return false; for(var i in g) { if(start(item) < end(g[i]) && end(item) > start(g[i])) { return true; } } return false; }; function group(d) { return d.group; } function start(d) { return d.start; } function end(d) { return d.end; } /* Getter/Setter */ chart.group = function(x) { if (!arguments.length) return x; group = x; return chart; } chart.start = function(x) { if (!arguments.length) return start; start = x; return chart; } chart.end = function(x) { if (!arguments.length) return end; end = x; return chart; } chart.height = function(x) { if (!arguments.length) return height; height = x; return chart; } return chart; } })();
humanitiesplusdesign/palladio
src/js/helpers/d3.timeline.js
JavaScript
bsd-3-clause
3,995
// // ClearBox Language File (JavaScript) // var CB_NavTextPrv='zurück', // text of previous image CB_NavTextNxt='weiter', // text of next image CB_NavTextFull='volle grösse', // text of original size (only at pictures) CB_NavTextOpen='in neuem Browser-Fenster öffnen', // text of open in a new browser window CB_NavTextDL='herunterladen', // text of download picture or any other content CB_NavTextClose='schliessen', // text of close CB CB_NavTextStart='Diaschau starten', // text of start slideshow CB_NavTextStop='Diaschau stoppen', // text of stop slideshow CB_NavTextRotR='Bild 90 grad nach rechts drehen', // text of rotation right CB_NavTextRotL='Bild 90 grad nach links drehen', // text of rotation left CB_NavTextReady='clearbox is ready' // text of clearbox ready ;
pradeepchaudhary/Project1v3_zend
public/js/clearbox/language/de/cb_language.js
JavaScript
bsd-3-clause
835
module.exports = { addAttribute: require("./addAttribute"), addAttributes: require("./addAttributes"), addClass: require("./addClass"), alignElement: require("./alignElement"), appendChild: require("./appendChild"), createElement: require("./createElement"), createElementNS: require("./createElementNS"), filterElements: require("./filterElements"), findElement: require("./findElement"), findElements: require("./findElements"), findLastElement: require("./findLastElement"), findNextElement: require("./findNextElement"), findNextElements: require("./findNextElements"), findParentElement: require("./findParentElement"), findPreviousElement: require("./findPreviousElement"), findPreviousElements: require("./findPreviousElements"), findSiblingElement: require("./findSiblingElement"), findSiblingElements: require("./findSiblingElements"), getAllNextElements: require("./getAllNextElements"), getAllPreviousElements: require("./getAllPreviousElements"), getAllSiblingElements: require("./getAllSiblingElements"), getAttribute: require("./getAttribute"), getAttributes: require("./getAttributes"), getBoundings: require("./getBoundings"), getChildren: require("./getChildren"), getDistributedElement: require("./getDistributedElement"), getDistributedElements: require("./getDistributedElements"), getElement: require("./getElement"), getElementById: require("./getElementById"), getElements: require("./getElements"), getHTML: require("./getHTML"), getHeight: require("./getHeight"), getMargin: require("./getMargin"), getNextElement: require("./getNextElement"), getNode: require("./getNode"), getNodes: require("./getNodes"), getPadding: require("./getPadding"), getParentElement: require("./getParentElement"), getPreviousElement: require("./getPreviousElement"), getSiblingElements: require("./getSiblingElements"), getStyle: require("./getStyle"), getStyles: require("./getStyles"), getTag: require("./getTag"), getText: require("./getText"), getValue: require("./getValue"), getWidth: require("./getWidth"), hasAttribute: require("./hasAttribute"), hasChild: require("./hasChild"), hasClass: require("./hasClass"), listen: require("./listen"), matches: require("./matches"), onMutation: require("./onMutation"), prependChild: require("./prependChild"), preventDefault: require("./preventDefault"), removeAttribute: require("./removeAttribute"), removeAttributes: require("./removeAttributes"), removeChild: require("./removeChild"), removeClass: require("./removeClass"), removeStyle: require("./removeStyle"), removeStyles: require("./removeStyles"), renameElement: require("./renameElement"), replaceNode: require("./replaceNode"), requestAnimationFrame: require("./requestAnimationFrame"), setAttribute: require("./setAttribute"), setAttributes: require("./setAttributes"), setChildren: require("./setChildren"), setHTML: require("./setHTML"), setStyle: require("./setStyle"), setStyles: require("./setStyles"), setText: require("./setText"), stop: require("./stop"), stopPropagation: require("./stopPropagation"), toggleAttribute: require("./toggleAttribute"), toggleClass: require("./toggleClass"), unlisten: require("./unlisten"), updateElement: require("./updateElement"), willBleedBottom: require("./willBleedBottom"), willBleedHorizontally: require("./willBleedHorizontally"), willBleedLeft: require("./willBleedLeft"), willBleedRight: require("./willBleedRight"), willBleedTop: require("./willBleedTop"), willBleedVertically: require("./willBleedVertically") };
Klaudit/expandjs
lib/dom/index.js
JavaScript
bsd-3-clause
3,810
/******************************************************************************* * KindEditor - WYSIWYG HTML Editor for Internet * Copyright (C) 2006-2011 kindsoft.net * * @author Roddy <luolonghao@gmail.com> * @site http://www.kindsoft.net/ * @licence http://www.kindsoft.net/license.php *******************************************************************************/ // Baidu Maps: http://dev.baidu.com/wiki/map/index.php?title=%E9%A6%96%E9%A1%B5 KindEditor.plugin('baidumap', function (K) { var self = this, name = 'baidumap', lang = self.lang(name + '.'); var mapWidth = K.undef(self.mapWidth, 558); var mapHeight = K.undef(self.mapHeight, 360); self.clickToolbar(name, function () { var html = ['<div style="padding:10px 20px;">', '<div class="ke-header">', // left start '<div class="ke-left">', lang.address + ' <input id="kindeditor_plugin_map_address" name="address" class="ke-input-text" value="" style="width:200px;" /> ', '<span class="ke-button-common ke-button-outer">', '<input type="button" name="searchBtn" class="ke-button-common ke-button" value="' + lang.search + '" />', '</span>', '</div>', // right start '<div class="ke-right">', '<input type="checkbox" id="keInsertDynamicMap" name="insertDynamicMap" value="1" /> <label for="keInsertDynamicMap">' + lang.insertDynamicMap + '</label>', '</div>', '<div class="ke-clearfix"></div>', '</div>', '<div class="ke-map" style="width:' + mapWidth + 'px;height:' + mapHeight + 'px;"></div>', '</div>'].join(''); var dialog = self.createDialog({ name: name, width: mapWidth + 42, title: self.lang(name), body: html, yesBtn: { name: self.lang('yes'), click: function (e) { var map = win.map; var centerObj = map.getCenter(); var center = centerObj.lng + ',' + centerObj.lat; var zoom = map.getZoom(); var url = [checkbox[0].checked ? self.pluginsPath + 'baidumap/index.html' : 'http://api.map.baidu.com/staticimage', '?center=' + encodeURIComponent(center), '&zoom=' + encodeURIComponent(zoom), '&width=' + mapWidth, '&height=' + mapHeight, '&markers=' + encodeURIComponent(center), '&markerStyles=' + encodeURIComponent('l,A')].join(''); if (checkbox[0].checked) { self.insertHtml('<iframe src="' + url + '" frameborder="0" style="width:' + (mapWidth + 2) + 'px;height:' + (mapHeight + 2) + 'px;"></iframe>'); } else { self.exec('insertimage', url); } self.hideDialog().focus(); } }, beforeRemove: function () { searchBtn.remove(); if (doc) { doc.write(''); } iframe.remove(); } }); var div = dialog.div, addressBox = K('[name="address"]', div), searchBtn = K('[name="searchBtn"]', div), checkbox = K('[name="insertDynamicMap"]', dialog.div), win, doc; var iframe = K('<iframe class="ke-textarea" frameborder="0" src="' + self.pluginsPath + 'baidumap/map.html" style="width:' + mapWidth + 'px;height:' + mapHeight + 'px;"></iframe>'); function ready() { win = iframe[0].contentWindow; doc = K.iframeDoc(iframe); } iframe.bind('load', function () { iframe.unbind('load'); if (K.IE) { ready(); } else { setTimeout(ready, 0); } }); K('.ke-map', div).replaceWith(iframe); // search map searchBtn.click(function () { win.search(addressBox.val()); }); }); });
329221391/home
web/plus/kindeditor-4.1.10/plugins/baidumap/baidumap.js
JavaScript
bsd-3-clause
4,209
define(["require", "exports", '../../has', "../dom/form/Text"], function (require, exports, has) { var Text; if (has('host-browser')) { Text = require('../dom/form/Text'); } return Text; }); //# sourceMappingURL=../../_debug/ui/form/Text.js.map
SitePen/mayhem-bower
ui/form/Text.js
JavaScript
bsd-3-clause
268
define(function () {'use strict'; function rn (n) { return n.toLowerCase().replace(/a$/, ''); } return rn; });
rainersu/color
src/var/rn.js
JavaScript
bsd-3-clause
114
//= require mes/modeler
cloud-mes/cloud-mes
core/lib/generators/cloud_mes/install/templates/vendor/assets/javascripts/mes/modeler/all.js
JavaScript
bsd-3-clause
24
// @flow import compose from 'ramda/src/compose'; import contains from 'ramda/src/contains'; import curry from 'ramda/src/curry'; import curryN from 'ramda/src/curryN'; import pipe from 'ramda/src/pipe'; import props from 'ramda/src/props'; import uniq from 'ramda/src/uniq'; import { FORMAT_HUETODEGREES, FORMAT_INCLUDEALPHA, FORMAT_INTTOPERCENT, FORMAT_SHORTHEX, linearTransformFactory, toHex, splitDoubles, checkDoubles } from './Transforms'; /* --- STRING --- */ const hasAlpha = contains(FORMAT_INCLUDEALPHA); const hasHueToDegress = contains(FORMAT_HUETODEGREES); const hasIntToPercent = contains(FORMAT_INTTOPERCENT); const hasShortHex = contains(FORMAT_SHORTHEX); /** * Extract keys from Disjoint ColorObject */ function getValue(func: string, keys: Array<string>, color: ColorObject): Array<any> { return (color.func === func) ? props(keys, color) : []; }; const getRgbVals: Function = curryN(3, getValue)('rgb', ['r', 'g', 'b', 'alpha', 'format']); function floatToPercent(n: number): string { let x = (n > 1) ? 1 : n; return `${Math.round(x * 100)}%`; } /** * Convert a float [0,1] to an int [0,255] */ function percentToInt(n: number): number { if (!n) return 0; return linearTransformFactory(0, 1, 0, 255)(n); } /** * RGB/RGBA -> String */ function makeRgbString(color: ColorObject): string { const keys = ['func', 'r', 'g', 'b', 'alpha', 'format']; let props = []; if (color.func === 'rgb') { props = getValue('rgb', keys, color); } if (color.func === 'rgba') { props = getValue('rgba', keys, color); } const [func, r, g, b, alpha, format] = props; let rgb: Array<any> = [r, g, b]; if (hasIntToPercent(format)) { rgb = rgb.map(floatToPercent); // [0, 1] -> n% } else { rgb = rgb.map(percentToInt); // [0, 1] -> [0, 255] } const [nr, ng, nb] = rgb; if (hasAlpha(format) || func === 'rgba') { return `rgba(${nr}, ${ng}, ${nb}, ${alpha})`; } return `rgb(${nr}, ${ng}, ${nb})`; } /** * HSL/HSLA -> String */ function makeHslString(color: ColorObject): string { const keys = ['func', 'h', 's', 'l', 'alpha', 'format']; let props = []; let out = ""; if (color.func === 'hsl') { props = getValue('hsl', keys, color); } if (color.func === 'hsla') { props = getValue('hsla', keys, color); } const [func, h, s, l, alpha, format] = props; let hsl: Array<any> = [ Math.round(h * 360), `${Math.round(s * 100)}%`, `${Math.round(l * 100)}%` ]; if (hasHueToDegress(format)) { hsl[0] = `${hsl[0]}deg`; } if (hasAlpha(format) || func === 'hsla') { out = `hsla(${hsl.join(', ')}, ${alpha})`; } else { out = `hsl(${hsl.join(', ')})`; } return out; } /** * HEX -> String */ function makeHexString(color: ColorObject): string { const keys = ['func', 'hex', 'r', 'g', 'b', 'alpha', 'format']; let props = []; if (color.func === 'hex') { props = getValue('hex', keys, color); } const [, hex, r, g, b, alpha, format] = props; let out = hex; // operate on a copy let pairs = []; // store modified channels // No changes to format and 6/8 long then short circuit using // the stored hex string. ALSO, account for the '#'!! if (!format.length && hex.length >= 7) { if (hex.length === 7) { return out; } // Lop off alpha hex if (hex.length === 9) { return out.substr(0, 7); } } // If we're not shortening and the hex string is short, // then expand it back out (ex: parse(#039f)) if (!hasShortHex(format) && hex.length <= 7) { if (hasAlpha(format)) { pairs = [r, g, b, alpha].map(toHex); out = "#" + pairs.join(''); } else { pairs = [r, g, b].map(toHex); out = "#" + pairs.join(''); } } // We can only shorten if all pairs are doubles if (hasShortHex(format)) { if (hasAlpha(format)) { pairs = [r, g, b, alpha].map(toHex); } else { pairs = [r, g, b].map(toHex); } const hasDoubles = pairs.map(checkDoubles).every(x => x); if (hasDoubles) { out = "#" + pairs.map(splitDoubles).join(''); } else { out = "#" + pairs.join(''); // no alpha and no doubles so just 6 } } return out; } function makeString(result: ColorObject): string { const {func} = result; switch (func) { case 'hex': return makeHexString(result); case 'hsl': case 'hsla': return makeHslString(result); case 'rgb': case 'rgba': return makeRgbString(result); default: return '#error - could not output string for this color object'; } }; export { makeString };
DarrenN/css-color-parser
src/Strings.js
JavaScript
bsd-3-clause
4,623
define(function (require) { 'use strict'; var $ = require('jquery'); var _ = require('underscore'); var XMLSerialiser = new window.XMLSerializer(); function xmlNodeReducer (memo, node) { return memo + XMLSerialiser.serializeToString(node); } /** * @typedef {Object} XMLParseResult * * @property {string} * - String representation of Either the value or subform Form definitions. */ /** * Takes a xml node and turns it into the format required for FORMS * * @param {Node} xmlNode - The XML Node of the subform element. * @return {XMLParseResult} - The result of parsing the subform node */ return function parseFormChildXML (xmlNode) { var result = {}; var $xmlNode = $(xmlNode); var children = $xmlNode.children(); result[$xmlNode.prop('nodeName')] = children.length ? _.reduce(children, xmlNodeReducer, '') : $xmlNode.text(); return result; }; });
blinkmobile/bic-jqm
src/bic/lib/parse-form-child-xml.js
JavaScript
bsd-3-clause
932
/*! * jquery.inputmask.regex.extensions.min.js * http://github.com/RobinHerbots/jquery.inputmask * Copyright (c) 2010 - 2015 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 3.1.62 */ !function (a) { "function" == typeof define && define.amd ? define(["jquery", "./jquery.inputmask"], a) : a(jQuery) }(function (a) { return a.extend(a.inputmask.defaults.aliases, { Regex: { mask: "r", greedy: !1, repeat: "*", regex: null, regexTokens: null, tokenizer: /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, quantifierFilter: /[0-9]+[^,]/, isComplete: function (a, b) { return new RegExp(b.regex).test(a.join("")) }, definitions: { r: { validator: function (b, c, d, e, f) { function g(a, b) { this.matches = [], this.isGroup = a || !1, this.isQuantifier = b || !1, this.quantifier = { min: 1, max: 1 }, this.repeaterPart = void 0 } function h() { var a, b, c = new g, d = []; for (f.regexTokens = []; a = f.tokenizer.exec(f.regex);)switch (b = a[0], b.charAt(0)) { case"(": d.push(new g(!0)); break; case")": var e = d.pop(); d.length > 0 ? d[d.length - 1].matches.push(e) : c.matches.push(e); break; case"{": case"+": case"*": var h = new g(!1, !0); b = b.replace(/[{}]/g, ""); var i = b.split(","), j = isNaN(i[0]) ? i[0] : parseInt(i[0]), k = 1 == i.length ? j : isNaN(i[1]) ? i[1] : parseInt(i[1]); if (h.quantifier = {min: j, max: k}, d.length > 0) { var l = d[d.length - 1].matches; if (a = l.pop(), !a.isGroup) { var e = new g(!0); e.matches.push(a), a = e } l.push(a), l.push(h) } else { if (a = c.matches.pop(), !a.isGroup) { var e = new g(!0); e.matches.push(a), a = e } c.matches.push(a), c.matches.push(h) } break; default: d.length > 0 ? d[d.length - 1].matches.push(b) : c.matches.push(b) } c.matches.length > 0 && f.regexTokens.push(c) } function i(b, c) { var d = !1; c && (k += "(", m++); for (var e = 0; e < b.matches.length; e++) { var f = b.matches[e]; if (1 == f.isGroup) { d = i(f, !0); } else if (1 == f.isQuantifier) { var g = a.inArray(f, b.matches), h = b.matches[g - 1], j = k; if (isNaN(f.quantifier.max)) { for (; f.repeaterPart && f.repeaterPart != k && f.repeaterPart.length > k.length && !(d = i(h, !0));); d = d || i(h, !0), d && (f.repeaterPart = k), k = j + f.quantifier.max } else { for (var l = 0, o = f.quantifier.max - 1; o > l && !(d = i(h, !0)); l++); k = j + "{" + f.quantifier.min + "," + f.quantifier.max + "}" } } else if (void 0 != f.matches) { for (var p = 0; p < f.length && !(d = i(f[p], c)); p++); } else { var q; if ("[" == f.charAt(0)) { q = k, q += f; for (var r = 0; m > r; r++)q += ")"; var s = new RegExp("^(" + q + ")$"); d = s.test(n) } else { for (var t = 0, u = f.length; u > t; t++)if ("\\" != f.charAt(t)) { q = k, q += f.substr(0, t + 1), q = q.replace(/\|$/, ""); for (var r = 0; m > r; r++)q += ")"; var s = new RegExp("^(" + q + ")$"); if (d = s.test(n)) { break } } } k += f } if (d) { break } } return c && (k += ")", m--), d } null == f.regexTokens && h(); var j = c.buffer.slice(), k = "", l = !1, m = 0; j.splice(d, 0, b); for (var n = j.join(""), o = 0; o < f.regexTokens.length; o++) { var g = f.regexTokens[o]; if (l = i(g, g.isGroup)) { break } } return l }, cardinality: 1 } } } }), a.fn.inputmask });
meishichao/yii2test
vendor/bower/jquery.inputmask/dist/inputmask/jquery.inputmask.regex.extensions.min.js
JavaScript
bsd-3-clause
6,902
'use strict'; var express = require('express'); var configurations = module.exports; var app = express.createServer(); var nconf = require('nconf'); var redis = require('redis'); var db = redis.createClient(); var settings = require('./settings')(app, configurations, express); nconf.argv().env().file({ file: 'local.json' }); var isLoggedIn = function(req, res, next) { if (req.session.email) { next(); } else { res.redirect('/'); } }; // routes require('./routes')(app, db, isLoggedIn); require('./routes/auth')(app, db, nconf, isLoggedIn); app.get('/404', function(req, res, next){ next(); }); app.get('/403', function(req, res, next){ err.status = 403; next(new Error('not allowed!')); }); app.get('/500', function(req, res, next){ next(new Error('something went wrong!')); }); app.listen(process.env.PORT || nconf.get('port'));
ednapiranha/surrender-the-dust
app.js
JavaScript
bsd-3-clause
863
module.exports = function() { return [{ "request": { "method": "GET", "url": "http://api.wordnik.com/v4/word.json/test/definitions", "params": { "limit":"1", "includeRelated":"true", "sourceDictionaries":"webster", "useCanonical":"true", "api_key":"a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5" } }, "response": { "code": 200, "data": [{ "textProns":[], "sourceDictionary":"gcide", "exampleUses":[], "relatedWords":[], "labels":[{"type":"fld","text":"(Metal.)"}], "citations": [ { "source":"Chaucer.", "cite":"Our ingots, tests, and many mo." } ], "word":"test", "text":[ "A cupel or cupelling hearth in which precious metals ", "are melted for trial and refinement." ].join(""), "sequence":"0", "score":0.0, "partOfSpeech":"noun", "attributionText": [ "from the GNU version of the Collaborative International ", "Dictionary of English"].join(""), "seqString":"1." }] } }, { "request": { "method": "GET", "url": "http://api.wordnik.com/v4/word.json/asd/definitions", "params": { "limit":"1", "includeRelated":"true", "sourceDictionaries":"webster", "useCanonical":"true", "api_key":"a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5" } }, "response": { "code": 200, "data": [{ "textProns":[], "sourceDictionary":"gcide", "exampleUses":[], "relatedWords":[ { "words":["added"], "gram":"imp. & p. p.", "relationshipType":"form"}, { "words":["adding"], "gram":"p. pr. & vb. n.", "relationshipType":"form"}, { "words":["added"], "gram":"imp. & p. p.", "relationshipType":"form"}, { "words":["adding"], "gram":"p. pr. & vb. n.", "relationshipType":"form"}], "labels":[], "citations": [ { "source":"Gen. xxx. 24.", "cite":"The Lord shall add to me another son." } ], "word":"add", "text":[ "To give by way of increased possession (to any one); to ", "bestow (on)." ].join(""), "sequence":"0", "score":0.0, "partOfSpeech":"verb-transitive", "attributionText": [ "from the GNU version of the Collaborative International ", "Dictionary of English"].join(""), "seqString":"1." }] } }, { "request": { "method": "GET", "url": "http://api.wordnik.com/v4/word.json/add/definitions", "params": { "limit":"1", "includeRelated":"true", "sourceDictionaries":"webster", "useCanonical":"true", "api_key":"a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5" } }, "response": { "code": 200, "data": [{ "word":"add", "text":[ "To give by way of increased possession (to any one); to ", "bestow (on)." ].join("") }] } }, { "request": { "method": "GET", "url": "http://api.wordnik.com/v4/word.json/notaword/definitions", "params": { "limit":"1", "includeRelated":"true", "sourceDictionaries":"webster", "useCanonical":"true", "api_key":"a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5" } }, "response": { "code": 200, "data": [] } }, { "request": { "method": "GET", "url": "http://api.wordnik.com/v4/word.json/longword/definitions", "params": { "limit":"1", "includeRelated":"true", "sourceDictionaries":"webster", "useCanonical":"true", "api_key":"a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5" } }, "response": { "code": 200, "data": [{ "word":"longword", "text":[ "This is a definition that is very very very very very", " very very very very very very very very very very very", " very very very very very very very very very very very", " very very very very very very very very very very very", " very very very very very very very very very very long" ].join("") }] } }]; };
praekelt/go-dictionary
test/fixtures.js
JavaScript
bsd-3-clause
5,814
Meteor.methods({ uploadFile: function (file) { console.log('saving '+file.name+' on server'); //appends to current file by same name.. file.save('/tmp/uploads', {}); } });
Pent/stoo
server/saveFile.js
JavaScript
bsd-3-clause
187
var DataMapping = require("montage-data/logic/service/data-mapping").DataMapping, ObjectDescriptor = require("montage-data/logic/model/object-descriptor").ObjectDescriptor; describe("A DataMapping", function() { function ClassA(a, b, c, d) { this.a = a; this.b = b; this.c = c; this.d = d; } function ClassB(a, b, c, d) { this.a = a; this.b = b; this.c = c; this.d = d; } it("can be created", function () { expect(new DataMapping()).toBeDefined(); }); it("copies raw data properties by default", function () { var object = {x: 42}, random = Math.random(), data = new ClassA(1, 2, object, random), mapped = new ClassB(); new DataMapping().mapFromRawData(mapped, data); expect(mapped).toEqual(new ClassB(1, 2, object, random)); }); });
montagestudio/montage-data
test/spec/data-mapping.js
JavaScript
bsd-3-clause
907
var NAVTREEINDEX7 = { "classIogn_1_1DatabaseIO.html#a4d31b02871089cc417ea990591acb9e7":[4,0,64,2,9], "classIogn_1_1DatabaseIO.html#a4f78970eb21804fb1eb863b93d174e0c":[4,0,64,2,42], "classIogn_1_1DatabaseIO.html#a509bdb2de719b050921fd03bd207361e":[4,0,64,2,21], "classIogn_1_1DatabaseIO.html#a567e232671c85ec139a7f32faf76c877":[4,0,64,2,10], "classIogn_1_1DatabaseIO.html#a5904dba99e21eaf6282d37394f2a513b":[4,0,64,2,54], "classIogn_1_1DatabaseIO.html#a64a655c1a5a50cba26c3fd87ab837b56":[4,0,64,2,6], "classIogn_1_1DatabaseIO.html#a6503f106c8686fde564c0966836f6ea3":[4,0,64,2,55], "classIogn_1_1DatabaseIO.html#a68969af20be800a8379c5940638d837b":[4,0,64,2,18], "classIogn_1_1DatabaseIO.html#a6d30dd13247c8da4de57d6a404c947f3":[4,0,64,2,27], "classIogn_1_1DatabaseIO.html#a704f25730c532ac67b7b71a9675d9de7":[4,0,64,2,39], "classIogn_1_1DatabaseIO.html#a71051cdc0000111a2d54e11f72929bc3":[4,0,64,2,53], "classIogn_1_1DatabaseIO.html#a77caac769115f8fb21a7ebef496f3220":[4,0,64,2,23], "classIogn_1_1DatabaseIO.html#a7a7040731f50f870721dd9803bbdcec6":[4,0,64,2,14], "classIogn_1_1DatabaseIO.html#a7c703a53160d8860611fd55d787ace3c":[4,0,64,2,1], "classIogn_1_1DatabaseIO.html#a7cecaf86bfedc04216c4a30697e875fd":[4,0,64,2,57], "classIogn_1_1DatabaseIO.html#a7ddf05aad9f647150922a91999c08cd9":[4,0,64,2,11], "classIogn_1_1DatabaseIO.html#a84a1354c5b74eafc2df1c666ecd2812d":[4,0,64,2,50], "classIogn_1_1DatabaseIO.html#a86c7a4e4185be29afc8b4d274a08e566":[4,0,64,2,34], "classIogn_1_1DatabaseIO.html#a8c6f6e516b509159942fdffa27d1cc9b":[4,0,64,2,46], "classIogn_1_1DatabaseIO.html#a8e36d96d6dd77f55db2a45401e9bc425":[4,0,64,2,51], "classIogn_1_1DatabaseIO.html#a8fb6a277f2b675197194c41db4f7bc7e":[4,0,64,2,31], "classIogn_1_1DatabaseIO.html#a99459762d0ff7aebe486ba5052baa386":[4,0,64,2,2], "classIogn_1_1DatabaseIO.html#aa021bc9f0a9d3b8214f8608d6abefa9c":[4,0,64,2,17], "classIogn_1_1DatabaseIO.html#aad08ce04e22d8b5665da7b627f1379f6":[4,0,64,2,41], "classIogn_1_1DatabaseIO.html#ab0d22387b04886ef956b3b8bf3a62c4a":[4,0,64,2,7], "classIogn_1_1DatabaseIO.html#ab1f013f572ff7e023d6c23a27c6b51b9":[4,0,64,2,48], "classIogn_1_1DatabaseIO.html#ab67092adab83d99fca4dffce6e4c1762":[4,0,64,2,20], "classIogn_1_1DatabaseIO.html#ac5739ee985ef7768a9828d56b7e65133":[4,0,64,2,44], "classIogn_1_1DatabaseIO.html#ac668eea5a603278f4029797e0ecef72b":[4,0,64,2,16], "classIogn_1_1DatabaseIO.html#acc9d78bc61d7a1189d39c4848050b92c":[4,0,64,2,56], "classIogn_1_1DatabaseIO.html#acfe917b575765e8045e9bce9ac83e4f3":[4,0,64,2,28], "classIogn_1_1DatabaseIO.html#adaeda3abcf261130233d0e34db0c0024":[4,0,64,2,22], "classIogn_1_1DatabaseIO.html#ae4a0a9b2d8458e3fc4a5496365ff4088":[4,0,64,2,38], "classIogn_1_1DatabaseIO.html#ae4d037f0c59d8f33078c1468d9fbaf97":[4,0,64,2,0], "classIogn_1_1DatabaseIO.html#ae56bab2a11f21796f54b70544207197a":[4,0,64,2,13], "classIogn_1_1DatabaseIO.html#ae57de4f765f5c7446cd787fdece6ff40":[4,0,64,2,60], "classIogn_1_1DatabaseIO.html#ae62830685d87e86bec496701000c17fa":[4,0,64,2,58], "classIogn_1_1DatabaseIO.html#aec9e0571cc2a24aa062acaa2c23b60b8":[4,0,64,2,8], "classIogn_1_1DatabaseIO.html#aede0b2afbf73abf2a2effffffe275d6c":[4,0,64,2,24], "classIogn_1_1DatabaseIO.html#af218ff0bca527558d2673557f0bd40ea":[4,0,64,2,36], "classIogn_1_1DatabaseIO.html#af3e3864087448c008a3b7d1ffd9365e0":[4,0,64,2,35], "classIogn_1_1DatabaseIO.html#af5a0f36dfdcf3f369965bdc96db9624c":[4,0,64,2,52], "classIogn_1_1DatabaseIO.html#af8d1d087e623fa885a0f53b865319979":[4,0,64,2,62], "classIogn_1_1ExodusMesh.html":[4,0,64,4], "classIogn_1_1ExodusMesh.html#a1426cd0ad97c69c7b46b2b1fb271f089":[4,0,64,4,13], "classIogn_1_1ExodusMesh.html#a196c58a4ebc812247e66825e2ecf0e57":[4,0,64,4,25], "classIogn_1_1ExodusMesh.html#a1f84298bd61b9fc904a2b194196a7ecd":[4,0,64,4,0], "classIogn_1_1ExodusMesh.html#a228bc43d440665c9ffa7a971ff2a205d":[4,0,64,4,15], "classIogn_1_1ExodusMesh.html#a2785e4f6e92f0bc147dd88c0dcac75c7":[4,0,64,4,12], "classIogn_1_1ExodusMesh.html#a2b8f4f67766498993cde2752e223313f":[4,0,64,4,24], "classIogn_1_1ExodusMesh.html#a55f1e2d41f7f457491c9f705668e1603":[4,0,64,4,33], "classIogn_1_1ExodusMesh.html#a57a246a3b031b623b514a577ec0c4c90":[4,0,64,4,8], "classIogn_1_1ExodusMesh.html#a590d018d89ba2e5799c310cbecdad4bb":[4,0,64,4,23], "classIogn_1_1ExodusMesh.html#a5dcdfdce5b8df21e6133109fd567cd5a":[4,0,64,4,32], "classIogn_1_1ExodusMesh.html#a60b7772a5af42b5fb26ae6b0c78863a0":[4,0,64,4,18], "classIogn_1_1ExodusMesh.html#a6cfaef3ab8a71d133c190aa63d168146":[4,0,64,4,6], "classIogn_1_1ExodusMesh.html#a6ec05cc82636f3eff7615210cf4b1a8c":[4,0,64,4,9], "classIogn_1_1ExodusMesh.html#a7721c157ee2f1c84c89c012642d99a27":[4,0,64,4,22], "classIogn_1_1ExodusMesh.html#a798037e20bd738e9fe4fbea5c25dca93":[4,0,64,4,10], "classIogn_1_1ExodusMesh.html#a86158efe7fe9c8598f92f0fb0e31a50e":[4,0,64,4,20], "classIogn_1_1ExodusMesh.html#aa1abff5fd86c3b561bb95cb245202227":[4,0,64,4,27], "classIogn_1_1ExodusMesh.html#aa4105a915087d145cd9d01b9f0f5248d":[4,0,64,4,2], "classIogn_1_1ExodusMesh.html#aa51baab6b21b7d6d1e0ce04c4337b127":[4,0,64,4,7], "classIogn_1_1ExodusMesh.html#ab886006a170dcb74faa6ecd375c1f459":[4,0,64,4,19], "classIogn_1_1ExodusMesh.html#abc7d9d1de0fa8c9b042b0aadd71df784":[4,0,64,4,1], "classIogn_1_1ExodusMesh.html#ac78df6eec1ade158f8371c4fa5d30baa":[4,0,64,4,11], "classIogn_1_1ExodusMesh.html#acfb7baea4bf762edb1076a976a75b055":[4,0,64,4,30], "classIogn_1_1ExodusMesh.html#ad5497328356b83714c576263bb0f1356":[4,0,64,4,21], "classIogn_1_1ExodusMesh.html#ad99efa8471084a0e2b8c168674f4e47d":[4,0,64,4,28], "classIogn_1_1ExodusMesh.html#add86edcc62c60a937435152d5609aed7":[4,0,64,4,16], "classIogn_1_1ExodusMesh.html#ae6f9c1b7479ec7356fda8d3ec624bdf3":[4,0,64,4,17], "classIogn_1_1ExodusMesh.html#ae75503dc4e3be1224fc57af8172a75f7":[4,0,64,4,31], "classIogn_1_1ExodusMesh.html#aeba5d79ab480d02e077c3d5b114f5337":[4,0,64,4,29], "classIogn_1_1ExodusMesh.html#aebfe20a7233940c8f1bc4ec1244fec69":[4,0,64,4,4], "classIogn_1_1ExodusMesh.html#aec704d94557fd943f21fc1a050cb6062":[4,0,64,4,14], "classIogn_1_1ExodusMesh.html#af51819218b717ae55f90e6dd0b8b4f75":[4,0,64,4,5], "classIogn_1_1ExodusMesh.html#afe3bb8943aeea6598b1c2f7e54f2c532":[4,0,64,4,26], "classIogn_1_1ExodusMesh.html#aff18e3ce3a36ce1b2c4a7c48f34bb380":[4,0,64,4,3], "classIogn_1_1GeneratedMesh.html":[4,0,64,5], "classIogn_1_1GeneratedMesh.html#a019976d10c69f756873e0a6fadf2e8cc":[4,0,64,5,65], "classIogn_1_1GeneratedMesh.html#a02e95e6ec75bd7ba0f06e6fcdd1e7227":[4,0,64,5,19], "classIogn_1_1GeneratedMesh.html#a039f2e588989fd56835209f3ca9dd42c":[4,0,64,5,49], "classIogn_1_1GeneratedMesh.html#a044bd2933b7defc613d2575e0784ead9":[4,0,64,5,78], "classIogn_1_1GeneratedMesh.html#a0da6689bb52014b75b29bc2422f93931":[4,0,64,5,66], "classIogn_1_1GeneratedMesh.html#a0e2fdc0a35b15deb16e77d4abb6bbb5e":[4,0,64,5,52], "classIogn_1_1GeneratedMesh.html#a173f48504d945ec4ad891c29c0e6ac34":[4,0,64,5,8], "classIogn_1_1GeneratedMesh.html#a1948a31534d670445b661d9a6156045c":[4,0,64,5,67], "classIogn_1_1GeneratedMesh.html#a198fba99565d1b8a4943fee4cb340dc6":[4,0,64,5,55], "classIogn_1_1GeneratedMesh.html#a1af1eec83012f46c09bb83ac483fdee5":[4,0,64,5,61], "classIogn_1_1GeneratedMesh.html#a1c0ed57406d0a57db7138ae065eda366":[4,0,64,5,40], "classIogn_1_1GeneratedMesh.html#a1d7592877dd54663fd5a863737afca2a":[4,0,64,5,18], "classIogn_1_1GeneratedMesh.html#a1ef6c65fbbec4f57ed6afde59a0d8bd9":[4,0,64,5,11], "classIogn_1_1GeneratedMesh.html#a1f3b8743a90effc7e9709249c98abdf0":[4,0,64,5,70], "classIogn_1_1GeneratedMesh.html#a2542d5e3dfad60f2f721dae5219ca3db":[4,0,64,5,68], "classIogn_1_1GeneratedMesh.html#a281ca8a27246c8106d3694b4ddf3bb24":[4,0,64,5,75], "classIogn_1_1GeneratedMesh.html#a29edc9ec94c7f7d496c1d897adbbf4de":[4,0,64,5,47], "classIogn_1_1GeneratedMesh.html#a2d860ec5ea8c4f52103e699f59bf3802":[4,0,64,5,85], "classIogn_1_1GeneratedMesh.html#a2e22640f336e797a31806e5850e696d3":[4,0,64,5,4], "classIogn_1_1GeneratedMesh.html#a3ee445d2299a764c57a2c385f2ce79fd":[4,0,64,5,34], "classIogn_1_1GeneratedMesh.html#a4356d7dc3c22525095b7154db26af75d":[4,0,64,5,82], "classIogn_1_1GeneratedMesh.html#a45b80209c9e51e84ed41483101b8e845":[4,0,64,5,16], "classIogn_1_1GeneratedMesh.html#a48aeb94ab3d67cb0b9d9ab050fdbe1f9":[4,0,64,5,24], "classIogn_1_1GeneratedMesh.html#a50bf123b6548caa25e31d466eba62daa":[4,0,64,5,73], "classIogn_1_1GeneratedMesh.html#a596a8ae9cebb5d8ac0855e53d36d6e95":[4,0,64,5,44], "classIogn_1_1GeneratedMesh.html#a5cb67eb372c3d129a31ae3f9c40c8958":[4,0,64,5,25], "classIogn_1_1GeneratedMesh.html#a5fda1c9c6eedb56f21a80c70649cf00e":[4,0,64,5,0], "classIogn_1_1GeneratedMesh.html#a5fda1c9c6eedb56f21a80c70649cf00ea0e3164560744889a3e70ace0217b71dd":[4,0,64,5,0,0], "classIogn_1_1GeneratedMesh.html#a5fda1c9c6eedb56f21a80c70649cf00ea52d815fa530a74910df05c2a63e82056":[4,0,64,5,0,5], "classIogn_1_1GeneratedMesh.html#a5fda1c9c6eedb56f21a80c70649cf00eaab7de06ad1d68fb486d80310fd6bd609":[4,0,64,5,0,4], "classIogn_1_1GeneratedMesh.html#a5fda1c9c6eedb56f21a80c70649cf00ead39695af2d82deb9bb63b6bb0ff15594":[4,0,64,5,0,3], "classIogn_1_1GeneratedMesh.html#a5fda1c9c6eedb56f21a80c70649cf00eae7b785c0c345a7a665299b2ff2d20953":[4,0,64,5,0,1], "classIogn_1_1GeneratedMesh.html#a5fda1c9c6eedb56f21a80c70649cf00eaf2f79c3f8f193864691d4ae78b3ddfbf":[4,0,64,5,0,2], "classIogn_1_1GeneratedMesh.html#a607a532e4e897982015d5e15108bb5b6":[4,0,64,5,56], "classIogn_1_1GeneratedMesh.html#a60cc36536d183fc61255883887679477":[4,0,64,5,23], "classIogn_1_1GeneratedMesh.html#a6153d3269cadb8a0074083ae42ec732d":[4,0,64,5,35], "classIogn_1_1GeneratedMesh.html#a646768c0285a3a86fc8d66416907018a":[4,0,64,5,77], "classIogn_1_1GeneratedMesh.html#a67a83ff6386e9f39aee35e1604c50cc4":[4,0,64,5,32], "classIogn_1_1GeneratedMesh.html#a67f12e833eb2ae2a8b0a8ad53b8f2de8":[4,0,64,5,13], "classIogn_1_1GeneratedMesh.html#a6abf96a7155db5b41acb68c5e5e5bfdf":[4,0,64,5,15], "classIogn_1_1GeneratedMesh.html#a73d09586d07597a0f6c9afa7536e7254":[4,0,64,5,29], "classIogn_1_1GeneratedMesh.html#a774f5d2cc3c9d735959121260a05f571":[4,0,64,5,84], "classIogn_1_1GeneratedMesh.html#a78b029bb950f8c58a6576ead6b4f00f1":[4,0,64,5,81], "classIogn_1_1GeneratedMesh.html#a78ef32eaeec128564a364248a33f3dbf":[4,0,64,5,71], "classIogn_1_1GeneratedMesh.html#a7d57a6c1a02f37b387a393f6895ebafd":[4,0,64,5,20], "classIogn_1_1GeneratedMesh.html#a80b39683b24235fcc06f1b8e1df04e4a":[4,0,64,5,9], "classIogn_1_1GeneratedMesh.html#a81d1adac34424c042de064e78377e1b4":[4,0,64,5,76], "classIogn_1_1GeneratedMesh.html#a83a6078a3e0fd8f119a864b694c275b7":[4,0,64,5,36], "classIogn_1_1GeneratedMesh.html#a854d1a47c083dda94d1d062715abbd99":[4,0,64,5,45], "classIogn_1_1GeneratedMesh.html#a87d33fb8709f4af5f9cdc68253e52907":[4,0,64,5,39], "classIogn_1_1GeneratedMesh.html#a88c210ac9a3d7218b2d5b61a320e40dc":[4,0,64,5,74], "classIogn_1_1GeneratedMesh.html#a8ca47dae9ba3512c1c8f97c553c646dc":[4,0,64,5,38], "classIogn_1_1GeneratedMesh.html#a8fc90fe583579d2e517886d61921f783":[4,0,64,5,57], "classIogn_1_1GeneratedMesh.html#a8ff4045f9e46990d7e02444d539b7013":[4,0,64,5,46], "classIogn_1_1GeneratedMesh.html#a915aaa8cba0e22c372d06453f66821f0":[4,0,64,5,69], "classIogn_1_1GeneratedMesh.html#a9917d28a15baa87231b8cc22929601f3":[4,0,64,5,83], "classIogn_1_1GeneratedMesh.html#a99c789006b20196fb83b6e9a801740e0":[4,0,64,5,59], "classIogn_1_1GeneratedMesh.html#a9e825e7d61b0484d2ad461f3fa24bf09":[4,0,64,5,42], "classIogn_1_1GeneratedMesh.html#a9fc4cb3c4fde1b63680838e7dda5a019":[4,0,64,5,27], "classIogn_1_1GeneratedMesh.html#aa79480f29286ba894936d3953f117356":[4,0,64,5,10], "classIogn_1_1GeneratedMesh.html#aa83160a16f7dde96086c096f9811a5ea":[4,0,64,5,3], "classIogn_1_1GeneratedMesh.html#aa8fecab82c56a3b0580163418d7c69e8":[4,0,64,5,80], "classIogn_1_1GeneratedMesh.html#aaaed84638dcfcacc18922d35cc8348ec":[4,0,64,5,30], "classIogn_1_1GeneratedMesh.html#aaf0d8cfcac9e12393b81d3f2e73f4c43":[4,0,64,5,48], "classIogn_1_1GeneratedMesh.html#ab14c39196bcfd234b8d737dde5d835b7":[4,0,64,5,31], "classIogn_1_1GeneratedMesh.html#ab1c9654c9c11407764fe61d6fdf2960f":[4,0,64,5,51], "classIogn_1_1GeneratedMesh.html#ab2e482c703e0ee0ec2087ea749c64cf3":[4,0,64,5,79], "classIogn_1_1GeneratedMesh.html#ab509db4f12cf2bcaee8763c56ac6d187":[4,0,64,5,7], "classIogn_1_1GeneratedMesh.html#aba34619c42e1af678511fd5718781932":[4,0,64,5,43], "classIogn_1_1GeneratedMesh.html#ac787e9970f88a517c64b943a842910c9":[4,0,64,5,33], "classIogn_1_1GeneratedMesh.html#ac932df42f2cf2a379e5359be1d9e8d94":[4,0,64,5,5], "classIogn_1_1GeneratedMesh.html#acab032df8c98616a0553930b344dbf6c":[4,0,64,5,12], "classIogn_1_1GeneratedMesh.html#acb6607d069e9c847c6ea27929758e706":[4,0,64,5,58], "classIogn_1_1GeneratedMesh.html#acd84560dcba7bffdbcdbe4c12318450f":[4,0,64,5,50], "classIogn_1_1GeneratedMesh.html#acf0b8edd6835b477db3fb891ec873cc0":[4,0,64,5,63], "classIogn_1_1GeneratedMesh.html#ad7301d73848b20e2590b56763de521b8":[4,0,64,5,2], "classIogn_1_1GeneratedMesh.html#ada5d7475f9b4cc33312181db5802038b":[4,0,64,5,22], "classIogn_1_1GeneratedMesh.html#ada65bf0562967a55ab5015cabfcd31bc":[4,0,64,5,72], "classIogn_1_1GeneratedMesh.html#adc70aa944b8e55eb598e1ada8fb003ec":[4,0,64,5,26], "classIogn_1_1GeneratedMesh.html#add032602121f08555548d8c8a58d0ba7":[4,0,64,5,6], "classIogn_1_1GeneratedMesh.html#ae63bcfa4dec36e883b5c1333154f389b":[4,0,64,5,37], "classIogn_1_1GeneratedMesh.html#ae7415cdfce392fc2c993f20fc258eb9e":[4,0,64,5,17], "classIogn_1_1GeneratedMesh.html#ae872b2bc88870537de38c044e3effcdc":[4,0,64,5,21], "classIogn_1_1GeneratedMesh.html#ae8c57a72f98f9a3c31f33a79836cdf51":[4,0,64,5,64], "classIogn_1_1GeneratedMesh.html#ae95a0d0eed44d809e04e839abfd9995f":[4,0,64,5,54], "classIogn_1_1GeneratedMesh.html#af0a5cb6153f5389b4d733cd1b2eea1ea":[4,0,64,5,60], "classIogn_1_1GeneratedMesh.html#af128caee4ea3af583b8e585540559945":[4,0,64,5,28], "classIogn_1_1GeneratedMesh.html#af8f492bc76477998966f104debc98d0b":[4,0,64,5,53], "classIogn_1_1GeneratedMesh.html#af9dde723f32dbd382071ca48cd3603d8":[4,0,64,5,41], "classIogn_1_1GeneratedMesh.html#afa54f23882f6ce165c0faa35ca90e0ea":[4,0,64,5,14], "classIogn_1_1GeneratedMesh.html#afb85c3f28b89a17725a0fae633f1e5a3":[4,0,64,5,1], "classIogn_1_1GeneratedMesh.html#aff06ce6326497f17d293173f117fd6eb":[4,0,64,5,62], "classIogn_1_1IOFactory.html":[4,0,64,6], "classIogn_1_1IOFactory.html#a40e5178c58ee47278e5834961cd2445e":[4,0,64,6,2], "classIogn_1_1IOFactory.html#a5c5ea69ac3f7d0697e533b1e2272a964":[4,0,64,6,0], "classIogn_1_1IOFactory.html#aa48939456bf85eb76980a38a7b2acdff":[4,0,64,6,1], "classIohb_1_1DatabaseIO.html":[4,0,65,0], "classIohb_1_1DatabaseIO.html#a0425afc6a1c3836a00bcd524385f3b5a":[4,0,65,0,48], "classIohb_1_1DatabaseIO.html#a06498f2ca86695f8834d36f027bcee45":[4,0,65,0,16], "classIohb_1_1DatabaseIO.html#a11a475218eb43a9515f1aa02920e4e8e":[4,0,65,0,33], "classIohb_1_1DatabaseIO.html#a149339d6f87ed1b831a78a531288b589":[4,0,65,0,23], "classIohb_1_1DatabaseIO.html#a14979888aa691450b6cdc5ba6ce06f4d":[4,0,65,0,45], "classIohb_1_1DatabaseIO.html#a1540090f1e82377b6fded5e37258ba69":[4,0,65,0,35], "classIohb_1_1DatabaseIO.html#a171d4690a7721dae6fd5381666f57a04":[4,0,65,0,53], "classIohb_1_1DatabaseIO.html#a1ed98178daf9881a9fd4905253b4a34a":[4,0,65,0,9], "classIohb_1_1DatabaseIO.html#a222031fa340da9493affabb6e0fb8850":[4,0,65,0,36], "classIohb_1_1DatabaseIO.html#a2e6e23b7b5f46d63ae168a40b5e85512":[4,0,65,0,26], "classIohb_1_1DatabaseIO.html#a2f85e187e5aa6685d08614585b32eb58":[4,0,65,0,28], "classIohb_1_1DatabaseIO.html#a334bc9a842b1c16e877f49ecefda6439":[4,0,65,0,37], "classIohb_1_1DatabaseIO.html#a372df18e1843d7f40a246cc891d6063f":[4,0,65,0,14], "classIohb_1_1DatabaseIO.html#a3beb94420150ba18cbe524224e09c171":[4,0,65,0,43], "classIohb_1_1DatabaseIO.html#a3d2c9c0bc0e681c6e2f2e7a4d85ac5f5":[4,0,65,0,52], "classIohb_1_1DatabaseIO.html#a3f4e7d713e2ca1262bf917e8d62f0397":[4,0,65,0,20], "classIohb_1_1DatabaseIO.html#a409f72d2949f834ff1ee9a3544c019bc":[4,0,65,0,1], "classIohb_1_1DatabaseIO.html#a4555c992e67be7ab9bc2e3435c4872c0":[4,0,65,0,8], "classIohb_1_1DatabaseIO.html#a4a5e3ca261a6c679496f40b780945872":[4,0,65,0,34], "classIohb_1_1DatabaseIO.html#a55f12c7379af5e04a6be07ec75ff5252":[4,0,65,0,40], "classIohb_1_1DatabaseIO.html#a5b7db18a777b445caa1880871f86581b":[4,0,65,0,11], "classIohb_1_1DatabaseIO.html#a60b6274217cb4675a11fad99797efec5":[4,0,65,0,41], "classIohb_1_1DatabaseIO.html#a61deb9361614d19a550b21ff5e8b8d51":[4,0,65,0,32], "classIohb_1_1DatabaseIO.html#a62086b17aff53d4bc28db295f535b026":[4,0,65,0,3], "classIohb_1_1DatabaseIO.html#a6295069bf27f1fba8787abe863aebe32":[4,0,65,0,51], "classIohb_1_1DatabaseIO.html#a67430c1bb08dffa5c41115cc1c08f759":[4,0,65,0,38], "classIohb_1_1DatabaseIO.html#a6f51330130211da88fed3f6c7109dfe2":[4,0,65,0,0], "classIohb_1_1DatabaseIO.html#a74f8f1c5f18f07c06f725511b55bc2a3":[4,0,65,0,7], "classIohb_1_1DatabaseIO.html#a75ab126ae48a989bc5c4b918f72c1a07":[4,0,65,0,17], "classIohb_1_1DatabaseIO.html#a75cc65cc986e2eb24cc915ab33183d80":[4,0,65,0,29], "classIohb_1_1DatabaseIO.html#a75df47c7782cbe86e68696a77dee0f1e":[4,0,65,0,50], "classIohb_1_1DatabaseIO.html#a7840bb08b4fd252a1824bd34c3fdd143":[4,0,65,0,13], "classIohb_1_1DatabaseIO.html#a80eb0c0374fda330f9f16965bcfec5a0":[4,0,65,0,30], "classIohb_1_1DatabaseIO.html#a85c7d1a98d7adc8205a95ade7bbc3f8b":[4,0,65,0,21], "classIohb_1_1DatabaseIO.html#a8a7e9ea6c9ee4886245cf9854b30ca92":[4,0,65,0,12], "classIohb_1_1DatabaseIO.html#a940b15793476c848161853b0c399f8af":[4,0,65,0,44], "classIohb_1_1DatabaseIO.html#a9821d1a682d3e3a0292e4a5b0ce0c374":[4,0,65,0,31], "classIohb_1_1DatabaseIO.html#a9d78c07810fbaa22e9729eb191d45752":[4,0,65,0,5], "classIohb_1_1DatabaseIO.html#aa4259c0205b7338e36e8ebf5ed142262":[4,0,65,0,4], "classIohb_1_1DatabaseIO.html#aa7d1cab20bcb347e2a10e4a699b4bb01":[4,0,65,0,19], "classIohb_1_1DatabaseIO.html#aacbf1478e80114cf69770b2c4d868f70":[4,0,65,0,55], "classIohb_1_1DatabaseIO.html#ab890a36edcf5f9cd61f255cbe14058b2":[4,0,65,0,54], "classIohb_1_1DatabaseIO.html#ab96a03cea2a276884b7e5a60d5730c48":[4,0,65,0,56], "classIohb_1_1DatabaseIO.html#abefb27b6cb9ab7fbfae439b9023dbeb6":[4,0,65,0,6], "classIohb_1_1DatabaseIO.html#ac0f3172b2fc161f2208945788ea85d65":[4,0,65,0,49], "classIohb_1_1DatabaseIO.html#ac2ce5a3711300a43f9b9381e472bd625":[4,0,65,0,15], "classIohb_1_1DatabaseIO.html#ac6d14b0261a07dd05402a149194a435b":[4,0,65,0,18], "classIohb_1_1DatabaseIO.html#ad1fd4fa960591553086edff8a6ee20e4":[4,0,65,0,10], "classIohb_1_1DatabaseIO.html#add79581e85907669ee33c797e633b9c8":[4,0,65,0,25], "classIohb_1_1DatabaseIO.html#adf759eddbe96e0b09e6807ea2680a2f2":[4,0,65,0,2], "classIohb_1_1DatabaseIO.html#ae4cbd1877902f335396d1aa5b1e4218d":[4,0,65,0,47], "classIohb_1_1DatabaseIO.html#ae8ffa290f634ae6ac7a016ee03abd1d3":[4,0,65,0,22], "classIohb_1_1DatabaseIO.html#ae9a0e90a733b8b1e75810f5c63e39edd":[4,0,65,0,24], "classIohb_1_1DatabaseIO.html#aec1bc1b47445d567a2ec33881a493984":[4,0,65,0,27], "classIohb_1_1DatabaseIO.html#af2679b5df217d772129357bc2a648914":[4,0,65,0,39], "classIohb_1_1DatabaseIO.html#afa89fbf0d222beee5ea4f0dc64790f2e":[4,0,65,0,46], "classIohb_1_1DatabaseIO.html#afc13975ead75040d3f6e4fe1ce8dc778":[4,0,65,0,42], "classIohb_1_1IOFactory.html":[4,0,65,1], "classIohb_1_1IOFactory.html#a2433d4de9ffa2d11dab63d4a48ea5c4c":[4,0,65,1,1], "classIohb_1_1IOFactory.html#ab892fb1738380590739d96fe1263e2c1":[4,0,65,1,0], "classIohb_1_1IOFactory.html#ad56f59e03b21fbeabe99904ac286c436":[4,0,65,1,2], "classIohb_1_1Layout.html":[4,0,65,2], "classIohb_1_1Layout.html#a008a95e0563088aa81320b5bcd1c8222":[4,0,65,2,4], "classIohb_1_1Layout.html#a112bbc36bd1e272ba407647d1d9174f6":[4,0,65,2,21], "classIohb_1_1Layout.html#a193e36c297502e28fe14d1d827dfc078":[4,0,65,2,20], "classIohb_1_1Layout.html#a1ce5bece951fce1536aed3f2dfc28a29":[4,0,65,2,14], "classIohb_1_1Layout.html#a1d169dbf45b68b1a722dcb787cf04eea":[4,0,65,2,8], "classIohb_1_1Layout.html#a1e708b18a1911d8e1267ccd753bc3594":[4,0,65,2,15], "classIohb_1_1Layout.html#a239fc494da656cd053af23b3d783db75":[4,0,65,2,0], "classIohb_1_1Layout.html#a5db9e63309152d635f747ec568858ab4":[4,0,65,2,18], "classIohb_1_1Layout.html#a65cd690cb4527012323ddf8cf781959a":[4,0,65,2,12], "classIohb_1_1Layout.html#a68f78edcffaa448b8d785723840af94a":[4,0,65,2,11], "classIohb_1_1Layout.html#a729244eba239301a4d18f70775bc8a7e":[4,0,65,2,3], "classIohb_1_1Layout.html#a735fee98692c08c54500e414a0f411e3":[4,0,65,2,2] };
nschloe/seacas
docs/ioss_html/navtreeindex7.js
JavaScript
bsd-3-clause
20,177
export function createDate(y, m, d, h, M, s, ms) { // can't just apply() to create a date: // https://stackoverflow.com/q/181348 var date = new Date(y, m, d, h, M, s, ms); // the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0 && isFinite(date.getFullYear())) { date.setFullYear(y); } return date; } export function createUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); // the Date.UTC function remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) { date.setUTCFullYear(y); } return date; }
hieupham0206/yii-cloudteam-app
vendor/bower/moment/src/lib/create/date-from-array.js
JavaScript
bsd-3-clause
635
"use strict"; // https://codereview.chromium.org/api/148223004/70001/?comments=true function PatchSet(issue, id, sequence) { this.files = []; // Array<PatchFile> this.sourceFiles = []; // Array<PatchFile> this.testFiles = []; // Array<PatchFile> this.tryJobResults = []; // Array<tryJobResults> this.created = ""; // Date this.messageCount = 0; this.draftCount = 0; this.lastModified = ""; // Date this.issue = issue || null; this.owner = null // User this.message = ""; this.id = id || 0; this.sequence = sequence || 0; this.commit = false; this.mostRecent = false; this.active = false; } PatchSet.DETAIL_URL = "/api/{1}/{2}/?comments=true" PatchSet.REVERT_URL = "/api/{1}/{2}/revert"; PatchSet.prototype.getDetailUrl = function() { return PatchSet.DETAIL_URL.assign( encodeURIComponent(this.issue.id), encodeURIComponent(this.id)); }; PatchSet.prototype.getRevertUrl = function() { return PatchSet.REVERT_URL.assign( encodeURIComponent(this.issue.id), encodeURIComponent(this.id)); }; PatchSet.prototype.loadDetails = function() { var patchset = this; return loadJSON(this.getDetailUrl()).then(function(data) { patchset.parseData(data); return patchset; }); }; PatchSet.prototype.revert = function(options) { if (!options.reason) return Promise.reject(new Error("Must supply a reason")); var patchset = this; return this.createRevertData(options).then(function(data) { return sendFormData(patchset.getRevertUrl(), data); }); }; PatchSet.prototype.createRevertData = function(options) { return User.loadCurrentUser().then(function(user) { return { xsrf_token: user.xsrfToken, revert_reason: options.reason, revert_cq: options.commit ? "1" : "0", }; }); }; PatchSet.prototype.parseData = function(data) { var patchset = this; if (!this.issue || data.issue != this.issue.id || data.patchset != this.id) { throw new Error("Invalid patchset loaded " + data.issue + " != " + this.issue.id + " or " + data.patchset + " != " + this.id); } this.owner = new User(data.owner); this.message = data.message || ""; this.lastModified = Date.utc.create(data.modified); this.created = Date.utc.create(data.created); Object.keys(data.files || {}, function(name, value) { var file = new PatchFile(patchset, name); file.parseData(value); patchset.files.push(file); }); this.files.sort(PatchFile.compare); this.files.forEach(function(file) { if (file.isLayoutTest) this.testFiles.push(file); else this.sourceFiles.push(file); }, this); var tryResults = (data.try_job_results || []).groupBy("builder"); this.tryJobResults = Object.keys(tryResults) .sort() .map(function(builder) { var jobSet = new TryJobResultSet(builder); jobSet.results = tryResults[builder].map(function(resultData) { var result = new TryJobResult(); result.parseData(resultData); return result; }).reverse(); return jobSet; }); };
esprehn/chromium-codereview
ui/model/patch_set.js
JavaScript
bsd-3-clause
3,280
var async = require('async'); Array.prototype.count = function() { var amount = 0; this.forEach(function(n) { if( typeof n !== 'number' ) { return; } amount += n; }); return amount; }; module.exports = function () { return function (game) { var iterateCuboid = function(l1, l2, callback) { var tasks = []; for(var x = (Math.min(l1.x, l2.x) & 0x0f); x <= (Math.max(l1.x, l2.x) & 0x0f); x++) { for(var y = Math.min(l1.y, l2.y); y <= Math.max(l1.y, l2.y); y++) { for(var z = (Math.min(l1.z, l2.z) & 0x0f); z <= (Math.max(l1.z, l2.z) & 0x0f); z++) { tasks.push(callback.bind(undefined, { 'x': x, 'y': y, 'z': z })); } } } return tasks; }; var locationToChunk = function(location) { return { x: location.x >> 4, z: location.z >> 4 }; }; var iterateChunks = function(l1, l2, callback) { var array = []; l1 = locationToChunk(l1); l2 = locationToChunk(l2); for(var x = Math.min(l1.x, l2.x); x <= Math.max(l1.x, l2.x); x++) { for(var z = Math.min(l1.z, l2.z); z <= Math.max(l1.z, l2.z); z++) { array.push(callback.bind(undefined, x, z)); } } return array; }; var set = function(axis, callbacks, finish) { var startTime = new Date().getTime(); var blocks = (Math.abs(axis.first.x - axis.second.x) + 1) * (Math.abs(axis.first.y - axis.second.y) + 1) * (Math.abs(axis.first.z - axis.second.z) + 1), count = 0; var weMin = { x: Math.min(axis.first.x, axis.second.x), z: Math.min(axis.first.z, axis.second.z) }, weMax = { x: Math.max(axis.first.x, axis.second.x), z: Math.max(axis.first.z, axis.second.z) }; async.series( iterateChunks(axis.first, axis.second, function(x, z, callback) { var cMin = { x: x << 4, y: axis.first.y, z: z << 4 }, cMax = { x: ((x + 1) << 4) -1, y: axis.second.y, z: ((z + 1) << 4) -1 }; if( weMin.x > cMin.x ) { cMin.x = weMin.x; } if( weMin.z > cMin.z ) { cMin.z = weMin.z; } if( weMax.x < cMax.x ) { cMax.x = weMax.x; } if( weMax.z < cMax.z ) { cMax.z = weMax.z; } game.map.get_chunk(x, z, function(err, chunk) { async.parallel( iterateCuboid(cMin, cMax, callbacks.perBlock.bind(undefined, chunk)), function(err, results) { var count = results.count(); process.nextTick( callback.bind(undefined, null, count) ); chunk.getPackage(function(newpacket) { game.players.forEach(function (player) { player.send(newpacket); }); }); } ); }); }), function(err, results) { var count = results.count(), endTime = new Date().getTime(); finish(count, endTime - startTime); } ); }; game.on("player:join", function (player) { player.message = function(msg, colour) { msg = "§5[Jsmc] §7" + msg; player.send({pid: 0x03, message: msg}); }; player.weAxis = {}; player.weReady = function() { if( !('first' in this.weAxis) || !('second' in this.weAxis) ) { return false; } return true; }; player.on("click", function (packet) { if( player.inventory.heldItem().block !== 269 ) { return; } player.weAxis.second = packet.location; player.message("Second point set!"); }); player.on("dig", function (packet) { if( player.inventory.heldItem().block !== 269 ) { return; } player.weAxis.first = packet.location; player.message("First point set!"); }); player.on("command", function(event) { // When player uses a command if (!player.isAdmin()) return; if( event.command.substr(0, 1) !== '/' ) return; event.command = event.command.substr(1); switch (event.command) { case "set": { game.storage.itemInfo(event.args[0], function(data) { if(!data) { player.message("No item " + event.args[0] + " found :(?"); return; } set(player.weAxis, { 'perBlock': function(chunk, location, callback) { chunk.set_block_type(location.x, location.z, location.y, data.id); callback(null, 1); } }, function(count, time) { player.message("Done in " + (Math.floor(time/100) / 10) + "!"); player.message("Changed " + count + " blocks!"); }); }); break; }; case "replace": { game.storage.itemInfo(event.args[0], function(item1) { game.storage.itemInfo(event.args[1], function(item2) { if(!item1) { player.message("No item " + event.args[0] + " found :(?"); return; } if(!item2) { player.message("No item " + event.args[1] + " found :(?"); return; } set(player.weAxis, { 'perBlock': function(chunk, location, callback) { if(chunk.get_block_type(location.x, location.z, location.y) !== item1.id) { callback(null, 0); return; } chunk.set_block_type(location.x, location.z, location.y, item2.id); callback(null, 1); } }, function( count, time) { player.message("Done in " + (Math.floor(time/100) / 10) + "!"); player.message("Changed " + count + " blocks!"); }); });}); break; }; case "clear": { player.weAxis = {}; player.message("World edit points cleared!"); break; }; } }); }); }; };
dralletje/DeserverPlots
plugins-example/game/worldedit.js
JavaScript
bsd-3-clause
8,927
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); let prettyPrintTypes = function (types) { const addArticle = (str) => { let vowels = ['a', 'e', 'i', 'o', 'u']; if (vowels.indexOf(str[0]) !== -1) { return 'an ' + str; } return 'a ' + str; }; return types.map(addArticle).join(' or '); }; let isArrayOfNotation = function (typeDefinition) { return /array of /.test(typeDefinition); }; let extractTypeFromArrayOfNotation = function (typeDefinition) { // The notation is e.g. 'array of string' return typeDefinition.split(' of ')[1]; }; let isValidTypeDefinition = (typeStr) => { if (isArrayOfNotation(typeStr)) { return isValidTypeDefinition(extractTypeFromArrayOfNotation(typeStr)); } return [ 'string', 'number', 'boolean', 'array', 'object', 'buffer', 'null', 'undefined', 'function' ].some(function (validType) { return validType === typeStr; }); }; const detectType = function (value) { if (value === null) { return 'null'; } if (Array.isArray(value)) { return 'array'; } if (Buffer.isBuffer(value)) { return 'buffer'; } return typeof value; }; const onlyUniqueValuesInArrayFilter = function (value, index, self) { return self.indexOf(value) === index; }; let detectTypeDeep = function (value) { let type = detectType(value); let typesInArray; if (type === 'array') { typesInArray = value .map((element) => { return detectType(element); }) .filter(onlyUniqueValuesInArrayFilter); type += ' of ' + typesInArray.join(', '); } return type; }; let validateArray = function (argumentValue, typeToCheck) { let allowedTypeInArray = extractTypeFromArrayOfNotation(typeToCheck); if (detectType(argumentValue) !== 'array') { return false; } return argumentValue.every(function (element) { return detectType(element) === allowedTypeInArray; }); }; function validateArgument(methodName, argumentName, argumentValue, argumentMustBe) { let isOneOfAllowedTypes = argumentMustBe.some(function (type) { if (!isValidTypeDefinition(type)) { throw new Error('Unknown type "' + type + '"'); } if (isArrayOfNotation(type)) { return validateArray(argumentValue, type); } return type === detectType(argumentValue); }); if (!isOneOfAllowedTypes) { throw new Error('Argument "' + argumentName + '" passed to ' + methodName + ' must be ' + prettyPrintTypes(argumentMustBe) + '. Received ' + detectTypeDeep(argumentValue)); } return false; } exports.validateArgument = validateArgument; ; function validateOptions(methodName, optionsObjName, obj, allowedOptions) { if (obj !== undefined) { validateArgument(methodName, optionsObjName, obj, ['object']); Object.keys(obj).forEach(function (key) { let argName = optionsObjName + '.' + key; if (allowedOptions.hasOwnProperty(key)) { validateArgument(methodName, argName, obj[key], allowedOptions[key]); } else { throw new Error('Unknown argument "' + argName + '" passed to ' + methodName); } }); } } exports.validateOptions = validateOptions; ; //# sourceMappingURL=validate.js.map
xblox/control-freak
_build/fs/utils/validate.js
JavaScript
bsd-3-clause
3,507
;(function($){ var objects = {}; $.editlive.sync = function() { $('editlive').each(function(){ var el = $(this); if (el.attr('app-label') && el.attr('module-name') && el.attr('field-name') && el.attr('object-id')) { var model = el.attr('app-label') +'.'+ el.attr('module-name'); if (!objects[model]) objects[model] = []; objects[model].push({ app_label: el.attr('app-label'), field_name: el.attr('field-name'), //field_type: el.data('type'), rendered_value: el.attr('rendered-value'), object_id: el.attr('object-id'), template_filters: el.attr('template_filters'), module_name: el.attr('module-name'), formset: el.attr('formset'), value: $('#'+ el.data('field-id')).val() //data: el.data() }); } }); }; var synched = function(data) { console.log(data); } $.editlive.do_sync = function() { Dajaxice.editlive.sync(synched, objects); }; $(function(){ $.editlive.sync(); }); })(jQuery);
h3/django-editlive
editlive/static/editlive/js/jquery.editlive.sync.js
JavaScript
bsd-3-clause
1,264
WGL.internal.Filter = function() { var manager = WGL.getManager(); var GLU = WGL.internal.GLUtils; manager.setFilter(this); this.rastersize = manager.r_size ; this.lastDim =""; this.filterProgram1d = GLU.compileShaders("filter1d_vShader", "filter1d_fShader", this); this.filterProgram2d = GLU.compileShaders("filter2d_vShader", "filter2d_fShader", this); // for Flags Dimension this.filterProgramFT = GLU.compileShaders("filterflags_vShader", "filterflags_fShader", this); this.filterProgramFT.name ="FlagsFilter"; var filterid = 'filterid'; manager.storeUniformLoc(this.filterProgram1d, filterid); manager.storeUniformLoc(this.filterProgram2d, filterid); manager.storeUniformLoc(this.filterProgramFT, filterid); var indexText = 'indexText'; manager.storeUniformLoc(this.filterProgram1d, indexText); manager.storeUniformLoc(this.filterProgram2d, indexText); manager.storeUniformLoc(this.filterProgramFT, indexText); manager.storeUniformLoc(this.filterProgramFT, 'isand'); manager.storeUniformLoc(this.filterProgramFT, 'num_selected'); //var isspatial = 'isspatial'; //manager.storeUniformLoc(this.filterProgram, isspatial); //this.filterProgram.name = "Main filter"; var framebuffer = []; var renderbuffer = []; var filterTexture = []; framebuffer.width = WGL.getRasterSize(); framebuffer.height = WGL.getRasterSize(); /*******************************first texture*************************************/ filterTexture[0] = gl.createTexture(); filterTexture[1] = gl.createTexture(); framebuffer[0] = gl.createFramebuffer(); framebuffer[1] = gl.createFramebuffer(); renderbuffer[0] = gl.createRenderbuffer(); renderbuffer[1] = gl.createRenderbuffer(); framebuffer[0].width = this.rastersize; framebuffer[0].height = this.rastersize; framebuffer[0].id = 0; framebuffer[1].width = this.rastersize; framebuffer[1].height = this.rastersize; framebuffer[1].id = 1; var activeID =0 ; var thatID = 1; /** Framebuffer */ confFrameBufferTexture(1); confFrameBufferTexture(0); function confFrameBufferTexture(tid){ /** Texture */ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer[tid]); //filterTexture[tid] = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, filterTexture[tid]); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, framebuffer.width, framebuffer.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); /** Render buffer */ //renderbuffer[tid] = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer[tid]); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, framebuffer.width, framebuffer.height); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, filterTexture[tid], 0); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer[tid]); /*set texture to 0*/ gl.viewport(0, 0, framebuffer.width,framebuffer.height); gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.bindTexture(gl.TEXTURE_2D, null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null); } /*evaluate all filters*/ this.applyFilterAll = function(dimensions) { gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer[thatID]); gl.viewport(0, 0, framebuffer.width,framebuffer.height); gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer[activeID]); gl.viewport(0, 0, framebuffer.width,framebuffer.height); gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.disable(gl.DEPTH_TEST); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE); for (var i in dimensions) { for (var f in dimensions[i].filters) { /* traverse all filters and evaluate them */ var d = dimensions[i].filters[f]; /*Filter texture*/ if(d.isActive){ /* Activate filter texture*/ if (d.isspatial === 2.0){ d.writeToThatTexture(dimensions[i], framebuffer[thatID]); // enable back Active ID gl.useProgram(this.filterProgramFT); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer[activeID]); // enable buffer for index manager.enableBufferForName(this.filterProgramFT, "index", "index"); /*Activate index texture*/ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, filterTexture[thatID]); gl.uniform1i(this.filterProgramFT.indexText, 1); // filter ID gl.uniform1f(this.filterProgramFT.filterid, d.index); // if 1.0 use AND operator 0.0 use OR operator if (d.operator === "OR"){ gl.uniform1f(this.filterProgramFT.isand, 0.); } else{ gl.uniform1f(this.filterProgramFT.isand, 1.); } // number of selected flags gl.uniform1f(this.filterProgramFT.num_selected, d.selected_flags.length); gl.drawArrays(gl.POINTS, 0, manager.num_rec); // clear thatID gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer[thatID]); gl.viewport(0, 0, framebuffer.width,framebuffer.height); gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // enable back activeID gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer[activeID]); continue; } else if (d.isspatial === 0.0){ this.filterProgram=this.filterProgram1d; gl.useProgram(this.filterProgram); } else { this.filterProgram=this.filterProgram2d; gl.useProgram(this.filterProgram); manager.bindMapMatrix(this.filterProgram); } manager.enableBufferForName(this.filterProgram, "index", "index"); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, d.filterTexture); gl.uniform1i(this.filterProgram.histLoc , 0); /*Activate index texture*/ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, filterTexture[thatID]); gl.uniform1i(this.filterProgram.indexText, 1); gl.uniform1f(this.filterProgram.filterid, d.index); gl.uniform1f(this.filterProgram.isspatial, d.isspatial); //console.log("filter num "+manager.filternum); if (d.isspatial === 0.0){ /*this fitler is not spatial - bind 1d attribute*/ manager.enableBufferForName(this.filterProgram, dimensions[i].name, "attr1"); gl.drawArrays(gl.POINTS, 0, manager.num_rec); } else { /*this filter is spatial - bind the wPoint*/ manager.enableBufferForName(this.filterProgram, "wPoint", "wPoint"); gl.drawArrays(gl.POINTS, 0, manager.num_rec); } } } } //this.readPixels(activeID, 'active'); //this.readPixels(thatID, 'pasive'); //this.filterTexture = filterTexture[activeID]; //manager.filterTexture = filterTexture[activeID]; //console.log("returnunt texture "+activeID); //this.readPixels(activeID, 'active'); //this.readPixels(thatID, 'pasive'); gl.useProgram(null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null); }; /*Render filter for particular dimension*/ this.applyFilterDim = function(dim, filterId) { if (dim.filters[filterId].isspatial === 2.0){ console.error('This operation in not supported for FlagsFilter'); return; } else if (dim.filters[filterId].isspatial === 0.0){ this.filterProgram=this.filterProgram1d; gl.useProgram(this.filterProgram); manager.enableBufferForName(this.filterProgram, dim.name, "attr1"); } else { this.filterProgram=this.filterProgram2d; gl.useProgram(this.filterProgram); manager.bindMapMatrix(this.filterProgram); manager.enableBufferForName(this.filterProgram, "wPoint", "wPoint"); } //console.log("binding framebuffer to "+activeID); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer[activeID]); gl.viewport(0, 0, framebuffer.width,framebuffer.height); //gl.clearColor(0.0, 0.0, 0.0, 0.0); //gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.disable(gl.DEPTH_TEST); gl.enable(gl.BLEND); gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ONE); // gl.blendFunc(gl.ONE, gl.ONE); // this.manager.enableBuffersAndCommonUniforms(this.filterProgram); manager.enableBufferForName(this.filterProgram, "index", "index"); /* Activate filtering texture*/ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, dim.filters[filterId].filterTexture); gl.uniform1i(this.filterProgram.histLoc , 0); /*Activate index texture*/ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, filterTexture[thatID]); gl.uniform1i(this.filterProgram.indexText, 1); //console.log("index "+ dim.filter.index); gl.uniform1f(this.filterProgram.filterid, dim.filters[filterId].index); //gl.uniform1f(this.filterProgram.isspatial, dim.filters[filterId].isspatial); gl.drawArrays(gl.POINTS, 0, manager.num_rec); gl.useProgram(null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null); }; this.getActiveTexture = function(){ return filterTexture[activeID]; } this.getActiveFB = function(){ return framebuffer[activeID]; } this.getPassiveFB = function(){ return framebuffer[thatID]; } this.switchTextures = function() { if (activeID == 0){ activeID = 1; thatID = 0; } else { activeID = 0; thatID = 1; } //manager.indexFB = framebuffer[activeID]; } this.readPixelsAll = function() { this.readPixels(thatID, "pasive id:"); this.readPixels(activeID, "active id:") } this.readPixels = function(id, label) { /** * bind restexture as uniform, render, and read */ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer[id]); // console.time("reading_pix"); var readout = new Uint8Array( framebuffer.width * framebuffer.height* 4); gl.readPixels(0, 0, framebuffer.width, framebuffer.height, gl.RGBA, gl.UNSIGNED_BYTE, readout); // console.timeEnd("reading_pix"); gl.bindFramebuffer(gl.FRAMEBUFFER, null); //console.log(readout); var selected = []; for (var i =0; i < readout.length; i=i+1){ //console.log(readout[i]); selected.push(readout[i]); //if (readout[i]>1) {selected.push(i/4)}; } console.log(label+" buffer: "+selected); return selected;// readout; } }
jezekjan/webglayer
src/internal/Filter.js
JavaScript
bsd-3-clause
11,235
/** * @name ElkArte Forum * @copyright ElkArte Forum contributors * @license BSD http://opensource.org/licenses/BSD-3-Clause * * This software is a derived product, based on: * * Simple Machines Forum (SMF) * copyright: 2011 Simple Machines (http://www.simplemachines.org) * license: BSD, See included LICENSE.TXT for terms and conditions. * * @version 1.1 dev */ /** * This file contains javascript associated with the captcha visual verification stuffs. */ (function($) { $.fn.Elk_Captcha = function(options) { var settings = { // By default the letter count is five. 'letterCount' : 5, 'uniqueID' : '', 'imageURL' : '', 'useLibrary' : false, 'refreshevent': 'click', 'playevent': 'click', 'admin': false }; $.extend(settings, options); return this.each(function() { $this = $(this); if ($this.data('type') == 'sound') { // Maybe a voice is here to spread light? $this.on(settings.playevent, function(e) { e.preventDefault(); // Don't follow the link if the popup worked, which it would have done! popupFailed = reqWin(settings.imageURL + ";sound", 400, 300); if (!popupFailed) { if (is_ie && e.cancelBubble) e.cancelBubble = true; else if (e.stopPropagation) { e.stopPropagation(); e.preventDefault(); } } return popupFailed; }); } else { $this.on(settings.refreshevent, function(e) { e.preventDefault(); var uniqueID = settings.uniqueID ? '_' + settings.uniqueID : '', new_url = '', i = 0; // The Admin area is a bit different unfortunately if (settings.admin) { settings.imageURL = $('#verification_image' + uniqueID).attr('src').replace(/.$/, '') + $this.val(); new_url = String(settings.imageURL); } else { // Make sure we are using a new rand code. new_url = String(settings.imageURL); new_url = new_url.substr(0, new_url.indexOf("rand=") + 5); // Quick and dirty way of converting decimal to hex var hexstr = "0123456789abcdef"; for (i = 0; i < 32; i++) new_url = new_url + hexstr.substr(Math.floor(Math.random() * 16), 1); } if (settings.useLibrary) { $('#verification_image' + uniqueID).attr('src', new_url); } else if (document.getElementById("verification_image" + uniqueID)) { for (i = 1; i <= settings.letterCount; i++) if (document.getElementById("verification_image" + uniqueID + "_" + i)) document.getElementById("verification_image" + uniqueID + "_" + i).src = new_url + ";letter=" + i; } }); } }); }; })( jQuery );
joshuaadickerson/Elkarte2
Elkarte/www/themes/default/scripts/jquery.captcha.js
JavaScript
bsd-3-clause
2,693
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview Offline message screen implementation. */ cr.define('login', function() { // Screens that should have offline message overlay. const MANAGED_SCREENS = ['gaia-signin']; // Network state constants. const NET_STATE = { OFFLINE: 0, ONLINE: 1, PORTAL: 2 }; // Error reasons which are passed to updateState_() method. const ERROR_REASONS = { PROXY_AUTH_CANCELLED: 'frame error:111', PROXY_CONNECTION_FAILED: 'frame error:130', PROXY_CONFIG_CHANGED: 'proxy changed', LOADING_TIMEOUT: 'loading timeout', PORTAL_DETECTED: 'portal detected' }; // Frame loading errors. const NET_ERROR = { ABORTED_BY_USER: 3 }; // Link which starts guest session for captive portal fixing. const FIX_CAPTIVE_PORTAL_ID = 'captive-portal-fix-link'; // Id of the element which holds current network name. const CURRENT_NETWORK_NAME_ID = 'captive-portal-network-name'; // Link which triggers frame reload. const RELOAD_PAGE_ID = 'proxy-error-retry-link'; /** * Creates a new offline message screen div. * @constructor * @extends {HTMLDivElement} */ var ErrorMessageScreen = cr.ui.define('div'); /** * Registers with Oobe. */ ErrorMessageScreen.register = function() { var screen = $('error-message'); ErrorMessageScreen.decorate(screen); // Note that ErrorMessageScreen is not registered with Oobe because // it is shown on top of sign-in screen instead of as an independent screen. }; ErrorMessageScreen.prototype = { __proto__: HTMLDivElement.prototype, /** @inheritDoc */ decorate: function() { chrome.send('loginAddNetworkStateObserver', ['login.ErrorMessageScreen.updateState']); cr.ui.DropDown.decorate($('offline-networks-list')); this.updateLocalizedContent_(); }, /** * Updates localized content of the screen that is not updated via template. */ updateLocalizedContent_: function() { $('captive-portal-message-text').innerHTML = localStrings.getStringF( 'captivePortalMessage', '<b id="' + CURRENT_NETWORK_NAME_ID + '"></b>', '<a id="' + FIX_CAPTIVE_PORTAL_ID + '" class="signin-link" href="#">', '</a>'); $(FIX_CAPTIVE_PORTAL_ID).onclick = function() { chrome.send('showCaptivePortal'); }; $('proxy-message-text').innerHTML = localStrings.getStringF( 'proxyMessageText', '<a id="' + RELOAD_PAGE_ID + '" class="signin-link" href="#">', '</a>'); $(RELOAD_PAGE_ID).onclick = function() { var currentScreen = Oobe.getInstance().currentScreen; // Schedules a immediate retry. currentScreen.doReload(); }; $('error-guest-signin').innerHTML = localStrings.getStringF( 'guestSignin', '<a id="error-guest-signin-link" class="signin-link" href="#">', '</a>'); $('error-guest-signin-link').onclick = function() { chrome.send('launchIncognito'); }; $('error-offline-login').innerHTML = localStrings.getStringF( 'offlineLogin', '<a id="error-offline-login-link" class="signin-link" href="#">', '</a>'); $('error-offline-login-link').onclick = function() { chrome.send('offlineLogin', []); }; }, onBeforeShow: function(lastNetworkType) { var currentScreen = Oobe.getInstance().currentScreen; cr.ui.DropDown.show('offline-networks-list', false, lastNetworkType); $('error-guest-signin').hidden = $('guestSignin').hidden || !$('add-user-header-bar-item').hidden; $('error-offline-login').hidden = !currentScreen.isOfflineAllowed; }, onBeforeHide: function() { cr.ui.DropDown.hide('offline-networks-list'); }, update: function() { chrome.send('loginRequestNetworkState', ['login.ErrorMessageScreen.updateState', 'update']); }, /** * Shows or hides offline message based on network on/offline state. * @param {Integer} state Current state of the network (see NET_STATE). * @param {string} network Name of the current network. * @param {string} reason Reason the callback was called. * @param {int} lastNetworkType Last active network type. */ updateState_: function(state, network, reason, lastNetworkType) { var currentScreen = Oobe.getInstance().currentScreen; var offlineMessage = this; var isOnline = (state == NET_STATE.ONLINE); var isUnderCaptivePortal = (state == NET_STATE.PORTAL); var isProxyError = reason == ERROR_REASONS.PROXY_AUTH_CANCELLED || reason == ERROR_REASONS.PROXY_CONNECTION_FAILED; var shouldOverlay = MANAGED_SCREENS.indexOf(currentScreen.id) != -1 && !currentScreen.isLocal; var isTimeout = false; if (reason == ERROR_REASONS.PROXY_CONFIG_CHANGED && shouldOverlay && !offlineMessage.classList.contains('hidden') && offlineMessage.classList.contains('show-captive-portal')) { // Schedules a immediate retry. currentScreen.doReload(); console.log('Retry page load since proxy settings has been changed'); } // Fake portal state for loading timeout. if (reason == ERROR_REASONS.LOADING_TIMEOUT) { isOnline = false; isUnderCaptivePortal = true; isTimeout = true; } // Portal was detected via generate_204 redirect on Chrome side. // Subsequent call to show dialog if it's already shown does nothing. if (reason == ERROR_REASONS.PORTAL_DETECTED) { isOnline = false; isUnderCaptivePortal = true; } if (!isOnline && shouldOverlay) { console.log('Show offline message: state=' + state + ', network=' + network + ', reason=' + reason, ', isUnderCaptivePortal=' + isUnderCaptivePortal); offlineMessage.onBeforeShow(lastNetworkType); if (isUnderCaptivePortal && !isProxyError) { // In case of timeout we're suspecting that network might be // a captive portal but would like to check that first. // Otherwise (signal from flimflam / generate_204 got redirected) // show dialog right away. if (isTimeout) chrome.send('fixCaptivePortal'); else chrome.send('showCaptivePortal'); } else { chrome.send('hideCaptivePortal'); } if (isUnderCaptivePortal) { if (isProxyError) { offlineMessage.classList.remove('show-offline-message'); offlineMessage.classList.remove('show-captive-portal'); offlineMessage.classList.add('show-proxy-error'); } else { $(CURRENT_NETWORK_NAME_ID).textContent = network; offlineMessage.classList.remove('show-offline-message'); offlineMessage.classList.remove('show-proxy-error'); offlineMessage.classList.add('show-captive-portal'); } } else { offlineMessage.classList.remove('show-captive-portal'); offlineMessage.classList.remove('show-proxy-error'); offlineMessage.classList.add('show-offline-message'); } offlineMessage.classList.remove('hidden'); offlineMessage.classList.remove('faded'); if (!currentScreen.classList.contains('faded')) { currentScreen.classList.add('faded'); currentScreen.addEventListener('webkitTransitionEnd', function f(e) { currentScreen.removeEventListener('webkitTransitionEnd', f); if (currentScreen.classList.contains('faded')) currentScreen.classList.add('hidden'); }); } chrome.send('networkErrorShown'); } else { chrome.send('hideCaptivePortal'); if (!offlineMessage.classList.contains('faded')) { console.log('Hide offline message.'); offlineMessage.onBeforeHide(); offlineMessage.classList.add('faded'); offlineMessage.addEventListener('webkitTransitionEnd', function f(e) { offlineMessage.removeEventListener('webkitTransitionEnd', f); if (offlineMessage.classList.contains('faded')) offlineMessage.classList.add('hidden'); }); currentScreen.classList.remove('hidden'); currentScreen.classList.remove('faded'); // Forces a reload for Gaia screen on hiding error message. if (currentScreen.id == 'gaia-signin') currentScreen.doReload(); } } }, // Request network state update with loading timeout as reason. showLoadingTimeoutError: function() { // Shows error message if it is not shown already. if (this.classList.contains('hidden')) { chrome.send('loginRequestNetworkState', ['login.ErrorMessageScreen.updateState', ERROR_REASONS.LOADING_TIMEOUT]); } } }; /** * Network state changed callback. * @param {Integer} state Current state of the network (see NET_STATE). * @param {string} network Name of the current network. * @param {string} reason Reason the callback was called. * @param {int} lastNetworkType Last active network type. */ ErrorMessageScreen.updateState = function( state, network, reason, lastNetworkType) { $('error-message').updateState_(state, network, reason, lastNetworkType); }; /** * Handler for iframe's error notification coming from the outside. * For more info see C++ class 'SnifferObserver' which calls this method. * @param {number} error Error code. */ ErrorMessageScreen.onFrameError = function(error) { console.log('Gaia frame error = ' + error); if (error == NET_ERROR.ABORTED_BY_USER) { // Gaia frame was reloaded. Nothing to do here. return; } $('gaia-signin').onFrameError(error); // Offline and simple captive portal cases are handled by the // NetworkStateInformer, so only the case when browser is online is // valuable. if (window.navigator.onLine) { // Check current network state if currentScreen is a managed one. var currentScreen = Oobe.getInstance().currentScreen; if (MANAGED_SCREENS.indexOf(currentScreen.id) != -1) { chrome.send('loginRequestNetworkState', ['login.ErrorMessageScreen.maybeRetry', 'frame error:' + error]); } } }; /** * Network state callback where we decide whether to schdule a retry. */ ErrorMessageScreen.maybeRetry = function(state, network, reason, lastNetworkType) { console.log('ErrorMessageScreen.maybeRetry, state=' + state + ', network=' + network); // No retry if we are not online. if (state != NET_STATE.ONLINE) return; var currentScreen = Oobe.getInstance().currentScreen; if (MANAGED_SCREENS.indexOf(currentScreen.id) != -1) { this.updateState(NET_STATE.PORTAL, network, reason, lastNetworkType); // Schedules a retry. currentScreen.scheduleRetry(); } }; /** * Updates screen localized content like links since they're not updated * via template. */ ErrorMessageScreen.updateLocalizedContent = function() { $('error-message').updateLocalizedContent_(); }; return { ErrorMessageScreen: ErrorMessageScreen }; });
gavinp/chromium
chrome/browser/resources/chromeos/login/screen_error_message.js
JavaScript
bsd-3-clause
11,685
import stringify from 'json-stable-stringify' import { createHash } from 'crypto' export default function hash (val) { const data = Buffer.isBuffer(val) ? val : stringify(val) return createHash('sha256').update(data).digest('hex') }
pavlovml/kibble
src/hash.js
JavaScript
bsd-3-clause
238
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2010, Robert Bosch LLC. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Robert Bosch nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Authors: Benjamin Pitzer, Robert Bosch LLC * *********************************************************************/ /** * Flag for CommStateMachine transitions * @constant */ ros.actionlib.NO_TRANSITION = -1; /** * Flag for CommStateMachine transitions * @constant */ ros.actionlib.INVALID_TRANSITION = -2; /** * Client side state machine to track the action client's state * * @class * @augments Class */ ros.actionlib.CommStateMachine = Class.extend( /** @lends ros.actionlib.CommStateMachine# */ { /** * Constructs a CommStateMachine and initializes its state with WAITING_FOR_GOAL_ACK. * * @param {ros.actionlib.ActionGoal} action_goal the action goal * @param transition_cb callback function that is being called at state transitions * @param feedback_cb callback function that is being called at the arrival of a feedback message * @param send_goal_fn function will send the goal message to the action server * @param send_cancel_fn function will send the cancel message to the action server */ init: function(action_goal, transition_cb, feedback_cb, send_goal_fn, send_cancel_fn) { this.action_goal = action_goal; this.transition_cb = transition_cb; this.feedback_cb = feedback_cb; this.send_goal_fn = send_goal_fn; this.send_cancel_fn = send_cancel_fn; this.state = ros.actionlib.CommState.WAITING_FOR_GOAL_ACK; this.latest_goal_status = ros.actionlib.GoalStatus.PENDING; this.latest_result = null; this.set_transitions(); }, /** * Helper method to construct the transition matrix. */ set_transitions: function() { this.transitions = new Array(); for(var i=0;i<8;i++) { this.transitions.push(new Array()); for(var j=0;j<9;j++) { this.transitions[i].push(new Array()); } switch(i) { case ros.actionlib.CommState.WAITING_FOR_GOAL_ACK: this.transitions[i][ros.actionlib.GoalStatus.PENDING] = [ros.actionlib.CommState.PENDING]; this.transitions[i][ros.actionlib.GoalStatus.ACTIVE] = [ros.actionlib.CommState.ACTIVE]; this.transitions[i][ros.actionlib.GoalStatus.REJECTED] = [ros.actionlib.CommState.PENDING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.RECALLING] = [ros.actionlib.CommState.PENDING, ros.actionlib.CommState.RECALLING]; this.transitions[i][ros.actionlib.GoalStatus.RECALLED] = [ros.actionlib.CommState.PENDING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTED] = [ros.actionlib.CommState.ACTIVE, ros.actionlib.CommState.PREEMPTING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.SUCCEEDED] = [ros.actionlib.CommState.ACTIVE, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.ABORTED] = [ros.actionlib.CommState.ACTIVE, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTING] = [ros.actionlib.CommState.ACTIVE, ros.actionlib.CommState.PREEMPTING]; break; case ros.actionlib.CommState.PENDING: this.transitions[i][ros.actionlib.GoalStatus.PENDING] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.ACTIVE] = [ros.actionlib.CommState.ACTIVE]; this.transitions[i][ros.actionlib.GoalStatus.REJECTED] = [ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.RECALLING] = [ros.actionlib.CommState.RECALLING]; this.transitions[i][ros.actionlib.GoalStatus.RECALLED] = [ros.actionlib.CommState.RECALLING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTED] = [ros.actionlib.CommState.ACTIVE, ros.actionlib.CommState.PREEMPTING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.SUCCEEDED] = [ros.actionlib.CommState.ACTIVE, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.ABORTED] = [ros.actionlib.CommState.ACTIVE, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTING] = [ros.actionlib.CommState.ACTIVE, ros.actionlib.CommState.PREEMPTING]; break; case ros.actionlib.CommState.ACTIVE: this.transitions[i][ros.actionlib.GoalStatus.PENDING] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.ACTIVE] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.REJECTED] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.RECALLING] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.RECALLED] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTED] = [ros.actionlib.CommState.PREEMPTING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.SUCCEEDED] = [ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.ABORTED] = [ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTING] = [ros.actionlib.CommState.PREEMPTING]; break; case ros.actionlib.CommState.WAITING_FOR_RESULT: this.transitions[i][ros.actionlib.GoalStatus.PENDING] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.ACTIVE] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.REJECTED] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.RECALLING] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.RECALLED] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTED] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.SUCCEEDED] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.ABORTED] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTING] = [ros.actionlib.INVALID_TRANSITION]; break; case ros.actionlib.CommState.WAITING_FOR_CANCEL_ACK: this.transitions[i][ros.actionlib.GoalStatus.PENDING] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.ACTIVE] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.REJECTED] = [ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.RECALLING] = [ros.actionlib.CommState.RECALLING]; this.transitions[i][ros.actionlib.GoalStatus.RECALLED] = [ros.actionlib.CommState.RECALLING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTED] = [ros.actionlib.CommState.PREEMPTING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.SUCCEEDED] = [ros.actionlib.CommState.PREEMPTING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.ABORTED] = [ros.actionlib.CommState.PREEMPTING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTING] = [ros.actionlib.CommState.PREEMPTING]; break; case ros.actionlib.CommState.RECALLING: this.transitions[i][ros.actionlib.GoalStatus.PENDING] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.ACTIVE] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.REJECTED] = [ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.RECALLING] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.RECALLED] = [ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTED] = [ros.actionlib.CommState.PREEMPTING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.SUCCEEDED] = [ros.actionlib.CommState.PREEMPTING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.ABORTED] = [ros.actionlib.CommState.PREEMPTING, ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTING] = [ros.actionlib.CommState.PREEMPTING]; break; case ros.actionlib.CommState.PREEMPTING: this.transitions[i][ros.actionlib.GoalStatus.PENDING] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.ACTIVE] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.REJECTED] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.RECALLING] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.RECALLED] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTED] = [ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.SUCCEEDED] = [ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.ABORTED] = [ros.actionlib.CommState.WAITING_FOR_RESULT]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTING] = [ros.actionlib.NO_TRANSITION]; break; case ros.actionlib.CommState.DONE: this.transitions[i][ros.actionlib.GoalStatus.PENDING] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.ACTIVE] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.REJECTED] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.RECALLING] = [ros.actionlib.INVALID_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.RECALLED] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTED] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.SUCCEEDED] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.ABORTED] = [ros.actionlib.NO_TRANSITION]; this.transitions[i][ros.actionlib.GoalStatus.PREEMPTING] = [ros.actionlib.INVALID_TRANSITION]; break; default: ros_error("Unknown CommState "+i); } } }, /** * returns true if the other CommStateMachine is identical to this one * * @param {ros.actionlib.CommStateMachine} other other CommStateMachine * @returns {Boolean} true if the other CommStateMachine is identical to this one */ isEqualTo: function(other) { return this.action_goal.goal_id.id == other.action_goal.goal_id.id; }, /** * Manually set the state * * @param {ros.actionlib.CommState} state the new state for the CommStateMachine */ set_state: function(state) { ros_debug("Transitioning CommState from "+this.state+" to "+state); this.state = state; }, /** * Finds the status of a goal by its id * * @param {ros.actionlib.GoalStatusArray} status_array the status array * @param {Integer} id the goal id */ _find_status_by_goal_id: function(status_array, id) { for(s in status_array.status_list) { var status = status_array.status_list[s]; if(status.goal_id.id == id) { return status; } } return null; }, /** * Main function to update the state machine by processing the goal status array * * @param {ros.actionlib.GoalStatusArray} status_array the status array */ update_status: function(status_array) { if(this.state == ros.actionlib.CommState.DONE) { return; } var status = this._find_status_by_goal_id(status_array, this.action_goal.goal_id.id); // You mean you haven't heard of me? if(!status) { if(!(this.state in [ros.actionlib.CommState.WAITING_FOR_GOAL_ACK, ros.actionlib.CommState.WAITING_FOR_RESULT, ros.actionlib.CommState.DONE])) { this._mark_as_lost(); } return; } this.latest_goal_status = status; // Determines the next state from the lookup table if(this.state >= this.transitions.length) { ros_error("CommStateMachine is in a funny state: " + this.state); return; } if(status.status >= this.transitions[this.state].length) { ros_error("Got an unknown status from the ActionServer: " + status.status); return; } next_states = this.transitions[this.state][status.status]; // Knowing the next state, what should we do? if(next_states[0] == ros.actionlib.NO_TRANSITION) { } else if(next_states[0] == ros.actionlib.INVALID_TRANSITION) { ros_error("Invalid goal status transition from "+this.state+" to "+status.status); } else { for(s in next_states) { var state = next_states[s]; this.transition_to(state); } } }, /** * Make state machine transition to a new state * * @param {ros.actionlib.CommState} state the new state for the CommStateMachine */ transition_to: function (state) { ros_debug("Transitioning to "+state+" (from "+this.state+", goal: "+this.action_goal.goal_id.id+")"); this.state = state; if(this.transition_cb) { this.transition_cb(new ros.actionlib.ClientGoalHandle(this)); } }, /** * Mark state machine as lost */ _mark_as_lost: function() { this.latest_goal_status.status = ros.actionlib.GoalStatus.LOST; this.transition_to(ros.actionlib.CommState.DONE); }, /** * Main function to update the results by processing the action result * * @param action_result the action result */ update_result: function(action_result) { // Might not be for us if(this.action_goal.goal_id.id != action_result.status.goal_id.id) return; this.latest_goal_status = action_result.status; this.latest_result = action_result; if(this.state in [ros.actionlib.CommState.WAITING_FOR_GOAL_ACK, ros.actionlib.CommState.WAITING_FOR_CANCEL_ACK, ros.actionlib.CommState.PENDING, ros.actionlib.CommState.ACTIVE, ros.actionlib.CommState.WAITING_FOR_RESULT, ros.actionlib.CommState.RECALLING, ros.actionlib.CommState.PREEMPTING]) { // Stuffs the goal status in the result into a GoalStatusArray var status_array = new ros.actionlib.GoalStatusArray(); status_array.status_list.push(action_result.status); this.update_status(status_array); this.transition_to(ros.actionlib.CommState.DONE); } else if(this.state == ros.actionlib.CommState.DONE) { ros_error("Got a result when we were already in the DONE state"); } else { ros_error("In a funny state: "+this.state); } }, /** * Function to process the action feedback message * * @param action_feedback an action feedback message */ update_feedback: function(action_feedback) { // Might not be for us if(this.action_goal.goal_id.id != action_feedback.status.goal_id.id) { return; } if(this.feedback_cb) { this.feedback_cb(new ros.actionlib.ClientGoalHandle(this), action_feedback.feedback); } }, });
gt-ros-pkg/rcommander-pr2
rcommander_web/html/js/ros/actionlib/commstatemachine.js
JavaScript
bsd-3-clause
17,673
if (typeof require != 'undefined' || !jsyrup) var jsyrup = require('../../../jsyrup'); describe('when creating', function() { var ds, modelClass, callback; beforeEach(function() { ds = new jsyrup.SQLDataSource(); callback = jasmine.createSpy(); modelClass = jsyrup.ModelFactory({ key: 'id', datasources: { sql: 'items' }, schema: { id: { type: 'Integer' }, name: { type: 'Text' } } }); }); it('should exists', function() { expect(ds).toBeDefined(); }); it('should have a craete method', function() { expect(ds.create).toBeFunction(); }); describe('when creating', function() { var instance; beforeEach(function() { instance = new modelClass(); instance.set('name', 'Fred'); }); it('should create', function() { spyOn(ds, '_execute'); ds.create(instance, callback); expect(ds._execute).toHaveBeenCalledWith( "INSERT INTO items (items.name) VALUES ($1)", ['Fred'], callback); }); }); describe('when updating', function() { var instance; beforeEach(function() { instance = new modelClass(); instance.load({ id: 3, name: 'Frank' }); }); it('should update', function() { spyOn(ds, '_execute'); ds.update(instance, callback); expect(ds._execute).toHaveBeenCalledWith( "UPDATE items SET items.name = $1 WHERE items.id = $2", ['Frank', 3], callback); }); }); });
russpos/jsyrup
test/unit/datasources/test.sql.js
JavaScript
bsd-3-clause
1,737
'use strict'; angular.module('BaubleApp') .controller('OrgEditCtrl', ['$scope', '$location', 'Alert', 'User', 'Organization', function ($scope, $location, Alert, User, Organization) { $scope.save = function(org){ $scope.working = true; Organization.save(org) .success(function(data, status, headers, config) { $scope.user = User.local(); $scope.user.organization_id = data.id; User.local($scope.user); // TODO: we should probably return to where we came from $location.path('/'); }) .error(function(data, status, headers, config) { var defaultMessage = "Could not save organization."; Alert.onErrorResponse(data, defaultMessage); }) .finally(function() { $scope.working = false; }); }; }]);
Bauble/bauble.webapp
app/scripts/controllers/org-edit.js
JavaScript
bsd-3-clause
1,000
this.MeteorIntl.__addLocaleData({"locale":"ja","pluralRuleFunction":function (n,ord){if(ord)return"other";return"other"},"fields":{"year":{"displayName":"年","relative":{"0":"今年","1":"翌年","-1":"昨年"},"relativeTime":{"future":{"other":"{0} 年後"},"past":{"other":"{0} 年前"}}},"month":{"displayName":"月","relative":{"0":"今月","1":"翌月","-1":"先月"},"relativeTime":{"future":{"other":"{0} か月後"},"past":{"other":"{0} か月前"}}},"day":{"displayName":"日","relative":{"0":"今日","1":"明日","2":"明後日","-1":"昨日","-2":"一昨日"},"relativeTime":{"future":{"other":"{0} 日後"},"past":{"other":"{0} 日前"}}},"hour":{"displayName":"時","relativeTime":{"future":{"other":"{0} 時間後"},"past":{"other":"{0} 時間前"}}},"minute":{"displayName":"分","relativeTime":{"future":{"other":"{0} 分後"},"past":{"other":"{0} 分前"}}},"second":{"displayName":"秒","relative":{"0":"今すぐ"},"relativeTime":{"future":{"other":"{0} 秒後"},"past":{"other":"{0} 秒前"}}}}}); this.MeteorIntl.__addLocaleData({"locale":"ja-JP","parentLocale":"ja"});
eXon/meteor-intl
dist/locale-data/ja.js
JavaScript
bsd-3-clause
1,093
// This code (and its parent process in changes.js) is a Node.JS listener // listening to CouchDB's _changes feed, and is derived from // https://github.com/mikeal/node.couch.js and // http://dominicbarnes.us/node-couchdb-api/api/database/changes.html // It monitors when requests are submitted to: // (when configuring a directory's settings) get a url in general // (when a directory is already configured) download all cong data for a directory // TODO: Could we use backbone-couch.js here instead of cradle, in order to use our // Backbone model here? var buffer = '', http = require('http'), https = require('https'), ncl_dir = '/_attachments/node_changes_listeners/', config = require('./config'), db = config.db, log = require('./lib').log; //$ = require('jquery'); //var model = require('model.js').model //stdin = process.openStdin(); // if (config.debug) // var longjohn = require('./node_modules/longjohn') //stdin.setEncoding('utf8'); console.log('Starting changes listener...') // -------- Declare utility functions -------- function get_url(doc, from_url, to_html, status_flag, options){ var http_lib = http if (doc[from_url].indexOf('https') === 0){ // Switch to using https if necessary var http_lib = https } http_lib.get(doc[from_url], function(res){ var pageData = '' res.on('data', function(chunk){ pageData += chunk }) res.on('end', function(){ // Check to see if we got a 404 response if (res.statusCode == '404'){ console.log('Got a 404!') // TODO: If we got a 404, then notify the user this page doesn't exist doc[status_flag] = '404' db.save(doc._id, doc._rev, doc) }else{ // Write the contents of the html variable back to the database doc[to_html] = pageData doc[status_flag] = 'gotten' // console.log(new Date().getTime() + '\t n: ' + status_flag + ': ' + doc[status_flag] + ' ' + doc[from_url]) // TODO: Use Backbone here instead of cradle db.save(doc._id, doc._rev, doc, function(err, res){ // TODO: Do anything more that needs to be done here if (to_html == 'url_html'){ console.log('Getting url_html...handling response end') console.log(doc) } if (options && options.success){ options.success() } }); } }) }); } function save(options){ db.get(options.doc._id, function(err, doc){ options.doc = doc if (!err && options.doc && options.doc._id && typeof options.doc._id !== 'undefined'){ // Save to the db all the HTML we've gotten // TODO: This is running several times in series options.doc[options.to_html] = options.output_array options.doc[options.status_flag] = 'gotten'; // Deletes number downloaded since it's not needed anymore delete options.doc[options.number_downloaded] db.save(options.doc._id, options.doc._rev, options.doc, function(err, response){ if (err !== null){ console.error(err) // Recurse to try saving again // Only recurse a certain number of times, then fail, to avoid a memory leak if (options.save_attempts <= 5){ options.save_attempts++; // console.log('options.save_attempts: ' + options.save_attempts) save(options) }else{ // TODO: This is where we get an error. For some reason sometimes, // but not always, we have the wrong revision here, and this causes get_state_url_html // to never == 'gotten', (so the state details page doesn't display?) // console.error('Failed to save doc: ' + options.doc._id, options.doc._rev) } }else{ // console.log('Succeeded at saving all the states\' HTML pages') options.output_array_saved = true // Remove this options.status_flag from the list of tasks currently_getting.splice(currently_getting.indexOf(options.status_flag),1) // Clean up some memory options.output_array = [] } }) } }) } function recurse_then_save(i, options){ // If we've downloaded all the HTML, and haven't saved to the db yet if (options.output_array.length == options.doc[options.from_urls].length && options.output_array_saved !== true){ options.save_attempts = 0 if (options.output_array_saved !== true){ save(options) // console.log ("after saving all the states") } } // Call the parent function recursively to enable throttling the rate of web-scraping requests // Handle next URL recurse_urls(i+1, options) } function recurse_urls(i, options){ if (typeof options.doc[options.from_urls] == 'undefined'){ // console.log(options.doc[options.from_urls]) } // Stop running if we have reached the end of the list of URLs, if (options.doc[options.from_urls][i] !== '' && typeof options.doc[options.from_urls][i] !== 'undefined' && // and don't run if we've already downloaded the HTML for this URL typeof options.doc[i] == 'undefined'){ // TODO: Make this handle options.doc[options.method] == 'post' http.get(options.doc[options.from_urls][i], function(res){ var pageData = '' res.on('data', function(chunk){ pageData += chunk }) res.on('end', function(){ // TODO: Check to see if we got a 404 response // Append result to options.output_array options.output_array[i] = pageData if (options.doc[options.status_flag] !== 'getting'){ options.doc[options.status_flag] = 'getting' // Set flag to indicate that we just reset the status_flag options.flag_set = true // report to the db the fact we are getting the HTML // console.log ("before saving all the states") db.save(options.doc._id, options.doc._rev, options.doc, function(err, response){ recurse_then_save(i, options) }) } // Record the number downloaded // Don't run until the status_flag has been set if (typeof options.flag_set !== 'undefined' && options.flag_set === true){ recurse_then_save(i, options) } }) }) }else{ currently_getting.splice(currently_getting.indexOf(options.status_flag),1) } } currently_getting = [] function get_url_set(options){ // Don't run more than one copy of this task at a time if (currently_getting.indexOf(options.status_flag) == -1){ // Add this options.status_flag to the list of tasks currently_getting.push(options.status_flag) var i = 0 options.output_array = [] options.output_array_saved = false // Use a recursive function to allow throttling the rate of web-scraping requests // per second to avoid getting banned by some servers. recurse_urls(i, options) } } // -------- Main routine that handles all db changes -------- // Only get changes after "update_seq" db.get('', function(err,doc){ // TODO: This throws: TypeError: Cannot read property 'update_seq' of undefined db.changes({since:doc.update_seq}).on('change', function (change) { db.get(change.id, change.changes[0].rev, function(err, doc){ if (change.id && change.id.slice(0, '_design/'.length) !== '_design/') { // This is a change to a data document // Feed the new doc into the changes listeners if (doc) { // Don't handle docs that have been deleted // Watch for requests to get the contents of a URL for a church directory // TODO: Check to see if the URL is valid if (doc.collection == 'directory' && doc.get_url_html=='requested' && doc.url){ // E.g., when a user enters "opc.org/locator.html" into the church directory configuration page, // then go get the contents of that URL. get_url(doc, 'url', 'url_html', 'get_url_html') } if (doc.collection == 'directory' && doc.get_cong_url_html=='requested' && doc.cong_url){ get_url(doc, 'cong_url_raw', 'cong_url_html', 'get_cong_url_html', {success:function(){ // Iterate state pages' HTML for (var i=0; i<doc.state_url_html.length; i++){ // TODO: Get each cong's URL var state_html = doc.state_url_html[i] // TODO: Get each cong page's HTML & write to database } }}) } // Watch for requests to get the contents of a state page URL if (doc.collection == 'directory' && doc.get_state_url_html=='requested' && doc.state_url){ // Interpolate state names into URLs var state_page_urls = [] // console.log('before interpolating state names into URLs') for (var i=0; i<doc.state_page_values.length; i++){ if (doc.state_page_values[i] !== ''){ state_page_urls.push(doc.state_url.replace('{state_name}', doc.state_page_values[i])) } } // console.log('about to get_url_set') doc.state_page_urls = state_page_urls get_url_set({ doc: doc, from_urls: 'state_page_urls', method: 'state_url_method', to_html: 'state_url_html', status_flag: 'get_state_url_html', number_downloaded: 'state_urls_gotten', success:function(){ // TODO: Cleanup unnecessary doc attributes here? Probably that should be done in // ImportDirectoryView.js instead. }}) } // Watch for requests to get the contents of a batchgeo map URL if (doc.collection == 'directory' && doc.get_batchgeo_map_html=='requested' && doc.batchgeo_map_url){ get_url(doc, 'batchgeo_map_url', 'batchgeo_map_html', 'get_batchgeo_map_html') } // Watch for requests to get the contents of a JSON feed if (doc.collection == 'directory' && doc.get_json=='requested' && doc.json_url){ get_url(doc, 'json_url', 'json', 'get_json') } } } }); }); })
DouglasHuston/rcl
node_changes_listeners/changes_listeners.js
JavaScript
bsd-3-clause
10,689
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var HandleitForm = function (_React$Component) { _inherits(HandleitForm, _React$Component); function HandleitForm(props) { _classCallCheck(this, HandleitForm); // this.hide_elements(); var _this = _possibleConstructorReturn(this, (HandleitForm.__proto__ || Object.getPrototypeOf(HandleitForm)).call(this, props)); _this.hide_elements = function () { $('#navID').css('display', 'none'); $('#userNav').css('display', 'none'); // $('#noUserNav').css('display', 'none') $('#imageBar').css('display', 'none'); $('#footerID').css('display', 'none'); // $('#noUserNav').css('display', 'none') }; _this.onClick_jspdf = function () { var doc = new jspdf.jsPDF({ format: "letter" }); var source = window.document.getElementsByTagName("body")[0]; doc.html(source, { callback: function callback(doc) { doc.output("dataurlnewwindow"); }, x: 15, y: 15 }); }; _this.onClick_print = function () { window.print(); }; return _this; } _createClass(HandleitForm, [{ key: 'roundCurrency', value: function roundCurrency(n) { var mult = 100, value = void 0; value = parseFloat((n * mult).toFixed(6)); return Math.round(value) / mult; } }, { key: 'render', value: function render() { var _this2 = this; var workitems = void 0, docApp = void 0; if (this.props.type == "project") { var proj = this.props.projectData; workitems = proj.workItems; docApp = proj.documentPackage.application; } else if (this.props.type == "assessment") { var assessment = this.props.assessmentData; workitems = assessment.workItems; docApp = assessment.documentPackage.application; } var name = docApp.name.middle && docApp.name.middle.length > 0 ? docApp.name.first + ' ' + docApp.name.middle + ' ' + docApp.name.last : docApp.name.first + ' ' + docApp.name.last; var address = docApp.address.line_1; if (docApp.address.line_2 && docApp.address.line_2.length > 0) { address += '| ' + docApp.address.line_2 + '\n'; } var total_volunteers = 0; return React.createElement( 'div', null, React.createElement( 'div', { id: 'buttons-container', className: 'no-print' }, React.createElement( 'button', { onClick: this.onClick_print }, 'Print' ) ), React.createElement( 'div', { id: 'cblock-container' }, React.createElement('img', { src: '/images/app_project/letterhead.png' }) ), React.createElement( 'p', { id: 'info-container' }, 'Catalyst Partnerships is a non-proft general contractor. We bring together useful resources and caring volunteers to meet the needs of under-resourced people in our community. \u201CHandle-It\u201D volunteers can provide minor home repairs to improve the safety of the home for no fee. Handle-It Volunteers are skilled handy men and women who have undergone and passed background checks and are insured by Catalyst. To the extent required by law, Catalyst is duly licensed, bonded, and insured to perform such work' ), React.createElement( 'h1', { id: 'doc-header' }, 'HANDLE-IT WORK AGREEMENT' ), React.createElement( 'table', null, React.createElement( 'tbody', null, React.createElement( 'tr', null, React.createElement( 'td', null, React.createElement( 'b', null, 'Property Owner:' ) ), React.createElement( 'td', null, name ) ), React.createElement( 'tr', null, React.createElement( 'td', null, React.createElement( 'b', null, 'Address:' ) ), React.createElement( 'td', null, React.createElement( 'div', null, address ), React.createElement( 'div', null, docApp.address.city, ', ', docApp.address.state, ' ', docApp.address.zip ) ) ), React.createElement( 'tr', null, React.createElement( 'td', null, React.createElement( 'b', null, 'Phone:' ) ), React.createElement( 'td', null, docApp.phone.preferred ) ), React.createElement( 'tr', null, React.createElement( 'td', null, React.createElement( 'b', null, 'Email:' ) ), React.createElement( 'td', null, docApp.email ) ) ) ), React.createElement( 'h2', null, 'Work Requested' ), workitems.map(function (workItem) { var workitemCost = 0; workItem.materialsItems.forEach(function (materialsItem) { workitemCost += _this2.roundCurrency(materialsItem.price * materialsItem.quantity); }); total_volunteers += workItem.volunteers_required; return React.createElement( 'div', { className: 'workitem-total-container', key: workItem._id }, React.createElement( 'div', { key: "wi-" + workItem._id, className: 'workitem-container' }, React.createElement( 'table', null, React.createElement( 'tbody', null, React.createElement( 'tr', null, React.createElement( 'th', null, 'Work Item Name' ), React.createElement( 'td', null, workItem.name ) ), React.createElement( 'tr', null, React.createElement( 'th', null, 'Description' ), React.createElement( 'td', null, workItem.description ) ), workItem.project_comments && workItem.project_comments.length > 0 ? React.createElement( 'tr', null, React.createElement( 'th', null, 'Project Comments' ), React.createElement( 'td', null, workItem.project_comments ) ) : null, React.createElement( 'tr', null, React.createElement( 'th', null, 'Cost' ), React.createElement( 'td', null, workitemCost.toFixed(2) ) ) ) ) ) ); }), React.createElement( 'p', { id: 'price-p' }, 'Price: Catalyst Partnerships shall provide resources for the work. The cost of this project to the property owner is $0.' ), React.createElement( 'p', null, 'Scope: The scope of Handle-It Projects are jobs that will require 1-3 volunteers one day\u2019s time and cost Catalyst $500 or less. In some cases, the property owner may already own the item that needs installation. If, after the Handle-It volunteer examines the scope of work, it is decided that the job would require more extensive labor and/or materials, this project may be recommended for consideration as a full Catalyst Project. This will require further fnancial vetting and estimation of the necessary work to restore the home to safety' ), React.createElement( 'p', null, 'Volunteer Labor: Catalyst Partnerships is responsible for providing volunteer labor required to complete this project. Catalyst Partnerships is also responsible for providing materials, tools, and all other resources required to complete this project. Due to the nature of this non-proft, volunteer activity, property owner understands that the quality of service and/or craftsmanship received may not refect professional standards.' ), React.createElement( 'p', { id: 'acceptance-p' }, 'Acceptance of Contract: The above price, specifcations and conditions are satisfactory and are hereby accepted. Catalyst Partnerships is authorized to furnish all materials and volunteer labor required to complete the project as stated.' ), React.createElement( 'div', { className: 'signatures-container' }, React.createElement( 'div', null, 'Date __________________' ), React.createElement( 'div', null, React.createElement( 'div', null, 'X_______________________________________________' ), React.createElement( 'div', null, 'Property Owner' ) ) ), React.createElement( 'div', { className: 'signatures-container' }, React.createElement( 'div', { className: '' }, 'Date __________________' ), React.createElement( 'div', { className: '' }, React.createElement( 'div', null, 'X_______________________________________________' ), React.createElement( 'div', null, 'Catalyst Handle-It Volunteer' ) ) ), React.createElement( 'p', null, 'Please sign two copies \u2013 one for the homeowner, the other for the Catalyst offce' ) ); } }]); return HandleitForm; }(React.Component); function loadReact() { console.log(type, assessment_id); if (type == "project") { $.ajax({ url: "/app_project/projects/" + project_id, type: "GET", success: function success(data) { console.log(data); ReactDOM.render(React.createElement(HandleitForm, { type: type, projectData: data }), document.getElementById("pdf_container")); } }); } else if (type == "assessment") { $.ajax({ url: "/app_project/site_assessments/" + assessment_id, type: "GET", success: function success(data) { console.log(data); ReactDOM.render(React.createElement(HandleitForm, { type: type, assessmentData: data }), document.getElementById("pdf_container")); } }); } } loadReact();
dandahle/Catalyst-AppVetting
public/javascripts/app_project/pdf/handleit_form.js
JavaScript
bsd-3-clause
13,826
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Scroll handling. // // Switches the sidebar between floating on the left and position:fixed // depending on whether it's scrolled into view. (function() { var sidebar = document.getElementById('gc-sidebar'); var offsetTop = sidebar.offsetTop; window.addEventListener('scroll', function() { // Obviously, this code executes every time the window scrolls, so avoid // putting things in here. if (sidebar.classList.contains('floating')) { if (window.scrollY < offsetTop) sidebar.classList.remove('floating'); } else { if (window.scrollY > offsetTop) { sidebar.classList.add('floating'); sidebar.scrollTop = 0; } } }); }());
timopulkkinen/BubbleFish
chrome/common/extensions/docs/static/js/scroll.js
JavaScript
bsd-3-clause
833
/** * Copyright (c) 2015, Facebook, Inc. All rights reserved. * * Facebook, Inc. ("Facebook") owns all right, title and interest, including * all intellectual property and other proprietary rights, in and to the React * Native CustomComponents software (the "Software"). Subject to your * compliance with these terms, you are hereby granted a non-exclusive, * worldwide, royalty-free copyright license to (1) use and copy the Software; * and (2) reproduce and distribute the Software as part of your own software * ("Your Software"). Facebook reserves all rights not expressly granted to * you in this license agreement. * * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. * IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR * EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @providesModule ListView */ 'use strict'; var ListViewDataSource = require('ListViewDataSource'); var React = require('React'); var RCTScrollViewManager = require('NativeModules').ScrollViewManager; var ScrollView = require('ScrollView'); var ScrollResponder = require('ScrollResponder'); var StaticRenderer = require('StaticRenderer'); var TimerMixin = require('react-timer-mixin'); var isEmpty = require('isEmpty'); var logError = require('logError'); var merge = require('merge'); var PropTypes = React.PropTypes; var DEFAULT_PAGE_SIZE = 1; var DEFAULT_INITIAL_ROWS = 10; var DEFAULT_SCROLL_RENDER_AHEAD = 1000; var DEFAULT_END_REACHED_THRESHOLD = 1000; var DEFAULT_SCROLL_CALLBACK_THROTTLE = 50; var SCROLLVIEW_REF = 'listviewscroll'; /** * ListView - A core component designed for efficient display of vertically * scrolling lists of changing data. The minimal API is to create a * `ListView.DataSource`, populate it with a simple array of data blobs, and * instantiate a `ListView` component with that data source and a `renderRow` * callback which takes a blob from the data array and returns a renderable * component. * * Minimal example: * * ``` * getInitialState: function() { * var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); * return { * dataSource: ds.cloneWithRows(['row 1', 'row 2']), * }; * }, * * render: function() { * return ( * <ListView * dataSource={this.state.dataSource} * renderRow={(rowData) => <Text>{rowData}</Text>} * /> * ); * }, * ``` * * ListView also supports more advanced features, including sections with sticky * section headers, header and footer support, callbacks on reaching the end of * the available data (`onEndReached`) and on the set of rows that are visible * in the device viewport change (`onChangeVisibleRows`), and several * performance optimizations. * * There are a few performance operations designed to make ListView scroll * smoothly while dynamically loading potentially very large (or conceptually * infinite) data sets: * * * Only re-render changed rows - the rowHasChanged function provided to the * data source tells the ListView if it needs to re-render a row because the * source data has changed - see ListViewDataSource for more details. * * * Rate-limited row rendering - By default, only one row is rendered per * event-loop (customizable with the `pageSize` prop). This breaks up the * work into smaller chunks to reduce the chance of dropping frames while * rendering rows. */ var ListView = React.createClass({ mixins: [ScrollResponder.Mixin, TimerMixin], statics: { DataSource: ListViewDataSource, }, /** * You must provide a renderRow function. If you omit any of the other render * functions, ListView will simply skip rendering them. * * - renderRow(rowData, sectionID, rowID, highlightRow); * - renderSectionHeader(sectionData, sectionID); */ propTypes: { ...ScrollView.propTypes, dataSource: PropTypes.instanceOf(ListViewDataSource).isRequired, /** * (sectionID, rowID, adjacentRowHighlighted) => renderable * * If provided, a renderable component to be rendered as the separator * below each row but not the last row if there is a section header below. * Take a sectionID and rowID of the row above and whether its adjacent row * is highlighted. */ renderSeparator: PropTypes.func, /** * (rowData, sectionID, rowID, highlightRow) => renderable * * Takes a data entry from the data source and its ids and should return * a renderable component to be rendered as the row. By default the data * is exactly what was put into the data source, but it's also possible to * provide custom extractors. ListView can be notified when a row is * being highlighted by calling highlightRow function. The separators above and * below will be hidden when a row is highlighted. The highlighted state of * a row can be reset by calling highlightRow(null). */ renderRow: PropTypes.func.isRequired, /** * How many rows to render on initial component mount. Use this to make * it so that the first screen worth of data apears at one time instead of * over the course of multiple frames. */ initialListSize: PropTypes.number, /** * Called when all rows have been rendered and the list has been scrolled * to within onEndReachedThreshold of the bottom. The native scroll * event is provided. */ onEndReached: PropTypes.func, /** * Threshold in pixels for onEndReached. */ onEndReachedThreshold: PropTypes.number, /** * Number of rows to render per event loop. */ pageSize: PropTypes.number, /** * () => renderable * * The header and footer are always rendered (if these props are provided) * on every render pass. If they are expensive to re-render, wrap them * in StaticContainer or other mechanism as appropriate. Footer is always * at the bottom of the list, and header at the top, on every render pass. */ renderFooter: PropTypes.func, renderHeader: PropTypes.func, /** * (sectionData, sectionID) => renderable * * If provided, a sticky header is rendered for this section. The sticky * behavior means that it will scroll with the content at the top of the * section until it reaches the top of the screen, at which point it will * stick to the top until it is pushed off the screen by the next section * header. */ renderSectionHeader: PropTypes.func, /** * (props) => renderable * * A function that returns the scrollable component in which the list rows * are rendered. Defaults to returning a ScrollView with the given props. */ renderScrollComponent: React.PropTypes.func.isRequired, /** * How early to start rendering rows before they come on screen, in * pixels. */ scrollRenderAheadDistance: React.PropTypes.number, /** * (visibleRows, changedRows) => void * * Called when the set of visible rows changes. `visibleRows` maps * { sectionID: { rowID: true }} for all the visible rows, and * `changedRows` maps { sectionID: { rowID: true | false }} for the rows * that have changed their visibility, with true indicating visible, and * false indicating the view has moved out of view. */ onChangeVisibleRows: React.PropTypes.func, /** * An experimental performance optimization for improving scroll perf of * large lists, used in conjunction with overflow: 'hidden' on the row * containers. Use at your own risk. */ removeClippedSubviews: React.PropTypes.bool, }, /** * Exports some data, e.g. for perf investigations or analytics. */ getMetrics: function() { return { contentLength: this.scrollProperties.contentLength, totalRows: this.props.dataSource.getRowCount(), renderedRows: this.state.curRenderedRowsCount, visibleRows: Object.keys(this._visibleRows).length, }; }, /** * Provides a handle to the underlying scroll responder to support operations * such as scrollTo. */ getScrollResponder: function() { return this.refs[SCROLLVIEW_REF] && this.refs[SCROLLVIEW_REF].getScrollResponder && this.refs[SCROLLVIEW_REF].getScrollResponder(); }, setNativeProps: function(props) { this.refs[SCROLLVIEW_REF].setNativeProps(props); }, /** * React life cycle hooks. */ getDefaultProps: function() { return { initialListSize: DEFAULT_INITIAL_ROWS, pageSize: DEFAULT_PAGE_SIZE, renderScrollComponent: props => <ScrollView {...props} />, scrollRenderAheadDistance: DEFAULT_SCROLL_RENDER_AHEAD, onEndReachedThreshold: DEFAULT_END_REACHED_THRESHOLD, }; }, getInitialState: function() { return { curRenderedRowsCount: this.props.initialListSize, prevRenderedRowsCount: 0, highlightedRow: {}, }; }, getInnerViewNode: function() { return this.refs[SCROLLVIEW_REF].getInnerViewNode(); }, componentWillMount: function() { // this data should never trigger a render pass, so don't put in state this.scrollProperties = { visibleLength: null, contentLength: null, offset: 0 }; this._childFrames = []; this._visibleRows = {}; }, componentDidMount: function() { // do this in animation frame until componentDidMount actually runs after // the component is laid out this.requestAnimationFrame(() => { this._measureAndUpdateScrollProps(); }); }, componentWillReceiveProps: function(nextProps) { if (this.props.dataSource !== nextProps.dataSource) { this.setState((state, props) => { var rowsToRender = Math.min( state.curRenderedRowsCount + props.pageSize, props.dataSource.getRowCount() ); return { prevRenderedRowsCount: 0, curRenderedRowsCount: rowsToRender, }; }); } }, componentDidUpdate: function() { this.requestAnimationFrame(() => { this._measureAndUpdateScrollProps(); }); }, onRowHighlighted: function(sectionID, rowID) { this.setState({highlightedRow: {sectionID, rowID}}); }, render: function() { var bodyComponents = []; var dataSource = this.props.dataSource; var allRowIDs = dataSource.rowIdentities; var rowCount = 0; var sectionHeaderIndices = []; var header = this.props.renderHeader && this.props.renderHeader(); var footer = this.props.renderFooter && this.props.renderFooter(); var totalIndex = header ? 1 : 0; for (var sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) { var sectionID = dataSource.sectionIdentities[sectionIdx]; var rowIDs = allRowIDs[sectionIdx]; if (rowIDs.length === 0) { continue; } if (this.props.renderSectionHeader) { var shouldUpdateHeader = rowCount >= this.state.prevRenderedRowsCount && dataSource.sectionHeaderShouldUpdate(sectionIdx); bodyComponents.push( <StaticRenderer key={'s_' + sectionID} shouldUpdate={!!shouldUpdateHeader} render={this.props.renderSectionHeader.bind( null, dataSource.getSectionHeaderData(sectionIdx), sectionID )} /> ); sectionHeaderIndices.push(totalIndex++); } for (var rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) { var rowID = rowIDs[rowIdx]; var comboID = sectionID + '_' + rowID; var shouldUpdateRow = rowCount >= this.state.prevRenderedRowsCount && dataSource.rowShouldUpdate(sectionIdx, rowIdx); var row = <StaticRenderer key={'r_' + comboID} shouldUpdate={!!shouldUpdateRow} render={this.props.renderRow.bind( null, dataSource.getRowData(sectionIdx, rowIdx), sectionID, rowID, this.onRowHighlighted )} />; bodyComponents.push(row); totalIndex++; if (this.props.renderSeparator && (rowIdx !== rowIDs.length - 1 || sectionIdx === allRowIDs.length - 1)) { var adjacentRowHighlighted = this.state.highlightedRow.sectionID === sectionID && ( this.state.highlightedRow.rowID === rowID || this.state.highlightedRow.rowID === rowIDs[rowIdx + 1] ); var separator = this.props.renderSeparator( sectionID, rowID, adjacentRowHighlighted ); bodyComponents.push(separator); totalIndex++; } if (++rowCount === this.state.curRenderedRowsCount) { break; } } if (rowCount >= this.state.curRenderedRowsCount) { break; } } var { renderScrollComponent, ...props, } = this.props; if (!props.scrollEventThrottle) { props.scrollEventThrottle = DEFAULT_SCROLL_CALLBACK_THROTTLE; } if (props.removeClippedSubviews === undefined) { props.removeClippedSubviews = true; } Object.assign(props, { onScroll: this._onScroll, stickyHeaderIndices: sectionHeaderIndices, // Do not pass these events downstream to ScrollView since they will be // registered in ListView's own ScrollResponder.Mixin onKeyboardWillShow: undefined, onKeyboardWillHide: undefined, onKeyboardDidShow: undefined, onKeyboardDidHide: undefined, }); // TODO(ide): Use function refs so we can compose with the scroll // component's original ref instead of clobbering it return React.cloneElement(renderScrollComponent(props), { ref: SCROLLVIEW_REF, onContentSizeChange: this._onContentSizeChange, onLayout: this._onLayout, }, header, bodyComponents, footer); }, /** * Private methods */ _measureAndUpdateScrollProps: function() { var scrollComponent = this.getScrollResponder(); if (!scrollComponent || !scrollComponent.getInnerViewNode) { return; } // RCTScrollViewManager.calculateChildFrames is not available on // every platform RCTScrollViewManager && RCTScrollViewManager.calculateChildFrames && RCTScrollViewManager.calculateChildFrames( React.findNodeHandle(scrollComponent), this._updateChildFrames, ); }, _onContentSizeChange: function(width, height) { this.scrollProperties.contentLength = !this.props.horizontal ? height : width; this._updateVisibleRows(); this._renderMoreRowsIfNeeded(); if (this.props.onContentSizeChange) { this.props.onContentSizeChange(width, height); } }, _onLayout: function(event) { var {width, height} = event.nativeEvent.layout; this.scrollProperties.visibleLength = !this.props.horizontal ? height : width; this._updateVisibleRows(); this._renderMoreRowsIfNeeded(); if (this.props.onLayout) { this.props.onLayout(event); } }, _setScrollVisibleLength: function(left, top, width, height) { this.scrollProperties.visibleLength = !this.props.horizontal ? height : width; this._updateVisibleRows(); this._renderMoreRowsIfNeeded(); }, _updateChildFrames: function(childFrames) { this._updateVisibleRows(childFrames); }, _maybeCallOnEndReached: function(event) { if (this.props.onEndReached && this.scrollProperties.contentLength !== this._sentEndForContentLength && this._getDistanceFromEnd(this.scrollProperties) < this.props.onEndReachedThreshold && this.state.curRenderedRowsCount === this.props.dataSource.getRowCount()) { this._sentEndForContentLength = this.scrollProperties.contentLength; this.props.onEndReached(event); return true; } return false; }, _renderMoreRowsIfNeeded: function() { if (this.scrollProperties.contentLength === null || this.scrollProperties.visibleLength === null || this.state.curRenderedRowsCount === this.props.dataSource.getRowCount()) { this._maybeCallOnEndReached(); return; } var distanceFromEnd = this._getDistanceFromEnd(this.scrollProperties); if (distanceFromEnd < this.props.scrollRenderAheadDistance) { this._pageInNewRows(); } }, _pageInNewRows: function() { this.setState((state, props) => { var rowsToRender = Math.min( state.curRenderedRowsCount + props.pageSize, props.dataSource.getRowCount() ); return { prevRenderedRowsCount: state.curRenderedRowsCount, curRenderedRowsCount: rowsToRender }; }, () => { this._measureAndUpdateScrollProps(); this.setState(state => ({ prevRenderedRowsCount: state.curRenderedRowsCount, })); }); }, _getDistanceFromEnd: function(scrollProperties) { var maxLength = Math.max( scrollProperties.contentLength, scrollProperties.visibleLength ); return maxLength - scrollProperties.visibleLength - scrollProperties.offset; }, _updateVisibleRows: function(updatedFrames) { if (!this.props.onChangeVisibleRows) { return; // No need to compute visible rows if there is no callback } if (updatedFrames) { updatedFrames.forEach((newFrame) => { this._childFrames[newFrame.index] = merge(newFrame); }); } var isVertical = !this.props.horizontal; var dataSource = this.props.dataSource; var visibleMin = this.scrollProperties.offset; var visibleMax = visibleMin + this.scrollProperties.visibleLength; var allRowIDs = dataSource.rowIdentities; var header = this.props.renderHeader && this.props.renderHeader(); var totalIndex = header ? 1 : 0; var visibilityChanged = false; var changedRows = {}; for (var sectionIdx = 0; sectionIdx < allRowIDs.length; sectionIdx++) { var rowIDs = allRowIDs[sectionIdx]; if (rowIDs.length === 0) { continue; } var sectionID = dataSource.sectionIdentities[sectionIdx]; if (this.props.renderSectionHeader) { totalIndex++; } var visibleSection = this._visibleRows[sectionID]; if (!visibleSection) { visibleSection = {}; } for (var rowIdx = 0; rowIdx < rowIDs.length; rowIdx++) { var rowID = rowIDs[rowIdx]; var frame = this._childFrames[totalIndex]; totalIndex++; if (!frame) { break; } var rowVisible = visibleSection[rowID]; var min = isVertical ? frame.y : frame.x; var max = min + (isVertical ? frame.height : frame.width); if (min > visibleMax || max < visibleMin) { if (rowVisible) { visibilityChanged = true; delete visibleSection[rowID]; if (!changedRows[sectionID]) { changedRows[sectionID] = {}; } changedRows[sectionID][rowID] = false; } } else if (!rowVisible) { visibilityChanged = true; visibleSection[rowID] = true; if (!changedRows[sectionID]) { changedRows[sectionID] = {}; } changedRows[sectionID][rowID] = true; } } if (!isEmpty(visibleSection)) { this._visibleRows[sectionID] = visibleSection; } else if (this._visibleRows[sectionID]) { delete this._visibleRows[sectionID]; } } visibilityChanged && this.props.onChangeVisibleRows(this._visibleRows, changedRows); }, _onScroll: function(e) { var isVertical = !this.props.horizontal; this.scrollProperties.visibleLength = e.nativeEvent.layoutMeasurement[ isVertical ? 'height' : 'width' ]; this.scrollProperties.contentLength = e.nativeEvent.contentSize[ isVertical ? 'height' : 'width' ]; this.scrollProperties.offset = e.nativeEvent.contentOffset[ isVertical ? 'y' : 'x' ]; this._updateVisibleRows(e.nativeEvent.updatedChildFrames); if (!this._maybeCallOnEndReached(e)) { this._renderMoreRowsIfNeeded(); } if (this.props.onEndReached && this._getDistanceFromEnd(this.scrollProperties) > this.props.onEndReachedThreshold) { // Scrolled out of the end zone, so it should be able to trigger again. this._sentEndForContentLength = null; } this.props.onScroll && this.props.onScroll(e); }, }); module.exports = ListView;
philonpang/react-native
Libraries/CustomComponents/ListView/ListView.js
JavaScript
bsd-3-clause
21,129
var searchData= [ ['decompile',['Decompile',['../classreranker_1_1_candidate.html#aeb149e5da4251f1854eadbf50230342c',1,'reranker::Candidate']]], ['decompilefeatures',['DecompileFeatures',['../classreranker_1_1_candidate_set.html#acf9fb683cb0435f29188de9218941bca',1,'reranker::CandidateSet']]], ['defined',['Defined',['../classreranker_1_1_environment_impl.html#ae88e17a317d959cf91bb4d5660a68c59',1,'reranker::EnvironmentImpl::Defined()'],['../classreranker_1_1_var_map_base.html#af9d31b9fe4a4a5b6b30ea968fd59ddf5',1,'reranker::VarMapBase::Defined()'],['../classreranker_1_1_environment.html#aed7a464b7498b2855eb24ee4563c8276',1,'reranker::Environment::Defined()'],['../classreranker_1_1_var_map.html#a9962a54a8e138ea24f49fdb92df108dd',1,'reranker::VarMap::Defined()']]], ['do',['Do',['../classreranker_1_1_end_of_epoch_model_writer.html#ae7b2e80d80d1fe56705b07b175a1418e',1,'reranker::EndOfEpochModelWriter::Do()'],['../classreranker_1_1_model_1_1_hook.html#a676b9a02709b0a61856a8ff246f182d6',1,'reranker::Model::Hook::Do()']]], ['dot',['Dot',['../classreranker_1_1_feature_vector.html#a03929c2f26faf01b1406074943f99b86',1,'reranker::FeatureVector']]] ];
dbikel/refr
html/search/functions_64.js
JavaScript
bsd-3-clause
1,166
/*! WebUploader 0.1.7-alpha */ /** * @fileOverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/AMD)模块定义方式组织起来。 * * AMD API 内部的简单不完全实现,请忽略。只有当WebUploader被合并成一个文件的时候才会引入。 */ (function( root, factory ) { var modules = {}, // 内部require, 简单不完全实现。 // https://github.com/amdjs/amdjs-api/wiki/require _require = function( deps, callback ) { var args, len, i; // 如果deps不是数组,则直接返回指定module if ( typeof deps === 'string' ) { return getModule( deps ); } else { args = []; for( len = deps.length, i = 0; i < len; i++ ) { args.push( getModule( deps[ i ] ) ); } return callback.apply( null, args ); } }, // 内部define,暂时不支持不指定id. _define = function( id, deps, factory ) { if ( arguments.length === 2 ) { factory = deps; deps = null; } _require( deps || [], function() { setModule( id, factory, arguments ); }); }, // 设置module, 兼容CommonJs写法。 setModule = function( id, factory, args ) { var module = { exports: factory }, returned; if ( typeof factory === 'function' ) { args.length || (args = [ _require, module.exports, module ]); returned = factory.apply( null, args ); returned !== undefined && (module.exports = returned); } modules[ id ] = module.exports; }, // 根据id获取module getModule = function( id ) { var module = modules[ id ] || root[ id ]; if ( !module ) { throw new Error( '`' + id + '` is undefined' ); } return module; }, // 将所有modules,将路径ids装换成对象。 exportsTo = function( obj ) { var key, host, parts, part, last, ucFirst; // make the first character upper case. ucFirst = function( str ) { return str && (str.charAt( 0 ).toUpperCase() + str.substr( 1 )); }; for ( key in modules ) { host = obj; if ( !modules.hasOwnProperty( key ) ) { continue; } parts = key.split('/'); last = ucFirst( parts.pop() ); while( (part = ucFirst( parts.shift() )) ) { host[ part ] = host[ part ] || {}; host = host[ part ]; } host[ last ] = modules[ key ]; } return obj; }, makeExport = function( dollar ) { root.__dollar = dollar; // exports every module. return exportsTo( factory( root, _define, _require ) ); }, origin; if ( typeof module === 'object' && typeof module.exports === 'object' ) { // For CommonJS and CommonJS-like environments where a proper window is present, module.exports = makeExport(); } else if ( typeof define === 'function' && define.amd ) { // Allow using this built library as an AMD module // in another project. That other project will only // see this AMD call, not the internal modules in // the closure below. define([ 'jquery' ], makeExport ); } else { // Browser globals case. Just assign the // result to a property on the global. origin = root.WebUploader; root.WebUploader = makeExport(); root.WebUploader.noConflict = function() { root.WebUploader = origin; }; } })( window, function( window, define, require ) { /** * @fileOverview jQuery or Zepto * @require "jquery" * @require "zepto" */ define('dollar-third',[],function() { var req = window.require; var $ = window.__dollar || window.jQuery || window.Zepto || req('jquery') || req('zepto'); if ( !$ ) { throw new Error('jQuery or Zepto not found!'); } return $; }); /** * @fileOverview Dom 操作相关 */ define('dollar',[ 'dollar-third' ], function( _ ) { return _; }); /** * @fileOverview 使用jQuery的Promise */ define('promise-third',[ 'dollar' ], function( $ ) { return { Deferred: $.Deferred, when: $.when, isPromise: function( anything ) { return anything && typeof anything.then === 'function'; } }; }); /** * 同jq-bridge,在没有jquery的时候才需要,用来实现Deferred * @fileOverview Promise/A+ */ define('promise',[ 'promise-third' ], function( _ ) { return _; }); /** * @fileOverview 基础类方法。 */ /** * Web Uploader内部类的详细说明,以下提及的功能类,都可以在`WebUploader`这个变量中访问到。 * * As you know, Web Uploader的每个文件都是用过[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)规范中的`define`组织起来的, 每个Module都会有个module id. * 默认module id为该文件的路径,而此路径将会转化成名字空间存放在WebUploader中。如: * * * module `base`:WebUploader.Base * * module `file`: WebUploader.File * * module `lib/dnd`: WebUploader.Lib.Dnd * * module `runtime/html5/dnd`: WebUploader.Runtime.Html5.Dnd * * * 以下文档中对类的使用可能省略掉了`WebUploader`前缀。 * @module WebUploader * @title WebUploader API文档 */ define('base',[ 'dollar', 'promise' ], function( $, promise ) { var noop = function() {}, call = Function.call; // http://jsperf.com/uncurrythis // 反科里化 function uncurryThis( fn ) { return function() { return call.apply( fn, arguments ); }; } function bindFn( fn, context ) { return function() { return fn.apply( context, arguments ); }; } function createObject( proto ) { var f; if ( Object.create ) { return Object.create( proto ); } else { f = function() {}; f.prototype = proto; return new f(); } } /** * 基础类,提供一些简单常用的方法。 * @class Base */ return { /** * @property {String} version 当前版本号。 */ version: '0.1.7-alpha', /** * @property {jQuery|Zepto} $ 引用依赖的jQuery或者Zepto对象。 */ $: $, Deferred: promise.Deferred, isPromise: promise.isPromise, when: promise.when, /** * @description 简单的浏览器检查结果。 * * * `webkit` webkit版本号,如果浏览器为非webkit内核,此属性为`undefined`。 * * `chrome` chrome浏览器版本号,如果浏览器为chrome,此属性为`undefined`。 * * `ie` ie浏览器版本号,如果浏览器为非ie,此属性为`undefined`。**暂不支持ie10+** * * `firefox` firefox浏览器版本号,如果浏览器为非firefox,此属性为`undefined`。 * * `safari` safari浏览器版本号,如果浏览器为非safari,此属性为`undefined`。 * * `opera` opera浏览器版本号,如果浏览器为非opera,此属性为`undefined`。 * * @property {Object} [browser] */ browser: (function( ua ) { var ret = {}, webkit = ua.match( /WebKit\/([\d.]+)/ ), chrome = ua.match( /Chrome\/([\d.]+)/ ) || ua.match( /CriOS\/([\d.]+)/ ), ie = ua.match( /MSIE\s([\d\.]+)/ ) || ua.match( /(?:trident)(?:.*rv:([\w.]+))?/i ), firefox = ua.match( /Firefox\/([\d.]+)/ ), safari = ua.match( /Safari\/([\d.]+)/ ), opera = ua.match( /OPR\/([\d.]+)/ ); webkit && (ret.webkit = parseFloat( webkit[ 1 ] )); chrome && (ret.chrome = parseFloat( chrome[ 1 ] )); ie && (ret.ie = parseFloat( ie[ 1 ] )); firefox && (ret.firefox = parseFloat( firefox[ 1 ] )); safari && (ret.safari = parseFloat( safari[ 1 ] )); opera && (ret.opera = parseFloat( opera[ 1 ] )); return ret; })( navigator.userAgent ), /** * @description 操作系统检查结果。 * * * `android` 如果在android浏览器环境下,此值为对应的android版本号,否则为`undefined`。 * * `ios` 如果在ios浏览器环境下,此值为对应的ios版本号,否则为`undefined`。 * @property {Object} [os] */ os: (function( ua ) { var ret = {}, // osx = !!ua.match( /\(Macintosh\; Intel / ), android = ua.match( /(?:Android);?[\s\/]+([\d.]+)?/ ), ios = ua.match( /(?:iPad|iPod|iPhone).*OS\s([\d_]+)/ ); // osx && (ret.osx = true); android && (ret.android = parseFloat( android[ 1 ] )); ios && (ret.ios = parseFloat( ios[ 1 ].replace( /_/g, '.' ) )); return ret; })( navigator.userAgent ), /** * 实现类与类之间的继承。 * @method inherits * @grammar Base.inherits( super ) => child * @grammar Base.inherits( super, protos ) => child * @grammar Base.inherits( super, protos, statics ) => child * @param {Class} super 父类 * @param {Object | Function} [protos] 子类或者对象。如果对象中包含constructor,子类将是用此属性值。 * @param {Function} [protos.constructor] 子类构造器,不指定的话将创建个临时的直接执行父类构造器的方法。 * @param {Object} [statics] 静态属性或方法。 * @return {Class} 返回子类。 * @example * function Person() { * console.log( 'Super' ); * } * Person.prototype.hello = function() { * console.log( 'hello' ); * }; * * var Manager = Base.inherits( Person, { * world: function() { * console.log( 'World' ); * } * }); * * // 因为没有指定构造器,父类的构造器将会执行。 * var instance = new Manager(); // => Super * * // 继承子父类的方法 * instance.hello(); // => hello * instance.world(); // => World * * // 子类的__super__属性指向父类 * console.log( Manager.__super__ === Person ); // => true */ inherits: function( Super, protos, staticProtos ) { var child; if ( typeof protos === 'function' ) { child = protos; protos = null; } else if ( protos && protos.hasOwnProperty('constructor') ) { //如果子类存在构造器则实用子类的构造器 child = protos.constructor; } else { //调用父类 child = function() { return Super.apply( this, arguments ); }; } // 复制静态方法 $.extend( true, child, Super, staticProtos || {} ); /* jshint camelcase: false */ // 让子类的__super__属性指向父类。 child.__super__ = Super.prototype; // 构建原型,添加原型方法或属性。 // 暂时用Object.create实现。 child.prototype = createObject( Super.prototype ); protos && $.extend( true, child.prototype, protos ); return child; }, /** * 一个不做任何事情的方法。可以用来赋值给默认的callback. * @method noop */ noop: noop, /** * 返回一个新的方法,此方法将已指定的`context`来执行。 * @grammar Base.bindFn( fn, context ) => Function * @method bindFn * @example * var doSomething = function() { * console.log( this.name ); * }, * obj = { * name: 'Object Name' * }, * aliasFn = Base.bind( doSomething, obj ); * * aliasFn(); // => Object Name * */ bindFn: bindFn, /** * 引用Console.log如果存在的话,否则引用一个[空函数noop](#WebUploader:Base.noop)。 * @grammar Base.log( args... ) => undefined * @method log */ log: (function() { if ( window.console ) { return bindFn( console.log, console ); } return noop; })(), nextTick: (function() { return function( cb ) { setTimeout( cb, 1 ); }; // @bug 当浏览器不在当前窗口时就停了。 // var next = window.requestAnimationFrame || // window.webkitRequestAnimationFrame || // window.mozRequestAnimationFrame || // function( cb ) { // window.setTimeout( cb, 1000 / 60 ); // }; // // fix: Uncaught TypeError: Illegal invocation // return bindFn( next, window ); })(), /** * 被[uncurrythis](http://www.2ality.com/2011/11/uncurrying-this.html)的数组slice方法。 * 将用来将非数组对象转化成数组对象。 * @grammar Base.slice( target, start[, end] ) => Array * @method slice * @example * function doSomthing() { * var args = Base.slice( arguments, 1 ); * console.log( args ); * } * * doSomthing( 'ignored', 'arg2', 'arg3' ); // => Array ["arg2", "arg3"] */ slice: uncurryThis( [].slice ), /** * 生成唯一的ID * @method guid * @grammar Base.guid() => String * @grammar Base.guid( prefx ) => String */ guid: (function() { var counter = 0; return function( prefix ) { var guid = (+new Date()).toString( 32 ), i = 0; for ( ; i < 5; i++ ) { guid += Math.floor( Math.random() * 65535 ).toString( 32 ); } return (prefix || 'wu_') + guid + (counter++).toString( 32 ); }; })(), /** * 格式化文件大小, 输出成带单位的字符串 * @method formatSize * @grammar Base.formatSize( size ) => String * @grammar Base.formatSize( size, pointLength ) => String * @grammar Base.formatSize( size, pointLength, units ) => String * @param {Number} size 文件大小 * @param {Number} [pointLength=2] 精确到的小数点数。 * @param {Array} [units=[ 'B', 'K', 'M', 'G', 'TB' ]] 单位数组。从字节,到千字节,一直往上指定。如果单位数组里面只指定了到了K(千字节),同时文件大小大于M, 此方法的输出将还是显示成多少K. * @example * console.log( Base.formatSize( 100 ) ); // => 100B * console.log( Base.formatSize( 1024 ) ); // => 1.00K * console.log( Base.formatSize( 1024, 0 ) ); // => 1K * console.log( Base.formatSize( 1024 * 1024 ) ); // => 1.00M * console.log( Base.formatSize( 1024 * 1024 * 1024 ) ); // => 1.00G * console.log( Base.formatSize( 1024 * 1024 * 1024, 0, ['B', 'KB', 'MB'] ) ); // => 1024MB */ formatSize: function( size, pointLength, units ) { var unit; units = units || [ 'B', 'K', 'M', 'G', 'TB' ]; while ( (unit = units.shift()) && size > 1024 ) { size = size / 1024; } return (unit === 'B' ? size : size.toFixed( pointLength || 2 )) + unit; } }; }); /** * 事件处理类,可以独立使用,也可以扩展给对象使用。 * @fileOverview Mediator */ define('mediator',[ 'base' ], function( Base ) { var $ = Base.$, slice = [].slice, separator = /\s+/, protos; // 根据条件过滤出事件handlers. function findHandlers( arr, name, callback, context ) { return $.grep( arr, function( handler ) { return handler && (!name || handler.e === name) && (!callback || handler.cb === callback || handler.cb._cb === callback) && (!context || handler.ctx === context); }); } function eachEvent( events, callback, iterator ) { // 不支持对象,只支持多个event用空格隔开 $.each( (events || '').split( separator ), function( _, key ) { iterator( key, callback ); }); } function triggerHanders( events, args ) { var stoped = false, i = -1, len = events.length, handler; while ( ++i < len ) { handler = events[ i ]; if ( handler.cb.apply( handler.ctx2, args ) === false ) { stoped = true; break; } } return !stoped; } protos = { /** * 绑定事件。 * * `callback`方法在执行时,arguments将会来源于trigger的时候携带的参数。如 * ```javascript * var obj = {}; * * // 使得obj有事件行为 * Mediator.installTo( obj ); * * obj.on( 'testa', function( arg1, arg2 ) { * console.log( arg1, arg2 ); // => 'arg1', 'arg2' * }); * * obj.trigger( 'testa', 'arg1', 'arg2' ); * ``` * * 如果`callback`中,某一个方法`return false`了,则后续的其他`callback`都不会被执行到。 * 切会影响到`trigger`方法的返回值,为`false`。 * * `on`还可以用来添加一个特殊事件`all`, 这样所有的事件触发都会响应到。同时此类`callback`中的arguments有一个不同处, * 就是第一个参数为`type`,记录当前是什么事件在触发。此类`callback`的优先级比脚低,会再正常`callback`执行完后触发。 * ```javascript * obj.on( 'all', function( type, arg1, arg2 ) { * console.log( type, arg1, arg2 ); // => 'testa', 'arg1', 'arg2' * }); * ``` * * @method on * @grammar on( name, callback[, context] ) => self * @param {String} name 事件名,支持多个事件用空格隔开 * @param {Function} callback 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable * @class Mediator */ on: function( name, callback, context ) { var me = this, set; if ( !callback ) { return this; } set = this._events || (this._events = []); eachEvent( name, callback, function( name, callback ) { var handler = { e: name }; handler.cb = callback; handler.ctx = context; handler.ctx2 = context || me; handler.id = set.length; set.push( handler ); }); return this; }, /** * 绑定事件,且当handler执行完后,自动解除绑定。 * @method once * @grammar once( name, callback[, context] ) => self * @param {String} name 事件名 * @param {Function} callback 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable */ once: function( name, callback, context ) { var me = this; if ( !callback ) { return me; } eachEvent( name, callback, function( name, callback ) { var once = function() { me.off( name, once ); return callback.apply( context || me, arguments ); }; once._cb = callback; me.on( name, once, context ); }); return me; }, /** * 解除事件绑定 * @method off * @grammar off( [name[, callback[, context] ] ] ) => self * @param {String} [name] 事件名 * @param {Function} [callback] 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable */ off: function( name, cb, ctx ) { var events = this._events; if ( !events ) { return this; } if ( !name && !cb && !ctx ) { this._events = []; return this; } eachEvent( name, cb, function( name, cb ) { $.each( findHandlers( events, name, cb, ctx ), function() { delete events[ this.id ]; }); }); return this; }, /** * 触发事件 * @method trigger * @grammar trigger( name[, args...] ) => self * @param {String} type 事件名 * @param {*} [...] 任意参数 * @return {Boolean} 如果handler中return false了,则返回false, 否则返回true */ trigger: function( type ) { var args, events, allEvents; if ( !this._events || !type ) { return this; } args = slice.call( arguments, 1 ); events = findHandlers( this._events, type ); allEvents = findHandlers( this._events, 'all' ); return triggerHanders( events, args ) && triggerHanders( allEvents, arguments ); } }; /** * 中介者,它本身是个单例,但可以通过[installTo](#WebUploader:Mediator:installTo)方法,使任何对象具备事件行为。 * 主要目的是负责模块与模块之间的合作,降低耦合度。 * * @class Mediator */ return $.extend({ /** * 可以通过这个接口,使任何对象具备事件功能。 * @method installTo * @param {Object} obj 需要具备事件行为的对象。 * @return {Object} 返回obj. */ installTo: function( obj ) { return $.extend( obj, protos ); } }, protos ); }); /** * @fileOverview Uploader上传类 */ define('uploader',[ 'base', 'mediator' ], function( Base, Mediator ) { var $ = Base.$; /** * 上传入口类。 * @class Uploader * @constructor * @grammar new Uploader( opts ) => Uploader * @example * var uploader = WebUploader.Uploader({ * swf: 'path_of_swf/Uploader.swf', * * // 开起分片上传。 * chunked: true * }); */ function Uploader( opts ) { this.options = $.extend( true, {}, Uploader.options, opts ); this._init( this.options ); } // default Options // widgets中有相应扩展 Uploader.options = {}; Mediator.installTo( Uploader.prototype ); // 批量添加纯命令式方法。 $.each({ upload: 'start-upload', stop: 'stop-upload', getFile: 'get-file', getFiles: 'get-files', addFile: 'add-file', addFiles: 'add-file', sort: 'sort-files', removeFile: 'remove-file', cancelFile: 'cancel-file', skipFile: 'skip-file', retry: 'retry', isInProgress: 'is-in-progress', makeThumb: 'make-thumb', md5File: 'md5-file', getDimension: 'get-dimension', addButton: 'add-btn', predictRuntimeType: 'predict-runtime-type', refresh: 'refresh', disable: 'disable', enable: 'enable', reset: 'reset' }, function( fn, command ) { Uploader.prototype[ fn ] = function() { return this.request( command, arguments ); }; }); $.extend( Uploader.prototype, { state: 'pending', _init: function( opts ) { var me = this; me.request( 'init', opts, function() { me.state = 'ready'; me.trigger('ready'); }); }, /** * 获取或者设置Uploader配置项。 * @method option * @grammar option( key ) => * * @grammar option( key, val ) => self * @example * * // 初始状态图片上传前不会压缩 * var uploader = new WebUploader.Uploader({ * compress: null; * }); * * // 修改后图片上传前,尝试将图片压缩到1600 * 1600 * uploader.option( 'compress', { * width: 1600, * height: 1600 * }); */ option: function( key, val ) { var opts = this.options; // setter if ( arguments.length > 1 ) { if ( $.isPlainObject( val ) && $.isPlainObject( opts[ key ] ) ) { $.extend( opts[ key ], val ); } else { opts[ key ] = val; } } else { // getter return key ? opts[ key ] : opts; } }, /** * 获取文件统计信息。返回一个包含一下信息的对象。 * * `successNum` 上传成功的文件数 * * `progressNum` 上传中的文件数 * * `cancelNum` 被删除的文件数 * * `invalidNum` 无效的文件数 * * `uploadFailNum` 上传失败的文件数 * * `queueNum` 还在队列中的文件数 * * `interruptNum` 被暂停的文件数 * @method getStats * @grammar getStats() => Object */ getStats: function() { // return this._mgr.getStats.apply( this._mgr, arguments ); var stats = this.request('get-stats'); return stats ? { successNum: stats.numOfSuccess, progressNum: stats.numOfProgress, // who care? // queueFailNum: 0, cancelNum: stats.numOfCancel, invalidNum: stats.numOfInvalid, uploadFailNum: stats.numOfUploadFailed, queueNum: stats.numOfQueue, interruptNum: stats.numofInterrupt } : {}; }, // 需要重写此方法来来支持opts.onEvent和instance.onEvent的处理器 trigger: function( type/*, args...*/ ) { var args = [].slice.call( arguments, 1 ), opts = this.options, name = 'on' + type.substring( 0, 1 ).toUpperCase() + type.substring( 1 ); if ( // 调用通过on方法注册的handler. Mediator.trigger.apply( this, arguments ) === false || // 调用opts.onEvent $.isFunction( opts[ name ] ) && opts[ name ].apply( this, args ) === false || // 调用this.onEvent $.isFunction( this[ name ] ) && this[ name ].apply( this, args ) === false || // 广播所有uploader的事件。 Mediator.trigger.apply( Mediator, [ this, type ].concat( args ) ) === false ) { return false; } return true; }, /** * 销毁 webuploader 实例 * @method destroy * @grammar destroy() => undefined */ destroy: function() { this.request( 'destroy', arguments ); this.off(); }, // widgets/widget.js将补充此方法的详细文档。 request: Base.noop }); /** * 创建Uploader实例,等同于new Uploader( opts ); * @method create * @class Base * @static * @grammar Base.create( opts ) => Uploader */ Base.create = Uploader.create = function( opts ) { return new Uploader( opts ); }; // 暴露Uploader,可以通过它来扩展业务逻辑。 Base.Uploader = Uploader; return Uploader; }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/runtime',[ 'base', 'mediator' ], function( Base, Mediator ) { var $ = Base.$, factories = {}, // 获取对象的第一个key getFirstKey = function( obj ) { for ( var key in obj ) { if ( obj.hasOwnProperty( key ) ) { return key; } } return null; }; // 接口类。 function Runtime( options ) { //默认container为document.body this.options = $.extend({ container: document.body }, options ); //生成uid this.uid = Base.guid('rt_'); } $.extend( Runtime.prototype, { getContainer: function() { var opts = this.options, parent, container; if ( this._container ) { return this._container; } parent = $( opts.container || document.body ); container = $( document.createElement('div') ); container.attr( 'id', 'rt_' + this.uid ); container.css({ position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); parent.append( container ); parent.addClass('webuploader-container'); this._container = container; this._parent = parent; return container; }, init: Base.noop, exec: Base.noop, destroy: function() { this._container && this._container.remove(); this._parent && this._parent.removeClass('webuploader-container'); this.off(); } }); Runtime.orders = 'html5,flash'; /** * 添加Runtime实现。 * @param {String} type 类型 * @param {Runtime} factory 具体Runtime实现。 */ Runtime.addRuntime = function( type, factory ) { factories[ type ] = factory; }; Runtime.hasRuntime = function( type ) { return !!(type ? factories[ type ] : getFirstKey( factories )); }; Runtime.create = function( opts, orders ) { var type, runtime; orders = orders || Runtime.orders; $.each( orders.split( /\s*,\s*/g ), function() { if ( factories[ this ] ) { type = this; return false; } }); type = type || getFirstKey( factories ); if ( !type ) { throw new Error('Runtime Error'); } runtime = new factories[ type ]( opts ); return runtime; }; Mediator.installTo( Runtime.prototype ); return Runtime; }); /** * 连接器 * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/client',[ 'base', 'mediator', 'runtime/runtime' ], function( Base, Mediator, Runtime ) { var cache; cache = (function() { var obj = {}; return { add: function( runtime ) { obj[ runtime.uid ] = runtime; }, get: function( ruid, standalone ) { var i; if ( ruid ) { return obj[ ruid ]; } for ( i in obj ) { // 有些类型不能重用,比如filepicker. if ( standalone && obj[ i ].__standalone ) { continue; } return obj[ i ]; } return null; }, remove: function( runtime ) { delete obj[ runtime.uid ]; } }; })(); function RuntimeClient( component, standalone ) { var deferred = Base.Deferred(), runtime; this.uid = Base.guid('client_'); // 允许runtime没有初始化之前,注册一些方法在初始化后执行。 this.runtimeReady = function( cb ) { return deferred.done( cb ); }; this.connectRuntime = function( opts, cb ) { // already connected. if ( runtime ) { throw new Error('already connected!'); } deferred.done( cb ); if ( typeof opts === 'string' && cache.get( opts ) ) { runtime = cache.get( opts ); } // 像filePicker只能独立存在,不能公用。 runtime = runtime || cache.get( null, standalone ); // 需要创建 if ( !runtime ) { runtime = Runtime.create( opts, opts.runtimeOrder ); runtime.__promise = deferred.promise(); runtime.once( 'ready', deferred.resolve ); runtime.init(); cache.add( runtime ); runtime.__client = 1; } else { // 来自cache Base.$.extend( runtime.options, opts ); runtime.__promise.then( deferred.resolve ); runtime.__client++; } standalone && (runtime.__standalone = standalone); return runtime; }; this.getRuntime = function() { return runtime; }; this.disconnectRuntime = function() { if ( !runtime ) { return; } runtime.__client--; if ( runtime.__client <= 0 ) { cache.remove( runtime ); delete runtime.__promise; runtime.destroy(); } runtime = null; }; this.exec = function() { if ( !runtime ) { return; } var args = Base.slice( arguments ); component && args.unshift( component ); return runtime.exec.apply( this, args ); }; this.getRuid = function() { return runtime && runtime.uid; }; this.destroy = (function( destroy ) { return function() { destroy && destroy.apply( this, arguments ); this.trigger('destroy'); this.off(); this.exec('destroy'); this.disconnectRuntime(); }; })( this.destroy ); } Mediator.installTo( RuntimeClient.prototype ); return RuntimeClient; }); /** * 文件拖拽 * @fileOverview 错误信息 */ define('lib/dnd',[ 'base', 'mediator', 'runtime/client' ], function( Base, Mediator, RuntimeClent ) { var $ = Base.$; function DragAndDrop( opts ) { opts = this.options = $.extend({}, DragAndDrop.options, opts ); opts.container = $( opts.container ); if ( !opts.container.length ) { return; } RuntimeClent.call( this, 'DragAndDrop' ); } DragAndDrop.options = { accept: null, disableGlobalDnd: false }; Base.inherits( RuntimeClent, { constructor: DragAndDrop, init: function() { var me = this; me.connectRuntime( me.options, function() { me.exec('init'); me.trigger('ready'); }); } }); Mediator.installTo( DragAndDrop.prototype ); return DragAndDrop; }); /** * 实现command机制 * @fileOverview 组件基类。 */ define('widgets/widget',[ 'base', 'uploader' ], function( Base, Uploader ) { var $ = Base.$, _init = Uploader.prototype._init, _destroy = Uploader.prototype.destroy, IGNORE = {}, widgetClass = []; function isArrayLike( obj ) { if ( !obj ) { return false; } var length = obj.length, type = $.type( obj ); if ( obj.nodeType === 1 && length ) { return true; } return type === 'array' || type !== 'function' && type !== 'string' && (length === 0 || typeof length === 'number' && length > 0 && (length - 1) in obj); } function Widget( uploader ) { this.owner = uploader; this.options = uploader.options; } $.extend( Widget.prototype, { init: Base.noop, // 类Backbone的事件监听声明,监听uploader实例上的事件 // widget直接无法监听事件,事件只能通过uploader来传递 invoke: function( apiName, args ) { /* { 'make-thumb': 'makeThumb' } */ var map = this.responseMap; // 如果无API响应声明则忽略 if ( !map || !(apiName in map) || !(map[ apiName ] in this) || !$.isFunction( this[ map[ apiName ] ] ) ) { return IGNORE; } return this[ map[ apiName ] ].apply( this, args ); }, /** * 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。 * @method request * @grammar request( command, args ) => * | Promise * @grammar request( command, args, callback ) => Promise * @for Uploader */ request: function() { return this.owner.request.apply( this.owner, arguments ); } }); // 扩展Uploader. $.extend( Uploader.prototype, { /** * @property {String | Array} [disableWidgets=undefined] * @namespace options * @for Uploader * @description 默认所有 Uploader.register 了的 widget 都会被加载,如果禁用某一部分,请通过此 option 指定黑名单。 */ // 覆写_init用来初始化widgets _init: function() { var me = this, widgets = me._widgets = [], deactives = me.options.disableWidgets || ''; $.each( widgetClass, function( _, klass ) { (!deactives || !~deactives.indexOf( klass._name )) && widgets.push( new klass( me ) ); }); return _init.apply( me, arguments ); }, request: function( apiName, args, callback ) { var i = 0, widgets = this._widgets, len = widgets && widgets.length, rlts = [], dfds = [], widget, rlt, promise, key; args = isArrayLike( args ) ? args : [ args ]; for ( ; i < len; i++ ) { widget = widgets[ i ]; rlt = widget.invoke( apiName, args ); if ( rlt !== IGNORE ) { // Deferred对象 if ( Base.isPromise( rlt ) ) { dfds.push( rlt ); } else { rlts.push( rlt ); } } } // 如果有callback,则用异步方式。 if ( callback || dfds.length ) { promise = Base.when.apply( Base, dfds ); key = promise.pipe ? 'pipe' : 'then'; // 很重要不能删除。删除了会死循环。 // 保证执行顺序。让callback总是在下一个 tick 中执行。 return promise[ key ](function() { var deferred = Base.Deferred(), args = arguments; if ( args.length === 1 ) { args = args[ 0 ]; } setTimeout(function() { deferred.resolve( args ); }, 1 ); return deferred.promise(); })[ callback ? key : 'done' ]( callback || Base.noop ); } else { return rlts[ 0 ]; } }, destroy: function() { _destroy.apply( this, arguments ); this._widgets = null; } }); /** * 添加组件 * @grammar Uploader.register(proto); * @grammar Uploader.register(map, proto); * @param {object} responseMap API 名称与函数实现的映射 * @param {object} proto 组件原型,构造函数通过 constructor 属性定义 * @method Uploader.register * @for Uploader * @example * Uploader.register({ * 'make-thumb': 'makeThumb' * }, { * init: function( options ) {}, * makeThumb: function() {} * }); * * Uploader.register({ * 'make-thumb': function() { * * } * }); */ Uploader.register = Widget.register = function( responseMap, widgetProto ) { var map = { init: 'init', destroy: 'destroy', name: 'anonymous' }, klass; if ( arguments.length === 1 ) { widgetProto = responseMap; // 自动生成 map 表。 $.each(widgetProto, function(key) { if ( key[0] === '_' || key === 'name' ) { key === 'name' && (map.name = widgetProto.name); return; } map[key.replace(/[A-Z]/g, '-$&').toLowerCase()] = key; }); } else { map = $.extend( map, responseMap ); } widgetProto.responseMap = map; klass = Base.inherits( Widget, widgetProto ); klass._name = map.name; widgetClass.push( klass ); return klass; }; /** * 删除插件,只有在注册时指定了名字的才能被删除。 * @grammar Uploader.unRegister(name); * @param {string} name 组件名字 * @method Uploader.unRegister * @for Uploader * @example * * Uploader.register({ * name: 'custom', * * 'make-thumb': function() { * * } * }); * * Uploader.unRegister('custom'); */ Uploader.unRegister = Widget.unRegister = function( name ) { if ( !name || name === 'anonymous' ) { return; } // 删除指定的插件。 for ( var i = widgetClass.length; i--; ) { if ( widgetClass[i]._name === name ) { widgetClass.splice(i, 1) } } }; return Widget; }); /** * 文件拖拽应用在Uploader * @fileOverview DragAndDrop Widget。 */ define('widgets/filednd',[ 'base', 'uploader', 'lib/dnd', 'widgets/widget' ], function( Base, Uploader, Dnd ) { var $ = Base.$; Uploader.options.dnd = ''; /** * @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。 * @namespace options * @for Uploader */ /** * @property {Selector} [disableGlobalDnd=false] 是否禁掉整个页面的拖拽功能,如果不禁用,图片拖进来的时候会默认被浏览器打开。 * @namespace options * @for Uploader */ /** * @event dndAccept * @param {DataTransferItemList} items DataTransferItem * @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。 * @for Uploader */ return Uploader.register({ name: 'dnd', init: function( opts ) { if ( !opts.dnd || this.request('predict-runtime-type') !== 'html5' ) { return; } var me = this, deferred = Base.Deferred(), options = $.extend({}, { disableGlobalDnd: opts.disableGlobalDnd, container: opts.dnd, accept: opts.accept }), dnd; this.dnd = dnd = new Dnd( options ); dnd.once( 'ready', deferred.resolve ); dnd.on( 'drop', function( files ) { me.request( 'add-file', [ files ]); }); // 检测文件是否全部允许添加。 dnd.on( 'accept', function( items ) { return me.owner.trigger( 'dndAccept', items ); }); dnd.init(); return deferred.promise(); }, destroy: function() { this.dnd && this.dnd.destroy(); } }); }); /** * * 负责图片黏贴 * @fileOverview 错误信息 */ define('lib/filepaste',[ 'base', 'mediator', 'runtime/client' ], function( Base, Mediator, RuntimeClent ) { var $ = Base.$; function FilePaste( opts ) { opts = this.options = $.extend({}, opts ); opts.container = $( opts.container || document.body ); RuntimeClent.call( this, 'FilePaste' ); } Base.inherits( RuntimeClent, { constructor: FilePaste, init: function() { var me = this; me.connectRuntime( me.options, function() { me.exec('init'); me.trigger('ready'); }); } }); Mediator.installTo( FilePaste.prototype ); return FilePaste; }); /** * 图片粘贴应用在Uploader * @fileOverview 组件基类。 */ define('widgets/filepaste',[ 'base', 'uploader', 'lib/filepaste', 'widgets/widget' ], function( Base, Uploader, FilePaste ) { var $ = Base.$; /** * @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`. * @namespace options * @for Uploader */ return Uploader.register({ name: 'paste', init: function( opts ) { if ( !opts.paste || this.request('predict-runtime-type') !== 'html5' ) { return; } var me = this, deferred = Base.Deferred(), options = $.extend({}, { container: opts.paste, accept: opts.accept }), paste; this.paste = paste = new FilePaste( options ); paste.once( 'ready', deferred.resolve ); paste.on( 'paste', function( files ) { me.owner.request( 'add-file', [ files ]); }); paste.init(); return deferred.promise(); }, destroy: function() { this.paste && this.paste.destroy(); } }); }); /**带ruid(为了兼容flash抽象出来的,ruid为运行时id)的Blob类 * @fileOverview Blob */ define('lib/blob',[ 'base', 'runtime/client' ], function( Base, RuntimeClient ) { function Blob( ruid, source ) { var me = this; me.source = source; me.ruid = ruid; this.size = source.size || 0; // 如果没有指定 mimetype, 但是知道文件后缀。 if ( !source.type && this.ext && ~'jpg,jpeg,png,gif,bmp'.indexOf( this.ext ) ) { this.type = 'image/' + (this.ext === 'jpg' ? 'jpeg' : this.ext); } else { this.type = source.type || 'application/octet-stream'; } RuntimeClient.call( me, 'Blob' ); this.uid = source.uid || this.uid; if ( ruid ) { me.connectRuntime( ruid ); } } Base.inherits( RuntimeClient, { constructor: Blob, slice: function( start, end ) { return this.exec( 'slice', start, end ); }, getSource: function() { return this.source; } }); return Blob; }); /** * 带ruid的文件类,blob的子类 * 为了统一化Flash的File和HTML5的File而存在。 * 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。 * @fileOverview File */ define('lib/file',[ 'base', 'lib/blob' ], function( Base, Blob ) { var uid = 1, rExt = /\.([^.]+)$/; function File( ruid, file ) { var ext; this.name = file.name || ('untitled' + uid++); ext = rExt.exec( file.name ) ? RegExp.$1.toLowerCase() : ''; // todo 支持其他类型文件的转换。 // 如果有 mimetype, 但是文件名里面没有找出后缀规律 if ( !ext && file.type ) { ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec( file.type ) ? RegExp.$1.toLowerCase() : ''; this.name += '.' + ext; } this.ext = ext; this.lastModifiedDate = file.lastModifiedDate || (new Date()).toLocaleString(); Blob.apply( this, arguments ); } return Base.inherits( Blob, File ); }); /** * 文件选择器 * @fileOverview 错误信息 */ define('lib/filepicker',[ 'base', 'runtime/client', 'lib/file' ], function( Base, RuntimeClient, File ) { var $ = Base.$; function FilePicker( opts ) { opts = this.options = $.extend({}, FilePicker.options, opts ); opts.container = $( opts.id ); if ( !opts.container.length ) { throw new Error('按钮指定错误'); } opts.innerHTML = opts.innerHTML || opts.label || opts.container.html() || ''; opts.button = $( opts.button || document.createElement('div') ); opts.button.html( opts.innerHTML ); opts.container.html( opts.button ); RuntimeClient.call( this, 'FilePicker', true ); } FilePicker.options = { button: null, container: null, label: null, innerHTML: null, multiple: true, accept: null, name: 'file', style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick" }; Base.inherits( RuntimeClient, { constructor: FilePicker, init: function() { var me = this, opts = me.options, button = opts.button, style = opts.style; if (style) button.addClass('webuploader-pick'); me.on( 'all', function( type ) { var files; switch ( type ) { case 'mouseenter': if (style) button.addClass('webuploader-pick-hover'); break; case 'mouseleave': if (style) button.removeClass('webuploader-pick-hover'); break; case 'change': files = me.exec('getFiles'); me.trigger( 'select', $.map( files, function( file ) { file = new File( me.getRuid(), file ); // 记录来源。 file._refer = opts.container; return file; }), opts.container ); break; } }); me.connectRuntime( opts, function() { me.refresh(); me.exec( 'init', opts ); me.trigger('ready'); }); this._resizeHandler = Base.bindFn( this.refresh, this ); $( window ).on( 'resize', this._resizeHandler ); }, refresh: function() { var shimContainer = this.getRuntime().getContainer(), button = this.options.button, width = button.outerWidth ? button.outerWidth() : button.width(), height = button.outerHeight ? button.outerHeight() : button.height(), pos = button.offset(); width && height && shimContainer.css({ bottom: 'auto', right: 'auto', width: width + 'px', height: height + 'px' }).offset( pos ); }, enable: function() { var btn = this.options.button; btn.removeClass('webuploader-pick-disable'); this.refresh(); }, disable: function() { var btn = this.options.button; this.getRuntime().getContainer().css({ top: '-99999px' }); btn.addClass('webuploader-pick-disable'); }, destroy: function() { var btn = this.options.button; $( window ).off( 'resize', this._resizeHandler ); btn.removeClass('webuploader-pick-disable webuploader-pick-hover ' + 'webuploader-pick'); } }); return FilePicker; }); /** * 文件上传应用在Uploader * @fileOverview 文件选择相关 */ define('widgets/filepicker',[ 'base', 'uploader', 'lib/filepicker', 'widgets/widget' ], function( Base, Uploader, FilePicker ) { var $ = Base.$; $.extend( Uploader.options, { /** * @property {Selector | Object} [pick=undefined] * @namespace options * @for Uploader * @description 指定选择文件的按钮容器,不指定则不创建按钮。 * * * `id` {Seletor|dom} 指定选择文件的按钮容器,不指定则不创建按钮。**注意** 这里虽然写的是 id, 但是不是只支持 id, 还支持 class, 或者 dom 节点。 * * `label` {String} 请采用 `innerHTML` 代替 * * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。 * * `multiple` {Boolean} 是否开起同时选择多个文件能力。 */ pick: null, /** * @property {Arroy} [accept=null] * @namespace options * @for Uploader * @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。 * * * `title` {String} 文字描述 * * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。 * * `mimeTypes` {String} 多个用逗号分割。 * * 如: * * ``` * { * title: 'Images', * extensions: 'gif,jpg,jpeg,bmp,png', * mimeTypes: 'image/*' * } * ``` */ accept: null/*{ title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' }*/ }); return Uploader.register({ name: 'picker', init: function( opts ) { this.pickers = []; return opts.pick && this.addBtn( opts.pick ); }, refresh: function() { $.each( this.pickers, function() { this.refresh(); }); }, /** * @method addBtn * @for Uploader * @grammar addBtn( pick ) => Promise * @description * 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。 * @example * uploader.addBtn({ * id: '#btnContainer', * innerHTML: '选择文件' * }); */ addBtn: function( pick ) { var me = this, opts = me.options, accept = opts.accept, promises = []; if ( !pick ) { return; } $.isPlainObject( pick ) || (pick = { id: pick }); $( pick.id ).each(function() { var options, picker, deferred; deferred = Base.Deferred(); options = $.extend({}, pick, { accept: $.isPlainObject( accept ) ? [ accept ] : accept, swf: opts.swf, runtimeOrder: opts.runtimeOrder, id: this }); picker = new FilePicker( options ); picker.once( 'ready', deferred.resolve ); picker.on( 'select', function( files ) { me.owner.request( 'add-file', [ files ]); }); picker.on('dialogopen', function() { me.owner.trigger('dialogOpen', picker.button); }); picker.init(); me.pickers.push( picker ); promises.push( deferred.promise() ); }); return Base.when.apply( Base, promises ); }, disable: function() { $.each( this.pickers, function() { this.disable(); }); }, enable: function() { $.each( this.pickers, function() { this.enable(); }); }, destroy: function() { $.each( this.pickers, function() { this.destroy(); }); this.pickers = null; } }); }); /** * 图片处理类,生成缩略图和图片压缩 * @fileOverview Image */ define('lib/image',[ 'base', 'runtime/client', 'lib/blob' ], function( Base, RuntimeClient, Blob ) { var $ = Base.$; // 构造器。 function Image( opts ) { this.options = $.extend({}, Image.options, opts ); RuntimeClient.call( this, 'Image' ); this.on( 'load', function() { this._info = this.exec('info'); this._meta = this.exec('meta'); }); } // 默认选项。 Image.options = { // 默认的图片处理质量 quality: 90, // 是否裁剪 crop: false, // 是否保留头部信息 preserveHeaders: false, // 是否允许放大。 allowMagnify: false }; // 继承RuntimeClient. Base.inherits( RuntimeClient, { constructor: Image, info: function( val ) { // setter if ( val ) { this._info = val; return this; } // getter return this._info; }, meta: function( val ) { // setter if ( val ) { this._meta = val; return this; } // getter return this._meta; }, loadFromBlob: function( blob ) { var me = this, ruid = blob.getRuid(); this.connectRuntime( ruid, function() { me.exec( 'init', me.options ); me.exec( 'loadFromBlob', blob ); }); }, resize: function() { var args = Base.slice( arguments ); return this.exec.apply( this, [ 'resize' ].concat( args ) ); }, crop: function() { var args = Base.slice( arguments ); return this.exec.apply( this, [ 'crop' ].concat( args ) ); }, getAsDataUrl: function( type ) { return this.exec( 'getAsDataUrl', type ); }, getAsBlob: function( type ) { var blob = this.exec( 'getAsBlob', type ); return new Blob( this.getRuid(), blob ); } }); return Image; }); /** * 图片文件在对应的时机做图片压缩和预览 * @fileOverview 图片操作, 负责预览图片和上传前压缩图片 */ define('widgets/image',[ 'base', 'uploader', 'lib/image', 'widgets/widget' ], function( Base, Uploader, Image ) { var $ = Base.$, throttle; // 根据要处理的文件大小来节流,一次不能处理太多,会卡。 throttle = (function( max ) { var occupied = 0, waiting = [], tick = function() { var item; while ( waiting.length && occupied < max ) { item = waiting.shift(); occupied += item[ 0 ]; item[ 1 ](); } }; return function( emiter, size, cb ) { waiting.push([ size, cb ]); emiter.once( 'destroy', function() { occupied -= size; setTimeout( tick, 1 ); }); setTimeout( tick, 1 ); }; })( 5 * 1024 * 1024 ); $.extend( Uploader.options, { /** * @property {Object} [thumb] * @namespace options * @for Uploader * @description 配置生成缩略图的选项。 * * 默认为: * * ```javascript * { * width: 110, * height: 110, * * // 图片质量,只有type为`image/jpeg`的时候才有效。 * quality: 70, * * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. * allowMagnify: true, * * // 是否允许裁剪。 * crop: true, * * // 为空的话则保留原有图片格式。 * // 否则强制转换成指定的类型。 * type: 'image/jpeg' * } * ``` */ thumb: { width: 110, height: 110, quality: 70, allowMagnify: true, crop: true, preserveHeaders: false, // 为空的话则保留原有图片格式。 // 否则强制转换成指定的类型。 // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可 // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg type: 'image/jpeg' }, /** * @property {Object} [compress] * @namespace options * @for Uploader * @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。 * * 默认为: * * ```javascript * { * width: 1600, * height: 1600, * * // 图片质量,只有type为`image/jpeg`的时候才有效。 * quality: 90, * * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. * allowMagnify: false, * * // 是否允许裁剪。 * crop: false, * * // 是否保留头部meta信息。 * preserveHeaders: true, * * // 如果发现压缩后文件大小比原来还大,则使用原来图片 * // 此属性可能会影响图片自动纠正功能 * noCompressIfLarger: false, * * // 单位字节,如果图片大小小于此值,不会采用压缩。 * compressSize: 0 * } * ``` */ compress: { width: 1600, height: 1600, quality: 90, allowMagnify: false, crop: false, preserveHeaders: true } }); return Uploader.register({ name: 'image', /** * 生成缩略图,此过程为异步,所以需要传入`callback`。 * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。 * * 当 width 或者 height 的值介于 0 - 1 时,被当成百分比使用。 * * `callback`中可以接收到两个参数。 * * 第一个为error,如果生成缩略图有错误,此error将为真。 * * 第二个为ret, 缩略图的Data URL值。 * * **注意** * Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。 * 也可以借助服务端,将 base64 数据传给服务端,生成一个临时文件供预览。 * * @method makeThumb * @grammar makeThumb( file, callback ) => undefined * @grammar makeThumb( file, callback, width, height ) => undefined * @for Uploader * @example * * uploader.on( 'fileQueued', function( file ) { * var $li = ...; * * uploader.makeThumb( file, function( error, ret ) { * if ( error ) { * $li.text('预览错误'); * } else { * $li.append('<img alt="" src="' + ret + '" />'); * } * }); * * }); */ makeThumb: function( file, cb, width, height ) { var opts, image; file = this.request( 'get-file', file ); // 只预览图片格式。 if ( !file.type.match( /^image/ ) ) { cb( true ); return; } opts = $.extend({}, this.options.thumb ); // 如果传入的是object. if ( $.isPlainObject( width ) ) { opts = $.extend( opts, width ); width = null; } width = width || opts.width; height = height || opts.height; image = new Image( opts ); image.once( 'load', function() { file._info = file._info || image.info(); file._meta = file._meta || image.meta(); // 如果 width 的值介于 0 - 1 // 说明设置的是百分比。 if ( width <= 1 && width > 0 ) { width = file._info.width * width; } // 同样的规则应用于 height if ( height <= 1 && height > 0 ) { height = file._info.height * height; } image.resize( width, height ); }); // 当 resize 完后 image.once( 'complete', function() { cb( false, image.getAsDataUrl( opts.type ) ); image.destroy(); }); image.once( 'error', function( reason ) { cb( reason || true ); image.destroy(); }); throttle( image, file.source.size, function() { file._info && image.info( file._info ); file._meta && image.meta( file._meta ); image.loadFromBlob( file.source ); }); }, beforeSendFile: function( file ) { var opts = this.options.compress || this.options.resize, compressSize = opts && opts.compressSize || 0, noCompressIfLarger = opts && opts.noCompressIfLarger || false, image, deferred; file = this.request( 'get-file', file ); // 只压缩 jpeg 图片格式。 // gif 可能会丢失针 // bmp png 基本上尺寸都不大,且压缩比比较小。 if ( !opts || !~'image/jpeg,image/jpg'.indexOf( file.type ) || file.size < compressSize || file._compressed ) { return; } opts = $.extend({}, opts ); deferred = Base.Deferred(); image = new Image( opts ); deferred.always(function() { image.destroy(); image = null; }); image.once( 'error', deferred.reject ); image.once( 'load', function() { var width = opts.width, height = opts.height; file._info = file._info || image.info(); file._meta = file._meta || image.meta(); // 如果 width 的值介于 0 - 1 // 说明设置的是百分比。 if ( width <= 1 && width > 0 ) { width = file._info.width * width; } // 同样的规则应用于 height if ( height <= 1 && height > 0 ) { height = file._info.height * height; } image.resize( width, height ); }); image.once( 'complete', function() { var blob, size; // 移动端 UC / qq 浏览器的无图模式下 // ctx.getImageData 处理大图的时候会报 Exception // INDEX_SIZE_ERR: DOM Exception 1 try { blob = image.getAsBlob( opts.type ); size = file.size; // 如果压缩后,比原来还大则不用压缩后的。 if ( !noCompressIfLarger || blob.size < size ) { // file.source.destroy && file.source.destroy(); file.source = blob; file.size = blob.size; file.trigger( 'resize', blob.size, size ); } // 标记,避免重复压缩。 file._compressed = true; deferred.resolve(); } catch ( e ) { // 出错了直接继续,让其上传原始图片 deferred.resolve(); } }); file._info && image.info( file._info ); file._meta && image.meta( file._meta ); image.loadFromBlob( file.source ); return deferred.promise(); } }); }); /** * 文件类,Queue中存放的数据类 * @fileOverview 文件属性封装 */ define('file',[ 'base', 'mediator' ], function( Base, Mediator ) { var $ = Base.$, idPrefix = 'WU_FILE_', idSuffix = 0, rExt = /\.([^.]+)$/, statusMap = {}; function gid() { return idPrefix + idSuffix++; } /** * 文件类 * @class File * @constructor 构造函数 * @grammar new File( source ) => File * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。 */ function WUFile( source ) { /** * 文件名,包括扩展名(后缀) * @property name * @type {string} */ this.name = source.name || 'Untitled'; /** * 文件体积(字节) * @property size * @type {uint} * @default 0 */ this.size = source.size || 0; /** * 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny) * @property type * @type {string} * @default 'application/octet-stream' */ this.type = source.type || 'application/octet-stream'; /** * 文件最后修改日期 * @property lastModifiedDate * @type {int} * @default 当前时间戳 */ this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1); /** * 文件ID,每个对象具有唯一ID,与文件名无关 * @property id * @type {string} */ this.id = gid(); /** * 文件扩展名,通过文件名获取,例如test.png的扩展名为png * @property ext * @type {string} */ this.ext = rExt.exec( this.name ) ? RegExp.$1 : ''; /** * 状态文字说明。在不同的status语境下有不同的用途。 * @property statusText * @type {string} */ this.statusText = ''; // 存储文件状态,防止通过属性直接修改 statusMap[ this.id ] = WUFile.Status.INITED; this.source = source; this.loaded = 0; this.on( 'error', function( msg ) { this.setStatus( WUFile.Status.ERROR, msg ); }); } $.extend( WUFile.prototype, { /** * 设置状态,状态变化时会触发`change`事件。 * @method setStatus * @grammar setStatus( status[, statusText] ); * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status) * @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。 */ setStatus: function( status, text ) { var prevStatus = statusMap[ this.id ]; typeof text !== 'undefined' && (this.statusText = text); if ( status !== prevStatus ) { statusMap[ this.id ] = status; /** * 文件状态变化 * @event statuschange */ this.trigger( 'statuschange', status, prevStatus ); } }, /** * 获取文件状态 * @return {File.Status} * @example 文件状态具体包括以下几种类型: { // 初始化 INITED: 0, // 已入队列 QUEUED: 1, // 正在上传 PROGRESS: 2, // 上传出错 ERROR: 3, // 上传成功 COMPLETE: 4, // 上传取消 CANCELLED: 5 } */ getStatus: function() { return statusMap[ this.id ]; }, /** * 获取文件原始信息。 * @return {*} */ getSource: function() { return this.source; }, destroy: function() { this.off(); delete statusMap[ this.id ]; } }); Mediator.installTo( WUFile.prototype ); /** * 文件状态值,具体包括以下几种类型: * * `inited` 初始状态 * * `queued` 已经进入队列, 等待上传 * * `progress` 上传中 * * `complete` 上传完成。 * * `error` 上传出错,可重试 * * `interrupt` 上传中断,可续传。 * * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。 * * `cancelled` 文件被移除。 * @property {Object} Status * @namespace File * @class File * @static */ WUFile.Status = { INITED: 'inited', // 初始状态 QUEUED: 'queued', // 已经进入队列, 等待上传 PROGRESS: 'progress', // 上传中 ERROR: 'error', // 上传出错,可重试 COMPLETE: 'complete', // 上传完成。 CANCELLED: 'cancelled', // 上传取消。 INTERRUPT: 'interrupt', // 上传中断,可续传。 INVALID: 'invalid' // 文件不合格,不能重试上传。 }; return WUFile; }); /** * @fileOverview 文件队列 */ define('queue',[ 'base', 'mediator', 'file' ], function (Base, Mediator, WUFile) { var $ = Base.$, STATUS = WUFile.Status; /** * 文件队列, 用来存储各个状态中的文件。 * @class Queue * @extends Mediator */ function Queue() { /** * 统计文件数。 * * `numOfQueue` 队列中的文件数。 * * `numOfSuccess` 上传成功的文件数 * * `numOfCancel` 被取消的文件数 * * `numOfProgress` 正在上传中的文件数 * * `numOfUploadFailed` 上传错误的文件数。 * * `numOfInvalid` 无效的文件数。 * * `numofDeleted` 被移除的文件数。 * @property {Object} stats */ this.stats = { numOfQueue: 0, numOfSuccess: 0, numOfCancel: 0, numOfProgress: 0, numOfUploadFailed: 0, numOfInvalid: 0, numofDeleted: 0, numofInterrupt: 0 }; // 上传队列,仅包括等待上传的文件 this._queue = []; // 存储所有文件 this._map = {}; } $.extend(Queue.prototype, { /** * 将新文件加入对队列尾部 * * @method append * @param {File} file 文件对象 */ append: function (file) { this._queue.push(file); this._fileAdded(file); return this; }, /** * 将新文件加入对队列头部 * * @method prepend * @param {File} file 文件对象 */ prepend: function (file) { this._queue.unshift(file); this._fileAdded(file); return this; }, /** * 获取文件对象 * * @method getFile * @param {String} fileId 文件ID * @return {File} */ getFile: function (fileId) { if (typeof fileId !== 'string') { return fileId; } return this._map[fileId]; }, /** * 从队列中取出一个指定状态的文件。 * @grammar fetch( status ) => File * @method fetch * @param {String} status [文件状态值](#WebUploader:File:File.Status) * @return {File} [File](#WebUploader:File) */ fetch: function (status) { var len = this._queue.length, i, file; status = status || STATUS.QUEUED; for (i = 0; i < len; i++) { file = this._queue[i]; if (status === file.getStatus()) { return file; } } return null; }, /** * 对队列进行排序,能够控制文件上传顺序。 * @grammar sort( fn ) => undefined * @method sort * @param {Function} fn 排序方法 */ sort: function (fn) { if (typeof fn === 'function') { this._queue.sort(fn); } }, /** * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。 * @grammar getFiles( [status1[, status2 ...]] ) => Array * @method getFiles * @param {String} [status] [文件状态值](#WebUploader:File:File.Status) */ getFiles: function () { var sts = [].slice.call(arguments, 0), ret = [], i = 0, len = this._queue.length, file; for (; i < len; i++) { file = this._queue[i]; if (sts.length && !~$.inArray(file.getStatus(), sts)) { continue; } ret.push(file); } return ret; }, /** * 在队列中删除文件。 * @grammar removeFile( file ) => Array * @method removeFile * @param {File} 文件对象。 */ removeFile: function (file) { var me = this, existing = this._map[file.id]; if (existing) { delete this._map[file.id]; this._delFile(file); file.destroy(); this.stats.numofDeleted++; } }, _fileAdded: function (file) { var me = this, existing = this._map[file.id]; if (!existing) { this._map[file.id] = file; file.on('statuschange', function (cur, pre) { me._onFileStatusChange(cur, pre); }); } }, _delFile: function (file) { for (var i = this._queue.length - 1; i >= 0; i--) { if (this._queue[i] == file) { this._queue.splice(i, 1); break; } } }, _onFileStatusChange: function (curStatus, preStatus) { var stats = this.stats; switch (preStatus) { case STATUS.PROGRESS: stats.numOfProgress--; break; case STATUS.QUEUED: stats.numOfQueue--; break; case STATUS.ERROR: stats.numOfUploadFailed--; break; case STATUS.INVALID: stats.numOfInvalid--; break; case STATUS.INTERRUPT: stats.numofInterrupt--; break; } switch (curStatus) { case STATUS.QUEUED: stats.numOfQueue++; break; case STATUS.PROGRESS: stats.numOfProgress++; break; case STATUS.ERROR: stats.numOfUploadFailed++; break; case STATUS.COMPLETE: stats.numOfSuccess++; break; case STATUS.CANCELLED: stats.numOfCancel++; break; case STATUS.INVALID: stats.numOfInvalid++; break; case STATUS.INTERRUPT: stats.numofInterrupt++; break; } } }); Mediator.installTo(Queue.prototype); return Queue; }); /** * 队列管理 * @fileOverview 队列 */ define('widgets/queue',[ 'base', 'uploader', 'queue', 'file', 'lib/file', 'runtime/client', 'widgets/widget' ], function( Base, Uploader, Queue, WUFile, File, RuntimeClient ) { var $ = Base.$, rExt = /\.\w+$/, Status = WUFile.Status; return Uploader.register({ name: 'queue', init: function( opts ) { var me = this, deferred, len, i, item, arr, accept, runtime; if ( $.isPlainObject( opts.accept ) ) { opts.accept = [ opts.accept ]; } // accept中的中生成匹配正则。 if ( opts.accept ) { arr = []; for ( i = 0, len = opts.accept.length; i < len; i++ ) { item = opts.accept[ i ].extensions; item && arr.push( item ); } if ( arr.length ) { accept = '\\.' + arr.join(',') .replace( /,/g, '$|\\.' ) .replace( /\*/g, '.*' ) + '$'; } me.accept = new RegExp( accept, 'i' ); } me.queue = new Queue(); me.stats = me.queue.stats; // 如果当前不是html5运行时,那就算了。 // 不执行后续操作 if ( this.request('predict-runtime-type') !== 'html5' ) { return; } // 创建一个 html5 运行时的 placeholder // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。 deferred = Base.Deferred(); this.placeholder = runtime = new RuntimeClient('Placeholder'); runtime.connectRuntime({ runtimeOrder: 'html5' }, function() { me._ruid = runtime.getRuid(); deferred.resolve(); }); return deferred.promise(); }, // 为了支持外部直接添加一个原生File对象。 _wrapFile: function( file ) { if ( !(file instanceof WUFile) ) { if ( !(file instanceof File) ) { if ( !this._ruid ) { throw new Error('Can\'t add external files.'); } file = new File( this._ruid, file ); } file = new WUFile( file ); } return file; }, // 判断文件是否可以被加入队列 acceptFile: function( file ) { var invalid = !file || !file.size || this.accept && // 如果名字中有后缀,才做后缀白名单处理。 rExt.exec( file.name ) && !this.accept.test( file.name ); return !invalid; }, /** * @event beforeFileQueued * @param {File} file File对象 * @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。 * @for Uploader */ /** * @event fileQueued * @param {File} file File对象 * @description 当文件被加入队列以后触发。 * @for Uploader */ _addFile: function( file ) { var me = this; file = me._wrapFile( file ); // 不过类型判断允许不允许,先派送 `beforeFileQueued` if ( !me.owner.trigger( 'beforeFileQueued', file ) ) { return; } // 类型不匹配,则派送错误事件,并返回。 if ( !me.acceptFile( file ) ) { me.owner.trigger( 'error', 'Q_TYPE_DENIED', file ); return; } me.queue.append( file ); me.owner.trigger( 'fileQueued', file ); return file; }, getFile: function( fileId ) { return this.queue.getFile( fileId ); }, /** * @event filesQueued * @param {File} files 数组,内容为原始File(lib/File)对象。 * @description 当一批文件添加进队列以后触发。 * @for Uploader */ /** * @property {Boolean} [auto=false] * @namespace options * @for Uploader * @description 设置为 true 后,不需要手动调用上传,有文件选择即开始上传。 * */ /** * @method addFiles * @grammar addFiles( file ) => undefined * @grammar addFiles( [file1, file2 ...] ) => undefined * @param {Array of File or File} [files] Files 对象 数组 * @description 添加文件到队列 * @for Uploader */ addFile: function( files ) { var me = this; if ( !files.length ) { files = [ files ]; } files = $.map( files, function( file ) { return me._addFile( file ); }); if ( files.length ) { me.owner.trigger( 'filesQueued', files ); if ( me.options.auto ) { setTimeout(function() { me.request('start-upload'); }, 20 ); } } }, getStats: function() { return this.stats; }, /** * @event fileDequeued * @param {File} file File对象 * @description 当文件被移除队列后触发。 * @for Uploader */ /** * @method removeFile * @grammar removeFile( file ) => undefined * @grammar removeFile( id ) => undefined * @grammar removeFile( file, true ) => undefined * @grammar removeFile( id, true ) => undefined * @param {File|id} file File对象或这File对象的id * @description 移除某一文件, 默认只会标记文件状态为已取消,如果第二个参数为 `true` 则会从 queue 中移除。 * @for Uploader * @example * * $li.on('click', '.remove-this', function() { * uploader.removeFile( file ); * }) */ removeFile: function( file, remove ) { var me = this; file = file.id ? file : me.queue.getFile( file ); this.request( 'cancel-file', file ); if ( remove ) { this.queue.removeFile( file ); } }, /** * @method getFiles * @grammar getFiles() => Array * @grammar getFiles( status1, status2, status... ) => Array * @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。 * @for Uploader * @example * console.log( uploader.getFiles() ); // => all files * console.log( uploader.getFiles('error') ) // => all error files. */ getFiles: function() { return this.queue.getFiles.apply( this.queue, arguments ); }, fetchFile: function() { return this.queue.fetch.apply( this.queue, arguments ); }, /** * @method retry * @grammar retry() => undefined * @grammar retry( file ) => undefined * @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。 * @for Uploader * @example * function retry() { * uploader.retry(); * } */ retry: function( file, noForceStart ) { var me = this, files, i, len; if ( file ) { file = file.id ? file : me.queue.getFile( file ); file.setStatus( Status.QUEUED ); noForceStart || me.request('start-upload'); return; } files = me.queue.getFiles( Status.ERROR ); i = 0; len = files.length; for ( ; i < len; i++ ) { file = files[ i ]; file.setStatus( Status.QUEUED ); } me.request('start-upload'); }, /** * @method sort * @grammar sort( fn ) => undefined * @description 排序队列中的文件,在上传之前调整可以控制上传顺序。 * @for Uploader */ sortFiles: function() { return this.queue.sort.apply( this.queue, arguments ); }, /** * @event reset * @description 当 uploader 被重置的时候触发。 * @for Uploader */ /** * @method reset * @grammar reset() => undefined * @description 重置uploader。目前只重置了队列。 * @for Uploader * @example * uploader.reset(); */ reset: function() { this.owner.trigger('reset'); this.queue = new Queue(); this.stats = this.queue.stats; }, destroy: function() { this.reset(); this.placeholder && this.placeholder.destroy(); } }); }); /** * 添加runtime信息给Uploader * @fileOverview 添加获取Runtime相关信息的方法。 */ define('widgets/runtime',[ 'uploader', 'runtime/runtime', 'widgets/widget' ], function( Uploader, Runtime ) { Uploader.support = function() { return Runtime.hasRuntime.apply( Runtime, arguments ); }; /** * @property {Object} [runtimeOrder=html5,flash] * @namespace options * @for Uploader * @description 指定运行时启动顺序。默认会想尝试 html5 是否支持,如果支持则使用 html5, 否则则使用 flash. * * 可以将此值设置成 `flash`,来强制使用 flash 运行时。 */ return Uploader.register({ name: 'runtime', init: function() { if ( !this.predictRuntimeType() ) { throw Error('Runtime Error'); } }, /** * 预测Uploader将采用哪个`Runtime` * @grammar predictRuntimeType() => String * @method predictRuntimeType * @for Uploader */ predictRuntimeType: function() { var orders = this.options.runtimeOrder || Runtime.orders, type = this.type, i, len; if ( !type ) { orders = orders.split( /\s*,\s*/g ); for ( i = 0, len = orders.length; i < len; i++ ) { if ( Runtime.hasRuntime( orders[ i ] ) ) { this.type = type = orders[ i ]; break; } } } return type; } }); }); /** * * 文件传送 * @fileOverview Transport */ define('lib/transport',[ 'base', 'runtime/client', 'mediator' ], function( Base, RuntimeClient, Mediator ) { var $ = Base.$; function Transport( opts ) { var me = this; opts = me.options = $.extend( true, {}, Transport.options, opts || {} ); RuntimeClient.call( this, 'Transport' ); this._blob = null; this._formData = opts.formData || {}; this._headers = opts.headers || {}; this.on( 'progress', this._timeout ); this.on( 'load error', function() { me.trigger( 'progress', 1 ); clearTimeout( me._timer ); }); } Transport.options = { server: '', method: 'POST', // 跨域时,是否允许携带cookie, 只有html5 runtime才有效 withCredentials: false, fileVal: 'file', timeout: 2 * 60 * 1000, // 2分钟 formData: {}, headers: {}, sendAsBinary: false }; $.extend( Transport.prototype, { // 添加Blob, 只能添加一次,最后一次有效。 appendBlob: function( key, blob, filename ) { var me = this, opts = me.options; if ( me.getRuid() ) { me.disconnectRuntime(); } // 连接到blob归属的同一个runtime. me.connectRuntime( blob.ruid, function() { me.exec('init'); }); me._blob = blob; opts.fileVal = key || opts.fileVal; opts.filename = filename || opts.filename; }, // 添加其他字段 append: function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._formData, key ); } else { this._formData[ key ] = value; } }, setRequestHeader: function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._headers, key ); } else { this._headers[ key ] = value; } }, send: function( method ) { this.exec( 'send', method ); this._timeout(); }, abort: function() { clearTimeout( this._timer ); return this.exec('abort'); }, destroy: function() { this.trigger('destroy'); this.off(); this.exec('destroy'); this.disconnectRuntime(); }, getResponse: function() { return this.exec('getResponse'); }, getResponseAsJson: function() { return this.exec('getResponseAsJson'); }, getStatus: function() { return this.exec('getStatus'); }, _timeout: function() { var me = this, duration = me.options.timeout; if ( !duration ) { return; } clearTimeout( me._timer ); me._timer = setTimeout(function() { me.abort(); me.trigger( 'error', 'timeout' ); }, duration ); } }); // 让Transport具备事件功能。 Mediator.installTo( Transport.prototype ); return Transport; }); /** * 负责具体的上传逻辑哦 * @fileOverview 负责文件上传相关。 */ define('widgets/upload',[ 'base', 'uploader', 'file', 'lib/transport', 'widgets/widget' ], function( Base, Uploader, WUFile, Transport ) { var $ = Base.$, isPromise = Base.isPromise, Status = WUFile.Status; // 添加默认配置项 $.extend( Uploader.options, { /** * @property {Boolean} [prepareNextFile=false] * @namespace options * @for Uploader * @description 是否允许在文件传输时提前把下一个文件准备好。 * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。 * 如果能提前在当前文件传输期处理,可以节省总体耗时。 */ prepareNextFile: false, /** * @property {Boolean} [chunked=false] * @namespace options * @for Uploader * @description 是否要分片处理大文件上传。 */ chunked: false, /** * @property {Boolean} [chunkSize=5242880] * @namespace options * @for Uploader * @description 如果要分片,分多大一片? 默认大小为5M. */ chunkSize: 5 * 1024 * 1024, /** * @property {Boolean} [chunkRetry=2] * @namespace options * @for Uploader * @description 如果某个分片由于网络问题出错,允许自动重传多少次? */ chunkRetry: 2, /** * @property {Boolean} [threads=3] * @namespace options * @for Uploader * @description 上传并发数。允许同时最大上传进程数。 */ threads: 3, /** * @property {Object} [formData={}] * @namespace options * @for Uploader * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。 */ formData: {} /** * @property {Object} [fileVal='file'] * @namespace options * @for Uploader * @description 设置文件上传域的name。 */ /** * @property {Object} [sendAsBinary=false] * @namespace options * @for Uploader * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容, * 其他参数在$_GET数组中。 */ }); // 负责将文件切片。 function CuteFile( file, chunkSize ) { var pending = [], blob = file.source, total = blob.size, chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1, start = 0, index = 0, len, api; api = { file: file, has: function() { return !!pending.length; }, shift: function() { return pending.shift(); }, unshift: function( block ) { pending.unshift( block ); } }; while ( index < chunks ) { len = Math.min( chunkSize, total - start ); pending.push({ file: file, start: start, end: chunkSize ? (start + len) : total, total: total, chunks: chunks, chunk: index++, cuted: api }); start += len; } file.blocks = pending.concat(); file.remaning = pending.length; return api; } Uploader.register({ name: 'upload', init: function() { var owner = this.owner, me = this; this.runing = false; this.progress = false; owner .on( 'startUpload', function() { me.progress = true; }) .on( 'uploadFinished', function() { me.progress = false; }); // 记录当前正在传的数据,跟threads相关 this.pool = []; // 缓存分好片的文件。 this.stack = []; // 缓存即将上传的文件。 this.pending = []; // 跟踪还有多少分片在上传中但是没有完成上传。 this.remaning = 0; this.__tick = Base.bindFn( this._tick, this ); // 销毁上传相关的属性。 owner.on( 'uploadComplete', function( file ) { // 把其他块取消了。 file.blocks && $.each( file.blocks, function( _, v ) { v.transport && (v.transport.abort(), v.transport.destroy()); delete v.transport; }); delete file.blocks; delete file.remaning; }); }, reset: function() { this.request( 'stop-upload', true ); this.runing = false; this.pool = []; this.stack = []; this.pending = []; this.remaning = 0; this._trigged = false; this._promise = null; }, /** * @event startUpload * @description 当开始上传流程时触发。 * @for Uploader */ /** * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。 * * 可以指定开始某一个文件。 * @grammar upload() => undefined * @grammar upload( file | fileId) => undefined * @method upload * @for Uploader */ startUpload: function(file) { var me = this; // 移出invalid的文件 $.each( me.request( 'get-files', Status.INVALID ), function() { me.request( 'remove-file', this ); }); // 如果指定了开始某个文件,则只开始指定的文件。 if ( file ) { file = file.id ? file : me.request( 'get-file', file ); if (file.getStatus() === Status.INTERRUPT) { file.setStatus( Status.QUEUED ); $.each( me.pool, function( _, v ) { // 之前暂停过。 if (v.file !== file) { return; } v.transport && v.transport.send(); file.setStatus( Status.PROGRESS ); }); } else if (file.getStatus() !== Status.PROGRESS) { file.setStatus( Status.QUEUED ); } } else { $.each( me.request( 'get-files', [ Status.INITED ] ), function() { this.setStatus( Status.QUEUED ); }); } if ( me.runing ) { me.owner.trigger('startUpload', file);// 开始上传或暂停恢复的,trigger event return Base.nextTick( me.__tick ); } me.runing = true; var files = []; // 如果有暂停的,则续传 file || $.each( me.pool, function( _, v ) { var file = v.file; if ( file.getStatus() === Status.INTERRUPT ) { me._trigged = false; files.push(file); v.transport && v.transport.send(); } }); $.each(files, function() { this.setStatus( Status.PROGRESS ); }); file || $.each( me.request( 'get-files', Status.INTERRUPT ), function() { this.setStatus( Status.PROGRESS ); }); me._trigged = false; Base.nextTick( me.__tick ); me.owner.trigger('startUpload'); }, /** * @event stopUpload * @description 当开始上传流程暂停时触发。 * @for Uploader */ /** * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。 * * 如果第一个参数是文件,则只暂停指定文件。 * @grammar stop() => undefined * @grammar stop( true ) => undefined * @grammar stop( file ) => undefined * @method stop * @for Uploader */ stopUpload: function( file, interrupt ) { var me = this; if (file === true) { interrupt = file; file = null; } if ( me.runing === false ) { return; } // 如果只是暂停某个文件。 if ( file ) { file = file.id ? file : me.request( 'get-file', file ); if ( file.getStatus() !== Status.PROGRESS && file.getStatus() !== Status.QUEUED ) { return; } file.setStatus( Status.INTERRUPT ); $.each( me.pool, function( _, v ) { // 只 abort 指定的文件,每一个分片。 if (v.file === file) { v.transport && v.transport.abort(); if (interrupt) { me._putback(v); me._popBlock(v); } } }); me.owner.trigger('stopUpload', file);// 暂停,trigger event return Base.nextTick( me.__tick ); } me.runing = false; // 正在准备中的文件。 if (this._promise && this._promise.file) { this._promise.file.setStatus( Status.INTERRUPT ); } interrupt && $.each( me.pool, function( _, v ) { v.transport && v.transport.abort(); v.file.setStatus( Status.INTERRUPT ); }); me.owner.trigger('stopUpload'); }, /** * @method cancelFile * @grammar cancelFile( file ) => undefined * @grammar cancelFile( id ) => undefined * @param {File|id} file File对象或这File对象的id * @description 标记文件状态为已取消, 同时将中断文件传输。 * @for Uploader * @example * * $li.on('click', '.remove-this', function() { * uploader.cancelFile( file ); * }) */ cancelFile: function( file ) { file = file.id ? file : this.request( 'get-file', file ); // 如果正在上传。 file.blocks && $.each( file.blocks, function( _, v ) { var _tr = v.transport; if ( _tr ) { _tr.abort(); _tr.destroy(); delete v.transport; } }); file.setStatus( Status.CANCELLED ); this.owner.trigger( 'fileDequeued', file ); }, /** * 判断`Uplaode`r是否正在上传中。 * @grammar isInProgress() => Boolean * @method isInProgress * @for Uploader */ isInProgress: function() { return !!this.progress; }, _getStats: function() { return this.request('get-stats'); }, /** * 掉过一个文件上传,直接标记指定文件为已上传状态。 * @grammar skipFile( file ) => undefined * @method skipFile * @for Uploader */ skipFile: function( file, status ) { file = file.id ? file : this.request( 'get-file', file ); file.setStatus( status || Status.COMPLETE ); file.skipped = true; // 如果正在上传。 file.blocks && $.each( file.blocks, function( _, v ) { var _tr = v.transport; if ( _tr ) { _tr.abort(); _tr.destroy(); delete v.transport; } }); this.owner.trigger( 'uploadSkip', file ); }, /** * @event uploadFinished * @description 当所有文件上传结束时触发。 * @for Uploader */ _tick: function() { var me = this, opts = me.options, fn, val; // 上一个promise还没有结束,则等待完成后再执行。 if ( me._promise ) { return me._promise.always( me.__tick ); } // 还有位置,且还有文件要处理的话。 if ( me.pool.length < opts.threads && (val = me._nextBlock()) ) { me._trigged = false; fn = function( val ) { me._promise = null; // 有可能是reject过来的,所以要检测val的类型。 val && val.file && me._startSend( val ); Base.nextTick( me.__tick ); }; me._promise = isPromise( val ) ? val.always( fn ) : fn( val ); // 没有要上传的了,且没有正在传输的了。 } else if ( !me.remaning && !me._getStats().numOfQueue && !me._getStats().numofInterrupt ) { me.runing = false; me._trigged || Base.nextTick(function() { me.owner.trigger('uploadFinished'); }); me._trigged = true; } }, _putback: function(block) { var idx; block.cuted.unshift(block); idx = this.stack.indexOf(block.cuted); if (!~idx) { this.stack.unshift(block.cuted); } }, _getStack: function() { var i = 0, act; while ( (act = this.stack[ i++ ]) ) { if ( act.has() && act.file.getStatus() === Status.PROGRESS ) { return act; } else if (!act.has() || act.file.getStatus() !== Status.PROGRESS && act.file.getStatus() !== Status.INTERRUPT ) { // 把已经处理完了的,或者,状态为非 progress(上传中)、 // interupt(暂停中) 的移除。 this.stack.splice( --i, 1 ); } } return null; }, _nextBlock: function() { var me = this, opts = me.options, act, next, done, preparing; // 如果当前文件还有没有需要传输的,则直接返回剩下的。 if ( (act = this._getStack()) ) { // 是否提前准备下一个文件 if ( opts.prepareNextFile && !me.pending.length ) { me._prepareNextFile(); } return act.shift(); // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。 } else if ( me.runing ) { // 如果缓存中有,则直接在缓存中取,没有则去queue中取。 if ( !me.pending.length && me._getStats().numOfQueue ) { me._prepareNextFile(); } next = me.pending.shift(); done = function( file ) { if ( !file ) { return null; } act = CuteFile( file, opts.chunked ? opts.chunkSize : 0 ); me.stack.push(act); return act.shift(); }; // 文件可能还在prepare中,也有可能已经完全准备好了。 if ( isPromise( next) ) { preparing = next.file; next = next[ next.pipe ? 'pipe' : 'then' ]( done ); next.file = preparing; return next; } return done( next ); } }, /** * @event uploadStart * @param {File} file File对象 * @description 某个文件开始上传前触发,一个文件只会触发一次。 * @for Uploader */ _prepareNextFile: function() { var me = this, file = me.request('fetch-file'), pending = me.pending, promise; if ( file ) { promise = me.request( 'before-send-file', file, function() { // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued. if ( file.getStatus() === Status.PROGRESS || file.getStatus() === Status.INTERRUPT ) { return file; } return me._finishFile( file ); }); me.owner.trigger( 'uploadStart', file ); file.setStatus( Status.PROGRESS ); promise.file = file; // 如果还在pending中,则替换成文件本身。 promise.done(function() { var idx = $.inArray( promise, pending ); ~idx && pending.splice( idx, 1, file ); }); // befeore-send-file的钩子就有错误发生。 promise.fail(function( reason ) { file.setStatus( Status.ERROR, reason ); me.owner.trigger( 'uploadError', file, reason ); me.owner.trigger( 'uploadComplete', file ); }); pending.push( promise ); } }, // 让出位置了,可以让其他分片开始上传 _popBlock: function( block ) { var idx = $.inArray( block, this.pool ); this.pool.splice( idx, 1 ); block.file.remaning--; this.remaning--; }, // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。 _startSend: function( block ) { var me = this, file = block.file, promise; // 有可能在 before-send-file 的 promise 期间改变了文件状态。 // 如:暂停,取消 // 我们不能中断 promise, 但是可以在 promise 完后,不做上传操作。 if ( file.getStatus() !== Status.PROGRESS ) { // 如果是中断,则还需要放回去。 if (file.getStatus() === Status.INTERRUPT) { me._putback(block); } return; } me.pool.push( block ); me.remaning++; // 如果没有分片,则直接使用原始的。 // 不会丢失content-type信息。 block.blob = block.chunks === 1 ? file.source : file.source.slice( block.start, block.end ); // hook, 每个分片发送之前可能要做些异步的事情。 promise = me.request( 'before-send', block, function() { // 有可能文件已经上传出错了,所以不需要再传输了。 if ( file.getStatus() === Status.PROGRESS ) { me._doSend( block ); } else { me._popBlock( block ); Base.nextTick( me.__tick ); } }); // 如果为fail了,则跳过此分片。 promise.fail(function() { if ( file.remaning === 1 ) { me._finishFile( file ).always(function() { block.percentage = 1; me._popBlock( block ); me.owner.trigger( 'uploadComplete', file ); Base.nextTick( me.__tick ); }); } else { block.percentage = 1; me.updateFileProgress( file ); me._popBlock( block ); Base.nextTick( me.__tick ); } }); }, /** * @event uploadBeforeSend * @param {Object} object * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。 * @param {Object} headers 可以扩展此对象来控制上传头部。 * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。 * @for Uploader */ /** * @event uploadAccept * @param {Object} object * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。 * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。 * @for Uploader */ /** * @event uploadProgress * @param {File} file File对象 * @param {Number} percentage 上传进度 * @description 上传过程中触发,携带上传进度。 * @for Uploader */ /** * @event uploadError * @param {File} file File对象 * @param {String} reason 出错的code * @description 当文件上传出错时触发。 * @for Uploader */ /** * @event uploadSuccess * @param {File} file File对象 * @param {Object} response 服务端返回的数据 * @description 当文件上传成功时触发。 * @for Uploader */ /** * @event uploadComplete * @param {File} [file] File对象 * @description 不管成功或者失败,文件上传完成时触发。 * @for Uploader */ // 做上传操作。 _doSend: function( block ) { var me = this, owner = me.owner, opts = me.options, file = block.file, tr = new Transport( opts ), data = $.extend({}, opts.formData ), headers = $.extend({}, opts.headers ), requestAccept, ret; block.transport = tr; tr.on( 'destroy', function() { delete block.transport; me._popBlock( block ); Base.nextTick( me.__tick ); }); // 广播上传进度。以文件为单位。 tr.on( 'progress', function( percentage ) { block.percentage = percentage; me.updateFileProgress( file ); }); // 用来询问,是否返回的结果是有错误的。 requestAccept = function( reject ) { var fn; ret = tr.getResponseAsJson() || {}; ret._raw = tr.getResponse(); fn = function( value ) { reject = value; }; // 服务端响应了,不代表成功了,询问是否响应正确。 if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) { reject = reject || 'server'; } return reject; }; // 尝试重试,然后广播文件上传出错。 tr.on( 'error', function( type, flag ) { block.retried = block.retried || 0; // 自动重试 if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) && block.retried < opts.chunkRetry ) { block.retried++; tr.send(); } else { // http status 500 ~ 600 if ( !flag && type === 'server' ) { type = requestAccept( type ); } file.setStatus( Status.ERROR, type ); owner.trigger( 'uploadError', file, type ); owner.trigger( 'uploadComplete', file ); } }); // 上传成功 tr.on( 'load', function() { var reason; // 如果非预期,转向上传出错。 if ( (reason = requestAccept()) ) { tr.trigger( 'error', reason, true ); return; } // 全部上传完成。 if ( file.remaning === 1 ) { me._finishFile( file, ret ); } else { tr.destroy(); } }); // 配置默认的上传字段。 data = $.extend( data, { id: file.id, name: file.name, type: file.type, lastModifiedDate: file.lastModifiedDate, size: file.size }); block.chunks > 1 && $.extend( data, { chunks: block.chunks, chunk: block.chunk }); // 在发送之间可以添加字段什么的。。。 // 如果默认的字段不够使用,可以通过监听此事件来扩展 owner.trigger( 'uploadBeforeSend', block, data, headers ); // 开始发送。 tr.appendBlob( opts.fileVal, block.blob, file.name ); tr.append( data ); tr.setRequestHeader( headers ); tr.send(); }, // 完成上传。 _finishFile: function( file, ret, hds ) { var owner = this.owner; return owner .request( 'after-send-file', arguments, function() { file.setStatus( Status.COMPLETE ); owner.trigger( 'uploadSuccess', file, ret, hds ); }) .fail(function( reason ) { // 如果外部已经标记为invalid什么的,不再改状态。 if ( file.getStatus() === Status.PROGRESS ) { file.setStatus( Status.ERROR, reason ); } owner.trigger( 'uploadError', file, reason ); }) .always(function() { owner.trigger( 'uploadComplete', file ); }); }, updateFileProgress: function(file) { var totalPercent = 0, uploaded = 0; if (!file.blocks) { return; } $.each( file.blocks, function( _, v ) { uploaded += (v.percentage || 0) * (v.end - v.start); }); totalPercent = uploaded / file.size; this.owner.trigger( 'uploadProgress', file, totalPercent || 0 ); } }); }); /** * 各种验证器 * @fileOverview 各种验证,包括文件总大小是否超出、单文件是否超出和文件是否重复。 */ define('widgets/validator',[ 'base', 'uploader', 'file', 'widgets/widget' ], function( Base, Uploader, WUFile ) { var $ = Base.$, validators = {}, api; /** * @event error * @param {String} type 错误类型。 * @description 当validate不通过时,会以派送错误事件的形式通知调用者。通过`upload.on('error', handler)`可以捕获到此类错误,目前有以下错误会在特定的情况下派送错来。 * * * `Q_EXCEED_NUM_LIMIT` 在设置了`fileNumLimit`且尝试给`uploader`添加的文件数量超出这个值时派送。 * * `Q_EXCEED_SIZE_LIMIT` 在设置了`Q_EXCEED_SIZE_LIMIT`且尝试给`uploader`添加的文件总大小超出这个值时派送。 * * `Q_TYPE_DENIED` 当文件类型不满足时触发。。 * @for Uploader */ // 暴露给外面的api api = { // 添加验证器 addValidator: function( type, cb ) { validators[ type ] = cb; }, // 移除验证器 removeValidator: function( type ) { delete validators[ type ]; } }; // 在Uploader初始化的时候启动Validators的初始化 Uploader.register({ name: 'validator', init: function() { var me = this; Base.nextTick(function() { $.each( validators, function() { this.call( me.owner ); }); }); } }); /** * @property {int} [fileNumLimit=undefined] * @namespace options * @for Uploader * @description 验证文件总数量, 超出则不允许加入队列。 */ api.addValidator( 'fileNumLimit', function() { var uploader = this, opts = uploader.options, count = 0, max = parseInt( opts.fileNumLimit, 10 ), flag = true; if ( !max ) { return; } uploader.on( 'beforeFileQueued', function( file ) { // 增加beforeFileQueuedCheckfileNumLimit验证,主要为了再次加载时(已存在历史文件)验证数量是否超过设置项 if (!this.trigger('beforeFileQueuedCheckfileNumLimit', file,count)) { return false; } if ( count >= max && flag ) { flag = false; this.trigger( 'error', 'Q_EXCEED_NUM_LIMIT', max, file ); setTimeout(function() { flag = true; }, 1 ); } return count >= max ? false : true; }); uploader.on( 'fileQueued', function() { count++; }); uploader.on( 'fileDequeued', function() { count--; }); uploader.on( 'reset', function() { count = 0; }); }); /** * @property {int} [fileSizeLimit=undefined] * @namespace options * @for Uploader * @description 验证文件总大小是否超出限制, 超出则不允许加入队列。 */ api.addValidator( 'fileSizeLimit', function() { var uploader = this, opts = uploader.options, count = 0, max = parseInt( opts.fileSizeLimit, 10 ), flag = true; if ( !max ) { return; } uploader.on( 'beforeFileQueued', function( file ) { var invalid = count + file.size > max; if ( invalid && flag ) { flag = false; this.trigger( 'error', 'Q_EXCEED_SIZE_LIMIT', max, file ); setTimeout(function() { flag = true; }, 1 ); } return invalid ? false : true; }); uploader.on( 'fileQueued', function( file ) { count += file.size; }); uploader.on( 'fileDequeued', function( file ) { count -= file.size; }); uploader.on( 'reset', function() { count = 0; }); }); /** * @property {int} [fileSingleSizeLimit=undefined] * @namespace options * @for Uploader * @description 验证单个文件大小是否超出限制, 超出则不允许加入队列。 */ api.addValidator( 'fileSingleSizeLimit', function() { var uploader = this, opts = uploader.options, max = opts.fileSingleSizeLimit; if ( !max ) { return; } uploader.on( 'beforeFileQueued', function( file ) { if ( file.size > max ) { file.setStatus( WUFile.Status.INVALID, 'exceed_size' ); this.trigger( 'error', 'F_EXCEED_SIZE', max, file ); return false; } }); }); /** * @property {Boolean} [duplicate=undefined] * @namespace options * @for Uploader * @description 去重, 根据文件名字、文件大小和最后修改时间来生成hash Key. */ api.addValidator( 'duplicate', function() { var uploader = this, opts = uploader.options, mapping = {}; if ( opts.duplicate ) { return; } function hashString( str ) { var hash = 0, i = 0, len = str.length, _char; for ( ; i < len; i++ ) { _char = str.charCodeAt( i ); hash = _char + (hash << 6) + (hash << 16) - hash; } return hash; } uploader.on( 'beforeFileQueued', function( file ) { var hash = file.__hash || (file.__hash = hashString( file.name + file.size + file.lastModifiedDate )); // 已经重复了 if ( mapping[ hash ] ) { this.trigger( 'error', 'F_DUPLICATE', file ); return false; } }); uploader.on( 'fileQueued', function( file ) { var hash = file.__hash; hash && (mapping[ hash ] = true); }); uploader.on( 'fileDequeued', function( file ) { var hash = file.__hash; hash && (delete mapping[ hash ]); }); uploader.on( 'reset', function() { mapping = {}; }); }); return api; }); /** * Component基类 * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/compbase',[],function() { function CompBase( owner, runtime ) { this.owner = owner; this.options = owner.options; this.getRuntime = function() { return runtime; }; this.getRuid = function() { return runtime.uid; }; this.trigger = function() { return owner.trigger.apply( owner, arguments ); }; } return CompBase; }); /** * @fileOverview Html5Runtime */ define('runtime/html5/runtime',[ 'base', 'runtime/runtime', 'runtime/compbase' ], function( Base, Runtime, CompBase ) { var type = 'html5', components = {}; function Html5Runtime() { var pool = {}, me = this, destroy = this.destroy; Runtime.apply( me, arguments ); me.type = type; // 这个方法的调用者,实际上是RuntimeClient me.exec = function( comp, fn/*, args...*/) { var client = this, uid = client.uid, args = Base.slice( arguments, 2 ), instance; if ( components[ comp ] ) { instance = pool[ uid ] = pool[ uid ] || new components[ comp ]( client, me ); if ( instance[ fn ] ) { return instance[ fn ].apply( instance, args ); } } }; me.destroy = function() { // @todo 删除池子中的所有实例 return destroy && destroy.apply( this, arguments ); }; } Base.inherits( Runtime, { constructor: Html5Runtime, // 不需要连接其他程序,直接执行callback init: function() { var me = this; setTimeout(function() { me.trigger('ready'); }, 1 ); } }); // 注册Components Html5Runtime.register = function( name, component ) { var klass = components[ name ] = Base.inherits( CompBase, component ); return klass; }; // 注册html5运行时。 // 只有在支持的前提下注册。 if ( window.Blob && window.FileReader && window.DataView ) { Runtime.addRuntime( type, Html5Runtime ); } return Html5Runtime; }); /** * @fileOverview Blob Html实现 */ define('runtime/html5/blob',[ 'runtime/html5/runtime', 'lib/blob' ], function( Html5Runtime, Blob ) { return Html5Runtime.register( 'Blob', { slice: function( start, end ) { var blob = this.owner.source, slice = blob.slice || blob.webkitSlice || blob.mozSlice; blob = slice.call( blob, start, end ); return new Blob( this.getRuid(), blob ); } }); }); /** * @fileOverview FilePaste */ define('runtime/html5/dnd',[ 'base', 'runtime/html5/runtime', 'lib/file' ], function( Base, Html5Runtime, File ) { var $ = Base.$, prefix = 'webuploader-dnd-'; return Html5Runtime.register( 'DragAndDrop', { init: function() { var elem = this.elem = this.options.container; this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this ); this.dragOverHandler = Base.bindFn( this._dragOverHandler, this ); this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this ); this.dropHandler = Base.bindFn( this._dropHandler, this ); this.dndOver = false; elem.on( 'dragenter', this.dragEnterHandler ); elem.on( 'dragover', this.dragOverHandler ); elem.on( 'dragleave', this.dragLeaveHandler ); elem.on( 'drop', this.dropHandler ); if ( this.options.disableGlobalDnd ) { $( document ).on( 'dragover', this.dragOverHandler ); $( document ).on( 'drop', this.dropHandler ); } }, _dragEnterHandler: function( e ) { var me = this, denied = me._denied || false, items; e = e.originalEvent || e; if ( !me.dndOver ) { me.dndOver = true; // 注意只有 chrome 支持。 items = e.dataTransfer.items; if ( items && items.length ) { me._denied = denied = !me.trigger( 'accept', items ); } me.elem.addClass( prefix + 'over' ); me.elem[ denied ? 'addClass' : 'removeClass' ]( prefix + 'denied' ); } e.dataTransfer.dropEffect = denied ? 'none' : 'copy'; return false; }, _dragOverHandler: function( e ) { // 只处理框内的。 var parentElem = this.elem.parent().get( 0 ); if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) { return false; } clearTimeout( this._leaveTimer ); this._dragEnterHandler.call( this, e ); return false; }, _dragLeaveHandler: function() { var me = this, handler; handler = function() { me.dndOver = false; me.elem.removeClass( prefix + 'over ' + prefix + 'denied' ); }; clearTimeout( me._leaveTimer ); me._leaveTimer = setTimeout( handler, 100 ); return false; }, _dropHandler: function( e ) { var me = this, ruid = me.getRuid(), parentElem = me.elem.parent().get( 0 ), dataTransfer, data; // 只处理框内的。 if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) { return false; } e = e.originalEvent || e; dataTransfer = e.dataTransfer; // 如果是页面内拖拽,还不能处理,不阻止事件。 // 此处 ie11 下会报参数错误, try { data = dataTransfer.getData('text/html'); } catch( err ) { } me.dndOver = false; me.elem.removeClass( prefix + 'over' ); if ( !dataTransfer || data ) { return; } me._getTansferFiles( dataTransfer, function( results ) { me.trigger( 'drop', $.map( results, function( file ) { return new File( ruid, file ); }) ); }); return false; }, // 如果传入 callback 则去查看文件夹,否则只管当前文件夹。 _getTansferFiles: function( dataTransfer, callback ) { var results = [], promises = [], items, files, file, item, i, len, canAccessFolder; items = dataTransfer.items; files = dataTransfer.files; canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry); for ( i = 0, len = files.length; i < len; i++ ) { file = files[ i ]; item = items && items[ i ]; if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) { promises.push( this._traverseDirectoryTree( item.webkitGetAsEntry(), results ) ); } else { results.push( file ); } } Base.when.apply( Base, promises ).done(function() { if ( !results.length ) { return; } callback( results ); }); }, _traverseDirectoryTree: function( entry, results ) { var deferred = Base.Deferred(), me = this; if ( entry.isFile ) { entry.file(function( file ) { results.push( file ); deferred.resolve(); }); } else if ( entry.isDirectory ) { entry.createReader().readEntries(function( entries ) { var len = entries.length, promises = [], arr = [], // 为了保证顺序。 i; for ( i = 0; i < len; i++ ) { promises.push( me._traverseDirectoryTree( entries[ i ], arr ) ); } Base.when.apply( Base, promises ).then(function() { results.push.apply( results, arr ); deferred.resolve(); }, deferred.reject ); }); } return deferred.promise(); }, destroy: function() { var elem = this.elem; // 还没 init 就调用 destroy if (!elem) { return; } elem.off( 'dragenter', this.dragEnterHandler ); elem.off( 'dragover', this.dragOverHandler ); elem.off( 'dragleave', this.dragLeaveHandler ); elem.off( 'drop', this.dropHandler ); if ( this.options.disableGlobalDnd ) { $( document ).off( 'dragover', this.dragOverHandler ); $( document ).off( 'drop', this.dropHandler ); } } }); }); /** * @fileOverview FilePaste */ define('runtime/html5/filepaste',[ 'base', 'runtime/html5/runtime', 'lib/file' ], function( Base, Html5Runtime, File ) { return Html5Runtime.register( 'FilePaste', { init: function() { var opts = this.options, elem = this.elem = opts.container, accept = '.*', arr, i, len, item; // accetp的mimeTypes中生成匹配正则。 if ( opts.accept ) { arr = []; for ( i = 0, len = opts.accept.length; i < len; i++ ) { item = opts.accept[ i ].mimeTypes; item && arr.push( item ); } if ( arr.length ) { accept = arr.join(','); accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' ); } } this.accept = accept = new RegExp( accept, 'i' ); this.hander = Base.bindFn( this._pasteHander, this ); elem.on( 'paste', this.hander ); }, _pasteHander: function( e ) { var allowed = [], ruid = this.getRuid(), items, item, blob, i, len; e = e.originalEvent || e; items = e.clipboardData.items; for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) { continue; } allowed.push( new File( ruid, blob ) ); } if ( allowed.length ) { // 不阻止非文件粘贴(文字粘贴)的事件冒泡 e.preventDefault(); e.stopPropagation(); this.trigger( 'paste', allowed ); } }, destroy: function() { this.elem.off( 'paste', this.hander ); } }); }); /** * @fileOverview FilePicker */ define('runtime/html5/filepicker',[ 'base', 'runtime/html5/runtime' ], function (Base, Html5Runtime) { var $ = Base.$; return Html5Runtime.register('FilePicker', { init: function () { var container = this.getRuntime().getContainer(), me = this, owner = me.owner, opts = me.options, label = this.label = $(document.createElement('label')), input = this.input = $(document.createElement('input')), arr, i, len, mouseHandler, changeHandler; input.attr('type', 'file'); input.attr('capture', 'camera'); input.attr('name', opts.name); input.addClass('webuploader-element-invisible'); label.on('click', function (e) { input.trigger('click'); e.stopPropagation(); owner.trigger('dialogopen'); }); label.css({ opacity: 0, width: '100%', height: '100%', display: 'block', cursor: 'pointer', background: '#ffffff' }); if (opts.multiple) { input.attr('multiple', 'multiple'); } // @todo Firefox不支持单独指定后缀 if (opts.accept && opts.accept.length > 0) { arr = []; for (i = 0, len = opts.accept.length; i < len; i++) { arr.push(opts.accept[i].mimeTypes); } input.attr('accept', arr.join(',')); } container.append(input); container.append(label); mouseHandler = function (e) { owner.trigger(e.type); }; changeHandler = function (e) { // var clone; // 解决chrome 56 第二次打开文件选择器,然后点击取消,依然会触发change事件的问题 if (e.target.files.length === 0) { return false; } // 第一次上传图片后,第二次再点击弹出文件选择器窗,等待 me.files = e.target.files; // reset input clone = this.cloneNode(true); clone.value = null; this.parentNode.replaceChild(clone, this); input.off(); input = $(clone).on('change', changeHandler) .on('mouseenter mouseleave', mouseHandler); owner.trigger('change'); } input.on('change', changeHandler); label.on('mouseenter mouseleave', mouseHandler); }, getFiles: function () { return this.files; }, destroy: function () { this.input.off(); this.label.off(); } }); }); /** * Terms: * * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer * @fileOverview Image控件 */ define('runtime/html5/util',[ 'base' ], function( Base ) { var urlAPI = window.createObjectURL && window || window.URL && URL.revokeObjectURL && URL || window.webkitURL, createObjectURL = Base.noop, revokeObjectURL = createObjectURL; if ( urlAPI ) { // 更安全的方式调用,比如android里面就能把context改成其他的对象。 createObjectURL = function() { return urlAPI.createObjectURL.apply( urlAPI, arguments ); }; revokeObjectURL = function() { return urlAPI.revokeObjectURL.apply( urlAPI, arguments ); }; } return { createObjectURL: createObjectURL, revokeObjectURL: revokeObjectURL, dataURL2Blob: function( dataURI ) { var byteStr, intArray, ab, i, mimetype, parts; parts = dataURI.split(','); if ( ~parts[ 0 ].indexOf('base64') ) { byteStr = atob( parts[ 1 ] ); } else { byteStr = decodeURIComponent( parts[ 1 ] ); } ab = new ArrayBuffer( byteStr.length ); intArray = new Uint8Array( ab ); for ( i = 0; i < byteStr.length; i++ ) { intArray[ i ] = byteStr.charCodeAt( i ); } mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ]; return this.arrayBufferToBlob( ab, mimetype ); }, dataURL2ArrayBuffer: function( dataURI ) { var byteStr, intArray, i, parts; parts = dataURI.split(','); if ( ~parts[ 0 ].indexOf('base64') ) { byteStr = atob( parts[ 1 ] ); } else { byteStr = decodeURIComponent( parts[ 1 ] ); } intArray = new Uint8Array( byteStr.length ); for ( i = 0; i < byteStr.length; i++ ) { intArray[ i ] = byteStr.charCodeAt( i ); } return intArray.buffer; }, arrayBufferToBlob: function( buffer, type ) { var builder = window.BlobBuilder || window.WebKitBlobBuilder, bb; // android不支持直接new Blob, 只能借助blobbuilder. if ( builder ) { bb = new builder(); bb.append( buffer ); return bb.getBlob( type ); } return new Blob([ buffer ], type ? { type: type } : {} ); }, // 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg. // 你得到的结果是png. canvasToDataUrl: function( canvas, type, quality ) { return canvas.toDataURL( type, quality / 100 ); }, // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。 parseMeta: function( blob, callback ) { callback( false, {}); }, // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。 updateImageHead: function( data ) { return data; } }; }); /** * Terms: * * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer * @fileOverview Image控件 */ define('runtime/html5/imagemeta',[ 'runtime/html5/util' ], function( Util ) { var api; api = { parsers: { 0xffe1: [] }, maxMetaDataSize: 262144, parse: function( blob, cb ) { var me = this, fr = new FileReader(); fr.onload = function() { cb( false, me._parse( this.result ) ); fr = fr.onload = fr.onerror = null; }; fr.onerror = function( e ) { cb( e.message ); fr = fr.onload = fr.onerror = null; }; blob = blob.slice( 0, me.maxMetaDataSize ); fr.readAsArrayBuffer( blob.getSource() ); }, _parse: function( buffer, noParse ) { if ( buffer.byteLength < 6 ) { return; } var dataview = new DataView( buffer ), offset = 2, maxOffset = dataview.byteLength - 4, headLength = offset, ret = {}, markerBytes, markerLength, parsers, i; if ( dataview.getUint16( 0 ) === 0xffd8 ) { while ( offset < maxOffset ) { markerBytes = dataview.getUint16( offset ); if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef || markerBytes === 0xfffe ) { markerLength = dataview.getUint16( offset + 2 ) + 2; if ( offset + markerLength > dataview.byteLength ) { break; } parsers = api.parsers[ markerBytes ]; if ( !noParse && parsers ) { for ( i = 0; i < parsers.length; i += 1 ) { parsers[ i ].call( api, dataview, offset, markerLength, ret ); } } offset += markerLength; headLength = offset; } else { break; } } if ( headLength > 6 ) { if ( buffer.slice ) { ret.imageHead = buffer.slice( 2, headLength ); } else { // Workaround for IE10, which does not yet // support ArrayBuffer.slice: ret.imageHead = new Uint8Array( buffer ) .subarray( 2, headLength ); } } } return ret; }, updateImageHead: function( buffer, head ) { var data = this._parse( buffer, true ), buf1, buf2, bodyoffset; bodyoffset = 2; if ( data.imageHead ) { bodyoffset = 2 + data.imageHead.byteLength; } if ( buffer.slice ) { buf2 = buffer.slice( bodyoffset ); } else { buf2 = new Uint8Array( buffer ).subarray( bodyoffset ); } buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength ); buf1[ 0 ] = 0xFF; buf1[ 1 ] = 0xD8; buf1.set( new Uint8Array( head ), 2 ); buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 ); return buf1.buffer; } }; Util.parseMeta = function() { return api.parse.apply( api, arguments ); }; Util.updateImageHead = function() { return api.updateImageHead.apply( api, arguments ); }; return api; }); /** * 代码来自于:https://github.com/blueimp/JavaScript-Load-Image * 暂时项目中只用了orientation. * * 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail. * @fileOverview EXIF解析 */ // Sample // ==================================== // Make : Apple // Model : iPhone 4S // Orientation : 1 // XResolution : 72 [72/1] // YResolution : 72 [72/1] // ResolutionUnit : 2 // Software : QuickTime 7.7.1 // DateTime : 2013:09:01 22:53:55 // ExifIFDPointer : 190 // ExposureTime : 0.058823529411764705 [1/17] // FNumber : 2.4 [12/5] // ExposureProgram : Normal program // ISOSpeedRatings : 800 // ExifVersion : 0220 // DateTimeOriginal : 2013:09:01 22:52:51 // DateTimeDigitized : 2013:09:01 22:52:51 // ComponentsConfiguration : YCbCr // ShutterSpeedValue : 4.058893515764426 // ApertureValue : 2.5260688216892597 [4845/1918] // BrightnessValue : -0.3126686601998395 // MeteringMode : Pattern // Flash : Flash did not fire, compulsory flash mode // FocalLength : 4.28 [107/25] // SubjectArea : [4 values] // FlashpixVersion : 0100 // ColorSpace : 1 // PixelXDimension : 2448 // PixelYDimension : 3264 // SensingMethod : One-chip color area sensor // ExposureMode : 0 // WhiteBalance : Auto white balance // FocalLengthIn35mmFilm : 35 // SceneCaptureType : Standard define('runtime/html5/imagemeta/exif',[ 'base', 'runtime/html5/imagemeta' ], function( Base, ImageMeta ) { var EXIF = {}; EXIF.ExifMap = function() { return this; }; EXIF.ExifMap.prototype.map = { 'Orientation': 0x0112 }; EXIF.ExifMap.prototype.get = function( id ) { return this[ id ] || this[ this.map[ id ] ]; }; EXIF.exifTagTypes = { // byte, 8-bit unsigned int: 1: { getValue: function( dataView, dataOffset ) { return dataView.getUint8( dataOffset ); }, size: 1 }, // ascii, 8-bit byte: 2: { getValue: function( dataView, dataOffset ) { return String.fromCharCode( dataView.getUint8( dataOffset ) ); }, size: 1, ascii: true }, // short, 16 bit int: 3: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getUint16( dataOffset, littleEndian ); }, size: 2 }, // long, 32 bit int: 4: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getUint32( dataOffset, littleEndian ); }, size: 4 }, // rational = two long values, // first is numerator, second is denominator: 5: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getUint32( dataOffset, littleEndian ) / dataView.getUint32( dataOffset + 4, littleEndian ); }, size: 8 }, // slong, 32 bit signed int: 9: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getInt32( dataOffset, littleEndian ); }, size: 4 }, // srational, two slongs, first is numerator, second is denominator: 10: { getValue: function( dataView, dataOffset, littleEndian ) { return dataView.getInt32( dataOffset, littleEndian ) / dataView.getInt32( dataOffset + 4, littleEndian ); }, size: 8 } }; // undefined, 8-bit byte, value depending on field: EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ]; EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length, littleEndian ) { var tagType = EXIF.exifTagTypes[ type ], tagSize, dataOffset, values, i, str, c; if ( !tagType ) { Base.log('Invalid Exif data: Invalid tag type.'); return; } tagSize = tagType.size * length; // Determine if the value is contained in the dataOffset bytes, // or if the value at the dataOffset is a pointer to the actual data: dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8, littleEndian ) : (offset + 8); if ( dataOffset + tagSize > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid data offset.'); return; } if ( length === 1 ) { return tagType.getValue( dataView, dataOffset, littleEndian ); } values = []; for ( i = 0; i < length; i += 1 ) { values[ i ] = tagType.getValue( dataView, dataOffset + i * tagType.size, littleEndian ); } if ( tagType.ascii ) { str = ''; // Concatenate the chars: for ( i = 0; i < values.length; i += 1 ) { c = values[ i ]; // Ignore the terminating NULL byte(s): if ( c === '\u0000' ) { break; } str += c; } return str; } return values; }; EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian, data ) { var tag = dataView.getUint16( offset, littleEndian ); data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset, dataView.getUint16( offset + 2, littleEndian ), // tag type dataView.getUint32( offset + 4, littleEndian ), // tag length littleEndian ); }; EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset, littleEndian, data ) { var tagsNumber, dirEndOffset, i; if ( dirOffset + 6 > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid directory offset.'); return; } tagsNumber = dataView.getUint16( dirOffset, littleEndian ); dirEndOffset = dirOffset + 2 + 12 * tagsNumber; if ( dirEndOffset + 4 > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid directory size.'); return; } for ( i = 0; i < tagsNumber; i += 1 ) { this.parseExifTag( dataView, tiffOffset, dirOffset + 2 + 12 * i, // tag offset littleEndian, data ); } // Return the offset to the next directory: return dataView.getUint32( dirEndOffset, littleEndian ); }; // EXIF.getExifThumbnail = function(dataView, offset, length) { // var hexData, // i, // b; // if (!length || offset + length > dataView.byteLength) { // Base.log('Invalid Exif data: Invalid thumbnail data.'); // return; // } // hexData = []; // for (i = 0; i < length; i += 1) { // b = dataView.getUint8(offset + i); // hexData.push((b < 16 ? '0' : '') + b.toString(16)); // } // return 'data:image/jpeg,%' + hexData.join('%'); // }; EXIF.parseExifData = function( dataView, offset, length, data ) { var tiffOffset = offset + 10, littleEndian, dirOffset; // Check for the ASCII code for "Exif" (0x45786966): if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) { // No Exif data, might be XMP data instead return; } if ( tiffOffset + 8 > dataView.byteLength ) { Base.log('Invalid Exif data: Invalid segment size.'); return; } // Check for the two null bytes: if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) { Base.log('Invalid Exif data: Missing byte alignment offset.'); return; } // Check the byte alignment: switch ( dataView.getUint16( tiffOffset ) ) { case 0x4949: littleEndian = true; break; case 0x4D4D: littleEndian = false; break; default: Base.log('Invalid Exif data: Invalid byte alignment marker.'); return; } // Check for the TIFF tag marker (0x002A): if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) { Base.log('Invalid Exif data: Missing TIFF marker.'); return; } // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal: dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian ); // Create the exif object to store the tags: data.exif = new EXIF.ExifMap(); // Parse the tags of the main image directory and retrieve the // offset to the next directory, usually the thumbnail directory: dirOffset = EXIF.parseExifTags( dataView, tiffOffset, tiffOffset + dirOffset, littleEndian, data ); // 尝试读取缩略图 // if ( dirOffset ) { // thumbnailData = {exif: {}}; // dirOffset = EXIF.parseExifTags( // dataView, // tiffOffset, // tiffOffset + dirOffset, // littleEndian, // thumbnailData // ); // // Check for JPEG Thumbnail offset: // if (thumbnailData.exif[0x0201]) { // data.exif.Thumbnail = EXIF.getExifThumbnail( // dataView, // tiffOffset + thumbnailData.exif[0x0201], // thumbnailData.exif[0x0202] // Thumbnail data length // ); // } // } }; ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData ); return EXIF; }); /** * @fileOverview Image */ define('runtime/html5/image',[ 'base', 'runtime/html5/runtime', 'runtime/html5/util' ], function( Base, Html5Runtime, Util ) { var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D'; return Html5Runtime.register( 'Image', { // flag: 标记是否被修改过。 modified: false, init: function() { var me = this, img = new Image(); img.onload = function() { me._info = { type: me.type, width: this.width, height: this.height }; //debugger; // 读取meta信息。 if ( !me._metas && 'image/jpeg' === me.type ) { Util.parseMeta( me._blob, function( error, ret ) { me._metas = ret; me.owner.trigger('load'); }); } else { me.owner.trigger('load'); } }; img.onerror = function() { me.owner.trigger('error'); }; me._img = img; }, loadFromBlob: function( blob ) { var me = this, img = me._img; me._blob = blob; me.type = blob.type; img.src = Util.createObjectURL( blob.getSource() ); me.owner.once( 'load', function() { Util.revokeObjectURL( img.src ); }); }, resize: function( width, height ) { var canvas = this._canvas || (this._canvas = document.createElement('canvas')); this._resize( this._img, canvas, width, height ); this._blob = null; // 没用了,可以删掉了。 this.modified = true; this.owner.trigger( 'complete', 'resize' ); }, crop: function( x, y, w, h, s ) { var cvs = this._canvas || (this._canvas = document.createElement('canvas')), opts = this.options, img = this._img, iw = img.naturalWidth, ih = img.naturalHeight, orientation = this.getOrientation(); s = s || 1; // todo 解决 orientation 的问题。 // values that require 90 degree rotation // if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) { // switch ( orientation ) { // case 6: // tmp = x; // x = y; // y = iw * s - tmp - w; // console.log(ih * s, tmp, w) // break; // } // (w ^= h, h ^= w, w ^= h); // } cvs.width = w; cvs.height = h; opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation ); this._renderImageToCanvas( cvs, img, -x, -y, iw * s, ih * s ); this._blob = null; // 没用了,可以删掉了。 this.modified = true; this.owner.trigger( 'complete', 'crop' ); }, getAsBlob: function( type ) { var blob = this._blob, opts = this.options, canvas; type = type || this.type; // blob需要重新生成。 if ( this.modified || this.type !== type ) { canvas = this._canvas; if ( type === 'image/jpeg' ) { blob = Util.canvasToDataUrl( canvas, type, opts.quality ); if ( opts.preserveHeaders && this._metas && this._metas.imageHead ) { blob = Util.dataURL2ArrayBuffer( blob ); blob = Util.updateImageHead( blob, this._metas.imageHead ); blob = Util.arrayBufferToBlob( blob, type ); return blob; } } else { blob = Util.canvasToDataUrl( canvas, type ); } blob = Util.dataURL2Blob( blob ); } return blob; }, getAsDataUrl: function( type ) { var opts = this.options; type = type || this.type; if ( type === 'image/jpeg' ) { return Util.canvasToDataUrl( this._canvas, type, opts.quality ); } else { return this._canvas.toDataURL( type ); } }, getOrientation: function() { return this._metas && this._metas.exif && this._metas.exif.get('Orientation') || 1; }, info: function( val ) { // setter if ( val ) { this._info = val; return this; } // getter return this._info; }, meta: function( val ) { // setter if ( val ) { this._metas = val; return this; } // getter return this._metas; }, destroy: function() { var canvas = this._canvas; this._img.onload = null; if ( canvas ) { canvas.getContext('2d') .clearRect( 0, 0, canvas.width, canvas.height ); canvas.width = canvas.height = 0; this._canvas = null; } // 释放内存。非常重要,否则释放不了image的内存。 this._img.src = BLANK; this._img = this._blob = null; }, _resize: function( img, cvs, width, height ) { var opts = this.options, naturalWidth = img.width, naturalHeight = img.height, orientation = this.getOrientation(), scale, w, h, x, y; // values that require 90 degree rotation if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) { // 交换width, height的值。 width ^= height; height ^= width; width ^= height; } scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth, height / naturalHeight ); // 不允许放大。 opts.allowMagnify || (scale = Math.min( 1, scale )); w = naturalWidth * scale; h = naturalHeight * scale; if ( opts.crop ) { cvs.width = width; cvs.height = height; } else { cvs.width = w; cvs.height = h; } x = (cvs.width - w) / 2; y = (cvs.height - h) / 2; opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation ); this._renderImageToCanvas( cvs, img, x, y, w, h ); }, _rotate2Orientaion: function( canvas, orientation ) { var width = canvas.width, height = canvas.height, ctx = canvas.getContext('2d'); switch ( orientation ) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; } switch ( orientation ) { case 2: // horizontal flip ctx.translate( width, 0 ); ctx.scale( -1, 1 ); break; case 3: // 180 rotate left ctx.translate( width, height ); ctx.rotate( Math.PI ); break; case 4: // vertical flip ctx.translate( 0, height ); ctx.scale( 1, -1 ); break; case 5: // vertical flip + 90 rotate right ctx.rotate( 0.5 * Math.PI ); ctx.scale( 1, -1 ); break; case 6: // 90 rotate right ctx.rotate( 0.5 * Math.PI ); ctx.translate( 0, -height ); break; case 7: // horizontal flip + 90 rotate right ctx.rotate( 0.5 * Math.PI ); ctx.translate( width, -height ); ctx.scale( -1, 1 ); break; case 8: // 90 rotate left ctx.rotate( -0.5 * Math.PI ); ctx.translate( -width, 0 ); break; } }, // https://github.com/stomita/ios-imagefile-megapixel/ // blob/master/src/megapix-image.js _renderImageToCanvas: (function() { // 如果不是ios, 不需要这么复杂! if ( !Base.os.ios ) { return function( canvas ) { var args = Base.slice( arguments, 1 ), ctx = canvas.getContext('2d'); ctx.drawImage.apply( ctx, args ); }; } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into * canvas for some images. */ function detectVerticalSquash( img, iw, ih ) { var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), sy = 0, ey = ih, py = ih, data, alpha, ratio; canvas.width = 1; canvas.height = ih; ctx.drawImage( img, 0, 0 ); data = ctx.getImageData( 0, 0, 1, ih ).data; // search image edge pixel position in case // it is squashed vertically. while ( py > sy ) { alpha = data[ (py - 1) * 4 + 3 ]; if ( alpha === 0 ) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } // fix ie7 bug // http://stackoverflow.com/questions/11929099/ // html5-canvas-drawimage-ratio-bug-ios if ( Base.os.ios >= 7 ) { return function( canvas, img, x, y, w, h ) { var iw = img.naturalWidth, ih = img.naturalHeight, vertSquashRatio = detectVerticalSquash( img, iw, ih ); return canvas.getContext('2d').drawImage( img, 0, 0, iw * vertSquashRatio, ih * vertSquashRatio, x, y, w, h ); }; } /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be * subsampled in rendering. */ function detectSubsampling( img ) { var iw = img.naturalWidth, ih = img.naturalHeight, canvas, ctx; // subsampling may happen overmegapixel image if ( iw * ih > 1024 * 1024 ) { canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; ctx = canvas.getContext('2d'); ctx.drawImage( img, -iw + 1, 0 ); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering // edge pixel or not. if alpha value is 0 // image is not covering, hence subsampled. return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0; } else { return false; } } return function( canvas, img, x, y, width, height ) { var iw = img.naturalWidth, ih = img.naturalHeight, ctx = canvas.getContext('2d'), subsampled = detectSubsampling( img ), doSquash = this.type === 'image/jpeg', d = 1024, sy = 0, dy = 0, tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx; if ( subsampled ) { iw /= 2; ih /= 2; } ctx.save(); tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; tmpCtx = tmpCanvas.getContext('2d'); vertSquashRatio = doSquash ? detectVerticalSquash( img, iw, ih ) : 1; dw = Math.ceil( d * width / iw ); dh = Math.ceil( d * height / ih / vertSquashRatio ); while ( sy < ih ) { sx = 0; dx = 0; while ( sx < iw ) { tmpCtx.clearRect( 0, 0, d, d ); tmpCtx.drawImage( img, -sx, -sy ); ctx.drawImage( tmpCanvas, 0, 0, d, d, x + dx, y + dy, dw, dh ); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; }; })() }); }); /** * @fileOverview Transport * @todo 支持chunked传输,优势: * 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分, * 而不需要重头再传一次。另外断点续传也需要用chunked方式。 */ define('runtime/html5/transport',[ 'base', 'runtime/html5/runtime' ], function( Base, Html5Runtime ) { var noop = Base.noop, $ = Base.$; return Html5Runtime.register( 'Transport', { init: function() { this._status = 0; this._response = null; }, send: function() { var owner = this.owner, opts = this.options, xhr = this._initAjax(), blob = owner._blob, server = opts.server, formData, binary, fr; if ( opts.sendAsBinary ) { server += (/\?/.test( server ) ? '&' : '?') + $.param( owner._formData ); binary = blob.getSource(); } else { formData = new FormData(); $.each( owner._formData, function( k, v ) { formData.append( k, v ); }); formData.append( opts.fileVal, blob.getSource(), opts.filename || owner._formData.name || '' ); } if ( opts.withCredentials && 'withCredentials' in xhr ) { xhr.open( opts.method, server, true ); xhr.withCredentials = true; } else { xhr.open( opts.method, server ); } this._setRequestHeader( xhr, opts.headers ); if ( binary ) { // 强制设置成 content-type 为文件流。 xhr.overrideMimeType && xhr.overrideMimeType('application/octet-stream'); // android直接发送blob会导致服务端接收到的是空文件。 // bug详情。 // https://code.google.com/p/android/issues/detail?id=39882 // 所以先用fileReader读取出来再通过arraybuffer的方式发送。 if ( Base.os.android ) { fr = new FileReader(); fr.onload = function() { xhr.send( this.result ); fr = fr.onload = null; }; fr.readAsArrayBuffer( binary ); } else { xhr.send( binary ); } } else { xhr.send( formData ); } }, getResponse: function() { return this._response; }, getResponseAsJson: function() { return this._parseJson( this._response ); }, getStatus: function() { return this._status; }, abort: function() { var xhr = this._xhr; if ( xhr ) { xhr.upload.onprogress = noop; xhr.onreadystatechange = noop; xhr.abort(); this._xhr = xhr = null; } }, destroy: function() { this.abort(); }, _initAjax: function() { var me = this, xhr = new XMLHttpRequest(), opts = this.options; if ( opts.withCredentials && !('withCredentials' in xhr) && typeof XDomainRequest !== 'undefined' ) { xhr = new XDomainRequest(); } xhr.upload.onprogress = function( e ) { var percentage = 0; if ( e.lengthComputable ) { percentage = e.loaded / e.total; } return me.trigger( 'progress', percentage ); }; xhr.onreadystatechange = function() { if ( xhr.readyState !== 4 ) { return; } xhr.upload.onprogress = noop; xhr.onreadystatechange = noop; me._xhr = null; me._status = xhr.status; if ( xhr.status >= 200 && xhr.status < 300 ) { me._response = xhr.responseText; return me.trigger('load'); } else if ( xhr.status >= 500 && xhr.status < 600 ) { me._response = xhr.responseText; return me.trigger( 'error', 'server-'+status ); } return me.trigger( 'error', me._status ? 'http-'+status : 'abort' ); }; me._xhr = xhr; return xhr; }, _setRequestHeader: function( xhr, headers ) { $.each( headers, function( key, val ) { xhr.setRequestHeader( key, val ); }); }, _parseJson: function( str ) { var json; try { json = JSON.parse( str ); } catch ( ex ) { json = {}; } return json; } }); }); /** * @fileOverview 只有html5实现的文件版本。 */ define('preset/html5only',[ 'base', // widgets 'widgets/filednd', 'widgets/filepaste', 'widgets/filepicker', 'widgets/image', 'widgets/queue', 'widgets/runtime', 'widgets/upload', 'widgets/validator', // runtimes // html5 'runtime/html5/blob', 'runtime/html5/dnd', 'runtime/html5/filepaste', 'runtime/html5/filepicker', 'runtime/html5/imagemeta/exif', 'runtime/html5/image', 'runtime/html5/transport' ], function( Base ) { return Base; }); define('webuploader',[ 'preset/html5only' ], function( preset ) { return preset; }); return require('webuploader'); });
VioletLife/webuploader
dist/webuploader.html5only.js
JavaScript
bsd-3-clause
207,085
(function () { "use strict"; var Pos = CodeMirror.Pos; function getHints(cm, options) { var tags = options && options.schemaInfo; var quote = (options && options.quoteChar) || '"'; if (!tags) return;// logO(tags, 'tags');//gets tags from schema (html in this case) var cur = cm.getCursor(), token = cm.getTokenAt(cur); var inner = CodeMirror.innerMode(cm.getMode(), token.state); if (inner.mode.name != "xml") return;//logO(inner.mode.name,'inner.mode.name'); //(still xml when in attribute quotes) var result = [], replaceToken = false, prefix; var isTag = token.string.charAt(0) == "<"; //Gather custom completions from my plugin //MY CUSTOM CODE var word = token.string;//logO(word, 'word'); if (CodeMirrorCustomCompletions && CodeMirrorCustomCompletions.length > 0) { for (var n = 0; n < CodeMirrorCustomCompletions.length; n++) { var name = CodeMirrorCustomCompletions[n].name; if (name.toLowerCase().indexOf(word) !== -1) { result.push(name); replaceToken = true; //IMPORTANT- I added this for custom completions to work, its possible that it may screw something up! } } }//end of my code //logO(result, 'result'); if (!inner.state.tagName || isTag) { // Tag completion if (isTag) { prefix = token.string.slice(1); replaceToken = true; } var cx = inner.state.context, curTag = cx && tags[cx.tagName]; var childList = cx ? curTag && curTag.children : tags["!top"]; if (childList) { for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].lastIndexOf(prefix, 0) == 0) result.push("<" + childList[i]); } else { for (var name in tags) if (tags.hasOwnProperty(name) && name != "!top" && (!prefix || name.lastIndexOf(prefix, 0) == 0)) result.push("<" + name); } if (cx && (!prefix || ("/" + cx.tagName).lastIndexOf(prefix, 0) == 0)) result.push("</" + cx.tagName + ">"); } else { // Attribute completion var curTag = tags[inner.state.tagName], attrs = curTag && curTag.attrs; if (!attrs) return; if (token.type == "string" || token.string == "=") { // A value var before = cm.getRange(Pos(cur.line, Math.max(0, cur.ch - 60)), Pos(cur.line, token.type == "string" ? token.start : token.end)); var atName = before.match(/([^\s\u00a0=<>\"\']+)=$/), atValues; if (!atName || !attrs.hasOwnProperty(atName[1]) || !(atValues = attrs[atName[1]])) return; if (typeof atValues == 'function') atValues = atValues.call(this, cm); // Functions can be used to supply values for autocomplete widget if (token.type == "string") { prefix = token.string; if (/['"]/.test(token.string.charAt(0))) { quote = token.string.charAt(0); prefix = token.string.slice(1); } replaceToken = true; } for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].lastIndexOf(prefix, 0) == 0) result.push(quote + atValues[i] + quote); } else { // An attribute name if (token.type == "attribute") { //logO(token, 'token xml-hint attribute'); prefix = token.string; replaceToken = true; } for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.lastIndexOf(prefix, 0) == 0)) result.push(attr); } } return { list: result, from: replaceToken ? Pos(cur.line, token.start) : cur, to: replaceToken ? Pos(cur.line, token.end) : cur }; } CodeMirror.xmlHint = getHints; // deprecated CodeMirror.registerHelper("hint", "xml", getHints); })();
webpadonline/webpadonline.github.io
lib/CodeMirror_Custom/addon/hint/xml-hint.js
JavaScript
bsd-3-clause
4,423
module.exports.name = 'development'; module.exports.dbtype = "mssql"; module.exports.datasource = {user: "sa", password: "sa", host: "localhost", port: 1433}; module.exports.windwalkerPort = 8080;
BHare1985/Windshaft
config/environments/development.js
JavaScript
bsd-3-clause
214
/** * This file is the event bus demo **/ // Global namespace var EventBus = (function() { var // List of optional events events = {}, // Reference to the last fired event lastEvent, domNodes = [] ; function init() { domNodes['create-name'] = document.querySelector('[data-create-name]'); domNodes['create-handler'] = document.querySelector('[data-create-handler]'); domNodes['events-list'] = document.querySelector('.js-events-list'); domNodes['last-event'] = document.querySelector('[data-last-event]') } /** * Register new event * * @param {Object} eventData - The event data. * The eventData should contain the following info * * {eventData} : name: The name of the event * handler: The callback to be called when the event is triggered */ function registerEvent(eventData) { var name; // Validation if (!eventData) { console.log('Missing parameters'); return; } // Get the event name or set default name name = eventData.name || 'event' + Date.now(); // Store the event in the events list events[name] = eventData; // add event listener to print out when the vent was called document.addEventListener(name, function(myEvent) { console.log(myEvent); // Update the last event domNodes['last-event'].textContent = JSON.stringify(myEvent.detail); }); // Update the UI updateList(); } /** * Update the GUI events list */ function updateList() { // Get the list of the events var events = EventBus.getEventsList().sort(), // The new list markup listFragment = document.createDocumentFragment() ; // Clear the previous list domNodes['events-list'].innerHTML = ''; // Loop and output the events events.forEach(function(eventName) { var radio = document.createElement('input'), label = document.createElement('label'); radio.type = 'checkbox'; radio.name = eventName; radio.addEventListener('click', EventBus.fireEvent); listFragment.appendChild(radio); label.textContent = eventName; listFragment.appendChild(label); listFragment.appendChild(document.createElement('br')); }); domNodes['events-list'].appendChild(listFragment); } /** * Create new event. */ function createEvent(e) { // We don't do anything with the event registerEvent({ "name": domNodes['create-name'].value, "handler": domNodes['create-handler'].value }); domNodes['create-name'].value = ''; domNodes['create-handler'].value = ''; } /** * Fire the event. */ function fireEvent() { var event; // un-check the previous event lastEvent ? lastEvent.checked = false : undefined; // Store the current event lastEvent = this; event = new CustomEvent( this.name, { detail: { message: "Fired event: " + this.name, time: Date.now() }, bubbles: true, cancelable: true } ); // Dispatch the event. document.dispatchEvent(event); } // Prepare the object init(); return { createEvent: createEvent, registerEvent: registerEvent, fireEvent: fireEvent, getEventsList: function() { return Object.keys(events); } } })(); // Bind the click button document.querySelector('.js-create-event').addEventListener('click', EventBus.createEvent);
nirgeier/EventBus
WorkingDemo/js/EventBus_solution.js
JavaScript
bsd-3-clause
3,985
var Backbone = require('backbone'); var camshaftReference = require('builder/data/camshaft-reference'); var areaOfInfluenceTemplate = require('builder/editor/layers/layer-content-views/analyses/analysis-form-models/area-of-influence-form.tpl'); var BaseAnalysisFormModel = require('builder/editor/layers/layer-content-views/analyses/analysis-form-models/base-analysis-form-model'); var AnalysisFormView = require('builder/editor/layers/layer-content-views/analyses/analysis-form-view'); var analyses = require('builder/data/analyses'); describe('editor/layers/layer-content-view/analyses/analysis-form-view', function () { beforeEach(function () { this.formModel = new BaseAnalysisFormModel({ id: 'a1', type: 'buffer', source: 'a0', radius: '100' }, { analyses: analyses, configModel: {}, layerDefinitionModel: {}, analysisSourceOptionsModel: {} }); this.formModel.schema.source = {type: 'Text'}; this.formModel.schema.radius = {type: 'Number'}; spyOn(this.formModel, 'getTemplate').and.returnValue(areaOfInfluenceTemplate); spyOn(this.formModel, 'getTemplateData').and.returnValue({parametersDataFields: 'radius'}); spyOn(this.formModel, 'setFormValidationErrors').and.callThrough(); spyOn(camshaftReference, 'validate'); this.view = new AnalysisFormView({ formModel: this.formModel, configModel: {} }); this.view.render(); }); it('should render with template and data from form model', function () { expect(this.view.$el.html()).toContain('form'); expect(this.view.$el.html()).toContain('data-fields="radius"'); }); it('should not validate when view is rendered intially', function () { expect(camshaftReference.validate).not.toHaveBeenCalled(); }); describe('when form changes with erroneous data', function () { beforeEach(function () { camshaftReference.validate.and.returnValue({radius: '42 is not the answer, you fool!'}); // simulate change this.view._formView.setValue('radius', '42'); this.view._formView.trigger('change'); }); it('should show errors when validation fails', function (done) { var self = this; setTimeout(function () { expect(camshaftReference.validate).toHaveBeenCalled(); expect(self.view.$el.html()).toContain('Error'); done(); }, 0); }); it('should update form model anyway', function () { expect(this.formModel.get('radius')).toEqual(42); }); it('should set form validation errors on the model', function (done) { var self = this; setTimeout(function () { expect(self.formModel.setFormValidationErrors).toHaveBeenCalled(); expect(self.formModel.setFormValidationErrors.calls.argsFor(0)[0]).toBeUndefined(); expect(self.formModel.setFormValidationErrors.calls.argsFor(1)[0]).toEqual({radius: jasmine.any(String)}); done(); }, 0); }); describe('when validation passes', function () { beforeEach(function () { this.formModel.setFormValidationErrors.calls.reset(); camshaftReference.validate.and.returnValue(undefined); // simulate change this.view._formView.setValue('radius', '20'); this.view._formView.trigger('change'); }); it('should remove form validation errors', function () { expect(this.formModel.setFormValidationErrors.calls.argsFor(0)[0]).toBeUndefined(); expect(this.formModel.setFormValidationErrors.calls.argsFor(1)[0]).toBeUndefined(); }); it('should update model', function () { expect(this.formModel.get('radius')).toEqual(20); }); }); }); describe('when schema changes', function () { beforeEach(function () { this.prev$form = this.view.$('form'); this.formModel.trigger('changeSchema'); }); afterEach(function () { this.prev$form = null; }); it('should re-render the form', function () { expect(this.view.$('form').length).toEqual(1); expect(this.view.$('form')).not.toBe(this.prev$form); }); }); describe('_onChangeAnalysisFormView and _showAnalysisFormErrors', function () { it('_onChangeAnalysisFormView calls _showAnalysisFormErrors with the form view Id that was active when the function was called', function (done) { var self = this; spyOn(this.view, '_showAnalysisFormErrors'); var formId = this.view._formView.cid; this.view._onChangeAnalysisFormView(); setTimeout(function () { expect(self.view._showAnalysisFormErrors).toHaveBeenCalledWith(formId); done(); }, 0); }); it('_showAnalysisFormErrors should not commit the form if the current form is different from the one who called it', function () { var _prevShowFn = this.view._showAnalysisFormErrors; var self = this; spyOn(this.view, '_showAnalysisFormErrors').and.callFake(function (formId) { self.view._formView.cid = 'another-form-808'; _prevShowFn.call(this, formId); }); spyOn(this.view, '_formView'); this.view._onChangeAnalysisFormView(); expect(this.view._formView).not.toHaveBeenCalled(); }); }); describe('when form is cleaned', function () { beforeEach(function () { spyOn(Backbone.Form.prototype, 'remove').and.callThrough(); this.view.clean(); }); it('should remove form when view is cleaned', function () { expect(Backbone.Form.prototype.remove).toHaveBeenCalled(); }); }); it('should not have any leaks', function () { expect(this.view).toHaveNoLeaks(); }); });
CartoDB/cartodb
lib/assets/test/spec/builder/editor/layers/layer-content-view/analyses/analysis-form-view.spec.js
JavaScript
bsd-3-clause
5,648
+function(n){"use strict";function t(){var n=document.createElement("bootstrap"),t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var i in t)if(void 0!==n.style[i])return{end:t[i]}}n.fn.emulateTransitionEnd=function(t){var i=!1,o=this;n(this).one(n.support.transition.end,function(){i=!0});var r=function(){i||n(o).trigger(n.support.transition.end)};return setTimeout(r,t),this},n(function(){n.support.transition=t()})}(jQuery);
jbsmith86/GiveMeNotice
public/assets/bootstrap/transition-e7d892bd6a7fb6c9f866f0230190cacf.js
JavaScript
bsd-3-clause
527
var notificationschema = require('../model/notification_model.js'); var mailer = require('./mail.js'); // Mail Functionality var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); var protocol = 'http'; // Response Function var sendResponse = function(req, res, status, errCode, errMsg) { var d = Date(); console.log(status +" "+ errCode +" "+ errMsg + " " + d); res.status(status).send({ errCode: errCode, errMsg: errMsg, dbDate: d }); } /*Verification Email api*/ module.exports.sendVerificationEmail = function(req){ console.log('Page Name : notification.js'); console.log('API Name : sendVerificationEmail'); console.log('sendVerificationEmail API Hitted'); console.log('Parameters Receiving..'); var accountInfo = req.body[0]; vhash = req.body[1].vhash; flag = req.body[1].flag; console.log(accountInfo); // Wallet if(flag == '2'){ var url= protocol+"://scoinz.com/presaleWallet/wallet/verifyUser.php?auth="+vhash+"&email="+encodeURIComponent(accountInfo.email)+"&errcode=15"; } // Web else { var url= protocol+"://localhost/st-web/keywords/views/verifyUser.php?auth="+vhash+"&email="+encodeURIComponent(accountInfo.email)+"&flag="+flag; } var text= '<div style="border:solid thin black; padding: 10px;"><div style="background: #25a2dc; color: #fff; padding: 5px"><img src="http://searchtrade.com/images/searchtrade_white.png" width="200px"></div><br><br><div style="background: #fff; color: #000; padding: 5px;"><div style="width:75%; margin: auto"><p>Hello '+accountInfo.first_name+' '+accountInfo.last_name+',</p><br><p>Your SearchTrade account has been created.</p><p>Please click <a href="'+url+'">Here</a> to verify your email address or copy/paste the link below into your browser.</p><p>'+url+'</p></div></div></div></div>'; // Setup E-mail Data With Unicode Symbols var mailOptions= { from: 'Search Trade <donotreply@searchtrade.com>', // Sender address to : accountInfo.email, // List of Receivers subject: "Search Trade: Email Verification", // Subject line text: text, // Text html: text }; mailer.sendmail(mailOptions, function(){ if(true){ console.log('mail callback success'); var notificationInfo = new notificationschema.notification_wallet({ user_id : accountInfo._id, first_name : accountInfo.first_name, last_name : accountInfo.last_name }); var notificationMsg = new notificationschema.notification_msg({ user_id : accountInfo._id, notification_body : 'Your account has been created successfully' }); notificationMsg.save(function(err){ if(err) { console.log(err); return err; } console.log('Message Saved SuccessFully'); }); notificationInfo.save(function(err){ if(err) { console.log(err); return err; } console.log('Saved SuccessFully'); var mailStatus = true; }); }else{ console.log('mail callback fails'); var mailStatus = false; } return mailStatus; }); } /*forgot password Email api*/ module.exports.sendforgotpassword = function(req){ console.log('Page Name : notification.js'); console.log('API Name : sendforgotpassword'); console.log('sendforgotpassword API Hitted'); console.log('Parameters Receiving..'); var accountInfo = req.body[0]; var vhash = req.body[1].vhash; var flag = req.body[1].flag; console.log(accountInfo); if(flag == '1') // For Web { var url= protocol+"://localhost/st-web/forgetpwd.php?auth="+vhash+"&email="+encodeURIComponent(accountInfo.email)+"&flag="+flag; } if(flag == '2') // For Wallet { var url= protocol+"://scoinz.com/presaleWallet/wallet/resetpass.php?auth="+vhash+"&email="+encodeURIComponent(accountInfo.email); } if(flag == '3') // For Mobile { var url= protocol+"://localhost/st-web/MobileSite/forgetpwd.php?auth="+vhash+"&email="+encodeURIComponent(accountInfo.email)+"&flag="+flag; } var text= '<div style="border: solid thin black; padding: 10px;"><div style="background: #25a2dc; color: #fff; padding: 5px"><img src="http://searchtrade.com/images/searchtrade_white.png" width="200px"></div><br><br><div style="background: #fff; color: #000; padding: 5px;"><div style="width:75%; margin: auto"><p>Hi '+accountInfo.first_name+' '+accountInfo.last_name+',</p><br><p>You have requested to Change your SearchTrade account password.</p><p>Please click <a href="'+url+'">Here</a> to reset your password.</p><p>OR</p><p>Copy Link Address below in your web browser</p><p>'+url+'</p><br><p>Regards the from SearchTrade team</p><br><p>Product of Searchtrade.com Pte Ltd, Singapore</p></div></div></div>'; // Setup E-mail data with unicode symbols var mailOptions= { from: 'Search Trade <donotreply@searchtrade.com>', // Sender address to: accountInfo.email, // List of Receivers subject: "Search Trade : Reset your password", // Subject line text: text, // Text html: text }; mailer.sendmail(mailOptions, function(){ if (true) { console.log('mail callback success'); var mailStatus = true; } else{ console.log('mail callback fails'); var mailStatus = false; } return mailStatus }); // end mailer.sendmail }; /*Chnage password email api*/ module.exports.changePassEmail = function(req){ var accountInfo = req.body; console.log(accountInfo); var text= '<div style="border: solid thin black; padding: 10px;"><div style="background: #25a2dc; color: #fff; padding: 5px"><img src="http://searchtrade.com/images/searchtrade_white.png" width="200px"></div><br><br><div style="background: #fff; color: #000; padding: 5px;"><div style="width:75%; margin: auto"><p>Hi '+accountInfo.first_name+' '+accountInfo.last_name+',</p><br><p>This is a confirmation mail that you have successfully changed your password</p><br><p>You can log into your account with your new password.</p><br><p>Regards from the SearchTrade team</p><br><p>Product of Searchtrade.com Pte Ltd, Singapore</p></div></div></div></div>'; // Setup e-mail data with unicode symbols var mailOptions = { from: 'Search Trade <donotreply@searchtrade.com>', // Sender address to: accountInfo.email, // List of Receivers subject: "Search Trade: Password Change Confirmation", // Subject line text: text, // Text html: text }; mailer.sendmail(mailOptions, function(){ if (true) { console.log('mail callback success'); var mailStatus = true; } else{ console.log('mail callback fails'); var mailStatus = false; } return mailStatus }); } /*Reset Password*/ module.exports.resettedConfirmation = function(req){ var accountInfo = req.body; console.log(accountInfo); var text= '<div style="border: solid thin black; padding: 10px;"><div style="background: #25a2dc; color: #fff; padding: 5px"><img src="http://searchtrade.com/images/searchtrade_white.png" width="200px"></div><br><br><div style="background: #fff; color: #000; padding: 5px;"><div style="width:75%; margin: auto"><p>Hi '+accountInfo.first_name+' '+accountInfo.last_name+',</p><br><p>This is a confirmation mail that you have successfully changed your password</p><br><p>You can log into your account with your new password.</p><br><p>Regards the from SearchTrade team</p><br><p>Product of Searchtrade.com Pte Ltd, Singapore</p></div></div></div></div>'; // Setup e-mail data with unicode symbols var mailOptions = { from: 'Search Trade <donotreply@searchtrade.com>', // Sender address to: accountInfo.email, // list of receivers subject: "Search Trade: Password Reset Confirmation", // Subject line text: text, // Text html: text }; mailer.sendmail(mailOptions, function(){ if (true) { console.log('mail callback success'); var mailStatus = true; } else{ console.log('mail callback fails'); var mailStatus = false; } return mailStatus }); } module.exports.getMyNotification = function(req,res){ var user_id = req.body.user_id; notificationschema.notification_wallet .find({'user_id':user_id}) .populate('user_id') .exec(function(err, results){ if (err) {throw err}; console.log(results); res.send(results); }); } // module.exports.populate = function(req,res){ // var user_id = req.body.user_id; // // notification_wallet.user_id // notificationschema.notification_msg // .find({'user_id':user_id}) // // .populate('notification_msg.notification_body') // .populate('read,created_at,notification_body,user_id,first_name,last_name') // .exec(function(err, results){ // if (err) {throw err}; // console.log(results); // res.send(results); // }); // }
rihbyne/notification-wallet
api/notification.js
JavaScript
bsd-3-clause
9,387
/* Javascript plotting library for jQuery, v. 0.5. * * Released under the MIT license by IOLA, December 2007. * */ (function($) { function Plot(target, data_, options_, plugins) { // data is on the form: // [ series1, series2 ... ] // where series is either just the data as [ [x1, y1], [x2, y2], ... ] // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } var series = [], options = { // the color theme used for graphs colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"], legend: { show: true, noColumns: 1, // number of colums in legend table labelFormatter: null, // fn: string -> string labelBoxBorderColor: "#ccc", // border color for the little label boxes container: null, // container (as jQuery object) to put legend in, null means default on top of graph position: "ne", // position of default legend container within plot margin: 5, // distance from grid edge to default legend container within plot backgroundColor: null, // null means auto-detect backgroundOpacity: 0.85 // set to 0 to avoid background }, xaxis: { mode: null, // null or "time" min: null, // min. value to show, null means set automatically max: null, // max. value to show, null means set automatically autoscaleMargin: null, // margin in % to add if auto-setting min/max ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks tickFormatter: null, // fn: number -> string labelWidth: null, // size of tick labels in pixels labelHeight: null, // mode specific options tickDecimals: null, // no. of decimals, null means auto tickSize: null, // number or [number, "unit"] minTickSize: null, // number or [number, "unit"] monthNames: null, // list of names of months timeformat: null // format string to use }, yaxis: { autoscaleMargin: 0.02 }, x2axis: { autoscaleMargin: null }, y2axis: { autoscaleMargin: 0.02 }, series: { points: { show: false, radius: 3, lineWidth: 2, // in pixels fill: true, fillColor: "#ffffff" }, lines: { // we don't put in show: false so we can see // whether lines were actively disabled lineWidth: 2, // in pixels fill: false, fillColor: null, steps: false }, bars: { show: false, lineWidth: 2, // in pixels barWidth: 1, // in units of the x axis fill: true, fillColor: null, align: "left", // or "center" horizontal: false // when horizontal, left is now top }, shadowSize: 3 }, grid: { color: "#545454", // primary color used for outline and labels backgroundColor: null, // null for transparent, else color tickColor: "#dddddd", // color used for the ticks labelMargin: 5, // in pixels borderWidth: 2, // in pixels borderColor: null, // set if different from the grid color markings: null, // array of ranges or fn: axes -> array of ranges markingsColor: "#f4f4f4", markingsLineWidth: 2, // interactive stuff clickable: false, hoverable: false, autoHighlight: true, // highlight in case mouse is near mouseActiveRadius: 10 // how far the mouse can be away to activate an item }, selection: { mode: null, // one of null, "x", "y" or "xy" color: "#e8cfac" } }, canvas = null, // the canvas for the plot itself overlay = null, // canvas for interactive stuff on top of plot eventHolder = null, // jQuery object that events should be bound to ctx = null, octx = null, axes = { xaxis: {}, yaxis: {}, x2axis: {}, y2axis: {} }, plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, canvasWidth = 0, canvasHeight = 0, plotWidth = 0, plotHeight = 0, hooks = { processOptions: [], processRawData: [], processDatapoints: [], bindEvents: [], drawOverlay: [] }, plot = this, // dedicated to storing data for buggy standard compliance cases workarounds = {}; // public functions plot.setData = setData; plot.setupGrid = setupGrid; plot.draw = draw; plot.clearSelection = clearSelection; plot.setSelection = setSelection; plot.getSelection = getSelection; plot.getCanvas = function() { return canvas; }; plot.getPlotOffset = function() { return plotOffset; }; plot.width = function () { return plotWidth; } plot.height = function () { return plotHeight; } plot.offset = function () { var o = eventHolder.offset(); o.left += plotOffset.left; o.top += plotOffset.top; return o; }; plot.getData = function() { return series; }; plot.getAxes = function() { return axes; }; plot.getOptions = function() { return options; }; plot.highlight = highlight; plot.unhighlight = unhighlight; plot.triggerRedrawOverlay = triggerRedrawOverlay; // public attributes plot.hooks = hooks; // initialize initPlugins(plot); parseOptions(options_); constructCanvas(); setData(data_); setupGrid(); draw(); bindEvents(); function executeHooks(hook, args) { args = [plot].concat(args); for (var i = 0; i < hook.length; ++i) hook[i].apply(this, args); } function initPlugins() { for (var i = 0; i < plugins.length; ++i) { var p = plugins[i]; p.init(plot); if (p.options) $.extend(true, options, p.options); } } function parseOptions(opts) { $.extend(true, options, opts); if (options.grid.borderColor == null) options.grid.borderColor = options.grid.color // backwards compatibility, to be removed in future if (options.xaxis.noTicks && options.xaxis.ticks == null) options.xaxis.ticks = options.xaxis.noTicks; if (options.yaxis.noTicks && options.yaxis.ticks == null) options.yaxis.ticks = options.yaxis.noTicks; if (options.grid.coloredAreas) options.grid.markings = options.grid.coloredAreas; if (options.grid.coloredAreasColor) options.grid.markingsColor = options.grid.coloredAreasColor; if (options.lines) $.extend(true, options.series.lines, options.lines); if (options.points) $.extend(true, options.series.points, options.points); if (options.bars) $.extend(true, options.series.bars, options.bars); if (options.shadowSize) options.series.shadowSize = options.shadowSize; executeHooks(hooks.processOptions, [options]); } function setData(d) { series = parseData(d); fillInSeriesOptions(); processData(); } function parseData(d) { var res = []; for (var i = 0; i < d.length; ++i) { var s = $.extend(true, {}, options.series); if (d[i].data) { s.data = d[i].data; // move the data instead of deep-copy delete d[i].data; $.extend(true, s, d[i]); d[i].data = s.data; } else s.data = d[i]; res.push(s); } return res; } function fillInSeriesOptions() { var i; // collect what we already got of colors var neededColors = series.length, usedColors = [], assignedColors = []; for (i = 0; i < series.length; ++i) { var sc = series[i].color; if (sc != null) { --neededColors; if (typeof sc == "number") assignedColors.push(sc); else usedColors.push(parseColor(series[i].color)); } } // we might need to generate more colors if higher indices // are assigned for (i = 0; i < assignedColors.length; ++i) { neededColors = Math.max(neededColors, assignedColors[i] + 1); } // produce colors as needed var colors = [], variation = 0; i = 0; while (colors.length < neededColors) { var c; if (options.colors.length == i) // check degenerate case c = new Color(100, 100, 100); else c = parseColor(options.colors[i]); // vary color if needed var sign = variation % 2 == 1 ? -1 : 1; var factor = 1 + sign * Math.ceil(variation / 2) * 0.2; c.scale(factor, factor, factor); // FIXME: if we're getting to close to something else, // we should probably skip this one colors.push(c); ++i; if (i >= options.colors.length) { i = 0; ++variation; } } // fill in the options var colori = 0, s; for (i = 0; i < series.length; ++i) { s = series[i]; // assign colors if (s.color == null) { s.color = colors[colori].toString(); ++colori; } else if (typeof s.color == "number") s.color = colors[s.color].toString(); // turn on lines automatically in case nothing is set if (s.lines.show == null && !s.bars.show && !s.points.show) s.lines.show = true; // setup axes if (!s.xaxis) s.xaxis = axes.xaxis; if (s.xaxis == 1) s.xaxis = axes.xaxis; else if (s.xaxis == 2) s.xaxis = axes.x2axis; if (!s.yaxis) s.yaxis = axes.yaxis; if (s.yaxis == 1) s.yaxis = axes.yaxis; else if (s.yaxis == 2) s.yaxis = axes.y2axis; } } function processData() { var topSentry = Number.POSITIVE_INFINITY, bottomSentry = Number.NEGATIVE_INFINITY, i, j, k, m, length, s, points, ps, x, y; for (axis in axes) { axes[axis].datamin = topSentry; axes[axis].datamax = bottomSentry; axes[axis].min = options[axis].min; axes[axis].max = options[axis].max; axes[axis].used = false; } function updateAxis(axis, min, max) { if (min < axis.datamin) axis.datamin = min; if (max > axis.datamax) axis.datamax = max; } for (i = 0; i < series.length; ++i) { s = series[i]; s.datapoints = { points: [] }; executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); } // first pass: clean and copy data for (i = 0; i < series.length; ++i) { s = series[i]; if (s.datapoints.pointsize != null) continue; // already filled in var data = s.data, format = [], p; // determine the point size if (s.bars.show) { s.datapoints.pointsize = 3; format.push({ d: 0 }); } else s.datapoints.pointsize = 2; /* // examine data to find out how to copy for (j = 0; j < data.length; ++j) { }*/ ps = s.datapoints.pointsize; points = s.datapoints.points; insertSteps = s.lines.show && s.lines.steps; s.xaxis.used = s.yaxis.used = true; for (j = k = 0; j < data.length; ++j, k += ps) { p = data[j]; if (p != null) { x = p[0]; y = p[1]; } else y = x = null; if (x != null) { x = +x; // convert to number if (isNaN(x)) x = null; } if (y != null) { y = +y; // convert to number if (isNaN(y)) y = null; } // check validity of point, making sure both are cleared if (x == null && y != null) { // extract min/max info before we whack updateAxis(s.yaxis, y, y); y = null; } if (y == null && x != null) { updateAxis(s.xaxis, x, x); x = null; } if (insertSteps && x != null && k > 0 && points[k - ps] != null && points[k - ps] != x && points[k - ps + 1] != y) { points[k + 1] = points[k - ps + 1]; points[k] = x; // copy the remainding from real point for (m = 2; m < ps; ++m) points[k + m] = p[m] == null ? format[m-2].d : p[m]; k += ps; } for (m = 2; m < ps; ++m) points[k + m] = p == null || p[m] == null ? format[m-2].d : p[m]; points[k] = x; points[k + 1] = y; } } for (i = 0; i < series.length; ++i) { s = series[i]; executeHooks(hooks.processDatapoints, [ s, s.datapoints]); } // second pass: find datamax/datamin for auto-scaling for (i = 0; i < series.length; ++i) { s = series[i]; points = s.datapoints.points, ps = s.datapoints.pointsize; var xmin = topSentry, ymin = topSentry, xmax = bottomSentry, ymax = bottomSentry; for (j = 0; j < points.length; j += ps) { x = points[j]; if (x == null) continue; if (x < xmin) xmin = x; if (x > xmax) xmax = x; y = points[j + 1]; if (y < ymin) ymin = y; if (y > ymax) ymax = y; } if (s.bars.show) { // make sure we got room for the bar on the dancing floor var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2; if (s.bars.horizontal) { ymin += delta; ymax += delta + s.bars.barWidth; } else { xmin += delta; xmax += delta + s.bars.barWidth; } } updateAxis(s.xaxis, xmin, xmax); updateAxis(s.yaxis, ymin, ymax); } } function constructCanvas() { function makeCanvas(width, height) { var c = document.createElement('canvas'); c.width = width; c.height = height; if ($.browser.msie) // excanvas hack c = window.G_vmlCanvasManager.initElement(c); return c; } canvasWidth = target.width(); canvasHeight = target.height(); target.html(""); // clear target if (target.css("position") == 'static') target.css("position", "relative"); // for positioning labels and overlay if (canvasWidth <= 0 || canvasHeight <= 0) throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight; if ($.browser.msie) // excanvas hack window.G_vmlCanvasManager.init_(document); // make sure everything is setup // the canvas canvas = $(makeCanvas(canvasWidth, canvasHeight)).appendTo(target).get(0); ctx = canvas.getContext("2d"); // overlay canvas for interactive features overlay = $(makeCanvas(canvasWidth, canvasHeight)).css({ position: 'absolute', left: 0, top: 0 }).appendTo(target).get(0); octx = overlay.getContext("2d"); octx.stroke(); } function bindEvents() { // we include the canvas in the event holder too, because IE 7 // sometimes has trouble with the stacking order eventHolder = $([overlay, canvas]); // bind events if (options.selection.mode != null || options.grid.hoverable) eventHolder.mousemove(onMouseMove); if (options.selection.mode != null) eventHolder.mousedown(onMouseDown); if (options.grid.clickable) eventHolder.click(onClick); executeHooks(hooks.bindEvents, [eventHolder]); } function setupGrid() { function setupAxis(axis, options) { setRange(axis, options); prepareTickGeneration(axis, options); setTicks(axis, options); // add transformation helpers if (axis == axes.xaxis || axis == axes.x2axis) { // data point to canvas coordinate axis.p2c = function (p) { return (p - axis.min) * axis.scale; }; // canvas coordinate to data point axis.c2p = function (c) { return axis.min + c / axis.scale; }; } else { axis.p2c = function (p) { return (axis.max - p) * axis.scale; }; axis.c2p = function (p) { return axis.max - p / axis.scale; }; } } for (var axis in axes) setupAxis(axes[axis], options[axis]); setSpacing(); insertLabels(); insertLegend(); } function setRange(axis, axisOptions) { var min = axisOptions.min != null ? +axisOptions.min : axis.datamin, max = axisOptions.max != null ? +axisOptions.max : axis.datamax; // degenerate case if (min == Number.POSITIVE_INFINITY) min = 0; if (max == Number.NEGATIVE_INFINITY) max = 1; if (max - min == 0.0) { // degenerate case var widen = max == 0 ? 1 : 0.01; if (axisOptions.min == null) min -= widen; // alway widen max if we couldn't widen min to ensure we // don't fall into min == max which doesn't work if (axisOptions.max == null || axisOptions.min != null) max += widen; } else { // consider autoscaling var margin = axisOptions.autoscaleMargin; if (margin != null) { if (axisOptions.min == null) { min -= (max - min) * margin; // make sure we don't go below zero if all values // are positive if (min < 0 && axis.datamin >= 0) min = 0; } if (axisOptions.max == null) { max += (max - min) * margin; if (max > 0 && axis.datamax <= 0) max = 0; } } } axis.min = min; axis.max = max; } function prepareTickGeneration(axis, axisOptions) { // estimate number of ticks var noTicks; if (typeof axisOptions.ticks == "number" && axisOptions.ticks > 0) noTicks = axisOptions.ticks; else if (axis == axes.xaxis || axis == axes.x2axis) noTicks = canvasWidth / 100; else noTicks = canvasHeight / 60; var delta = (axis.max - axis.min) / noTicks; var size, generator, unit, formatter, i, magn, norm; if (axisOptions.mode == "time") { // pretty handling of time // map of app. size of time units in milliseconds var timeUnitSize = { "second": 1000, "minute": 60 * 1000, "hour": 60 * 60 * 1000, "day": 24 * 60 * 60 * 1000, "month": 30 * 24 * 60 * 60 * 1000, "year": 365.2425 * 24 * 60 * 60 * 1000 }; // the allowed tick sizes, after 1 year we use // an integer algorithm var spec = [ [1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"], [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"], [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"], [1, "day"], [2, "day"], [3, "day"], [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"], [3, "month"], [6, "month"], [1, "year"] ]; var minSize = 0; if (axisOptions.minTickSize != null) { if (typeof axisOptions.tickSize == "number") minSize = axisOptions.tickSize; else minSize = axisOptions.minTickSize[0] * timeUnitSize[axisOptions.minTickSize[1]]; } for (i = 0; i < spec.length - 1; ++i) if (delta < (spec[i][0] * timeUnitSize[spec[i][1]] + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) break; size = spec[i][0]; unit = spec[i][1]; // special-case the possibility of several years if (unit == "year") { magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10)); norm = (delta / timeUnitSize.year) / magn; if (norm < 1.5) size = 1; else if (norm < 3) size = 2; else if (norm < 7.5) size = 5; else size = 10; size *= magn; } if (axisOptions.tickSize) { size = axisOptions.tickSize[0]; unit = axisOptions.tickSize[1]; } generator = function(axis) { var ticks = [], tickSize = axis.tickSize[0], unit = axis.tickSize[1], d = new Date(axis.min); var step = tickSize * timeUnitSize[unit]; if (unit == "second") d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize)); if (unit == "minute") d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize)); if (unit == "hour") d.setUTCHours(floorInBase(d.getUTCHours(), tickSize)); if (unit == "month") d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize)); if (unit == "year") d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize)); // reset smaller components d.setUTCMilliseconds(0); if (step >= timeUnitSize.minute) d.setUTCSeconds(0); if (step >= timeUnitSize.hour) d.setUTCMinutes(0); if (step >= timeUnitSize.day) d.setUTCHours(0); if (step >= timeUnitSize.day * 4) d.setUTCDate(1); if (step >= timeUnitSize.year) d.setUTCMonth(0); var carry = 0, v = Number.NaN, prev; do { prev = v; v = d.getTime(); ticks.push({ v: v, label: axis.tickFormatter(v, axis) }); if (unit == "month") { if (tickSize < 1) { // a bit complicated - we'll divide the month // up but we need to take care of fractions // so we don't end up in the middle of a day d.setUTCDate(1); var start = d.getTime(); d.setUTCMonth(d.getUTCMonth() + 1); var end = d.getTime(); d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); carry = d.getUTCHours(); d.setUTCHours(0); } else d.setUTCMonth(d.getUTCMonth() + tickSize); } else if (unit == "year") { d.setUTCFullYear(d.getUTCFullYear() + tickSize); } else d.setTime(v + step); } while (v < axis.max && v != prev); return ticks; }; formatter = function (v, axis) { var d = new Date(v); // first check global format if (axisOptions.timeformat != null) return $.plot.formatDate(d, axisOptions.timeformat, axisOptions.monthNames); var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; var span = axis.max - axis.min; if (t < timeUnitSize.minute) fmt = "%h:%M:%S"; else if (t < timeUnitSize.day) { if (span < 2 * timeUnitSize.day) fmt = "%h:%M"; else fmt = "%b %d %h:%M"; } else if (t < timeUnitSize.month) fmt = "%b %d"; else if (t < timeUnitSize.year) { if (span < timeUnitSize.year) fmt = "%b"; else fmt = "%b %y"; } else fmt = "%y"; return $.plot.formatDate(d, fmt, axisOptions.monthNames); }; } else { // pretty rounding of base-10 numbers var maxDec = axisOptions.tickDecimals; var dec = -Math.floor(Math.log(delta) / Math.LN10); if (maxDec != null && dec > maxDec) dec = maxDec; magn = Math.pow(10, -dec); norm = delta / magn; // norm is between 1.0 and 10.0 if (norm < 1.5) size = 1; else if (norm < 3) { size = 2; // special case for 2.5, requires an extra decimal if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { size = 2.5; ++dec; } } else if (norm < 7.5) size = 5; else size = 10; size *= magn; if (axisOptions.minTickSize != null && size < axisOptions.minTickSize) size = axisOptions.minTickSize; if (axisOptions.tickSize != null) size = axisOptions.tickSize; axis.tickDecimals = Math.max(0, (maxDec != null) ? maxDec : dec); generator = function (axis) { var ticks = []; // spew out all possible ticks var start = floorInBase(axis.min, axis.tickSize), i = 0, v = Number.NaN, prev; do { prev = v; v = start + i * axis.tickSize; ticks.push({ v: v, label: axis.tickFormatter(v, axis) }); ++i; } while (v < axis.max && v != prev); return ticks; }; formatter = function (v, axis) { return v.toFixed(axis.tickDecimals); }; } axis.tickSize = unit ? [size, unit] : size; axis.tickGenerator = generator; if ($.isFunction(axisOptions.tickFormatter)) axis.tickFormatter = function (v, axis) { return "" + axisOptions.tickFormatter(v, axis); }; else axis.tickFormatter = formatter; if (axisOptions.labelWidth != null) axis.labelWidth = axisOptions.labelWidth; if (axisOptions.labelHeight != null) axis.labelHeight = axisOptions.labelHeight; } function setTicks(axis, axisOptions) { axis.ticks = []; if (!axis.used) return; if (axisOptions.ticks == null) axis.ticks = axis.tickGenerator(axis); else if (typeof axisOptions.ticks == "number") { if (axisOptions.ticks > 0) axis.ticks = axis.tickGenerator(axis); } else if (axisOptions.ticks) { var ticks = axisOptions.ticks; if ($.isFunction(ticks)) // generate the ticks ticks = ticks({ min: axis.min, max: axis.max }); // clean up the user-supplied ticks, copy them over var i, v; for (i = 0; i < ticks.length; ++i) { var label = null; var t = ticks[i]; if (typeof t == "object") { v = t[0]; if (t.length > 1) label = t[1]; } else v = t; if (label == null) label = axis.tickFormatter(v, axis); axis.ticks[i] = { v: v, label: label }; } } if (axisOptions.autoscaleMargin != null && axis.ticks.length > 0) { // snap to ticks if (axisOptions.min == null) axis.min = Math.min(axis.min, axis.ticks[0].v); if (axisOptions.max == null && axis.ticks.length > 1) axis.max = Math.min(axis.max, axis.ticks[axis.ticks.length - 1].v); } } function setSpacing() { function measureXLabels(axis) { // to avoid measuring the widths of the labels, we // construct fixed-size boxes and put the labels inside // them, we don't need the exact figures and the // fixed-size box content is easy to center if (axis.labelWidth == null) axis.labelWidth = canvasWidth / 6; // measure x label heights if (axis.labelHeight == null) { labels = []; for (i = 0; i < axis.ticks.length; ++i) { l = axis.ticks[i].label; if (l) labels.push('<div class="tickLabel" style="float:left;width:' + axis.labelWidth + 'px">' + l + '</div>'); } axis.labelHeight = 0; if (labels.length > 0) { var dummyDiv = $('<div style="position:absolute;top:-10000px;width:10000px;font-size:smaller">' + labels.join("") + '<div style="clear:left"></div></div>').appendTo(target); axis.labelHeight = dummyDiv.height(); dummyDiv.remove(); } } } function measureYLabels(axis) { if (axis.labelWidth == null || axis.labelHeight == null) { var i, labels = [], l; // calculate y label dimensions for (i = 0; i < axis.ticks.length; ++i) { l = axis.ticks[i].label; if (l) labels.push('<div class="tickLabel">' + l + '</div>'); } if (labels.length > 0) { var dummyDiv = $('<div style="position:absolute;top:-10000px;font-size:smaller">' + labels.join("") + '</div>').appendTo(target); if (axis.labelWidth == null) axis.labelWidth = dummyDiv.width(); if (axis.labelHeight == null) axis.labelHeight = dummyDiv.find("div").height(); dummyDiv.remove(); } if (axis.labelWidth == null) axis.labelWidth = 0; if (axis.labelHeight == null) axis.labelHeight = 0; } } measureXLabels(axes.xaxis); measureYLabels(axes.yaxis); measureXLabels(axes.x2axis); measureYLabels(axes.y2axis); // get the most space needed around the grid for things // that may stick out var maxOutset = options.grid.borderWidth; for (i = 0; i < series.length; ++i) maxOutset = Math.max(maxOutset, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = maxOutset; var margin = options.grid.labelMargin + options.grid.borderWidth; if (axes.xaxis.labelHeight > 0) plotOffset.bottom = Math.max(maxOutset, axes.xaxis.labelHeight + margin); if (axes.yaxis.labelWidth > 0) plotOffset.left = Math.max(maxOutset, axes.yaxis.labelWidth + margin); if (axes.x2axis.labelHeight > 0) plotOffset.top = Math.max(maxOutset, axes.x2axis.labelHeight + margin); if (axes.y2axis.labelWidth > 0) plotOffset.right = Math.max(maxOutset, axes.y2axis.labelWidth + margin); plotWidth = canvasWidth - plotOffset.left - plotOffset.right; plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top; // precompute how much the axis is scaling a point in canvas space axes.xaxis.scale = plotWidth / (axes.xaxis.max - axes.xaxis.min); axes.yaxis.scale = plotHeight / (axes.yaxis.max - axes.yaxis.min); axes.x2axis.scale = plotWidth / (axes.x2axis.max - axes.x2axis.min); axes.y2axis.scale = plotHeight / (axes.y2axis.max - axes.y2axis.min); } function draw() { drawGrid(); for (var i = 0; i < series.length; ++i) drawSeries(series[i]); } function extractRange(ranges, coord) { var firstAxis = coord + "axis", secondaryAxis = coord + "2axis", axis, from, to, reverse; if (ranges[firstAxis]) { axis = axes[firstAxis]; from = ranges[firstAxis].from; to = ranges[firstAxis].to; } else if (ranges[secondaryAxis]) { axis = axes[secondaryAxis]; from = ranges[secondaryAxis].from; to = ranges[secondaryAxis].to; } else { // backwards-compat stuff - to be removed in future axis = axes[firstAxis]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) return { from: to, to: from, axis: axis }; return { from: from, to: to, axis: axis }; } function drawGrid() { var i; ctx.save(); ctx.clearRect(0, 0, canvasWidth, canvasHeight); ctx.translate(plotOffset.left, plotOffset.top); // draw background, if any if (options.grid.backgroundColor) { ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)"); ctx.fillRect(0, 0, plotWidth, plotHeight); } // draw markings var markings = options.grid.markings; if (markings) { if ($.isFunction(markings)) // xmin etc. are backwards-compatible, to be removed in future markings = markings({ xmin: axes.xaxis.min, xmax: axes.xaxis.max, ymin: axes.yaxis.min, ymax: axes.yaxis.max, xaxis: axes.xaxis, yaxis: axes.yaxis, x2axis: axes.x2axis, y2axis: axes.y2axis }); for (i = 0; i < markings.length; ++i) { var m = markings[i], xrange = extractRange(m, "x"), yrange = extractRange(m, "y"); // fill in missing if (xrange.from == null) xrange.from = xrange.axis.min; if (xrange.to == null) xrange.to = xrange.axis.max; if (yrange.from == null) yrange.from = yrange.axis.min; if (yrange.to == null) yrange.to = yrange.axis.max; // clip if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max || yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) continue; xrange.from = Math.max(xrange.from, xrange.axis.min); xrange.to = Math.min(xrange.to, xrange.axis.max); yrange.from = Math.max(yrange.from, yrange.axis.min); yrange.to = Math.min(yrange.to, yrange.axis.max); if (xrange.from == xrange.to && yrange.from == yrange.to) continue; // then draw xrange.from = xrange.axis.p2c(xrange.from); xrange.to = xrange.axis.p2c(xrange.to); yrange.from = yrange.axis.p2c(yrange.from); yrange.to = yrange.axis.p2c(yrange.to); if (xrange.from == xrange.to || yrange.from == yrange.to) { // draw line ctx.strokeStyle = m.color || options.grid.markingsColor; ctx.beginPath(); ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; //ctx.moveTo(Math.floor(xrange.from), yrange.from); //ctx.lineTo(Math.floor(xrange.to), yrange.to); ctx.moveTo(xrange.from, yrange.from); ctx.lineTo(xrange.to, yrange.to); ctx.stroke(); } else { // fill area ctx.fillStyle = m.color || options.grid.markingsColor; ctx.fillRect(xrange.from, yrange.to, xrange.to - xrange.from, yrange.from - yrange.to); } } } // draw the inner grid ctx.lineWidth = 1; ctx.strokeStyle = options.grid.tickColor; ctx.beginPath(); var v, axis = axes.xaxis; for (i = 0; i < axis.ticks.length; ++i) { v = axis.ticks[i].v; if (v <= axis.min || v >= axes.xaxis.max) continue; // skip those lying on the axes ctx.moveTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, 0); ctx.lineTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, plotHeight); } axis = axes.yaxis; for (i = 0; i < axis.ticks.length; ++i) { v = axis.ticks[i].v; if (v <= axis.min || v >= axis.max) continue; ctx.moveTo(0, Math.floor(axis.p2c(v)) + ctx.lineWidth/2); ctx.lineTo(plotWidth, Math.floor(axis.p2c(v)) + ctx.lineWidth/2); } axis = axes.x2axis; for (i = 0; i < axis.ticks.length; ++i) { v = axis.ticks[i].v; if (v <= axis.min || v >= axis.max) continue; ctx.moveTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, -5); ctx.lineTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, 5); } axis = axes.y2axis; for (i = 0; i < axis.ticks.length; ++i) { v = axis.ticks[i].v; if (v <= axis.min || v >= axis.max) continue; ctx.moveTo(plotWidth-5, Math.floor(axis.p2c(v)) + ctx.lineWidth/2); ctx.lineTo(plotWidth+5, Math.floor(axis.p2c(v)) + ctx.lineWidth/2); } ctx.stroke(); if (options.grid.borderWidth) { // draw border var bw = options.grid.borderWidth; ctx.lineWidth = bw; ctx.strokeStyle = options.grid.borderColor; ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw); } ctx.restore(); } function insertLabels() { target.find(".tickLabels").remove(); var html = ['<div class="tickLabels" style="font-size:smaller;color:' + options.grid.color + '">']; function addLabels(axis, labelGenerator) { for (var i = 0; i < axis.ticks.length; ++i) { var tick = axis.ticks[i]; if (!tick.label || tick.v < axis.min || tick.v > axis.max) continue; html.push(labelGenerator(tick, axis)); } } var margin = options.grid.labelMargin + options.grid.borderWidth; addLabels(axes.xaxis, function (tick, axis) { return '<div style="position:absolute;top:' + (plotOffset.top + plotHeight + margin) + 'px;left:' + Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2) + 'px;width:' + axis.labelWidth + 'px;text-align:center" class="tickLabel">' + tick.label + "</div>"; }); addLabels(axes.yaxis, function (tick, axis) { return '<div style="position:absolute;top:' + Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2) + 'px;right:' + (plotOffset.right + plotWidth + margin) + 'px;width:' + axis.labelWidth + 'px;text-align:right" class="tickLabel">' + tick.label + "</div>"; }); addLabels(axes.x2axis, function (tick, axis) { return '<div style="position:absolute;bottom:' + (plotOffset.bottom + plotHeight + margin) + 'px;left:' + Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2) + 'px;width:' + axis.labelWidth + 'px;text-align:center" class="tickLabel">' + tick.label + "</div>"; }); addLabels(axes.y2axis, function (tick, axis) { return '<div style="position:absolute;top:' + Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2) + 'px;left:' + (plotOffset.left + plotWidth + margin) +'px;width:' + axis.labelWidth + 'px;text-align:left" class="tickLabel">' + tick.label + "</div>"; }); html.push('</div>'); target.append(html.join("")); } function drawSeries(series) { if (series.lines.show) drawSeriesLines(series); if (series.bars.show) drawSeriesBars(series); if (series.points.show) drawSeriesPoints(series); } function drawSeriesLines(series) { function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, prevx = null, prevy = null; ctx.beginPath(); for (var i = ps; i < points.length; i += ps) { var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; if (x1 == null || x2 == null) continue; // clip with ymin if (y1 <= y2 && y1 < axisy.min) { if (y2 < axisy.min) continue; // line segment is outside // compute new intersection point x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min) { if (y1 < axisy.min) continue; x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max) { if (y2 > axisy.max) continue; x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max) { if (y1 > axisy.max) continue; x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (x1 != prevx || y1 != prevy) ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset); prevx = x2; prevy = y2; ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset); } ctx.stroke(); } function plotLineArea(datapoints, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, bottom = Math.min(Math.max(0, axisy.min), axisy.max), top, lastX = 0, areaOpen = false; for (var i = ps; i < points.length; i += ps) { var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; if (areaOpen && x1 != null && x2 == null) { // close area ctx.lineTo(axisx.p2c(lastX), axisy.p2c(bottom)); ctx.fill(); areaOpen = false; continue; } if (x1 == null || x2 == null) continue; // clip x values // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (!areaOpen) { // open area ctx.beginPath(); ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom)); areaOpen = true; } // now first check the case where both is outside if (y1 >= axisy.max && y2 >= axisy.max) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max)); lastX = x2; continue; } else if (y1 <= axisy.min && y2 <= axisy.min) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min)); lastX = x2; continue; } // else it's a bit more complicated, there might // be two rectangles and two triangles we need to fill // in; to find these keep track of the current x values var x1old = x1, x2old = x2; // and clip the y values, without shortcutting // clip with ymin if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) { x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) { x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) { x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // if the x value was changed we got a rectangle // to fill if (x1 != x1old) { if (y1 <= axisy.min) top = axisy.min; else top = axisy.max; ctx.lineTo(axisx.p2c(x1old), axisy.p2c(top)); ctx.lineTo(axisx.p2c(x1), axisy.p2c(top)); } // fill the triangles ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); // fill the other rectangle if it's there if (x2 != x2old) { if (y2 <= axisy.min) top = axisy.min; else top = axisy.max; ctx.lineTo(axisx.p2c(x2), axisy.p2c(top)); ctx.lineTo(axisx.p2c(x2old), axisy.p2c(top)); } lastX = Math.max(x2, x2old); } if (areaOpen) { ctx.lineTo(axisx.p2c(lastX), axisy.p2c(bottom)); ctx.fill(); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.lineJoin = "round"; var lw = series.lines.lineWidth, sw = series.shadowSize; // FIXME: consider another form of shadow when filling is turned on if (lw > 0 && sw > 0) { // draw shadow as a thick and thin line with transparency ctx.lineWidth = sw; ctx.strokeStyle = "rgba(0,0,0,0.1)"; var xoffset = 1; plotLine(series.datapoints, xoffset, Math.sqrt((lw/2 + sw/2)*(lw/2 + sw/2) - xoffset*xoffset), series.xaxis, series.yaxis); ctx.lineWidth = sw/2; plotLine(series.datapoints, xoffset, Math.sqrt((lw/2 + sw/4)*(lw/2 + sw/4) - xoffset*xoffset), series.xaxis, series.yaxis); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight); if (fillStyle) { ctx.fillStyle = fillStyle; plotLineArea(series.datapoints, series.xaxis, series.yaxis); } if (lw > 0) plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis); ctx.restore(); } function drawSeriesPoints(series) { function plotPoints(datapoints, radius, fillStyle, offset, circumference, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var x = points[i], y = points[i + 1]; if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue; ctx.beginPath(); ctx.arc(axisx.p2c(x), axisy.p2c(y) + offset, radius, 0, circumference, true); if (fillStyle) { ctx.fillStyle = fillStyle; ctx.fill(); } ctx.stroke(); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var lw = series.lines.lineWidth, sw = series.shadowSize, radius = series.points.radius; if (lw > 0 && sw > 0) { // draw shadow in two steps var w = sw / 2; ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; plotPoints(series.datapoints, radius, null, w + w/2, 2 * Math.PI, series.xaxis, series.yaxis); ctx.strokeStyle = "rgba(0,0,0,0.2)"; plotPoints(series.datapoints, radius, null, w/2, 2 * Math.PI, series.xaxis, series.yaxis); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; plotPoints(series.datapoints, radius, getFillStyle(series.points, series.color), 0, 2 * Math.PI, series.xaxis, series.yaxis); ctx.restore(); } function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal) { var left, right, bottom, top, drawLeft, drawRight, drawTop, drawBottom, tmp; if (horizontal) { drawBottom = drawRight = drawTop = true; drawLeft = false; left = b; right = x; top = y + barLeft; bottom = y + barRight; // account for negative bars if (right < left) { tmp = right; right = left; left = tmp; drawLeft = true; drawRight = false; } } else { drawLeft = drawRight = drawTop = true; drawBottom = false; left = x + barLeft; right = x + barRight; bottom = b; top = y; // account for negative bars if (top < bottom) { tmp = top; top = bottom; bottom = tmp; drawBottom = true; drawTop = false; } } // clip if (right < axisx.min || left > axisx.max || top < axisy.min || bottom > axisy.max) return; if (left < axisx.min) { left = axisx.min; drawLeft = false; } if (right > axisx.max) { right = axisx.max; drawRight = false; } if (bottom < axisy.min) { bottom = axisy.min; drawBottom = false; } if (top > axisy.max) { top = axisy.max; drawTop = false; } left = axisx.p2c(left); bottom = axisy.p2c(bottom); right = axisx.p2c(right); top = axisy.p2c(top); // fill the bar if (fillStyleCallback) { c.beginPath(); c.moveTo(left, bottom); c.lineTo(left, top); c.lineTo(right, top); c.lineTo(right, bottom); c.fillStyle = fillStyleCallback(bottom, top); c.fill(); } // draw outline if (drawLeft || drawRight || drawTop || drawBottom) { c.beginPath(); // FIXME: inline moveTo is buggy with excanvas c.moveTo(left, bottom + offset); if (drawLeft) c.lineTo(left, top + offset); else c.moveTo(left, top + offset); if (drawTop) c.lineTo(right, top + offset); else c.moveTo(right, top + offset); if (drawRight) c.lineTo(right, bottom + offset); else c.moveTo(right, bottom + offset); if (drawBottom) c.lineTo(left, bottom + offset); else c.moveTo(left, bottom + offset); c.stroke(); } } function drawSeriesBars(series) { function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // FIXME: figure out a way to add shadows (for instance along the right edge) ctx.lineWidth = series.bars.lineWidth; ctx.strokeStyle = series.color; var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null; plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis); ctx.restore(); } function getFillStyle(filloptions, seriesColor, bottom, top) { var fill = filloptions.fill; if (!fill) return null; if (filloptions.fillColor) return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); var c = parseColor(seriesColor); c.a = typeof fill == "number" ? fill : 0.4; c.normalize(); return c.toString(); } function insertLegend() { target.find(".legend").remove(); if (!options.legend.show) return; var fragments = [], rowStarted = false, lf = options.legend.labelFormatter, s, label; for (i = 0; i < series.length; ++i) { s = series[i]; label = s.label; if (!label) continue; if (i % options.legend.noColumns == 0) { if (rowStarted) fragments.push('</tr>'); fragments.push('<tr>'); rowStarted = true; } if (lf) label = lf(label, s); fragments.push( '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + s.color + ';overflow:hidden"></div></div></td>' + '<td class="legendLabel">' + label + '</td>'); } if (rowStarted) fragments.push('</tr>'); if (fragments.length == 0) return; var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>'; if (options.legend.container != null) $(options.legend.container).html(table); else { var pos = "", p = options.legend.position, m = options.legend.margin; if (m[0] == null) m = [m, m]; if (p.charAt(0) == "n") pos += 'top:' + (m[1] + plotOffset.top) + 'px;'; else if (p.charAt(0) == "s") pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;'; if (p.charAt(1) == "e") pos += 'right:' + (m[0] + plotOffset.right) + 'px;'; else if (p.charAt(1) == "w") pos += 'left:' + (m[0] + plotOffset.left) + 'px;'; var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(target); if (options.legend.backgroundOpacity != 0.0) { // put in the transparent background // separately to avoid blended labels and // label boxes var c = options.legend.backgroundColor; if (c == null) { var tmp; if (options.grid.backgroundColor && typeof options.grid.backgroundColor == "string") tmp = options.grid.backgroundColor; else tmp = extractColor(legend); c = parseColor(tmp).adjust(null, null, null, 1).toString(); } var div = legend.children(); $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity); } } } // interactive features var lastMousePos = { pageX: null, pageY: null }, selection = { first: { x: -1, y: -1}, second: { x: -1, y: -1}, show: false, active: false }, highlights = [], clickIsMouseUp = false, redrawTimeout = null, hoverTimeout = null; // returns the data item the mouse is over, or null if none is found function findNearbyItem(mouseX, mouseY, seriesFilter) { var maxDistance = options.grid.mouseActiveRadius, lowestDistance = maxDistance * maxDistance + 1, item = null, foundPoint = false, i, j; for (var i = 0; i < series.length; ++i) { if (!seriesFilter(series[i])) continue; var s = series[i], axisx = s.xaxis, axisy = s.yaxis, points = s.datapoints.points, ps = s.datapoints.pointsize, mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster my = axisy.c2p(mouseY), maxx = maxDistance / axisx.scale, maxy = maxDistance / axisy.scale; if (s.lines.show || s.points.show) { for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1]; if (x == null) continue; // For points and lines, the cursor must be within a // certain distance to the data point if (x - mx > maxx || x - mx < -maxx || y - my > maxy || y - my < -maxy) continue; // We have to calculate distances in pixels, not in // data units, because the scales of the axes may be different var dx = Math.abs(axisx.p2c(x) - mouseX), dy = Math.abs(axisy.p2c(y) - mouseY), dist = dx * dx + dy * dy; // no idea in taking sqrt if (dist < lowestDistance) { lowestDistance = dist; item = [i, j / ps]; } } } if (s.bars.show && !item) { // no other point can be nearby var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2, barRight = barLeft + s.bars.barWidth; for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1], b = points[j + 2]; if (x == null) continue; // for a bar graph, the cursor must be inside the bar if (series[i].bars.horizontal ? (mx <= Math.max(b, x) && mx >= Math.min(b, x) && my >= y + barLeft && my <= y + barRight) : (mx >= x + barLeft && mx <= x + barRight && my >= Math.min(b, y) && my <= Math.max(b, y))) item = [i, j / ps]; } } } if (item) { i = item[0]; j = item[1]; return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), dataIndex: j, series: series[i], seriesIndex: i }; } return null; } function onMouseMove(e) { lastMousePos.pageX = e.pageX; lastMousePos.pageY = e.pageY; if (options.grid.hoverable) triggerClickHoverEvent("plothover", lastMousePos, function (s) { return s["hoverable"] != false; }); if (selection.active) { target.trigger("plotselecting", [ getSelection() ]); updateSelection(lastMousePos); } } function onMouseDown(e) { if (e.which != 1) // only accept left-click return; // cancel out any text selections document.body.focus(); // prevent text selection and drag in old-school browsers if (document.onselectstart !== undefined && workarounds.onselectstart == null) { workarounds.onselectstart = document.onselectstart; document.onselectstart = function () { return false; }; } if (document.ondrag !== undefined && workarounds.ondrag == null) { workarounds.ondrag = document.ondrag; document.ondrag = function () { return false; }; } setSelectionPos(selection.first, e); lastMousePos.pageX = null; selection.active = true; $(document).one("mouseup", onSelectionMouseUp); } function onClick(e) { if (clickIsMouseUp) { clickIsMouseUp = false; return; } triggerClickHoverEvent("plotclick", e, function (s) { return s["clickable"] != false; }); } /* function userPositionInCanvasSpace(pos) { return { x: parseInt(pos.x != null ? axes.xaxis.p2c(pos.x) : axes.x2axis.p2c(pos.x2)), y: parseInt(pos.y != null ? axes.yaxis.p2c(pos.y) : axes.y2axis.p2c(pos.y2)) }; } function positionInDivSpace(pos) { var cpos = userPositionInCanvasSpace(pos); return { x: cpos.x + plotOffset.left, y: cpos.y + plotOffset.top }; }*/ // trigger click or hover event (they send the same parameters // so we share their code) function triggerClickHoverEvent(eventname, event, seriesFilter) { var offset = eventHolder.offset(), pos = { pageX: event.pageX, pageY: event.pageY }, canvasX = event.pageX - offset.left - plotOffset.left, canvasY = event.pageY - offset.top - plotOffset.top; if (axes.xaxis.used) pos.x = axes.xaxis.c2p(canvasX); if (axes.yaxis.used) pos.y = axes.yaxis.c2p(canvasY); if (axes.x2axis.used) pos.x2 = axes.x2axis.c2p(canvasX); if (axes.y2axis.used) pos.y2 = axes.y2axis.c2p(canvasY); var item = findNearbyItem(canvasX, canvasY, seriesFilter); if (item) { // fill in mouse pos for any listeners out there item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left); item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top); } if (options.grid.autoHighlight) { // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.auto == eventname && !(item && h.series == item.series && h.point == item.datapoint)) unhighlight(h.series, h.point); } if (item) highlight(item.series, item.datapoint, eventname); } target.trigger(eventname, [ pos, item ]); } function triggerRedrawOverlay() { if (!redrawTimeout) redrawTimeout = setTimeout(drawOverlay, 30); } function drawOverlay() { redrawTimeout = null; // draw highlights octx.save(); octx.clearRect(0, 0, canvasWidth, canvasHeight); octx.translate(plotOffset.left, plotOffset.top); var i, hi; for (i = 0; i < highlights.length; ++i) { hi = highlights[i]; if (hi.series.bars.show) drawBarHighlight(hi.series, hi.point); else drawPointHighlight(hi.series, hi.point); } // draw selection if (selection.show && selectionIsSane()) { octx.strokeStyle = parseColor(options.selection.color).scale(null, null, null, 0.8).toString(); octx.lineWidth = 1; ctx.lineJoin = "round"; octx.fillStyle = parseColor(options.selection.color).scale(null, null, null, 0.4).toString(); var x = Math.min(selection.first.x, selection.second.x), y = Math.min(selection.first.y, selection.second.y), w = Math.abs(selection.second.x - selection.first.x), h = Math.abs(selection.second.y - selection.first.y); octx.fillRect(x, y, w, h); octx.strokeRect(x, y, w, h); } octx.restore(); executeHooks(hooks.drawOverlay, [octx]); } function highlight(s, point, auto) { if (typeof s == "number") s = series[s]; if (typeof point == "number") point = s.data[point]; var i = indexOfHighlight(s, point); if (i == -1) { highlights.push({ series: s, point: point, auto: auto }); triggerRedrawOverlay(); } else if (!auto) highlights[i].auto = false; } function unhighlight(s, point) { if (s == null && point == null) { highlights = []; triggerRedrawOverlay(); } if (typeof s == "number") s = series[s]; if (typeof point == "number") point = s.data[point]; var i = indexOfHighlight(s, point); if (i != -1) { highlights.splice(i, 1); triggerRedrawOverlay(); } } function indexOfHighlight(s, p) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.series == s && h.point[0] == p[0] && h.point[1] == p[1]) return i; } return -1; } function drawPointHighlight(series, point) { var x = point[0], y = point[1], axisx = series.xaxis, axisy = series.yaxis; if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) return; var pointRadius = series.points.radius + series.points.lineWidth / 2; octx.lineWidth = pointRadius; octx.strokeStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); var radius = 1.5 * pointRadius; octx.beginPath(); octx.arc(axisx.p2c(x), axisy.p2c(y), radius, 0, 2 * Math.PI, true); octx.stroke(); } function drawBarHighlight(series, point) { octx.lineWidth = series.bars.lineWidth; octx.strokeStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); var fillStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, 0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal); } function getSelection() { if (!selectionIsSane()) return null; var x1 = Math.min(selection.first.x, selection.second.x), x2 = Math.max(selection.first.x, selection.second.x), y1 = Math.max(selection.first.y, selection.second.y), y2 = Math.min(selection.first.y, selection.second.y); var r = {}; if (axes.xaxis.used) r.xaxis = { from: axes.xaxis.c2p(x1), to: axes.xaxis.c2p(x2) }; if (axes.x2axis.used) r.x2axis = { from: axes.x2axis.c2p(x1), to: axes.x2axis.c2p(x2) }; if (axes.yaxis.used) r.yaxis = { from: axes.yaxis.c2p(y1), to: axes.yaxis.c2p(y2) }; if (axes.y2axis.used) r.y2axis = { from: axes.y2axis.c2p(y1), to: axes.y2axis.c2p(y2) }; return r; } function triggerSelectedEvent() { var r = getSelection(); target.trigger("plotselected", [ r ]); // backwards-compat stuff, to be removed in future if (axes.xaxis.used && axes.yaxis.used) target.trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]); } function onSelectionMouseUp(e) { // revert drag stuff for old-school browsers if (document.onselectstart !== undefined) document.onselectstart = workarounds.onselectstart; if (document.ondrag !== undefined) document.ondrag = workarounds.ondrag; // no more draggy-dee-drag selection.active = false; updateSelection(e); if (selectionIsSane()) { triggerSelectedEvent(); clickIsMouseUp = true; } else { // this counts as a clear target.trigger("plotunselected", [ ]); target.trigger("plotselecting", [ null ]); } return false; } function setSelectionPos(pos, e) { var offset = eventHolder.offset(); pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plotWidth); pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plotHeight); if (options.selection.mode == "y") { if (pos == selection.first) pos.x = 0; else pos.x = plotWidth; } if (options.selection.mode == "x") { if (pos == selection.first) pos.y = 0; else pos.y = plotHeight; } } function updateSelection(pos) { if (pos.pageX == null) return; setSelectionPos(selection.second, pos); if (selectionIsSane()) { selection.show = true; triggerRedrawOverlay(); } else clearSelection(true); } function clearSelection(preventEvent) { if (selection.show) { selection.show = false; triggerRedrawOverlay(); if (!preventEvent) target.trigger("plotunselected", [ ]); } } function setSelection(ranges, preventEvent) { var range; if (options.selection.mode == "y") { selection.first.x = 0; selection.second.x = plotWidth; } else { range = extractRange(ranges, "x"); selection.first.x = range.axis.p2c(range.from); selection.second.x = range.axis.p2c(range.to); } if (options.selection.mode == "x") { selection.first.y = 0; selection.second.y = plotHeight; } else { range = extractRange(ranges, "y"); selection.first.y = range.axis.p2c(range.from); selection.second.y = range.axis.p2c(range.to); } selection.show = true; triggerRedrawOverlay(); if (!preventEvent) triggerSelectedEvent(); } function selectionIsSane() { var minSize = 5; return Math.abs(selection.second.x - selection.first.x) >= minSize && Math.abs(selection.second.y - selection.first.y) >= minSize; } function getColorOrGradient(spec, bottom, top, defaultColor) { if (typeof spec == "string") return spec; else { // assume this is a gradient spec; IE currently only // supports a simple vertical gradient properly, so that's // what we support too var gradient = ctx.createLinearGradient(0, top, 0, bottom); for (var i = 0, l = spec.colors.length; i < l; ++i) { var c = spec.colors[i]; gradient.addColorStop(i / (l - 1), typeof c == "string" ? c : parseColor(defaultColor).scale(c.brightness, c.brightness, c.brightness, c.opacity)); } return gradient; } } } $.plot = function(target, data, options) { var plot = new Plot($(target), data, options, $.plot.plugins); /*var t0 = new Date(); var t1 = new Date(); var tstr = "time used (msecs): " + (t1.getTime() - t0.getTime()) if (window.console) console.log(tstr); else alert(tstr);*/ return plot; }; $.plot.plugins = []; // returns a string with the date d formatted according to fmt $.plot.formatDate = function(d, fmt, monthNames) { var leftPad = function(n) { n = "" + n; return n.length == 1 ? "0" + n : n; }; var r = []; var escape = false; if (monthNames == null) monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; for (var i = 0; i < fmt.length; ++i) { var c = fmt.charAt(i); if (escape) { switch (c) { case 'h': c = "" + d.getUTCHours(); break; case 'H': c = leftPad(d.getUTCHours()); break; case 'M': c = leftPad(d.getUTCMinutes()); break; case 'S': c = leftPad(d.getUTCSeconds()); break; case 'd': c = "" + d.getUTCDate(); break; case 'm': c = "" + (d.getUTCMonth() + 1); break; case 'y': c = "" + d.getUTCFullYear(); break; case 'b': c = "" + monthNames[d.getUTCMonth()]; break; } r.push(c); escape = false; } else { if (c == "%") escape = true; else r.push(c); } } return r.join(""); }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } function clamp(min, value, max) { if (value < min) return min; else if (value > max) return max; else return value; } // color helpers, inspiration from the jquery color animation // plugin by John Resig function Color (r, g, b, a) { var rgba = ['r','g','b','a']; var x = 4; //rgba.length while (-1<--x) { this[rgba[x]] = arguments[x] || ((x==3) ? 1.0 : 0); } this.toString = function() { if (this.a >= 1.0) { return "rgb("+[this.r,this.g,this.b].join(",")+")"; } else { return "rgba("+[this.r,this.g,this.b,this.a].join(",")+")"; } }; this.scale = function(rf, gf, bf, af) { x = 4; //rgba.length while (-1<--x) { if (arguments[x] != null) this[rgba[x]] *= arguments[x]; } return this.normalize(); }; this.adjust = function(rd, gd, bd, ad) { x = 4; //rgba.length while (-1<--x) { if (arguments[x] != null) this[rgba[x]] += arguments[x]; } return this.normalize(); }; this.clone = function() { return new Color(this.r, this.b, this.g, this.a); }; var limit = function(val,minVal,maxVal) { return Math.max(Math.min(val, maxVal), minVal); }; this.normalize = function() { this.r = clamp(0, parseInt(this.r), 255); this.g = clamp(0, parseInt(this.g), 255); this.b = clamp(0, parseInt(this.b), 255); this.a = clamp(0, this.a, 1); return this; }; this.normalize(); } var lookupColors = { aqua:[0,255,255], azure:[240,255,255], beige:[245,245,220], black:[0,0,0], blue:[0,0,255], brown:[165,42,42], cyan:[0,255,255], darkblue:[0,0,139], darkcyan:[0,139,139], darkgrey:[169,169,169], darkgreen:[0,100,0], darkkhaki:[189,183,107], darkmagenta:[139,0,139], darkolivegreen:[85,107,47], darkorange:[255,140,0], darkorchid:[153,50,204], darkred:[139,0,0], darksalmon:[233,150,122], darkviolet:[148,0,211], fuchsia:[255,0,255], gold:[255,215,0], green:[0,128,0], indigo:[75,0,130], khaki:[240,230,140], lightblue:[173,216,230], lightcyan:[224,255,255], lightgreen:[144,238,144], lightgrey:[211,211,211], lightpink:[255,182,193], lightyellow:[255,255,224], lime:[0,255,0], magenta:[255,0,255], maroon:[128,0,0], navy:[0,0,128], olive:[128,128,0], orange:[255,165,0], pink:[255,192,203], purple:[128,0,128], violet:[128,0,128], red:[255,0,0], silver:[192,192,192], white:[255,255,255], yellow:[255,255,0] }; function extractColor(element) { var color, elem = element; do { color = elem.css("background-color").toLowerCase(); // keep going until we find an element that has color, or // we hit the body if (color != '' && color != 'transparent') break; elem = elem.parent(); } while (!$.nodeName(elem.get(0), "body")); // catch Safari's way of signalling transparent if (color == "rgba(0, 0, 0, 0)") return "transparent"; return color; } // parse string, returns Color function parseColor(str) { var result; // Look for rgb(num,num,num) if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str)) return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10)); // Look for rgba(num,num,num,num) if (result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10), parseFloat(result[4])); // Look for rgb(num%,num%,num%) if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str)) return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55); // Look for rgba(num%,num%,num%,num) if (result = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4])); // Look for #a0b1c2 if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str)) return new Color(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)); // Look for #fff if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str)) return new Color(parseInt(result[1]+result[1], 16), parseInt(result[2]+result[2], 16), parseInt(result[3]+result[3], 16)); // Otherwise, we're most likely dealing with a named color var name = $.trim(str).toLowerCase(); if (name == "transparent") return new Color(255, 255, 255, 0); else { result = lookupColors[name]; return new Color(result[0], result[1], result[2]); } } })(jQuery);
brosner/Cony
assets/javascript/jquery.flot.js
JavaScript
bsd-3-clause
95,053
/** * @ngdoc service * @name $ionicModal * @module ionic * @codepen gblny * @description * * Related: {@link ionic.controller:ionicModal ionicModal controller}. * * The Modal is a content pane that can go over the user's main view * temporarily. Usually used for making a choice or editing an item. * * Put the content of the modal inside of an `<ion-modal-view>` element. * * **Notes:** * - A modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating * scope, passing in itself as an event argument. Both the modal.removed and modal.hidden events are * called when the modal is removed. * * - This example assumes your modal is in your main index file or another template file. If it is in its own * template file, remove the script tags and call it by file name. * * @usage * ```html * <script id="my-modal.html" type="text/ng-template"> * <ion-modal-view> * <ion-header-bar> * <h1 class="title">My Modal title</h1> * </ion-header-bar> * <ion-content> * Hello! * </ion-content> * </ion-modal-view> * </script> * ``` * ```js * angular.module('testApp', ['ionic']) * .controller('MyController', function($scope, $ionicModal) { * $ionicModal.fromTemplateUrl('my-modal.html', { * scope: $scope, * animation: 'slide-in-up' * }).then(function(modal) { * $scope.modal = modal; * }); * $scope.openModal = function() { * $scope.modal.show(); * }; * $scope.closeModal = function() { * $scope.modal.hide(); * }; * // Cleanup the modal when we're done with it! * $scope.$on('$destroy', function() { * $scope.modal.remove(); * }); * // Execute action on hide modal * $scope.$on('modal.hidden', function() { * // Execute action * }); * // Execute action on remove modal * $scope.$on('modal.removed', function() { * // Execute action * }); * }); * ``` */ IonicModule .factory('$ionicModal', [ '$rootScope', '$ionicBody', '$compile', '$timeout', '$ionicPlatform', '$ionicTemplateLoader', '$$q', '$log', '$ionicClickBlock', '$window', 'IONIC_BACK_PRIORITY', function($rootScope, $ionicBody, $compile, $timeout, $ionicPlatform, $ionicTemplateLoader, $$q, $log, $ionicClickBlock, $window, IONIC_BACK_PRIORITY) { /** * @ngdoc controller * @name ionicModal * @module ionic * @description * Instantiated by the {@link ionic.service:$ionicModal} service. * * Be sure to call [remove()](#remove) when you are done with each modal * to clean it up and avoid memory leaks. * * Note: a modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating * scope, passing in itself as an event argument. Note: both modal.removed and modal.hidden are * called when the modal is removed. */ var ModalView = ionic.views.Modal.inherit({ /** * @ngdoc method * @name ionicModal#initialize * @description Creates a new modal controller instance. * @param {object} options An options object with the following properties: * - `{object=}` `scope` The scope to be a child of. * Default: creates a child of $rootScope. * - `{string=}` `animation` The animation to show & hide with. * Default: 'slide-in-up' * - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of * the modal when shown. Will only show the keyboard on iOS, to force the keyboard to show * on Android, please use the [Ionic keyboard plugin](https://github.com/driftyco/ionic-plugin-keyboard#keyboardshow). * Default: false. * - `{boolean=}` `backdropClickToClose` Whether to close the modal on clicking the backdrop. * Default: true. * - `{boolean=}` `hardwareBackButtonClose` Whether the modal can be closed using the hardware * back button on Android and similar devices. Default: true. */ initialize: function(opts) { ionic.views.Modal.prototype.initialize.call(this, opts); this.animation = opts.animation || 'slide-in-up'; }, /** * @ngdoc method * @name ionicModal#show * @description Show this modal instance. * @returns {promise} A promise which is resolved when the modal is finished animating in. */ show: function(target) { var self = this; if (self.scope.$$destroyed) { $log.error('Cannot call ' + self.viewType + '.show() after remove(). Please create a new ' + self.viewType + ' instance.'); return $$q.when(); } // on iOS, clicks will sometimes bleed through/ghost click on underlying // elements $ionicClickBlock.show(600); stack.add(self); var modalEl = jqLite(self.modalEl); self.el.classList.remove('hide'); $timeout(function() { if (!self._isShown) return; $ionicBody.addClass(self.viewType + '-open'); }, 400, false); if (!self.el.parentElement) { modalEl.addClass(self.animation); $ionicBody.append(self.el); } // if modal was closed while the keyboard was up, reset scroll view on // next show since we can only resize it once it's visible var scrollCtrl = modalEl.data('$$ionicScrollController'); scrollCtrl && scrollCtrl.resize(); if (target && self.positionView) { self.positionView(target, modalEl); // set up a listener for in case the window size changes self._onWindowResize = function() { if (self._isShown) self.positionView(target, modalEl); }; ionic.on('resize', self._onWindowResize, window); } modalEl.addClass('ng-enter active') .removeClass('ng-leave ng-leave-active'); self._isShown = true; self._deregisterBackButton = $ionicPlatform.registerBackButtonAction( self.hardwareBackButtonClose ? angular.bind(self, self.hide) : noop, IONIC_BACK_PRIORITY.modal ); ionic.views.Modal.prototype.show.call(self); $timeout(function() { if (!self._isShown) return; modalEl.addClass('ng-enter-active'); ionic.trigger('resize'); self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.shown', self); self.el.classList.add('active'); self.scope.$broadcast('$ionicHeader.align'); self.scope.$broadcast('$ionicFooter.align'); }, 20); return $timeout(function() { if (!self._isShown) return; self.$el.on('touchmove', function(e) { //Don't allow scrolling while open by dragging on backdrop var isInScroll = ionic.DomUtil.getParentOrSelfWithClass(e.target, 'scroll'); if (!isInScroll) { e.preventDefault(); } }); //After animating in, allow hide on backdrop click self.$el.on('click', function(e) { if (self.backdropClickToClose && e.target === self.el && stack.isHighest(self)) { self.hide(); } }); }, 400); }, /** * @ngdoc method * @name ionicModal#hide * @description Hide this modal instance. * @returns {promise} A promise which is resolved when the modal is finished animating out. */ hide: function() { var self = this; var modalEl = jqLite(self.modalEl); // on iOS, clicks will sometimes bleed through/ghost click on underlying // elements $ionicClickBlock.show(600); stack.remove(self); self.el.classList.remove('active'); modalEl.addClass('ng-leave'); $timeout(function() { if (self._isShown) return; modalEl.addClass('ng-leave-active') .removeClass('ng-enter ng-enter-active active'); }, 20, false); self.$el.off('click'); self._isShown = false; self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.hidden', self); self._deregisterBackButton && self._deregisterBackButton(); ionic.views.Modal.prototype.hide.call(self); // clean up event listeners if (self.positionView) { ionic.off('resize', self._onWindowResize, window); } return $timeout(function() { $ionicBody.removeClass(self.viewType + '-open'); self.el.classList.add('hide'); }, self.hideDelay || 320); }, /** * @ngdoc method * @name ionicModal#remove * @description Remove this modal instance from the DOM and clean up. * @returns {promise} A promise which is resolved when the modal is finished animating out. */ remove: function() { var self = this; self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.removed', self); return self.hide().then(function() { self.scope.$destroy(); self.$el.remove(); }); }, /** * @ngdoc method * @name ionicModal#isShown * @returns boolean Whether this modal is currently shown. */ isShown: function() { return !!this._isShown; } }); var createModal = function(templateString, options) { // Create a new scope for the modal var scope = options.scope && options.scope.$new() || $rootScope.$new(true); options.viewType = options.viewType || 'modal'; extend(scope, { $hasHeader: false, $hasSubheader: false, $hasFooter: false, $hasSubfooter: false, $hasTabs: false, $hasTabsTop: false }); // Compile the template var element = $compile('<ion-' + options.viewType + '>' + templateString + '</ion-' + options.viewType + '>')(scope); options.$el = element; options.el = element[0]; options.modalEl = options.el.querySelector('.' + options.viewType); var modal = new ModalView(options); modal.scope = scope; // If this wasn't a defined scope, we can assign the viewType to the isolated scope // we created if (!options.scope) { scope[ options.viewType ] = modal; } return modal; }; var modalStack = []; var stack = { add: function(modal) { modalStack.push(modal); }, remove: function(modal) { var index = modalStack.indexOf(modal); if (index > -1 && index < modalStack.length) { modalStack.splice(index, 1); } }, isHighest: function(modal) { var index = modalStack.indexOf(modal); return (index > -1 && index === modalStack.length - 1); } }; return { /** * @ngdoc method * @name $ionicModal#fromTemplate * @param {string} templateString The template string to use as the modal's * content. * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method. * @returns {object} An instance of an {@link ionic.controller:ionicModal} * controller. */ fromTemplate: function(templateString, options) { var modal = createModal(templateString, options || {}); return modal; }, /** * @ngdoc method * @name $ionicModal#fromTemplateUrl * @param {string} templateUrl The url to load the template from. * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method. * options object. * @returns {promise} A promise that will be resolved with an instance of * an {@link ionic.controller:ionicModal} controller. */ fromTemplateUrl: function(url, options, _) { var cb; //Deprecated: allow a callback as second parameter. Now we return a promise. if (angular.isFunction(options)) { cb = options; options = _; } return $ionicTemplateLoader.load(url).then(function(templateString) { var modal = createModal(templateString, options || {}); cb && cb(modal); return modal; }); }, stack: stack }; }]);
gu1cortez/X-Nerd
www/js/modal.js
JavaScript
bsd-3-clause
11,921
var appName; var popupMask; var popupDialog; var clientId; var realm; var redirect_uri; var clientSecret; var scopeSeparator; var additionalQueryStringParams; function handleLogin() { var scopes = []; var auths = window.swaggerUi.api.authSchemes || window.swaggerUi.api.securityDefinitions; if(auths) { var key; var defs = auths; for(key in defs) { var auth = defs[key]; if(auth.type === 'oauth2' && auth.scopes) { var scope; if(Array.isArray(auth.scopes)) { // 1.2 support var i; for(i = 0; i < auth.scopes.length; i++) { scopes.push(auth.scopes[i]); } } else { // 2.0 support for(scope in auth.scopes) { scopes.push({scope: scope, description: auth.scopes[scope], OAuthSchemeKey: key}); } } } } } if(window.swaggerUi.api && window.swaggerUi.api.info) { appName = window.swaggerUi.api.info.title; } $('.api-popup-dialog').remove(); popupDialog = $( [ '<div class="api-popup-dialog">', '<div class="api-popup-title">Select OAuth2.0 Scopes</div>', '<div class="api-popup-content">', '<p>Scopes are used to grant an application different levels of access to data on behalf of the end user. Each API may declare one or more scopes.', '<a href="#">Learn how to use</a>', '</p>', '<p><strong>' + appName + '</strong> API requires the following scopes. Select which ones you want to grant to Swagger UI.</p>', '<ul class="api-popup-scopes">', '</ul>', '<p class="error-msg"></p>', '<div class="api-popup-actions"><button class="api-popup-authbtn api-button green" type="button">Authorize</button><button class="api-popup-cancel api-button gray" type="button">Cancel</button></div>', '</div>', '</div>'].join('')); $(document.body).append(popupDialog); //TODO: only display applicable scopes (will need to pass them into handleLogin) popup = popupDialog.find('ul.api-popup-scopes').empty(); for (i = 0; i < scopes.length; i ++) { scope = scopes[i]; str = '<li><input type="checkbox" id="scope_' + i + '" scope="' + scope.scope + '"' +'" oauthtype="' + scope.OAuthSchemeKey +'"/>' + '<label for="scope_' + i + '">' + scope.scope ; if (scope.description) { if ($.map(auths, function(n, i) { return i; }).length > 1) //if we have more than one scheme, display schemes str += '<br/><span class="api-scope-desc">' + scope.description + ' ('+ scope.OAuthSchemeKey+')' +'</span>'; else str += '<br/><span class="api-scope-desc">' + scope.description + '</span>'; } str += '</label></li>'; popup.append(str); } var $win = $(window), dw = $win.width(), dh = $win.height(), st = $win.scrollTop(), dlgWd = popupDialog.outerWidth(), dlgHt = popupDialog.outerHeight(), top = (dh -dlgHt)/2 + st, left = (dw - dlgWd)/2; popupDialog.css({ top: (top < 0? 0 : top) + 'px', left: (left < 0? 0 : left) + 'px' }); popupDialog.find('button.api-popup-cancel').click(function() { popupMask.hide(); popupDialog.hide(); popupDialog.empty(); popupDialog = []; }); $('button.api-popup-authbtn').unbind(); popupDialog.find('button.api-popup-authbtn').click(function() { popupMask.hide(); popupDialog.hide(); var authSchemes = window.swaggerUi.api.authSchemes; var host = window.location; var pathname = location.pathname.substring(0, location.pathname.lastIndexOf("/")); var defaultRedirectUrl = host.protocol + '//' + host.host + pathname + '/o2c-html'; var redirectUrl = window.oAuthRedirectUrl || defaultRedirectUrl; var url = null; var scopes = [] var o = popup.find('input:checked'); var OAuthSchemeKeys = []; var state; for(k =0; k < o.length; k++) { var scope = $(o[k]).attr('scope'); if (scopes.indexOf(scope) === -1) scopes.push(scope); var OAuthSchemeKey = $(o[k]).attr('oauthtype'); if (OAuthSchemeKeys.indexOf(OAuthSchemeKey) === -1) OAuthSchemeKeys.push(OAuthSchemeKey); } //TODO: merge not replace if scheme is different from any existing //(needs to be aware of schemes to do so correctly) window.enabledScopes=scopes; for (var key in authSchemes) { if (authSchemes.hasOwnProperty(key) && OAuthSchemeKeys.indexOf(key) != -1) { //only look at keys that match this scope. var flow = authSchemes[key].flow; if(authSchemes[key].type === 'oauth2' && flow && (flow === 'implicit' || flow === 'accessCode')) { var dets = authSchemes[key]; url = dets.authorizationUrl + '?response_type=' + (flow === 'implicit' ? 'token' : 'code'); window.swaggerUi.tokenName = dets.tokenName || 'access_token'; window.swaggerUi.tokenUrl = (flow === 'accessCode' ? dets.tokenUrl : null); state = key; } else if(authSchemes[key].type === 'oauth2' && flow && (flow === 'application')) { var dets = authSchemes[key]; window.swaggerUi.tokenName = dets.tokenName || 'access_token'; clientCredentialsFlow(scopes, dets.tokenUrl, key); return; } else if(authSchemes[key].grantTypes) { // 1.2 support var o = authSchemes[key].grantTypes; for(var t in o) { if(o.hasOwnProperty(t) && t === 'implicit') { var dets = o[t]; var ep = dets.loginEndpoint.url; url = dets.loginEndpoint.url + '?response_type=token'; window.swaggerUi.tokenName = dets.tokenName; } else if (o.hasOwnProperty(t) && t === 'accessCode') { var dets = o[t]; var ep = dets.tokenRequestEndpoint.url; url = dets.tokenRequestEndpoint.url + '?response_type=code'; window.swaggerUi.tokenName = dets.tokenName; } } } } } redirect_uri = redirectUrl; url += '&redirect_uri=' + encodeURIComponent(redirectUrl); url += '&realm=' + encodeURIComponent(realm); url += '&client_id=' + encodeURIComponent(clientId); url += '&scope=' + encodeURIComponent(scopes.join(scopeSeparator)); url += '&state=' + encodeURIComponent(state); for (var key in additionalQueryStringParams) { url += '&' + key + '=' + encodeURIComponent(additionalQueryStringParams[key]); } window.open(url); }); popupMask.show(); popupDialog.show(); return; } function handleLogout() { for(key in window.swaggerUi.api.clientAuthorizations.authz){ window.swaggerUi.api.clientAuthorizations.remove(key) } window.enabledScopes = null; $('.api-ic.ic-on').addClass('ic-off'); $('.api-ic.ic-on').removeClass('ic-on'); // set the info box $('.api-ic.ic-warning').addClass('ic-error'); $('.api-ic.ic-warning').removeClass('ic-warning'); } function initOAuth(opts) { var o = (opts||{}); var errors = []; appName = (o.appName||errors.push('missing appName')); popupMask = (o.popupMask||$('#api-common-mask')); popupDialog = (o.popupDialog||$('.api-popup-dialog')); clientId = (o.clientId||errors.push('missing client id')); clientSecret = (o.clientSecret||null); realm = (o.realm||errors.push('missing realm')); scopeSeparator = (o.scopeSeparator||' '); additionalQueryStringParams = (o.additionalQueryStringParams||{}); if(errors.length > 0){ log('auth unable initialize oauth: ' + errors); return; } $('pre code').each(function(i, e) {hljs.highlightBlock(e)}); $('.api-ic').unbind(); $('.api-ic').click(function(s) { if($(s.target).hasClass('ic-off')) handleLogin(); else { handleLogout(); } false; }); } function clientCredentialsFlow(scopes, tokenUrl, OAuthSchemeKey) { var params = { 'client_id': clientId, 'client_secret': clientSecret, 'scope': scopes.join(' '), 'grant_type': 'client_credentials' } $.ajax( { url : tokenUrl, type: "POST", data: params, success:function(data, textStatus, jqXHR) { onOAuthComplete(data,OAuthSchemeKey); }, error: function(jqXHR, textStatus, errorThrown) { onOAuthComplete(""); } }); } window.processOAuthCode = function processOAuthCode(data) { var OAuthSchemeKey = data.state; var params = { 'client_id': clientId, 'code': data.code, 'grant_type': 'authorization_code', 'redirect_uri': redirect_uri }; if (clientSecret) { params.client_secret = clientSecret; } $.ajax( { url : window.swaggerUi.tokenUrl, type: "POST", data: params, success:function(data, textStatus, jqXHR) { onOAuthComplete(data, OAuthSchemeKey); }, error: function(jqXHR, textStatus, errorThrown) { onOAuthComplete(""); } }); }; window.onOAuthComplete = function onOAuthComplete(token,OAuthSchemeKey) { if(token) { if(token.error) { var checkbox = $('input[type=checkbox],.secured') checkbox.each(function(pos){ checkbox[pos].checked = false; }); alert(token.error); } else { var b = token[window.swaggerUi.tokenName]; if (!OAuthSchemeKey){ OAuthSchemeKey = token.state; } if(b){ // if all roles are satisfied var o = null; $.each($('.auth .api-ic .api_information_panel'), function(k, v) { var children = v; if(children && children.childNodes) { var requiredScopes = []; $.each((children.childNodes), function (k1, v1){ var inner = v1.innerHTML; if(inner) requiredScopes.push(inner); }); var diff = []; for(var i=0; i < requiredScopes.length; i++) { var s = requiredScopes[i]; if(window.enabledScopes && window.enabledScopes.indexOf(s) == -1) { diff.push(s); } } if(diff.length > 0){ o = v.parentNode.parentNode; $(o.parentNode).find('.api-ic.ic-on').addClass('ic-off'); $(o.parentNode).find('.api-ic.ic-on').removeClass('ic-on'); // sorry, not all scopes are satisfied $(o).find('.api-ic').addClass('ic-warning'); $(o).find('.api-ic').removeClass('ic-error'); } else { o = v.parentNode.parentNode; $(o.parentNode).find('.api-ic.ic-off').addClass('ic-on'); $(o.parentNode).find('.api-ic.ic-off').removeClass('ic-off'); // all scopes are satisfied $(o).find('.api-ic').addClass('ic-info'); $(o).find('.api-ic').removeClass('ic-warning'); $(o).find('.api-ic').removeClass('ic-error'); } } }); window.swaggerUi.api.clientAuthorizations.add(OAuthSchemeKey, new SwaggerClient.ApiKeyAuthorization('Authorization', 'Bearer ' + b, 'header')); } } } };
bigtlb/Swashbuckle
Swashbuckle.Core/SwaggerUi/CustomAssets/swagger-oauth.js
JavaScript
bsd-3-clause
11,183
/** @file Export all functions in yuv-video to user @author Gilson Varghese<gilsonvarghese7@gmail.com> @date 13 Oct, 2016 **/ /** Module includes */ var frameReader = require(./lib/framereader); var frameWriter = require(./lib/framewriter); var frameConverter = require(./lib/frameconverter); /** Global variables */ var version = "1.0.0"; /** Export all the functions to global namespace */ module.exports = { /** Test function to test the reader */ version: function() { return version; }, /** Frame reader to read frame according to the given options */ frameReader: frameReader, /** Frame Writer to write frame according to the options */ frameWrite: frameWriter, /** Frame Converter to conver frame into various formats Currently only YV21 and V210 are supported */ frameConverter: frameConverter };
gilson27/yuv-video
index.js
JavaScript
bsd-3-clause
878
/* Mark special links * * Options: * external_links_open_new_window(boolean): Open external links in a new window. (false) * mark_special_links(boolean): Marks external or special protocl links with class. (true) * * Documentation: * # General * * Scan all links in the container and mark external links with class * if they point outside the site, or are special protocols. * Also implements new window opening for external links. * To disable this effect for links on a one-by-one-basis, * give them a class of 'link-plain' * * # Default external link example * * {{ example-1 }} * * # Open external link in new window * * {{ example-2 }} * * # Open external link in new window, without icons * * {{ example-3 }} * * # List of all protocol icons * * {{ example-4 }} * * Example: example-1 * <div class="pat-markspeciallinks"> * <ul> * <li>Find out What's new in <a href="http://www.plone.org">Plone</a>.</li> * <li>Plone is written in <a class="link-plain" href="http://www.python.org">Python</a>.</li> * <li>Plone builds on <a href="http://zope.org">Zope</a>.</li> * <li>Plone uses <a href="/">Mockup</a>.</li> * </ul> * </div> * * Example: example-2 * <div class="pat-markspeciallinks" data-pat-markspeciallinks='{"external_links_open_new_window": "true"}'> * <ul> * <li>Find out What's new in <a href="http://www.plone.org">Plone</a>.</li> * <li>Plone is written in <a class="link-plain" href="http://www.python.org">Python</a>.</li> * <li>Plone builds on <a href="http://zope.org">Zope</a>.</li> * <li>Plone uses <a href="/">Mockup</a>.</li> * </ul> * </div> * * Example: example-3 * <div class="pat-markspeciallinks" data-pat-markspeciallinks='{"external_links_open_new_window": "true", "mark_special_links": "false"}'> * <ul> * <li>Find out What's new in <a href="http://www.plone.org">Plone</a>.</li> * <li>Plone is written in <a class="link-plain" href="http://www.python.org">Python</a>.</li> * <li>Plone builds on <a href="http://zope.org">Zope</a>.</li> * <li>Plone uses <a href="/">Mockup</a>.</li> * </ul> * </div> * * Example: example-4 * <div class="pat-markspeciallinks"> * <ul> * <li><a href="http://www.plone.org">http</a></li> * <li><a href="https://www.plone.org">https</a></li> * <li><a href="mailto:info@plone.org">mailto</a></li> * <li><a href="ftp://www.plone.org">ftp</a></li> * <li><a href="news://www.plone.org">news</a></li> * <li><a href="irc://www.plone.org">irc</a></li> * <li><a href="h323://www.plone.org">h323</a></li> * <li><a href="sip://www.plone.org">sip</a></li> * <li><a href="callto://www.plone.org">callto</a></li> * <li><a href="feed://www.plone.org">feed</a></li> * <li><a href="webcal://www.plone.org">webcal</a></li> * </ul> * </div> * */ define(["pat-base", "jquery"], function (Base, $) { "use strict"; var MarkSpecialLinks = Base.extend({ name: "markspeciallinks", trigger: ".pat-markspeciallinks", parser: "mockup", defaults: { external_links_open_new_window: false, mark_special_links: true, }, init: function () { var self = this, $el = self.$el; // first make external links open in a new window, afterwards do the // normal plone link wrapping in only the content area var elonw, msl, url, protocols, contentarea, res; if ( typeof self.options.external_links_open_new_window === "string" ) { elonw = self.options.external_links_open_new_window.toLowerCase() === "true"; } else if ( typeof self.options.external_links_open_new_window === "boolean" ) { elonw = self.options.external_links_open_new_window; } if (typeof self.options.mark_special_links === "string") { msl = self.options.mark_special_links.toLowerCase() === "true"; } else if (typeof self.options.mark_special_links === "boolean") { msl = self.options.mark_special_links; } url = window.location.protocol + "//" + window.location.host; protocols = /^(mailto|ftp|news|irc|h323|sip|callto|https|feed|webcal)/; contentarea = $el; if (elonw) { // all http links (without the link-plain class), not within this site contentarea .find( 'a[href^="http"]:not(.link-plain):not([href^="' + url + '"])' ) .attr("target", "_blank") .attr("rel", "noopener"); } if (msl) { // All links with an http href (without the link-plain class), not within this site, // and no img children should be wrapped in a link-external span contentarea .find( 'a[href^="http:"]:not(.link-plain):not([href^="' + url + '"]):not(:has(img))' ) .before('<i class="glyphicon link-external"></i>'); // All links without an http href (without the link-plain class), not within this site, // and no img children should be wrapped in a link-[protocol] span contentarea .find( 'a[href]:not([href^="http:"]):not(.link-plain):not([href^="' + url + '"]):not(:has(img)):not([href^="#"])' ) .each(function () { // those without a http link may have another interesting protocol // wrap these in a link-[protocol] span res = protocols.exec($(this).attr("href")); if (res) { var iconclass = "glyphicon link-" + res[0]; $(this).before('<i class="' + iconclass + '"></i>'); } }); } }, }); return MarkSpecialLinks; });
plone/mockup
mockup/patterns/markspeciallinks/pattern.js
JavaScript
bsd-3-clause
6,596
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails oncall+relay */ 'use strict'; jest.dontMock('GraphQLSegment'); const GraphQLSegment = require('GraphQLSegment'); const RelayRecord = require('RelayRecord'); RelayRecord.getDataID.mockImplementation(function(data) { return data.__dataID__; }); var edges = [ { __dataID__:'edge1', node: {__dataID__: 'id1'}, cursor: 'cursor1', }, { __dataID__:'edge2', node: {__dataID__: 'id2'}, cursor: 'cursor2', }, { __dataID__:'edge3', node: {__dataID__: 'id3'}, cursor: 'cursor3', }, ]; var moreEdges = [ { __dataID__:'edge4', node: {__dataID__: 'id4'}, cursor: 'cursor4', }, { __dataID__:'edge5', node: {__dataID__: 'id5'}, cursor: 'cursor5', }, { __dataID__:'edge6', node: {__dataID__: 'id6'}, cursor: 'cursor6', }, ]; var lastEdges = [ { __dataID__:'edge98', node: {__dataID__: 'id98'}, cursor: 'cursor98', }, { __dataID__:'edge99', node: {__dataID__: 'id99'}, cursor: 'cursor99', }, { __dataID__:'edge100', node: {__dataID__: 'id100'}, cursor: 'cursor100', }, ]; var beforeLastEdges = [ { __dataID__:'edge95', node: {__dataID__: 'id95'}, cursor: 'cursor95', }, { __dataID__:'edge96', node: {__dataID__: 'id96'}, cursor: 'cursor96', }, { __dataID__:'edge97', node: {__dataID__: 'id97'}, cursor: 'cursor97', }, ]; var oneEdge = { __dataID__:'edgeOneEdge', node: {__dataID__: 'idOneEdge'}, cursor: 'cursorOneEdge', }; var anotherEdge = { __dataID__:'edgeAnotherEdge', node: {__dataID__: 'idAnotherEdge'}, cursor: 'cursorAnotherEdge', }; /** * Returns all valid ids and cursors. */ function getAllMetadata(segment) { return segment.getMetadataAfterCursor(segment.getLength(), null); } describe('GraphQLSegment', () => { var segment; var consoleWarn; beforeEach(() => { segment = new GraphQLSegment(); consoleWarn = console.warn; }); afterEach(() => { console.warn = consoleWarn; }); it('should add after', () => { // Initial add segment.addEdgesAfterCursor(edges, null); var metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edge1', 'edge2', 'edge3']); expect(metadata.cursors).toEqual(['cursor1', 'cursor2', 'cursor3']); // Add more segment.addEdgesAfterCursor(moreEdges, 'cursor3'); metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual( ['edge1', 'edge2', 'edge3', 'edge4', 'edge5', 'edge6'] ); expect(metadata.cursors).toEqual( ['cursor1', 'cursor2', 'cursor3', 'cursor4', 'cursor5', 'cursor6'] ); }); it('should add before', () => { // Initial add segment.addEdgesBeforeCursor(lastEdges, null); var metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edge98', 'edge99', 'edge100']); expect(metadata.cursors).toEqual(['cursor98', 'cursor99', 'cursor100']); // Add more segment.addEdgesBeforeCursor(beforeLastEdges, 'cursor98'); metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual( ['edge95', 'edge96', 'edge97', 'edge98', 'edge99', 'edge100'] ); expect(metadata.cursors).toEqual( ['cursor95', 'cursor96', 'cursor97', 'cursor98', 'cursor99', 'cursor100'] ); }); it('should handle repeated edges', () => { console.warn = jest.genMockFunction(); var repeatedEdges = edges.concat(edges.slice(0, 1)); // Attempting to add edges 1 2 3 1. segment.addEdgesAfterCursor(repeatedEdges, null); expect(console.warn.mock.calls.length).toBe(1); expect(console.warn).toBeCalledWith( 'Attempted to add an ID already in GraphQLSegment: %s', 'edge1' ); // Should have skipped the repeated ones. var metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edge1', 'edge2', 'edge3']); expect(metadata.cursors).toEqual(['cursor1', 'cursor2', 'cursor3']); }); it('should prepend', () => { // Prepend on new segment segment.prependEdge(oneEdge); var metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edgeOneEdge']); expect(metadata.cursors).toEqual(['cursorOneEdge']); // Prepend on segment that already has item segment.prependEdge(anotherEdge); metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edgeAnotherEdge', 'edgeOneEdge']); expect(metadata.cursors).toEqual(['cursorAnotherEdge', 'cursorOneEdge']); }); it('should append', () => { // Append on new segment segment.appendEdge(oneEdge); var metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edgeOneEdge']); expect(metadata.cursors).toEqual(['cursorOneEdge']); // Append on segment that already has item segment.appendEdge(anotherEdge); metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edgeOneEdge', 'edgeAnotherEdge']); expect(metadata.cursors).toEqual(['cursorOneEdge', 'cursorAnotherEdge']); }); it('should retrieve metadata correctly', () => { var before = segment.getMetadataBeforeCursor( segment.getLength(), null ); var after = segment.getMetadataAfterCursor( segment.getLength(), null ); expect(before.edgeIDs).toEqual([]); expect(before.edgeIDs).toEqual(after.edgeIDs); expect(before.cursors).toEqual([]); expect(before.cursors).toEqual(after.cursors); segment.addEdgesAfterCursor(edges, null); before = segment.getMetadataBeforeCursor( segment.getLength(), null ); after = segment.getMetadataAfterCursor( segment.getLength(), null ); expect(before.edgeIDs).toEqual(['edge1', 'edge2', 'edge3']); expect(before.edgeIDs).toEqual(after.edgeIDs); expect(before.cursors).toEqual(['cursor1', 'cursor2', 'cursor3']); expect(before.cursors).toEqual(after.cursors); }); it('should remove', () => { segment.addEdgesAfterCursor(edges, null); // Remove the middle edge segment.removeEdge('edge2'); var metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edge1', 'edge3']); expect(metadata.cursors).toEqual(['cursor1', 'cursor3']); }); it('should include removed edges in `getLength()` calculation', () => { expect(segment.getCount()).toBe(0); segment.addEdgesAfterCursor(edges, null); expect(segment.getLength()).toBe(3); segment.removeEdge('edge2'); expect(segment.getLength()).toBe(3); }); it('should exclude removed edges from `getCount()` calculation', () => { // with addEdgesAfterCursor expect(segment.getCount()).toBe(0); segment.addEdgesAfterCursor(edges, null); expect(segment.getCount()).toBe(3); segment.removeEdge('edge2'); expect(segment.getCount()).toBe(2); // with concatSegment var otherSegment = new GraphQLSegment(); otherSegment.addEdgesAfterCursor(edges.slice(0, 2), null); expect(otherSegment.getCount()).toBe(2); otherSegment.removeEdge('edge2'); expect(otherSegment.getCount()).toBe(1); segment.removeEdge('edge1'); otherSegment.concatSegment(segment, null); expect(otherSegment.getCount()).toBe(2); }); it('rolls back failed concatSegment operations', () => { console.warn = jest.genMockFunction(); segment.addEdgesAfterCursor(edges.slice(0, 2), null); expect(segment.getCount()).toBe(2); expect(segment.getLength()).toBe(2); var otherSegment = new GraphQLSegment(); otherSegment.addEdgesAfterCursor(edges.slice(1, 2), null); var concatResult = segment.concatSegment(otherSegment); expect(concatResult).toBe(false); expect(console.warn).toBeCalledWith( 'Attempt to concat an ID already in GraphQLSegment: %s', 'edge2' ); expect(segment.getCount()).toBe(2); expect(segment.getLength()).toBe(2); }); it('rolls back bumped edges from failed concatSegment operations', () => { console.warn = jest.genMockFunction(); segment.addEdgesAfterCursor(edges.slice(0, 2), null); expect(segment.__debug().idToIndices.edge2.length).toBe(1); var otherSegment = new GraphQLSegment(); var edge2 = edges.slice(1, 2); otherSegment.addEdgesAfterCursor(edge2, null); // bumping the edge otherSegment.removeEdge('edge2', 1001); otherSegment.addEdgesAfterCursor(edge2, null, 1001); var concatResult = segment.concatSegment(otherSegment); expect(concatResult).toBe(false); expect(console.warn).toBeCalledWith( 'Attempt to concat an ID already in GraphQLSegment: %s', 'edge2' ); // Make sure it rolled back the deleted edge from indices map expect(segment.__debug().idToIndices.edge2.length).toBe(1); }); it('should check for valid id in segment', () => { segment.addEdgesAfterCursor(edges, null); // Remove the middle edge segment.removeEdge('edge2'); // Never added expect(segment.containsEdgeWithID('edge0')).toBeFalsy(); // Added expect(segment.containsEdgeWithID('edge1')).toBeTruthy(); // Deleted expect(segment.containsEdgeWithID('edge2')).toBeFalsy(); }); it('should check for valid cursor in segment', () => { segment.addEdgesAfterCursor(edges, null); // Remove the middle edge segment.removeEdge('edge2'); // Never added expect(segment.containsEdgeWithCursor('cursor0')).toBeFalsy(); // Added expect(segment.containsEdgeWithCursor('cursor1')).toBeTruthy(); // Deleted expect(segment.containsEdgeWithCursor('cursor2')).toBeFalsy(); }); it('should get first and last cursor in segment', () => { // Returns undefined for empty segment expect(segment.getFirstCursor()).toBeUndefined(); expect(segment.getLastCursor()).toBeUndefined(); // Returns property for basic edges segment.addEdgesAfterCursor(edges, null); expect(segment.getFirstCursor()).toEqual('cursor1'); expect(segment.getLastCursor()).toEqual('cursor3'); // Skips over deleted edges segment.removeEdge('edge1'); segment.removeEdge('edge3'); expect(segment.getFirstCursor()).toEqual('cursor2'); expect(segment.getLastCursor()).toEqual('cursor2'); // Returns undefined when all edges are deleted segment.removeEdge('edge2'); expect(segment.getFirstCursor()).toBeUndefined(); expect(segment.getLastCursor()).toBeUndefined(); // Appends and prepends new edges segment.prependEdge(oneEdge); segment.appendEdge(anotherEdge); expect(segment.getFirstCursor()).toEqual('cursorOneEdge'); expect(segment.getLastCursor()).toEqual('cursorAnotherEdge'); // Returns null for null cursors segment = new GraphQLSegment(); segment.addEdgesAfterCursor( [{__dataID__: 'edgeid', cursor: null, node: {__dataID__: 'id'}}], null ); expect(segment.getFirstCursor()).toBeNull(); expect(segment.getLastCursor()).toBeNull(); }); it('should get first and last id in segment', () => { // Returns undefined for empty segment expect(segment.getFirstID()).toBeUndefined(); expect(segment.getLastID()).toBeUndefined(); // Returns property for basic edges segment.addEdgesAfterCursor(edges, null); expect(segment.getFirstID()).toEqual('edge1'); expect(segment.getLastID()).toEqual('edge3'); // Skips over deleted edges segment.removeEdge('edge1'); segment.removeEdge('edge3'); expect(segment.getFirstID()).toEqual('edge2'); expect(segment.getLastID()).toEqual('edge2'); // Returns undefined when all edges are deleted segment.removeEdge('edge2'); expect(segment.getFirstID()).toBeUndefined(); expect(segment.getLastID()).toBeUndefined(); // Appends and prepends new edges segment.prependEdge(oneEdge); segment.appendEdge(anotherEdge); expect(segment.getFirstID()).toEqual('edgeOneEdge'); expect(segment.getLastID()).toEqual('edgeAnotherEdge'); }); it('should concat segments', () => { segment.addEdgesAfterCursor(edges, null); var segment2 = new GraphQLSegment(); segment2.addEdgesAfterCursor(moreEdges, null); var concatenated = segment.concatSegment(segment2); expect(concatenated).toBe(true); var metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual( ['edge1', 'edge2', 'edge3', 'edge4', 'edge5', 'edge6'] ); expect(metadata.cursors).toEqual( ['cursor1', 'cursor2', 'cursor3', 'cursor4', 'cursor5', 'cursor6'] ); }); it('should concat with empty segments', () => { var segment2 = new GraphQLSegment(); segment2.addEdgesAfterCursor(edges, null); // Concatenating from an empty segment var concatenated = segment.concatSegment(segment2); expect(concatenated).toBe(true); var metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edge1', 'edge2', 'edge3']); expect(metadata.cursors).toEqual(['cursor1', 'cursor2', 'cursor3']); var segment3 = new GraphQLSegment(); // Concatenating empty segment concatenated = segment.concatSegment(segment3); expect(concatenated).toBe(true); metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edge1', 'edge2', 'edge3']); expect(metadata.cursors).toEqual(['cursor1', 'cursor2', 'cursor3']); }); it('should concat with deleted edges', () => { // Makes sure we update cursor and id to index map correctly // based on removal time. var edges345 = [ { __dataID__: 'edge3', node: {__dataID__: 'id3'}, cursor: 'cursor3', }, { __dataID__: 'edge4', node: {__dataID__: 'id4'}, cursor: 'cursor4', }, { __dataID__: 'edge5', node: {__dataID__: 'id5'}, cursor: 'cursor5', }, ]; // deleted edge in the original segment segment.addEdgesAfterCursor(edges, null); segment.removeEdge('edge3'); var segment2 = new GraphQLSegment(); segment2.addEdgesAfterCursor(edges345, null); var concatenated = segment.concatSegment(segment2); expect(concatenated).toBe(true); var metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual( ['edge1', 'edge2', 'edge3', 'edge4', 'edge5'] ); expect(metadata.cursors).toEqual( ['cursor1', 'cursor2', 'cursor3', 'cursor4', 'cursor5'] ); expect(segment.containsEdgeWithID('edge3')).toBe(true); expect(segment.containsEdgeWithCursor('cursor3')).toBe(true); // deleted edge in the input segment segment = new GraphQLSegment(); segment.addEdgesAfterCursor(edges, null); segment2 = new GraphQLSegment(); segment2.addEdgesAfterCursor(edges345, null); segment2.removeEdge('edge3'); concatenated = segment.concatSegment(segment2); expect(concatenated).toBe(true); metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual( ['edge1', 'edge2', 'edge3', 'edge4', 'edge5'] ); expect(metadata.cursors).toEqual( ['cursor1', 'cursor2', 'cursor3', 'cursor4', 'cursor5'] ); expect(segment.containsEdgeWithID('edge3')).toBe(true); expect(segment.containsEdgeWithCursor('cursor3')).toBe(true); }); it('should toJSON', () => { segment.addEdgesAfterCursor(edges, null); var actual = JSON.stringify(segment); expect(actual).toEqual('[{"0":{"edgeID":"edge1","cursor":"cursor1",' + '"deleted":false},"1":{"edgeID":"edge2","cursor":"cursor2",' + '"deleted":false},"2":{"edgeID":"edge3","cursor":"cursor3","deleted"' + ':false}},{"edge1":[0],"edge2":[1],"edge3":[2]},{"cursor1":0,' + '"cursor2":1,"cursor3":2},0,2,3]' ); segment = GraphQLSegment.fromJSON(JSON.parse(actual)); var metadata = getAllMetadata(segment); expect(metadata.edgeIDs).toEqual(['edge1', 'edge2', 'edge3']); expect(metadata.cursors).toEqual(['cursor1', 'cursor2', 'cursor3']); }); });
venepe/relay
src/legacy/store/__tests__/GraphQLSegment-test.js
JavaScript
bsd-3-clause
16,171
'use strict'; const schema = require('screwdriver-data-schema'); const listSchema = schema.models.banner.list; module.exports = () => ({ method: 'GET', path: '/banners', config: { description: 'Get banners', notes: 'Returns all banner records', tags: ['api', 'banners'], handler: (request, reply) => { const { bannerFactory } = request.server.app; // list params defaults to empty object in models if undefined return bannerFactory.list({ params: request.query }) .then(banners => reply(banners.map(c => c.toJson()))); }, response: { schema: listSchema } } });
screwdriver-cd/api
plugins/banners/list.js
JavaScript
bsd-3-clause
700
var through = require('through2') module.exports = function (filename) { return through(function (buf, enc, next) { next(null, buf.toString().toUpperCase()) }) }
livejs/tequire
test/uppercase.js
JavaScript
isc
170
Array.prototype.equals = function(array) { // if the other array is a falsy value, return if (!array) return false; // compare lengths - can save a lot of time if (this.length != array.length) return false; for (var i = 0, l = this.length; i < l; i++) { // Check if we have nested arrays if (this[i] instanceof Array && array[i] instanceof Array) { // recurse into the nested arrays if (!this[i].equals(array[i])) return false; } else if (this[i] != array[i]) { // Warning - two different object instances will never be equal: {x:20} != {x:20} return false; } } return true; } var installed_date = new Date().getTime(); var DefaultSettings = { "installed_date": installed_date, "timestamp": "absolute", "full_after_24h": false, "name_display": "both", "typeahead_display_username_only": true, "circled_avatars": true, "no_columns_icons": true, "yt_rm_button": true, "small_icons_compose": true, "grayscale_notification_icons": false, "url_redirection": true, "blurred_modals": true, "only_one_thumbnails": true, "minimal_mode": true, "flash_tweets": "mentions", "shorten_text": false, "share_button": true, "providers": { "500px": true, "bandcamp": true, "cloudapp": true, "dailymotion": true, "deviantart": true, "dribbble": true, "droplr": true, "flickr": true, "imgly": true, "imgur": true, "instagram": true, "mobyto": true, "soundcloud": true, "ted": true, "toresize": true, "tumblr": true, "vimeo": true, "yfrog": true, } }; var currentOptions; function onInstall() { chrome.tabs.create({ url: "options/options.html#installed" }); } function onUpdate() { chrome.tabs.create({ url: "options/options.html#updated" }); } function getVersion() { var details = chrome.app.getDetails(); return details.version; } var currVersion = getVersion(); if (!localStorage['version']) { localStorage['version'] = currVersion; } var prevVersion = localStorage['version']; function init() { const TWEETDECK_WEB_URL = 'https://tweetdeck.twitter.com'; /** * Step 2: Collate a list of all the open tabs. */ function gatherTabs(urls, itemInfos) { var allTheTabs = []; var windowsChecked = 0; console.log("gatherTabs", itemInfos.timestamp); // First get all the windows... chrome.windows.getAll(function(windows) { for (var i = 0; i < windows.length; i++) { // ... and then all their tabs. chrome.tabs.getAllInWindow(windows[i].id, function(tabs) { windowsChecked++; allTheTabs = allTheTabs.concat(tabs); if (windowsChecked === windows.length) { // We have all the tabs! Search for a TweetDeck... openApp(urls, allTheTabs, itemInfos); } }); } }); } function openApp(urls, tabs, itemInfos) { console.log("openApp", itemInfos.timestamp); // Search urls in priority order... for (var i = 0; i < urls.length; i++) { var url = urls[i]; // Search tabs... for (var j = 0; j < tabs.length; j++) { var tab = tabs[j]; if (tab.url.indexOf(url) === 0) { // Found it! var tabId = tab.id; chrome.windows.update(tab.windowId, { focused: true }); chrome.tabs.update(tabId, { selected: true, active: true, highlighted: true }, function() { console.log("update", itemInfos.timestamp); var text = itemInfos.text; var url = itemInfos.url; chrome.tabs.sendMessage(tabId, { text: text, url: url, timestamp: itemInfos.timestamp, count: 2 }) }); return; } } } // Didn't find it! Open a new one! chrome.tabs.create({ url: urls[0] }, function(tab) { var count = 0; chrome.tabs.onUpdated.addListener(function(tabId, info) { if (info.status == "complete") { count += 1; console.log("onUpdated", itemInfos.timestamp, count); chrome.tabs.sendMessage(tabId, { text: itemInfos.text, url: itemInfos.url, timestamp: itemInfos.timestamp, count: count }); } }) }); }; var clickHandler = function(info, tab) { var text; var url; if (info.selectionText && currentOptions.shorten_text) { text = "\"" + info.selectionText.substr(0, 110) + "\""; } else if (info.selectionText) { text = "\"" + info.selectionText + "\""; } else { text = tab.title.substr(0, 110); } if (info.linkUrl) { url = info.linkUrl } else { url = info.pageUrl; } if (info.mediaType === "image") { url = info.srcUrl; text = ""; } gatherTabs([TWEETDECK_WEB_URL], { "text": text, "url": url, "timestamp": new Date().getTime() }); }; if (currentOptions.share_button) { console.debug('Share button enabled'); chrome.contextMenus.create({ "title": "Share on (Better) TweetDeck", "contexts": ["page", "selection", "image", "link"], "onclick": clickHandler }); } } chrome.storage.sync.get("BTDSettings", function(obj) { if (obj.BTDSettings !== undefined) { currentOptions = obj.BTDSettings; var reApply = false; for (var setting in DefaultSettings) { if (currentOptions[setting] == undefined) { console.debug("Defining", setting, "to default value", DefaultSettings[setting]); currentOptions[setting] = DefaultSettings[setting]; reApply = true; } } if (currVersion != prevVersion) { if (!(prevVersion.split(".")[0] == currVersion.split(".")[0] && prevVersion.split(".")[1] == currVersion.split(".")[1])) { onUpdate(); } localStorage['version'] = currVersion; } for (var provider in DefaultSettings["providers"]) { if (currentOptions["providers"][provider] == undefined) { console.log("Adding", provider, "as a new provider with value", DefaultSettings["providers"][provider]); currentOptions["providers"][provider] = DefaultSettings["providers"][provider]; reApply = true; } } for (var setting in currentOptions) { if (DefaultSettings[setting] == undefined) { console.log("Deleting", setting); delete currentOptions[setting]; reApply = true; } } for (var setting in currentOptions["providers"]) { if (DefaultSettings["providers"][setting] == undefined) { delete currentOptions["providers"][setting]; reApply = true; } } if (reApply === true) { chrome.storage.sync.set({ "BTDSettings": currentOptions }, function() { console.log("Options updated!"); console.log(currentOptions); init(); }); } else { init(); } } else { chrome.storage.sync.set({ "BTDSettings": DefaultSettings }, function() { console.log("Default options set"); onInstall(); init(); }) } });
rodrigopolo/EvenBetterTweetDeck
source/js/background.js
JavaScript
mit
7,269
const assert = require('assert') const {ipcRenderer, remote} = require('electron') const {BrowserWindow, Menu, MenuItem} = remote const {closeWindow} = require('./window-helpers') describe('menu module', function () { describe('Menu.buildFromTemplate', function () { it('should be able to attach extra fields', function () { var menu = Menu.buildFromTemplate([ { label: 'text', extra: 'field' } ]) assert.equal(menu.items[0].extra, 'field') }) it('does not modify the specified template', function () { var template = ipcRenderer.sendSync('eval', "var template = [{label: 'text', submenu: [{label: 'sub'}]}];\nrequire('electron').Menu.buildFromTemplate(template);\ntemplate;") assert.deepStrictEqual(template, [ { label: 'text', submenu: [ { label: 'sub' } ] } ]) }) it('does not throw exceptions for undefined/null values', function () { assert.doesNotThrow(function () { Menu.buildFromTemplate([ { label: 'text', accelerator: undefined }, { label: 'text again', accelerator: null } ]) }) }) describe('Menu.buildFromTemplate should reorder based on item position specifiers', function () { it('should position before existing item', function () { var menu = Menu.buildFromTemplate([ { label: '2', id: '2' }, { label: '3', id: '3' }, { label: '1', id: '1', position: 'before=2' } ]) assert.equal(menu.items[0].label, '1') assert.equal(menu.items[1].label, '2') assert.equal(menu.items[2].label, '3') }) it('should position after existing item', function () { var menu = Menu.buildFromTemplate([ { label: '1', id: '1' }, { label: '3', id: '3' }, { label: '2', id: '2', position: 'after=1' } ]) assert.equal(menu.items[0].label, '1') assert.equal(menu.items[1].label, '2') assert.equal(menu.items[2].label, '3') }) it('should position at endof existing separator groups', function () { var menu = Menu.buildFromTemplate([ { type: 'separator', id: 'numbers' }, { type: 'separator', id: 'letters' }, { label: 'a', id: 'a', position: 'endof=letters' }, { label: '1', id: '1', position: 'endof=numbers' }, { label: 'b', id: 'b', position: 'endof=letters' }, { label: '2', id: '2', position: 'endof=numbers' }, { label: 'c', id: 'c', position: 'endof=letters' }, { label: '3', id: '3', position: 'endof=numbers' } ]) assert.equal(menu.items[0].id, 'numbers') assert.equal(menu.items[1].label, '1') assert.equal(menu.items[2].label, '2') assert.equal(menu.items[3].label, '3') assert.equal(menu.items[4].id, 'letters') assert.equal(menu.items[5].label, 'a') assert.equal(menu.items[6].label, 'b') assert.equal(menu.items[7].label, 'c') }) it('should create separator group if endof does not reference existing separator group', function () { var menu = Menu.buildFromTemplate([ { label: 'a', id: 'a', position: 'endof=letters' }, { label: '1', id: '1', position: 'endof=numbers' }, { label: 'b', id: 'b', position: 'endof=letters' }, { label: '2', id: '2', position: 'endof=numbers' }, { label: 'c', id: 'c', position: 'endof=letters' }, { label: '3', id: '3', position: 'endof=numbers' } ]) assert.equal(menu.items[0].id, 'letters') assert.equal(menu.items[1].label, 'a') assert.equal(menu.items[2].label, 'b') assert.equal(menu.items[3].label, 'c') assert.equal(menu.items[4].id, 'numbers') assert.equal(menu.items[5].label, '1') assert.equal(menu.items[6].label, '2') assert.equal(menu.items[7].label, '3') }) it('should continue inserting items at next index when no specifier is present', function () { var menu = Menu.buildFromTemplate([ { label: '4', id: '4' }, { label: '5', id: '5' }, { label: '1', id: '1', position: 'before=4' }, { label: '2', id: '2' }, { label: '3', id: '3' } ]) assert.equal(menu.items[0].label, '1') assert.equal(menu.items[1].label, '2') assert.equal(menu.items[2].label, '3') assert.equal(menu.items[3].label, '4') assert.equal(menu.items[4].label, '5') }) }) }) describe('Menu.insert', function () { it('should store item in @items by its index', function () { var menu = Menu.buildFromTemplate([ { label: '1' }, { label: '2' }, { label: '3' } ]) var item = new MenuItem({ label: 'inserted' }) menu.insert(1, item) assert.equal(menu.items[0].label, '1') assert.equal(menu.items[1].label, 'inserted') assert.equal(menu.items[2].label, '2') assert.equal(menu.items[3].label, '3') }) }) describe('Menu.popup', function () { let w = null afterEach(function () { return closeWindow(w).then(function () { w = null }) }) it('returns immediately (default async)', function () { w = new BrowserWindow({show: false, width: 200, height: 200}) const menu = Menu.buildFromTemplate([ { label: '1' }, { label: '2' }, { label: '3' } ]) menu.popup(w, {x: 100, y: 100}) menu.closePopup(w) }) }) describe('MenuItem.click', function () { it('should be called with the item object passed', function (done) { var menu = Menu.buildFromTemplate([ { label: 'text', click: function (item) { assert.equal(item.constructor.name, 'MenuItem') assert.equal(item.label, 'text') done() } } ]) menu.delegate.executeCommand({}, menu.items[0].commandId) }) }) describe('MenuItem with checked property', function () { it('clicking an checkbox item should flip the checked property', function () { var menu = Menu.buildFromTemplate([ { label: 'text', type: 'checkbox' } ]) assert.equal(menu.items[0].checked, false) menu.delegate.executeCommand({}, menu.items[0].commandId) assert.equal(menu.items[0].checked, true) }) it('clicking an radio item should always make checked property true', function () { var menu = Menu.buildFromTemplate([ { label: 'text', type: 'radio' } ]) menu.delegate.executeCommand({}, menu.items[0].commandId) assert.equal(menu.items[0].checked, true) menu.delegate.executeCommand({}, menu.items[0].commandId) assert.equal(menu.items[0].checked, true) }) it('at least have one item checked in each group', function () { var i, j, k, menu, template template = [] for (i = j = 0; j <= 10; i = ++j) { template.push({ label: '' + i, type: 'radio' }) } template.push({ type: 'separator' }) for (i = k = 12; k <= 20; i = ++k) { template.push({ label: '' + i, type: 'radio' }) } menu = Menu.buildFromTemplate(template) menu.delegate.menuWillShow() assert.equal(menu.items[0].checked, true) assert.equal(menu.items[12].checked, true) }) it('should assign groupId automatically', function () { var groupId, i, j, k, l, m, menu, template template = [] for (i = j = 0; j <= 10; i = ++j) { template.push({ label: '' + i, type: 'radio' }) } template.push({ type: 'separator' }) for (i = k = 12; k <= 20; i = ++k) { template.push({ label: '' + i, type: 'radio' }) } menu = Menu.buildFromTemplate(template) groupId = menu.items[0].groupId for (i = l = 0; l <= 10; i = ++l) { assert.equal(menu.items[i].groupId, groupId) } for (i = m = 12; m <= 20; i = ++m) { assert.equal(menu.items[i].groupId, groupId + 1) } }) it("setting 'checked' should flip other items' 'checked' property", function () { var i, j, k, l, m, menu, n, o, p, q, template template = [] for (i = j = 0; j <= 10; i = ++j) { template.push({ label: '' + i, type: 'radio' }) } template.push({ type: 'separator' }) for (i = k = 12; k <= 20; i = ++k) { template.push({ label: '' + i, type: 'radio' }) } menu = Menu.buildFromTemplate(template) for (i = l = 0; l <= 10; i = ++l) { assert.equal(menu.items[i].checked, false) } menu.items[0].checked = true assert.equal(menu.items[0].checked, true) for (i = m = 1; m <= 10; i = ++m) { assert.equal(menu.items[i].checked, false) } menu.items[10].checked = true assert.equal(menu.items[10].checked, true) for (i = n = 0; n <= 9; i = ++n) { assert.equal(menu.items[i].checked, false) } for (i = o = 12; o <= 20; i = ++o) { assert.equal(menu.items[i].checked, false) } menu.items[12].checked = true assert.equal(menu.items[10].checked, true) for (i = p = 0; p <= 9; i = ++p) { assert.equal(menu.items[i].checked, false) } assert.equal(menu.items[12].checked, true) for (i = q = 13; q <= 20; i = ++q) { assert.equal(menu.items[i].checked, false) } }) }) describe('MenuItem command id', function () { it('cannot be overwritten', function () { var item = new MenuItem({ label: 'item' }) var commandId = item.commandId assert(commandId != null) item.commandId = '' + commandId + '-modified' assert.equal(item.commandId, commandId) }) }) describe('MenuItem with invalid type', function () { it('throws an exception', function () { assert.throws(function () { Menu.buildFromTemplate([ { label: 'text', type: 'not-a-type' } ]) }, /Unknown menu item type: not-a-type/) }) }) describe('MenuItem with submenu type and missing submenu', function () { it('throws an exception', function () { assert.throws(function () { Menu.buildFromTemplate([ { label: 'text', type: 'submenu' } ]) }, /Invalid submenu/) }) }) describe('MenuItem role', function () { it('includes a default label and accelerator', function () { var item = new MenuItem({role: 'close'}) assert.equal(item.label, process.platform === 'darwin' ? 'Close Window' : 'Close') assert.equal(item.accelerator, undefined) assert.equal(item.getDefaultRoleAccelerator(), 'CommandOrControl+W') item = new MenuItem({role: 'close', label: 'Other', accelerator: 'D'}) assert.equal(item.label, 'Other') assert.equal(item.accelerator, 'D') assert.equal(item.getDefaultRoleAccelerator(), 'CommandOrControl+W') item = new MenuItem({role: 'help'}) assert.equal(item.label, 'Help') assert.equal(item.accelerator, undefined) assert.equal(item.getDefaultRoleAccelerator(), undefined) item = new MenuItem({role: 'hide'}) assert.equal(item.label, 'Hide Electron Test') assert.equal(item.accelerator, undefined) assert.equal(item.getDefaultRoleAccelerator(), 'Command+H') }) }) })
brave/muon
spec/api-menu-spec.js
JavaScript
mit
12,792
/** settings.js */
majestrate/nntpchan
contrib/frontends/django/nntpchan/nntpchan/frontend/static/settings.js
JavaScript
mit
19
const gulp = require('gulp') const plugins = require('gulp-load-plugins')() const rupture = require('rupture') gulp.task('css', function () { return gulp.src('./static/styl/index.styl') .pipe(plugins.stylus({ use: [rupture()] })) .pipe(plugins.autoprefixer()) .pipe(plugins.csso()) .pipe(gulp.dest('./dist')) })
izolate/smr10-tracker
gulp/css.js
JavaScript
mit
341
var through = require('through2') var split = require('split2') var duplexer = require('duplexer2') module.exports = function (opt) { opt = opt || {} var out = through() var parse = split() .on('data', function (buf) { var str = buf.toString() var match = /^\[.+console\([0-9]+\)\]\s*\"(.*)\"/i.exec(str) if (match) { if (opt.verbose) { out.push(match[1] + '\n') } } else if (!/^\[[0-9]+[\/\:]/.test(str)) { out.push(str + '\n') } }) return duplexer(parse, out) }
Jam3/chromeo
lib/fix-logs.js
JavaScript
mit
547
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- if (this.WScript && this.WScript.LoadScriptFile) { // Check for running in ch this.WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js"); } var tests = [ { name: "Increment BigInt literal", body: function () { var x = 123n; assert.isTrue(x == 123n); x++; assert.isTrue(x == 124n); ++x; assert.isTrue(x == 125n); } }, { name: "Increment negative BigInt literal", body: function () { var x = -123n; assert.isTrue(x == -123n); x++; assert.isTrue(x == -122n); ++x; assert.isTrue(x == -121n); } }, { name: "Increment -1n", body: function () { var x = -1n; assert.isTrue(x == -1n); x++; assert.isTrue(x == 0n); ++x; assert.isTrue(x == 1n); } }, { name: "Increment to change length", body: function () { var x = 4294967295n; assert.isTrue(x == 4294967295n); x++; assert.isTrue(x == 4294967296n); ++x; assert.isTrue(x == 4294967297n); var y = -4294967297n; assert.isTrue(y == -4294967297n); y++; assert.isTrue(y == -4294967296n); ++y; assert.isTrue(y == -4294967295n); } }, { name: "Increment BigInt Object", body: function () { var x = BigInt(12345678901234567890n); var y = BigInt(12345678901234567891n); assert.isTrue(x < y); ++x; assert.isTrue(x == y); x++; assert.isTrue(x >= y); } }, { name: "Out of 64 bit range", body: function () { var x = 1234567890123456789012345678901234567890n; var y = BigInt(1234567890123456789012345678901234567891n); assert.isFalse(x == y); x++; ++y; assert.isTrue(x < y); ++x; assert.isTrue(x == y); } }, { name: "Very big", body: function () { var x = eval('1234567890'.repeat(20)+'0n'); var y = BigInt(eval('1234567890'.repeat(20)+'1n')); assert.isFalse(x == y); x++; ++y; assert.isTrue(x < y); ++x; assert.isTrue(x == y); } }, { name: "With assign", body: function () { var x = 3n; var y = x++; assert.isTrue(x == 4n); assert.isTrue(y == 3n); y = ++x; assert.isTrue(x == 5n); assert.isTrue(y == 5n); } }, ]; testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
Microsoft/ChakraCore
test/BigInt/increment.js
JavaScript
mit
3,410
(function() { 'use strict'; angular .module('siteApp') .constant('paginationConstants', { 'itemsPerPage': 20 }); })();
lucasa/Politicos
site/src/main/webapp/app/components/form/pagination.constants.js
JavaScript
mit
164
/*! * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file. */ import {patterns} from '@ciscospark/common'; const usersByEmail = new WeakMap(); const usersById = new WeakMap(); /** * @class */ export default class UserUUIDStore { /** * @constructs {UserUUIDStore} */ constructor() { usersByEmail.set(this, new Map()); usersById.set(this, new Map()); } /** * Adds a user object to the store * @param {Object} user * @param {string} user.id * @param {string} user.emailAddress * @returns {Promise} */ add(user) { if (!user.id) { return Promise.reject(new Error('`user.id` is required')); } if (!user.emailAddress) { return Promise.reject(new Error('`user.emailAddress` is required')); } if (!patterns.uuid.test(user.id)) { return Promise.reject(new Error('`user.id` does not appear to be a uuid')); } if (!patterns.email.test(user.emailAddress)) { return Promise.reject(new Error('`user.emailAddress` does not appear to be an email address')); } const p1 = this.getById(user.id) .then((u) => usersById.get(this).set(user.id, Object.assign({}, u, user))) .catch(() => usersById.get(this).set(user.id, Object.assign({}, user))); const p2 = this.getByEmail(user.emailAddress) .then((u) => usersByEmail.get(this).set(user.emailAddress, Object.assign({}, u, user))) .catch(() => usersByEmail.get(this).set(user.emailAddress, Object.assign({}, user))); return Promise.all([p1, p2]); } /** * Retrievves the specified user object from the store * @param {string} id * @returns {Promise<Object>} */ get(id) { if (patterns.uuid.test(id)) { return this.getById(id); } if (patterns.email.test(id)) { return this.getByEmail(id); } return Promise.reject(new Error('`id` does not appear to be a valid user identifier')); } /** * Retrieves the specified user object by id from the store * @param {Object} id * @returns {Promise<Object>} */ getById(id) { const ret = usersById.get(this).get(id); if (ret) { return Promise.resolve(ret); } return Promise.reject(new Error('No user found by specified id')); } /** * Retrieves the specified user object by id from the store * @param {Object} email * @returns {Promise<Object>} */ getByEmail(email) { const ret = usersByEmail.get(this).get(email); if (ret) { return Promise.resolve(ret); } return Promise.reject(new Error('No user found by specified email address')); } }
ciscospark/spark-js-sdk
packages/node_modules/@ciscospark/internal-plugin-user/src/user-uuid-store.js
JavaScript
mit
2,592
var assert = require('assert') , fs = require('fs'); var DB_PATH = __dirname + '/../../tmp/db'; var USERS = { 1: {name: 'Pedro', age: 35, sex: 'm'} , 2: {name: 'John', age: 32, sex: 'm'} , 3: {name: 'Bruno', age: 28, sex: 'm'} , 4: {name: 'Sandra', age: 35, sex: 'f'} , 5: {name: 'Patricia', age: 42, sex: 'f'} , 6: {name: 'Joana', age: 29, sex: 'f'} , 7: {name: 'Susana', age: 30, sex: 'f'} }; var USER_COUNT = 7; module.exports.setup = function(next) { fs.readdirSync(DB_PATH).forEach(function(dir) { fs.unlinkSync(DB_PATH + '/' + dir); }); next(); }; module.exports.run = function(next) { var alfred = require('../../lib/alfred'); var timeout = setTimeout(function() { throw new Error('timeout'); }, 5000); alfred.open(DB_PATH, function(err, db) { if (err) { next(err); return; } db.ensure_key_map_attached('users', null, function(err) { if (err) { next(err); return; } var age_transform_function = function(user) { return user.age; }; var sex_transform_function = function(user) { return user.sex; }; db.users.ensureIndex('sex', {ordered: true}, sex_transform_function, function(err) { if (err) { next(err); return; } db.users.ensureIndex('age', {ordered: true}, age_transform_function, function(err) { if (err) { next(err); return; } var users_in = 0; for (var id in USERS) { if (USERS.hasOwnProperty(id)) { (function(id) { var user = USERS[id]; db.users.put(id, user, function(err) { if (err) { next(err); return; } users_in ++; if (users_in == USER_COUNT) { // all users done var users_1_found = 0; var users_2_found = 0; var users_3_found = 0; var users_4 = false var end_test = function() { if (users_1_found == 2 && users_2_found == 4 && users_3_found == 6 && users_4) { db.close(function(err) { if (err) { next(err); return; } clearTimeout(timeout); next(); }) } }; db.users.find({'age' : {$gt: 29, $lt: 42, $lte: 35}, 'sex': {$eq: 'f'}}) (function(err, key, value) { if (err) { next(err); return; } assert.deepEqual(value, USERS[key]); assert.ok(value.age > 29 && value.age <= 35, 'age is not equal to > 29 and < 35 for found user with key ' + key); assert.ok(value.sex =='f', 'sex != \'f\' for found user with key ' + key); users_1_found ++; assert.ok(users_1_found <= 2, 'already found ' + users_1_found + ' users'); end_test(); }) .reset() .where({'age' : {$gt: 29, $lt: 42}}) (function(err, key, value) { if (err) { next(err); return; } assert.deepEqual(value, USERS[key]); assert.ok(value.age > 29 && value.age < 42, 'age is not equal to > 29 and < 35 for found user with key ' + key); users_2_found ++; assert.ok(users_2_found <= 4, 'already found ' + users_2_found + ' users'); end_test(); }) .reset() .where({'age' : {$gt: 29, $lt: 35}}) .or({'sex': {$eq: 'f'}}) (function(err, key, value) { if (err) { next(err); return; } assert.deepEqual(value, USERS[key]); assert.ok((value.age > 29 && value.age < 35) || value.sex == 'f', '(age is not equal to > 29 and < 35) or sex == \'f\' for found user with key ' + key); users_3_found ++; assert.ok(users_3_found <= 6, 'already found ' + users_3_found + ' users'); end_test(); }) .bulk(function(err, records) { if (err) { next(err); return; } assert.equal(6, records.length); records.forEach(function(record) { assert.deepEqual(record.value, USERS[record.key]); }); users_4 = true; end_test(); }); } }); })(id); } } }); }); }) }); };
Student007/alfred
test/operators/test_chainable.js
JavaScript
mit
4,902
module.exports={A:{A:{"2":"K D G E A B iB"},B:{"2":"2 C d J M H I AB"},C:{"2":"0 1 2 3 4 6 7 8 9 fB FB F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z IB BB CB DB GB ZB YB"},D:{"2":"0 1 2 3 4 6 7 8 9 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z IB BB CB DB GB SB OB MB lB NB KB AB PB QB"},E:{"2":"F N K D G E A B RB JB TB UB VB WB XB","132":"5 C p aB"},F:{"2":"0 1 5 6 E B C J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z bB cB dB eB p EB gB"},G:{"2":"G JB hB HB jB kB LB mB nB oB pB qB rB","132":"sB tB uB"},H:{"2":"vB"},I:{"2":"4 FB F wB xB yB zB HB 0B 1B"},J:{"2":"D A"},K:{"2":"5 A B C L p EB"},L:{"2":"KB"},M:{"2":"3"},N:{"2":"A B"},O:{"2":"2B"},P:{"2":"F 3B 4B 5B 6B 7B"},Q:{"2":"8B"},R:{"2":"9B"},S:{"2":"AC"}},B:5,C:"CSS math functions min(), max() and clamp()"};
quentinbernet/quentinbernet.github.io
node_modules/caniuse-lite/data/features/css-math-functions.js
JavaScript
mit
918
define(['marionette', '../../../shared/component/componentLayoutTemplate.hbs', './treeHtmlCodeTemplate.hbs', './treeJsCodeTemplate.hbs', './treeBodyView', './treeTestView', '../../../shared/component/componentExampleCodeView', 'rup.tree'], function(Marionette, ComponentLayoutTemplate, TreeHtmlCodeTemplate, TreeJsCodeTemplate, TreeBodyView, TreeTestView, ComponentExampleCodeView){ var TreeView = Marionette.LayoutView.extend({ template: ComponentLayoutTemplate, regions:{ Main: '#componentMainBody', Example: '#exampleCode', Test: '#componentTest' }, onRender: fncOnRender }); function fncOnRender(){ var $view = this; $view.Main.show(new TreeBodyView()); $view.Example.show(new ComponentExampleCodeView({ templateHtml: TreeHtmlCodeTemplate, templateJs: TreeJsCodeTemplate })); window.$ = $; $view.Test.show(new TreeTestView()); } return TreeView; });
UDA-EJIE/uda-rup
demo/app/components/tree/examples/treeView.js
JavaScript
mit
906
'use strict'; /** * Module dependencies. */ var errorHandler = require('./errors.server.controller'), db = require('../models/fixsession.server.model'), _ = require('lodash'), bluebird = require('bluebird'); /** * Create a Fixsession */ exports.create = function(req, res) { db.FixSession.create({ name: req.body.name, assignedFixManager: req.body.assignedFixManager, assignedTcpManager: req.body.assignedTcpManager, initiator : req.body.initiator, host: req.body.host, port: req.body.port, username: req.body.username, password: req.body.password, defaultRoute: req.body.defaultRoute, assignedOOBProcessor: req.body.assignedOOBProcessor }).complete(function(err, results){ res.sendStatus(201); }); }; /** * List of Fixsessions */ exports.list = function(req, res) { db.FixSession.findAll() .complete(function(err, results){ res.json(results); }); };
victorleungtw/fixit
app/controllers/fixsessions.server.controller.js
JavaScript
mit
959
BASE.require([ "BASE.data.Edm", "BASE.odata4.ODataAnnotation" ], function () { var ODataAnnotation = BASE.odata4.ODataAnnotation; BASE.namespace("BASE.data.testing"); var HumanoidType = function () { }; HumanoidType.annotations = [new ODataAnnotation("Namespace.HumanoidType")]; HumanoidType.None = new Enum(0); HumanoidType.None.name = "None"; HumanoidType.Human = new Enum(1); HumanoidType.Human.name = "Human"; HumanoidType.Vulcan = new Enum(2); HumanoidType.Vulcan.name = "Vulcan"; BASE.data.testing.HumanoidType = HumanoidType; });
jaredjbarnes/WoodlandCreatures
packages/WebLib.2.0.0.724/content/lib/weblib/lib/BASE/BASE/data/testing/HumanoidType.js
JavaScript
mit
617
import React, { Component } from 'react'; import { GoogleMapLoader, GoogleMap, Marker, SearchBox } from 'react-google-maps'; class CreateMapView extends Component { constructor(props) { super(props); this.state = { coordinates: '', }; this.handlePlacesChanged = this.handlePlacesChanged.bind(this); } handlePlacesChanged() { const places = this.refs.searchBox.getPlaces(); const address = places[0].formatted_address; const lat = places[0].geometry.location.lat().toString(); const lng = places[0].geometry.location.lng().toString(); const coordinates = lat.concat(',').concat(lng); this.props.addMarker(coordinates); this.props.onLocationChange(address); } render() { return ( <div className="ui card"> <GoogleMapLoader options={{ mapTypeControl: false }} containerElement={ <div {...this.props} style={{ height: '250px', width: '500px', }} /> } googleMapElement={ <GoogleMap zoom={this.props.zoom} center={this.props.center} onClick={this.props.addMarker.bind(this)} options={{ disableDefaultUI: true }} > <SearchBox className="searchBox" ref="searchBox" bounds={this.props.bounds} controlPosition={google.maps.ControlPosition.TOP_CENTER} placeholder="Enter spread location (e.g. a park)" onPlacesChanged={this.handlePlacesChanged.bind(this)} /> {this.props.markers.map((marker) => { return ( <Marker {...marker} /> ); })} </GoogleMap> } /> </div> ); } } export default CreateMapView;
Block-and-Frame/block-and-frame
app/components/events/CreateMapView.js
JavaScript
mit
2,036
"use strict" var redrawService = require("./redraw") module.exports = require("./api/router")(window, redrawService)
tivac/mithril.js
route.js
JavaScript
mit
119
global.requireWithCoverage = function (libName) { if (process.env.NODE_CHESS_COVERAGE) { return require('../lib-cov/' + libName + '.js'); } if (libName === 'index') { return require('../lib'); } else { return require('../lib/' + libName + '.js'); } }; global.chai = require('chai'); global.assert = chai.assert; global.expect = chai.expect; global.should = chai.should();
akiomik/node-chess
test/common.js
JavaScript
mit
384
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'SALTI Test Express Site' }); }); module.exports = router;
cicorias/salt2
sample/routes/index.js
JavaScript
mit
221
version https://git-lfs.github.com/spec/v1 oid sha256:49c54ee863855e8fa7d43bdb5142596122609269a2e98c9a92e10dffcda1376d size 65177
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.1.2/node/node-debug.js
JavaScript
mit
130
'use strict'; var util = require('util'); var GtReq = require('../GtReq'); var BaseTemplate = require('./BaseTemplate'); function IncTemplate(options) { BaseTemplate.call(this, options); options = util._extend({ transmissionContent: '', incAppId: '' }, options); util._extend(this, options); } util.inherits(IncTemplate, BaseTemplate); IncTemplate.prototype.getActionChain = function() { var actionChain1 = new GtReq.ActionChain({ actionId: 1, type: GtReq.ActionChain.Type.Goto, next: 10030 }); var appStartUp = new GtReq.AppStartUp({ android: '', symbia: '', ios: '' }); // 启动app // Start the app var actionChain2 = new GtReq.ActionChain({ actionId: 10030, type: GtReq.ActionChain.Type.startapp, appid: this.incAppId, autostart: 1 === this.transmissionType, appstartupid: appStartUp, failedAction: 100, next: 100 }); // 结束 // Finish var actionChain3 = new GtReq.ActionChain({ actionId: 100, type: GtReq.ActionChain.Type.eoa }); var actionChains = [actionChain1, actionChain2, actionChain3]; return actionChains; }; IncTemplate.prototype.getTransmissionContent = function() { return this.transmissionContent; }; IncTemplate.prototype.getPushType = function() { return 'TransmissionMsg'; }; /** * 设置 透传消息类型 1:收到通知立即启动应用 2:收到通知不启动应用 * Set direct display message type 1:Start the app once gets notification. 2:Not to start the app once gets notification * @param transmissionType */ IncTemplate.prototype.setTransmissionType = function(transmissionType) { this.transmissionType = transmissionType; return this; }; IncTemplate.prototype.setTransmissionContent = function(transmissionContent) { this.transmissionContent = transmissionContent; return this; }; IncTemplate.prototype.setIncAppId = function(incAppId) { this.incAppId = incAppId; return this; }; module.exports = IncTemplate;
hardylake8020/youka-server
libraries/getuiLibs/getui/template/IncTemplate.js
JavaScript
mit
2,170
/** * @module ember-paper */ import Ember from 'ember'; import RippleMixin from '../mixins/ripple-mixin'; import ProxyMixin from 'ember-paper/mixins/proxy-mixin'; const { get, set, isEmpty, computed, run, Component } = Ember; /** * @class PaperItem * @extends Ember.Component * @uses ProxyMixin * @uses RippleMixin */ export default Component.extend(RippleMixin, ProxyMixin, { tagName: 'md-list-item', // Ripple Overrides rippleContainerSelector: '.md-no-style', center: false, dimBackground: true, outline: false, classNameBindings: ['shouldBeClickable:md-clickable', 'hasProxiedComponent:md-proxy-focus'], attributeBindings: ['role', 'tabindex'], role: 'listitem', tabindex: '-1', hasProxiedComponent: computed.bool('proxiedComponents.length'), hasPrimaryAction: computed.notEmpty('onClick'), hasSecondaryAction: computed('secondaryItem', 'onClick', function() { let secondaryItem = get(this, 'secondaryItem'); if (!isEmpty(secondaryItem)) { let hasClickAction = get(secondaryItem, 'onClick'); let hasChangeAction = get(secondaryItem, 'onChange'); return hasClickAction || hasChangeAction; } else { return false; } }), secondaryItem: computed('proxiedComponents.[]', function() { let proxiedComponents = get(this, 'proxiedComponents'); return proxiedComponents.find((component)=> { return get(component, 'isSecondary'); }); }), shouldBeClickable: computed.or('proxiedComponents.length', 'onClick'), click(ev) { this.get('proxiedComponents').forEach((component)=> { if (component.processProxy && !get(component, 'disabled') && (get(component, 'bubbles') | !get(this, 'hasPrimaryAction'))) { component.processProxy(); } }); this.sendAction('onClick', ev); }, setupProxiedComponent() { let tEl = this.$(); let proxiedComponents = get(this, 'proxiedComponents'); proxiedComponents.forEach((component)=> { let isProxyHandlerSet = get(component, 'isProxyHandlerSet'); // we run init only once for each component. if (!isProxyHandlerSet) { // Allow proxied component to propagate ripple hammer event if (!get(component, 'onClick') && !get(component, 'propagateRipple')) { set(component, 'propagateRipple', true); } // ripple let el = component.$(); set(this, 'mouseActive', false); el.on('mousedown', ()=> { set(this, 'mouseActive', true); run.later(()=> { set(this, 'mouseActive', false); }, 100); }); el.on('focus', ()=> { if (!get(this, 'mouseActive')) { tEl.addClass('md-focused'); } el.on('blur', function proxyOnBlur() { tEl.removeClass('md-focused'); el.off('blur', proxyOnBlur); }); }); // If we don't have primary action then // no need to bubble if (!get(this, 'hasPrimaryAction')) { let bubbles = get(component, 'bubbles'); if (isEmpty(bubbles)) { set(component, 'bubbles', false); } } else if (get(proxiedComponents, 'length')) { // primary action exists. Make sure child // that has separate action won't bubble. proxiedComponents.forEach((component)=> { let hasClickAction = get(component, 'onClick'); let hasChangeAction = get(component, 'onChange'); if (hasClickAction || hasChangeAction) { let bubbles = get(component, 'bubbles'); if (isEmpty(bubbles)) { set(component, 'bubbles', false); } } }); } // Init complete. We don't want it to run again // for that particular component. set(component, 'isProxyHandlerSet', true); } }); } });
tmclouisluk/ember-paper
addon/components/paper-item.js
JavaScript
mit
3,910
/*jshint unused:false */ var dojoConfig = { async: 1, cacheBust: 0, 'routing-map': { pathPrefix: '', layers: {} }, packages: [ { name: 'oe_dojo', location: '..' } ] };
OnroerendErfgoed/oe_dojo
tests/manual/selectiondialog/selectionConfig.js
JavaScript
mit
191
/** * Generate a function that accepts a variable number of arguments as the last * function argument. * * @param {Function} fn * @return {Function} */ module.exports = function (fn) { var count = Math.max(fn.length - 1, 0); return function () { var args = new Array(count); var index = 0; // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments for (; index < count; index++) { args[index] = arguments[index]; } var variadic = args[count] = []; for (; index < arguments.length; index++) { variadic.push(arguments[index]); } return fn.apply(this, args); }; };
blakeembrey/variadic
variadic.js
JavaScript
mit
661
function char2int(c) { return c.charCodeAt(0); } var hexD = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' ]; hexD = ['0'].concat(hexD); function hex(number) { var str = ""; str = hexD[number&0xf] + str str = hexD[(number>>=4)&0xf] + str ; str = hexD[(number>>=4)&0xf] + str ; str = hexD[(number>>=4)&0xf] + str ; return str; } function hex2(number) { var str = ""; str = hexD[number&0xf] + str str = hexD[(number>>=4)&0xf] + str ; return str; } function fromRunLenCodes(runLenArray, bitm) { bitm = bitm || []; var bit = runLenArray[0]; var runLenIdx = 1, bitIdx = 0; var runLen = 0; while (runLenIdx < runLenArray.length) { runLen = runLenArray[runLenIdx]; while (runLen--) { while ((INTBITLEN * (bitm.length)) < bitIdx) bitm.push(0); if (bit) bitm[bitIdx >> D_INTBITLEN] |= (1 << (M_INTBITLEN & bitIdx)); bitIdx++ ; } runLenIdx++ ; bit ^= 1; } return (bitm); } function arguments_or_eval(l) { switch ( l ) { case 'arguments': case 'eval': return true; } return false; }; var has = Object.prototype.hasOwnProperty; function fromcode(codePoint ) { if ( codePoint <= 0xFFFF) return String.fromCharCode(codePoint) ; return String.fromCharCode(((codePoint-0x10000 )>>10)+0x0D800, ((codePoint-0x10000 )&(1024-1))+0x0DC00); } function core(n) { return n.type === PAREN ? n.expr : n; }; function toNum (n) { return (n >= CH_0 && n <= CH_9) ? n - CH_0 : (n <= CH_f && n >= CH_a) ? 10 + n - CH_a : (n >= CH_A && n <= CH_F) ? 10 + n - CH_A : -1; };
Jazzling/jazzle-parser
src/util.js
JavaScript
mit
1,655
import { getTransitionNames, getAvailableTransitionNames, getTransitionStylesName } from 'frontend/transitions'; describe('getTransitionNames', () => { it('returns array of names', () => { const result = getTransitionNames(); expect(result).toContain('scroll'); expect(result).toContain('fade'); }); }); describe('getAvailableTransitions', () => { it('offers fade transitions if section and previous section both have full height', () => { const section = {fullHeight: true}; const previousSection = {fullHeight: true}; const result = getAvailableTransitionNames(section, previousSection); expect(result).toContain('fade'); expect(result).toContain('fadeBg'); }); it('does not offer fade transitions if section does not have full height', () => { const section = {}; const previousSection = {fullHeight: true}; const result = getAvailableTransitionNames(section, previousSection); expect(result).toContain('scroll'); expect(result).not.toContain('fade'); expect(result).not.toContain('fadeBg'); }); it('does not offer fade transitions if previous section does not have full height', () => { const section = {fullHeight: true}; const previousSection = {}; const result = getAvailableTransitionNames(section, previousSection); expect(result).toContain('scroll'); expect(result).not.toContain('fade'); expect(result).not.toContain('fadeBg'); }); }); describe('getTransitionStylesName', () => { it('uses fadeIn if both section and previous section have fullHeight', () => { const previousSection = {fullHeight: true, transition: 'scroll'}; const section = {fullHeight: true, transition: 'fade'}; const nextSection = {transition: 'scroll'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('fadeInScrollOut'); }); it('falls back to scrollIn if previous section does not have fullHeight', () => { const previousSection = {transition: 'scroll'}; const section = {fullHeight: true, transition: 'fade'}; const nextSection = {fullHeight: true, transition: 'scroll'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('scrollInScrollOut'); }); it('falls back to scrollIn if section does not have fullHeight', () => { const previousSection = {fullHeight: true, transition: 'scroll'}; const section = {transition: 'fade'}; const nextSection = {fullHeight: true, transition: 'scroll'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('scrollInScrollOut'); }); it('falls back to scrollIn if previous is missing', () => { const section = {transition: 'fade'}; const nextSection = {fullHeight: true, transition: 'scroll'}; const result = getTransitionStylesName(section, null, nextSection); expect(result).toBe('scrollInScrollOut'); }); it('uses fadeOut if both section and next section have fullHeight', () => { const previousSection = {transition: 'scroll'}; const section = {fullHeight: true, transition: 'reveal'}; const nextSection = {fullHeight: true, transition: 'fade'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('revealFadeOut'); }); it('falls back to scrollOut if next section does not have fullHeight', () => { const previousSection = {transition: 'scroll'}; const section = {fullHeight: true, transition: 'reveal'}; const nextSection = {transition: 'fade'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('revealScrollOut'); }); it('falls back to scrollOut if section does not have fullHeight', () => { const previousSection = {transition: 'scroll'}; const section = {transition: 'reveal'}; const nextSection = {fullHeight: true, transition: 'fade'}; const result = getTransitionStylesName(section, previousSection, nextSection); expect(result).toBe('revealScrollOut'); }); it('falls back to scrollOut if next section is missing', () => { const previousSection = {transition: 'scroll'}; const section = {transition: 'reveal'}; const result = getTransitionStylesName(section, previousSection, null); expect(result).toBe('revealScrollOut'); }); });
tf/pageflow
entry_types/scrolled/package/spec/frontend/transitions-spec.js
JavaScript
mit
4,422
/* * Created for OpenROV: www.openrov.com * Author: Dominik * Date: 06/03/12 * * Description: * This file acts as a mock implementation for the camera module. It reads jpg files from a directory and returns them. * * License * This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a * letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. * */ var EventEmitter = require('events').EventEmitter, fs = require('fs'), path = require('path'), CONFIG = require('./config'), logger = require('./logger').create(CONFIG); var FirmwareInstaller = function () { var installer = new EventEmitter(); installer.installfromsource = function () { installer.install(''); }; installer.unpack = function (filename) { setTimeout(function () { installer.emit('firmwareinstaller-unpacked', 'some directory'); }, 2000); }; installer.compile = function (directory) { setTimeout(function () { installer.emit('firmwareinstaller-output', 'Stated compiling\n'); }, 500); setTimeout(function () { installer.emit('firmwareinstaller-output', 'Do compiling\n'); }, 1000); setTimeout(function () { installer.emit('firmwareinstaller-compilled', directory); }, 2000); }; installer.upload = function (directory) { setTimeout(function () { installer.emit('firmwareinstaller-uploaded', directory); }, 2000); }; installer.install = function (filename) { installer.unpack(filename); setTimeout(installer.compile, 2000); setTimeout(installer.upload, 4000); }; return installer; }; module.exports = FirmwareInstaller;
ChangerR/burrito-cockpid
src/lib/FirmwareInstaller-mock.js
JavaScript
mit
1,829
module.exports = function (config) { config.set({ basePath: './', files: [ 'www/lib/**/*.js', 'www/**/*.js' ], preprocessors: { 'www/app.js': 'coverage', 'www/**/*.js': 'sourcemap' }, autoWatch: true, frameworks: [ 'jasmine' ], browsers: ['Chrome', 'Safari'], plugins: [ 'karma-chrome-launcher', 'karma-coverage', 'karma-jasmine', 'karma-safari-launcher', 'karma-spec-reporter', 'karma-sourcemap-loader' ], logLevel: 'warn', loggers: [ {type: 'console'} ], reporters: ['spec', 'coverage'], coverageReporter: { dir: 'coverage/', reporters: [ {type: 'html', subdir: 'html'}, {type: 'text', subdir: '.', file: 'coverage.txt'}, {type: 'json', subdir: '.', file: 'coverage-karma.json'}, {type: 'text-summary'} ] } }); };
etsuo/generator-hybrid
generators/app/templates/web/karma.conf.js
JavaScript
mit
1,115