code
stringlengths
2
1.05M
var dir_f4703b3db1bd5f8d2d3fca771c570947 = [ [ "led.c", "led_8c.html", "led_8c" ], [ "tick.c", "tick_8c.html", "tick_8c" ], [ "usart2.c", "usart2_8c.html", "usart2_8c" ] ];
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("circle", { cx: "7.2", cy: "14.4", r: "3.2" }), h("circle", { cx: "14.8", cy: "18", r: "2" }), h("circle", { cx: "15.2", cy: "8.8", r: "4.8" })), 'BubbleChart');
var Nightmare = require('nightmare') var NTU = require('./NightmareTestUtils') const NounPhraseTest = (nightmare, delay) => { return nightmare // Can I open the addedit form and make it go away by clicking cancel? .click('#add-np').wait(delay) .click('#np-addedit-form #cancel').wait(delay) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) // If I open the addedit form, enter and a save a noun, // will the form then go away and can I see the insertNounPhraseCheck mark in the quiz? /*.then( res => { return nightmare .click('#add-np').wait(delay) .type('#base', 'carrot').wait(delay) .click('#save-np').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) .then( res => {return NTU.lookFor(nightmare, '#insertNounPhraseCheck', true)}) // Can I open the addedit form via editing and make it go away by clicking cancel? .then( res => { return nightmare .click('#id1').wait(delay) .click('#cancel').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) // If I open the addedit form via editing, change and a save a noun, // will the form then go away and can I see the updateNounPhraseCheck mark in the quiz? .then( res => { return nightmare .click('#id1').wait(delay) .type('#base', 'beaver').wait(delay) .click('#save-np').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) .then( res => {return NTU.lookFor(nightmare, '#updateNounPhraseCheck', true)}) // If I open the addedit form via editing and delete the noun, // will the form then go away and can I see the deleteNounPhraseCheck mark in the quiz? .then( res => { return nightmare .click('#id1').wait(delay) .click('#delete-np').wait(delay) }) .then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)}) .then( res => {return NTU.lookFor(nightmare, '#deleteNounPhraseCheck', true)}) //.then( res => {return NTU.lookFor(nightmare, '#quiz', false)}) .then( res => { return nightmare .click('#add-np').wait(delay) .type('#base', 'carrot').wait(delay) .click('#save-np').wait(delay) })*/ // Can I see the examples button? //.then( res => {return NTU.lookFor(nightmare, '#examples', true)}) // Does it go away after I click it? //.then( res => {return nightmare.click('#examples')}) //.then( res => {return NTU.lookFor(nightmare, '#examples', false)}) } module.exports = NounPhraseTest
import { UIPanel, UIRow, UIHorizontalRule } from './libs/ui.js'; import { AddObjectCommand } from './commands/AddObjectCommand.js'; import { RemoveObjectCommand } from './commands/RemoveObjectCommand.js'; import { MultiCmdsCommand } from './commands/MultiCmdsCommand.js'; import { SetMaterialValueCommand } from './commands/SetMaterialValueCommand.js'; function MenubarEdit( editor ) { var strings = editor.strings; var container = new UIPanel(); container.setClass( 'menu' ); var title = new UIPanel(); title.setClass( 'title' ); title.setTextContent( strings.getKey( 'menubar/edit' ) ); container.add( title ); var options = new UIPanel(); options.setClass( 'options' ); container.add( options ); // Undo var undo = new UIRow(); undo.setClass( 'option' ); undo.setTextContent( strings.getKey( 'menubar/edit/undo' ) ); undo.onClick( function () { editor.undo(); } ); options.add( undo ); // Redo var redo = new UIRow(); redo.setClass( 'option' ); redo.setTextContent( strings.getKey( 'menubar/edit/redo' ) ); redo.onClick( function () { editor.redo(); } ); options.add( redo ); // Clear History var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/clear_history' ) ); option.onClick( function () { if ( confirm( 'The Undo/Redo History will be cleared. Are you sure?' ) ) { editor.history.clear(); } } ); options.add( option ); editor.signals.historyChanged.add( function () { var history = editor.history; undo.setClass( 'option' ); redo.setClass( 'option' ); if ( history.undos.length == 0 ) { undo.setClass( 'inactive' ); } if ( history.redos.length == 0 ) { redo.setClass( 'inactive' ); } } ); // --- options.add( new UIHorizontalRule() ); // Clone var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/clone' ) ); option.onClick( function () { var object = editor.selected; if ( object.parent === null ) return; // avoid cloning the camera or scene object = object.clone(); editor.execute( new AddObjectCommand( editor, object ) ); } ); options.add( option ); // Delete var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/delete' ) ); option.onClick( function () { var object = editor.selected; if ( object !== null && object.parent !== null ) { editor.execute( new RemoveObjectCommand( editor, object ) ); } } ); options.add( option ); // Minify shaders var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/minify_shaders' ) ); option.onClick( function () { var root = editor.selected || editor.scene; var errors = []; var nMaterialsChanged = 0; var path = []; function getPath( object ) { path.length = 0; var parent = object.parent; if ( parent !== undefined ) getPath( parent ); path.push( object.name || object.uuid ); return path; } var cmds = []; root.traverse( function ( object ) { var material = object.material; if ( material !== undefined && material.isShaderMaterial ) { try { var shader = glslprep.minifyGlsl( [ material.vertexShader, material.fragmentShader ] ); cmds.push( new SetMaterialValueCommand( editor, object, 'vertexShader', shader[ 0 ] ) ); cmds.push( new SetMaterialValueCommand( editor, object, 'fragmentShader', shader[ 1 ] ) ); ++ nMaterialsChanged; } catch ( e ) { var path = getPath( object ).join( "/" ); if ( e instanceof glslprep.SyntaxError ) errors.push( path + ":" + e.line + ":" + e.column + ": " + e.message ); else { errors.push( path + ": Unexpected error (see console for details)." ); console.error( e.stack || e ); } } } } ); if ( nMaterialsChanged > 0 ) { editor.execute( new MultiCmdsCommand( editor, cmds ), 'Minify Shaders' ); } window.alert( nMaterialsChanged + " material(s) were changed.\n" + errors.join( "\n" ) ); } ); options.add( option ); options.add( new UIHorizontalRule() ); // Set textures to sRGB. See #15903 var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/edit/fixcolormaps' ) ); option.onClick( function () { editor.scene.traverse( fixColorMap ); } ); options.add( option ); var colorMaps = [ 'map', 'envMap', 'emissiveMap' ]; function fixColorMap( obj ) { var material = obj.material; if ( material !== undefined ) { if ( Array.isArray( material ) === true ) { for ( var i = 0; i < material.length; i ++ ) { fixMaterial( material[ i ] ); } } else { fixMaterial( material ); } editor.signals.sceneGraphChanged.dispatch(); } } function fixMaterial( material ) { var needsUpdate = material.needsUpdate; for ( var i = 0; i < colorMaps.length; i ++ ) { var map = material[ colorMaps[ i ] ]; if ( map ) { map.encoding = THREE.sRGBEncoding; needsUpdate = true; } } material.needsUpdate = needsUpdate; } return container; } export { MenubarEdit };
import React from 'react'; class Icon extends React.Component { constructor(props) { super(props); this.displayName = 'Icon'; this.icon = "fa " + this.props.icon + " " + this.props.size; } render() { return ( <i className={this.icon}></i> ); } } export default Icon;
module.exports={A:{A:{"2":"L H G E A B jB"},B:{"1":"8","2":"C D e K I N J"},C:{"1":"DB EB O GB HB","2":"0 1 2 3 4 5 7 9 gB BB F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB aB ZB"},D:{"1":"8 HB TB PB NB mB OB LB QB RB","2":"0 1 2 3 4 5 7 9 F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB"},E:{"1":"6 C D p bB","2":"4 F L H G E A SB KB UB VB WB XB YB","132":"B"},F:{"1":"0 1 2 3 z","2":"5 6 7 E B C K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y cB dB eB fB p AB hB"},G:{"1":"D tB uB vB","2":"G KB iB FB kB lB MB nB oB pB qB rB","132":"sB"},H:{"2":"wB"},I:{"1":"O","2":"BB F xB yB zB 0B FB 1B 2B"},J:{"2":"H A"},K:{"2":"6 A B C M p AB"},L:{"1":"LB"},M:{"1":"O"},N:{"2":"A B"},O:{"2":"3B"},P:{"2":"F 4B 5B 6B 7B 8B"},Q:{"2":"9B"},R:{"2":"AC"},S:{"2":"BC"}},B:7,C:"CSS Environment Variables env()"};
import './init' import React from 'react' import ReactDom from 'react-dom' import Root from './root' import {APP_THEMES_LIGHT, APP_THEMES_DARK} from 'reducers/settings/constants' import LocalStorage from 'lib/localStorage' import {initializeStore} from './redux/store' import {initServiceWorker} from './swWindow' // render app const renderApp = (Component, appRoot, store) => { initServiceWorker(store) ReactDom.render( <Component store={store} />, appRoot, () => { // need to make this for feature tests - application ready for testing window.__isAppReady = true }) } const prepareStoreData = () => { let theme = LocalStorage.getItem('theme') if (!theme) { if (window.matchMedia('(prefers-color-scheme: dark)')?.matches) { theme = APP_THEMES_DARK } } return { settings: { theme: theme || APP_THEMES_LIGHT } } } // init store and start app const appRoot = document.getElementById('app-root') const store = initializeStore(prepareStoreData()) renderApp(Root, appRoot, store)
/** * @author Kai Salmen / www.kaisalmen.de */ 'use strict'; if ( KSX.test.projectionspace === undefined ) KSX.test.projectionspace = {}; KSX.test.projectionspace.VerifyPP = (function () { PPCheck.prototype = Object.create(KSX.core.ThreeJsApp.prototype, { constructor: { configurable: true, enumerable: true, value: PPCheck, writable: true } }); function PPCheck(elementToBindTo, loader) { KSX.core.ThreeJsApp.call(this); this.configure({ name: 'PPCheck', htmlCanvas: elementToBindTo, useScenePerspective: true, loader: loader }); this.controls = null; this.projectionSpace = new KSX.instancing.ProjectionSpace({ low: { index: 0, name: 'Low', x: 240, y: 100, defaultHeightFactor: 9, mesh: null }, medium: { index: 1, name: 'Medium', x: 720, y: 302, defaultHeightFactor: 18, mesh: null } }, 0); this.cameraDefaults = { posCamera: new THREE.Vector3( 300, 300, 300 ), far: 100000 }; } PPCheck.prototype.initPreGL = function() { var scope = this; var callbackOnSuccess = function () { scope.preloadDone = true; }; scope.projectionSpace.loadAsyncResources( callbackOnSuccess ); }; PPCheck.prototype.initGL = function () { this.projectionSpace.initGL(); this.projectionSpace.flipTexture( 'linkPixelProtest' ); this.scenePerspective.scene.add( this.projectionSpace.dimensions[this.projectionSpace.index].mesh ); this.scenePerspective.setCameraDefaults( this.cameraDefaults ); this.controls = new THREE.TrackballControls( this.scenePerspective.camera ); }; PPCheck.prototype.resizeDisplayGL = function () { this.controls.handleResize(); }; PPCheck.prototype.renderPre = function () { this.controls.update(); }; return PPCheck; })();
import test from 'ava' import Vue from 'vue' import {createRenderer} from 'vue-server-renderer' import ContentPlaceholder from '../src' test.cb('ssr', t => { const rows = [{height: '5px', boxes: [[0, '40px']]}] const renderer = createRenderer() const app = new Vue({ template: '<content-placeholder :rows="rows"></content-placeholder>', components: {ContentPlaceholder}, data: {rows} }) renderer.renderToString(app, (err, html) => { t.falsy(err) t.true(html.includes('data-server-rendered')) t.end() }) })
import { dealsService } from '../services'; const fetchDealsData = () => { return dealsService().getDeals() .then(res => { return res.data }) // Returning [] as a placeholder now so it does not error out when this service // fails. We should be handling this in our DISPATCH_REQUEST_FAILURE .catch(() => []); }; export default fetchDealsData;
import { createPlugin } from 'draft-extend'; // TODO(mime): can't we just use LINK? i forget why we're using ANCHOR separately..., something with images probably :-/ const ENTITY_TYPE = 'ANCHOR'; // TODO(mime): one day, maybe switch wholesale to draft-extend. for now, we have a weird hybrid // of draft-extend/draft-convert/draft-js-plugins export default createPlugin({ htmlToEntity: (nodeName, node, create) => { if (nodeName === 'a') { const mutable = node.firstElementChild?.nodeName === 'IMG' ? 'IMMUTABLE' : 'MUTABLE'; const { href, target } = node; return create(ENTITY_TYPE, mutable, { href, target }); } }, entityToHTML: (entity, originalText) => { if (entity.type === ENTITY_TYPE) { const { href } = entity.data; return `<a href="${href}" target="_blank" rel="noopener noreferrer">${originalText}</a>`; } return originalText; }, }); export const AnchorDecorator = (props) => { const { href } = props.contentState.getEntity(props.entityKey).getData(); return ( <a href={href} target="_blank" rel="noopener noreferrer"> {props.children} </a> ); }; export function anchorStrategy(contentBlock, callback, contentState) { contentBlock.findEntityRanges((character) => { const entityKey = character.getEntity(); return entityKey !== null && contentState.getEntity(entityKey).getType() === ENTITY_TYPE; }, callback); }
'use strict'; var assert = require('../../helpers/assert'); var commandOptions = require('../../factories/command-options'); var stub = require('../../helpers/stub').stub; var Promise = require('../../../lib/ext/promise'); var Task = require('../../../lib/models/task'); var TestCommand = require('../../../lib/commands/test'); describe('test command', function() { var tasks; var options; var buildRun; var testRun; beforeEach(function(){ tasks = { Build: Task.extend(), Test: Task.extend() }; options = commandOptions({ tasks: tasks, testing: true }); stub(tasks.Test.prototype, 'run', Promise.resolve()); stub(tasks.Build.prototype, 'run', Promise.resolve()); buildRun = tasks.Build.prototype.run; testRun = tasks.Test.prototype.run; }); it('builds and runs test', function() { return new TestCommand(options).validateAndRun([]).then(function() { assert.equal(buildRun.called, 1, 'expected build task to be called once'); assert.equal(testRun.called, 1, 'expected test task to be called once'); }); }); it('has the correct options', function() { return new TestCommand(options).validateAndRun([]).then(function() { var buildOptions = buildRun.calledWith[0][0]; var testOptions = testRun.calledWith[0][0]; assert.equal(buildOptions.environment, 'development', 'has correct env'); assert.ok(buildOptions.outputPath, 'has outputPath'); assert.equal(testOptions.configFile, './testem.json', 'has config file'); assert.equal(testOptions.port, 7357, 'has config file'); }); }); it('passes through custom configFile option', function() { return new TestCommand(options).validateAndRun(['--config-file=some-random/path.json']).then(function() { var testOptions = testRun.calledWith[0][0]; assert.equal(testOptions.configFile, 'some-random/path.json'); }); }); it('passes through custom port option', function() { return new TestCommand(options).validateAndRun(['--port=5678']).then(function() { var testOptions = testRun.calledWith[0][0]; assert.equal(testOptions.port, 5678); }); }); });
import Vector from '../prototype' import {componentOrder, allComponents} from './components' export const withInvertedCurryingSupport = f => { const curried = right => left => f(left, right) return (first, second) => { if (second === undefined) { // check for function to allow usage by the pipeline function if (Array.isArray(first) && first.length === 2 && !(first[0] instanceof Function) && !(first[0] instanceof Number)) { return f(first[0], first[1]) } // curried form uses the given single parameter as the right value for the operation f return curried(first) } return f(first, second) } } export const skipUndefinedArguments = (f, defaultValue) => (a, b) => a === undefined || b === undefined ? defaultValue : f(a, b) export const clone = v => { if (Array.isArray(v)) { const obj = Object.create(Vector.prototype) v.forEach((value, i) => { obj[allComponents[i]] = value }) return [...v] } const prototype = Object.getPrototypeOf(v) return Object.assign(Object.create(prototype === Object.prototype ? Vector.prototype : prototype), v) }
module.exports = function() { return { server: { src: ['<%= tmp %>/index.html'], ignorePath: /\.\.\// } } };
'use strict'; angular.module('mpApp') .factory( 'preloader', function($q, $rootScope) { // I manage the preloading of image objects. Accepts an array of image URLs. function Preloader(imageLocations) { // I am the image SRC values to preload. this.imageLocations = imageLocations; // As the images load, we'll need to keep track of the load/error // counts when announing the progress on the loading. this.imageCount = this.imageLocations.length; this.loadCount = 0; this.errorCount = 0; // I am the possible states that the preloader can be in. this.states = { PENDING: 1, LOADING: 2, RESOLVED: 3, REJECTED: 4 }; // I keep track of the current state of the preloader. this.state = this.states.PENDING; // When loading the images, a promise will be returned to indicate // when the loading has completed (and / or progressed). this.deferred = $q.defer(); this.promise = this.deferred.promise; } // --- // STATIC METHODS. // --- // I reload the given images [Array] and return a promise. The promise // will be resolved with the array of image locations. 111111 Preloader.preloadImages = function(imageLocations) { var preloader = new Preloader(imageLocations); return (preloader.load()); }; // --- // INSTANCE METHODS. // --- Preloader.prototype = { // Best practice for "instnceof" operator. constructor: Preloader, // --- // PUBLIC METHODS. // --- // I determine if the preloader has started loading images yet. isInitiated: function isInitiated() { return (this.state !== this.states.PENDING); }, // I determine if the preloader has failed to load all of the images. isRejected: function isRejected() { return (this.state === this.states.REJECTED); }, // I determine if the preloader has successfully loaded all of the images. isResolved: function isResolved() { return (this.state === this.states.RESOLVED); }, // I initiate the preload of the images. Returns a promise. 222 load: function load() { // If the images are already loading, return the existing promise. if (this.isInitiated()) { return (this.promise); } this.state = this.states.LOADING; for (var i = 0; i < this.imageCount; i++) { this.loadImageLocation(this.imageLocations[i]); } // Return the deferred promise for the load event. return (this.promise); }, // --- // PRIVATE METHODS. // --- // I handle the load-failure of the given image location. handleImageError: function handleImageError(imageLocation) { this.errorCount++; // If the preload action has already failed, ignore further action. if (this.isRejected()) { return; } this.state = this.states.REJECTED; this.deferred.reject(imageLocation); }, // I handle the load-success of the given image location. handleImageLoad: function handleImageLoad(imageLocation) { this.loadCount++; // If the preload action has already failed, ignore further action. if (this.isRejected()) { return; } // Notify the progress of the overall deferred. This is different // than Resolving the deferred - you can call notify many times // before the ultimate resolution (or rejection) of the deferred. this.deferred.notify({ percent: Math.ceil(this.loadCount / this.imageCount * 100), imageLocation: imageLocation }); // If all of the images have loaded, we can resolve the deferred // value that we returned to the calling context. if (this.loadCount === this.imageCount) { this.state = this.states.RESOLVED; this.deferred.resolve(this.imageLocations); } }, // I load the given image location and then wire the load / error // events back into the preloader instance. // -- // NOTE: The load/error events trigger a $digest. 333 loadImageLocation: function loadImageLocation(imageLocation) { var preloader = this; // When it comes to creating the image object, it is critical that // we bind the event handlers BEFORE we actually set the image // source. Failure to do so will prevent the events from proper // triggering in some browsers. var image = angular.element(new Image()) .bind('load', function(event) { // Since the load event is asynchronous, we have to // tell AngularJS that something changed. $rootScope.$apply( function() { preloader.handleImageLoad(event.target.src); // Clean up object reference to help with the // garbage collection in the closure. preloader = image = event = null; } ); }) .bind('error', function(event) { // Since the load event is asynchronous, we have to // tell AngularJS that something changed. $rootScope.$apply( function() { preloader.handleImageError(event.target.src); // Clean up object reference to help with the // garbage collection in the closure. preloader = image = event = null; } ); }) .attr('src', imageLocation); } }; // Return the factory instance. return (Preloader); } );
var gulp = require('gulp'); gulp.task('dist', ['setProduction', 'sass:dist', 'browserify:dist']);
/* json2.js 2013-05-26 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', { '': value }); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({ '': j }, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } } ());
'use strict'; import Chart from 'chart.js'; import Controller from './controller'; import Scale, {defaults} from './scale'; // Register the Controller and Scale Chart.controllers.smith = Controller; Chart.defaults.smith = { aspectRatio: 1, scale: { type: 'smith', }, tooltips: { callbacks: { title: () => null, label: (bodyItem, data) => { const dataset = data.datasets[bodyItem.datasetIndex]; const d = dataset.data[bodyItem.index]; return dataset.label + ': ' + d.real + ' + ' + d.imag + 'i'; } } } }; Chart.scaleService.registerScaleType('smith', Scale, defaults);
var packageInfo = require('./package.json'); var taskList = [{name:'default'},{name:'delete'},{name:'build'},{name:'copy'},{name:'minify'}]; var gulpTalk2me = require('gulp-talk2me'); var talk2me = new gulpTalk2me(packageInfo,taskList); var del = require('del'); var gulp = require('gulp'); var runSequence = require('run-sequence'); var sourcemaps = require('gulp-sourcemaps'); var rename = require('gulp-rename'); var ngAnnotate = require('gulp-ng-annotate'); var bytediff = require('gulp-bytediff'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var templateCache = require('gulp-angular-templatecache'); var series = require('stream-series'); var angularFilesort = require('gulp-angular-filesort'); console.log(talk2me.greeting); gulp.task('default',function(callback){ runSequence('build',callback); }); gulp.task('delete',function(callback){ del('dist/**/*', callback()); }); gulp.task('build',function(callback){ runSequence('delete',['copy','minify'],callback); }); gulp.task('copy',function(){ return series(genTemplateStream(),gulp.src(['src/**/*.js','!src/**/*.spec.js'])) .pipe(sourcemaps.init()) .pipe(angularFilesort()) .pipe(concat('bs-fa-boolean-directive.js', {newLine: ';\n'})) .pipe(ngAnnotate({ add: true })) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('dist')); }); gulp.task('minify',function(){ return series(genTemplateStream(),gulp.src(['src/**/*.js','!src/**/*.spec.js'])) .pipe(sourcemaps.init()) .pipe(angularFilesort()) .pipe(concat('bs-fa-boolean-directive.js', {newLine: ';'})) .pipe(rename(function (path) { path.basename += ".min"; })) .pipe(ngAnnotate({ add: true })) .pipe(bytediff.start()) .pipe(uglify({mangle: true})) .pipe(bytediff.stop()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('dist')); }); function genTemplateStream () { return gulp.src(['src/**/*.view.html']) .pipe(templateCache({standalone:true,module:'bs-fa-boolean.template'})); }
//https://github.com/nothingrandom/project_euler.js var square=0;var sum=0;var answer=0;var number2=0;for(var i=0;i<=100;i++){var number=Math.pow(i,2);square+=number}for(var i=0;i<=100;i++){number2+=i;sum=Math.pow(number2,2)}var answer=sum-square;console.log(answer)
var BasicMathLib = artifacts.require("./BasicMathLib.sol"); var Array256Lib = artifacts.require("./Array256Lib.sol"); var TokenLib = artifacts.require("./TokenLib.sol"); var CrowdsaleLib = artifacts.require("./CrowdsaleLib.sol"); var EvenDistroCrowdsaleLib = artifacts.require("./EvenDistroCrowdsaleLib.sol"); var CrowdsaleTestTokenEteenD = artifacts.require("./CrowdsaleTestTokenEteenD"); var EvenDistroTestEteenD = artifacts.require("./EvenDistroTestEteenD.sol"); var CrowdsaleTestTokenTenD = artifacts.require("./CrowdsaleTestTokenTenD"); var EvenDistroTestTenD = artifacts.require("./EvenDistroTestTenD.sol"); module.exports = function(deployer, network, accounts) { deployer.deploy(BasicMathLib,{overwrite: false}); deployer.deploy(Array256Lib, {overwrite: false}); deployer.link(BasicMathLib, TokenLib); deployer.deploy(TokenLib, {overwrite: false}); deployer.link(BasicMathLib,CrowdsaleLib); deployer.link(TokenLib,CrowdsaleLib); deployer.deploy(CrowdsaleLib, {overwrite: false}); deployer.link(BasicMathLib,EvenDistroCrowdsaleLib); deployer.link(TokenLib,EvenDistroCrowdsaleLib); deployer.link(CrowdsaleLib,EvenDistroCrowdsaleLib); deployer.deploy(EvenDistroCrowdsaleLib, {overwrite:false}); if(network === "development" || network === "coverage"){ deployer.link(TokenLib,CrowdsaleTestTokenEteenD); deployer.link(CrowdsaleLib,EvenDistroTestEteenD); deployer.link(EvenDistroCrowdsaleLib, EvenDistroTestEteenD); deployer.link(TokenLib,CrowdsaleTestTokenTenD); deployer.link(CrowdsaleLib,EvenDistroTestTenD); deployer.link(EvenDistroCrowdsaleLib, EvenDistroTestTenD); // startTime 3 days + 1 hour in the future var startTime = (Math.floor((new Date().valueOf()/1000))) + 262800; // first price step in 7 days var stepOne = startTime + 604800; // second price step in 14 days var stepTwo = stepOne + 604800; // endTime in 30 days var endTime = startTime + 2592000; deployer.deploy(CrowdsaleTestTokenEteenD, accounts[0], "Eighteen Decimals", "ETEEN", 18, 50000000000000000000000000, false, {from:accounts[5]}) .then(function() { var purchaseData =[startTime,600000000000000000000,100, stepOne,600000000000000000000,100, stepTwo,300000000000000000000,0]; return deployer.deploy(EvenDistroTestEteenD, accounts[5], purchaseData, endTime, 100, 10000000000000000000000, false, CrowdsaleTestTokenEteenD.address, {from:accounts[5]}) }) .then(function(){ return deployer.deploy(CrowdsaleTestTokenTenD, accounts[0], "Ten Decimals", "TEN", 10, 1000000000000000, false, {from:accounts[5]}) }) .then(function() { // start next sale in 7 days startTime = endTime + 604800; stepOne = startTime + 604800; stepTwo = stepOne + 604800; endTime = startTime + 2592000; purchaseData =[startTime,4000000000000,0, stepOne,8000000000000,20000000000000, stepTwo,16000000000000,0]; return deployer.deploy(EvenDistroTestTenD, accounts[0], purchaseData, endTime, 25, 0, true, CrowdsaleTestTokenTenD.address, {from:accounts[5]}) }); } };
// // Adapted from: // http://stackoverflow.com/questions/22330103/how-to-include-node-modules-in-a-separate-browserify-vendor-bundle // var gulp = require('gulp'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var bust = require('gulp-buster'); var streamify = require('gulp-streamify'); var htmlreplace = require('gulp-html-replace'); var fs = require('fs'); var packageJson = require('./package.json'); var dependencies = Object.keys(packageJson && packageJson.dependencies || {}); function handleErrors(error) { console.error(error.stack); // Emit 'end' as the stream wouldn't do it itself. // Without this, the gulp task won't end and the watch stops working. this.emit('end'); } gulp.task('libs', function () { return browserify({debug: true}) .require(dependencies) .bundle() .on('error', handleErrors) .pipe(source('libs.js')) .pipe(gulp.dest('./dist/')) .pipe(streamify(bust())) .pipe(gulp.dest('.')); }); gulp.task('scripts', function () { return browserify('./src/index.js', {debug: true}) .external(dependencies) .bundle() .on('error', handleErrors) .on('end', ()=>{console.log("ended")}) .pipe(source('scripts.js')) .pipe(gulp.dest('./dist/')) .pipe(streamify(bust())) .pipe(gulp.dest('.')); }); gulp.task('css', function () { return gulp.src('./styles/styles.css') .pipe(gulp.dest('./dist/')) .pipe(streamify(bust())) .pipe(gulp.dest('.')); }); gulp.task('icons', function () { return gulp.src('./icons/**/*') .pipe(gulp.dest('./dist/icons')); }); gulp.task('favicons', function () { return gulp.src('./favicons/**/*') .pipe(gulp.dest('./dist/')); }); gulp.task('html', function () { var busters = JSON.parse(fs.readFileSync('busters.json')); return gulp.src('index.html') .pipe(htmlreplace({ 'css': 'styles.css?v=' + busters['dist/styles.css'], 'js': [ 'libs.js?v=' + busters['dist/libs.js'], 'scripts.js?v=' + busters['dist/scripts.js'] ] })) .pipe(gulp.dest('./dist/')); }); gulp.task('watch', function(){ gulp.watch('package.json', ['libs']); gulp.watch('src/**', ['scripts']); gulp.watch('styles/styles.css', ['css']); gulp.watch('icons/**', ['icons']); gulp.watch('favicons/**', ['favicons']); gulp.watch(['busters.json', 'index.html'], ['html']); }); gulp.task('default', ['libs', 'scripts', 'css', 'icons', 'favicons', 'html', 'watch']);
BrowserPolicy.content.allowOriginForAll("*.googleapis.com"); BrowserPolicy.content.allowOriginForAll("*.gstatic.com"); BrowserPolicy.content.allowOriginForAll("*.bootstrapcdn.com"); BrowserPolicy.content.allowOriginForAll("*.geobytes.com"); BrowserPolicy.content.allowFontDataUrl();
'use strict' if (!process.addAsyncListener) require('async-listener') var noop = function () {} module.exports = function () { return new AsyncState() } function AsyncState () { var state = this process.addAsyncListener({ create: asyncFunctionInitialized, before: asyncCallbackBefore, error: noop, after: asyncCallbackAfter }) // Record the state currently set on on the async-state object and return a // snapshot of it. The returned object will later be passed as the `data` // arg in the functions below. function asyncFunctionInitialized () { var data = {} for (var key in state) { data[key] = state[key] } return data } // We just returned from the event-loop: We'll now restore the state // previously saved by `asyncFunctionInitialized`. function asyncCallbackBefore (context, data) { for (var key in data) { state[key] = data[key] } } // Clear the state so that it doesn't leak between isolated async stacks. function asyncCallbackAfter (context, data) { for (var key in state) { delete state[key] } } }
/** Problem 9. Extract e-mails Write a function for extracting all email addresses from given text. All sub-strings that match the format @… should be recognized as emails. Return the emails as array of strings. */ console.log('Problem 9. Extract e-mails'); var text='[email protected] bla bla bla [email protected] bla bla [email protected]' function extractEmails(text) { var result=text.match(/[A-Z0-9._-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/gi); return result; } console.log('Text: '+text); console.log('E-mail: '+extractEmails(text)); console.log('#########################################');
/** * Border Left Radius */ module.exports = function (decl, args) { var radius = args[1] || '3px'; decl.replaceWith({ prop: 'border-bottom-left-radius', value: radius, source: decl.source }, { prop: 'border-top-left-radius', value: radius, source: decl.source }); };
//===================================================================== // This sample demonstrates using TeslaJS // // https://github.com/mseminatore/TeslaJS // // Copyright (c) 2016 Mark Seminatore // // Refer to included LICENSE file for usage rights and restrictions //===================================================================== "use strict"; require('colors'); var program = require('commander'); var framework = require('./sampleFramework.js'); // // // program .usage('[options]') .option('-i, --index <n>', 'vehicle index (first car by default)', parseInt) .option('-U, --uri [string]', 'URI of test server (e.g. http://127.0.0.1:3000)') .parse(process.argv); // var sample = new framework.SampleFramework(program, sampleMain); sample.run(); // // // function sampleMain(tjs, options) { var streamingOptions = { vehicle_id: options.vehicle_id, authToken: options.authToken }; console.log("\nNote: " + "Inactive vehicle streaming responses can take up to several minutes.".green); console.log("\nStreaming starting...".cyan); console.log("Columns: timestamp," + tjs.streamingColumns.toString()); tjs.startStreaming(streamingOptions, function (error, response, body) { if (error) { console.log(error); return; } // display the streaming results console.log(body); console.log("...Streaming ended.".cyan); }); }
module.exports = { dist: { files: { 'dist/geo.js': ['src/index.js'], } } };
var Model = require('./model'); var schema = { name : String, stuff: { electronics: [{ type: String }], computing_dev: [{ type: String }] }, age:{ biological: Number }, fruits: [ { name: String, fav: Boolean, about: [{ type: String }] } ] }; var person = function(data){ Model.call(this, schema, data); } person.prototype = Object.create(Model.prototype); module.exports = person;
// Depends on jsbn.js and rng.js // Version 1.1: support utf-8 encoding in pkcs1pad2 // convert a (hex) string to a bignum object function parseBigInt(str,r) { return new BigInteger(str,r); } function linebrk(s,n) { var ret = ""; var i = 0; while(i + n < s.length) { ret += s.substring(i,i+n) + "\n"; i += n; } return ret + s.substring(i,s.length); } function byte2Hex(b) { if(b < 0x10) return "0" + b.toString(16); else return b.toString(16); } // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint function pkcs1pad2(s,n) { if(n < s.length + 11) { // TODO: fix for utf-8 alert("Message too long for RSA"); return null; } var ba = new Array(); var i = s.length - 1; while(i >= 0 && n > 0) { var c = s.charCodeAt(i--); if(c < 128) { // encode using utf-8 ba[--n] = c; } else if((c > 127) && (c < 2048)) { ba[--n] = (c & 63) | 128; ba[--n] = (c >> 6) | 192; } else { ba[--n] = (c & 63) | 128; ba[--n] = ((c >> 6) & 63) | 128; ba[--n] = (c >> 12) | 224; } } ba[--n] = 0; var rng = new SecureRandom(); var x = new Array(); while(n > 2) { // random non-zero pad x[0] = 0; while(x[0] == 0) rng.nextBytes(x); ba[--n] = x[0]; } ba[--n] = 2; ba[--n] = 0; return new BigInteger(ba); } // "empty" RSA key constructor function RSAKey() { this.n = null; this.e = 0; this.d = null; this.p = null; this.q = null; this.dmp1 = null; this.dmq1 = null; this.coeff = null; } // Set the public key fields N and e from hex strings function RSASetPublic(N,E) { if(N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N,16); this.e = parseInt(E,16); } else alert("Invalid RSA public key"); } // Perform raw public operation on "x": return x^e (mod n) function RSADoPublic(x) { return x.modPowInt(this.e, this.n); } // Return the PKCS#1 RSA encryption of "text" as an even-length hex string function RSAEncrypt(text) { var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); if(m == null) return null; var c = this.doPublic(m); if(c == null) return null; var h = c.toString(16); if((h.length & 1) == 0) return h; else return "0" + h; } // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string function RSAEncryptB64(text) { var h = this.encrypt(text); if(h) return hex2b64(h); else return null; } // protected RSAKey.prototype.doPublic = RSADoPublic; // public RSAKey.prototype.setPublic = RSASetPublic; RSAKey.prototype.encrypt = RSAEncrypt; RSAKey.prototype.encrypt_b64 = RSAEncryptB64; //my encrypt function, using fixed mudulus var modulus = "BEB90F8AF5D8A7C7DA8CA74AC43E1EE8A48E6860C0D46A5D690BEA082E3A74E1" +"571F2C58E94EE339862A49A811A31BB4A48F41B3BCDFD054C3443BB610B5418B" +"3CBAFAE7936E1BE2AFD2E0DF865A6E59C2B8DF1E8D5702567D0A9650CB07A43D" +"E39020969DF0997FCA587D9A8AE4627CF18477EC06765DF3AA8FB459DD4C9AF3"; var publicExponent = "10001"; function MyRSAEncryptB64(text) { var rsa = new RSAKey(); rsa.setPublic(modulus, publicExponent); return rsa.encrypt_b64(text); }
var ShaderTool = new (function ShaderTool(){ function catchReady(fn) { var L = 'loading'; if (document.readyState != L){ fn(); } else if (document.addEventListener) { document.addEventListener('DOMContentLoaded', fn); } else { document.attachEvent('onreadystatechange', function() { if (document.readyState != L){ fn(); } }); } } this.VERSION = '0.01'; this.modules = {}; this.helpers = {}; this.classes = {}; var self = this; catchReady(function(){ self.modules.GUIHelper.init(); self.modules.UniformControls.init(); self.modules.Editor.init(); self.modules.Rendering.init(); self.modules.SaveController.init(); self.modules.PopupManager.init(); document.documentElement.className = '_ready'; }); })(); // Utils ShaderTool.Utils = { trim: function( string ){ return string.replace(/^\s+|\s+$/g, ''); }, isSet: function( object ){ return typeof object != 'undefined' && object != null }, isArray: function( object ){ var str = Object.prototype.toString.call(object); return str == '[object Array]' || str == '[object Float32Array]'; // return Object.prototype.toString.call(object) === '[object Array]'; }, isArrayLike: function( object ){ if( this.isArray(object) ){ return true } if( typeof object.length == 'number' && typeof object[0] != 'undefined' && typeof object[object.length] != 'undefined'){ return true; } return false; }, isArrayLike: function( object ){ if(this.isArray(object)){ return true; } if(this.isObject(object) && this.isNumber(object.length) ){ return true; } return false; }, isNumber: function( object ){ return typeof object == 'number' && !isNaN(object); }, isFunction: function( object ){ return typeof object == 'function'; }, isObject: function( object ){ return typeof object == 'object'; }, isString: function( object ){ return typeof object == 'string'; }, createNamedObject: function( name, props ){ return internals.createNamedObject( name, props ); }, testCallback: function( callback, applyArguments, context ){ if(this.isFunction(callback)){ return callback.apply(context, applyArguments || []); } return null; }, copy: function( from, to ){ for(var i in from){ to[i] = from[i]; } return to; }, delegate: function( context, method ){ return function delegated(){ for(var argumentsLength = arguments.length, args = new Array(argumentsLength), k=0; k<argumentsLength; k++){ args[k] = arguments[k]; } return method.apply( context, args ); } }, debounce: function(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate){ func.apply(context, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow){ func.apply(context, args); } }; }, throttle: function(func, ms) { var isThrottled = false, savedArgs, savedThis; function wrapper() { if (isThrottled) { savedArgs = arguments; savedThis = this; return; } func.apply(this, arguments); isThrottled = true; setTimeout(function() { isThrottled = false; if (savedArgs) { wrapper.apply(savedThis, savedArgs); savedArgs = savedThis = null; } }, ms); } return wrapper; }, now: function(){ var P = 'performance'; if (window[P] && window[P]['now']) { this.now = function(){ return window.performance.now() } } else { this.now = function(){ return +(new Date()) } } return this.now(); }, isFunction: function( object ){ return typeof object == 'function'; }, isNumberKey: function(e){ var charCode = (e.which) ? e.which : e.keyCode; if (charCode == 46) { //Check if the text already contains the . character if (txt.value.indexOf('.') === -1) { return true; } else { return false; } } else { // if (charCode > 31 && (charCode < 48 || charCode > 57)){ if(charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8)){ if(charCode < 96 && charCode > 105){ return false; } } } return true; }, toDecimalString: function( string ){ if(this.isNumber(string)){ return string; } if(string.substr(0,1) == '0'){ if(string.substr(1,1) != '.'){ string = '0.' + string.substr(1, string.length); } } return string == '0.' ? '0' : string; }, /* hexToRgb: function(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? [ r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) ] : []; } */ }; // Callback (Signal?) ShaderTool.Utils.Callback = (function(){ // Callback == Signal ? function Callback() { this._handlers = []; var self = this; this.callShim = function(){ self.call.apply(self, arguments); } } Callback.prototype = { _throwError: function() { throw new TypeError('Callback handler must be function!'); }, add: function(handler, context) { if (typeof handler != 'function') { this._throwError(); return; } this.remove(handler); this._handlers.push({handler:handler, context: context}); }, remove: function(handler) { if (typeof handler != 'function') { this._throwError(); return; } var totalHandlers = this._handlers.length; for (var k = 0; k < totalHandlers; k++) { if (handler === this._handlers[k].handler) { this._handlers.splice(k, 1); return; } } }, call: function() { var totalHandlers = this._handlers.length; for (var k = 0; k < totalHandlers; k++) { var handlerData = this._handlers[k]; handlerData.handler.apply(handlerData.context || null, arguments); } } }; return Callback; })(); ShaderTool.Utils.Float32Array = (function(){ return typeof Float32Array === 'function' ? Float32Array : Array; })(); ShaderTool.Utils.DOMUtils = (function(){ function addSingleEventListener(element, eventName, handler){ if (element.addEventListener) { element.addEventListener(eventName, handler); } else { element.attachEvent('on' + eventName, function(e){ handler.apply(element,[e]); }); } } var tempDiv = document.createElement('div'); function DOMUtils(){}; DOMUtils.prototype = { addEventListener : function(element, eventName, handler){ if(ShaderTool.Utils.isArrayLike(element)){ var totalElements = element.length; for(var k=0; k<totalElements; k++){ this.addEventListener(element[k], eventName, handler); } } else { var eventName = ShaderTool.Utils.isArray(eventName) ? eventName : eventName.split(' ').join('|').split(',').join('|').split('|'); if(eventName.length > 1){ var totalEvents = eventName.length; for(var k=0; k<totalEvents; k++){ addSingleEventListener(element, eventName[k], handler ); } } else { addSingleEventListener(element, eventName[0], handler); } } }, addClass : function(element, className){ if (element.classList){ element.classList.add(className); } else { element.className += SPACE + className; } }, removeClass : function(element, className){ if (element.classList){ element.classList.remove(className); } else{ element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(SPACE).join('|') + '(\\b|$)', 'gi'), SPACE); } }, injectCSS: function( cssText ){ try{ var styleElement = document.createElement('style'); styleElement.type = 'text/css'; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = cssText; } else { styleElement.appendChild(document.createTextNode(cssText)); } document.getElementsByTagName('head')[0].appendChild(styleElement); return true; } catch( e ){ return false; } }, createFromHTML: function( html ){ tempDiv.innerHTML = html.trim(); var result = tempDiv.childNodes; if(result.length > 1){ tempDiv.innerHTML = '<div>' + html.trim() + '<div/>' result = tempDiv.childNodes; } return result[0]; } } return new DOMUtils(); })(); // Helpers // LSHelper ShaderTool.helpers.LSHelper = (function(){ var ALLOW_WORK = window.localStorage != null || window.sessionStorage != null; function LSHelper(){ this._storage = window.localStorage || window.sessionStorage; } LSHelper.prototype = { setItem: function( key, data ){ if( !ALLOW_WORK ){ return null } var json = JSON.stringify(data) this._storage.setItem( key, json ); return json; }, getItem: function( key ){ if( !ALLOW_WORK ){ return null } return JSON.parse(this._storage.getItem( key )) }, clearItem: function( key ){ if( !ALLOW_WORK ){ return null } this._storage.removeItem( key ) } } return new LSHelper(); })(); // FSHelper ShaderTool.helpers.FSHelper = (function(){ function FSHelper(){}; FSHelper.prototype = { request: function( element ){ if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.webkitRequestFullScreen) { element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } }, exit: function(){ if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } } } return new FSHelper(); })(); // Ticker ShaderTool.helpers.Ticker = (function(){ var raf; var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame){ raf = function( callback ) { var currTime = Utils.now(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout( function(){ callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } else { raf = function( callback ){ return window.requestAnimationFrame( callback ); } } function Ticker(){ this.onTick = new ShaderTool.Utils.Callback(); var activeState = true; var applyArgs = []; var listeners = []; var prevTime = ShaderTool.Utils.now(); var elapsedTime = 0; var timeScale = 1; var self = this; var skippedFrames = 0; var maxSkipFrames = 3; this.stop = this.pause = this.sleep = function(){ activeState = false; return this; } this.start = this.wake = function(){ activeState = true; return this; } this.reset = function(){ elapsedTime = 0; } this.timeScale = function( value ){ if(ShaderTool.Utils.isSet(value)){ timeScale = value; } return timeScale; } this.toggle = function(){ return (activeState ? this.stop() : this.start()); } this.isActive = function(){ return activeState; } this.getTime = function(){ return elapsedTime; } function tickHandler( nowTime ){ var delta = (nowTime - prevTime) * timeScale; prevTime = nowTime; if(skippedFrames < maxSkipFrames){ skippedFrames++; } else { if(activeState){ elapsedTime += delta; self.onTick.call(delta, elapsedTime) } } raf( tickHandler ); } raf( tickHandler ); }; return new Ticker(); })(); // Modules // Future module ShaderTool.modules.GUIHelper = (function(){ function GUIHelper(){} GUIHelper.prototype = { init: function(){ console.log('ShaderTool.modules.GUIHelper.init') }, showError: function( message ){ console.error('GUIHelper: ' + message) } } return new GUIHelper(); })(); // Editor ShaderTool.modules.Editor = (function(){ function Editor(){} Editor.prototype = { init: function(){ console.log('ShaderTool.modules.Editor.init'); this._container = document.getElementById('st-editor'); this._editor = ace.edit(this._container); this._editor.getSession().setMode('ace/mode/glsl'); // https://ace.c9.io/build/kitchen-sink.html // this._editor.getSession().setTheme(); this._editor.$blockScrolling = Infinity; this.onChange = new ShaderTool.Utils.Callback(); var self = this; //this._editor.on('change', function(){ //self.onChange.call(); //}); this._editor.on('change', ShaderTool.Utils.throttle(function(){ if(!self._skipCallChange){ self.onChange.call(); } }, 1000 / 60 * 10)); }, getData: function(){ return this._editor.getSession().getValue(); }, setData: function( value, skipCallChangeFlag ){ this._skipCallChange = skipCallChangeFlag; this._editor.getSession().setValue( value ); this._skipCallChange = false; if(!skipCallChangeFlag){ this.onChange.call(); } }, clear: function(){ this.setValue(''); }, // future methods: //lock: function(){}, //unlock: function(){}, //load: function( url ){} } return new Editor(); })(); ShaderTool.modules.Rendering = (function(){ var VERTEX_SOURCE = 'attribute vec2 av2_vtx;varying vec2 vv2_v;void main(){vv2_v = av2_vtx;gl_Position = vec4(av2_vtx, 0., 1.);}'; function Rendering(){} Rendering.prototype = { init: function(){ console.log('ShaderTool.modules.Rendering.init'); this._canvas = document.getElementById('st-canvas'); this._context = D3.createContextOnCanvas(this._canvas); this._initSceneControls(); this.onChange = new ShaderTool.Utils.Callback(); // this._sourceChanged = true; var fragmentSource = 'precision mediump float;\n'; fragmentSource += 'uniform sampler2D us2_source;\n'; fragmentSource += 'uniform float uf_time;\n'; fragmentSource += 'uniform vec2 uv2_resolution;\n'; fragmentSource += 'void main() {\n'; fragmentSource += '\tgl_FragColor = \n'; // fragmentSource += 'vec4(gl_FragCoord.xy / uv2_resolution, sin(uf_time), 1.);\n'; fragmentSource += '\t\ttexture2D(us2_source, gl_FragCoord.xy / uv2_resolution);\n'; fragmentSource += '}\n'; this._program = this._context.createProgram({ vertex: VERTEX_SOURCE, fragment: fragmentSource }); this._buffer = this._context.createVertexBuffer().upload(new ShaderTool.Utils.Float32Array([1,-1,1,1,-1,-1,-1,1])); this._resolution = null; this._texture = null; this._framebuffer = null; this._writePosition = 0; this._source = { program: this._program, attributes: { 'av2_vtx': { buffer: this._buffer, size: 2, type: this._context.AttribType.Float, offset: 0 } }, uniforms: { 'us2_source': this._context.UniformSampler(this._texture) }, mode: this._context.Primitive.TriangleStrip, count: 4 }; this._rasterizers = []; this._rasterizers.push(new ShaderTool.classes.Rasterizer( this._context )); // this._updateSource(); ShaderTool.modules.Editor.onChange.add(this._updateSource, this); ShaderTool.modules.UniformControls.onChangeUniformList.add(this._updateSource, this); ShaderTool.modules.UniformControls.onChangeUniformValue.add(this._updateUniforms, this); ShaderTool.helpers.Ticker.onTick.add(this._render, this); }, _updateSource: function( skipCallChangeFlag ){ var uniformSource = ShaderTool.modules.UniformControls.getUniformsCode(); var shaderSource = ShaderTool.modules.Editor.getData(); var fullSource = 'precision mediump float;\n\n' + uniformSource + '\n\n\n' + shaderSource; var totalRasterizers = this._rasterizers.length; for(var k=0; k<totalRasterizers; k++){ var rasterizer = this._rasterizers[k]; rasterizer.updateSource(fullSource); } this._updateUniforms( skipCallChangeFlag ); }, _updateUniforms: function( skipCallChangeFlag ){ var uniforms = ShaderTool.modules.UniformControls.getUniformsData( this._context ); var totalRasterizers = this._rasterizers.length; for(var k=0; k<totalRasterizers; k++){ var rasterizer = this._rasterizers[k]; rasterizer.updateUniforms(uniforms); } if(!skipCallChangeFlag){ this.onChange.call(); } }, _setResolution: function (width, height) { if (!this._resolution) { this._texture = [ this._context.createTexture().uploadEmpty(this._context.TextureFormat.RGBA_8, width, height), this._context.createTexture().uploadEmpty(this._context.TextureFormat.RGBA_8, width, height) ]; framebuffer = [ this._context.createFramebuffer().attachColor(this._texture[1]), this._context.createFramebuffer().attachColor(this._texture[0]) ]; } else if (this._resolution[0] !== width || this._resolution[1] !== height) { this._texture[0].uploadEmpty(this._context.TextureFormat.RGBA_8, width, height); this._texture[1].uploadEmpty(this._context.TextureFormat.RGBA_8, width, height); } this._resolution = [width, height]; }, _initSceneControls: function(){ var self = this; this.dom = {}; this.dom.playButton = document.getElementById('st-play'); this.dom.pauseButton = document.getElementById('st-pause'); this.dom.rewindButton = document.getElementById('st-rewind'); this.dom.fullscreenButton = document.getElementById('st-fullscreen'); this.dom.timescaleRange = document.getElementById('st-timescale'); this.dom.renderWidthLabel = document.getElementById('st-renderwidth'); this.dom.renderHeightLabel = document.getElementById('st-renderheight'); this.dom.sceneTimeLabel = document.getElementById('st-scenetime'); function setPlayingState( state ){ if(state){ ShaderTool.helpers.Ticker.start(); self.dom.playButton.style.display = 'none'; self.dom.pauseButton.style.display = ''; } else { ShaderTool.helpers.Ticker.stop(); self.dom.playButton.style.display = ''; self.dom.pauseButton.style.display = 'none'; } } ShaderTool.Utils.DOMUtils.addEventListener(this.dom.playButton, 'mousedown', function( e ){ e.preventDefault(); setPlayingState( true ); }); ShaderTool.Utils.DOMUtils.addEventListener(this.dom.pauseButton, 'mousedown', function( e ){ e.preventDefault(); setPlayingState( false ); }); ShaderTool.Utils.DOMUtils.addEventListener(this.dom.rewindButton, 'mousedown', function( e ){ e.preventDefault(); ShaderTool.helpers.Ticker.reset(); }); ShaderTool.Utils.DOMUtils.addEventListener(this.dom.fullscreenButton, 'mousedown', function( e ){ e.preventDefault(); ShaderTool.helpers.FSHelper.request(self._canvas); }); ShaderTool.Utils.DOMUtils.addEventListener(this._canvas, 'dblclick', function( e ){ e.preventDefault(); ShaderTool.helpers.FSHelper.exit(); }); this.dom.timescaleRange.setAttribute('step', '0.001'); this.dom.timescaleRange.setAttribute('min', '0.001'); this.dom.timescaleRange.setAttribute('max', '10'); this.dom.timescaleRange.setAttribute('value', '1'); ShaderTool.Utils.DOMUtils.addEventListener(this.dom.timescaleRange, 'input change', function( e ){ ShaderTool.helpers.Ticker.timeScale( parseFloat(self.dom.timescaleRange.value) ) }); setPlayingState( true ); }, _render: function( delta, elapsedTime ){ // To seconds: delta = delta * 0.001; elapsedTime = elapsedTime * 0.001; this.dom.sceneTimeLabel.innerHTML = elapsedTime.toFixed(2);; if (this._canvas.clientWidth !== this._canvas.width || this._canvas.clientHeight !== this._canvas.height) { var pixelRatio = window.devicePixelRatio || 1; var cWidth = this._canvas.width = this._canvas.clientWidth * pixelRatio; var cHeight = this._canvas.height = this._canvas.clientHeight * pixelRatio; this._setResolution(cWidth, cHeight); this.dom.renderWidthLabel.innerHTML = cWidth + 'px'; this.dom.renderHeightLabel.innerHTML = cHeight + 'px'; } var previosFrame = this._texture[this._writePosition]; var resolution = this._resolution; var destination = { framebuffer: framebuffer[this._writePosition] }; var totalRasterizers = this._rasterizers.length; for(var k=0; k<totalRasterizers; k++){ var rasterizer = this._rasterizers[k]; rasterizer.render(elapsedTime, previosFrame, resolution, destination); } if (!this._resolution) { return; } this._writePosition = (this._writePosition + 1) & 1; this._source.uniforms['uf_time'] = this._context.UniformFloat( elapsedTime ); this._source.uniforms['uv2_resolution'] = this._context.UniformVec2( this._resolution ); this._source.uniforms['us2_source'] = this._context.UniformSampler( this._texture[this._writePosition] ); this._context.rasterize(this._source); }, getData: function(){ return { uniforms: ShaderTool.modules.UniformControls.getData(), source: ShaderTool.modules.Editor.getData() } }, setData: function( data, skipCallChangeFlag ){ ShaderTool.modules.UniformControls.setData( data.uniforms, true ); ShaderTool.modules.Editor.setData( data.source, true ); this._updateSource( skipCallChangeFlag ); ShaderTool.helpers.Ticker.reset(); if(!skipCallChangeFlag){ this.onChange.call(); } } } return new Rendering(); })(); // Controls ShaderTool.modules.UniformControls = (function(){ function UniformControls(){} UniformControls.prototype = { init: function(){ console.log('ShaderTool.modules.UniformControls.init'); this.onChangeUniformList = new ShaderTool.Utils.Callback(); this.onChangeUniformValue = new ShaderTool.Utils.Callback(); this._changed = true; this._callChangeUniformList = function(){ this._changed = true; this.onChangeUniformList.call(); } this._callChangeUniformValue = function(){ this._changed = true; this.onChangeUniformValue.call(); } this._container = document.getElementById('st-uniforms-container'); this._controls = []; this._uniforms = {}; this._createMethods = {}; this._createMethods[UniformControls.FLOAT] = this._createFloat; this._createMethods[UniformControls.VEC2] = this._createVec2; this._createMethods[UniformControls.VEC3] = this._createVec3; this._createMethods[UniformControls.VEC4] = this._createVec4; this._createMethods[UniformControls.COLOR3] = this._createColor3; this._createMethods[UniformControls.COLOR4] = this._createColor4; // Templates: this._templates = {}; var totalTypes = UniformControls.TYPES.length; for(var k=0; k<totalTypes; k++){ var type = UniformControls.TYPES[k] var templateElement = document.getElementById('st-template-control-' + type); if(templateElement){ this._templates[type] = templateElement.innerHTML; templateElement.parentNode.removeChild(templateElement); } else { console.warn('No template html for ' + type + ' type!'); } } this._container.innerHTML = ''; // Clear container // Tests: /* for(var k=0; k<totalTypes; k++){ this._createControl('myControl' + (k+1), UniformControls.TYPES[k], null, true ); } //uniform float slide; //uniform vec3 color1; this._createControl('slide', UniformControls.FLOAT, [{max: 10, value: 10}], true ); // this._createControl('color1', UniformControls.COLOR3, null, true ); this._createControl('color1', UniformControls.VEC3, [{value:1},{},{}], true ); this._createControl('test', UniformControls.FLOAT, null, true ); this._createControl('test2', UniformControls.FLOAT, [{value: 1}], true ); this._createControl('test3', UniformControls.FLOAT, [{ value: 1 }], true ); // //this._callChangeUniformList(); //this._callChangeUniformValue(); */ this._initCreateControls(); }, /* Public methods */ getUniformsCode: function(){ var result = []; var totalControls = this._controls.length; for(var k=0; k<totalControls; k++){ result.push(this._controls[k].code); } return result.join('\n'); }, getUniformsData: function( context ){ if(!this._changed){ return this._uniforms; } this._changed = false; this._uniforms = {}; var totalControls = this._controls.length; for(var k=0; k<totalControls; k++){ var control = this._controls[k]; var value = control.getUniformValue(); if(control.type == UniformControls.FLOAT){ this._uniforms[control.name] = context.UniformFloat(value); } else if(control.type == UniformControls.VEC2){ this._uniforms[control.name] = context.UniformVec2(value); } else if(control.type == UniformControls.VEC3 || control.type == UniformControls.COLOR3){ this._uniforms[control.name] = context.UniformVec3(value); } else if(control.type == UniformControls.VEC4 || control.type == UniformControls.COLOR4){ this._uniforms[control.name] = context.UniformVec4(value); } } return this._uniforms; }, getData: function(){ var uniforms = []; var totalControls = this._controls.length; for(var k=0; k<totalControls; k++){ var control = this._controls[k]; uniforms.push({ name: control.name, type: control.type, data: control.data }) } return uniforms; }, setData: function( uniforms, skipCallChangeFlag){ this._clearControls( skipCallChangeFlag ); // TODO; var totalUniforms = uniforms.length; for(var k=0; k<totalUniforms; k++){ var uniformData = uniforms[k]; this._createControl(uniformData.name, uniformData.type, uniformData.data, true) } if(!skipCallChangeFlag){ this._callChangeUniformList(); } }, /* Private methods */ _checkNewUniformName: function( name ){ // TODO; return name != ''; }, _initCreateControls: function(){ var addUniformNameInput = document.getElementById('st-add-uniform-name'); var addUniformTypeSelect = document.getElementById('st-add-uniform-type'); var addUniformSubmit = document.getElementById('st-add-uniform-submit'); var self = this; ShaderTool.Utils.DOMUtils.addEventListener(addUniformSubmit, 'click', function( e ){ e.preventDefault(); var name = addUniformNameInput.value; if( !self._checkNewUniformName(name) ){ // TODO: Show info about incorrect uniforn name? addUniformNameInput.focus(); } else { var type = addUniformTypeSelect.value; self._createControl( name, type, null, false ); addUniformNameInput.value = ''; } }); }, _createControl: function( name, type, initialData, skipCallChangeFlag ){ this._changed = true; var self = this; var control; var elementTemplate = this._templates[type]; if( typeof elementTemplate == 'undefined' ){ console.error('No control template for type ' + type); return; } var element = ShaderTool.Utils.DOMUtils.createFromHTML(elementTemplate); var createMethod = this._createMethods[type]; if( createMethod ){ initialData = ShaderTool.Utils.isArray(initialData) ? initialData : []; control = createMethod.apply(this, [name, element, initialData] ); } else { throw new ShaderTool.Exception('Unknown uniform control type: ' + type); return null; } control.name = name; control.type = type; control.element = element; this._controls.push(control); this._container.appendChild(element); // name element var nameElement = element.querySelector('[data-uniform-name]'); if(nameElement){ nameElement.setAttribute('title', 'Uniform ' + name + ' settings'); nameElement.innerHTML = name; ShaderTool.Utils.DOMUtils.addEventListener(nameElement, 'dblclick', function( e ){ e.preventDefault(); alert('Show uniform rename dialog?') }); } // delete element var deleteElement = element.querySelector('[data-uniform-delete]'); if(deleteElement){ ShaderTool.Utils.DOMUtils.addEventListener(deleteElement, 'click', function( e ){ e.preventDefault(); if (confirm('Delete uniform?')) { self._removeControl( control ); } }); } if(!skipCallChangeFlag){ this._callChangeUniformList(); } }, _removeControl: function( control, skipCallChangeFlag ){ var totalControls = this._controls.length; for(var k=0; k<totalControls; k++){ if(this._controls[k] === control){ this._controls.splice(k, 1); control.element.parentNode.removeChild( control.element ); break; } } if(!skipCallChangeFlag){ this._callChangeUniformList(); } }, _clearControls: function(skipCallChangeFlag){ var c = 0; for(var k=0;k<this._controls.length; k++){ c++; if(c > 100){ return; } this._removeControl( this._controls[k], true ); k--; } if(!skipCallChangeFlag){ this._callChangeUniformList(); } }, _createFloat: function( name, element, initialData ){ var self = this; var saveData = [ this._prepareRangeData( initialData[0]) ]; var uniformValue = saveData[0].value; this._initRangeElementGroup(element, '1', saveData[0], function(){ uniformValue = saveData[0].value; self._callChangeUniformValue(); }); return { code: 'uniform float ' + name + ';', data: saveData, getUniformValue: function(){ return uniformValue; } } }, _createVec2: function( name, element, initialData ){ var self = this; var saveData = [ this._prepareRangeData( initialData[0] ), this._prepareRangeData( initialData[1] ) ]; var uniformValue = [saveData[0].value, saveData[1].value]; this._initRangeElementGroup(element, '1', saveData[0], function(){ uniformValue[0] = saveData[0].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '2', saveData[1], function(){ uniformValue[1] = saveData[1].value; self._callChangeUniformValue(); }); return { code: 'uniform vec2 ' + name + ';', data: saveData, getUniformValue: function(){ return uniformValue; } } }, _createVec3: function( name, element, initialData ){ var self = this; var saveData = [ this._prepareRangeData( initialData[0] ), this._prepareRangeData( initialData[1] ), this._prepareRangeData( initialData[2] ) ]; var uniformValue = [saveData[0].value, saveData[1].value, saveData[2].value]; this._initRangeElementGroup(element, '1', saveData[0], function(){ uniformValue[0] = saveData[0].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '2', saveData[1], function(){ uniformValue[1] = saveData[1].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '3', saveData[2], function(){ uniformValue[2] = saveData[2].value; self._callChangeUniformValue(); }); return { code: 'uniform vec3 ' + name + ';', data: saveData, getUniformValue: function(){ return uniformValue; } } }, _createVec4: function( name, element, initialData ){ var self = this; var saveData = [ this._prepareRangeData( initialData[0] ), this._prepareRangeData( initialData[1] ), this._prepareRangeData( initialData[2] ), this._prepareRangeData( initialData[3] ) ]; var uniformValue = [saveData[0].value, saveData[1].value, saveData[2].value, saveData[3].value]; this._initRangeElementGroup(element, '1', saveData[0], function(){ uniformValue[0] = saveData[0].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '2', saveData[1], function(){ uniformValue[1] = saveData[1].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '3', saveData[2], function(){ uniformValue[2] = saveData[2].value; self._callChangeUniformValue(); }); this._initRangeElementGroup(element, '4', saveData[3], function(){ uniformValue[3] = saveData[3].value; self._callChangeUniformValue(); }); return { code: 'uniform vec4 ' + name + ';', data: saveData, getUniformValue: function(){ return uniformValue; } } }, _createColor3: function( name, element, initialData ){ var self = this; var saveData = this._prepareColorData(initialData, false) this._initColorSelectElementGroup( element, false, saveData, function(){ self._callChangeUniformValue(); }) return { code: 'uniform vec3 ' + name + ';', data: saveData, getUniformValue: function(){ return saveData; } } }, _createColor4: function( name, element, initialData ){ var self = this; var saveData = this._prepareColorData(initialData, true); this._initColorSelectElementGroup( element, true, saveData, function(){ self._callChangeUniformValue(); }) return { code: 'uniform vec4 ' + name + ';', data: saveData, getUniformValue: function(){ return saveData; } } }, _prepareColorData: function( inputData, vec4Format ){ inputData = ShaderTool.Utils.isArray( inputData ) ? inputData : []; var resultData = vec4Format ? [0,0,0,1] : [0,0,0]; var counter = vec4Format ? 4 : 3; for(var k=0; k<counter;k++){ var inputComponent = inputData[k]; if( typeof inputComponent != 'undefined' ){ resultData[k] = inputComponent; } } return resultData; }, _prepareRangeData: function( inputData ){ inputData = typeof inputData == 'undefined' ? {} : inputData; var resultData = { value: 0, min: 0, max: 1 }; for(var i in resultData){ if(typeof inputData[i] != 'undefined'){ resultData[i] = inputData[i]; } } return resultData; }, _componentToHex: function(c){ var hex = c.toString(16); return hex.length == 1 ? '0' + hex : hex; }, _hexFromRGB: function(r, g, b){ return '#' + this._componentToHex(r) + this._componentToHex(g) + this._componentToHex(b); }, _initColorSelectElementGroup: function( element, useAlpha, initialData, changeHandler ){ var colorElement = element.querySelector('[data-color]'); colorElement.value = this._hexFromRGB(initialData[0] * 256 << 0, initialData[1] * 256 << 0, initialData[2] * 256 << 0); ShaderTool.Utils.DOMUtils.addEventListener(colorElement, 'change', function( e ){ var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(colorElement.value); initialData[0] = parseInt( result[1], 16 ) / 256; initialData[1] = parseInt( result[2], 16 ) / 256; initialData[2] = parseInt( result[3], 16 ) / 256; changeHandler(); }); if(useAlpha){ var rangeElement = element.querySelector('[data-range]'); rangeElement.setAttribute('min', '0'); rangeElement.setAttribute('max', '1'); rangeElement.setAttribute('step', '0.001'); rangeElement.setAttribute('value', initialData[3] ); ShaderTool.Utils.DOMUtils.addEventListener(rangeElement, 'input', function( e ){ initialData[3] = parseFloat(rangeElement.value); changeHandler(); }) } }, _initRangeElementGroup: function( element, attrIndex, initialData, changeHandler, stepValue ){ var minValue = initialData.min; var maxValue = initialData.max; var minElement = element.querySelector('[data-range-min-' + attrIndex + ']');// || document.createElement('input'); var maxElement = element.querySelector('[data-range-max-' + attrIndex + ']');// || document.createElement('input'); var rangeElement = element.querySelector('[data-range-' + attrIndex + ']'); var valueElement = element.querySelector('[data-range-value-' + attrIndex + ']') || document.createElement('div'); rangeElement.setAttribute('step', typeof stepValue != 'undefined' ? stepValue : '0.0001'); var prevMinValue; var prevMaxValue; minElement.setAttribute('title', 'Minimum value'); maxElement.setAttribute('title', 'Maximum value'); prevMinValue = minElement.value = valueElement.innerHTML = minValue; prevMaxValue = maxElement.value = maxValue; rangeElement.value = initialData.value; ShaderTool.Utils.DOMUtils.addEventListener(rangeElement, 'input', function( e ){ if(minElement.value == ''){ minElement.value = prevMinValue; } if(maxElement.value == ''){ maxElement.value = prevMaxValue; } if(minValue > maxValue){ prevMinValue = minElement.value = maxValue; prevMaxValue = maxElement.value = minValue; } valueElement.innerHTML = rangeElement.value; initialData.min = minValue; initialData.max = maxValue; initialData.value = parseFloat(rangeElement.value); changeHandler( initialData ); }); function updateRangeSettings(){ if(minElement.value == '' || maxElement.value == ''){ return; } prevMinValue = minElement.value; prevMaxValue = maxElement.value; minValue = ShaderTool.Utils.toDecimalString(minElement.value); maxValue = ShaderTool.Utils.toDecimalString(maxElement.value); var min = minValue = parseFloat(minValue); var max = maxValue = parseFloat(maxValue); if(min > max){ max = [min, min = max][0]; } rangeElement.setAttribute('min', min); rangeElement.setAttribute('max', max); initialData.min = min; initialData.max = max; } ShaderTool.Utils.DOMUtils.addEventListener([minElement, maxElement], 'keydown input change', function( e ){ if(!ShaderTool.Utils.isNumberKey( e )){ e.preventDefault(); return false; } updateRangeSettings(); }); updateRangeSettings(); } } UniformControls.FLOAT = 'float'; UniformControls.VEC2 = 'vec2'; UniformControls.VEC3 = 'vec3'; UniformControls.VEC4 = 'vec4'; UniformControls.COLOR3 = 'color3'; UniformControls.COLOR4 = 'color4'; UniformControls.TYPES = [UniformControls.FLOAT, UniformControls.VEC2, UniformControls.VEC3, UniformControls.VEC4, UniformControls.COLOR3, UniformControls.COLOR4]; return new UniformControls(); })(); // SaveController ShaderTool.modules.SaveController = (function(){ var DEFAULT_CODE = '{"uniforms":[{"name":"bgcolor","type":"color3","data":[0.99609375,0.8046875,0.56640625]}],"source":"void main() {\\n gl_FragColor = vec4(bgcolor, 1.);\\n}"}'; function SaveController(){} SaveController.prototype = { init: function(){ console.log('ShaderTool.modules.SaveController.init'); var savedData = ShaderTool.helpers.LSHelper.getItem('lastShaderData'); if(savedData){ ShaderTool.modules.Rendering.setData(savedData, true); } else { ShaderTool.modules.Rendering.setData(JSON.parse(DEFAULT_CODE), true); } this._initSaveDialogs(); ShaderTool.modules.Rendering.onChange.add( this._saveLocalState, this); this._saveLocalState(); }, _initSaveDialogs: function(){ this.dom = {}; this.dom.setCodeInput = document.getElementById('st-set-code-input'); this.dom.setCodeSubmit = document.getElementById('st-set-code-submit'); this.dom.getCodeInput = document.getElementById('st-get-code-input'); var self = this; ShaderTool.Utils.DOMUtils.addEventListener(this.dom.setCodeSubmit, 'click', function( e ){ var code = self.dom.setCodeInput.value; if(code != ''){ ShaderTool.modules.Rendering.setData(JSON.parse(code), true) } }) }, _saveLocalState: function(){ var saveData = ShaderTool.modules.Rendering.getData(); ShaderTool.helpers.LSHelper.setItem('lastShaderData', saveData); this.dom.getCodeInput.value = JSON.stringify(saveData); } } return new SaveController(); })(); ShaderTool.modules.PopupManager = (function(){ var OPENED_CLASS_NAME = '_opened'; function PopupManager(){} PopupManager.prototype = { init: function(){ console.log('ShaderTool.modules.PopupManager.init'); this.dom = {}; this.dom.overlay = document.getElementById('st-popup-overlay'); this._opened = false; var self = this; ShaderTool.Utils.DOMUtils.addEventListener(this.dom.overlay, 'mousedown', function( e ){ if( e.target === self.dom.overlay ){ self.close(); } }) var openers = document.querySelectorAll('[data-popup-opener]'); ShaderTool.Utils.DOMUtils.addEventListener(openers, 'click', function( e ){ self.open( this.getAttribute('data-popup-opener') ) }) }, open: function( popupName ){ this.close(); var popup = this.dom.overlay.querySelector(popupName); if( popup ){ this._opened = true; this._currentPopup = popup; ShaderTool.Utils.DOMUtils.addClass(this._currentPopup, OPENED_CLASS_NAME); ShaderTool.Utils.DOMUtils.addClass(this.dom.overlay, OPENED_CLASS_NAME); } else { // TODO; } }, close: function(){ if(!this._opened){ return; } this._opened = false; ShaderTool.Utils.DOMUtils.removeClass(this.dom.overlay, OPENED_CLASS_NAME); ShaderTool.Utils.DOMUtils.removeClass(this._currentPopup, OPENED_CLASS_NAME); } } return new PopupManager(); })(); // classes ShaderTool.classes.Rasterizer = (function(){ var VERTEX_SOURCE = 'attribute vec2 av2_vtx;varying vec2 vv2_v;void main(){vv2_v = av2_vtx;gl_Position = vec4(av2_vtx, 0., 1.);}'; function Rasterizer( context ){ this._context = context; this._program = null; this._prevProgram = null; this._buffer = this._context.createVertexBuffer().upload(new ShaderTool.Utils.Float32Array([1,-1,1,1,-1,-1,-1,1])); this._source = { program: this._program, attributes: { 'av2_vtx': { buffer: this._buffer, size: 2, type: this._context.AttribType.Float, offset: 0 } }, uniforms: {}, mode: this._context.Primitive.TriangleStrip, count: 4 }; } Rasterizer.prototype = { updateSource: function (fragmentSource) { var savePrevProgramFlag = true; try{ var newProgram = this._context.createProgram({ vertex: VERTEX_SOURCE, fragment: fragmentSource }); this._source.program = newProgram; } catch( e ){ console.warn('Error updating Rasterizer fragmentSource: ' + e.message); savePrevProgramFlag = false; if(this._prevProgram){ this._source.program = this._prevProgram; } } if(savePrevProgramFlag){ this._prevProgram = newProgram; } }, updateUniforms: function(uniforms){ this._source.uniforms = uniforms; }, render: function ( elapsedTime, frame, resolution, destination ) { this._source.uniforms['us2_frame'] = this._context.UniformSampler( frame ); this._source.uniforms['uv2_resolution'] = this._context.UniformVec2( resolution ); this._source.uniforms['uf_time'] = this._context.UniformFloat( elapsedTime); this._context.rasterize(this._source, null, destination); } } return Rasterizer; })();
import React, { PureComponent } from "react"; import { graphql } from 'gatsby' import Link from "gatsby-link"; import path from "ramda/src/path"; import ScrollReveal from "scrollreveal"; import Layout from "../components/Layout"; import "prismjs/themes/prism.css"; import styles from "./post.module.scss"; const getPost = path(["data", "markdownRemark"]); const getContext = path(["pageContext"]); const PostNav = ({ prev, next }) => ( <div className={styles.postNav}> {prev && ( <Link to={`/${prev.fields.slug}`}> 上一篇: {prev.frontmatter.title} </Link> )} {next && ( <Link to={`/${next.fields.slug}`}> 下一篇: {next.frontmatter.title} </Link> )} </div> ); export default class Post extends PureComponent { componentDidMount() { ScrollReveal().reveal(".article-header>h1", { delay: 500, useDelay: "onload", reset: true, origin: "top", distance: "120px" }); ScrollReveal().reveal(".article-content", { delay: 500, useDelay: "onload", reset: true, origin: "bottom", distance: "120px" }); } componentWillUnmount() { ScrollReveal().destroy(); } render() { const post = getPost(this.props); const { next, prev } = getContext(this.props); // Not to be confused with react context... return ( <Layout> <header className="article-header"> <h1>{post.frontmatter.title}</h1> </header> <div className="article-content" dangerouslySetInnerHTML={{ __html: post.html }} /> <PostNav prev={prev} next={next} /> </Layout> ); } } export const query = graphql` query BlogPostQuery($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { title } } } `;
import React, {Component} from 'react'; import {View, Text} from 'react-native'; import {xdateToData} from '../../interface'; import XDate from 'xdate'; import dateutils from '../../dateutils'; import styleConstructor from './style'; class ReservationListItem extends Component { constructor(props) { super(props); this.styles = styleConstructor(props.theme); } shouldComponentUpdate(nextProps) { const r1 = this.props.item; const r2 = nextProps.item; let changed = true; if (!r1 && !r2) { changed = false; } else if (r1 && r2) { if (r1.day.getTime() !== r2.day.getTime()) { changed = true; } else if (!r1.reservation && !r2.reservation) { changed = false; } else if (r1.reservation && r2.reservation) { if ((!r1.date && !r2.date) || (r1.date && r2.date)) { changed = this.props.rowHasChanged(r1.reservation, r2.reservation); } } } return changed; } renderDate(date, item) { if (this.props.renderDay) { return this.props.renderDay(date ? xdateToData(date) : undefined, item); } const today = dateutils.sameDate(date, XDate()) ? this.styles.today : undefined; if (date) { return ( <View style={this.styles.day}> <Text style={[this.styles.dayNum, today]}>{date.getDate()}</Text> <Text style={[this.styles.dayText, today]}>{XDate.locales[XDate.defaultLocale].dayNamesShort[date.getDay()]}</Text> </View> ); } else { return ( <View style={this.styles.day}/> ); } } render() { const {reservation, date} = this.props.item; let content; if (reservation) { const firstItem = date ? true : false; content = this.props.renderItem(reservation, firstItem); } else { content = this.props.renderEmptyDate(date); } return ( <View style={this.styles.container}> {this.renderDate(date, reservation)} <View style={{flex:1}}> {content} </View> </View> ); } } export default ReservationListItem;
/*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Metadata. pkg: grunt.file.readJSON('package.json'), banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n', // Task configuration. concat: { options: { banner: '<%= banner %>', stripBanners: true }, dist: { src: ['lib/<%= pkg.name %>.js'], dest: 'dist/<%= pkg.name %>.js' } }, uglify: { options: { banner: '<%= banner %>' }, dist: { src: '<%= concat.dist.dest %>', dest: 'dist/<%= pkg.name %>.min.js' } }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, unused: true, boss: true, eqnull: true, browser: true, globals: { jQuery: true } }, gruntfile: { src: 'Gruntfile.js' }, lib_test: { src: ['lib/**/*.js', 'test/**/*.js'] } }, qunit: { files: ['test/**/*.html'] }, watch: { gruntfile: { files: '<%= jshint.gruntfile.src %>', tasks: ['jshint:gruntfile'] }, lib_test: { files: '<%= jshint.lib_test.src %>', tasks: ['jshint:lib_test', 'qunit'] }, stylesheets: { files: 'stylesheets/sass/**/*.scss', tasks:['sass:dist'] } }, sass: { dist: { files: [{ expand: true, cwd: 'stylesheets/sass/project', src: ['*.scss'], dest: 'stylesheets/styles', ext: '.css' }] } } }); // These plugins provide necessary tasks. //grunt.loadNpmTasks('grunt-contrib-concat'); //grunt.loadNpmTasks('grunt-contrib-uglify'); //grunt.loadNpmTasks('grunt-contrib-qunit'); //grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); // Default task. //grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']); };
version https://git-lfs.github.com/spec/v1 oid sha256:2566f139073c240a090aee1fb4254ec2b799a9402dd6494447afbe4e12c97654 size 6184
import React from 'react' export default class NoteItem extends React.Component { render () { return ( <div> <p>Category = {this.props.note.category}</p> <p>The Note = {this.props.note.noteText}</p> <hr /> </div> ) } }
///<reference path="./otmword.ts" /> ///<reference path="./wmmodules.ts" /> ///<reference path="./wgenerator.ts" /> ///<reference path="./ntdialog.ts" /> /** * 単語作成部で使用するViewModel */ class WordDisplayVM { /** * コンストラクタ * @param el バインディングを適用するタグのid * @param dict OTM形式辞書クラス * @param createSetting 単語文字列作成に使用する設定 */ constructor(el, dict, createSetting, equivalent) { this.el = el; this.data = { dictionary: dict, isDisabled: false, createSetting: createSetting, id: 1, equivalent: equivalent, }; this.initMethods(); } /** * VMで使用するメソッドを定義するメソッド */ initMethods() { this.methods = { /** * 単語文字列を作成するメソッド */ create: function _create() { let form = ""; switch (this.createSetting.mode) { case WordGenerator.SIMPLE_SYMBOL: form = WordGenerator.simple(this.createSetting.simple); break; case WordGenerator.SIMPLECV_SYMBOL: form = WordGenerator.simplecv(this.createSetting.simplecv); break; case WordGenerator.DEPENDENCYCV_SYMBOL: form = WordGenerator.dependencycv(this.createSetting.dependencycv); break; default: break; } let word = new OtmWord(this.id++, form); word.add(""); this.dictionary.add(word); }, /** * 設定されている全ての訳語に対して単語を作成するメソッド */ createAll: function _createAll() { this.equivalent.equivalentsList.data.forEach((x) => { let form = ""; switch (this.createSetting.mode) { case WordGenerator.SIMPLE_SYMBOL: form = WordGenerator.simple(this.createSetting.simple); break; case WordGenerator.SIMPLECV_SYMBOL: form = WordGenerator.simplecv(this.createSetting.simplecv); break; case WordGenerator.DEPENDENCYCV_SYMBOL: form = WordGenerator.dependencycv(this.createSetting.dependencycv); break; default: break; } let word = new OtmWord(this.id++, form); word.add(x.equivalents.join(",")); this.dictionary.add(word); }); }, /** * 作成した全ての単語を削除するメソッド */ removeAll: function _removeAll() { this.dictionary.removeAll(); // idを初期値にする this.id = 1; }, /** * 作成した単語一覧をOTM-JSON形式で出力するメソッド */ outputOtmJSON: function _outputOtmJSON() { // idを振り直す let id = 1; this.dictionary.words.forEach((x) => { x.entry.id = id++; }); WMModules.exportJSON(this.dictionary, "dict.json"); // 引き続き作成する場合を考えてidを更新する this.id = id; }, // 個々で使用する部分 /** * 訳語選択ダイアログを呼び出すメソッド * @param 訳語を設定する単語クラス */ showEquivalentDialog: function _showEquivalentDialog(word) { this.equivalent.selectedWordId = word.entry.id.toString(); WMModules.equivalentDialog.show(); }, /** * 単語を削除するメソッド * @param 削除する単語クラス */ remove: function _remove(word) { this.dictionary.remove(word.entry.id); }, /** * 単語の区切りの","で文字列を区切って配列にするためのメソッド * @param 単語の訳語(カンマ区切り) * @return カンマを区切り文字として分割した結果の文字列配列 */ splitter: function _splitter(value) { return value.split(",").map(function (x) { return x.trim(); }); }, }; } } //# sourceMappingURL=worddisplayvm.js.map
var CategoryLevel = function(){ 'use strict'; var categorys = {}; this.addCategory = function(_name) { categorys[_name] = []; }; this.addDataToLastCategory = function(_categoryName, _lineData, _className) { var category = categorys[_categoryName]; }; };
/* global $:true */ + function($) { var defaults; var Photos = function(config) { this.initConfig(config); this.index = 0; } Photos.prototype = { initConfig: function (config) { this.config = $.extend({}, defaults, config); this.activeIndex = this.lastActiveIndex = this.config.initIndex; this.config.items = this.config.items.map(function(d, i) { if(typeof d === typeof 'a') { return { image: d, caption: '' } } return d; }); this.tpl = $.t7.compile(this.config.tpl); if(this.config.autoOpen) this.open(); }, open: function (index) { if (this._open) return false; if (!this.modal) { this.modal = $(this.tpl(this.config)).appendTo(document.body); this.container = this.modal.find('.swiper-container'); this.wrapper = this.modal.find('.swiper-wrapper'); var hammer = new Hammer(this.container[0]); hammer.get('pinch').set({ enable: true }); hammer.on('pinchstart', $.proxy(this.onGestureStart, this)); hammer.on('pinchmove', $.proxy(this.onGestureChange, this)); hammer.on('pinchend', $.proxy(this.onGestureEnd, this)); this.modal.on($.touchEvents.start, $.proxy(this.onTouchStart, this)); this.modal.on($.touchEvents.move, $.proxy(this.onTouchMove, this)); this.modal.on($.touchEvents.end, $.proxy(this.onTouchEnd, this)); //init index this.wrapper.transition(0); this.wrapper.transform('translate3d(-' + $(window).width()*this.config.initIndex + 'px,0,0)'); this.container.find('.caption-item').eq(this.config.initIndex).addClass('active'); this.container.find('.swiper-pagination-bullet').eq(this.config.initIndex).addClass('swiper-pagination-bullet-active'); } var self = this; this.modal.show().height(); this.modal.addClass('weui-photo-browser-modal-visible'); this.container.addClass('swiper-container-visible').transitionEnd(function() { self.initParams(); if(index !== undefined) { self.slideTo(index); } if(self.config.onOpen) { self.config.onOpen.call(self); } }); this._open = true; }, close: function() { this.container.transitionEnd($.proxy(function() { this.modal.hide(); this._open = false; if(this.config.onClose) this.config.onClose.call(this); }, this)); this.container.removeClass('swiper-container-visible'); this.modal.removeClass('weui-photo-browser-modal-visible'); }, initParams: function () { if(this.containerHeight) return false; this.windowWidth = $(window).width(); this.containerHeight = this.container.height(); this.containerWidth = this.container.width(); this.touchStart = {}; this.wrapperTransform = 0; this.wrapperLastTransform = - $(window).width()*this.config.initIndex; this.wrapperDiff = 0; this.lastScale = 1; this.currentScale = 1; this.imageLastTransform = { x: 0, y: 0 }; this.imageTransform = { x: 0, y: 0 }; this.imageDiff = { x: 0, y: 0 }; this.imageLastDiff = { x: 0, y: 0 }; }, onTouchStart: function (e) { if(this.scaling) return false; this.touching = true; this.touchStart = $.getTouchPosition(e); this.touchMove = null; this.touchStartTime = + new Date; this.wrapperDiff = 0; this.breakpointPosition = null; }, onTouchMove: function (e) { if(!this.touching || this.scaling) return false; e.preventDefault(); if(this.gestureImage) { var rect = this.gestureImage[0].getBoundingClientRect(); if (rect.left >= 0 || rect.right <= this.windowWidth) { this.overflow = true; } else { this.overflow = false; } } else { this.oveflow = false; } var p = this.touchMove = $.getTouchPosition(e); if(this.currentScale === 1 || this.overflow) { if(this.breakpointPosition) { this.wrapperDiff = p.x - this.breakpointPosition.x; } else { this.wrapperDiff = p.x - this.touchStart.x; } if(this.activeIndex === 0 && this.wrapperDiff > 0) this.wrapperDiff = Math.pow(this.wrapperDiff, .8); if(this.activeIndex === this.config.items.length - 1 && this.wrapperDiff < 0) this.wrapperDiff = - Math.pow(-this.wrapperDiff, .8); this.wrapperTransform = this.wrapperLastTransform + this.wrapperDiff; this.doWrapperTransform(); } else { var img = this.gestureImage; this.imageDiff = { x: p.x - this.touchStart.x, y: p.y - this.touchStart.y } this.imageTransform = { x: this.imageDiff.x + this.imageLastTransform.x, y: this.imageDiff.y + this.imageLastTransform.y }; this.doImageTransform(); this.breakpointPosition = p; this.imageLastDiff = this.imageDiff; } }, onTouchEnd: function (e) { if(!this.touching) return false; this.touching = false; if(this.scaling) return false; var duration = (+ new Date) - this.touchStartTime; if(duration < 200 && (!this.touchMove || Math.abs(this.touchStart.x - this.touchMove.x) <= 2 && Math.abs(this.touchStart.y - this.touchMove.y) <= 2)) { this.onClick(); return; } if(this.wrapperDiff > 0) { if(this.wrapperDiff > this.containerWidth/2 || (this.wrapperDiff > 20 && duration < 300)) { this.slidePrev(); } else { this.slideTo(this.activeIndex, 200); } } else { if(- this.wrapperDiff > this.containerWidth/2 || (-this.wrapperDiff > 20 && duration < 300)) { this.slideNext(); } else { this.slideTo(this.activeIndex, 200); } } this.imageLastTransform = this.imageTransform; this.adjust(); }, onClick: function () { var self = this; if (this._lastClickTime && ( + new Date - this._lastClickTime < 300)) { this.onDoubleClick(); clearTimeout(this._clickTimeout); } else { this._clickTimeout = setTimeout(function () { self.close(); }, 300); } this._lastClickTime = + new Date; }, onDoubleClick: function () { this.gestureImage = this.container.find('.swiper-slide').eq(this.activeIndex).find('img'); this.currentScale = this.currentScale > 1 ? 1 : 2; this.doImageTransform(200); this.adjust(); }, onGestureStart: function (e) { this.scaling = true; this.gestureImage = this.container.find('.swiper-slide').eq(this.activeIndex).find('img'); }, onGestureChange: function (e) { var s = this.lastScale * e.scale; if (s > this.config.maxScale) { s = this.config.maxScale + Math.pow((s - this.config.maxScale), 0.5); } else if (s < 1) { s = Math.pow(s, .5); } this.currentScale = s; this.doImageTransform(); }, onGestureEnd: function (e) { if (this.currentScale > this.config.maxScale) { this.currentScale = this.config.maxScale; this.doImageTransform(200); } else if (this.currentScale < 1) { this.currentScale = 1; this.doImageTransform(200); } this.lastScale = this.currentScale; this.scaling = false; this.adjust(); }, doWrapperTransform: function(duration, callback) { if (duration === 0) { var origin = this.wrapper.css('transition-property') this.wrapper.css('transition-property', 'none').transform('translate3d(' + this.wrapperTransform + 'px, 0, 0)'); this.wrapper.css('transition-property', origin); callback() } else { this.wrapper.transitionEnd(function() { callback && callback(); }); this.wrapper.transition(duration || defaults.duration).transform('translate3d(' + this.wrapperTransform + 'px, 0, 0)'); } }, doImageTransform: function(duration, callback) { if(!this.gestureImage) return; this.gestureImage.transition(duration || 0).transform('translate3d(' + this.imageTransform.x + 'px,' + this.imageTransform.y + 'px, 0) scale(' + this.currentScale + ')'); this._needAdjust = true; }, adjust: function() { if(!this._needAdjust) return false; var img = this.gestureImage; if(!img) return false; if(this.currentScale === 1) { this.imageTransform = this.imageLastDiff = {x:0,y:0}; this.doImageTransform(200); return; } var rect = img[0].getBoundingClientRect(); //调整上下 if(rect.height < this.containerHeight) { // 如果高度没容器高,则自动居中 this.imageTransform.y = this.imageLastTransform.y = 0; } else { //如果比容器高,那么要保证上下不能有空隙 if(rect.top > 0) this.imageTransform.y = this.imageTransform.y - rect.top; else if(rect.bottom < this.containerHeight) this.imageTransform.y = this.imageTransform.y + this.containerHeight - rect.bottom; } this.doImageTransform(200); this._needAdjust = false; // must at last line, because doImageTransform will set this._needAdjust true }, slideTo: function(index, duration) { if(index < 0) index = 0; if(index > this.config.items.length-1) index = this.config.items.length - 1; this.lastActiveIndex = this.activeIndex; this.activeIndex = index; this.wrapperTransform = - (index * this.containerWidth); this.wrapperLastTransform = this.wrapperTransform; this.doWrapperTransform(duration, $.proxy(function() { if(this.lastActiveIndex === this.activeIndex) return false; // active index not change this.container.find('.caption-item.active').removeClass('active'); this.container.find('.swiper-slide-active').removeClass('swiper-slide-active'); this.container.find('.swiper-pagination-bullet-active').removeClass('swiper-pagination-bullet-active'); this.container.find('.caption-item').eq(this.activeIndex).addClass('active'); this.container.find('.swiper-slide').eq(this.activeIndex).addClass('swiper-slide-active'); this.container.find('.swiper-pagination-bullet').eq(this.activeIndex).addClass('swiper-pagination-bullet-active'); //reset image transform this.container.find('.swiper-slide img[style]').transition(0).transform('translate3d(0,0,0) scale(1)'); this.lastScale = 1; this.currentScale = 1; this.imageLastTransform = { x: 0, y: 0 }; this.imageTransform = { x: 0, y: 0 }; this.imageDiff = { x: 0, y: 0 }; this.imageLastDiff = { x: 0, y: 0 }; if(this.config.onSlideChange) { this.config.onSlideChange.call(this, this.activeIndex); } }, this)); }, slideNext: function() { return this.slideTo(this.activeIndex+1, 200); }, slidePrev: function() { return this.slideTo(this.activeIndex-1, 200); } } defaults = Photos.prototype.defaults = { items: [], autoOpen: false, //初始化完成之后立刻打开 onOpen: undefined, onClose: undefined, initIndex: 0, //打开时默认显示第几张 maxScale: 3, onSlideChange: undefined, duration: 200, // 默认动画时间,如果没有在调用函数的时候指定,则使用这个值 tpl: '<div class="weui-photo-browser-modal">\ <div class="swiper-container">\ <div class="swiper-wrapper">\ {{#items}}\ <div class="swiper-slide">\ <div class="photo-container">\ <img src="{{image}}" />\ </div>\ </div>\ {{/items}}\ </div>\ <div class="caption">\ {{#items}}\ <div class="caption-item caption-item-{{@index}}">{{caption}}</div>\ {{/items}}\ </div>\ <div class="swiper-pagination swiper-pagination-bullets">\ {{#items}}\ <span class="swiper-pagination-bullet"></span>\ {{/items}}\ </div>\ </div>\ </div>' } $.photoBrowser = function(params) { return new Photos(params); } }($);
define(function(){ var config = {}; config.app = 'pregapp'; // Your App name //config.jqueryMobileTheme = "/francine/css/theme.css"; //config.jqueryMobilePath="/francine/js/jquery.mobile-1.2.0"; //config.jqueryMobileCss="/francine/css/mobile.css"; config.extraScripts = []; config.quickformsEnding = ""; // "" or ".asp" config.defaultPageTransition = "none"; // slide, pop, none config.defaultDialogTransition = "none"; // slide, pop, none return config; });
describe('A Feature', function() { it('A Scenario', function() { // ### Given missing code }); });
/** * FlowrouteNumbersLib * * This file was automatically generated for flowroute by APIMATIC BETA v2.0 on 02/08/2016 */ var configuration = { //The base Uri for API calls BASEURI : "https://api.flowroute.com/v1", //Tech Prefix //TODO: Replace the Username with an appropriate value username : "TODO: Replace", //API Secret Key //TODO: Replace the Password with an appropriate value password : "TODO: Replace" }; module.exports = configuration;
$(document).ready(function(){ //The user will be prompted to continue and go down the page by clicking on an HTML element //The result will be a smooth transition of the word ">>>Continue" and then a smooth scroll down the page //to the next stage of the user's process in the application: making an account(probably done through Google and Facebook) $(document).ready(function(){ $('#userPrompt>span:nth-child(1)').delay(350).fadeTo(450,1.0); $('#userPrompt>span:nth-child(2)').delay(450).fadeTo(450,1.0); $('#userPrompt>span:nth-child(3)').delay(550).fadeTo(450,1.0); //this div represents the bottom option, or the 'quick presentation div' $('#Continue').delay(700).fadeTo(850,1.0); //Continue button }); /*$('#userPrompt').click(function(){ $('#promptOverlay').fadeTo(850,0.0); $(this).delay(850).animate({marginLeft: '900px'}, 850) $(this).delay(100).fadeOut(850); }); The "#promptOverlay" div is not longer in use, and as a result, we do not need to use this line of code... Let's keep things....simpler... */ $('#userPrompt').one("click",function(){ $(this).fadeTo(850,0); //Scroll Down var height = $("#navBar").css('height'); $('html , body').animate({ scrollTop: 725 }, 1250); //Create Options on Options Bar div, first by making a dividing line $('#imagine').delay(1250).animate({ height: '330px' }); //Create Third option by making it now visible... $('#quick').delay(1850).fadeTo(300, 1); //Time to make options visible... $('.heading').delay(2000).fadeTo(300, 1); }); //With options now created, we can create some functionality to those options, making the user's experience both meaningful and aesthetically pleasing. /*$('#returner, #imagine').click(function(){ //alert("Log into account"); Test $('.heading').fadeTo(850, 0); $('#quick').fadeOut(); $('#imagine').delay(250).animate({ height: '0px' }); $('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)"); $('#optionsBar'); });*/ /*$('#newUser').one("click", function(){ //alert("Make account"); Test $('#optionsBar>div').fadeOut(850); $('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)"); var welcomeHeader = '<h3 margin-top="20px" class="heading">Welcome to ShowCase. Please Log In Below...</h3>'; var inputTypeOne = '<input type="text/plain">keep' //$('h3').delay(1900).html("Welcome to ShowCase. Please Log In Below...").appendTo("#optionsBar"); $(welcomeHeader).hide().delay(2000).appendTo('#optionsBar').fadeIn(100); var styles = { fontFamily: 'Lato', color: 'rgba(16,16,14,0.65)', paddingTop: '10px', }; // $(welcomeHeader).css(headerStyle); $('#optionsBar').css(styles); });//End of Account Creation Process...* $('#quick').click(function(){ //alert("I just don't care."); Test $('.heading').fadeTo(850, 0); $('#quick').fadeOut(); $('#imagine').delay(250).animate({ height: '0px' }); $('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)"); });*/ });
import AnswerRating from './answerRating'; import FeedBackResults from './feedbackResults'; import './less/feedback.less'; // Check if bar rating should be initialized const ratingWrapper = document.querySelector('.rating-wrapper'); if (ratingWrapper !== null) { AnswerRating(); } // Check if feed back results charts should be initialized const feedBackResultsElement = document.getElementById('feedback-results'); if (feedBackResultsElement !== null) { FeedBackResults(); }
function initialize(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), exec: { build: { command: 'make build' }, // 'build-types': { command: 'make build-types' }, 'build-style': { command: 'make build-style' }, 'build-server': { command: 'make build-server' }, 'build-client': { command: 'make build-client' }, // 'database-shell': { // command: "echo 'mongo --username client --password testing christian.mongohq.com:10062/Beta-CitizenDish'" // } }, watch: { types: { files: [ 'types/egyptian-number-system.d.ts'], tasks: [ 'exec:build-types'], spawn: false }, style: { files: [ 'style/less/*.less', 'style/less/**/*.less','public/less/**/*.less' ], tasks: [ 'exec:build-style'], spawn: false }, server: { files: [ 'server/**/*.ts', 'server/*.ts', ], tasks: [ 'exec:build-server' ], spawn: false }, client: { files: [ 'client/**/*.ts', 'client/*.ts'], tasks: [ 'exec:build-client' ], spawn: false } }, nodemon: { application: { script: 'server/api.js', options: { ext: 'js', watch: ['server'], ignore: ['server/**'], delay: 2000, legacyWatch: false } }, developer: { script: 'server/developer-api.js', options: { ext: 'js', watch: ['server'], // ignore: ['server/**'], delay: 3000, legacyWatch: false } } } , concurrent: { options: { logConcurrentOutput: true }, developer: { tasks: [ 'exec:build', 'nodemon:developer', 'watch:style', 'watch:server', 'watch:client' ] // tasks: [ 'exec:build', 'nodemon:server', 'watch:types', 'watch:style', 'watch:server', 'watch:client' ] }, application: { tasks: [ 'exec:build', 'nodemon:application', 'watch:style', 'watch:server', 'watch:client' ] // tasks: [ 'exec:build', 'nodemon:server', 'watch:types', 'watch:style', 'watch:server', 'watch:client' ] } } }) ; grunt.loadNpmTasks('grunt-exec'); grunt.loadNpmTasks('grunt-nodemon'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-concurrent'); grunt.registerTask('default', ['concurrent:application']) ; grunt.registerTask('developer', ['concurrent:developer']) ; grunt.option('debug', true); // grunt.option('force', true); } module.exports = initialize;
const should = require('should'); const MissionLog = require('../lib/log').MissionLog; const Severity = require('../lib/Severity'); describe('MissionLog', function () { it('should test the properties', function () { const Log = new MissionLog(); Log.should.have.property('severities').with.lengthOf(5); Log.should.have.property('defaultSeverity'); }); it('should return the default severity', function () { const Log = new MissionLog(); Log.getDefaultSeverity().name.should.be.equal('VERBOSE'); const severities = Log.getSeverities(); should(severities.length).be.equal(5); }); it('should add a new severity', function() { const severityName = 'Test123123'; const newSeverity = new Severity(severityName); const Log = new MissionLog(); Log.addSeverity(newSeverity); const severities = Log.getSeverities(); const length = severities.length; should(length).be.equal(6); should(severities[5].name).be.equal(severityName.toUpperCase()); }); it('should switch the default severity', function() { const newSeverity = new Severity('Test'); const Log = new MissionLog(); Log.setDefaultSeverity(newSeverity); const defaultSeverity = Log.getDefaultSeverity(); should(defaultSeverity.name).equal(newSeverity.name); }); it('should try to add a severity twice', function() { const firstSeverity = new Severity('UnitTesting'); const secondSeverity = new Severity('UnitTesting'); const Log = new MissionLog(); const preCount = Log.getSeverities().length; Log.addSeverity(firstSeverity); const afterFirst = Log.getSeverities().length; Log.addSeverity(secondSeverity); const afterSecond = Log.getSeverities().length; should(afterFirst).be.equal(afterSecond); }); it('should log using verbose severity', function () { const Log = new MissionLog(); Log.log('VERBOSE', 'test'); }); });
const { getURL, sockets } = require('../common/configuration.js'); const io = require('socket.io-client'); const os = require('os'); const socket = io.connect(getURL(sockets.measures), { query: `id=${os.hostname()}&cores=${os.cpus().length}` }); setInterval(() => { socket.emit('new.load', { load: os.loadavg(), timestamp: new Date().getTime() }); }, 5000);
import React from 'react' import { mount, shallow, render } from 'enzyme' import { Stepper } from './Stepper' import Step from './Stepper.Step' import { StepUI, StepperUI } from './Stepper.css' const mockSteps = [ { id: 'Id1', title: 'Test Title 1', }, { id: 'Id2', title: 'Test Title 2', }, { id: 'Id3', title: 'Test Title 3', }, { id: 'Id4', title: 'Test Title 4', }, ] describe('className', () => { test('Has default className', () => { const wrapper = render(<Stepper />) expect(wrapper.hasClass('c-Stepper')).toBeTruthy() }) test('Can render custom className', () => { const customClassName = 'blue' const wrapper = render(<Stepper className={customClassName} />) expect(wrapper.hasClass(customClassName)).toBeTruthy() }) }) describe('HTML props', () => { test('Can render default HTML props', () => { const wrapper = render(<Stepper data-cy="blue" />) expect(wrapper.attr('data-cy')).toBe('blue') }) }) describe('children', () => { test('should have a child component for each step', () => { const wrapper = mount(<Stepper steps={mockSteps} currentIndex={0} />) const steps = wrapper.find(Step) expect(steps.length).toEqual(4) }) test('should assign proper isActive state to each step', () => { const wrapper = mount(<Stepper steps={mockSteps} currentIndex={2} />) wrapper.update() const steps = wrapper.find(StepUI) let results = [] steps.forEach(step => { results.push(step.hasClass('is-active')) }) expect(results[0]).toEqual(true) expect(results[1]).toEqual(true) expect(results[2]).toEqual(true) expect(results[3]).toEqual(false) }) }) describe('callbacks', () => { test('should call callbacks', () => { const onChangeSpy = jest.fn() const onCompleteSpy = jest.fn() const wrapper = mount( <Stepper onChange={onChangeSpy} onComplete={onCompleteSpy} currentIndex={0} steps={mockSteps} /> ) expect(onChangeSpy).toHaveBeenCalledTimes(0) expect(onCompleteSpy).toHaveBeenCalledTimes(0) wrapper.setProps({ currentIndex: 1 }) expect(onChangeSpy).toHaveBeenCalledTimes(1) expect(onCompleteSpy).toHaveBeenCalledTimes(0) wrapper.setProps({ currentIndex: 2 }) expect(onChangeSpy).toHaveBeenCalledTimes(2) expect(onCompleteSpy).toHaveBeenCalledTimes(0) wrapper.setProps({ currentIndex: 3 }) expect(onChangeSpy).toHaveBeenCalledTimes(3) expect(onCompleteSpy).toHaveBeenCalledTimes(1) }) test('should call onStepClick callback', () => { const onStepClickSpy = jest.fn() const wrapper = shallow( <Stepper steps={mockSteps} onStepClick={onStepClickSpy} /> ) wrapper .find(Step) .at(0) .simulate('click') expect(onStepClickSpy).toHaveBeenCalledTimes(1) }) }) describe('StepperUI', () => { test('should return the correct value for getProgress', () => { const wrapper = mount(<Stepper steps={mockSteps} currentIndex={2} />) expect(wrapper.find(StepperUI).prop('aria-valuenow')).toEqual(3) }) }) describe('getProgress', () => { test('should equal 2', () => { const wrapper = mount(<Stepper steps={mockSteps} currentIndex={1} />) expect(wrapper.instance().getProgress()).toEqual(2) }) test('when no currentIndex is null, kkshould return 1', () => { const wrapper = mount(<Stepper currentIndex={null} />) expect(wrapper.instance().getProgress()).toEqual(1) }) }) describe('getMatchIndex', () => { test('should return 1', () => { const wrapper = mount(<Stepper currentIndex={1} />) expect(wrapper.instance().getMatchIndex()).toEqual(1) }) test('when no currentIndex defined should return 0', () => { const wrapper = mount(<Stepper currentIndex={null} />) expect(wrapper.instance().getMatchIndex()).toEqual(-1) }) }) describe('componentDidUpdate', () => { test('should call onChange callback', () => { const onChangeSpy = jest.fn() const wrapper = mount( <Stepper onChange={onChangeSpy} steps={mockSteps} currentIndex={1} /> ) wrapper.instance().componentDidUpdate({ currentIndex: 0 }) expect(onChangeSpy).toHaveBeenCalled() }) test('should not call onChange callback', () => { const onChangeSpy = jest.fn() const wrapper = mount( <Stepper onChange={onChangeSpy} steps={mockSteps} currentIndex={1} /> ) wrapper.instance().componentDidUpdate({ currentIndex: 1 }) expect(onChangeSpy).not.toHaveBeenCalled() }) }) describe('handleChangeCallback', () => { test('should not call onChange', () => { const onChangeSpy = jest.fn() const wrapper = mount( <Stepper onChange={onChangeSpy} steps={[]} currentIndex={1} /> ) wrapper.instance().handleChangeCallback() expect(onChangeSpy).not.toHaveBeenCalled() }) }) describe('Step className', () => { test('should call click handler if isClickable is true', () => { const onClickSpy = jest.fn() const wrapper = mount(<Step isClickable={true} onClick={onClickSpy} />) wrapper .find('.c-StepperStep') .at(0) .simulate('click') expect(onClickSpy).toHaveBeenCalledTimes(1) }) test('should NOT call click handler if isClickable is false', () => { const onClickSpy = jest.fn() const wrapper = mount(<Step isClickable={false} onClick={onClickSpy} />) wrapper .find('.c-StepperStep') .at(0) .simulate('click') expect(onClickSpy).toHaveBeenCalledTimes(0) }) })
module.exports = middleware; var states = { STANDBY: 0, BUSY: 1 }; function middleware(options) { var regio = require('regio'), tessel = require('tessel'), camera = require('camera-vc0706').use(tessel.port[options.port]), app = regio.router(), hwReady = false, current; camera.on('ready', function() { hwReady = true; current = states.STANDBY; }); app.get('/', handler); function handler(req, res) { if (hwReady) { if (current === states.STANDBY) { current = states.BUSY; camera.takePicture(function (err, image) { res.set('Content-Type', 'image/jpeg'); res.set('Content-Length', image.length); res.status(200).end(image); current = states.STANDBY; }); } else { res.set('Retry-After', 100); res.status(503).end(); } } else { res.status(503).end(); } } return app; }
'use strict'; var ObjectUtil, self; module.exports = ObjectUtil = function () { self = this; }; /** * @method promiseWhile * @reference http://blog.victorquinn.com/javascript-promise-while-loop */ ObjectUtil.prototype.promiseWhile = function () { };
var assert = require('chai').assert; var Pad = require('../lib/pad'); describe('Pad', function() { it('should be an object', function() { var pad = new Pad(); assert.isObject(pad); }); it('should have a x coordinate of 310 by default', function() { var terminator = new Pad(); assert.equal(terminator.x, 310); }); it('should have a y coordinate of 470 by default', function() { var jon = new Pad(); assert.equal(jon.y, 470); }); it('should have a r value of 23 by default', function() { var terminator = new Pad(); assert.equal(terminator.r, 23); }); it('should have a sAngle value of 0 by default', function() { var jon = new Pad(); assert.equal(jon.sAngle, 0); }); it('should have an eAngle value of 2*Math.PI by default', function() { var jon = new Pad(); assert.equal(jon.eAngle, 2*Math.PI); }); it('should have a draw function', function(){ var jon = new Pad(); assert.isFunction(jon.draw); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:fd2ad8a08df37f7b13dad35da22197faf51ef6887162bf5f74ce30df59fdba0f size 15638
// client.express.js JavaScript Routing, version: 0.3.4 // (c) 2011 Mark Nijhof // // Released under MIT license. // ClientExpress={};ClientExpress.createServer=function(){return new ClientExpress.Server};ClientExpress.supported=function(){return typeof window.history.pushState=="function"};ClientExpress.logger=function(){return function(){var c=new ClientExpress.Logger;this.eventBroker.addListener("onLog",function(a){a.arguments.shift()=="warning"?c.warning(a.arguments):c.information(a.arguments)})}}; ClientExpress.setTitle=function(c){var a=c&&c.titleArgument;return function(){this.eventBroker.addListener("onRequestProcessed",function(c){var e;e=c.response.title;a&&c.args[a]&&(e=c.args[a]);if(e)document.title=e})}}; ClientExpress.Server=function(){var c=0,a=function(){this.version="0.3.4";this.id=[(new Date).valueOf(),c++].join("-");this.settings={};this.templateEngines={};this.router=new ClientExpress.Router;this.eventListener=new ClientExpress.EventListener;this.eventBroker=new ClientExpress.EventBroker(this);this.session={};this.content_target_element=document.childNodes[1];this.setup_functions=[];this.log=function(){this.eventBroker.fire({type:"Log",arguments:ClientExpress.utils.toArray(arguments)})}; this.eventBroker.addListener("onProcessRequest",e);this.eventBroker.addListener("onRequestProcessed",b);this.eventBroker.addListener("onRender",f);this.eventBroker.addListener("onSend",h);this.eventBroker.addListener("onRedirect",i)};a.prototype.content_target_area=function(d){var b=this;return function(){var a=document.getElementById?document.getElementById(d):document.all?document.all[d]:document.layers?document.layers[d]:null;b.content_target_element=a||document.childNodes[1];b.content_target_element== document.childNodes[1]&&this.log("warning",'Element "',d,'" could not be located!')}};a.prototype.configure=function(d,b){typeof d=="function"?this.setup_functions.push(d):this.setup_functions.push(function(){server.enabled(d)&&b.call()})};a.prototype.use=function(d,b){if(typeof d=="function")d.call(this);else{d[d.length-1]==="/"&&(d=d.substring(0,d.length-1));var a=function(d,b){if(b=="/")return d;if(b.substr(0,1)!="/")return d+"/"+b;return d+b},f=this,h=b.router.routes;ClientExpress.utils.forEach(h.get, function(b){g(f,b.method,a(d,b.path),b.action,d)});ClientExpress.utils.forEach(h.post,function(b){g(f,b.method,a(d,b.path),b.action,d)});ClientExpress.utils.forEach(h.put,function(b){g(f,b.method,a(d,b.path),b.action,d)});ClientExpress.utils.forEach(h.del,function(b){g(f,b.method,a(d,b.path),b.action,d)})}};a.prototype.set=function(d,b){if(b===void 0)if(this.settings.hasOwnProperty(d))return this.settings[d];else{if(this.parent)return this.parent.set(d)}else return this.settings[d]=b,this};a.prototype.enable= function(d){this.settings.hasOwnProperty(d);this.settings[d]=!0};a.prototype.disable=function(d){this.settings.hasOwnProperty(d);this.settings[d]=!1};a.prototype.enabled=function(d){return this.settings.hasOwnProperty(d)&&this.settings[d]};a.prototype.disabled=function(d){return this.settings.hasOwnProperty(d)&&!this.settings[d]};a.prototype.register=function(d,b){if(b===void 0)if(this.templateEngines.hasOwnProperty(d))return this.templateEngines[d];else{if(this.parent)return this.parent.set(d)}else return this.templateEngines[d]= b,this};a.prototype.get=function(d,b){return g(this,"get",d,b,"")};a.prototype.post=function(d,b){return g(this,"post",d,b,"")};a.prototype.put=function(d,b){return g(this,"put",d,b,"")};a.prototype.del=function(b,a){return g(this,"del",b,a,"")};var g=function(b,a,f,h,c){b.router.registerRoute(a,f,h,c);return b};a.prototype.listen=function(){if(ClientExpress.supported()){var b=this;ClientExpress.onDomReady(function(){ClientExpress.utils.forEach(b.setup_functions,function(a){a.call(b)});b.eventListener.registerEventHandlers(b); var a=new ClientExpress.Request({method:"get",fullPath:window.location.pathname,title:document.title,session:b.session,delegateToServer:function(){window.location.pathname=window.location.pathname}});history.replaceState(a,a.title,a.location());b.log("information","Listening");a=b.router.routes.get.concat(b.router.routes.post.concat(b.router.routes.put.concat(b.router.routes.del))).sortByName("path");ClientExpress.utils.forEach(a,function(a){b.log("information","Route registered:",a.method.toUpperCase().lpad(" "), a.path)})})}else this.log("information","Not supported on this browser")};var e=function(b){var a=b.request,f=this.router.match(a.method,a.path);f.resolved()?(this.log("information",200,a.method.toUpperCase().lpad(" "),a.path),a.attachRoute(f),b=new ClientExpress.Response(a,this),f.action(a,b)):(this.log("information",404,a.method.toUpperCase().lpad(" "),a.path),b.request.delegateToServer())},b=function(b){if(!b.request.isHistoryRequest&&!b.request.isRedirect)b=b.request,history.pushState(b, b.title,b.location())},f=function(b){var a=this.settings["view engine"]||"",f=(this.settings.views||"")+b.template;f.lastIndexOf(".")!=-1&&f.lastIndexOf(".")<=4&&(a=f.substr(f.lastIndexOf(".")-1,f.length),f=f.substr(0,f.lastIndexOf(".")-1));a=a||this.settings["view engine"]||"";a!=""&&(a="."+a,f+=a);b.target_element.innerHTML=this.templateEngines[a].compile(f,b.args);this.eventBroker.fire({type:"RequestProcessed",request:b.request,response:b.response,target_element:b.target_element,args:b.args||{}})}, h=function(b){b.target_element.innerHTML=b.content;this.eventBroker.fire({type:"RequestProcessed",request:b.request,response:b.response,target_element:b.target_element,args:{}})},i=function(b){this.log("information",302,"GET ",b.path);this.eventBroker.fire({type:"ProcessRequest",request:new ClientExpress.Request({method:"get",fullPath:b.path,title:"",isRedirect:!0,session:b.request.session,delegateToServer:function(){window.location.pathname=b.path}})});this.eventBroker.fire({type:"RequestProcessed", request:b.request,response:b.response,target_element:b.target_element,args:{}})};return a}(); ClientExpress.Route=function(){function c(a,c,b){if(a instanceof RegExp)return a;a=a.concat("/?").replace(/\/\(/g,"(?:/").replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g,function(b,a,g,d,k,j){c.push({name:d,optional:!!j});a=a||"";return""+(j?"":a)+"(?:"+(j?a:"")+(g||"")+(k||"([^/]+?)")+")"+(j||"")}).replace(/([\/.])/g,"\\$1").replace(/\*/g,"(.+)");return RegExp("^"+a+"$",b?"":"i")}var a=function(a,e,b,f,h){this.resolved=function(){return!0};this.method=a;this.path=e;this.action=b;this.base_path=f; this.params=[];this.regexp=c(e,this.keys=[],h.sensitive)};a.prototype.match=function(a){return this.regexp.exec(a)};return a}(); ClientExpress.Router=function(){var c=function(){this.routes={get:[],post:[],put:[],del:[]}};c.prototype.match=function(a,c){for(var e=this.routes[a].length,b=0;b<e;++b){var f=this.routes[a][b];if(captures=f.match(c)){keys=f.keys;f.params=[];e=1;for(b=captures.length;e<b;++e){var h=keys[e-1],i="string"==typeof captures[e]?decodeURIComponent(captures[e]):captures[e];h?f.params[h.name]=i:f.params.push(i)}return f}}return{resolved:function(){return!1}}};c.prototype.registerRoute=function(a,c,e,b){this.routes[a].push(new ClientExpress.Route(a, c,e,b,{sensitive:!1}))};return c}(); ClientExpress.EventBroker=function(){var c=function(a){this.server=a;this.eventListeners={}};c.prototype.addListener=function(a,c){typeof this.eventListeners[a]=="undefined"&&(this.eventListeners[a]=[]);this.eventListeners[a].push(c)};c.prototype.removeListener=function(a,c){if(this.eventListeners[a]instanceof Array){var e=this.eventListeners[a];e.forEach(function(b,a){b===c&&e.splice(a,1)})}};c.prototype.fire=function(a){typeof a=="string"&&(a={type:a});if(!a.target)a.target=this.server;if(!a.type)throw Error("Event object missing 'type' property."); a.type="on"+a.type;this.eventListeners[a.type]instanceof Array&&this.eventListeners[a.type].forEach(function(c){c.call(this.server,a)})};return c}(); ClientExpress.EventListener=function(){var c=function(){};c.prototype.registerEventHandlers=function(b){a(b);g(b);e(b)};var a=function(b){document.onclick=function(a){a=a||window.event;var c=a.target||a.srcElement;if(c.tagName.toLowerCase()=="a")return a=new ClientExpress.Request({method:"get",fullPath:c.href,title:c.title||"",session:b.session,delegateToServer:function(){c.href.indexOf("://")!=-1?window.location=c.href:window.location.pathname=c.href}}),b.eventBroker.fire({type:"ProcessRequest", request:a}),!1}},g=function(b){document.onsubmit=function(a){a=a||window.event;var c=a.target||a.srcElement;if(c.tagName.toLowerCase()=="form")return a=new ClientExpress.Request({method:c.method,fullPath:[c.action,ClientExpress.utils.serializeArray(c)].join("?"),title:c.title,session:b.session,delegateToServer:function(){c.submit()}}),b.eventBroker.fire({type:"ProcessRequest",request:a}),!1}},e=function(b){window.onpopstate=function(a){if(a.state)a=a.state,a.__proto__=ClientExpress.Request.prototype, a.HistoryRequest(),b.eventBroker.fire({type:"ProcessRequest",request:a})}};return c}(); ClientExpress.Request=function(){var c=function(a){var c=this;this.isHistoryRequest=!1;this.session=a.session;this.body={};this.title=a.title;this.params=[];this.base_path="";this.isRedirect=a.isRedirect||!1;(this.queryString=a.fullPath.split("?")[1])&&ClientExpress.utils.forEach(this.queryString.split("&"),function(a){var b=a.split("=")[0];a=a.split("=")[1];var f;if(f=/^(\w+)\[(\w+)\]/.exec(b)){var h=f[1];b=f[2];f=c.body[h]||{};f[b]=a;c.body[h]=f}else c.body[b]=a});this.method=(this.body._method|| a.method).toLowerCase();this.path=a.fullPath.replace(/\?.+$/,"").replace(window.location.protocol+"//"+window.location.host,"");this.delegateToServer=a.delegateToServer||function(){}};c.prototype.attachRoute=function(a){this.params=a.params;this.base_path=a.base_path};c.prototype.location=function(){return this.method==="get"?this.path:""};c.prototype.HistoryRequest=function(){this.isHistoryRequest=!0};return c}(); ClientExpress.Response=function(){var c=function(a,c){this.request=a;this.server=c;this.output=this.redirect_path="";this.title=a.title};c.prototype.send=function(a){this.server.eventBroker.fire({type:"Send",request:this.request,response:this,target_element:this.server.content_target_element,content:a})};c.prototype.render=function(a,c){this.server.eventBroker.fire({type:"Render",request:this.request,response:this,target_element:this.server.content_target_element,template:a,args:c})};c.prototype.redirect= function(a){this.server.eventBroker.fire({type:"Redirect",request:this.request,response:this,path:(a.substr(0,1)=="/"?this.request.base_path:"")+a})};return c}();ClientExpress.Logger=function(){var c=function(){};c.prototype.error=function(){window.console&&console.error(arguments[0].join(" "))};c.prototype.information=function(){window.console&&console.log(arguments[0].join(" "))};c.prototype.warning=function(){window.console&&console.warn(arguments[0].join(" "))};return c}(); String.prototype.rpad=function(c){return c.substr(0,c.length-this.length)+this};String.prototype.lpad=function(c){return this+c.substr(0,c.length-this.length)}; ClientExpress.utils=function(){var c=Array.prototype.every?function(b,a,c){return b.every(a,c)}:function(b,a,c){if(b===void 0||b===null)throw new TypeError;b=Object(b);var i=b.length>>>0;if(typeof a!=="function")throw new TypeError;for(var d=0;d<i;d++)if(d in b&&!a.call(c,b[d],d,b))return!1;return!0},a=Array.prototype.forEach?function(b,a,c){return b.forEach(a,c)}:function(b,a,c){if(b===void 0||b===null)throw new TypeError;b=Object(b);var i=b.length>>>0;if(typeof a!=="function")throw new TypeError; for(var d=0;d<i;d++)d in b&&a.call(c,b[d],d,b)},g=Array.prototype.filter?function(b,a,c){return b.filter(a,c)}:function(b,a,c){if(b===void 0||b===null)throw new TypeError;b=Object(b);var i=b.length>>>0;if(typeof a!=="function")throw new TypeError;for(var d=[],e=0;e<i;e++)if(e in b){var g=b[e];a.call(c,g,e,b)&&d.push(g)}return d},e=Array.prototype.map?function(b,a,c){return b.map(a,c)}:function(b,a,c){if(b===void 0||b===null)throw new TypeError;b=Object(b);var e=b.length>>>0;if(typeof a!=="function")throw new TypeError; for(var d=Array(e),g=0;g<e;g++)g in b&&(d[g]=a.call(c,b[g],g,b));return d};if(!Array.prototype.sortByName)Array.prototype.sortByName=function(b){if(this===void 0||this===null)throw new TypeError;if(typeof b!=="string")throw new TypeError;return this.sort(function(a,c){var e=a[b].toLowerCase(),d=c[b].toLowerCase();return e<d?-1:e>d?1:0})};return{every:c,forEach:a,filter:g,map:e,toArray:function(a,c){return Array.prototype.slice.call(a,c||0)},serializeArray:function(a){var c="";a=a.getElementsByTagName("*"); for(var e=0;e<a.length;e++){var g=a[e];if(!g.disabled&&g.name&&g.name.length>0)switch(g.tagName.toLowerCase()){case "input":switch(g.type){case "checkbox":case "radio":g.checked&&(c.length>0&&(c+="&"),c+=g.name+"="+encodeURIComponent(g.value));break;case "hidden":case "password":case "text":c.length>0&&(c+="&"),c+=g.name+"="+encodeURIComponent(g.value)}break;case "select":case "textarea":c.length>0&&(c+="&"),c+=g.name+"="+encodeURIComponent(g.value)}}return c},objectIterator:function(a,c){for(var e in a)callBackValue= {isFunction:a[e]instanceof Function,name:e,value:a[e]},c(callBackValue)}}}();
const R = require('ramda'); const {thread} = require('davis-shared').fp; const DataLoader = require('dataloader'); const Task = require('data.task'); const Async = require('control.async')(Task); const when = require('when'); const task2Promise = Async.toPromise(when.promise); module.exports = (entityRepository, entityTypes) => thread(entityTypes, R.map(entityType => ([ entityType, new DataLoader(ids => task2Promise( entityRepository.queryById(entityType, ids).map(entities => { const indexedEntities = R.indexBy(R.prop('id'), entities); return ids.map(R.propOr(null, R.__, indexedEntities)); })))])), R.fromPairs);
'use strict'; var spawn = require('child_process').spawn; var font2svg = require('../'); var fs = require('graceful-fs'); var noop = require('nop'); var rimraf = require('rimraf'); var test = require('tape'); var xml2js = require('xml2js'); var parseXML = xml2js.parseString; var fontPath = 'test/SourceHanSansJP-Normal.otf'; var fontBuffer = fs.readFileSync(fontPath); var pkg = require('../package.json'); rimraf.sync('test/tmp'); test('font2svg()', function(t) { t.plan(22); font2svg(fontBuffer, {include: 'Hello,☆世界★(^_^)b!'}, function(err, buf) { t.error(err, 'should create a font buffer when `include` option is a string.'); parseXML(buf.toString(), function(err, result) { t.error(err, 'should create a valid SVG buffer.'); var glyphs = result.svg.font[0].glyph; var unicodes = glyphs.map(function(glyph) { return glyph.$.unicode; }); t.deepEqual( unicodes, [ String.fromCharCode('57344'), '!', '(', ')', ',', 'H', '^', '_', 'b', 'e', 'l', 'o', '★', '☆', '世', '界' ], 'should create glyphs including private use area automatically.' ); t.strictEqual(glyphs[0].$.d, undefined, 'should place `.notdef` at the first glyph'); }); }); font2svg(fontBuffer, { include: ['\u0000', '\ufffe', '\uffff'], encoding: 'utf8' }, function(err, str) { t.error(err, 'should create a font buffer when `include` option is an array.'); parseXML(str, function(err, result) { t.error(err, 'should create a valid SVG string when the encoding is utf8.'); var glyphs = result.svg.font[0].glyph; t.equal(glyphs.length, 1, 'should ignore glyphs which are not included in CMap.'); }); }); font2svg(fontBuffer, {encoding: 'base64'}, function(err, str) { t.error(err, 'should create a font buffer even if `include` option is not specified.'); parseXML(new Buffer(str, 'base64').toString(), function(err, result) { t.error(err, 'should encode the result according to `encoding` option.'); t.equal( result.svg.font[0].glyph.length, 1, 'should create a SVG including at least one glyph.' ); }); }); font2svg(fontBuffer, null, function(err) { t.error(err, 'should not throw errors even if `include` option is falsy value.'); }); font2svg(fontBuffer, {include: 1}, function(err) { t.error(err, 'should not throw errors even if `include` option is not an array or a string.'); }); font2svg(fontBuffer, {include: 'a', maxBuffer: 1}, function(err) { t.equal(err.message, 'stdout maxBuffer exceeded.', 'should pass an error of child_process.'); }); font2svg(fontBuffer, { include: 'foo', fontFaceAttr: { 'font-weight': 'bold', 'underline-position': '-100' } }, function(err, buf) { t.error(err, 'should accept `fontFaceAttr` option.'); parseXML(buf.toString(), function(err, result) { t.error(err, 'should create a valid SVG buffer when `fontFaceAttr` option is enabled.'); var fontFace = result.svg.font[0]['font-face'][0]; t.equal( fontFace.$['font-weight'], 'bold', 'should change the property of the `font-face` element, using `fontFaceAttr` option.' ); t.equal( fontFace.$['underline-position'], '-100', 'should change the property of the `font-face` element, using `fontFaceAttr` option.' ); }); }); t.throws( font2svg.bind(null, new Buffer('foo'), noop), /out/, 'should throw an error when the buffer doesn\'t represent a font.' ); t.throws( font2svg.bind(null, 'foo', {include: 'a'}, noop), /is not a buffer/, 'should throw an error when the first argument is not a buffer.' ); t.throws( font2svg.bind(null, fontBuffer, {include: 'a'}, [noop]), /TypeError/, 'should throw a type error when the last argument is not a function.' ); t.throws( font2svg.bind(null, fontBuffer, {fontFaceAttr: 'bold'}, noop), /TypeError/, 'should throw a type error when the `fontFaceAttr` is not an object.' ); t.throws( font2svg.bind(null, fontBuffer, { fontFaceAttr: {foo: 'bar'} }, noop), /foo is not a valid attribute name/, 'should throw an error when the `fontFaceAttr` has an invalid property..' ); }); test('"font2svg" command inside a TTY context', function(t) { t.plan(20); var cmd = function(args) { var tmpCp = spawn('node', [pkg.bin].concat(args), { stdio: [process.stdin, null, null] }); tmpCp.stdout.setEncoding('utf8'); tmpCp.stderr.setEncoding('utf8'); return tmpCp; }; cmd([fontPath]) .stdout.on('data', function(data) { t.ok(/<\/svg>/.test(data), 'should print font data to stdout.'); }); cmd([fontPath, 'test/tmp/foo.svg']).on('close', function() { fs.exists('test/tmp/foo.svg', function(result) { t.ok(result, 'should create a font file.'); }); }); cmd([fontPath, '--include', 'abc']) .stdout.on('data', function(data) { t.ok(/<\/svg>/.test(data), 'should accept --include flag.'); }); cmd([fontPath, '--in', '123']) .stdout.on('data', function(data) { t.ok(/<\/svg>/.test(data), 'should use --in flag as an alias of --include.'); }); cmd([fontPath, '-i', 'あ']) .stdout.on('data', function(data) { t.ok(/<\/svg>/.test(data), 'should use -i flag as an alias of --include.'); }); cmd([fontPath, '-g', '亜']) .stdout.on('data', function(data) { t.ok(/<\/svg>/.test(data), 'should use -g flag as an alias of --include.'); }); cmd([fontPath, '--font-weight', 'bold']) .stdout.on('data', function(data) { t.ok( /font-weight="bold"/.test(data), 'should set the property of font-face element, using property name flag.' ); }); cmd(['--help']) .stdout.on('data', function(data) { t.ok(/Usage/.test(data), 'should print usage information with --help flag.'); }); cmd(['-h']) .stdout.on('data', function(data) { t.ok(/Usage/.test(data), 'should use -h flag as an alias of --help.'); }); cmd(['--version']) .stdout.on('data', function(data) { t.equal(data, pkg.version + '\n', 'should print version with --version flag.'); }); cmd(['-v']) .stdout.on('data', function(data) { t.equal(data, pkg.version + '\n', 'should use -v as an alias of --version.'); }); cmd([]) .stdout.on('data', function(data) { t.ok(/Usage/.test(data), 'should print usage information when it takes no arguments.'); }); var unsupportedErr = ''; cmd(['cli.js']) .on('close', function(code) { t.notEqual(code, 0, 'should fail when it cannot parse the input.'); t.ok( /Unsupported/.test(unsupportedErr), 'should print `Unsupported OpenType` error message to stderr.' ); }) .stderr.on('data', function(data) { unsupportedErr += data; }); var invalidAttrErr = ''; cmd([fontPath, '--font-eight', 'bold', '--font-smile']) .on('close', function(code) { t.notEqual(code, 0, 'should fail when it takes invalid flags.'); t.ok( /font-eight is not a valid attribute name/.test(invalidAttrErr), 'should print `invalid attribute` error message to stderr.' ); }) .stderr.on('data', function(data) { invalidAttrErr += data; }); var enoentErr = ''; cmd(['foo']) .on('close', function(code) { t.notEqual(code, 0, 'should fail when the file doesn\'t exist.'); t.ok(/ENOENT/.test(enoentErr), 'should print ENOENT error message to stderr.'); }) .stderr.on('data', function(data) { enoentErr += data; }); var eisdirErr = ''; cmd([fontPath, 'node_modules']) .on('close', function(code) { t.notEqual(code, 0, 'should fail when a directory exists in the destination path.'); t.ok(/EISDIR/.test(eisdirErr), 'should print EISDIR error message to stderr.'); }) .stderr.on('data', function(data) { eisdirErr += data; }); }); test('"font2svg" command outside a TTY context', function(t) { t.plan(4); var cmd = function(args) { var tmpCp = spawn('node', [pkg.bin].concat(args), { stdio: ['pipe', null, null] }); tmpCp.stdout.setEncoding('utf8'); tmpCp.stderr.setEncoding('utf8'); return tmpCp; }; var cp = cmd([]); cp.stdout.on('data', function(data) { t.ok(/<\/svg>/.test(data), 'should parse stdin and print SVG data.'); }); cp.stdin.end(fontBuffer); cmd(['test/tmp/bar.svg', '--include', 'ア']) .on('close', function() { fs.exists('test/tmp/bar.svg', function(result) { t.ok(result, 'should write a SVG file.'); }); }) .stdin.end(fontBuffer); var err = ''; var cpErr = cmd([]); cpErr.on('close', function(code) { t.notEqual(code, 0, 'should fail when stdin receives unsupported file buffer.'); t.ok( /Unsupported/.test(err), 'should print an error when stdin receives unsupported file buffer.' ); }); cpErr.stderr.on('data', function(output) { err += output; }); cpErr.stdin.end(new Buffer('invalid data')); });
'use strict'; var should = require('should'), request = require('supertest'), app = require('../../server'), mongoose = require('mongoose'), User = mongoose.model('User'), Rawrecords3 = mongoose.model('Rawrecords3'), agent = request.agent(app); /** * Globals */ var credentials, user, rawrecords3; /** * Rawrecords3 routes tests */ describe('Rawrecords3 CRUD tests', function() { beforeEach(function(done) { // Create user credentials credentials = { username: 'username', password: 'password' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: '[email protected]', username: credentials.username, password: credentials.password, provider: 'local' }); // Save a user to the test db and create new Rawrecords3 user.save(function() { rawrecords3 = { name: 'Rawrecords3 Name' }; done(); }); }); it('should be able to save Rawrecords3 instance if logged in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Rawrecords3 agent.post('/rawrecords3s') .send(rawrecords3) .expect(200) .end(function(rawrecords3SaveErr, rawrecords3SaveRes) { // Handle Rawrecords3 save error if (rawrecords3SaveErr) done(rawrecords3SaveErr); // Get a list of Rawrecords3s agent.get('/rawrecords3s') .end(function(rawrecords3sGetErr, rawrecords3sGetRes) { // Handle Rawrecords3 save error if (rawrecords3sGetErr) done(rawrecords3sGetErr); // Get Rawrecords3s list var rawrecords3s = rawrecords3sGetRes.body; // Set assertions (rawrecords3s[0].user._id).should.equal(userId); (rawrecords3s[0].name).should.match('Rawrecords3 Name'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save Rawrecords3 instance if not logged in', function(done) { agent.post('/rawrecords3s') .send(rawrecords3) .expect(401) .end(function(rawrecords3SaveErr, rawrecords3SaveRes) { // Call the assertion callback done(rawrecords3SaveErr); }); }); it('should not be able to save Rawrecords3 instance if no name is provided', function(done) { // Invalidate name field rawrecords3.name = ''; agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Rawrecords3 agent.post('/rawrecords3s') .send(rawrecords3) .expect(400) .end(function(rawrecords3SaveErr, rawrecords3SaveRes) { // Set message assertion (rawrecords3SaveRes.body.message).should.match('Please fill Rawrecords3 name'); // Handle Rawrecords3 save error done(rawrecords3SaveErr); }); }); }); it('should be able to update Rawrecords3 instance if signed in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Rawrecords3 agent.post('/rawrecords3s') .send(rawrecords3) .expect(200) .end(function(rawrecords3SaveErr, rawrecords3SaveRes) { // Handle Rawrecords3 save error if (rawrecords3SaveErr) done(rawrecords3SaveErr); // Update Rawrecords3 name rawrecords3.name = 'WHY YOU GOTTA BE SO MEAN?'; // Update existing Rawrecords3 agent.put('/rawrecords3s/' + rawrecords3SaveRes.body._id) .send(rawrecords3) .expect(200) .end(function(rawrecords3UpdateErr, rawrecords3UpdateRes) { // Handle Rawrecords3 update error if (rawrecords3UpdateErr) done(rawrecords3UpdateErr); // Set assertions (rawrecords3UpdateRes.body._id).should.equal(rawrecords3SaveRes.body._id); (rawrecords3UpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of Rawrecords3s if not signed in', function(done) { // Create new Rawrecords3 model instance var rawrecords3Obj = new Rawrecords3(rawrecords3); // Save the Rawrecords3 rawrecords3Obj.save(function() { // Request Rawrecords3s request(app).get('/rawrecords3s') .end(function(req, res) { // Set assertion res.body.should.be.an.Array.with.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single Rawrecords3 if not signed in', function(done) { // Create new Rawrecords3 model instance var rawrecords3Obj = new Rawrecords3(rawrecords3); // Save the Rawrecords3 rawrecords3Obj.save(function() { request(app).get('/rawrecords3s/' + rawrecords3Obj._id) .end(function(req, res) { // Set assertion res.body.should.be.an.Object.with.property('name', rawrecords3.name); // Call the assertion callback done(); }); }); }); it('should be able to delete Rawrecords3 instance if signed in', function(done) { agent.post('/auth/signin') .send(credentials) .expect(200) .end(function(signinErr, signinRes) { // Handle signin error if (signinErr) done(signinErr); // Get the userId var userId = user.id; // Save a new Rawrecords3 agent.post('/rawrecords3s') .send(rawrecords3) .expect(200) .end(function(rawrecords3SaveErr, rawrecords3SaveRes) { // Handle Rawrecords3 save error if (rawrecords3SaveErr) done(rawrecords3SaveErr); // Delete existing Rawrecords3 agent.delete('/rawrecords3s/' + rawrecords3SaveRes.body._id) .send(rawrecords3) .expect(200) .end(function(rawrecords3DeleteErr, rawrecords3DeleteRes) { // Handle Rawrecords3 error error if (rawrecords3DeleteErr) done(rawrecords3DeleteErr); // Set assertions (rawrecords3DeleteRes.body._id).should.equal(rawrecords3SaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete Rawrecords3 instance if not signed in', function(done) { // Set Rawrecords3 user rawrecords3.user = user; // Create new Rawrecords3 model instance var rawrecords3Obj = new Rawrecords3(rawrecords3); // Save the Rawrecords3 rawrecords3Obj.save(function() { // Try deleting Rawrecords3 request(app).delete('/rawrecords3s/' + rawrecords3Obj._id) .expect(401) .end(function(rawrecords3DeleteErr, rawrecords3DeleteRes) { // Set message assertion (rawrecords3DeleteRes.body.message).should.match('User is not logged in'); // Handle Rawrecords3 error error done(rawrecords3DeleteErr); }); }); }); afterEach(function(done) { User.remove().exec(); Rawrecords3.remove().exec(); done(); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:b63ef97b9f85b0d4a07926b186083c9952568e26bbb65d610b592d15208f79a9 size 24953
/* globals Promise:true */ var _ = require('lodash') var EventEmitter = require('events').EventEmitter var inherits = require('util').inherits var LRU = require('lru-cache') var Promise = require('bluebird') var Snapshot = require('./snapshot') var errors = require('../errors') var util = require('../util') /** * @event Blockchain#error * @param {Error} error */ /** * @event Blockchain#syncStart */ /** * @event Blockchain#syncStop */ /** * @event Blockchain#newBlock * @param {string} hash * @param {number} height */ /** * @event Blockchain#touchAddress * @param {string} address */ /** * @class Blockchain * @extends events.EventEmitter * * @param {Connector} connector * @param {Object} [opts] * @param {string} [opts.networkName=livenet] * @param {number} [opts.txCacheSize=100] */ function Blockchain (connector, opts) { var self = this EventEmitter.call(self) opts = _.extend({ networkName: 'livenet', txCacheSize: 100 }, opts) self.connector = connector self.networkName = opts.networkName self.latest = {hash: util.zfill('', 64), height: -1} self._txCache = LRU({max: opts.txCacheSize, allowSlate: true}) self._isSyncing = false self.on('syncStart', function () { self._isSyncing = true }) self.on('syncStop', function () { self._isSyncing = false }) } inherits(Blockchain, EventEmitter) Blockchain.prototype._syncStart = function () { if (!this.isSyncing()) this.emit('syncStart') } Blockchain.prototype._syncStop = function () { if (this.isSyncing()) this.emit('syncStop') } /** * @param {errors.Connector} err * @throws {errors.Connector} */ Blockchain.prototype._rethrow = function (err) { var nerr switch (err.name) { case 'ErrorBlockchainJSConnectorHeaderNotFound': nerr = new errors.Blockchain.HeaderNotFound() break case 'ErrorBlockchainJSConnectorTxNotFound': nerr = new errors.Blockchain.TxNotFound() break case 'ErrorBlockchainJSConnectorTxSendError': nerr = new errors.Blockchain.TxSendError() break default: nerr = err break } nerr.message = err.message throw nerr } /** * Return current syncing status * * @return {boolean} */ Blockchain.prototype.isSyncing = function () { return this._isSyncing } /** * @return {Promise<Snapshot>} */ Blockchain.prototype.getSnapshot = function () { return Promise.resolve(new Snapshot(this)) } /** * @abstract * @param {(number|string)} id height or hash * @return {Promise<Connector~HeaderObject>} */ Blockchain.prototype.getHeader = function () { return Promise.reject(new errors.NotImplemented('Blockchain.getHeader')) } /** * @abstract * @param {string} txid * @return {Promise<string>} */ Blockchain.prototype.getTx = function () { return Promise.reject(new errors.NotImplemented('Blockchain.getTx')) } /** * @typedef {Object} Blockchain~TxBlockHashObject * @property {string} source `blocks` or `mempool` * @property {Object} [block] defined only when source is blocks * @property {string} data.hash * @property {number} data.height */ /** * @abstract * @param {string} txid * @return {Promise<Blockchain~TxBlockHashObject>} */ Blockchain.prototype.getTxBlockHash = function () { return Promise.reject(new errors.NotImplemented('Blockchain.getTxBlockHash')) } /** * @abstract * @param {string} rawtx * @return {Promise<string>} */ Blockchain.prototype.sendTx = function () { return Promise.reject(new errors.NotImplemented('Blockchain.sendTx')) } /** * @abstract * @param {string[]} addresses * @param {Object} [opts] * @param {string} [opts.source] `blocks` or `mempool` * @param {(string|number)} [opts.from] `hash` or `height` * @param {(string|number)} [opts.to] `hash` or `height` * @param {string} [opts.status] * @return {Promise<Connector~AddressesQueryObject>} */ Blockchain.prototype.addressesQuery = function () { return Promise.reject(new errors.NotImplemented('Blockchain.addressesQuery')) } /** * @abstract * @param {string} address * @return {Promise} */ Blockchain.prototype.subscribeAddress = function () { return Promise.reject(new errors.NotImplemented('Blockchain.subscribeAddress')) } module.exports = Blockchain
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { StyleSheet, css } from 'aphrodite'; import { changeTimeSignature } from '../../actions/track'; import HoverableText from './HoverableText'; const styles = StyleSheet.create({ text: { fontFamily: 'Optima, Segoe, Segoe UI, Candara, Calibri, Arial, sans-serif' }, popoverContainer: { background: '#FEFBF7', height: 200, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }, templateRow: { display: 'flex', justifyContent: 'space-around', paddingTop: 10 }, timeSigRow: { display: 'flex', justifyContent: 'center', flexShrink: 10 }, checkboxRow: { display: 'flex', justifyContent: 'space-around', paddingBottom: 10, paddingLeft: 5, paddingRight: 5 }, beats: { display: 'flex', flexDirection: 'column', justifyContent: 'center', paddingTop: 15, alignItems: 'flex-end', flexBasis: '55%' }, beatType: { display: 'flex', flexDirection: 'column', justifyContent: 'center', paddingBottom: 15, alignItems: 'flex-end', flexBasis: '55%' }, numberText: { fontSize: 40, paddingRight: 10 }, topArrows: { display: 'flex', flexDirection: 'column', justifyContent: 'center', paddingTop: 15, flexBasis: '45%' }, bottomArrows: { display: 'flex', flexDirection: 'column', justifyContent: 'center', paddingBottom: 15, flexBasis: '45%' }, checkboxText: { fontWeight: 300, fontSize: 12, paddingTop: 3 } }); class TimeSignaturePopover extends Component { constructor(props) { super(props); this.state = { timeSignature: Object.assign({}, props.timeSignature), toEndChecked: false, allChecked: false }; } componentWillUnmount() { const { timeSignature, toEndChecked, allChecked } = this.state; this.props.changeTimeSignature( { measureIndex: this.props.measureIndex }, timeSignature, toEndChecked, allChecked ); } onTwoFourClick = () => { // TODO extract these things into a component this.setState({ timeSignature: { beats: 2, beatType: 4 } }); }; onFourFourClick = () => { this.setState({ timeSignature: { beats: 4, beatType: 4 } }); }; onSixEightClick = () => { this.setState({ timeSignature: { beats: 6, beatType: 8 } }); }; onIncrementBeats = () => { if (this.state.timeSignature.beats < 32) { this.setState({ timeSignature: { beats: this.state.timeSignature.beats + 1, beatType: this.state.timeSignature.beatType } }); } }; onIncrementBeatType = () => { if (this.state.timeSignature.beatType < 32) { this.setState({ timeSignature: { beats: this.state.timeSignature.beats, beatType: this.state.timeSignature.beatType * 2 } }); } }; onDecrementBeats = () => { if (this.state.timeSignature.beats > 1) { this.setState({ timeSignature: { beats: this.state.timeSignature.beats - 1, beatType: this.state.timeSignature.beatType } }); } }; onDecrementBeatType = () => { if (this.state.timeSignature.beatType > 1) { this.setState({ timeSignature: { beats: this.state.timeSignature.beats, beatType: this.state.timeSignature.beatType / 2 } }); } }; toEndChanged = () => { this.setState({ toEndChecked: !this.state.toEndChecked }); }; allChanged = () => { this.setState({ allChecked: !this.state.allChecked }); }; render() { return ( <div className={css(styles.popoverContainer)}> <span className={css(styles.templateRow)}> <HoverableText onClick={this.onTwoFourClick} text="2/4" /> <HoverableText onClick={this.onFourFourClick} text="4/4" /> <HoverableText onClick={this.onSixEightClick} text="6/8" /> </span> <div className={css(styles.timeSigRow)}> <span className={css(styles.beats)}> <h3 className={css(styles.text, styles.numberText)}> {this.state.timeSignature.beats} </h3> </span> <span className={css(styles.topArrows)}> <HoverableText onClick={this.onIncrementBeats} text="▲" /> <HoverableText onClick={this.onDecrementBeats} text="▼" /> </span> </div> <div className={css(styles.timeSigRow)}> <span className={css(styles.beatType)}> <h3 className={css(styles.text, styles.numberText)}> {this.state.timeSignature.beatType} </h3> </span> <span className={css(styles.bottomArrows)}> <HoverableText onClick={this.onIncrementBeatType} text="▲" /> <HoverableText onClick={this.onDecrementBeatType} text="▼" /> </span> </div> <span className={css(styles.checkboxRow)}> <small className={css(styles.text, styles.checkboxText)}> To End </small> <input type="checkbox" value={this.state.toEndChecked} onChange={this.toEndChanged} /> <small className={css(styles.text, styles.checkboxText)}> All Measures </small> <input type="checkbox" value={this.state.allChecked} onChange={this.allChanged} /> </span> </div> ); } } export default connect(null, { changeTimeSignature })(TimeSignaturePopover);
import webpack from 'webpack'; import webpackConfig from '../webpack.config.js'; async function build() { return new Promise((resolve, reject) => { webpack(webpackConfig[1]).run((errServer, serverStats) => { if (errServer) reject(errServer); console.log(serverStats.toString(webpackConfig[1].stats)); webpack(webpackConfig[0]).run((errClient, clientStats) => { if (errClient) reject(errClient); console.log(clientStats.toString(webpackConfig[0].stats)); resolve(); }); }); }); } export default build;
export default from './unview.container'
// jslint.js // 2009-03-28 // TO DO: In ADsafe, make lib run only. /* Copyright (c) 2002 Douglas Crockford (www.JSLint.com) 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 shall be used for Good, not Evil. 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. */ /* JSLINT is a global function. It takes two parameters. var myResult = JSLINT(source, option); The first parameter is either a string or an array of strings. If it is a string, it will be split on '\n' or '\r'. If it is an array of strings, it is assumed that each string represents one line. The source can be a JavaScript text, or HTML text, or a Konfabulator text. The second parameter is an optional object of options which control the operation of JSLINT. Most of the options are booleans: They are all are optional and have a default value of false. If it checks out, JSLINT returns true. Otherwise, it returns false. If false, you can inspect JSLINT.errors to find out the problems. JSLINT.errors is an array of objects containing these members: { line : The line (relative to 0) at which the lint was found character : The character (relative to 0) at which the lint was found reason : The problem evidence : The text line in which the problem occurred raw : The raw message before the details were inserted a : The first detail b : The second detail c : The third detail d : The fourth detail } If a fatal error was found, a null will be the last element of the JSLINT.errors array. You can request a Function Report, which shows all of the functions and the parameters and vars that they use. This can be used to find implied global variables and other problems. The report is in HTML and can be inserted in an HTML <body>. var myReport = JSLINT.report(limited); If limited is true, then the report will be limited to only errors. */ /*jslint evil: true, nomen: false, onevar: false, regexp: false , strict: true */ /*global JSLINT*/ /*members "\b", "\t", "\n", "\f", "\r", "\"", "%", "(begin)", "(breakage)", "(context)", "(error)", "(global)", "(identifier)", "(line)", "(loopage)", "(name)", "(onevar)", "(params)", "(scope)", "(verb)", ")", "++", "--", "\/", ADSAFE, Array, Boolean, COM, Canvas, CustomAnimation, Date, Debug, E, Error, EvalError, FadeAnimation, Flash, FormField, Frame, Function, HotKey, Image, JSON, LN10, LN2, LOG10E, LOG2E, MAX_VALUE, MIN_VALUE, Math, MenuItem, MoveAnimation, NEGATIVE_INFINITY, Number, Object, Option, PI, POSITIVE_INFINITY, Point, RangeError, Rectangle, ReferenceError, RegExp, ResizeAnimation, RotateAnimation, SQRT1_2, SQRT2, ScrollBar, String, Style, SyntaxError, System, Text, TextArea, Timer, TypeError, URIError, URL, Web, Window, XMLDOM, XMLHttpRequest, "\\", "]", a, abbr, acronym, active, address, adsafe, after, alert, aliceblue, animator, antiquewhite, appleScript, applet, apply, approved, aqua, aquamarine, area, arguments, arity, autocomplete, azure, b, background, "background-attachment", "background-color", "background-image", "background-position", "background-repeat", base, bdo, beep, before, beige, big, bisque, bitwise, black, blanchedalmond, block, blockquote, blue, blueviolet, blur, body, border, "border-bottom", "border-bottom-color", "border-bottom-style", "border-bottom-width", "border-collapse", "border-color", "border-left", "border-left-color", "border-left-style", "border-left-width", "border-right", "border-right-color", "border-right-style", "border-right-width", "border-spacing", "border-style", "border-top", "border-top-color", "border-top-style", "border-top-width", "border-width", bottom, br, brown, browser, burlywood, button, bytesToUIString, c, cadetblue, call, callee, caller, canvas, cap, caption, "caption-side", cases, center, charAt, charCodeAt, character, chartreuse, chocolate, chooseColor, chooseFile, chooseFolder, cite, clear, clearInterval, clearTimeout, clip, close, closeWidget, closed, cm, code, col, colgroup, color, comment, condition, confirm, console, constructor, content, convertPathToHFS, convertPathToPlatform, coral, cornflowerblue, cornsilk, "counter-increment", "counter-reset", create, crimson, css, cursor, cyan, d, darkblue, darkcyan, darkgoldenrod, darkgray, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkturquoise, darkviolet, dd, debug, decodeURI, decodeURIComponent, deeppink, deepskyblue, defaultStatus, defineClass, del, deserialize, dfn, dimgray, dir, direction, display, div, dl, document, dodgerblue, dt, else, em, embed, empty, "empty-cells", encodeURI, encodeURIComponent, entityify, eqeqeq, errors, escape, eval, event, evidence, evil, ex, exec, exps, fieldset, filesystem, firebrick, first, "first-child", "first-letter", "first-line", float, floor, floralwhite, focus, focusWidget, font, "font-face", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", forestgreen, forin, form, fragment, frame, frames, frameset, from, fromCharCode, fuchsia, fud, funct, function, g, gainsboro, gc, getComputedStyle, ghostwhite, gold, goldenrod, gray, green, greenyellow, h1, h2, h3, h4, h5, h6, hasOwnProperty, head, height, help, history, honeydew, hotpink, hover, hr, html, i, iTunes, id, identifier, iframe, img, immed, import, in, include, indent, indexOf, indianred, indigo, init, input, ins, isAlpha, isApplicationRunning, isDigit, isFinite, isNaN, ivory, join, kbd, khaki, konfabulatorVersion, label, labelled, lang, lavender, lavenderblush, lawngreen, laxbreak, lbp, led, left, legend, lemonchiffon, length, "letter-spacing", li, lib, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightsteelblue, lightyellow, lime, limegreen, line, "line-height", linen, link, "list-style", "list-style-image", "list-style-position", "list-style-type", load, loadClass, location, log, m, magenta, map, margin, "margin-bottom", "margin-left", "margin-right", "margin-top", "marker-offset", maroon, match, "max-height", "max-width", md5, media, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, menu, message, meta, midnightblue, "min-height", "min-width", mintcream, mistyrose, mm, moccasin, moveBy, moveTo, name, navajowhite, navigator, navy, new, newcap, noframes, nomen, noscript, nud, object, ol, oldlace, olive, olivedrab, on, onblur, onerror, onevar, onfocus, onload, onresize, onunload, opacity, open, openURL, opener, opera, optgroup, option, orange, orangered, orchid, outer, outline, "outline-color", "outline-style", "outline-width", overflow, p, padding, "padding-bottom", "padding-left", "padding-right", "padding-top", page, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, param, parent, parseFloat, parseInt, passfail, pc, peachpuff, peru, pink, play, plum, plusplus, pop, popupMenu, position, powderblue, pre, predef, preferenceGroups, preferences, print, prompt, prototype, pt, purple, push, px, q, quit, quotes, random, range, raw, reach, readFile, readUrl, reason, red, regexp, reloadWidget, replace, report, reserved, resizeBy, resizeTo, resolvePath, resumeUpdates, rhino, right, rosybrown, royalblue, runCommand, runCommandInBg, saddlebrown, safe, salmon, samp, sandybrown, saveAs, savePreferences, screen, script, scroll, scrollBy, scrollTo, seagreen, seal, search, seashell, select, self, serialize, setInterval, setTimeout, shift, showWidgetPreferences, sidebar, sienna, silver, skyblue, slateblue, slategray, sleep, slice, small, snow, sort, span, spawn, speak, split, springgreen, src, status, steelblue, strict, strong, style, styleproperty, sub, substr, sup, supplant, suppressUpdates, sync, system, table, "table-layout", tan, tbody, td, teal, tellWidget, test, "text-align", "text-decoration", "text-indent", "text-shadow", "text-transform", textarea, tfoot, th, thead, thistle, title, toLowerCase, toString, toUpperCase, toint32, token, tomato, top, tr, tt, turquoise, type, u, ul, undef, unescape, "unicode-bidi", unwatch, updateNow, value, valueOf, var, version, "vertical-align", violet, visibility, visited, watch, wheat, white, "white-space", whitesmoke, widget, width, window, "word-spacing", yahooCheckLogin, yahooLogin, yahooLogout, yellow, yellowgreen, "z-index" */ // We build the application inside a function so that we produce only a single // global variable. The function will be invoked, its return value is the JSLINT // application itself. "use strict"; JSLINT = (function () { var adsafe_id, // The widget's ADsafe id. adsafe_may, // The widget may load approved scripts. adsafe_went, // ADSAFE.go has been called. anonname, // The guessed name for anonymous functions. approved, // ADsafe approved urls. atrule = { 'import' : true, media : true, 'font-face': true, page : true }, badbreak = { ')': true, ']': true, '++': true, '--': true }, // These are members that should not be permitted in third party ads. banned = { // the member names that ADsafe prohibits. apply : true, 'arguments' : true, call : true, callee : true, caller : true, constructor : true, 'eval' : true, prototype : true, unwatch : true, valueOf : true, watch : true }, // These are the JSLint boolean options. boolOptions = { adsafe : true, // if ADsafe should be enforced bitwise : true, // if bitwise operators should not be allowed browser : true, // if the standard browser globals should be predefined cap : true, // if upper case HTML should be allowed css : true, // if CSS workarounds should be tolerated debug : true, // if debugger statements should be allowed eqeqeq : true, // if === should be required evil : true, // if eval should be allowed forin : true, // if for in statements must filter fragment : true, // if HTML fragments should be allowed immed : true, // if immediate invocations must be wrapped in parens laxbreak : true, // if line breaks should not be checked newcap : true, // if constructor names must be capitalized nomen : true, // if names should be checked on : true, // if HTML event handlers should be allowed onevar : true, // if only one var statement per function should be allowed passfail : true, // if the scan should stop on first error plusplus : true, // if increment/decrement should not be allowed regexp : true, // if the . should not be allowed in regexp literals rhino : true, // if the Rhino environment globals should be predefined undef : true, // if variables should be declared before used safe : true, // if use of some browser features should be restricted sidebar : true, // if the System object should be predefined strict : true, // require the "use strict"; pragma sub : true, // if all forms of subscript notation are tolerated white : true, // if strict whitespace rules apply widget : true // if the Yahoo Widgets globals should be predefined }, // browser contains a set of global names which are commonly provided by a // web browser environment. browser = { alert : true, blur : true, clearInterval : true, clearTimeout : true, close : true, closed : true, confirm : true, console : true, Debug : true, defaultStatus : true, document : true, event : true, focus : true, frames : true, getComputedStyle: true, history : true, Image : true, length : true, location : true, moveBy : true, moveTo : true, name : true, navigator : true, onblur : true, onerror : true, onfocus : true, onload : true, onresize : true, onunload : true, open : true, opener : true, opera : true, Option : true, parent : true, print : true, prompt : true, resizeBy : true, resizeTo : true, screen : true, scroll : true, scrollBy : true, scrollTo : true, self : true, setInterval : true, setTimeout : true, status : true, top : true, window : true, XMLHttpRequest : true }, cssAttributeData, cssAny, cssColorData = { "aliceblue": true, "antiquewhite": true, "aqua": true, "aquamarine": true, "azure": true, "beige": true, "bisque": true, "black": true, "blanchedalmond": true, "blue": true, "blueviolet": true, "brown": true, "burlywood": true, "cadetblue": true, "chartreuse": true, "chocolate": true, "coral": true, "cornflowerblue": true, "cornsilk": true, "crimson": true, "cyan": true, "darkblue": true, "darkcyan": true, "darkgoldenrod": true, "darkgray": true, "darkgreen": true, "darkkhaki": true, "darkmagenta": true, "darkolivegreen": true, "darkorange": true, "darkorchid": true, "darkred": true, "darksalmon": true, "darkseagreen": true, "darkslateblue": true, "darkslategray": true, "darkturquoise": true, "darkviolet": true, "deeppink": true, "deepskyblue": true, "dimgray": true, "dodgerblue": true, "firebrick": true, "floralwhite": true, "forestgreen": true, "fuchsia": true, "gainsboro": true, "ghostwhite": true, "gold": true, "goldenrod": true, "gray": true, "green": true, "greenyellow": true, "honeydew": true, "hotpink": true, "indianred": true, "indigo": true, "ivory": true, "khaki": true, "lavender": true, "lavenderblush": true, "lawngreen": true, "lemonchiffon": true, "lightblue": true, "lightcoral": true, "lightcyan": true, "lightgoldenrodyellow": true, "lightgreen": true, "lightpink": true, "lightsalmon": true, "lightseagreen": true, "lightskyblue": true, "lightslategray": true, "lightsteelblue": true, "lightyellow": true, "lime": true, "limegreen": true, "linen": true, "magenta": true, "maroon": true, "mediumaquamarine": true, "mediumblue": true, "mediumorchid": true, "mediumpurple": true, "mediumseagreen": true, "mediumslateblue": true, "mediumspringgreen": true, "mediumturquoise": true, "mediumvioletred": true, "midnightblue": true, "mintcream": true, "mistyrose": true, "moccasin": true, "navajowhite": true, "navy": true, "oldlace": true, "olive": true, "olivedrab": true, "orange": true, "orangered": true, "orchid": true, "palegoldenrod": true, "palegreen": true, "paleturquoise": true, "palevioletred": true, "papayawhip": true, "peachpuff": true, "peru": true, "pink": true, "plum": true, "powderblue": true, "purple": true, "red": true, "rosybrown": true, "royalblue": true, "saddlebrown": true, "salmon": true, "sandybrown": true, "seagreen": true, "seashell": true, "sienna": true, "silver": true, "skyblue": true, "slateblue": true, "slategray": true, "snow": true, "springgreen": true, "steelblue": true, "tan": true, "teal": true, "thistle": true, "tomato": true, "turquoise": true, "violet": true, "wheat": true, "white": true, "whitesmoke": true, "yellow": true, "yellowgreen": true }, cssBorderStyle, cssLengthData = { '%': true, 'cm': true, 'em': true, 'ex': true, 'in': true, 'mm': true, 'pc': true, 'pt': true, 'px': true }, escapes = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '/' : '\\/', '\\': '\\\\' }, funct, // The current function functions, // All of the functions global, // The global scope htmltag = { a: {}, abbr: {}, acronym: {}, address: {}, applet: {}, area: {empty: true, parent: ' map '}, b: {}, base: {empty: true, parent: ' head '}, bdo: {}, big: {}, blockquote: {}, body: {parent: ' html noframes '}, br: {empty: true}, button: {}, canvas: {parent: ' body p div th td '}, caption: {parent: ' table '}, center: {}, cite: {}, code: {}, col: {empty: true, parent: ' table colgroup '}, colgroup: {parent: ' table '}, dd: {parent: ' dl '}, del: {}, dfn: {}, dir: {}, div: {}, dl: {}, dt: {parent: ' dl '}, em: {}, embed: {}, fieldset: {}, font: {}, form: {}, frame: {empty: true, parent: ' frameset '}, frameset: {parent: ' html frameset '}, h1: {}, h2: {}, h3: {}, h4: {}, h5: {}, h6: {}, head: {parent: ' html '}, html: {parent: '*'}, hr: {empty: true}, i: {}, iframe: {}, img: {empty: true}, input: {empty: true}, ins: {}, kbd: {}, label: {}, legend: {parent: ' fieldset '}, li: {parent: ' dir menu ol ul '}, link: {empty: true, parent: ' head '}, map: {}, menu: {}, meta: {empty: true, parent: ' head noframes noscript '}, noframes: {parent: ' html body '}, noscript: {parent: ' body head noframes '}, object: {}, ol: {}, optgroup: {parent: ' select '}, option: {parent: ' optgroup select '}, p: {}, param: {empty: true, parent: ' applet object '}, pre: {}, q: {}, samp: {}, script: {empty: true, parent: ' body div frame head iframe p pre span '}, select: {}, small: {}, span: {}, strong: {}, style: {parent: ' head ', empty: true}, sub: {}, sup: {}, table: {}, tbody: {parent: ' table '}, td: {parent: ' tr '}, textarea: {}, tfoot: {parent: ' table '}, th: {parent: ' tr '}, thead: {parent: ' table '}, title: {parent: ' head '}, tr: {parent: ' table tbody thead tfoot '}, tt: {}, u: {}, ul: {}, 'var': {} }, ids, // HTML ids implied, // Implied globals inblock, indent, jsonmode, lines, lookahead, member, membersOnly, nexttoken, noreach, option, predefined, // Global variables defined by option prereg, prevtoken, pseudorule = { 'first-child': true, link : true, visited : true, hover : true, active : true, focus : true, lang : true, 'first-letter' : true, 'first-line' : true, before : true, after : true }, rhino = { defineClass : true, deserialize : true, gc : true, help : true, load : true, loadClass : true, print : true, quit : true, readFile : true, readUrl : true, runCommand : true, seal : true, serialize : true, spawn : true, sync : true, toint32 : true, version : true }, scope, // The current scope sidebar = { System : true }, src, stack, // standard contains the global names that are provided by the // ECMAScript standard. standard = { Array : true, Boolean : true, Date : true, decodeURI : true, decodeURIComponent : true, encodeURI : true, encodeURIComponent : true, Error : true, 'eval' : true, EvalError : true, Function : true, isFinite : true, isNaN : true, JSON : true, Math : true, Number : true, Object : true, parseInt : true, parseFloat : true, RangeError : true, ReferenceError : true, RegExp : true, String : true, SyntaxError : true, TypeError : true, URIError : true }, standard_member = { E : true, LN2 : true, LN10 : true, LOG2E : true, LOG10E : true, PI : true, SQRT1_2 : true, SQRT2 : true, MAX_VALUE : true, MIN_VALUE : true, NEGATIVE_INFINITY : true, POSITIVE_INFINITY : true }, syntax = {}, tab, token, urls, warnings, // widget contains the global names which are provided to a Yahoo // (fna Konfabulator) widget. widget = { alert : true, animator : true, appleScript : true, beep : true, bytesToUIString : true, Canvas : true, chooseColor : true, chooseFile : true, chooseFolder : true, closeWidget : true, COM : true, convertPathToHFS : true, convertPathToPlatform : true, CustomAnimation : true, escape : true, FadeAnimation : true, filesystem : true, Flash : true, focusWidget : true, form : true, FormField : true, Frame : true, HotKey : true, Image : true, include : true, isApplicationRunning : true, iTunes : true, konfabulatorVersion : true, log : true, md5 : true, MenuItem : true, MoveAnimation : true, openURL : true, play : true, Point : true, popupMenu : true, preferenceGroups : true, preferences : true, print : true, prompt : true, random : true, Rectangle : true, reloadWidget : true, ResizeAnimation : true, resolvePath : true, resumeUpdates : true, RotateAnimation : true, runCommand : true, runCommandInBg : true, saveAs : true, savePreferences : true, screen : true, ScrollBar : true, showWidgetPreferences : true, sleep : true, speak : true, Style : true, suppressUpdates : true, system : true, tellWidget : true, Text : true, TextArea : true, Timer : true, unescape : true, updateNow : true, URL : true, Web : true, widget : true, Window : true, XMLDOM : true, XMLHttpRequest : true, yahooCheckLogin : true, yahooLogin : true, yahooLogout : true }, // xmode is used to adapt to the exceptions in html parsing. // It can have these states: // false .js script file // html // outer // script // style // scriptstring // styleproperty xmode, xquote, // unsafe comment or string ax = /@cc|<\/?|script|\]*s\]|<\s*!|&lt/i, // unsafe characters that are silently deleted by one or more browsers cx = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/, // token tx = /^\s*([(){}\[.,:;'"~\?\]#@]|==?=?|\/(\*(global|extern|jslint|member|members)?|=|\/)?|\*[\/=]?|\+[+=]?|-[\-=]?|%=?|&[&=]?|\|[|=]?|>>?>?=?|<([\/=!]|\!(\[|--)?|<=?)?|\^=?|\!=?=?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+([xX][0-9a-fA-F]+|\.[0-9]*)?([eE][+\-]?[0-9]+)?)/, // html token hx = /^\s*(['"=>\/&#]|<(?:\/|\!(?:--)?)?|[a-zA-Z][a-zA-Z0-9_\-]*|[0-9]+|--|.)/, // outer html token ox = /[>&]|<[\/!]?|--/, // star slash lx = /\*\/|\/\*/, // identifier ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/, // javascript url jx = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i, // url badness ux = /&|\+|\u00AD|\.\.|\/\*|%[^;]|base64|url|expression|data|mailto/i, // style sx = /^\s*([{:#*%.=,>+\[\]@()"';*]|[a-zA-Z0-9_][a-zA-Z0-9_\-]*|<\/|\/\*)/, ssx = /^\s*([@#!"'};:\-\/%.=,+\[\]()*_]|[a-zA-Z][a-zA-Z0-9._\-]*|\d+(?:\.\d+)?|<\/)/, // query characters qx = /[\[\]\/\\"'*<>.&:(){}+=#_]/, // query characters for ids dx = /[\[\]\/\\"'*<>.&:(){}+=#]/, rx = { outer: hx, html: hx, style: sx, styleproperty: ssx }; function F() {} if (typeof Object.create !== 'function') { Object.create = function (o) { F.prototype = o; return new F(); }; } function combine(t, o) { var n; for (n in o) { if (o.hasOwnProperty(n)) { t[n] = o[n]; } } } String.prototype.entityify = function () { return this. replace(/&/g, '&amp;'). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); }; String.prototype.isAlpha = function () { return (this >= 'a' && this <= 'z\uffff') || (this >= 'A' && this <= 'Z\uffff'); }; String.prototype.isDigit = function () { return (this >= '0' && this <= '9'); }; String.prototype.supplant = function (o) { return this.replace(/\{([^{}]*)\}/g, function (a, b) { var r = o[b]; return typeof r === 'string' || typeof r === 'number' ? r : a; }); }; String.prototype.name = function () { // If the string looks like an identifier, then we can return it as is. // If the string contains no control characters, no quote characters, and no // backslash characters, then we can simply slap some quotes around it. // Otherwise we must also replace the offending characters with safe // sequences. if (ix.test(this)) { return this; } if (/[&<"\/\\\x00-\x1f]/.test(this)) { return '"' + this.replace(/[&<"\/\\\x00-\x1f]/g, function (a) { var c = escapes[a]; if (c) { return c; } c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"'; } return '"' + this + '"'; }; function assume() { if (!option.safe) { if (option.rhino) { combine(predefined, rhino); } if (option.browser || option.sidebar) { combine(predefined, browser); } if (option.sidebar) { combine(predefined, sidebar); } if (option.widget) { combine(predefined, widget); } } } // Produce an error warning. function quit(m, l, ch) { throw { name: 'JSLintError', line: l, character: ch, message: m + " (" + Math.floor((l / lines.length) * 100) + "% scanned)." }; } function warning(m, t, a, b, c, d) { var ch, l, w; t = t || nexttoken; if (t.id === '(end)') { // `~ t = token; } l = t.line || 0; ch = t.from || 0; w = { id: '(error)', raw: m, evidence: lines[l] || '', line: l, character: ch, a: a, b: b, c: c, d: d }; w.reason = m.supplant(w); JSLINT.errors.push(w); if (option.passfail) { quit('Stopping. ', l, ch); } warnings += 1; if (warnings === 50) { quit("Too many errors.", l, ch); } return w; } function warningAt(m, l, ch, a, b, c, d) { return warning(m, { line: l, from: ch }, a, b, c, d); } function error(m, t, a, b, c, d) { var w = warning(m, t, a, b, c, d); quit("Stopping, unable to continue.", w.line, w.character); } function errorAt(m, l, ch, a, b, c, d) { return error(m, { line: l, from: ch }, a, b, c, d); } // lexical analysis var lex = (function lex() { var character, from, line, s; // Private lex methods function nextLine() { var at; line += 1; if (line >= lines.length) { return false; } character = 0; s = lines[line].replace(/\t/g, tab); at = s.search(cx); if (at >= 0) { warningAt("Unsafe character.", line, at); } return true; } // Produce a token object. The token inherits from a syntax symbol. function it(type, value) { var i, t; if (type === '(color)') { t = {type: type}; } else if (type === '(punctuator)' || (type === '(identifier)' && syntax.hasOwnProperty(value))) { t = syntax[value] || syntax['(error)']; // Mozilla bug workaround. if (!t.id) { t = syntax[type]; } } else { t = syntax[type]; } t = Object.create(t); if (type === '(string)' || type === '(range)') { if (jx.test(value)) { warningAt("Script URL.", line, from); } } if (type === '(identifier)') { t.identifier = true; if (option.nomen && value.charAt(0) === '_') { warningAt("Unexpected '_' in '{a}'.", line, from, value); } } t.value = value; t.line = line; t.character = character; t.from = from; i = t.id; if (i !== '(endline)') { prereg = i && (('(,=:[!&|?{};'.indexOf(i.charAt(i.length - 1)) >= 0) || i === 'return'); } return t; } // Public lex methods return { init: function (source) { if (typeof source === 'string') { lines = source. replace(/\r\n/g, '\n'). replace(/\r/g, '\n'). split('\n'); } else { lines = source; } line = -1; nextLine(); from = 0; }, range: function (begin, end) { var c, value = ''; from = character; if (s.charAt(0) !== begin) { errorAt("Expected '{a}' and instead saw '{b}'.", line, character, begin, s.charAt(0)); } for (;;) { s = s.slice(1); character += 1; c = s.charAt(0); switch (c) { case '': errorAt("Missing '{a}'.", line, character, c); break; case end: s = s.slice(1); character += 1; return it('(range)', value); case xquote: case '\\': case '\'': case '"': warningAt("Unexpected '{a}'.", line, character, c); } value += c; } }, // token -- this is called by advance to get the next token. token: function () { var b, c, captures, d, depth, high, i, l, low, q, t; function match(x) { var r = x.exec(s), r1; if (r) { l = r[0].length; r1 = r[1]; c = r1.charAt(0); s = s.substr(l); character += l; from = character - r1.length; return r1; } } function string(x) { var c, j, r = ''; if (jsonmode && x !== '"') { warningAt("Strings must use doublequote.", line, character); } if (xquote === x || (xmode === 'scriptstring' && !xquote)) { return it('(punctuator)', x); } function esc(n) { var i = parseInt(s.substr(j + 1, n), 16); j += n; if (i >= 32 && i <= 126 && i !== 34 && i !== 92 && i !== 39) { warningAt("Unnecessary escapement.", line, character); } character += n; c = String.fromCharCode(i); } j = 0; for (;;) { while (j >= s.length) { j = 0; if (xmode !== 'html' || !nextLine()) { errorAt("Unclosed string.", line, from); } } c = s.charAt(j); if (c === x) { character += 1; s = s.substr(j + 1); return it('(string)', r, x); } if (c < ' ') { if (c === '\n' || c === '\r') { break; } warningAt("Control character in string: {a}.", line, character + j, s.slice(0, j)); } else if (c === xquote) { warningAt("Bad HTML string", line, character + j); } else if (c === '<') { if (option.safe && xmode === 'html') { warningAt("ADsafe string violation.", line, character + j); } else if (s.charAt(j + 1) === '/' && (xmode || option.safe)) { warningAt("Expected '<\\/' and instead saw '</'.", line, character); } else if (s.charAt(j + 1) === '!' && (xmode || option.safe)) { warningAt("Unexpected '<!' in a string.", line, character); } } else if (c === '\\') { if (xmode === 'html') { if (option.safe) { warningAt("ADsafe string violation.", line, character + j); } } else if (xmode === 'styleproperty') { j += 1; character += 1; c = s.charAt(j); if (c !== x) { warningAt("Escapement in style string.", line, character + j); } } else { j += 1; character += 1; c = s.charAt(j); switch (c) { case xquote: warningAt("Bad HTML string", line, character + j); break; case '\\': case '\'': case '"': case '/': break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'u': esc(4); break; case 'v': c = '\v'; break; case 'x': if (jsonmode) { warningAt("Avoid \\x-.", line, character); } esc(2); break; default: warningAt("Bad escapement.", line, character); } } } r += c; character += 1; j += 1; } } for (;;) { if (!s) { return it(nextLine() ? '(endline)' : '(end)', ''); } while (xmode === 'outer') { i = s.search(ox); if (i === 0) { break; } else if (i > 0) { character += 1; s = s.slice(i); break; } else { if (!nextLine()) { return it('(end)', ''); } } } t = match(rx[xmode] || tx); if (!t) { if (xmode === 'html') { return it('(error)', s.charAt(0)); } else { t = ''; c = ''; while (s && s < '!') { s = s.substr(1); } if (s) { errorAt("Unexpected '{a}'.", line, character, s.substr(0, 1)); } } } else { // identifier if (c.isAlpha() || c === '_' || c === '$') { return it('(identifier)', t); } // number if (c.isDigit()) { if (xmode !== 'style' && !isFinite(Number(t))) { warningAt("Bad number '{a}'.", line, character, t); } if (xmode !== 'styleproperty' && s.substr(0, 1).isAlpha()) { warningAt("Missing space after '{a}'.", line, character, t); } if (c === '0') { d = t.substr(1, 1); if (d.isDigit()) { if (token.id !== '.' && xmode !== 'styleproperty') { warningAt("Don't use extra leading zeros '{a}'.", line, character, t); } } else if (jsonmode && (d === 'x' || d === 'X')) { warningAt("Avoid 0x-. '{a}'.", line, character, t); } } if (t.substr(t.length - 1) === '.') { warningAt( "A trailing decimal point can be confused with a dot '{a}'.", line, character, t); } return it('(number)', t); } switch (t) { // string case '"': case "'": return string(t); // // comment case '//': if (src || (xmode && xmode !== 'script')) { warningAt("Unexpected comment.", line, character); } else if (xmode === 'script' && /<\s*\//i.test(s)) { warningAt("Unexpected <\/ in comment.", line, character); } else if ((option.safe || xmode === 'script') && ax.test(s)) { warningAt("Dangerous comment.", line, character); } s = ''; token.comment = true; break; // /* comment case '/*': if (src || (xmode && xmode !== 'script' && xmode !== 'style' && xmode !== 'styleproperty')) { warningAt("Unexpected comment.", line, character); } if (option.safe && ax.test(s)) { warningAt("ADsafe comment violation.", line, character); } for (;;) { i = s.search(lx); if (i >= 0) { break; } if (!nextLine()) { errorAt("Unclosed comment.", line, character); } else { if (option.safe && ax.test(s)) { warningAt("ADsafe comment violation.", line, character); } } } character += i + 2; if (s.substr(i, 1) === '/') { errorAt("Nested comment.", line, character); } s = s.substr(i + 2); token.comment = true; break; // /*global /*extern /*members /*jslint */ case '/*global': case '/*extern': case '/*members': case '/*member': case '/*jslint': case '*/': return { value: t, type: 'special', line: line, character: character, from: from }; case '': break; // / case '/': if (prereg) { depth = 0; captures = 0; l = 0; for (;;) { b = true; c = s.charAt(l); l += 1; switch (c) { case '': errorAt("Unclosed regular expression.", line, from); return; case '/': if (depth > 0) { warningAt("Unescaped '{a}'.", line, from + l, '/'); } c = s.substr(0, l - 1); q = { g: true, i: true, m: true }; while (q[s.charAt(l)] === true) { q[s.charAt(l)] = false; l += 1; } character += l; s = s.substr(l); return it('(regexp)', c); case '\\': c = s.charAt(l); if (c < ' ') { warningAt("Unexpected control character in regular expression.", line, from + l); } else if (c === '<') { warningAt("Unexpected escaped character '{a}' in regular expression.", line, from + l, c); } l += 1; break; case '(': depth += 1; b = false; if (s.charAt(l) === '?') { l += 1; switch (s.charAt(l)) { case ':': case '=': case '!': l += 1; break; default: warningAt("Expected '{a}' and instead saw '{b}'.", line, from + l, ':', s.charAt(l)); } } else { captures += 1; } break; case ')': if (depth === 0) { warningAt("Unescaped '{a}'.", line, from + l, ')'); } else { depth -= 1; } break; case ' ': q = 1; while (s.charAt(l) === ' ') { l += 1; q += 1; } if (q > 1) { warningAt("Spaces are hard to count. Use {{a}}.", line, from + l, q); } break; case '[': if (s.charAt(l) === '^') { l += 1; } q = false; klass: do { c = s.charAt(l); l += 1; switch (c) { case '[': case '^': warningAt("Unescaped '{a}'.", line, from + l, c); q = true; break; case '-': if (q) { q = false; } else { warningAt("Unescaped '{a}'.", line, from + l, '-'); q = true; } break; case ']': if (!q) { warningAt("Unescaped '{a}'.", line, from + l - 1, '-'); } break klass; case '\\': c = s.charAt(l); if (c < ' ') { warningAt("Unexpected control character in regular expression.", line, from + l); } else if (c === '<') { warningAt("Unexpected escaped character '{a}' in regular expression.", line, from + l, c); } l += 1; q = true; break; case '/': warningAt("Unescaped '{a}'.", line, from + l - 1, '/'); q = true; break; case '<': if (xmode === 'script') { c = s.charAt(l); if (c === '!' || c === '/') { warningAt("HTML confusion in regular expression '<{a}'.", line, from + l, c); } } q = true; break; default: q = true; } } while (c); break; case '.': if (option.regexp) { warningAt("Unexpected '{a}'.", line, from + l, c); } break; case ']': case '?': case '{': case '}': case '+': case '*': warningAt("Unescaped '{a}'.", line, from + l, c); break; case '<': if (xmode === 'script') { c = s.charAt(l); if (c === '!' || c === '/') { warningAt("HTML confusion in regular expression '<{a}'.", line, from + l, c); } } } if (b) { switch (s.charAt(l)) { case '?': case '+': case '*': l += 1; if (s.charAt(l) === '?') { l += 1; } break; case '{': l += 1; c = s.charAt(l); if (c < '0' || c > '9') { warningAt("Expected a number and instead saw '{a}'.", line, from + l, c); } l += 1; low = +c; for (;;) { c = s.charAt(l); if (c < '0' || c > '9') { break; } l += 1; low = +c + (low * 10); } high = low; if (c === ',') { l += 1; high = Infinity; c = s.charAt(l); if (c >= '0' && c <= '9') { l += 1; high = +c; for (;;) { c = s.charAt(l); if (c < '0' || c > '9') { break; } l += 1; high = +c + (high * 10); } } } if (s.charAt(l) !== '}') { warningAt("Expected '{a}' and instead saw '{b}'.", line, from + l, '}', c); } else { l += 1; } if (s.charAt(l) === '?') { l += 1; } if (low > high) { warningAt("'{a}' should not be greater than '{b}'.", line, from + l, low, high); } } } } c = s.substr(0, l - 1); character += l; s = s.substr(l); return it('(regexp)', c); } return it('(punctuator)', t); // punctuator case '#': if (xmode === 'html' || xmode === 'styleproperty') { for (;;) { c = s.charAt(0); if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) { break; } character += 1; s = s.substr(1); t += c; } if (t.length !== 4 && t.length !== 7) { warningAt("Bad hex color '{a}'.", line, from + l, t); } return it('(color)', t); } return it('(punctuator)', t); default: if (xmode === 'outer' && c === '&') { character += 1; s = s.substr(1); for (;;) { c = s.charAt(0); character += 1; s = s.substr(1); if (c === ';') { break; } if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || c === '#')) { errorAt("Bad entity", line, from + l, character); } } break; } return it('(punctuator)', t); } } } } }; }()); function addlabel(t, type) { if (t === 'hasOwnProperty') { error("'hasOwnProperty' is a really bad name."); } if (option.safe && funct['(global)']) { warning('ADsafe global: ' + t + '.', token); } // Define t in the current function in the current scope. if (funct.hasOwnProperty(t)) { warning(funct[t] === true ? "'{a}' was used before it was defined." : "'{a}' is already defined.", nexttoken, t); } funct[t] = type; if (type === 'label') { scope[t] = funct; } else if (funct['(global)']) { global[t] = funct; if (implied.hasOwnProperty(t)) { warning("'{a}' was used before it was defined.", nexttoken, t); delete implied[t]; } } else { funct['(scope)'][t] = funct; } } function doOption() { var b, obj, filter, o = nexttoken.value, t, v; switch (o) { case '*/': error("Unbegun comment."); break; case '/*global': case '/*extern': if (option.safe) { warning("ADsafe restriction."); } obj = predefined; break; case '/*members': case '/*member': o = '/*members'; if (!membersOnly) { membersOnly = {}; } obj = membersOnly; break; case '/*jslint': if (option.safe) { warning("ADsafe restriction."); } obj = option; filter = boolOptions; } for (;;) { t = lex.token(); if (t.id === ',') { t = lex.token(); } while (t.id === '(endline)') { t = lex.token(); } if (t.type === 'special' && t.value === '*/') { break; } if (t.type !== '(string)' && t.type !== '(identifier)' && o !== '/*members') { error("Bad option.", t); } if (filter) { if (filter[t.value] !== true) { error("Bad option.", t); } v = lex.token(); if (v.id !== ':') { error("Expected '{a}' and instead saw '{b}'.", t, ':', t.value); } v = lex.token(); if (v.value === 'true') { b = true; } else if (v.value === 'false') { b = false; } else { error("Expected '{a}' and instead saw '{b}'.", t, 'true', t.value); } } else { b = true; } obj[t.value] = b; } if (filter) { assume(); } } // We need a peek function. If it has an argument, it peeks that much farther // ahead. It is used to distinguish // for ( var i in ... // from // for ( var i = ... function peek(p) { var i = p || 0, j = 0, t; while (j <= i) { t = lookahead[j]; if (!t) { t = lookahead[j] = lex.token(); } j += 1; } return t; } // Produce the next token. It looks for programming errors. function advance(id, t) { var l; switch (token.id) { case '(number)': if (nexttoken.id === '.') { warning( "A dot following a number can be confused with a decimal point.", token); } break; case '-': if (nexttoken.id === '-' || nexttoken.id === '--') { warning("Confusing minusses."); } break; case '+': if (nexttoken.id === '+' || nexttoken.id === '++') { warning("Confusing plusses."); } break; } if (token.type === '(string)' || token.identifier) { anonname = token.value; } if (id && nexttoken.id !== id) { if (t) { if (nexttoken.id === '(end)') { warning("Unmatched '{a}'.", t, t.id); } else { warning("Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", nexttoken, id, t.id, t.line + 1, nexttoken.value); } } else if (nexttoken.type !== '(identifier)' || nexttoken.value !== id) { warning("Expected '{a}' and instead saw '{b}'.", nexttoken, id, nexttoken.value); } } prevtoken = token; token = nexttoken; for (;;) { nexttoken = lookahead.shift() || lex.token(); if (nexttoken.id === '(end)' || nexttoken.id === '(error)') { return; } if (nexttoken.type === 'special') { doOption(); } else { if (nexttoken.id !== '(endline)') { break; } l = !xmode && !option.laxbreak && (token.type === '(string)' || token.type === '(number)' || token.type === '(identifier)' || badbreak[token.id]); } } if (!option.evil && nexttoken.value === 'eval') { warning("eval is evil.", nexttoken); } if (l) { switch (nexttoken.id) { case '{': case '}': case ']': case '.': break; case ')': switch (token.id) { case ')': case '}': case ']': break; default: warning("Line breaking error '{a}'.", token, ')'); } break; default: warning("Line breaking error '{a}'.", token, token.value); } } } // This is the heart of JSLINT, the Pratt parser. In addition to parsing, it // is looking for ad hoc lint patterns. We add to Pratt's model .fud, which is // like nud except that it is only used on the first token of a statement. // Having .fud makes it much easier to define JavaScript. I retained Pratt's // nomenclature. // .nud Null denotation // .fud First null denotation // .led Left denotation // lbp Left binding power // rbp Right binding power // They are key to the parsing method called Top Down Operator Precedence. function parse(rbp, initial) { var left, o; if (nexttoken.id === '(end)') { error("Unexpected early end of program.", token); } advance(); if (option.safe && predefined[token.value] === true && (nexttoken.id !== '(' && nexttoken.id !== '.')) { warning('ADsafe violation.', token); } if (initial) { anonname = 'anonymous'; funct['(verb)'] = token.value; } if (initial === true && token.fud) { left = token.fud(); } else { if (token.nud) { o = token.exps; left = token.nud(); } else { if (nexttoken.type === '(number)' && token.id === '.') { warning( "A leading decimal point can be confused with a dot: '.{a}'.", token, nexttoken.value); advance(); return token; } else { error("Expected an identifier and instead saw '{a}'.", token, token.id); } } while (rbp < nexttoken.lbp) { o = nexttoken.exps; advance(); if (token.led) { left = token.led(left); } else { error("Expected an operator and instead saw '{a}'.", token, token.id); } } if (initial && !o) { warning( "Expected an assignment or function call and instead saw an expression.", token); } } return left; } // Functions for conformance of style. function abut(left, right) { left = left || token; right = right || nexttoken; if (left.line !== right.line || left.character !== right.from) { warning("Unexpected space after '{a}'.", right, left.value); } } function adjacent(left, right) { left = left || token; right = right || nexttoken; if (option.white || xmode === 'styleproperty' || xmode === 'style') { if (left.character !== right.from && left.line === right.line) { warning("Unexpected space after '{a}'.", right, left.value); } } } function nospace(left, right) { left = left || token; right = right || nexttoken; if (option.white && !left.comment) { if (left.line === right.line) { adjacent(left, right); } } } function nonadjacent(left, right) { left = left || token; right = right || nexttoken; if (option.white) { if (left.character === right.from) { warning("Missing space after '{a}'.", nexttoken, left.value); } } } function indentation(bias) { var i; if (option.white && nexttoken.id !== '(end)') { i = indent + (bias || 0); if (nexttoken.from !== i) { warning("Expected '{a}' to have an indentation of {b} instead of {c}.", nexttoken, nexttoken.value, i, nexttoken.from); } } } function nolinebreak(t) { if (t.line !== nexttoken.line) { warning("Line breaking error '{a}'.", t, t.id); } } // Parasitic constructors for making the symbols that will be inherited by // tokens. function symbol(s, p) { var x = syntax[s]; if (!x || typeof x !== 'object') { syntax[s] = x = { id: s, lbp: p, value: s }; } return x; } function delim(s) { return symbol(s, 0); } function stmt(s, f) { var x = delim(s); x.identifier = x.reserved = true; x.fud = f; return x; } function blockstmt(s, f) { var x = stmt(s, f); x.block = true; return x; } function reserveName(x) { var c = x.id.charAt(0); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { x.identifier = x.reserved = true; } return x; } function prefix(s, f) { var x = symbol(s, 150); reserveName(x); x.nud = (typeof f === 'function') ? f : function () { if (option.plusplus && (this.id === '++' || this.id === '--')) { warning("Unexpected use of '{a}'.", this, this.id); } this.right = parse(150); this.arity = 'unary'; return this; }; return x; } function type(s, f) { var x = delim(s); x.type = s; x.nud = f; return x; } function reserve(s, f) { var x = type(s, f); x.identifier = x.reserved = true; return x; } function reservevar(s, v) { return reserve(s, function () { if (this.id === 'this') { if (option.safe) { warning("ADsafe violation.", this); } } return this; }); } function infix(s, f, p) { var x = symbol(s, p); reserveName(x); x.led = (typeof f === 'function') ? f : function (left) { nonadjacent(prevtoken, token); nonadjacent(token, nexttoken); this.left = left; this.right = parse(p); return this; }; return x; } function relation(s, f) { var x = symbol(s, 100); x.led = function (left) { nonadjacent(prevtoken, token); nonadjacent(token, nexttoken); var right = parse(100); if ((left && left.id === 'NaN') || (right && right.id === 'NaN')) { warning("Use the isNaN function to compare with NaN.", this); } else if (f) { f.apply(this, [left, right]); } this.left = left; this.right = right; return this; }; return x; } function isPoorRelation(node) { return (node.type === '(number)' && !+node.value) || (node.type === '(string)' && !node.value) || node.type === 'true' || node.type === 'false' || node.type === 'undefined' || node.type === 'null'; } function assignop(s, f) { symbol(s, 20).exps = true; return infix(s, function (left) { var l; this.left = left; nonadjacent(prevtoken, token); nonadjacent(token, nexttoken); if (option.safe) { l = left; do { if (predefined[l.value] === true) { warning('ADsafe violation.', l); } l = l.left; } while (l); } if (left) { if (left.id === '.' || left.id === '[') { if (left.left.value === 'arguments') { warning('Bad assignment.', this); } this.right = parse(19); return this; } else if (left.identifier && !left.reserved) { if (funct[left.value] === 'exception') { warning("Do not assign to the exception parameter.", left); } this.right = parse(19); return this; } if (left === syntax['function']) { warning( "Expected an identifier in an assignment and instead saw a function invocation.", token); } } error("Bad assignment.", this); }, 20); } function bitwise(s, f, p) { var x = symbol(s, p); reserveName(x); x.led = (typeof f === 'function') ? f : function (left) { if (option.bitwise) { warning("Unexpected use of '{a}'.", this, this.id); } nonadjacent(prevtoken, token); nonadjacent(token, nexttoken); this.left = left; this.right = parse(p); return this; }; return x; } function bitwiseassignop(s) { symbol(s, 20).exps = true; return infix(s, function (left) { if (option.bitwise) { warning("Unexpected use of '{a}'.", this, this.id); } nonadjacent(prevtoken, token); nonadjacent(token, nexttoken); if (left) { if (left.id === '.' || left.id === '[' || (left.identifier && !left.reserved)) { parse(19); return left; } if (left === syntax['function']) { warning( "Expected an identifier in an assignment, and instead saw a function invocation.", token); } } error("Bad assignment.", this); }, 20); } function suffix(s, f) { var x = symbol(s, 150); x.led = function (left) { if (option.plusplus) { warning("Unexpected use of '{a}'.", this, this.id); } this.left = left; return this; }; return x; } function optionalidentifier() { if (nexttoken.reserved && nexttoken.value !== 'arguments') { warning("Expected an identifier and instead saw '{a}' (a reserved word).", nexttoken, nexttoken.id); } if (nexttoken.identifier) { advance(); return token.value; } } function identifier() { var i = optionalidentifier(); if (i) { return i; } if (token.id === 'function' && nexttoken.id === '(') { warning("Missing name in function statement."); } else { error("Expected an identifier and instead saw '{a}'.", nexttoken, nexttoken.value); } } function reachable(s) { var i = 0, t; if (nexttoken.id !== ';' || noreach) { return; } for (;;) { t = peek(i); if (t.reach) { return; } if (t.id !== '(endline)') { if (t.id === 'function') { warning( "Inner functions should be listed at the top of the outer function.", t); break; } warning("Unreachable '{a}' after '{b}'.", t, t.value, s); break; } i += 1; } } function statement(noindent) { var i = indent, r, s = scope, t = nexttoken; // We don't like the empty statement. if (t.id === ';') { warning("Unnecessary semicolon.", t); advance(';'); return; } // Is this a labelled statement? if (t.identifier && !t.reserved && peek().id === ':') { advance(); advance(':'); scope = Object.create(s); addlabel(t.value, 'label'); if (!nexttoken.labelled) { warning("Label '{a}' on {b} statement.", nexttoken, t.value, nexttoken.value); } if (jx.test(t.value + ':')) { warning("Label '{a}' looks like a javascript url.", t, t.value); } nexttoken.label = t.value; t = nexttoken; } // Parse the statement. if (!noindent) { indentation(); } r = parse(0, true); // Look for the final semicolon. if (!t.block) { if (nexttoken.id !== ';') { warningAt("Missing semicolon.", token.line, token.from + token.value.length); } else { adjacent(token, nexttoken); advance(';'); nonadjacent(token, nexttoken); } } // Restore the indentation. indent = i; scope = s; return r; } function use_strict() { if (nexttoken.type === '(string)' && /^use +strict(?:,.+)?$/.test(nexttoken.value)) { advance(); advance(';'); return true; } else { return false; } } function statements(begin) { var a = [], f, p; if (begin && !use_strict() && option.strict) { warning('Missing "use strict" statement.', nexttoken); } if (option.adsafe) { switch (begin) { case 'script': if (!adsafe_may) { if (nexttoken.value !== 'ADSAFE' || peek(0).id !== '.' || (peek(1).value !== 'id' && peek(1).value !== 'go')) { error('ADsafe violation: Missing ADSAFE.id or ADSAFE.go.', nexttoken); } } if (nexttoken.value === 'ADSAFE' && peek(0).id === '.' && peek(1).value === 'id') { if (adsafe_may) { error('ADsafe violation.', nexttoken); } advance('ADSAFE'); advance('.'); advance('id'); advance('('); if (nexttoken.value !== adsafe_id) { error('ADsafe violation: id does not match.', nexttoken); } advance('(string)'); advance(')'); advance(';'); adsafe_may = true; } break; case 'lib': if (nexttoken.value === 'ADSAFE') { advance('ADSAFE'); advance('.'); advance('lib'); advance('('); advance('(string)'); advance(','); f = parse(0); if (f.id !== 'function') { error('The second argument to lib must be a function.', f); } p = f.funct['(params)']; if (p && p !== 'lib') { error("Expected '{a}' and instead saw '{b}'.", f, 'lib', p); } advance(')'); advance(';'); return a; } else { error("ADsafe lib violation."); } } } while (!nexttoken.reach && nexttoken.id !== '(end)') { if (nexttoken.id === ';') { warning("Unnecessary semicolon."); advance(';'); } else { a.push(statement()); } } return a; } function block(f) { var a, b = inblock, s = scope, t; inblock = f; if (f) { scope = Object.create(scope); } nonadjacent(token, nexttoken); t = nexttoken; if (nexttoken.id === '{') { advance('{'); if (nexttoken.id !== '}' || token.line !== nexttoken.line) { indent += option.indent; if (!f && nexttoken.from === indent + option.indent) { indent += option.indent; } if (!f) { use_strict(); } a = statements(); indent -= option.indent; indentation(); } advance('}', t); } else { warning("Expected '{a}' and instead saw '{b}'.", nexttoken, '{', nexttoken.value); noreach = true; a = [statement()]; noreach = false; } funct['(verb)'] = null; scope = s; inblock = b; return a; } // An identity function, used by string and number tokens. function idValue() { return this; } function countMember(m) { if (membersOnly && membersOnly[m] !== true) { warning("Unexpected /*member '{a}'.", nexttoken, m); } if (typeof member[m] === 'number') { member[m] += 1; } else { member[m] = 1; } } function note_implied(token) { var name = token.value, line = token.line + 1, a = implied[name]; if (typeof a === 'function') { a = false; } if (!a) { a = [line]; implied[name] = a; } else if (a[a.length - 1] !== line) { a.push(line); } } // CSS parsing. function cssName() { if (nexttoken.identifier) { advance(); return true; } } function cssNumber() { if (nexttoken.id === '-') { advance('-'); advance('(number)'); } if (nexttoken.type === '(number)') { advance(); return true; } } function cssString() { if (nexttoken.type === '(string)') { advance(); return true; } } function cssColor() { var i, number; if (nexttoken.identifier) { if (nexttoken.value === 'rgb') { advance(); advance('('); for (i = 0; i < 3; i += 1) { number = nexttoken.value; if (nexttoken.type !== '(number)' || number < 0) { warning("Expected a positive number and instead saw '{a}'", nexttoken, number); advance(); } else { advance(); if (nexttoken.id === '%') { advance('%'); if (number > 100) { warning("Expected a percentage and instead saw '{a}'", token, number); } } else { if (number > 255) { warning("Expected a small number and instead saw '{a}'", token, number); } } } } advance(')'); return true; } else if (cssColorData[nexttoken.value] === true) { advance(); return true; } } else if (nexttoken.type === '(color)') { advance(); return true; } return false; } function cssLength() { if (nexttoken.id === '-') { advance('-'); adjacent(); } if (nexttoken.type === '(number)') { advance(); if (nexttoken.type !== '(string)' && cssLengthData[nexttoken.value] === true) { adjacent(); advance(); } else if (+token.value !== 0) { warning("Expected a linear unit and instead saw '{a}'.", nexttoken, nexttoken.value); } return true; } return false; } function cssLineHeight() { if (nexttoken.id === '-') { advance('-'); adjacent(); } if (nexttoken.type === '(number)') { advance(); if (nexttoken.type !== '(string)' && cssLengthData[nexttoken.value] === true) { adjacent(); advance(); } return true; } return false; } function cssWidth() { if (nexttoken.identifier) { switch (nexttoken.value) { case 'thin': case 'medium': case 'thick': advance(); return true; } } else { return cssLength(); } } function cssMargin() { if (nexttoken.identifier) { if (nexttoken.value === 'auto') { advance(); return true; } } else { return cssLength(); } } function cssAttr() { if (nexttoken.identifier && nexttoken.value === 'attr') { advance(); advance('('); if (!nexttoken.identifier) { warning("Expected a name and instead saw '{a}'.", nexttoken, nexttoken.value); } advance(); advance(')'); return true; } return false; } function cssCommaList() { while (nexttoken.id !== ';') { if (!cssName() && !cssString()) { warning("Expected a name and instead saw '{a}'.", nexttoken, nexttoken.value); } if (nexttoken.id !== ',') { return true; } advance(','); } } function cssCounter() { if (nexttoken.identifier && nexttoken.value === 'counter') { advance(); advance('('); if (!nexttoken.identifier) { } advance(); if (nexttoken.id === ',') { advance(','); if (nexttoken.type !== '(string)') { warning("Expected a string and instead saw '{a}'.", nexttoken, nexttoken.value); } advance(); } advance(')'); return true; } if (nexttoken.identifier && nexttoken.value === 'counters') { advance(); advance('('); if (!nexttoken.identifier) { warning("Expected a name and instead saw '{a}'.", nexttoken, nexttoken.value); } advance(); if (nexttoken.id === ',') { advance(','); if (nexttoken.type !== '(string)') { warning("Expected a string and instead saw '{a}'.", nexttoken, nexttoken.value); } advance(); } if (nexttoken.id === ',') { advance(','); if (nexttoken.type !== '(string)') { warning("Expected a string and instead saw '{a}'.", nexttoken, nexttoken.value); } advance(); } advance(')'); return true; } return false; } function cssShape() { var i; if (nexttoken.identifier && nexttoken.value === 'rect') { advance(); advance('('); for (i = 0; i < 4; i += 1) { if (!cssLength()) { warning("Expected a number and instead saw '{a}'.", nexttoken, nexttoken.value); break; } } advance(')'); return true; } return false; } function cssUrl() { var url; if (nexttoken.identifier && nexttoken.value === 'url') { nexttoken = lex.range('(', ')'); url = nexttoken.value; advance(); if (option.safe && ux.test(url)) { error("ADsafe URL violation."); } urls.push(url); return true; } return false; } cssAny = [cssUrl, function () { for (;;) { if (nexttoken.identifier) { switch (nexttoken.value.toLowerCase()) { case 'url': cssUrl(); break; case 'expression': warning("Unexpected expression '{a}'.", nexttoken, nexttoken.value); advance(); break; default: advance(); } } else { if (nexttoken.id === ';' || nexttoken.id === '!' || nexttoken.id === '(end)' || nexttoken.id === '}') { return true; } advance(); } } }]; cssBorderStyle = [ 'none', 'hidden', 'dotted', 'dashed', 'solid', 'double', 'ridge', 'inset', 'outset' ]; cssAttributeData = { background: [ true, 'background-attachment', 'background-color', 'background-image', 'background-position', 'background-repeat' ], 'background-attachment': ['scroll', 'fixed'], 'background-color': ['transparent', cssColor], 'background-image': ['none', cssUrl], 'background-position': [ 2, [cssLength, 'top', 'bottom', 'left', 'right', 'center'] ], 'background-repeat': [ 'repeat', 'repeat-x', 'repeat-y', 'no-repeat' ], 'border': [true, 'border-color', 'border-style', 'border-width'], 'border-bottom': [true, 'border-bottom-color', 'border-bottom-style', 'border-bottom-width'], 'border-bottom-color': cssColor, 'border-bottom-style': cssBorderStyle, 'border-bottom-width': cssWidth, 'border-collapse': ['collapse', 'separate'], 'border-color': ['transparent', 4, cssColor], 'border-left': [ true, 'border-left-color', 'border-left-style', 'border-left-width' ], 'border-left-color': cssColor, 'border-left-style': cssBorderStyle, 'border-left-width': cssWidth, 'border-right': [ true, 'border-right-color', 'border-right-style', 'border-right-width' ], 'border-right-color': cssColor, 'border-right-style': cssBorderStyle, 'border-right-width': cssWidth, 'border-spacing': [2, cssLength], 'border-style': [4, cssBorderStyle], 'border-top': [ true, 'border-top-color', 'border-top-style', 'border-top-width' ], 'border-top-color': cssColor, 'border-top-style': cssBorderStyle, 'border-top-width': cssWidth, 'border-width': [4, cssWidth], bottom: [cssLength, 'auto'], 'caption-side' : ['bottom', 'left', 'right', 'top'], clear: ['both', 'left', 'none', 'right'], clip: [cssShape, 'auto'], color: cssColor, content: [ 'open-quote', 'close-quote', 'no-open-quote', 'no-close-quote', cssString, cssUrl, cssCounter, cssAttr ], 'counter-increment': [ cssName, 'none' ], 'counter-reset': [ cssName, 'none' ], cursor: [ cssUrl, 'auto', 'crosshair', 'default', 'e-resize', 'help', 'move', 'n-resize', 'ne-resize', 'nw-resize', 'pointer', 's-resize', 'se-resize', 'sw-resize', 'w-resize', 'text', 'wait' ], direction: ['ltr', 'rtl'], display: [ 'block', 'compact', 'inline', 'inline-block', 'inline-table', 'list-item', 'marker', 'none', 'run-in', 'table', 'table-caption', 'table-column', 'table-column-group', 'table-footer-group', 'table-header-group', 'table-row', 'table-row-group' ], 'empty-cells': ['show', 'hide'], 'float': ['left', 'none', 'right'], font: [ 'caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar', true, 'font-size', 'font-style', 'font-weight', 'font-family' ], 'font-family': cssCommaList, 'font-size': [ 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'larger', 'smaller', cssLength ], 'font-size-adjust': ['none', cssNumber], 'font-stretch': [ 'normal', 'wider', 'narrower', 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'semi-expanded', 'expanded', 'extra-expanded' ], 'font-style': [ 'normal', 'italic', 'oblique' ], 'font-variant': [ 'normal', 'small-caps' ], 'font-weight': [ 'normal', 'bold', 'bolder', 'lighter', cssNumber ], height: [cssLength, 'auto'], left: [cssLength, 'auto'], 'letter-spacing': ['normal', cssLength], 'line-height': ['normal', cssLineHeight], 'list-style': [ true, 'list-style-image', 'list-style-position', 'list-style-type' ], 'list-style-image': ['none', cssUrl], 'list-style-position': ['inside', 'outside'], 'list-style-type': [ 'circle', 'disc', 'square', 'decimal', 'decimal-leading-zero', 'lower-roman', 'upper-roman', 'lower-greek', 'lower-alpha', 'lower-latin', 'upper-alpha', 'upper-latin', 'hebrew', 'katakana', 'hiragana-iroha', 'katakana-oroha', 'none' ], margin: [4, cssMargin], 'margin-bottom': cssMargin, 'margin-left': cssMargin, 'margin-right': cssMargin, 'margin-top': cssMargin, 'marker-offset': [cssLength, 'auto'], 'max-height': [cssLength, 'none'], 'max-width': [cssLength, 'none'], 'min-height': cssLength, 'min-width': cssLength, opacity: cssNumber, outline: [true, 'outline-color', 'outline-style', 'outline-width'], 'outline-color': ['invert', cssColor], 'outline-style': [ 'dashed', 'dotted', 'double', 'groove', 'inset', 'none', 'outset', 'ridge', 'solid' ], 'outline-width': cssWidth, overflow: ['auto', 'hidden', 'scroll', 'visible'], padding: [4, cssLength], 'padding-bottom': cssLength, 'padding-left': cssLength, 'padding-right': cssLength, 'padding-top': cssLength, position: ['absolute', 'fixed', 'relative', 'static'], quotes: [8, cssString], right: [cssLength, 'auto'], 'table-layout': ['auto', 'fixed'], 'text-align': ['center', 'justify', 'left', 'right'], 'text-decoration': ['none', 'underline', 'overline', 'line-through', 'blink'], 'text-indent': cssLength, 'text-shadow': ['none', 4, [cssColor, cssLength]], 'text-transform': ['capitalize', 'uppercase', 'lowercase', 'none'], top: [cssLength, 'auto'], 'unicode-bidi': ['normal', 'embed', 'bidi-override'], 'vertical-align': [ 'baseline', 'bottom', 'sub', 'super', 'top', 'text-top', 'middle', 'text-bottom', cssLength ], visibility: ['visible', 'hidden', 'collapse'], 'white-space': ['normal', 'pre', 'nowrap'], width: [cssLength, 'auto'], 'word-spacing': ['normal', cssLength], 'z-index': ['auto', cssNumber] }; function styleAttribute() { var v; while (nexttoken.id === '*' || nexttoken.id === '#' || nexttoken.value === '_') { if (!option.css) { warning("Unexpected '{a}'.", nexttoken, nexttoken.value); } advance(); } if (nexttoken.id === '-') { if (!option.css) { warning("Unexpected '{a}'.", nexttoken, nexttoken.value); } advance('-'); if (!nexttoken.identifier) { warning("Expected a non-standard style attribute and instead saw '{a}'.", nexttoken, nexttoken.value); } advance(); return cssAny; } else { if (!nexttoken.identifier) { warning("Excepted a style attribute, and instead saw '{a}'.", nexttoken, nexttoken.value); } else { if (cssAttributeData.hasOwnProperty(nexttoken.value)) { v = cssAttributeData[nexttoken.value]; } else { v = cssAny; if (!option.css) { warning("Unrecognized style attribute '{a}'.", nexttoken, nexttoken.value); } } } advance(); return v; } } function styleValue(v) { var i = 0, n, once, match, round, start = 0, vi; switch (typeof v) { case 'function': return v(); case 'string': if (nexttoken.identifier && nexttoken.value === v) { advance(); return true; } return false; } for (;;) { if (i >= v.length) { return false; } vi = v[i]; i += 1; if (vi === true) { break; } else if (typeof vi === 'number') { n = vi; vi = v[i]; i += 1; } else { n = 1; } match = false; while (n > 0) { if (styleValue(vi)) { match = true; n -= 1; } else { break; } } if (match) { return true; } } start = i; once = []; for (;;) { round = false; for (i = start; i < v.length; i += 1) { if (!once[i]) { if (styleValue(cssAttributeData[v[i]])) { match = true; round = true; once[i] = true; break; } } } if (!round) { return match; } } } function substyle() { var v; for (;;) { if (nexttoken.id === '}' || nexttoken.id === '(end)' || xquote && nexttoken.id === xquote) { return; } while (nexttoken.id === ';') { warning("Misplaced ';'."); advance(';'); } v = styleAttribute(); advance(':'); if (nexttoken.identifier && nexttoken.value === 'inherit') { advance(); } else { styleValue(v); } while (nexttoken.id !== ';' && nexttoken.id !== '!' && nexttoken.id !== '}' && nexttoken.id !== '(end)' && nexttoken.id !== xquote) { warning("Unexpected token '{a}'.", nexttoken, nexttoken.value); advance(); } if (nexttoken.id === '!') { advance('!'); adjacent(); if (nexttoken.identifier && nexttoken.value === 'important') { advance(); } else { warning("Expected '{a}' and instead saw '{b}'.", nexttoken, 'important', nexttoken.value); } } if (nexttoken.id === '}' || nexttoken.id === xquote) { warning("Missing '{a}'.", nexttoken, ';'); } else { advance(';'); } } } function stylePattern() { var name; if (nexttoken.id === '{') { warning("Expected a style pattern, and instead saw '{a}'.", nexttoken, nexttoken.id); } else if (nexttoken.id === '@') { advance('@'); name = nexttoken.value; if (nexttoken.identifier && atrule[name] === true) { advance(); return name; } warning("Expected an at-rule, and instead saw @{a}.", nexttoken, name); } for (;;) { if (nexttoken.identifier) { if (!htmltag.hasOwnProperty(nexttoken.value)) { warning("Expected a tagName, and instead saw {a}.", nexttoken, nexttoken.value); } advance(); } else { switch (nexttoken.id) { case '>': case '+': advance(); if (!nexttoken.identifier || !htmltag.hasOwnProperty(nexttoken.value)) { warning("Expected a tagName, and instead saw {a}.", nexttoken, nexttoken.value); } advance(); break; case ':': advance(':'); if (pseudorule[nexttoken.value] !== true) { warning("Expected a pseudo, and instead saw :{a}.", nexttoken, nexttoken.value); } advance(); if (nexttoken.value === 'lang') { advance('('); if (!nexttoken.identifier) { warning("Expected a lang code, and instead saw :{a}.", nexttoken, nexttoken.value); } advance(')'); } break; case '#': advance('#'); if (!nexttoken.identifier) { warning("Expected an id, and instead saw #{a}.", nexttoken, nexttoken.value); } advance(); break; case '*': advance('*'); break; case '.': advance('.'); if (!nexttoken.identifier) { warning("Expected a class, and instead saw #.{a}.", nexttoken, nexttoken.value); } advance(); break; case '[': advance('['); if (!nexttoken.identifier) { warning("Expected an attribute, and instead saw [{a}].", nexttoken, nexttoken.value); } advance(); if (nexttoken.id === '=' || nexttoken.id === '~=' || nexttoken.id === '|=') { advance(); if (nexttoken.type !== '(string)') { warning("Expected a string, and instead saw {a}.", nexttoken, nexttoken.value); } advance(); } advance(']'); break; default: error("Expected a CSS selector, and instead saw {a}.", nexttoken, nexttoken.value); } } if (nexttoken.id === '</' || nexttoken.id === '{' || nexttoken.id === '(end)') { return ''; } if (nexttoken.id === ',') { advance(','); } } } function styles() { while (nexttoken.id !== '</' && nexttoken.id !== '(end)') { stylePattern(); xmode = 'styleproperty'; if (nexttoken.id === ';') { advance(';'); } else { advance('{'); substyle(); xmode = 'style'; advance('}'); } } } // HTML parsing. function doBegin(n) { if (n !== 'html' && !option.fragment) { if (n === 'div' && option.adsafe) { error("ADSAFE: Use the fragment option."); } else { error("Expected '{a}' and instead saw '{b}'.", token, 'html', n); } } if (option.adsafe) { if (n === 'html') { error("Currently, ADsafe does not operate on whole HTML documents. It operates on <div> fragments and .js files.", token); } if (option.fragment) { if (n !== 'div') { error("ADsafe violation: Wrap the widget in a div.", token); } } else { error("Use the fragment option.", token); } } option.browser = true; assume(); } function doAttribute(n, a, v) { var u, x; if (a === 'id') { u = typeof v === 'string' ? v.toUpperCase() : ''; if (ids[u] === true) { warning("Duplicate id='{a}'.", nexttoken, v); } if (option.adsafe) { if (adsafe_id) { if (v.slice(0, adsafe_id.length) !== adsafe_id) { warning("ADsafe violation: An id must have a '{a}' prefix", nexttoken, adsafe_id); } else if (!/^[A-Z]+_[A-Z]+$/.test(v)) { warning("ADSAFE violation: bad id."); } } else { adsafe_id = v; if (!/^[A-Z]+_$/.test(v)) { warning("ADSAFE violation: bad id."); } } } x = v.search(dx); if (x >= 0) { warning("Unexpected character '{a}' in {b}.", token, v.charAt(x), a); } ids[u] = true; } else if (a === 'class' || a === 'type' || a === 'name') { x = v.search(qx); if (x >= 0) { warning("Unexpected character '{a}' in {b}.", token, v.charAt(x), a); } ids[u] = true; } else if (a === 'href' || a === 'background' || a === 'content' || a === 'data' || a.indexOf('src') >= 0 || a.indexOf('url') >= 0) { if (option.safe && ux.test(v)) { error("ADsafe URL violation."); } urls.push(v); } else if (a === 'for') { if (option.adsafe) { if (adsafe_id) { if (v.slice(0, adsafe_id.length) !== adsafe_id) { warning("ADsafe violation: An id must have a '{a}' prefix", nexttoken, adsafe_id); } else if (!/^[A-Z]+_[A-Z]+$/.test(v)) { warning("ADSAFE violation: bad id."); } } else { warning("ADSAFE violation: bad id."); } } } else if (a === 'name') { if (option.adsafe && v.indexOf('_') >= 0) { warning("ADsafe name violation."); } } } function doTag(n, a) { var i, t = htmltag[n], x; src = false; if (!t) { error("Unrecognized tag '<{a}>'.", nexttoken, n === n.toLowerCase() ? n : n + ' (capitalization error)'); } if (stack.length > 0) { if (n === 'html') { error("Too many <html> tags.", token); } x = t.parent; if (x) { if (x.indexOf(' ' + stack[stack.length - 1].name + ' ') < 0) { error("A '<{a}>' must be within '<{b}>'.", token, n, x); } } else if (!option.adsafe && !option.fragment) { i = stack.length; do { if (i <= 0) { error("A '<{a}>' must be within '<{b}>'.", token, n, 'body'); } i -= 1; } while (stack[i].name !== 'body'); } } switch (n) { case 'div': if (option.adsafe && stack.length === 1 && !adsafe_id) { warning("ADSAFE violation: missing ID_."); } break; case 'script': xmode = 'script'; advance('>'); indent = nexttoken.from; if (a.lang) { warning("lang is deprecated.", token); } if (option.adsafe && stack.length !== 1) { warning("ADsafe script placement violation.", token); } if (a.src) { if (option.adsafe && (!adsafe_may || !approved[a.src])) { warning("ADsafe unapproved script source.", token); } if (a.type) { warning("type is unnecessary.", token); } } else { if (adsafe_went) { error("ADsafe script violation.", token); } statements('script'); } xmode = 'html'; advance('</'); if (!nexttoken.identifier && nexttoken.value !== 'script') { warning("Expected '{a}' and instead saw '{b}'.", nexttoken, 'script', nexttoken.value); } advance(); xmode = 'outer'; break; case 'style': xmode = 'style'; advance('>'); styles(); xmode = 'html'; advance('</'); if (!nexttoken.identifier && nexttoken.value !== 'style') { warning("Expected '{a}' and instead saw '{b}'.", nexttoken, 'style', nexttoken.value); } advance(); xmode = 'outer'; break; case 'input': switch (a.type) { case 'radio': case 'checkbox': case 'text': case 'button': case 'file': case 'reset': case 'submit': case 'password': case 'file': case 'hidden': case 'image': break; default: warning("Bad input type."); } if (option.adsafe && a.autocomplete !== 'off') { warning("ADsafe autocomplete violation."); } break; case 'applet': case 'body': case 'embed': case 'frame': case 'frameset': case 'head': case 'iframe': case 'img': case 'noembed': case 'noframes': case 'object': case 'param': if (option.adsafe) { warning("ADsafe violation: Disallowed tag: " + n); } break; } } function closetag(n) { return '</' + n + '>'; } function html() { var a, attributes, e, n, q, t, v, w = option.white, wmode; xmode = 'html'; xquote = ''; stack = null; for (;;) { switch (nexttoken.value) { case '<': xmode = 'html'; advance('<'); attributes = {}; t = nexttoken; if (!t.identifier) { warning("Bad identifier {a}.", t, t.value); } n = t.value; if (option.cap) { n = n.toLowerCase(); } t.name = n; advance(); if (!stack) { stack = []; doBegin(n); } v = htmltag[n]; if (typeof v !== 'object') { error("Unrecognized tag '<{a}>'.", t, n); } e = v.empty; t.type = n; for (;;) { if (nexttoken.id === '/') { advance('/'); if (nexttoken.id !== '>') { warning("Expected '{a}' and instead saw '{b}'.", nexttoken, '>', nexttoken.value); } break; } if (nexttoken.id && nexttoken.id.substr(0, 1) === '>') { break; } if (!nexttoken.identifier) { if (nexttoken.id === '(end)' || nexttoken.id === '(error)') { error("Missing '>'.", nexttoken); } warning("Bad identifier."); } option.white = true; nonadjacent(token, nexttoken); a = nexttoken.value; option.white = w; advance(); if (!option.cap && a !== a.toLowerCase()) { warning("Attribute '{a}' not all lower case.", nexttoken, a); } a = a.toLowerCase(); xquote = ''; if (attributes.hasOwnProperty(a)) { warning("Attribute '{a}' repeated.", nexttoken, a); } if (a.slice(0, 2) === 'on') { if (!option.on) { warning("Avoid HTML event handlers."); } xmode = 'scriptstring'; advance('='); q = nexttoken.id; if (q !== '"' && q !== "'") { error("Missing quote."); } xquote = q; wmode = option.white; option.white = false; advance(q); statements('on'); option.white = wmode; if (nexttoken.id !== q) { error("Missing close quote on script attribute."); } xmode = 'html'; xquote = ''; advance(q); v = false; } else if (a === 'style') { xmode = 'scriptstring'; advance('='); q = nexttoken.id; if (q !== '"' && q !== "'") { error("Missing quote."); } xmode = 'styleproperty'; xquote = q; advance(q); substyle(); xmode = 'html'; xquote = ''; advance(q); v = false; } else { if (nexttoken.id === '=') { advance('='); v = nexttoken.value; if (!nexttoken.identifier && nexttoken.id !== '"' && nexttoken.id !== '\'' && nexttoken.type !== '(string)' && nexttoken.type !== '(number)' && nexttoken.type !== '(color)') { warning("Expected an attribute value and instead saw '{a}'.", token, a); } advance(); } else { v = true; } } attributes[a] = v; doAttribute(n, a, v); } doTag(n, attributes); if (!e) { stack.push(t); } xmode = 'outer'; advance('>'); break; case '</': xmode = 'html'; advance('</'); if (!nexttoken.identifier) { warning("Bad identifier."); } n = nexttoken.value; if (option.cap) { n = n.toLowerCase(); } advance(); if (!stack) { error("Unexpected '{a}'.", nexttoken, closetag(n)); } t = stack.pop(); if (!t) { error("Unexpected '{a}'.", nexttoken, closetag(n)); } if (t.name !== n) { error("Expected '{a}' and instead saw '{b}'.", nexttoken, closetag(t.name), closetag(n)); } if (nexttoken.id !== '>') { error("Missing '{a}'.", nexttoken, '>'); } xmode = 'outer'; advance('>'); break; case '<!': if (option.safe) { warning("ADsafe HTML violation."); } xmode = 'html'; for (;;) { advance(); if (nexttoken.id === '>' || nexttoken.id === '(end)') { break; } if (nexttoken.id === '--') { warning("Unexpected --."); } } xmode = 'outer'; advance('>'); break; case '<!--': xmode = 'html'; if (option.safe) { warning("ADsafe HTML violation."); } for (;;) { advance(); if (nexttoken.id === '(end)') { error("Missing '-->'."); } if (nexttoken.id === '<!' || nexttoken.id === '<!--') { error("Unexpected '<!' in HTML comment."); } if (nexttoken.id === '--') { advance('--'); break; } } abut(); xmode = 'outer'; advance('>'); break; case '(end)': return; default: if (nexttoken.id === '(end)') { error("Missing '{a}'.", nexttoken, '</' + stack[stack.length - 1].value + '>'); } else { advance(); } } if (stack && stack.length === 0 && (option.adsafe || !option.fragment || nexttoken.id === '(end)')) { break; } } if (nexttoken.id !== '(end)') { error("Unexpected material after the end."); } } // Build the syntax table by declaring the syntactic elements of the language. type('(number)', idValue); type('(string)', idValue); syntax['(identifier)'] = { type: '(identifier)', lbp: 0, identifier: true, nud: function () { var v = this.value, s = scope[v]; if (typeof s === 'function') { s = false; } // The name is in scope and defined in the current function. if (s && (s === funct || s === funct['(global)'])) { // If we are not also in the global scope, change 'unused' to 'var', // and reject labels. if (!funct['(global)']) { switch (funct[v]) { case 'unused': funct[v] = 'var'; break; case 'label': warning("'{a}' is a statement label.", token, v); break; } } // The name is not defined in the function. If we are in the global scope, // then we have an undefined variable. } else if (funct['(global)']) { if (option.undef) { warning("'{a}' is not defined.", token, v); } note_implied(token); // If the name is already defined in the current // function, but not as outer, then there is a scope error. } else { switch (funct[v]) { case 'closure': case 'function': case 'var': case 'unused': warning("'{a}' used out of scope.", token, v); break; case 'label': warning("'{a}' is a statement label.", token, v); break; case 'outer': case true: break; default: // If the name is defined in an outer function, make an outer entry, and if // it was unused, make it var. if (s === true) { funct[v] = true; } else if (typeof s !== 'object') { if (option.undef) { warning("'{a}' is not defined.", token, v); } else { funct[v] = true; } note_implied(token); } else { switch (s[v]) { case 'function': case 'var': case 'unused': s[v] = 'closure'; funct[v] = 'outer'; break; case 'closure': case 'parameter': funct[v] = 'outer'; break; case 'label': warning("'{a}' is a statement label.", token, v); } } } } return this; }, led: function () { error("Expected an operator and instead saw '{a}'.", nexttoken, nexttoken.value); } }; type('(regexp)', function () { return this; }); delim('(endline)'); delim('(begin)'); delim('(end)').reach = true; delim('</').reach = true; delim('<!'); delim('<!--'); delim('-->'); delim('(error)').reach = true; delim('}').reach = true; delim(')'); delim(']'); delim('"').reach = true; delim("'").reach = true; delim(';'); delim(':').reach = true; delim(','); delim('#'); delim('@'); reserve('else'); reserve('case').reach = true; reserve('catch'); reserve('default').reach = true; reserve('finally'); reservevar('arguments'); reservevar('eval'); reservevar('false'); reservevar('Infinity'); reservevar('NaN'); reservevar('null'); reservevar('this'); reservevar('true'); reservevar('undefined'); assignop('=', 'assign', 20); assignop('+=', 'assignadd', 20); assignop('-=', 'assignsub', 20); assignop('*=', 'assignmult', 20); assignop('/=', 'assigndiv', 20).nud = function () { error("A regular expression literal can be confused with '/='."); }; assignop('%=', 'assignmod', 20); bitwiseassignop('&=', 'assignbitand', 20); bitwiseassignop('|=', 'assignbitor', 20); bitwiseassignop('^=', 'assignbitxor', 20); bitwiseassignop('<<=', 'assignshiftleft', 20); bitwiseassignop('>>=', 'assignshiftright', 20); bitwiseassignop('>>>=', 'assignshiftrightunsigned', 20); infix('?', function (left) { this.left = left; this.right = parse(10); advance(':'); this['else'] = parse(10); return this; }, 30); infix('||', 'or', 40); infix('&&', 'and', 50); bitwise('|', 'bitor', 70); bitwise('^', 'bitxor', 80); bitwise('&', 'bitand', 90); relation('==', function (left, right) { if (option.eqeqeq) { warning("Expected '{a}' and instead saw '{b}'.", this, '===', '=='); } else if (isPoorRelation(left)) { warning("Use '{a}' to compare with '{b}'.", this, '===', left.value); } else if (isPoorRelation(right)) { warning("Use '{a}' to compare with '{b}'.", this, '===', right.value); } return this; }); relation('==='); relation('!=', function (left, right) { if (option.eqeqeq) { warning("Expected '{a}' and instead saw '{b}'.", this, '!==', '!='); } else if (isPoorRelation(left)) { warning("Use '{a}' to compare with '{b}'.", this, '!==', left.value); } else if (isPoorRelation(right)) { warning("Use '{a}' to compare with '{b}'.", this, '!==', right.value); } return this; }); relation('!=='); relation('<'); relation('>'); relation('<='); relation('>='); bitwise('<<', 'shiftleft', 120); bitwise('>>', 'shiftright', 120); bitwise('>>>', 'shiftrightunsigned', 120); infix('in', 'in', 120); infix('instanceof', 'instanceof', 120); infix('+', function (left) { nonadjacent(prevtoken, token); nonadjacent(token, nexttoken); var right = parse(130); if (left && right && left.id === '(string)' && right.id === '(string)') { left.value += right.value; left.character = right.character; if (jx.test(left.value)) { warning("JavaScript URL.", left); } return left; } this.left = left; this.right = right; return this; }, 130); prefix('+', 'num'); infix('-', 'sub', 130); prefix('-', 'neg'); infix('*', 'mult', 140); infix('/', 'div', 140); infix('%', 'mod', 140); suffix('++', 'postinc'); prefix('++', 'preinc'); syntax['++'].exps = true; suffix('--', 'postdec'); prefix('--', 'predec'); syntax['--'].exps = true; prefix('delete', function () { var p = parse(0); if (p.id !== '.' && p.id !== '[') { warning("Expected '{a}' and instead saw '{b}'.", nexttoken, '.', nexttoken.value); } }).exps = true; prefix('~', function () { if (option.bitwise) { warning("Unexpected '{a}'.", this, '~'); } parse(150); return this; }); prefix('!', 'not'); prefix('typeof', 'typeof'); prefix('new', function () { var c = parse(155), i; if (c && c.id !== 'function') { if (c.identifier) { c['new'] = true; switch (c.value) { case 'Object': warning("Use the object literal notation {}.", token); break; case 'Array': warning("Use the array literal notation [].", token); break; case 'Number': case 'String': case 'Boolean': case 'Math': warning("Do not use {a} as a constructor.", token, c.value); break; case 'Function': if (!option.evil) { warning("The Function constructor is eval."); } break; case 'Date': case 'RegExp': break; default: if (c.id !== 'function') { i = c.value.substr(0, 1); if (option.newcap && (i < 'A' || i > 'Z')) { warning( "A constructor name should start with an uppercase letter.", token); } } } } else { if (c.id !== '.' && c.id !== '[' && c.id !== '(') { warning("Bad constructor.", token); } } } else { warning("Weird construction. Delete 'new'.", this); } adjacent(token, nexttoken); if (nexttoken.id !== '(') { warning("Missing '()' invoking a constructor."); } this.first = c; return this; }); syntax['new'].exps = true; infix('.', function (left) { adjacent(prevtoken, token); var t = this, m = identifier(); if (typeof m === 'string') { countMember(m); } t.left = left; t.right = m; if (!option.evil && left && left.value === 'document' && (m === 'write' || m === 'writeln')) { warning("document.write can be a form of eval.", left); } if (option.adsafe) { if (left && left.value === 'ADSAFE') { if (m === 'id' || m === 'lib') { warning("ADsafe violation.", this); } else if (m === 'go') { if (xmode !== 'script') { warning("ADsafe violation.", this); } else if (adsafe_went || nexttoken.id !== '(' || peek(0).id !== '(string)' || peek(0).value !== adsafe_id || peek(1).id !== ',') { error("ADsafe violation: go.", this); } adsafe_went = true; adsafe_may = false; } } } if (option.safe) { for (;;) { if (banned[m] === true) { warning("ADsafe restricted word '{a}'.", token, m); } if (predefined[left.value] !== true || nexttoken.id === '(') { break; } if (standard_member[m] === true) { if (nexttoken.id === '.') { warning("ADsafe violation.", this); } break; } if (nexttoken.id !== '.') { warning("ADsafe violation.", this); break; } advance('.'); token.left = t; token.right = m; t = token; m = identifier(); if (typeof m === 'string') { countMember(m); } } } return t; }, 160); infix('(', function (left) { adjacent(prevtoken, token); nospace(); var n = 0, p = []; if (left) { if (left.type === '(identifier)') { if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { if (left.value !== 'Number' && left.value !== 'String' && left.value !== 'Boolean' && left.value !== 'Date') { if (left.value === 'Math') { warning("Math is not a function.", left); } else if (option.newcap) { warning("Missing 'new' prefix when invoking a constructor.", left); } } } } else if (left.id === '.') { if (option.safe && left.left.value === 'Math' && left.right === 'random') { warning("ADsafe violation.", left); } } } if (nexttoken.id !== ')') { for (;;) { p[p.length] = parse(10); n += 1; if (nexttoken.id !== ',') { break; } advance(','); nonadjacent(token, nexttoken); } } advance(')'); if (option.immed && left.id === 'function' && nexttoken.id !== ')') { warning("Wrap the entire immediate function invocation in parens.", this); } nospace(prevtoken, token); if (typeof left === 'object') { if (left.value === 'parseInt' && n === 1) { warning("Missing radix parameter.", left); } if (!option.evil) { if (left.value === 'eval' || left.value === 'Function' || left.value === 'execScript') { warning("eval is evil.", left); } else if (p[0] && p[0].id === '(string)' && (left.value === 'setTimeout' || left.value === 'setInterval')) { warning( "Implied eval is evil. Pass a function instead of a string.", left); } } if (!left.identifier && left.id !== '.' && left.id !== '[' && left.id !== '(' && left.id !== '&&' && left.id !== '||' && left.id !== '?') { warning("Bad invocation.", left); } } this.left = left; return this; }, 155).exps = true; prefix('(', function () { nospace(); var v = parse(0); advance(')', this); nospace(prevtoken, token); if (option.immed && v.id === 'function') { if (nexttoken.id === '(') { warning( "Move the invocation into the parens that contain the function.", nexttoken); } else { warning( "Do not wrap function literals in parens unless they are to be immediately invoked.", this); } } return v; }); infix('[', function (left) { nospace(); var e = parse(0), s; if (e && e.type === '(string)') { if (option.safe && banned[e.value] === true) { warning("ADsafe restricted word '{a}'.", this, e.value); } countMember(e.value); if (!option.sub && ix.test(e.value)) { s = syntax[e.value]; if (!s || !s.reserved) { warning("['{a}'] is better written in dot notation.", e, e.value); } } } else if (!e || (e.type !== '(number)' && (e.id !== '+' || e.arity !== 'unary'))) { if (option.safe) { warning('ADsafe subscripting.'); } } advance(']', this); nospace(prevtoken, token); this.left = left; this.right = e; return this; }, 160); prefix('[', function () { if (nexttoken.id === ']') { advance(']'); return; } var b = token.line !== nexttoken.line; if (b) { indent += option.indent; if (nexttoken.from === indent + option.indent) { indent += option.indent; } } for (;;) { if (b && token.line !== nexttoken.line) { indentation(); } parse(10); if (nexttoken.id === ',') { adjacent(token, nexttoken); advance(','); if (nexttoken.id === ',') { warning("Extra comma.", token); } else if (nexttoken.id === ']') { warning("Extra comma.", token); break; } nonadjacent(token, nexttoken); } else { if (b) { indent -= option.indent; indentation(); } break; } } advance(']', this); return; }, 160); (function (x) { x.nud = function () { var b, i, s, seen = {}; b = token.line !== nexttoken.line; if (b) { indent += option.indent; if (nexttoken.from === indent + option.indent) { indent += option.indent; } } for (;;) { if (nexttoken.id === '}') { break; } if (b) { indentation(); } i = optionalidentifier(true); if (!i) { if (nexttoken.id === '(string)') { i = nexttoken.value; if (ix.test(i)) { s = syntax[i]; } advance(); } else if (nexttoken.id === '(number)') { i = nexttoken.value.toString(); advance(); } else { error("Expected '{a}' and instead saw '{b}'.", nexttoken, '}', nexttoken.value); } } if (seen[i] === true) { warning("Duplicate member '{a}'.", nexttoken, i); } seen[i] = true; countMember(i); advance(':'); nonadjacent(token, nexttoken); parse(10); if (nexttoken.id === ',') { adjacent(token, nexttoken); advance(','); if (nexttoken.id === ',' || nexttoken.id === '}') { warning("Extra comma.", token); } nonadjacent(token, nexttoken); } else { break; } } if (b) { indent -= option.indent; indentation(); } advance('}', this); return; }; x.fud = function () { error("Expected to see a statement and instead saw a block.", token); }; }(delim('{'))); function varstatement(prefix) { // JavaScript does not have block scope. It only has function scope. So, // declaring a variable in a block can have unexpected consequences. if (funct['(onevar)'] && option.onevar) { warning("Too many var statements."); } else if (!funct['(global)']) { funct['(onevar)'] = true; } for (;;) { nonadjacent(token, nexttoken); addlabel(identifier(), 'unused'); if (prefix) { return; } if (nexttoken.id === '=') { nonadjacent(token, nexttoken); advance('='); nonadjacent(token, nexttoken); if (peek(0).id === '=') { error("Variable {a} was not declared correctly.", nexttoken, nexttoken.value); } parse(20); } if (nexttoken.id !== ',') { return; } adjacent(token, nexttoken); advance(','); nonadjacent(token, nexttoken); } } stmt('var', varstatement); stmt('new', function () { error("'new' should not be used as a statement."); }); function functionparams() { var i, t = nexttoken, p = []; advance('('); nospace(); if (nexttoken.id === ')') { advance(')'); nospace(prevtoken, token); return; } for (;;) { i = identifier(); p.push(i); addlabel(i, 'parameter'); if (nexttoken.id === ',') { advance(','); nonadjacent(token, nexttoken); } else { advance(')', t); nospace(prevtoken, token); return p.join(', '); } } } function doFunction(i) { var s = scope; scope = Object.create(s); funct = { '(name)' : i || '"' + anonname + '"', '(line)' : nexttoken.line + 1, '(context)' : funct, '(breakage)': 0, '(loopage)' : 0, '(scope)' : scope }; token.funct = funct; functions.push(funct); if (i) { addlabel(i, 'function'); } funct['(params)'] = functionparams(); block(false); scope = s; funct = funct['(context)']; } blockstmt('function', function () { if (inblock) { warning( "Function statements cannot be placed in blocks. Use a function expression or move the statement to the top of the outer function.", token); } var i = identifier(); adjacent(token, nexttoken); addlabel(i, 'unused'); doFunction(i); if (nexttoken.id === '(' && nexttoken.line === token.line) { error( "Function statements are not invocable. Wrap the whole function invocation in parens."); } }); prefix('function', function () { var i = optionalidentifier(); if (i) { adjacent(token, nexttoken); } else { nonadjacent(token, nexttoken); } doFunction(i); if (funct['(loopage)'] && nexttoken.id !== '(') { warning("Be careful when making functions within a loop. Consider putting the function in a closure."); } return this; }); blockstmt('if', function () { var t = nexttoken; advance('('); nonadjacent(this, t); nospace(); parse(20); if (nexttoken.id === '=') { warning("Expected a conditional expression and instead saw an assignment."); advance('='); parse(20); } advance(')', t); nospace(prevtoken, token); block(true); if (nexttoken.id === 'else') { nonadjacent(token, nexttoken); advance('else'); if (nexttoken.id === 'if' || nexttoken.id === 'switch') { statement(true); } else { block(true); } } return this; }); blockstmt('try', function () { var b, e, s; if (option.adsafe) { warning("ADsafe try violation.", this); } block(false); if (nexttoken.id === 'catch') { advance('catch'); nonadjacent(token, nexttoken); advance('('); s = scope; scope = Object.create(s); e = nexttoken.value; if (nexttoken.type !== '(identifier)') { warning("Expected an identifier and instead saw '{a}'.", nexttoken, e); } else { addlabel(e, 'exception'); } advance(); advance(')'); block(false); b = true; scope = s; } if (nexttoken.id === 'finally') { advance('finally'); block(false); return; } else if (!b) { error("Expected '{a}' and instead saw '{b}'.", nexttoken, 'catch', nexttoken.value); } }); blockstmt('while', function () { var t = nexttoken; funct['(breakage)'] += 1; funct['(loopage)'] += 1; advance('('); nonadjacent(this, t); nospace(); parse(20); if (nexttoken.id === '=') { warning("Expected a conditional expression and instead saw an assignment."); advance('='); parse(20); } advance(')', t); nospace(prevtoken, token); block(true); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; }).labelled = true; reserve('with'); blockstmt('switch', function () { var t = nexttoken, g = false; funct['(breakage)'] += 1; advance('('); nonadjacent(this, t); nospace(); this.condition = parse(20); advance(')', t); nospace(prevtoken, token); nonadjacent(token, nexttoken); t = nexttoken; advance('{'); nonadjacent(token, nexttoken); indent += option.indent; this.cases = []; for (;;) { switch (nexttoken.id) { case 'case': switch (funct['(verb)']) { case 'break': case 'case': case 'continue': case 'return': case 'switch': case 'throw': break; default: warning( "Expected a 'break' statement before 'case'.", token); } indentation(-option.indent); advance('case'); this.cases.push(parse(20)); g = true; advance(':'); funct['(verb)'] = 'case'; break; case 'default': switch (funct['(verb)']) { case 'break': case 'continue': case 'return': case 'throw': break; default: warning( "Expected a 'break' statement before 'default'.", token); } indentation(-option.indent); advance('default'); g = true; advance(':'); break; case '}': indent -= option.indent; indentation(); advance('}', t); if (this.cases.length === 1 || this.condition.id === 'true' || this.condition.id === 'false') { warning("This 'switch' should be an 'if'.", this); } funct['(breakage)'] -= 1; funct['(verb)'] = undefined; return; case '(end)': error("Missing '{a}'.", nexttoken, '}'); return; default: if (g) { switch (token.id) { case ',': error("Each value should have its own case label."); return; case ':': statements(); break; default: error("Missing ':' on a case clause.", token); } } else { error("Expected '{a}' and instead saw '{b}'.", nexttoken, 'case', nexttoken.value); } } } }).labelled = true; stmt('debugger', function () { if (!option.debug) { warning("All 'debugger' statements should be removed."); } }); stmt('do', function () { funct['(breakage)'] += 1; funct['(loopage)'] += 1; block(true); advance('while'); var t = nexttoken; nonadjacent(token, t); advance('('); nospace(); parse(20); if (nexttoken.id === '=') { warning("Expected a conditional expression and instead saw an assignment."); advance('='); parse(20); } advance(')', t); nospace(prevtoken, token); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; }).labelled = true; blockstmt('for', function () { var s, t = nexttoken; funct['(breakage)'] += 1; funct['(loopage)'] += 1; advance('('); nonadjacent(this, t); nospace(); if (peek(nexttoken.id === 'var' ? 1 : 0).id === 'in') { if (nexttoken.id === 'var') { advance('var'); varstatement(true); } else { advance(); } advance('in'); parse(20); advance(')', t); s = block(true); if (!option.forin && (s.length > 1 || typeof s[0] !== 'object' || s[0].value !== 'if')) { warning("The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.", this); } funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; } else { if (nexttoken.id !== ';') { if (nexttoken.id === 'var') { advance('var'); varstatement(); } else { for (;;) { parse(0, 'for'); if (nexttoken.id !== ',') { break; } advance(','); } } } advance(';'); if (nexttoken.id !== ';') { parse(20); if (nexttoken.id === '=') { warning("Expected a conditional expression and instead saw an assignment."); advance('='); parse(20); } } advance(';'); if (nexttoken.id === ';') { error("Expected '{a}' and instead saw '{b}'.", nexttoken, ')', ';'); } if (nexttoken.id !== ')') { for (;;) { parse(0, 'for'); if (nexttoken.id !== ',') { break; } advance(','); } } advance(')', t); nospace(prevtoken, token); block(true); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; } }).labelled = true; stmt('break', function () { var v = nexttoken.value; if (funct['(breakage)'] === 0) { warning("Unexpected '{a}'.", nexttoken, this.value); } nolinebreak(this); if (nexttoken.id !== ';') { if (token.line === nexttoken.line) { if (funct[v] !== 'label') { warning("'{a}' is not a statement label.", nexttoken, v); } else if (scope[v] !== funct) { warning("'{a}' is out of scope.", nexttoken, v); } advance(); } } reachable('break'); }); stmt('continue', function () { var v = nexttoken.value; if (funct['(breakage)'] === 0) { warning("Unexpected '{a}'.", nexttoken, this.value); } nolinebreak(this); if (nexttoken.id !== ';') { if (token.line === nexttoken.line) { if (funct[v] !== 'label') { warning("'{a}' is not a statement label.", nexttoken, v); } else if (scope[v] !== funct) { warning("'{a}' is out of scope.", nexttoken, v); } advance(); } } reachable('continue'); }); stmt('return', function () { nolinebreak(this); if (nexttoken.id === '(regexp)') { warning("Wrap the /regexp/ literal in parens to disambiguate the slash operator."); } if (nexttoken.id !== ';' && !nexttoken.reach) { nonadjacent(token, nexttoken); parse(20); } reachable('return'); }); stmt('throw', function () { nolinebreak(this); nonadjacent(token, nexttoken); parse(20); reachable('throw'); }); reserve('void'); // Superfluous reserved words reserve('class'); reserve('const'); reserve('enum'); reserve('export'); reserve('extends'); reserve('float'); reserve('goto'); reserve('import'); reserve('let'); reserve('super'); function jsonValue() { function jsonObject() { var t = nexttoken; advance('{'); if (nexttoken.id !== '}') { for (;;) { if (nexttoken.id === '(end)') { error("Missing '}' to match '{' from line {a}.", nexttoken, t.line + 1); } else if (nexttoken.id === '}') { warning("Unexpected comma.", token); break; } else if (nexttoken.id === ',') { error("Unexpected comma.", nexttoken); } else if (nexttoken.id !== '(string)') { warning("Expected a string and instead saw {a}.", nexttoken, nexttoken.value); } advance(); advance(':'); jsonValue(); if (nexttoken.id !== ',') { break; } advance(','); } } advance('}'); } function jsonArray() { var t = nexttoken; advance('['); if (nexttoken.id !== ']') { for (;;) { if (nexttoken.id === '(end)') { error("Missing ']' to match '[' from line {a}.", nexttoken, t.line + 1); } else if (nexttoken.id === ']') { warning("Unexpected comma.", token); break; } else if (nexttoken.id === ',') { error("Unexpected comma.", nexttoken); } jsonValue(); if (nexttoken.id !== ',') { break; } advance(','); } } advance(']'); } switch (nexttoken.id) { case '{': jsonObject(); break; case '[': jsonArray(); break; case 'true': case 'false': case 'null': case '(number)': case '(string)': advance(); break; case '-': advance('-'); if (token.character !== nexttoken.from) { warning("Unexpected space after '-'.", token); } adjacent(token, nexttoken); advance('(number)'); break; default: error("Expected a JSON value.", nexttoken); } } // The actual JSLINT function itself. var itself = function (s, o) { var a, i; JSLINT.errors = []; predefined = Object.create(standard); if (o) { a = o.predef; if (a instanceof Array) { for (i = 0; i < a.length; i += 1) { predefined[a[i]] = true; } } if (o.adsafe) { o.safe = true; } if (o.safe) { o.browser = false; o.css = false; o.debug = false; o.eqeqeq = true; o.evil = false; o.forin = false; o.nomen = true; o.on = false; o.rhino = false; o.safe = true; o.sidebar = false; o.strict = true; o.sub = false; o.undef = true; o.widget = false; predefined.Date = false; predefined['eval'] = false; predefined.Function = false; predefined.Object = false; predefined.ADSAFE = true; predefined.lib = true; } option = o; } else { option = {}; } option.indent = option.indent || 4; adsafe_id = ''; adsafe_may = false; adsafe_went = false; approved = {}; if (option.approved) { for (i = 0; i < option.approved.length; i += 1) { approved[option.approved[i]] = option.approved[i]; } } approved.test = 'test'; /////////////////////////////////////// tab = ''; for (i = 0; i < option.indent; i += 1) { tab += ' '; } indent = 0; global = Object.create(predefined); scope = global; funct = { '(global)': true, '(name)': '(global)', '(scope)': scope, '(breakage)': 0, '(loopage)': 0 }; functions = []; ids = {}; urls = []; src = false; xmode = false; stack = null; member = {}; membersOnly = null; implied = {}; inblock = false; lookahead = []; jsonmode = false; warnings = 0; lex.init(s); prereg = true; prevtoken = token = nexttoken = syntax['(begin)']; assume(); try { advance(); if (nexttoken.value.charAt(0) === '<') { html(); if (option.adsafe && !adsafe_went) { warning("ADsafe violation: Missing ADSAFE.go.", this); } } else { switch (nexttoken.id) { case '{': case '[': option.laxbreak = true; jsonmode = true; jsonValue(); break; case '@': case '*': case '#': case '.': case ':': xmode = 'style'; advance(); if (token.id !== '@' || !nexttoken.identifier || nexttoken.value !== 'charset') { error('A css file should begin with @charset "UTF-8";'); } advance(); if (nexttoken.type !== '(string)' && nexttoken.value !== 'UTF-8') { error('A css file should begin with @charset "UTF-8";'); } advance(); advance(';'); styles(); break; default: if (option.adsafe && option.fragment) { warning("ADsafe violation.", this); } statements('lib'); } } advance('(end)'); } catch (e) { if (e) { JSLINT.errors.push({ reason : e.message, line : e.line || nexttoken.line, character : e.character || nexttoken.from }, null); } } return JSLINT.errors.length === 0; }; function to_array(o) { var a = [], k; for (k in o) { if (o.hasOwnProperty(k)) { a.push(k); } } return a; } // Report generator. itself.report = function (option, sep) { var a = [], c, e, f, i, k, l, m = '', n, o = [], s, v, cl, ex, va, un, ou, gl, la; function detail(h, s, sep) { if (s.length) { o.push('<div><i>' + h + '</i> ' + s.sort().join(sep || ', ') + '</div>'); } } s = to_array(implied); k = JSLINT.errors.length; if (k || s.length > 0) { o.push('<div id=errors><i>Error:</i>'); if (s.length > 0) { s.sort(); for (i = 0; i < s.length; i += 1) { s[i] = '<code>' + s[i] + '</code>&nbsp;<i>' + implied[s[i]].join(' ') + '</i>'; } o.push('<p><i>Implied global:</i> ' + s.join(', ') + '</p>'); c = true; } for (i = 0; i < k; i += 1) { c = JSLINT.errors[i]; if (c) { e = c.evidence || ''; o.push('<p>Problem' + (isFinite(c.line) ? ' at line ' + (c.line + 1) + ' character ' + (c.character + 1) : '') + ': ' + c.reason.entityify() + '</p><p class=evidence>' + (e && (e.length > 80 ? e.slice(0, 77) + '...' : e).entityify()) + '</p>'); } } o.push('</div>'); if (!c) { return o.join(''); } } if (!option) { o.push('<br><div id=functions>'); if (urls.length > 0) { detail("URLs<br>", urls, '<br>'); } s = to_array(scope); if (s.length === 0) { if (jsonmode) { if (k === 0) { o.push('<p>JSON: good.</p>'); } else { o.push('<p>JSON: bad.</p>'); } } else { o.push('<div><i>No new global variables introduced.</i></div>'); } } else { o.push('<div><i>Global</i> ' + s.sort().join(', ') + '</div>'); } for (i = 0; i < functions.length; i += 1) { f = functions[i]; cl = []; ex = []; va = []; un = []; ou = []; gl = []; la = []; for (k in f) { if (f.hasOwnProperty(k) && k.charAt(0) !== '(') { v = f[k]; switch (v) { case 'closure': cl.push(k); break; case 'exception': ex.push(k); break; case 'var': va.push(k); break; case 'unused': un.push(k); break; case 'label': la.push(k); break; case 'outer': ou.push(k); break; case true: gl.push(k); break; } } } o.push('<br><div class=function><i>' + f['(line)'] + '</i> ' + (f['(name)'] || '') + '(' + (f['(params)'] || '') + ')</div>'); detail('Closure', cl); detail('Variable', va); detail('Exception', ex); detail('Outer', ou); detail('Global', gl); detail('<big><b>Unused</b></big>', un); detail('Label', la); } a = []; for (k in member) { if (typeof member[k] === 'number') { a.push(k); } } if (a.length) { a = a.sort(); m = '<br><pre>/*members '; l = 10; for (i = 0; i < a.length; i += 1) { k = a[i]; n = k.name(); if (l + n.length > 72) { o.push(m + '<br>'); m = ' '; l = 1; } l += n.length + 2; if (member[k] === 1) { n = '<i>' + n + '</i>'; } if (i < a.length - 1) { n += ', '; } m += n; } o.push(m + '<br>*/</pre>'); } o.push('</div>'); } return o.join(''); }; return itself; }());
(function () { angular.module('travelApp', ['toursApp']) .service('dateParse', function () { this.myDateParse = function (value) { var pattern = /Date\(([^)]+)\)/; var results = pattern.exec(value); var dt = new Date(parseFloat(results[1])); return dt; } }) .filter('myDateFormat', [ 'dateParse', function (dateParse) { return function (x) { return dateParse.myDateParse(x); }; } ]); })();
import getDevTool from './devtool' import getTarget from './target' import getEntry from './entry' import getOutput from './output' import getResolve from './resolve' import getResolveLoader from './resolveLoader' import getModule from './module' import getExternals from './externals' import getPlugins from './plugins' import getPostcss from './postcss' import getNode from './node' export default function make(name) { if(typeof name !== 'string') throw new Error('Name is required.') return { name , context: __dirname , cache: true , target: getTarget(name) , devtool: getDevTool(name) , entry: getEntry(name) , output: getOutput(name) , resolve: getResolve(name) , resolveLoader: getResolveLoader(name) , module: getModule(name) , externals: getExternals(name) , plugins: getPlugins(name) , node: getNode(name) , postcss: getPostcss(name) } }
import Ember from 'ember'; export default Ember.Controller.extend({ shortcuts: [ { title: "Task Editor", combos: [ { set: [["ctl","sh","del"]], description: "delete focused task" }, { set: [["ctl","sh","ent"], ["ctl","+"]], description: "create new task and edit it" }, { set: [["ctl","sh","h"], ["ctl", "sh", "⥢"],["esc"]], description: "focus left into task list" }, ] }, { title: "Task List", combos: [ { set: [["down"], ["j"]], description: "move down" }, { set: [["up"], ["k"]], description: "move up" }, { set: [["o"], ["e"], ["ent"], ["space"]], description: "toggle task in editor" }, { set: [["l"], ["⥤"]], description: "display task in editor" }, { set: [["ctl", "sh", "l"],["ctl", "sh", "⥤"]], description: "display task in editor and edit it" }, { set: [["h"], ["⥢"]], description: "hide task from editor" }, { set: [["ctl","sh","del"]], description: "delete focused task" }, { set: [["ctl","sh","ent"], ["ctl","sh","="]], description: "create new task and edit it" }, ] }, ] });
/** * @fileoverview Rule to flag on declaring variables already declared in the outer scope * @author Ilya Volodin */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ let astUtils = require("../ast-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "disallow `var` declarations from shadowing variables in the outer scope", category: "Variables", recommended: false }, schema: [ { type: "object", properties: { builtinGlobals: {type: "boolean"}, hoist: {enum: ["all", "functions", "never"]}, allow: { type: "array", items: { type: "string" } } }, additionalProperties: false } ] }, create: function(context) { let options = { builtinGlobals: Boolean(context.options[0] && context.options[0].builtinGlobals), hoist: (context.options[0] && context.options[0].hoist) || "functions", allow: (context.options[0] && context.options[0].allow) || [] }; /** * Check if variable name is allowed. * * @param {ASTNode} variable The variable to check. * @returns {boolean} Whether or not the variable name is allowed. */ function isAllowed(variable) { return options.allow.indexOf(variable.name) !== -1; } /** * Checks if a variable of the class name in the class scope of ClassDeclaration. * * ClassDeclaration creates two variables of its name into its outer scope and its class scope. * So we should ignore the variable in the class scope. * * @param {Object} variable The variable to check. * @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration. */ function isDuplicatedClassNameVariable(variable) { let block = variable.scope.block; return block.type === "ClassDeclaration" && block.id === variable.identifiers[0]; } /** * Checks if a variable is inside the initializer of scopeVar. * * To avoid reporting at declarations such as `var a = function a() {};`. * But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`. * * @param {Object} variable The variable to check. * @param {Object} scopeVar The scope variable to look for. * @returns {boolean} Whether or not the variable is inside initializer of scopeVar. */ function isOnInitializer(variable, scopeVar) { let outerScope = scopeVar.scope; let outerDef = scopeVar.defs[0]; let outer = outerDef && outerDef.parent && outerDef.parent.range; let innerScope = variable.scope; let innerDef = variable.defs[0]; let inner = innerDef && innerDef.name.range; return ( outer && inner && outer[0] < inner[0] && inner[1] < outer[1] && ((innerDef.type === "FunctionName" && innerDef.node.type === "FunctionExpression") || innerDef.node.type === "ClassExpression") && outerScope === innerScope.upper ); } /** * Get a range of a variable's identifier node. * @param {Object} variable The variable to get. * @returns {Array|undefined} The range of the variable's identifier node. */ function getNameRange(variable) { let def = variable.defs[0]; return def && def.name.range; } /** * Checks if a variable is in TDZ of scopeVar. * @param {Object} variable The variable to check. * @param {Object} scopeVar The variable of TDZ. * @returns {boolean} Whether or not the variable is in TDZ of scopeVar. */ function isInTdz(variable, scopeVar) { let outerDef = scopeVar.defs[0]; let inner = getNameRange(variable); let outer = getNameRange(scopeVar); return ( inner && outer && inner[1] < outer[0] && // Excepts FunctionDeclaration if is {"hoist":"function"}. (options.hoist !== "functions" || !outerDef || outerDef.node.type !== "FunctionDeclaration") ); } /** * Checks the current context for shadowed variables. * @param {Scope} scope - Fixme * @returns {void} */ function checkForShadows(scope) { let variables = scope.variables; for (let i = 0; i < variables.length; ++i) { let variable = variables[i]; // Skips "arguments" or variables of a class name in the class scope of ClassDeclaration. if (variable.identifiers.length === 0 || isDuplicatedClassNameVariable(variable) || isAllowed(variable) ) { continue; } // Gets shadowed variable. let shadowed = astUtils.getVariableByName(scope.upper, variable.name); if (shadowed && (shadowed.identifiers.length > 0 || (options.builtinGlobals && "writeable" in shadowed)) && !isOnInitializer(variable, shadowed) && !(options.hoist !== "all" && isInTdz(variable, shadowed)) ) { context.report({ node: variable.identifiers[0], message: "'{{name}}' is already declared in the upper scope.", data: variable }); } } } return { "Program:exit": function() { let globalScope = context.getScope(); let stack = globalScope.childScopes.slice(); let scope; while (stack.length) { scope = stack.pop(); stack.push.apply(stack, scope.childScopes); checkForShadows(scope); } } }; } };
module.exports = { framework: 'qunit', test_page: 'tests/index.html?hidepassed', disable_watching: true, launch_in_ci: [ 'Chrome' ], launch_in_dev: [ 'Chrome' ], browser_args: { Chrome: { mode: 'ci', args: [ // --no-sandbox is needed when running Chrome inside a container process.env.TRAVIS ? '--no-sandbox' : null, '--disable-gpu', '--headless', '--no-sandbox', '--remote-debugging-port=9222', '--window-size=1440,900' ].filter(Boolean) } } };
/* * The MIT License * Copyright (c) 2014-2016 Nick Guletskii * * 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. */ import Util from "oolutil"; import { property as _property, omit as _omit } from "lodash"; import { services } from "app"; class UserService { /* @ngInject*/ constructor($http, $q, Upload, $rootScope) { this.$http = $http; this.$q = $q; this.$rootScope = $rootScope; this.Upload = Upload; } getCurrentUser() { return this.$http.get("/api/user/personalInfo", {}) .then(_property("data")); } changePassword(passwordObj, userId) { const passwordPatchUrl = !userId ? "/api/user/changePassword" : `/api/admin/user/${userId}/changePassword`; return this.$http({ method: "PATCH", url: passwordPatchUrl, data: _omit(Util.emptyToNull(passwordObj), "passwordConfirmation") }) .then(_property("data")); } countPendingUsers() { return this.$http.get("/api/admin/pendingUsersCount") .then(_property("data")); } getPendingUsersPage(page) { return this.$http.get("/api/admin/pendingUsers", { params: { page } }) .then(_property("data")); } countUsers() { return this.$http.get("/api/admin/usersCount") .then(_property("data")); } getUsersPage(page) { return this.$http.get("/api/admin/users", { params: { page } }) .then(_property("data")); } getUserById(id) { return this.$http.get("/api/user", { params: { id } }) .then(_property("data")); } approveUsers(users) { return this.$http.post("/api/admin/users/approve", users) .then(_property("data")); } deleteUsers(users) { return this.$http.post("/api/admin/users/deleteUsers", users) .then(_property("data")); } countArchiveUsers() { return this.$http.get("/api/archive/rankCount") .then(_property("data")); } getArchiveRankPage(page) { return this.$http.get("/api/archive/rank", { params: { page } }) .then(_property("data")); } addUserToGroup(groupId, username) { const deferred = this.$q.defer(); const formData = new FormData(); formData.append("username", username); this.Upload.http({ method: "POST", url: `/api/group/${groupId}/addUser`, headers: { "Content-Type": undefined, "X-Auth-Token": this.$rootScope.authToken }, data: formData, transformRequest: angular.identity }) .success((data) => { deferred.resolve(data); }); return deferred.promise; } removeUserFromGroup(groupId, userId) { return this.$http.delete(`/api/group/${groupId}/removeUser`, { params: { user: userId } }) .then(_property("data")); } } services.service("UserService", UserService);
define(['view', 'class'], function(View, clazz) { function Overlay(el, options) { options = options || {}; Overlay.super_.call(this, el, options); this.closable = options.closable; this._autoRemove = options.autoRemove !== undefined ? options.autoRemove : true; var self = this; if (this.closable) { this.el.on('click', function() { self.hide(); return false; }); } } clazz.inherits(Overlay, View); Overlay.prototype.show = function() { this.emit('show'); this.el.appendTo(document.body); this.el.removeClass('hide'); return this; } Overlay.prototype.hide = function() { this.emit('hide'); this.el.addClass('hide'); if (this._autoRemove) { var self = this; setTimeout(function() { self.remove(); self.dispose(); }, 10); } return this; } return Overlay; });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var androidUnlock = exports.androidUnlock = { "viewBox": "0 0 512 512", "children": [{ "name": "path", "attribs": { "d": "M376,186h-20v-40c0-55-45-100-100-100S156,91,156,146h37.998c0-34.004,28.003-62.002,62.002-62.002\r\n\tc34.004,0,62.002,27.998,62.002,62.002H318v40H136c-22.002,0-40,17.998-40,40v200c0,22.002,17.998,40,40,40h240\r\n\tc22.002,0,40-17.998,40-40V226C416,203.998,398.002,186,376,186z M256,368c-22.002,0-40-17.998-40-40s17.998-40,40-40\r\n\ts40,17.998,40,40S278.002,368,256,368z" }, "children": [] }] };
/* this is all example code which should be changed; see query.js for how it works */ authUrl = "http://importio-signedserver.herokuapp.com/"; reEx.push(/\/_source$/); /* //change doReady() to auto-query on document ready var doReadyOrg = doReady; doReady = function() { doReadyOrg(); doQuery();//query on ready } */ //change doReady() to add autocomplete-related events // http://jqueryui.com/autocomplete/ http://api.jqueryui.com/autocomplete/ var acField;//autocomplete data field var acSel;//autocomplete input selector var acsSel = "#autocomplete-spin";//autocomplete spinner selector var cache = {};//autocomplete cache var termCur = "";//autocomplete current term var doReadyOrg = doReady; doReady = function() { doReadyOrg(); $(acSel) .focus() .bind("keydown", function(event) { // http://api.jqueryui.com/jQuery.ui.keyCode/ switch(event.keyCode) { //don't fire autocomplete on certain keys case $.ui.keyCode.LEFT: case $.ui.keyCode.RIGHT: event.stopImmediatePropagation(); return true; break; //submit form on enter case $.ui.keyCode.ENTER: doQuery(); $(this).autocomplete("close"); break; } }) .autocomplete({ minLength: 3, source: function(request, response) { var term = request.term.replace(/[^\w\s]/gi, '').trim().toUpperCase();//replace all but "words" [A-Za-z0-9_] & whitespaces if (term in cache) { doneCompleteCallbackStop(); response(cache[term]); return; } termCur = term; if (spinOpts) { $(acsSel).spin(spinOpts); } cache[term] = []; doComplete(term); response(cache[term]);//send empty for now } }); }; function doComplete(term) { doQueryMy(); var qObjComplete = jQuery.extend({}, qObj);//copy to new obj qObjComplete.maxPages = 1; importio.query(qObjComplete, { "data": function(data) { dataCompleteCallback(data, term); }, "done": function(data) { doneCompleteCallback(data, term); } } ); } var dataCompleteCallback = function(data, term) { console.log("Data received", data); for (var i = 0; i < data.length; i++) { var d = data[i]; var c = d.data[acField]; if (typeof filterComplete === 'function') { c = filterComplete(c); } c = c.trim(); if (!c) { continue; } cache[term].push(c); } } var doneCompleteCallback = function(data, term) { console.log("Done, all data:", data); console.log("cache:", cache); // http://stackoverflow.com/questions/16747798/delete-duplicate-elements-from-an-array cache[term] = cache[term].filter( function(elem, index, self) { return index == self.indexOf(elem); }); if (termCur != term) { return; } doneCompleteCallbackStop(); $(acSel).trigger("keydown"); } var doneCompleteCallbackStop = function() { termCur = ""; if (spinOpts) { $(acsSel).spin(false); } } /* Query for tile Store Locators */ fFields.push({id: "postcode", html: '<input id="postcode" type="text" value="EC2M 4TP" />'}); fFields.push({id: "autocomplete-spin", html: '<span id="autocomplete-spin"></span>'}); fFields.push({id: "submit", html: '<button id="submit" onclick="doQuery();">Query</button>'}); acField = "address"; var filterComplete = function(val) { if (val.indexOf(", ") == -1) { return ""; } return val.split(", ").pop(); } acSel = "#postcode"; qObj.connectorGuids = [ "8f628f9d-b564-4888-bc99-1fb54b2df7df", "7290b98f-5bc0-4055-a5df-d7639382c9c3", "14d71ff7-b58f-4b37-bb5b-e2475bdb6eb9", "9c99f396-2b8c-41e0-9799-38b039fe19cc", "a0087993-5673-4d62-a5ae-62c67c1bcc40" ]; var doQueryMy = function() { qObj.input = { "postcode": $("#postcode").val() }; } /* Here's some other example code for a completely different API fFields.push({id: "title", html: '<input id="title" type="text" value="harry potter" />'}); fFields.push({id: "autocomplete-spin", html: '<span id="autocomplete-spin"></span>'}); fFields.push({id: "submit", html: '<button id="submit" onclick="doQuery();">Query</button>'}); acField = "title"; acSel = "#title"; filters["image"] = function(val, row) { return '<a href="' + val + '" target="_blank">' + val + '</a>'; } qObj.connectorGuids = [ "ABC" ]; var doQueryMy = function() { qObj.input = { "search": $("#title").val() }; } */ /* Here's some other example code for a completely different API colNames = ["ranking", "title", "artist", "album", "peak_pos", "last_pos", "weeks", "image", "spotify", "rdio", "video"]; filters["title"] = function(val, row) { return "<b>" + val + "</b>"; } filters["video"] = function(val, row) { if (val.substring(0, 7) != "http://") { return val; } return '<a href="' + val + '" target="_blank">' + val + '</a>'; } doQuery = function() { doQueryPre(); for (var page = 0; page < 10; page++) { importio.query({ "connectorGuids": [ "XYZ" ], "input": { "webpage/url": "http://www.billboard.com/charts/hot-100?page=" + page } }, { "data": dataCallback, "done": doneCallback }); } } */
function flashMessage(type, message) { var flashContainer = $('#flash-message'); var flash = null; if (message.title) { flash = $('<div class="alert alert-block alert-' + type + '"><h4 class="alert-heading">' + message.title + '</h4><p>' + message.message + '</p></div>'); } else { flash = $('<div class="alert alert-block alert-' + type + '"><p>' + message + '</p></div>'); } flashContainer.append(flash); setupFlash.call(flash); } function setupFlash() { var flash = $(this); if (flash.html() != '') { var timeout = flash.data('timeout'); if (timeout) { clearTimeout(timeout); } if (!flash.hasClass('alert-danger')) { flash.data('timeout', setTimeout(function() { flash.fadeOut(400, function() { $(this).remove(); }); }, 5000)); } flash.fadeIn(); } } function showFlashMessage() { var flashes = $('#flash-message .alert'); flashes.each(setupFlash); } function initFlashMessage(){ $('#flash-message').on('click', '.alert', function() { $(this).fadeOut(400, function() { $(this).remove(); }) ; }); showFlashMessage(); }
var curl = require('./lib/curl'); var clean = require('./lib/extract'); curl('http://blog.rainy.im/2015/09/02/web-content-and-main-image-extractor/', function (content) { console.log('fetch done'); clean(content, { blockSize: 3 }); });
const fs = require('fs') const Log = require('log') const browserify = require('browserify') const babelify = require('babelify') const errorify = require('errorify') const cssNext = require('postcss-cssnext') const cssModulesify = require('css-modulesify') const exec = require('child_process').exec const log = new Log('info') const fileMap = { 'index.js': 'main' } const files = Object.keys(fileMap) const srcFolder = `${__dirname}/../demo` const buildFolder = `${__dirname}/../docs` const outFiles = files.map(file => { return `${buildFolder}/${fileMap[file]}.js ${buildFolder}/${fileMap[file]}.css` }).join(' ') exec(`rm -rf ${outFiles} ${buildFolder}/index.html`, (err) => { if (err) { throw err } exec(`cp ${srcFolder}/index.html ${buildFolder}/index.html`, (error) => { if (error) { throw error } }) files.forEach(file => { const inFile = `${srcFolder}/${file}` const outFile = `${buildFolder}/${fileMap[file]}` const b = browserify({ entries: [inFile], plugin: [ errorify ], transform: [ [ babelify, { presets: [ 'es2015', 'stage-0', 'react' ] }] ] }) b.plugin(cssModulesify, { output: `${outFile}.css`, after: [cssNext()] }) function bundle () { b.bundle().pipe(fs.createWriteStream(`${outFile}.js`)) } b.on('log', message => log.info(message)) b.on('error', message => log.error(message)) bundle() }) })
var style = document.createElement('p').style, prefixes = 'O ms Moz webkit'.split(' '), hasPrefix = /^(o|ms|moz|webkit)/, upper = /([A-Z])/g, memo = {}; function get(key) { return (key in memo) ? memo[key] : memo[key] = prefix(key); } function prefix(key) { var capitalizedKey = key.replace(/-([a-z])/g, function (s, match) { return match.toUpperCase(); }), i = prefixes.length, name; if (style[capitalizedKey] !== undefined) return capitalizedKey; capitalizedKey = capitalize(key); while (i--) { name = prefixes[i] + capitalizedKey; if (style[name] !== undefined) return name; } throw new Error('unable to prefix ' + key); } function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } function dashedPrefix(key) { var prefixedKey = get(key), upper = /([A-Z])/g; if (upper.test(prefixedKey)) { prefixedKey = (hasPrefix.test(prefixedKey) ? '-' : '') + prefixedKey.replace(upper, '-$1'); } return prefixedKey.toLowerCase(); } if (typeof module != 'undefined' && module.exports) { module.exports = get; module.exports.dash = dashedPrefix; } else { return get; }
'use strict'; var angular = require('angular'); var calendarUtils = require('calendar-utils'); angular .module('mwl.calendar') .controller('MwlCalendarHourListCtrl', function($scope, $document, moment, calendarHelper) { var vm = this; // source: http://stackoverflow.com/questions/13382516/getting-scroll-bar-width-using-javascript function getScrollbarWidth() { var outer = $document[0].createElement('div'); outer.style.visibility = 'hidden'; outer.style.width = '100px'; outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps $document[0].body.appendChild(outer); var widthNoScroll = outer.offsetWidth; // force scrollbars outer.style.overflow = 'scroll'; // add innerdiv var inner = $document[0].createElement('div'); inner.style.width = '100%'; outer.appendChild(inner); var widthWithScroll = inner.offsetWidth; // remove divs outer.parentNode.removeChild(outer); return widthNoScroll - widthWithScroll; } vm.scrollBarWidth = getScrollbarWidth(); function updateDays() { vm.dayViewSplit = parseInt(vm.dayViewSplit); var dayStart = (vm.dayViewStart || '00:00').split(':'); var dayEnd = (vm.dayViewEnd || '23:59').split(':'); vm.hourGrid = calendarUtils.getDayViewHourGrid({ viewDate: vm.view === 'week' ? moment(vm.viewDate).startOf('week').toDate() : moment(vm.viewDate).toDate(), hourSegments: 60 / vm.dayViewSplit, dayStart: { hour: dayStart[0], minute: dayStart[1] }, dayEnd: { hour: dayEnd[0], minute: dayEnd[1] } }); vm.hourGrid.forEach(function(hour) { hour.segments.forEach(function(segment) { segment.date = moment(segment.date); segment.nextSegmentDate = segment.date.clone().add(vm.dayViewSplit, 'minutes'); if (vm.view === 'week') { segment.days = []; for (var i = 0; i < 7; i++) { var day = { date: moment(segment.date).add(i, 'days') }; day.nextSegmentDate = day.date.clone().add(vm.dayViewSplit, 'minutes'); vm.cellModifier({calendarCell: day}); segment.days.push(day); } } else { vm.cellModifier({calendarCell: segment}); } }); }); } var originalLocale = moment.locale(); $scope.$on('calendar.refreshView', function() { if (originalLocale !== moment.locale()) { originalLocale = moment.locale(); updateDays(); } }); $scope.$watchGroup([ 'vm.dayViewStart', 'vm.dayViewEnd', 'vm.dayViewSplit', 'vm.viewDate' ], function() { updateDays(); }); vm.eventDropped = function(event, date) { var newStart = moment(date); var newEnd = calendarHelper.adjustEndDateFromStartDiff(event.startsAt, newStart, event.endsAt); vm.onEventTimesChanged({ calendarEvent: event, calendarDate: date, calendarNewEventStart: newStart.toDate(), calendarNewEventEnd: newEnd ? newEnd.toDate() : null }); }; vm.onDragSelectStart = function(date, dayIndex) { if (!vm.dateRangeSelect) { vm.dateRangeSelect = { active: true, startDate: date, endDate: date, dayIndex: dayIndex }; } }; vm.onDragSelectMove = function(date) { if (vm.dateRangeSelect) { vm.dateRangeSelect.endDate = date; } }; vm.onDragSelectEnd = function(date) { if (vm.dateRangeSelect) { vm.dateRangeSelect.endDate = date; if (vm.dateRangeSelect.endDate > vm.dateRangeSelect.startDate) { vm.onDateRangeSelect({ calendarRangeStartDate: vm.dateRangeSelect.startDate.toDate(), calendarRangeEndDate: vm.dateRangeSelect.endDate.toDate() }); } delete vm.dateRangeSelect; } }; }) .directive('mwlCalendarHourList', function() { return { restrict: 'E', template: '<div mwl-dynamic-directive-template name="calendarHourList" overrides="vm.customTemplateUrls"></div>', controller: 'MwlCalendarHourListCtrl as vm', scope: { viewDate: '=', dayViewStart: '=', dayViewEnd: '=', dayViewSplit: '=', dayWidth: '=?', onTimespanClick: '=', onDateRangeSelect: '=', onEventTimesChanged: '=', customTemplateUrls: '=?', cellModifier: '=', templateScope: '=', view: '@' }, bindToController: true }; });
'use strict'; describe('Controller: MainCtrl', function() { // load the controller's module beforeEach(module('actionatadistanceApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function($controller) { scope = {}; MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function() { expect(scope.awesomeThings.length).toBe(3); }); });
import React from 'react'; import PropTypes from 'prop-types'; import _get from 'lodash.get'; import _words from 'lodash.words'; import { VictoryAxis, VictoryBar, VictoryChart, VictoryTheme } from 'victory'; export class CrawlChart extends React.Component { constructor(props) { super(props); this.state = { data: [ {movie: 1, word_count: 0}, {movie: 2, word_count: 0}, {movie: 3, word_count: 0}, {movie: 4, word_count: 0}, {movie: 5, word_count: 0}, {movie: 6, word_count: 0}, {movie: 7, word_count: 0} ] }; } componentWillReceiveProps(nextProps) { let movieCrawls = nextProps.movies.map((m) => _get(m, 'opening_crawl', '')); let newState = { data: movieCrawls.map((c, i) => { return { movie: i+1, word_count: _words(c).length}; }) }; this.setState(newState); } render() { return ( <div> <h3>Opening Crawl Word Count</h3> <VictoryChart // adding the material theme provided with Victory animate={{duration: 500}} theme={VictoryTheme.material} domainPadding={20} > <VictoryAxis tickFormat={['Ep 1', 'Ep 2', 'Ep 3', 'Ep 4', 'Ep 5', 'Ep 6', 'Ep 7']} tickValues={[1, 2, 3, 4, 5, 6, 7]} /> <VictoryAxis dependentAxis domain={[0, 100]} tickFormat={(x) => (`${x}`)} /> <VictoryBar data={this.state.data} style={{ data: {fill: '#fe9901', width:12} }} labels={(d) => `${Math.ceil(d.y)}`} x="movie" y="word_count" /> </VictoryChart> </div> ); } } CrawlChart.propTypes = { movies: PropTypes.arrayOf( PropTypes.shape({ opening_crawl: PropTypes.string.isRequired, title: PropTypes.string }) ) };
// ES2015 사용을 위한 babel 모듈 호출 import 'babel-polyfill'; // 전역 변수 객체 호출 import globalConfig from './helpers/global-config'; // npm 모듈 호출 import mobileDetect from 'mobile-detect'; //import scroll from 'scroll'; //import ease from 'ease-component'; import detectScrollPageObj from 'scroll-doc'; // devTools 호출 import devTools from './devtools/dev-tools'; import mirror from './devtools/mirror'; import preview from './devtools/preview'; // 헬퍼 모듈 호출 import catchEventTarget from './helpers/catch-event-target'; //import clipboardFunc from './helpers/clipboard-function'; //import cloneObj from './helpers/clone-obj'; //import colorAdjust from './helpers/color-adjust'; //import delayEvent from './helpers/delay-event'; import index from './helpers/index'; //import parents from './helpers/parents'; //import readingZero from './helpers/reading-zero'; //import toggleBoolean from './helpers/toggle-boolean'; import modifier from './helpers/modifier'; //import splitSearch from '../../app_helpers/split-search'; // 프로젝트 모듈 호출 //import {socketFunc} from './project/socket'; //import * as kbs from './project/kbs'; // 전역변수 선언 let socket; document.addEventListener('DOMContentLoaded', () => { // 돔 로드완료 이벤트 const WIN = window, DOC = document, MD = new mobileDetect(WIN.navigator.userAgent), detectScrollPage = detectScrollPageObj(); if(MD.mobile()) console.log(`mobile DOM's been loaded`); else console.log(`DOM's been loaded`); DOC.addEventListener('click', (e) => { // 클릭 이벤트 버블링 const eventTarget = catchEventTarget(e.target || e.srcElement); console.log(eventTarget.target, eventTarget.findJsString); switch(eventTarget.findJsString) { case 'js-copy-link' : console.log(index(eventTarget.target)); scroll.top( detectScrollPage, 1000, { duration: 1000, ease: ease.inQuint }, function (error, scrollLeft) { } ); modifier( 'toggle', eventTarget.target, 'paging__elm--actived' ); break; default : return false; } }, false); WIN.addEventListener('load', () => { // 윈도우 로드완료 이벤트 if(MD.mobile()) console.log(`mobile WINDOW's been loaded`); else console.log(`WINDOW's been loaded`); // socket = io(); // socketFunc(socket); }); WIN.addEventListener('resize', () => { // 윈도우 리사이즈 이벤트 // delayEvent(/*second*/, /*func*/); }); WIN.addEventListener('keypress', (e) => { const pressedKeyCode = e.which; switch(pressedKeyCode) { case 0: // some Function break; default : return false; } }); DOC.addEventListener('wheel', (e) => { const eventTarget = catchEventTarget(e.target || e.srcElement); switch(eventTarget.findJsString) { case 'js-test': console.log(eventTarget.target); break; default : return false; } }, true); DOC.addEventListener('touchstart', (e) => { let touchObj = e.changedTouches[0]; }); DOC.addEventListener('touchmove', (e) => { let touchObj = e.changedTouches[0]; }); DOC.addEventListener('touchend', (e) => { let touchObj = e.changedTouches[0]; }); });
version https://git-lfs.github.com/spec/v1 oid sha256:0f924f0bd38d3dfb7ebc34016ec96c018aee7fb62e1cd562898fdeb85ca7d283 size 2234
!(function(){ var spg = require('./simple-password-generator.js'); console.log(spg.generate({ length : 3 })); })();
/* @flow */ /* ********************************************************** * File: tests/utils/dataStreams/graphBuffer.spec.js * * Brief: Provides a storage class for buffering data outputs * * Authors: Craig Cheney * * 2017.10.01 CC - Updated test suite for multi-device * 2017.09.28 CC - Document created * ********************************************************* */ import { getDeviceObj, resetStartTime, getStartTime, getLastTime, getDataPointDecimated, getDataIndex, logDataPoints, resetDataBuffer, getDataLength, getLastDataPointsDecimated, getDataSeries, getFullDataObj, getDataObjById } from '../../../app/utils/dataStreams/graphBuffer'; import { deviceIdFactory } from '../../factories/factories'; import { accDataFactory } from '../../factories/dataFactories'; import type { deviceObjT } from '../../../app/utils/dataStreams/graphBuffer'; /* Global IDs of devices */ const deviceId1 = deviceIdFactory(); const deviceId2 = deviceIdFactory(); const deviceId3 = deviceIdFactory(); /* Test Suite */ describe('graphBuffer.spec.js', () => { describe('getDeviceObj', () => { it('should create an empty device', () => { const deviceId = deviceIdFactory(); const deviceObj: deviceObjT = getDeviceObj(deviceId); expect(deviceObj.data).toEqual([]); expect(deviceObj.dataIndex).toBe(0); expect(deviceObj.startTime).toBeGreaterThan(0); expect(deviceObj.lastTime).toBe(deviceObj.startTime); }); }); describe('timing events', () => { describe('resetStartTime', () => { it('should set the start time, and last time', () => { const deviceId = deviceIdFactory(); const resetReturn = resetStartTime(deviceId); expect(resetReturn).toEqual(getStartTime(deviceId)); expect(resetReturn).toEqual(getLastTime(deviceId)); }); }); }); describe('data events', () => { beforeEach(() => { resetDataBuffer(deviceId1); resetDataBuffer(deviceId2); resetStartTime(deviceId1); resetStartTime(deviceId2); }); describe('resetDataBuffer', () => { it('should reset the buffer length', () => { const data = accDataFactory(); const num = logDataPoints(deviceId1, [data]); expect(num).toBe(1); expect(getDataLength(deviceId1)).toBe(1); expect(getDataIndex(deviceId1)).toBe(0); /* Get it back */ const dataReturned = getDataPointDecimated(deviceId1); expect(dataReturned).toEqual(data); expect(getDataLength(deviceId1)).toBe(1); expect(getDataIndex(deviceId1)).toBe(1); resetDataBuffer(deviceId1); expect(getDataLength(deviceId1)).toBe(0); expect(getDataIndex(deviceId1)).toBe(0); }); }); describe('logDataPoints', () => { it('should store an event', () => { const startTime = resetStartTime(deviceId1); const time = startTime + 1; const data = accDataFactory(['x'], time); /* Log the data point */ const num = logDataPoints(deviceId1, [data]); expect(num).toBe(1); const lastTime = getLastTime(deviceId1); expect(lastTime).toEqual(time); expect(lastTime).toEqual(startTime + 1); /* Retrieve the point */ const dataRetrieved = getDataPointDecimated(deviceId1); expect(dataRetrieved).toEqual(data); expect(getDataIndex(deviceId1)).toEqual(1); }); }); describe('getDataPointDecimated', () => { it('should return a decimated list', () => { /* Create the dummy data */ const data = []; const startTime = getStartTime(deviceId1); for (let i = 0; i <= 10; i++) { data.push(accDataFactory(['x'], startTime + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId1, data)).toEqual(11); /* Retrieve the decimated data */ const decimation = 100 / 30; expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[0]); expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[3]); expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[7]); expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[10]); }); it('should not increment an index if already beyond the length of the array', () => { /* Create the dummy data */ const data = []; const startTime = getStartTime(deviceId1); for (let i = 0; i <= 10; i++) { data.push(accDataFactory(['x'], startTime + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId1, data)).toEqual(11); /* Retrieve the decimated data */ const decimation = 5; expect(getDataIndex(deviceId1)).toBe(0); expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[0]); expect(getDataIndex(deviceId1)).toBe(5); expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[5]); expect(getDataIndex(deviceId1)).toBe(10); expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data[10]); expect(getDataIndex(deviceId1)).toBe(15); expect(getDataPointDecimated(deviceId1, decimation)).toBe(undefined); expect(getDataIndex(deviceId1)).toBe(15); }); }); describe('getLastDataPointDecimated', () => { it('should return the last element with no args', () => { /* Create the dummy data */ const data = []; const startTime = getStartTime(deviceId1); for (let i = 0; i < 20; i++) { data.push(accDataFactory(['x'], startTime + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId1, data)).toEqual(20); /* Get the last point */ const lastData = getLastDataPointsDecimated(deviceId1); expect(lastData[0]).toEqual(data[19]); }); it('should return N elements', () => { /* Create the dummy data */ const data = []; const startTime = getStartTime(deviceId1); for (let i = 0; i < 20; i++) { data.push(accDataFactory(['x'], startTime + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId1, data)).toEqual(20); /* Get the last point */ const lastData = getLastDataPointsDecimated(deviceId1, 5); expect(lastData.length).toBe(5); expect(lastData[0]).toEqual(data[15]); expect(lastData[1]).toEqual(data[16]); expect(lastData[2]).toEqual(data[17]); expect(lastData[3]).toEqual(data[18]); expect(lastData[4]).toEqual(data[19]); }); it('should not return more elements than allowed', () => { /* Create the dummy data */ const data = []; const startTime = getStartTime(deviceId1); for (let i = 0; i < 20; i++) { data.push(accDataFactory(['x'], startTime + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId1, data)).toEqual(20); /* Get the last point */ const lastData = getLastDataPointsDecimated(deviceId1, 5, 5); expect(lastData.length).toBe(4); expect(lastData[0]).toEqual(data[4]); expect(lastData[1]).toEqual(data[9]); expect(lastData[2]).toEqual(data[14]); expect(lastData[3]).toEqual(data[19]); }); it('should handle non-integer decimation', () => { /* Create the dummy data */ const data = []; const startTime = getStartTime(deviceId1); for (let i = 0; i < 11; i++) { data.push(accDataFactory(['x'], startTime + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId1, data)).toEqual(11); /* Get the last point */ const decimation = 10 / 3; const lastData = getLastDataPointsDecimated(deviceId1, 4, decimation); expect(lastData.length).toBe(4); expect(lastData[0]).toEqual(data[0]); expect(lastData[1]).toEqual(data[3]); expect(lastData[2]).toEqual(data[7]); expect(lastData[3]).toEqual(data[10]); }); it('should handle multiple devices', () => { /* Create the dummy data */ const data1 = []; const data2 = []; const startTime1 = getStartTime(deviceId1); const startTime2 = getStartTime(deviceId2); for (let i = 0; i <= 10; i++) { data1.push(accDataFactory(['x'], startTime1 + i)); data2.push(accDataFactory(['x'], startTime2 + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId1, data1)).toEqual(11); expect(logDataPoints(deviceId2, data2)).toEqual(11); /* Retrieve the decimated data */ const decimation = 100 / 30; expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data1[0]); expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data1[3]); expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data1[7]); expect(getDataPointDecimated(deviceId1, decimation)).toEqual(data1[10]); /* Device 2 */ expect(getDataPointDecimated(deviceId2, decimation)).toEqual(data2[0]); expect(getDataPointDecimated(deviceId2, decimation)).toEqual(data2[3]); expect(getDataPointDecimated(deviceId2, decimation)).toEqual(data2[7]); expect(getDataPointDecimated(deviceId2, decimation)).toEqual(data2[10]); }); }); describe('getDataSeries', () => { it('should return the full data series for a device', () => { /* Create the dummy data */ const data = []; const startTime = getStartTime(deviceId1); for (let i = 0; i < 11; i++) { data.push(accDataFactory(['x'], startTime + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId1, data)).toEqual(11); /* Retrieve the data points */ const dataReturned = getDataSeries(deviceId1); expect(dataReturned.length).toBe(data.length); /* Check that all of the points match */ for (let j = 0; j < data.length; j++) { expect(dataReturned[j]).toEqual(data[j]); } }); }); describe('getFullDataObj', () => { it('should return the entire data object', () => { /* Create the dummy data */ const data1 = []; const startTime1 = getStartTime(deviceId1); for (let i = 0; i < 11; i++) { data1.push(accDataFactory(['x'], startTime1 + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId1, data1)).toEqual(11); /* Create the dummy data */ const data2 = []; const startTime2 = getStartTime(deviceId2); for (let i = 0; i < 11; i++) { data2.push(accDataFactory(['x'], startTime2 + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId2, data2)).toEqual(11); /* Retrieve the data object */ const dataObj = getFullDataObj(); const dataReturned1 = dataObj[deviceId1].data; const dataReturned2 = dataObj[deviceId2].data; expect(data1).toEqual(dataReturned1); expect(data2).toEqual(dataReturned2); // const dataReturned1 = getDataSeries(deviceId1); // expect(dataReturned1.length).toBe(data.length); // /* Check that all of the points match */ // for (let j = 0; j < data.length; j++) { // expect(dataReturned1[j]).toEqual(data[j]); // } }); }); describe('getDataObjById', () => { it('should return dataObjs for only the ids request', () => { /* Create the dummy data */ const data1 = []; const startTime1 = getStartTime(deviceId1); for (let i = 0; i < 11; i++) { data1.push(accDataFactory(['x'], startTime1 + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId1, data1)).toEqual(11); /* Create the dummy data */ const data2 = []; const startTime2 = getStartTime(deviceId2); for (let i = 0; i < 11; i++) { data2.push(accDataFactory(['x'], startTime2 + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId2, data2)).toEqual(11); /* Create the dummy data 3 */ const data3 = []; const startTime3 = getStartTime(deviceId3); for (let i = 0; i < 11; i++) { data3.push(accDataFactory(['x'], startTime3 + i)); } /* Log the dummy data */ expect(logDataPoints(deviceId3, data3)).toEqual(11); /* Retrieve part of the data */ const reqIds = [deviceId2, deviceId3]; const dataById = getDataObjById(reqIds); /* Expect to get back keys for those requested */ expect(Object.keys(dataById)).toEqual(reqIds); /* Check that the object match */ expect(dataById[deviceId2].data).toEqual(data2); expect(dataById[deviceId3].data).toEqual(data3); }); }); }); }); /* [] - END OF FILE */
module.exports = function (grunt) { 'use strict'; grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-uncss'); grunt.loadNpmTasks('grunt-shell'); var config = { pkg: grunt.file.readJSON('package.json'), jekyllConfig: grunt.file.readYAML('_config.yml'), project: { src: { css: 'src/css', js: 'src/js' }, assets: { css: 'assets/<%= jekyllConfig.github_username %>-<%= jekyllConfig.version %>.css', js: 'assets/<%= jekyllConfig.github_username %>-<%= jekyllConfig.version %>.js' } }, meta: { banner: '/*!\n' + ' * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * <%= pkg.author %>\n' + ' * <%= pkg.description %>\n' + ' * <%= pkg.url %>\n' + ' * Copyright <%= pkg.copyright %>. <%= pkg.license %> licensed.\n' + ' */\n' }, clean: ['assets'], copy: { font: { src: 'fonts/*', dest: 'assets', expand: true, cwd: 'bower_components/font-awesome' }, images: { src: 'images/**/*', dest: 'assets', expand: true, cwd: 'src' }, src: { src: 'favicon.ico', dest: './', expand: true, cwd: 'src' } }, jshint: { files: ['<%= project.src.js %>/*.js', '!<%= project.src.js %>/linkedin.js'], options: { jshintrc: '.jshintrc' } }, less: { build: { src: '<%= project.src.css %>/site.less', dest: '<%= project.assets.css %>' }, dist: { src: ['<%= project.assets.css %>'], dest: '<%= project.assets.css %>', options: { banner: '<%= meta.banner %>', cleancss: true, compress: true } } }, /* ignore: do not remove code block highlight sytlesheet */ uncss: { dist: { options: { ignore: ['pre', 'code', 'pre code', /\.highlight(\s\.\w{1,3}(\s\.\w)?)?/, '.post img', '.post h4', 'aside section ul li span.disqus-author'], media: ['(min-width: 768px)', '(min-width: 992px)', '(min-width: 1200px)'], stylesheets: ['<%= project.assets.css %>'], ignoreSheets: [/fonts.googleapis/], report: 'min' }, files: { '<%= project.assets.css %>': ['_site/index.html', '_site/about/index.html'] } } }, shell: { jekyllBuild: { command: 'jekyll build' } }, uglify: { options: { banner: "<%= meta.banner %>" }, dist: { files: { '<%= project.assets.js %>': '<%= project.assets.js %>' } } }, watch: { files: [ '_includes/*.html', '_docs/*.md', '_press/*.md', '_blog/*.md', '_layouts/*.html', '_posts/*.md', '_config.yml', 'src/js/*.js', 'index.html', 'src/css/*.less', 'about/*.html', 'projects/*.html' ], tasks: ['build', 'shell:jekyllBuild'], options: { interrupt: true, atBegin: true } }, delta: { jshint: { files: ['<%= project.src.js %>/**/*.js'], tasks: ['jshint', 'copy:js'] }, less: { files: ['<%= project.src.css %>/**/*.less'], tasks: ['less:build'] } } }; grunt.initConfig(config); grunt.registerTask('build', ['clean', 'jshint', 'copy', 'concatScripts', 'less:build']); grunt.registerTask('dist', ['build', 'less:dist', 'uglify', 'shell:jekyllBuild']); grunt.registerTask('default', ['watch']); grunt.registerTask('concatScripts', 'concat scripts based on jekyll configuration file _config.yml', function () { // concat task provides a process function to load dynamic scripts parameters var concat = { js: { dest: '<%= project.assets.js %>', options: { process: function (content, srcPath) { return grunt.template.process(content); } } } }, jekyllConfig = grunt.config.get('jekyllConfig'), scriptSrc = []; scriptSrc.push('<%= project.src.js %>/module.prefix'); scriptSrc.push('<%= project.src.js %>/github.js'); // only put scripts that will be used if (jekyllConfig.share.twitter) { scriptSrc.push('<%= project.src.js %>/twitter.js'); } if (jekyllConfig.share.facebook) { scriptSrc.push('<%= project.src.js %>/facebook.js'); } if (jekyllConfig.share.google_plus) { scriptSrc.push('<%= project.src.js %>/google-plus.js'); } if (jekyllConfig.share.disqus) { scriptSrc.push('<%= project.src.js %>/disqus.js'); } // include JQuery scriptSrc.push('bower_components/jquery/dist/jquery.js'); scriptSrc.push('bower_components/jquery-validation/dist/jquery.validate.js'); // include material.js scriptSrc.push('bower_components/bootstrap-material-design/dist/js/material.js'); scriptSrc.push('bower_components/bootstrap-material-design/dist/js/ripples.js'); // include scripts.js scriptSrc.push('<%= project.src.js %>/scripts.js'); scriptSrc.push('<%= project.src.js %>/module.suffix'); // explicitly put the linkedIn code out of the immediate function to work if (jekyllConfig.share.linkedin) { scriptSrc.push('<%= project.src.js %>/linkedin.js'); } // set source concat.js.src = scriptSrc; // set a new task configuration grunt.config.set('concat', concat); // execute task grunt.task.run('concat'); }); };
var expect = require('chai').expect; var search = require('./'); describe('binary search', function() { it('should search 0 elements', function() { var arr = []; expect(search(arr, 4)).to.equal(-1); }); it('should search 1 element not found', function() { var arr = [1]; expect(search(arr, 4)).to.equal(-1); }); it('should search 1 element found', function() { var arr = [1]; expect(search(arr, 1)).to.equal(0); }); it('should search odd', function() { var arr = [1, 2, 3, 4, 5, 6, 7]; expect(search(arr, 4)).to.equal(3); }); it('should search even', function() { var arr = [1, 2, 3, 4, 5, 6, 7, 8]; expect(search(arr, 4)).to.equal(3); }); });
import { Client, ClientDao } from '../database/clientDao'; const dao = new ClientDao(); export default class ClientService { static save(accessToken, refreshToken, profile, done) { process.nextTick(() => { let client = new Client(); client.name = profile.displayName; client.email = profile.emails[0].value; client.facebookId = profile.id; client.token = accessToken; client.photo = 'https://graph.facebook.com/' + profile.id + '/picture?type=large'; dao.save(client, (err, client) => { if (err) { return done(err); } done(err, client); }); }); } static find(req, res, next) { dao.find((err, clients) => { if (err) { return next(err); } res.status(200).json(clients); }) } }
import { createRangeFromZeroTo } from '../../helpers/utils/range' describe('utils range', () => { describe('createRangeFromZeroTo range 2', () => { const range = createRangeFromZeroTo(2) it('return the array 0 to 1', () => { expect(range).toEqual([0, 1]) }) }) describe('createRangeFromZeroTo range 7', () => { const range = createRangeFromZeroTo(7) it('return the array 0 to 6', () => { expect(range).toEqual([0, 1, 2, 3, 4, 5, 6]) }) }) describe('createRangeFromZeroTo range 1', () => { const range = createRangeFromZeroTo(1) it('return the array 0', () => { expect(range).toEqual([0]) }) }) describe('createRangeFromZeroTo range 0', () => { const range = createRangeFromZeroTo(0) it('return the array empty', () => { expect(range).toEqual([]) }) }) describe('createRangeFromZeroTo range undefined', () => { const range = createRangeFromZeroTo() it('return the array empty', () => { expect(range).toEqual([]) }) }) describe('createRangeFromZeroTo range string', () => { const range = createRangeFromZeroTo('toto') it('return the array empty', () => { expect(range).toEqual([]) }) }) })
/*global YoBackbone, Backbone*/ YoBackbone.Collections = YoBackbone.Collections || {}; (function () { 'use strict'; var Todos = Backbone.Collection.extend({ model: YoBackbone.Models.Todo, localStorage: new Backbone.LocalStorage('todos-backbone'), // Filter down the list of all todo items that are finished. completed: function() { return this.filter(function( todo ) { return todo.get('completed'); }); }, // Filter down the list to only todo items that are still not finished. remaining: function() { // apply allowsus to define the context of this within our function scope return this.without.apply( this, this.completed() ); }, // We keep the Todos in sequential order, despite being saved by unordered // GUID in the database. This generates the next order number for new items. nextOrder: function() { if ( !this.length ) { return 1; } return this.last().get('order') + 1; }, // Todos are sorted by their original insertion order. comparator: function( todo ) { return todo.get('order'); } }); YoBackbone.Application.todos = new Todos(); })();
Nectar.createStruct("test", "a:string", "b:int", "c:double"); function Test() { var testStruct = Nectar.initStruct("test"); testStruct.NStruct("test").a = "Hello Struct!"; console.log(testStruct.NStruct("test").a); return testStruct } var retStruct = Test(); retStruct.NStruct("test").a = "After return"; console.log(retStruct.NStruct("test").a); // access to non struct member fall back on hashmap retStruct.NStruct("test").x = "Fallback"; console.log(retStruct.NStruct("test").x);
// Abacus Machine Simulator // Gaurav Manek // // machine.js compiles the parser output to an intermediate form and simulates the machine. "use strict"; // The compiler transforms the output of the parser to an intermediate form that the machine can use. // Encode integer values as negative numbers to allow JavaScript engines in browsers to optimize this away. function ENCODE_INTEGER(v) { return -v-1; } function DECODE_INTEGER(v) { return -v-1; } var DEFAULT_MAX_ITER = 10000; var MACHINE_CONSTANTS = (function () { var i = 0; return { CODE_TYPE_CALL : i++, CODE_TYPE_REGISTER : i++, CODE_TYPE_GOTO : i++, CODE_TYPE_RETURN : i++, CODE_TYPE_VALUES : i++, EXEC_RUNNING : i++, EXEC_HALTED : i++, EXEC_WAITING : i++, TEST_EQUALITY : i++, DBG_STEP_OVER : i++, DBG_STEP_INTO : i++, DBG_STEP_OUT : i++, DBG_RUN_TO_END : i++, STOP_NORMAL : i++, STOP_HALTED : i++, STOP_BREAKPOINT : i++, RUN_NORMAL : i++, RUN_RETURN : i++, RUN_ENTER : i++ }; })(); var Compiler = (function() { "use strict"; function CompilerException(text, location) { this.message = text; this.location = location; }; function abacm$except(text, location) { throw new CompilerException(text, location); } // Takes a function specification, spits out the version in an intermediate form that the machine // can directly use. function abacm$compile(fn, opts) { // Compiled form var rv = { frst: 0, // The first instruction in the function. name: fn.name, args: [], // The register to put the args into. rets: [], // The registers to return. deps: [], // Dependencies regs: [], // Registers exec: [], // Code to execute opts: opts, lineno: fn.lineno } var anchors = {}; // Anchor positions var jumpsToRewrite = []; // Takes an object that represents a function argument, // If it is a register, adds it to rv.regs. If not, it // (depending on enforceRegisters) throws an exception // or encodes it as a number. function addRegister(robj, enforceRegisters, obj) { if (robj.type == "register") { var id = "" + robj.id; var idx = rv.regs.indexOf(id); if(idx < 0) { idx = rv.regs.length; rv.regs.push(id); } return idx; } else if (enforceRegisters) { abacm$except("Register expected, but number found.", obj.lineno); } else if (robj.type == "integer") { return ENCODE_INTEGER(robj.val); } } // Get the exec number corresponding to an anchor, throwing an exception // if the anchor cannot be found. If the anchor is relative, this computes // the new line number and returns it. // The arguments are: // anc: anchor object // i: index of current line // jR: instruction at line function getAnchor(anc, i, jR) { if(!anc || anc.type == "rel") { if (!anc || anc.val == "next") { return (i+1); } else { abacm$except("Unrecognized relative anchor.", jR.lineno); } } else if(anc.type == "anchor") { if(anchors.hasOwnProperty(anc.val)) { return anchors[anc.val]; } else { abacm$except("Jumping to unrecognized anchor.", jR.lineno); } } else { abacm$except("Unrecognized anchor type.", jR.lineno); } } // Step 1: go through the arguments and return values, put them in registers; rv.args = fn.args.val.map(function(r){ return addRegister(r, true, fn); }); rv.rets = fn.return.val.map(function(r){ return addRegister(r, true, fn); }); // Step 2: go through the code and: // (a) convert registers to new registers, // (b) put all anchor positions in anchors, and // (c) log dependencies. for (var i = 0; i < fn.body.length; i++) { // Process fn.body[i] // (b) if(fn.body[i].anchor) { if(anchors.hasOwnProperty(fn.body[i].anchor.val)) { abacm$except("Multiple definition of anchor \":"+fn.body[i].anchor.val + "\".", fn.body[i].lineno); } anchors[fn.body[i].anchor.val] = rv.exec.length // Make it point to the next instruction. } // Check to see if there is any instruction here. if(fn.body[i].exec) { var e = fn.body[i].exec; if (e.type == "callandstore") { rv.exec.push({ type: MACHINE_CONSTANTS.CODE_TYPE_CALL, // The input to the function call, as registers or integers in: e.fn.args.val.map(function(r) { return addRegister(r, false, fn.body[i]); }), // The output from the function call, only registers. out:e.store.val.map(function(r) { return addRegister(r, true, fn.body[i]); }), fn: e.fn.name, lineno: fn.body[i].lineno }); var depFind = rv.deps.find(function(n){ return n.name == e.fn.name}); if (depFind) { // Check if the signature is as expected. if(depFind.in != e.fn.args.val.length || depFind.out != e.store.val.length) { abacm$except("Conflicting function signature for dependency \""+ e.fn.name + "\".", fn.body[i].lineno); } } else { rv.deps.push({name: e.fn.name, in: e.fn.args.val.length, out: e.store.val.length }); } } else if (e.type == "rchange") { var ep = { type: MACHINE_CONSTANTS.CODE_TYPE_REGISTER, // Register register: addRegister(e.register, true, fn.body[i]), // Operation increment: (e.operation=="+"), lineno: fn.body[i].lineno }; if (ep.increment) { ep.next = e.next; } else { ep.next_pos = e.npos; ep.next_zero = e.nzero; } rv.exec.push(ep); } else { abacm$except("Unknown instruction type "+e.type + "\".", fn.body[i].lineno); } } else if (fn.body[i].type == "goto") { var ep = { type: MACHINE_CONSTANTS.CODE_TYPE_GOTO, next: fn.body[i].to, lineno: fn.body[i].lineno }; rv.exec.push(ep); } } // Push the return instruction to the end. rv.exec.push({type: MACHINE_CONSTANTS.CODE_TYPE_RETURN, lineno: fn.lineno}); // Next, use the information in anchors to rewrite all the jumps. for (var i = 0; i < rv.exec.length; i++) { var jR = rv.exec[i]; if(jR.type == MACHINE_CONSTANTS.CODE_TYPE_GOTO || jR.type == MACHINE_CONSTANTS.CODE_TYPE_CALL) { jR.next = getAnchor(jR.next, i, jR); } else if (jR.type == MACHINE_CONSTANTS.CODE_TYPE_REGISTER) { if (jR.increment) { jR.next = getAnchor(jR.next, i, jR); } else { jR.next_pos = getAnchor(jR.next_pos, i, jR); jR.next_zero = getAnchor(jR.next_zero, i, jR); } } } return rv; } function abacm$compileTests(fn) { // Tests var tests = []; // Takes an object that represents a list of arguments, // all of which must be numbers, not registers. function mapValues(rlist, obj) { var rv = rlist.map(function (v) { if(v.type != "integer") abacm$except("Number expected, but register found.", obj.lineno); return v.val; }); return rv; } function testFunction(l, t) { return { type: MACHINE_CONSTANTS.CODE_TYPE_CALL, fcall: FunctionCall(l.name, mapValues(l.args.val, t), 0), lineno: t.lineno }; } function testValues(va, t) { return { type: MACHINE_CONSTANTS.CODE_TYPE_VALUES, values: mapValues(va.val, t), lineno: t.lineno }; } // For each test, store it in the new format, with // the function call in lhs, and the comparing function call // or list of values in rhs. // We enforce the "only numbers no registers" rule here. for(var i = 0; i < fn.tests.length; ++i) { var l = fn.tests[i].lhs; if(l.type != "functioncall") { abacm$except("Expected a function call on the left-hand side.", fn.tests[i].lineno); } var lhs = testFunction(l, fn.tests[i]); var r = fn.tests[i].rhs; var rhs; if(r.type == "functioncall") { rhs = testFunction(r, fn.tests[i]); } else if (r.type == "arglist"){ rhs = testValues(r, fn.tests[i]); } tests.push({ lhs: lhs, rhs: rhs, mode: MACHINE_CONSTANTS.TEST_EQUALITY, lineno: fn.tests[i].lineno }); } return tests; } function abacm$resolveGotos(fn, opts) { // Change all pointers to gotos to point to the goto target (i.e. "through" the goto.) // If an infinite loop is detected, this will throw an exception. // This does not remove the gotos themselves, that happens in a later function. fn.opts.resolveGotos = true; function resolve(i, trace) { if(!trace) trace = RepetitionDetector(); if(trace.push(i)) abacm$except("Infinite GOTO loop detected in function " + fn.name + ".", fn.exec[i].lineno); // Now we look at the instruction at i if(fn.exec[i].type == MACHINE_CONSTANTS.CODE_TYPE_GOTO) { // Okay, we have yet to find the ultimate target of // the goto chain. We return the result of resolving // the next goto along the chain, and replace the // current goto's next parameter to reduce future // computation cost. var tgt = resolve(fn.exec[i].next, trace); fn.exec[i].next = tgt; return tgt; } else { // Oh, good, we found a non-goto instruction. // We return this index as the resolved index: return i; } } fn.frst = resolve(fn.frst); abacm$mapnexts(fn, resolve); return fn; } function abacm$mapnexts(fn, mapper) { for (var i = 0; i < fn.exec.length; i++) { if(fn.exec[i].type != MACHINE_CONSTANTS.CODE_TYPE_RETURN) { if(fn.exec[i].hasOwnProperty("next")) { fn.exec[i].next = mapper(fn.exec[i].next); } else { fn.exec[i].next_pos = mapper(fn.exec[i].next_pos); fn.exec[i].next_zero = mapper(fn.exec[i].next_zero); } } } } function abacm$prune(fn, opts) { // We prune all lines that are not reachable, in any case, // from the input. // Eventually, we may support the pruning of registers // that are only present on unreachable lines. fn.opts.prune = true; var reach = fn.exec.map((v, i) => false); var stack = [fn.frst]; while(stack.length > 0) { var i = stack.pop(); // If I has yet to be marked as reachable: if(!reach[i]) { reach[i] = true; // If it's not a return instruction, add its nexts to // the stack. if(fn.exec[i].type != MACHINE_CONSTANTS.CODE_TYPE_RETURN) { if(fn.exec[i].hasOwnProperty("next")) { stack.push(fn.exec[i].next); } else { stack.push(fn.exec[i].next_pos); stack.push(fn.exec[i].next_zero); } } } } // If the return instruction cannot be reached, then we throw an exception. // This should be considered a fatal error. if(!reach[reach.length - 1]) { abacm$except("This function never exits.", fn.lineno); } // Now we use the reachability list to make a list of destination // indices for each element. var indices = []; for (var i = 0, j = 0; i < reach.length; ++i) { indices[i] = j; // If i is reachable, then the next reachable // index must be assigned the next available // number. if(reach[i]) j++; } // Now we actually rewrite the actual targets of each jump. abacm$mapnexts(fn, (i) => indices[i]); // Copy and filter. var execs = fn.exec; fn.exec = execs.filter((v, i) => reach[i]); var unr = execs.map((f) => f.lineno).filter((v, i) => !reach[i]); // There's no need to filter out the return instruction here because // if it is inaccessible, that makes this a fatal error. return { code: fn, unreachable: unr }; } function abacm$compilerManager(fn, opts) { if(!opts) opts = {}; // Perform basic compilation: var rv = { code: abacm$compile(fn, opts), tests: abacm$compileTests(fn, opts) }; if(opts.resolveGotos) { rv.code = abacm$resolveGotos(rv.code, opts); if(!opts.hasOwnProperty("prune")) opts.prune = true; } if(opts.prune) { var tmp = abacm$prune(rv.code, opts); rv.code = tmp.code; rv.unreachable = tmp.unreachable; } return rv; } return { resolveGotos: abacm$resolveGotos, prune: abacm$prune, compile: abacm$compilerManager, CompilerException: CompilerException }; })(); // A simple loop-detecting object, used to check for infinite GOTO loops // and mutual recursion. function RepetitionDetector() { "use strict"; var loop = []; function repdec$push(id) { if(loop.indexOf(id) >= 0) { return true; } loop.push(id); return false; } function repdec$getLoop(id) { var startpos = loop.indexOf(id); if(startpos < 0) { return []; } // Note use of slice, not s_p_lice, here: return [1, 2,3];//loop.slice(startpos, loop.length).concat([id]); } function repdec$pop() { var cmpid = loop.pop(); } function repdec$reset() { loop = []; } return { // Returns true if a repetition is found, // false otherwise. Once it returns true, // further pushes are disallowed. push : repdec$push, // Remove the last element in the checker. pop : repdec$pop, // Reset the repetition checker. reset: repdec$reset, // Get the loop state getLoop: repdec$getLoop }; } // Object representing a function call // _fn is the function name // _in is the argument list // _out is either zero to unrestrict the return tuple size, or // positive with the expected length of returned tuple. function FunctionCall(_fn, _in, _out) { "use strict"; // Returns true if the function name and signature match, // throws an exception if the name matches but signatures do not, // returns false otherwise. function fncall$match(other) { if(_fn != other.name) return false; if(_in.length != other.args.length || (_out > 0 && _out != other.rets.length)) throw new MachineException("Function \"" + _fn + "\" with correct name but incorrect signature found"); return true; } function fncall$tostr() { return _fn + "(" + _in.join(", ") + ")"; } return { fn: _fn, in: _in, out: _out, matches: fncall$match, toString: fncall$tostr }; } function MachineException(text, location) { this.message = text; this.location = location; }; // A Machine object represents the result of running a single function. It relies // on a MachineRunner object to handle recursion and the stack. // compiled: The code object // options: configuration options for the machine // - exceptionOnNegativeRegister : Throw an exception if a 0-valued register is decremented. function Machine(compiled, args, options) { "use strict"; function abacm$except(text, location) { throw new MachineException(text, location); } var code = compiled; var opts = options?options:{}; var registers = []; var curr = 0; var state = MACHINE_CONSTANTS.EXEC_RUNNING; var loopDetector = RepetitionDetector(); var stepCount = 0; function abacm$init(compiled, args) { // Initialize the registers for(var i = 0; i < code.regs.length; ++i) { registers.push(0); } // Check the argument array if(code.args.length != args.length) abacm$except("Incorrect number of arguments to function.", code.lineno); // Copy the arguments into the registers. for(var i = 0; i < code.args.length; ++i) { if(args[i] < 0) { abacm$except("Negative argument to function.", code.lineno); } registers[code.args[i]] = args[i]; } } // Advances the state of the machine by one step, accepts parameters: // returns: returns by the recursive function call, if one is expected. null otherwise. function abacm$next(returns) { var rv = {}; // Return value var cL = code.exec[curr]; // The line to evaluate at this step. // Check the current state and evolve the machine: if (state == MACHINE_CONSTANTS.EXEC_HALTED) { abacm$except("Attempting to run halted machine.", cL.lineno); } else if (state == MACHINE_CONSTANTS.EXEC_WAITING) { // We've been invoked after sending a request to call a function. // Make sure that we have the desired values. if(cL.type != MACHINE_CONSTANTS.CODE_TYPE_CALL) abacm$except("Internal error, in EXEC_WAITING state but not at a function.", cL.lineno); if(!returns) abacm$except("Expected return values from function call.", cL.lineno); if(returns.length != cL.out.length) abacm$except("Expected " + cL.out.length + " return values from function call, " + returns.length + " received.", cL.lineno); // Now we copy the returned values to the appropriate registers for(var i = 0; i < returns.length; ++i) { if(returns[i] < 0) abacm$except("Negative value returned by " + cL.fn + " return values :" + ", ".join(returns) + ".", cL.lineno); registers[cL.out[i]] = returns[i]; } // Excellent, we're done now! We advance `curr` to the next state and change `state`: curr = cL.next; state = MACHINE_CONSTANTS.EXEC_RUNNING; } else if (state == MACHINE_CONSTANTS.EXEC_RUNNING) { stepCount++; // We're expecting an null value for returns, so we enforce that. if(returns) abacm$except("Expected no return values.", cL.lineno); // Use the loopDetector to check if we have visited this state before, // without going through a branching jump. // Since the only branching jump is with register subtractions, we reset // loopDetector there. if(loopDetector.push(curr)) abacm$except("Infinite loop detected in code, see lines " + loopDetector.getLoop(curr).join(", ") + ".", cL.lineno); // We look at the current state and figure out what to do next based on this. if (cL.type == MACHINE_CONSTANTS.CODE_TYPE_CALL) { // Oh, goody, we need to call a function. var fnArgs = []; // Populate fncall.in with the values of various argument for(var i=0; i<cL.in.length; i++) { if(cL.in[i] < 0) { // If this is a value argument, decode it. fnArgs.push(DECODE_INTEGER(cL.in[i])); } else { // If this is a register argument, copy the value. fnArgs.push(registers[cL.in[i]]); } } // Put this in the return value. rv.functioncall = FunctionCall(cL.fn, fnArgs, cL.out.length); // Change the state to WAITING state = MACHINE_CONSTANTS.EXEC_WAITING; // We don't change the pointer curr yet, that happens // upon function return. } else if (cL.type == MACHINE_CONSTANTS.CODE_TYPE_GOTO) { curr = cL.next; // Go to the given line. } else if (cL.type == MACHINE_CONSTANTS.CODE_TYPE_REGISTER) { // Check if need to increment or decrement: if(cL.increment) { // Increment registers[cL.register]++; curr = cL.next; } else { // Decrement if(opts.exceptionOnNegativeRegister && registers[cL.register] == 0) abacm$except("Decrementing the zero-valued register [" + cL.register + "]", cL.lineno); // Branch depending on the value of the register if (registers[cL.register] == 0) { curr = cL.next_zero; } else { curr = cL.next_pos; } // Decrement the register if positive if (registers[cL.register] > 0) registers[cL.register]--; // Reset the infinite loop detection, because we've found a branching instruction: loopDetector.reset(); } } else if (cL.type == MACHINE_CONSTANTS.CODE_TYPE_RETURN) { // Oh, goody! We're done with this function. We return values in // rv.retval; rv.retval = []; for(var i = 0; i < code.rets.length; ++i) rv.retval.push(registers[code.rets[i]]); // And we change the state to HALTED state = MACHINE_CONSTANTS.EXEC_HALTED; } else if (cL.type == MACHINE_CONSTANTS.CODE_TYPE_VALUES) { // Wait, what? How did this ever make it all the way to the machine? abacm$except("Unexpected line type: values.", cL.lineno); } else { abacm$except("Unexpected line type.", cL.lineno); } } // Incorporate the state into the return value. rv.state = state; rv.lineno = code.exec[curr].lineno; return rv; } function abacm$set(adj) { if(!adj) return; adj.forEach(function (v){ var z = code.regs.indexOf(v.reg); if (z < 0) { abacm$except("Trying to set value of unknown register [" + v.val + "]."); } if(v.val < 0) { abacm$except("Trying to set register [" + v.val + "] to illegal value " + v.val + "."); } registers[z] = v.val; }); } function abacm$state() { // Output the current state in a nice manner, easy for the visualization system to use. return { lineno: code.exec[curr].lineno, registers: code.regs, values: registers, state: state, name: code.name + "(" + args.join(", ") + ");", steps: stepCount } } abacm$init(compiled, args); return { step: abacm$next, getState: abacm$state, set: abacm$set }; } // Handles the stack, spins up a Machine object for each level // allfn: an array of all compiled functions, // fcall: a FunctionCall object representing the function call to make. function MachineRunner(_allfn, _fcall, _options) { "use strict"; var step = 0; var funcs = _allfn; var opts = _options; var stack = []; var state = MACHINE_CONSTANTS.EXEC_RUNNING; var recursionDetector = RepetitionDetector(); var retval = null; var startingLineNo = -1; function mrun$except(text, location) { throw new MachineException(text, location); } // Start a new function call, deepening the stack. function mrun$invokefunc(fcall) { // Check for recursion if(recursionDetector.push(fcall.fn)) mrun$except("Attempted recursion.", fcall.lineno); var f = funcs.find(fcall.matches); if(!f) mrun$except("Cannot find function \"" + fcall.fn + "\"."); // Since fcall.matches checks the function signature, we can use it without // further checking. var m = Machine(f, fcall.in, opts); stack.push(m); } function mrun$returnfunc() { recursionDetector.pop(); stack.pop(); if(stack.length == 0) { state = MACHINE_CONSTANTS.EXEC_HALTED; } } // Initializer, simply invokes the function. function mrun$init(allfn, fcall) { mrun$invokefunc(fcall); startingLineNo = mrun$getlineno(); } function mrun$next() { // Get the machine corresponding to the innermost state var m = stack[stack.length - 1]; // Advance it by one step, including the previous return value if one is set. var s = m.step(retval); retval = null; // Reset retval, if not already done. var rv = { lastAction: MACHINE_CONSTANTS.RUN_NORMAL }; if(s.state == MACHINE_CONSTANTS.EXEC_RUNNING) { // Do nothing, the machine is still running. } else if(s.state == MACHINE_CONSTANTS.EXEC_WAITING) { // s.functioncall contains the function call that m needs to continue. if(!s.functioncall) mrun$except("Machine WAITING without a pending function call.", s.lineno); rv.lastAction = MACHINE_CONSTANTS.RUN_ENTER; // Invoke the recursive function. mrun$invokefunc(s.functioncall); } else if(s.state == MACHINE_CONSTANTS.EXEC_HALTED) { // s.retval contains the returned value. if(!s.retval) mrun$except("Machine HALTED without a return value.", s.lineno); // Store the return value in retval for the next invocation. retval = s.retval; rv.lastAction = MACHINE_CONSTANTS.RUN_RETURN; // Return the function. mrun$returnfunc(); } step++; return rv; } // Returns a state descriptor, used to render the view of // the inner workings of the machine. function mrun$state(i) { if(typeof i != "undefined") { return stack[i].getState(); } return stack.map(st => st.getState()); } // Set a value in the innermost scope. function mrun$set(v) { stack[stack.length - 1].set(v); } function mrun$getlineno() { if(stack.length > 0) { return stack[stack.length - 1].getState().lineno; } else { return startingLineNo; } } // Run the machine until one of the termination conditions are met. // In the worst case, it stops at DEFAULT_MAX_ITER. function mrun$runner(options) { // options, contains: // lines: Breakpoints corresponding to line numbers, // registers: [not done yet] breakpoints corresponding to change in a particular register // stepmode: MACHINE_CONSTANTS.{DBG_STEP_OVER, DBG_STEP_INTO, DBG_STEP_OUT, DBG_RUN_TO_END} // Defaults to DBG_RUN_TO_END. // max_iter: The maximum number of iterations to run before pausing. Defaults to DEFAULT_MAX_ITER. // Make sure that this works. if(state == MACHINE_CONSTANTS.EXEC_HALTED) return { state: state, steps: step }; // Defaults: if(!options) options = {}; if(!options.max_iter) options.max_iter = DEFAULT_MAX_ITER; if(!options.stepmode) options.stepmode = MACHINE_CONSTANTS.DBG_RUN_TO_END; // Starting stack length var startStackLength = stack.length; // Ending iteration var endC = step + options.max_iter; var stopCause = MACHINE_CONSTANTS.STOP_NORMAL; while(step < endC) { var toBreak = false; var st = mrun$next(); // If the machine has halted, stop. if(state == MACHINE_CONSTANTS.EXEC_HALTED) { stopCause = MACHINE_CONSTANTS.STOP_HALTED; break; } switch(options.stepmode) { case MACHINE_CONSTANTS.DBG_STEP_INTO: // Always break. toBreak = true; break; case MACHINE_CONSTANTS.DBG_STEP_OVER: // If there is no stack length change, then we can end right here. // Otherwise, we continue until the stack returns to this length. toBreak = (stack.length <= startStackLength); break; case MACHINE_CONSTANTS.DBG_STEP_OUT: toBreak = (stack.length < startStackLength); break; case MACHINE_CONSTANTS.DBG_RUN_TO_END: default: // Do nothing, just keep going. } // Check for line number breakpoints: if(options.lines && stack.length > 0) { var cs = stack[stack.length - 1].getState(); if(options.lines.indexOf(cs.lineno) >= 0 && (st.lastAction != MACHINE_CONSTANTS.RUN_RETURN)){ toBreak = true; stopCause = MACHINE_CONSTANTS.STOP_BREAKPOINT; } } if(toBreak) break; } var rv = { state: state, steps: step, lineno: mrun$getlineno(), stop: stopCause }; // If the machine has halted, stop. if(state == MACHINE_CONSTANTS.EXEC_HALTED) { if(!retval) { mrun$except("Machine HALTED without a return value.", s.lineno); } rv.retval = retval; } return rv; } mrun$init(_allfn, _fcall); return { fcall: _fcall, run: mrun$runner, getState: mrun$state, set: mrun$set, lineno: mrun$getlineno }; } // Uses a topological sort to order tests, so that the // function that is at the very tail of the dependency // DAG is tested first. // // The _listener is called each time a test succeeds, and // notifies the UI each time a test passes or fails, and // when all tests associated with a function pass. function TestEngine(__compiledOutput, _listener) { "use strict" var tests = []; var testFunc = []; var lastInFunction = null; var ct = 0; var cp = 0; var passedAllTests = true; var prevTest = null; var listener = _listener; function tests$init(_compiledOutput) { var fn = []; var deps = []; _compiledOutput.forEach(function(v) { fn.push(v.code.name); deps.push(v.code.deps.map(function(z) { return z.name; })); }); while(fn.length > 0) { // Strip all functions that are not in the pending list. deps = deps.map(function (v) { return v.filter(function(z) { return fn.indexOf(z) >= 0; }); }); // There should be at least one function that has 0 dependencies // at each step, otherwise there is a cycle somewhere. var empties = deps.reduce(function(arr, v, idx) { return (v.length == 0)?arr.concat(idx):arr; }, []); if(empties.length == 0) throw new MachineException("Circular dependency detected when preparing tests."); // Prepend the functions to the list, maintaining the topological order. testFunc = empties.map(function(v) { return fn[v]; }).concat(testFunc); // Remove all corresponding elements from fn and deps. var emptyRemoveFunction = function (v, idx) { return empties.indexOf(idx) < 0; }; fn = fn.filter(emptyRemoveFunction); deps = deps.filter(emptyRemoveFunction); } // Now all functions are in testFunc, topologically sorted. tests = testFunc.map(function(fn) { return _compiledOutput.find(function(v) { return v.code.name == fn; }).tests; }); tests$removeTrailingEmpties(); // Count up the tests ct = tests.reduce(function(f,v) { return v.length + f; }, 0); } function tests$hasTest() { return (tests.length > 0); } function tests$removeTrailingEmpties(){ while(tests.length > 0 && tests[tests.length - 1].length == 0){ tests.pop(); } } function tests$nextTest() { var tt = tests[tests.length - 1]; prevTest = tt.pop(); if(tt.length == 0) { tests.pop(); lastInFunction = testFunc.pop(); } else { lastInFunction = null; } tests$removeTrailingEmpties(); return prevTest; } // Return true if we should continue, false otherwise. function tests$status(succ) { if(succ) cp++; passedAllTests = succ && passedAllTests; if(listener) { listener(prevTest, succ, lastInFunction); } return true; } function tests$passed() { return cp; } tests$init(__compiledOutput); return { hasTest: tests$hasTest, next: tests$nextTest, status: tests$status, count: ct, passed: tests$passed } } var Linker = (function(){ "use strict" var REGISTER_TMP_COPY = 0; function LinkerException(message, lineno){ this.message = message; this.lineno = lineno; } function lnkr$except(text, location){ throw new LinkerException(text, location); } function lnkr$find(allfunc, target){ var rf = allfunc.find((t) => t.name == target); if(!rf) { lnkr$except("Cannot find function \"" + target + "\""); } return rf; } // Copy from global register rF to global register rT, // assumes rT is zero. function lnkr$makePreambleCopy(rF, rT, first){ var r0 = REGISTER_TMP_COPY; var rv = [ { "type":1, "register":rF, "increment":false, "next_pos":1, "next_zero":6 }, { "type":1, "register":rT, "increment":true, "next":2 }, { "type":1, "register":r0, "increment":true, "next":3 }, { "type":1, "register":rF, "increment":false, "next_pos":1, "next_zero":4 }, { "type":1, "register":r0, "increment":false, "next_pos":5, "next_zero":6 }, { "type":1, "register":rF, "increment":true, "next":4 }]; return lnkr$makePreambleWrapper(rv, first); } // Zeros rZ. function lnkr$makePreambleZero(rZ, first){ var rv = [ { "type":1, "register":rZ, "increment":false, "next_pos":0, "next_zero":1 } ]; return lnkr$makePreambleWrapper(rv, first); } // Sets rZ to value v. function lnkr$makePreambleValue(rZ, v, first){ var rv = []; var i = 0; while(i < v) rv.push({ "type":1, "register":rZ, "increment":true, "next":++i }); return lnkr$makePreambleWrapper(rv, first); } function lnkr$makePreambleWrapper(l, first) { var idx = l.map((v, i) => lnkr$lazyIndex(-1, i + 1)); idx.unshift(first); // Temporarily add the exit pointer to idx // Switch all nexts from numbers to lazy indices. for(var i = 0; i < l.length; ++i) { if(l[i].hasOwnProperty("next")) { l[i].next = idx[l[i].next]; } else { l[i].next_pos = idx[l[i].next_pos]; l[i].next_zero = idx[l[i].next_zero]; } } var next = idx.pop(); // Sanity checks if(l.length != idx.length) lnkr$except("Wrapper broke invariant that exec and jump are of same length."); if(!next) lnkr$except("Wrapper returning null lazyIndex."); return { exec: l, jump: idx, next: next }; } function lnkr$makeGoto(dest) { return { type: MACHINE_CONSTANTS.CODE_TYPE_GOTO, next: dest }; } function lnkr$deepCopyCode(obj) { var temp = {}; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { if(Array.isArray(obj[key])) { temp[key] = obj[key].slice(0); } else { temp[key] = obj[key]; } } } return temp; } // Lazily evaluated index object. Used to // stand in for an actual index until the flattening is done. function lnkr$lazyIndex(sc, i) { return { sc: sc, i: i, pos: -1 }; } // Convert an entire execution tree into a single function. // allfunc: an array of functions, // target: the name of the function to compile, and // opts: extra options. // // Note that we do not perform any cleaning operations here, so it is important to // run `goto` resolution and pruning after this. function lnkr$link(allfunc, target, opts) { // Oh, good. Now we have the starting function. Now we prepare scope resolution. A "scope" corresponds // to the position of a function call in the final, linked, function and the registers assigned to it. var nextScope = 0; // The next scope id. var startingRegister = []; // The index of the first register of the original function in a scope. var registerMapping = []; // Map from (scope, local register) to global register. var regs = []; startingRegister.push(1); // We need a temporary copying register somewhere here. registerMapping.push(0); // Convenience functions: var getReg = (scope, i) => registerMapping[startingRegister[scope] + i]; var setReg = (scope, i, k) => registerMapping[startingRegister[scope] + i] = k; // Function Calling Convention: // Each function has a preamble that copies data from an input register in the caller's scope to // the appropriate register in the callee's scope, and zeros out registers in the caller's scope // that are to be written to. If a register is both in the caller's and callee's scope, then we // leave it alone. function flattenFunctionCode(fname, next, input_registers, output_registers, return_target) { var scope = nextScope++; // Get the next scope id for this function. var fn = lnkr$find(allfunc, fname); // Find the compiled function data. var pend = fn.exec.map(lnkr$deepCopyCode); // Commands to be processed, deep copied. var idxs = fn.exec.map((v, j) => lnkr$lazyIndex(scope, j)); // Prepare the lazy indexing object array. var exec = []; // The final sequence of exec[] commands associated with this. var jump = []; // The lazyIndex object associated with each line. // Allocate all the registers we need in this scope, and tell the next scope // where it can start allocating registers. fn.regs.forEach(function (v, j) { registerMapping.push(startingRegister[scope] + j); regs.push(scope + "_" + fn.name + "_" + fn.regs[j]); }); startingRegister.push(startingRegister[scope] + fn.regs.length); // next is the entrypoint into the function. If it is not given, then this must be the // root function call. In that case, we use the first instruction's index as the entrypoint. if(!next) { next = idxs[fn.frst]; } else { // This is not the root function call. We need to massage the registers a little. if(!Array.isArray(input_registers) || !Array.isArray(output_registers)) lnkr$except("Non-root function call without preamble data.", fn.lineno); if(input_registers.length != fn.args.length || output_registers.length != fn.rets.length) lnkr$except("Incorrect input or output register length.", fn.lineno); // Function preamble // Here's the tricky part: we need to map input_registers to fn.args and // fn.rets to output_registers. // Here are the rules for that mapping: // (1) Remap and erase output registers. // (a) We set registerMapping[(scope, fn.rets[j])] = output_registers[j] for all // output registers. (This corresponds to setting the output location.) // (b) All output_registers that ARE NOT also input_registers are zeroed // using lnkr$makePreambleZero. (Zero returning registers.) // (2) Copy various input registers. // (a) If an input_register is also an output_register, we ignore it. It has been // dealt with in (1)(a). // (b) If an input_register is non-negative, we use lnkr$makePreambleCopy to copy // the value from input_register[j] to rn.args[j]. (Pass-by-value support.) // (c) If an input_register is negative, we use lnkr$makePreambleValue to store // the corresponding value in the corresponding register in fn.args. (Integer // constants support.) // // The result of all this preamble code will be to emulate the function abstractions of // passing by value to and from a function. // // Also, next is the index to which control will be passed. We use that as the first index of // each part of the preamble and overwrite it with the returned rv.next index. // // Don't worry, this will not be on the final. :) output_registers.forEach(function (r, j) { // (a) setReg(scope, fn.rets[j], r); // (b) if(input_registers.indexOf(r) < 0) { var c = lnkr$makePreambleZero(r, next); exec = exec.concat(c.exec); jump = jump.concat(c.jump); next = c.next; } }); // (2) input_registers.forEach(function (r, j) { if(output_registers.indexOf(r) >= 0) { // (a) } else { var c; if (r >= 0) { // (b) c = lnkr$makePreambleCopy(r, getReg(scope, fn.args[j]), next); } else { // (c) c = lnkr$makePreambleValue(getReg(scope, fn.args[j]), DECODE_INTEGER(r), next); } exec = exec.concat(c.exec); jump = jump.concat(c.jump); next = c.next; } }); } // next is the entrypoint into the function, so we set the first instruction in the function // to next. idxs[fn.frst] = next; for(var i=0; i<pend.length; ++i) { if(pend[i].type == MACHINE_CONSTANTS.CODE_TYPE_RETURN) { // Oh, goody! We're done processing this function. // If there is a return target to jump to after this function, // then we put a goto there. Otherwise we leave the return function in. if(return_target) { exec.push(lnkr$makeGoto(return_target)); } else { exec.push(pend[i]); // We copy in the return function. } jump.push(idxs[i]); // Sanity check. // console.log(exec.length); if(exec.length != jump.length) { lnkr$except("Exec and Jump of different lengths."); } return { exec: exec, jump: jump }; } else { // We swap out the next jumps for lazily evaluated indices, // no matter what the type is. if(pend[i].hasOwnProperty("next")) { pend[i].next = idxs[pend[i].next]; } else { pend[i].next_pos = idxs[pend[i].next_pos]; pend[i].next_zero = idxs[pend[i].next_zero]; } switch (pend[i].type) { case MACHINE_CONSTANTS.CODE_TYPE_REGISTER: // We're accessing a register here. We map the accessed register // from the local to the global registers. pend[i].register = getReg(scope, pend[i].register); // Note: no break; here, we still need to add the line to the code. case MACHINE_CONSTANTS.CODE_TYPE_GOTO: // Add the current line to the code: exec.push(pend[i]); jump.push(idxs[i]); break; case MACHINE_CONSTANTS.CODE_TYPE_CALL: // We need to map both the input and output registers, // but leave the numbers unchanged. Numbers are stored as // negative values. var r_in = pend[i].in.map((v) => (v >= 0?getReg(scope, v):v)); var r_out = pend[i].out.map((v) => (v >= 0?getReg(scope, v):v)); var sub = flattenFunctionCode(pend[i].fn, idxs[i], r_in, r_out, pend[i].next); exec = exec.concat(sub.exec); jump = jump.concat(sub.jump); break; default: lnkr$except("Unexpected type for compiled code.", fn.lineno); } } } // We've finished running over all indices without // returning. This should not have happened. lnkr$except("Function without return.", fn.lineno); } var srcF = lnkr$find(allfunc, target); var rv = flattenFunctionCode(target); var exec = rv.exec; var line = rv.jump; // Now we update the lazyIndices with the actual line number: line.forEach((l, i) => l.pos = i); // And we swap each lazyIndex with the position: exec.forEach(function(e) { if(e.type != MACHINE_CONSTANTS.CODE_TYPE_RETURN) { if(e.hasOwnProperty("next")) { e.next = e.next.pos; } else { e.next_pos = e.next_pos.pos; e.next_zero = e.next_zero.pos; } } }); // ...and we're done! return { "frst": srcF.frst, "name": srcF.name + "_compiled", "args": srcF.args.map((r) => r + startingRegister[0]), "rets": srcF.rets.map((r) => r + startingRegister[0]), "deps": [], "regs": regs, "exec": exec, "opts": {"linked":true} }; } return { LinkerException: LinkerException, link: lnkr$link }; })();
define('view/rooms/users-rooms-list', [ 'view' ], function ( View ) { function UsersRoomsListView() { View.apply(this, arguments); } View.extend({ constructor: UsersRoomsListView, template: { 'root': { each: { view: UserRoomView, el: '> *' } } } }); function UserRoomView() { View.apply(this, arguments); } View.extend({ constructor: UserRoomView, template: { 'root': { 'class': { 'hidden': '@hidden' } }, '[data-title]': { text: '@name', attr: { 'href': function () { return '#user-room/' + this.model.get('id') } } } } }); return UsersRoomsListView; });
angular.module('messages') .controller('messageCtrl',['$scope','messages','socket','$stateParams',MessageController]) function MessageController($scope,messages,socket,$stateParams) { $scope.messages = messages; $scope.msg = ''; $scope.sendMsg = function() { socket.sendMsg({content : $scope.msg, to : $stateParams.id}); }; };
/** * Created by uzysjung on 2016. 10. 21.. */ import React, { PropTypes,Component } from 'react'; import Box from '../../components/widget/Box' import { Link, browserHistory } from 'react-router' import superagent from 'superagent'; import { Form , FormGroup, Col, Button, FormControl, Checkbox, ControlLabel , PageHeader, Alert } from 'react-bootstrap' const styleLogin = { panel : { maxWidth : 600, position : 'absolute', top : '50%', left : '50%', transform : 'translate(-50%,-50%)' }, header : { maxHeight : 40, bottomMargin : 100, borderBottom : '1px solid #bababa' } }; class LoginPage extends React.Component { constructor(props) { super(props); this.state = { email : '', password : '' } } componentWillMount() { const { authenticated, replace, redirect } = this.props; if (authenticated) { replace(redirect) } } componentDidMount() { } handleFormSubmit = (e) => { e.preventDefault(); const { email, password } = this.state; setTimeout(() => this.setState({error: false}), 3000); if ( !email || email.length < 1) { this.setState({error: 'Insert Email address'}); return; } if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email)) { this.setState({error: 'Please check whether this email is valid'}); return; } if (!password) { this.setState({error: 'Insert Password'}); return; } if ( password && password.length < 5 ) { this.setState({error: 'Password must be longer than 5 characters'}); return; } superagent.post('/api/login').send({login_email: email, login_pw: password}).end((err, result) => { if (!err) { localStorage.setItem('jwt', result.body.token); browserHistory.push('/'); } else { this.setState({error: 'Login email/password incorrect :('}); } }); }; handleForChange = (e) => { console.log('e.target.id',e.target.id); switch(e.target.id) { case 'formHorizontalEmail' : this.setState( { email : e.target.value } ); break; case 'formHorizontalPassword' : this.setState( { password : e.target.value } ); break; } }; renderAlert() { if (this.state.error) { return ( <Alert bsStyle="danger"> {this.state.error} </Alert> ) } return null; } render() { return ( <div style={styleLogin.panel}> <PageHeader style={styleLogin.header}>Weapon Management System</PageHeader> <Box title="Login" status="info" solid > <Form onSubmit={this.handleFormSubmit} horizontal> <FormGroup controlId="formHorizontalEmail"> <Col componentClass={ControlLabel} sm={2}> Email </Col> <Col sm={10}> <FormControl type="email" placeholder="Email" value={this.state.email} onChange={this.handleForChange} /> </Col> </FormGroup> <FormGroup controlId="formHorizontalPassword"> <Col componentClass={ControlLabel} sm={2}> Password </Col> <Col sm={10}> <FormControl type="password" placeholder="Password" value={this.state.password} onChange={this.handleForChange} /> </Col> </FormGroup> <FormGroup> <Col smOffset={2} sm={10}> <Checkbox>Remember me</Checkbox> </Col> </FormGroup> {this.renderAlert()} <FormGroup> <Col smOffset={2} sm={10}> <Button className="btn btn-success" type="submit"> Sign in </Button> </Col> </FormGroup> </Form> </Box> </div> ); } } export default LoginPage;
$(function () { $('[data-toggle="tooltip"]').tooltip() }) $(function () { $('[data-toggle="popover"]').popover() })
'use strict'; //var async = require('async'), // nconf = require('nconf'), // user = require('../user'), // groups = require('../groups'), // topics = require('../topics'), // posts = require('../posts'), // notifications = require('../notifications'), // messaging = require('../messaging'), // plugins = require('../plugins'), // utils = require('../../public/src/utils'), // websockets = require('./index'), // meta = require('../meta'), var linkParser = require('../controllers/mind-map/linkParser_new-format'), swaggerBuilder = require('../modeling/swaggerBuilder'), swaggerBuildertr069 = require('../modeling/swaggerBuilder-Scope'); var SocketCustom = {}; SocketCustom.refreshLinkParser = function(socket, sets, callback) { if (!socket.uid) { return callback(new Error('[[invalid-uid]]')); } linkParser.init(function(err) { callback(null, '{"message": "Refreshed Link Parser"}'); }); }; SocketCustom.refreshSwagger = function(socket, data, callback) { if (!socket.uid) { return callback(new Error('[[invalid-uid]]')); } swaggerBuilder.init(function(err) { callback(null, '{"message": "Refreshed Swagger File"}'); }); }; SocketCustom.refreshZoneSwagger = function(socket, data, callback) { if (!socket.uid) { return callback(new Error('[[invalid-uid]]')); } swaggerBuildertr069.init(function(err) { callback(null, '{"message": "Refreshed Zone Swagger File"}'); }); }; /* Exports */ module.exports = SocketCustom;
import {getTims} from '../api/api'; export function loadData() { return getTims().then(data => { const parser = new DOMParser(); const doc = parser.parseFromString(data, 'text/xml'); if (doc.documentElement.nodeName === 'parseerror') { throw new Error(doc); } return toJSON(doc); }).catch(e => { console.error(e); }); } function toJSON(doc) { const json = { published: null, disruptions: [] }; const { header, disruptions } = getChildren(doc.documentElement, 'header', 'disruptions'); if (header) { const publishedElement = getChild(header, 'publishdatetime'); if (publishedElement) { const pubDateAttr = getAttr(publishedElement, 'canonical'); if (pubDateAttr) { json.published = pubDateAttr.value; } } const refreshRateElement = getChild(header, 'refreshrate'); if (refreshRateElement) { const refreshRate = Number(refreshRateElement.textContent); if (!isNaN(refreshRate) && refreshRate > 0) { json.refreshRate = refreshRate; } } } if (disruptions) { json.disruptions = mapDisruptions(disruptions); } return json; } function mapDisruptions(disruptions) { const res = {}; for (let i = 0; i < disruptions.children.length; ++i) { const disr = disruptions.children[i]; const idAttr = getAttr(disr, 'id'); if (!idAttr || !idAttr.value) { continue; } const props = {}; for (let j = 0; j < disr.children.length; ++j) { const propElem = disr.children[j]; if (propElem.children.length === 0) { props[propElem.nodeName] = propElem.textContent; } else if (propElem.nodeName.toLowerCase() === 'causearea') { const displayPoint = getChild(propElem, 'displaypoint'); if (displayPoint) { const point = getChild(displayPoint, 'point'); if (point) { const coords = getChild(point, 'coordinatesll'); if (coords) { const split = coords.textContent.split(','); if (split.length === 2) { props.coords = { lat: parseFloat(split[1]), lng: parseFloat(split[0]) }; } } } } } } res[idAttr.value] = props; } return res; } function getChildren(element, ...names) { const res = {}; for (let i = 0; i < element.children.length; ++i) { const name = element.children[i].nodeName.toLowerCase(); if (names.find(n => n === name)) { res[name] = element.children[i]; } } return res; } function getChild(element, name) { const res = getChildren(element, name); return res[name] || null; } function getAttr(element, name) { for (let i = 0; i < element.attributes.length; ++i) { if (element.attributes[i].name === name) { return element.attributes[i]; } } return null; }
'use strict'; angular.module('cocoApp') .directive('loginform', [function () { return { restrict: 'E', controller: 'LoginInterceptCtrl', scope: { eventid: '=' }, templateUrl: 'partials/login.html' }; }]);
/* Copyright (c) 2012 Greg Reimer ( http://obadger.com/ ) 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(w, d, $){ // defaults var defaultArgs = { rays: 16, originX: '50%', originY: '50%', bgColorStart: 'rgba(0,0,0,0.1)', bgColorEnd: 'rgba(0,0,0,0.2)', rayColorStart: 'hsla(0,0%,100%,0.2)', rayColorEnd: 'hsla(0,0%,100%,0.3)', sizingRatio: 1 }; $.fn.pow = (function(){ return function(args){ // bail if none if (this.length === 0) { return; } // set defaults args = $.extend({}, defaultArgs, args); // set vars and grab a few values to use later var $el = this.eq(0); var width = $el.outerWidth(); var height = $el.outerHeight(); var offset = $el.offset(); var originX = (parseFloat(args.originX) || 0) / 100; var originY = (parseFloat(args.originY) || 0) / 100; // center rays on a given element if (args.originEl) { var $oel = $(args.originEl); if ($oel.length) { var oOffset = $oel.offset(); var oWidth = $oel.outerWidth(); var oHeight = $oel.outerHeight(); originX = (((oOffset.left - offset.left) + (oWidth / 2)) / width); originY = (((oOffset.top - offset.top) + (oHeight / 2)) / height); } } // convert to absolute lengths originX = width * originX; originY = height * originY; // find maximum distance to a corner var radius = Math.max.apply(Math, [ {x:0,y:0}, {x:width,y:0}, {x:0,y:height}, {x:width,y:height} ].map(function(c){ // use the pythagorean theorem, luke return Math.sqrt(Math.pow(c.x - originX, 2) + Math.pow(c.y - originY, 2)); })); try{ var canvas = $('<canvas width="'+width+'" height="'+height+'" style="position:fixed;top:-999999px"></canvas>').appendTo(d.body).get(0); var ctx = canvas.getContext('2d'); } catch(err) { return; } // build the background gradient var bgGrad = ctx.createRadialGradient( originX, originY, 0, // inner circle, infinitely small originX, originY, radius // outer circle, will just cover canvas area ); bgGrad.addColorStop(0, args.bgColorStart); bgGrad.addColorStop(1, args.bgColorEnd); // build the foreground gradient var rayGrad = ctx.createRadialGradient( originX, originY, 0, // inner circle, infinitely small originX, originY, radius // outer circle, will just cover canvas area ); rayGrad.addColorStop(0, args.rayColorStart); rayGrad.addColorStop(1, args.rayColorEnd); // fill in bg ctx.fillStyle = bgGrad; ctx.fillRect(0,0,width,height); // draw rays ctx.fillStyle = rayGrad; ctx.beginPath(); var spokeCount = args.rays * 2; ctx.moveTo(originX, originY); for (var i=0; i<args.rays; i++){ for (var j=0; j<2; j++) { var thisSpoke = i * 2 + j; var traversal = thisSpoke / spokeCount; var ax = originX + radius * 1.5 * Math.cos(traversal * 2 * Math.PI); var ay = originY + radius * 1.5 * Math.sin(traversal * 2 * Math.PI); ctx.lineTo(ax,ay); } ctx.lineTo(originX, originY); } ctx.fill(); // set the data as css to the element var data = canvas.toDataURL("image/png"); $(canvas).remove(); $el.css({ 'background-image':'url("'+data+'")', 'background-repeat':'no-repeat', 'background-position':'50% 50%', 'background-size':'cover' }); }; })(); })(window, document, jQuery);
'use strict' import Macro from './macro.js' /** * マクロスタック */ export default class MacroStack { /** * コンストラクタ */ constructor () { /** * [*store manual] スタックの中身 * @private * @type {Array} */ this.stack = [] } /** * スタックへ積む * @param {Macro} macro マクロ */ push (macro) { this.stack.push(macro) } /** * スタックから降ろす * @return {Macro} マクロ */ pop () { return this.stack.pop() } /** * スタックが空かどうか * @return {boolean} 空ならtrue */ isEmpty () { return this.stack.length <= 0 } /** * スタックの一番上のマクロを返す * @return {Macro} マクロ */ getTop () { if (this.isEmpty()) { return null } else { return this.stack[this.stack.length - 1] } } /** * 状態を保存 * @param {number} tick 時刻 * @return {object} 保存データ */ store (tick) { // Generated by genStoreMethod.js let data = {} // 保存 // 以下、手動で復元する // store this.stack data.stack = [] this.stack.forEach((macro) => { data.stack.push(macro.store(tick)) }) return data } /** * 状態を復元 * @param {object} data 復元データ * @param {number} tick 時刻 * @param {AsyncTask} task 非同期処理管理 */ restore (data, tick, task) { // Generated by genRestoreMethod.js // 復元 // 以下、手動で復元する // restore this.stack this.stack = [] // console.log(data) data.stack.forEach((macroData) => { let macro = new Macro('') macro.restore(macroData, tick, task) this.stock.push(macro) }) } }
const interviewSchema = require('./interview.schema'); const InterviewModel = require('mongoose').model('Interview', interviewSchema); module.exports = InterviewModel;
"use strict"; /** * @license * Copyright 2018 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var non_max_suppression_impl_1 = require("../backends/non_max_suppression_impl"); var engine_1 = require("../engine"); var tensor_util_env_1 = require("../tensor_util_env"); var util = require("../util"); var operation_1 = require("./operation"); /** * Bilinear resize a batch of 3D images to a new shape. * * @param images The images, of rank 4 or rank 3, of shape * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed. * @param size The new shape `[newHeight, newWidth]` to resize the * images to. Each channel is resized individually. * @param alignCorners Defaults to False. If true, rescale * input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4 * corners of images and resized images. If false, rescale by * `new_height / height`. Treat similarly the width dimension. */ /** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */ function resizeBilinear_(images, size, alignCorners) { if (alignCorners === void 0) { alignCorners = false; } var $images = tensor_util_env_1.convertToTensor(images, 'images', 'resizeBilinear'); util.assert($images.rank === 3 || $images.rank === 4, function () { return "Error in resizeBilinear: x must be rank 3 or 4, but got " + ("rank " + $images.rank + "."); }); util.assert(size.length === 2, function () { return "Error in resizeBilinear: new shape must 2D, but got shape " + (size + "."); }); var batchImages = $images; var reshapedTo4D = false; if ($images.rank === 3) { reshapedTo4D = true; batchImages = $images.as4D(1, $images.shape[0], $images.shape[1], $images.shape[2]); } var newHeight = size[0], newWidth = size[1]; var forward = function (backend, save) { save([batchImages]); return backend.resizeBilinear(batchImages, newHeight, newWidth, alignCorners); }; var backward = function (dy, saved) { return { x: function () { return engine_1.ENGINE.runKernelFunc(function (backend) { return backend.resizeBilinearBackprop(dy, saved[0], alignCorners); }, {}); } }; }; var res = engine_1.ENGINE.runKernelFunc(forward, { x: batchImages }, backward, 'ResizeBilinear', { alignCorners: alignCorners, newHeight: newHeight, newWidth: newWidth }); if (reshapedTo4D) { return res.as3D(res.shape[1], res.shape[2], res.shape[3]); } return res; } /** * NearestNeighbor resize a batch of 3D images to a new shape. * * @param images The images, of rank 4 or rank 3, of shape * `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed. * @param size The new shape `[newHeight, newWidth]` to resize the * images to. Each channel is resized individually. * @param alignCorners Defaults to False. If true, rescale * input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4 * corners of images and resized images. If false, rescale by * `new_height / height`. Treat similarly the width dimension. */ /** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */ function resizeNearestNeighbor_(images, size, alignCorners) { if (alignCorners === void 0) { alignCorners = false; } var $images = tensor_util_env_1.convertToTensor(images, 'images', 'resizeNearestNeighbor'); util.assert($images.rank === 3 || $images.rank === 4, function () { return "Error in resizeNearestNeighbor: x must be rank 3 or 4, but got " + ("rank " + $images.rank + "."); }); util.assert(size.length === 2, function () { return "Error in resizeNearestNeighbor: new shape must 2D, but got shape " + (size + "."); }); util.assert($images.dtype === 'float32' || $images.dtype === 'int32', function () { return '`images` must have `int32` or `float32` as dtype'; }); var batchImages = $images; var reshapedTo4D = false; if ($images.rank === 3) { reshapedTo4D = true; batchImages = $images.as4D(1, $images.shape[0], $images.shape[1], $images.shape[2]); } var newHeight = size[0], newWidth = size[1]; var forward = function (backend, save) { save([batchImages]); return backend.resizeNearestNeighbor(batchImages, newHeight, newWidth, alignCorners); }; var backward = function (dy, saved) { return { batchImages: function () { return engine_1.ENGINE.runKernelFunc(function (backend) { return backend.resizeNearestNeighborBackprop(dy, saved[0], alignCorners); }, {}); } }; }; var res = engine_1.ENGINE.runKernelFunc(forward, { batchImages: batchImages }, backward); if (reshapedTo4D) { return res.as3D(res.shape[1], res.shape[2], res.shape[3]); } return res; } /** * Performs non maximum suppression of bounding boxes based on * iou (intersection over union). * * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of * the bounding box. * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`. * @param maxOutputSize The maximum number of boxes to be selected. * @param iouThreshold A float representing the threshold for deciding whether * boxes overlap too much with respect to IOU. Must be between [0, 1]. * Defaults to 0.5 (50% box overlap). * @param scoreThreshold A threshold for deciding when to remove boxes based * on score. Defaults to -inf, which means any score is accepted. * @return A 1D tensor with the selected box indices. */ /** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */ function nonMaxSuppression_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) { if (iouThreshold === void 0) { iouThreshold = 0.5; } if (scoreThreshold === void 0) { scoreThreshold = Number.NEGATIVE_INFINITY; } var $boxes = tensor_util_env_1.convertToTensor(boxes, 'boxes', 'nonMaxSuppression'); var $scores = tensor_util_env_1.convertToTensor(scores, 'scores', 'nonMaxSuppression'); var inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold); maxOutputSize = inputs.maxOutputSize; iouThreshold = inputs.iouThreshold; scoreThreshold = inputs.scoreThreshold; var attrs = { maxOutputSize: maxOutputSize, iouThreshold: iouThreshold, scoreThreshold: scoreThreshold }; return engine_1.ENGINE.runKernelFunc(function (b) { return b.nonMaxSuppression($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold); }, { boxes: $boxes, scores: $scores }, null /* grad */, 'NonMaxSuppressionV3', attrs); } /** This is the async version of `nonMaxSuppression` */ function nonMaxSuppressionAsync_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) { if (iouThreshold === void 0) { iouThreshold = 0.5; } if (scoreThreshold === void 0) { scoreThreshold = Number.NEGATIVE_INFINITY; } return __awaiter(this, void 0, void 0, function () { var $boxes, $scores, inputs, boxesAndScores, boxesVals, scoresVals, res; return __generator(this, function (_a) { switch (_a.label) { case 0: $boxes = tensor_util_env_1.convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync'); $scores = tensor_util_env_1.convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync'); inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold); maxOutputSize = inputs.maxOutputSize; iouThreshold = inputs.iouThreshold; scoreThreshold = inputs.scoreThreshold; return [4 /*yield*/, Promise.all([$boxes.data(), $scores.data()])]; case 1: boxesAndScores = _a.sent(); boxesVals = boxesAndScores[0]; scoresVals = boxesAndScores[1]; res = non_max_suppression_impl_1.nonMaxSuppressionV3(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold); if ($boxes !== boxes) { $boxes.dispose(); } if ($scores !== scores) { $scores.dispose(); } return [2 /*return*/, res]; } }); }); } /** * Performs non maximum suppression of bounding boxes based on * iou (intersection over union). * * This op also supports a Soft-NMS mode (c.f. * Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score * of other overlapping boxes, therefore favoring different regions of the image * with high scores. To enable this Soft-NMS mode, set the `softNmsSigma` * parameter to be larger than 0. * * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of * the bounding box. * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`. * @param maxOutputSize The maximum number of boxes to be selected. * @param iouThreshold A float representing the threshold for deciding whether * boxes overlap too much with respect to IOU. Must be between [0, 1]. * Defaults to 0.5 (50% box overlap). * @param scoreThreshold A threshold for deciding when to remove boxes based * on score. Defaults to -inf, which means any score is accepted. * @param softNmsSigma A float representing the sigma parameter for Soft NMS. * When sigma is 0, it falls back to nonMaxSuppression. * @return A map with the following properties: * - selectedIndices: A 1D tensor with the selected box indices. * - selectedScores: A 1D tensor with the corresponding scores for each * selected box. */ /** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */ function nonMaxSuppressionWithScore_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) { if (iouThreshold === void 0) { iouThreshold = 0.5; } if (scoreThreshold === void 0) { scoreThreshold = Number.NEGATIVE_INFINITY; } if (softNmsSigma === void 0) { softNmsSigma = 0.0; } var $boxes = tensor_util_env_1.convertToTensor(boxes, 'boxes', 'nonMaxSuppression'); var $scores = tensor_util_env_1.convertToTensor(scores, 'scores', 'nonMaxSuppression'); var inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma); maxOutputSize = inputs.maxOutputSize; iouThreshold = inputs.iouThreshold; scoreThreshold = inputs.scoreThreshold; softNmsSigma = inputs.softNmsSigma; var attrs = { maxOutputSize: maxOutputSize, iouThreshold: iouThreshold, scoreThreshold: scoreThreshold, softNmsSigma: softNmsSigma }; var result = engine_1.ENGINE.runKernel('NonMaxSuppressionV5', { boxes: $boxes, scores: $scores }, attrs); return { selectedIndices: result[0], selectedScores: result[1] }; } /** This is the async version of `nonMaxSuppressionWithScore` */ function nonMaxSuppressionWithScoreAsync_(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) { if (iouThreshold === void 0) { iouThreshold = 0.5; } if (scoreThreshold === void 0) { scoreThreshold = Number.NEGATIVE_INFINITY; } if (softNmsSigma === void 0) { softNmsSigma = 0.0; } return __awaiter(this, void 0, void 0, function () { var $boxes, $scores, inputs, boxesAndScores, boxesVals, scoresVals, res; return __generator(this, function (_a) { switch (_a.label) { case 0: $boxes = tensor_util_env_1.convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync'); $scores = tensor_util_env_1.convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync'); inputs = nonMaxSuppSanityCheck($boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma); maxOutputSize = inputs.maxOutputSize; iouThreshold = inputs.iouThreshold; scoreThreshold = inputs.scoreThreshold; softNmsSigma = inputs.softNmsSigma; return [4 /*yield*/, Promise.all([$boxes.data(), $scores.data()])]; case 1: boxesAndScores = _a.sent(); boxesVals = boxesAndScores[0]; scoresVals = boxesAndScores[1]; res = non_max_suppression_impl_1.nonMaxSuppressionV5(boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma); if ($boxes !== boxes) { $boxes.dispose(); } if ($scores !== scores) { $scores.dispose(); } return [2 /*return*/, res]; } }); }); } function nonMaxSuppSanityCheck(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma) { if (iouThreshold == null) { iouThreshold = 0.5; } if (scoreThreshold == null) { scoreThreshold = Number.NEGATIVE_INFINITY; } if (softNmsSigma == null) { softNmsSigma = 0.0; } var numBoxes = boxes.shape[0]; maxOutputSize = Math.min(maxOutputSize, numBoxes); util.assert(0 <= iouThreshold && iouThreshold <= 1, function () { return "iouThreshold must be in [0, 1], but was '" + iouThreshold + "'"; }); util.assert(boxes.rank === 2, function () { return "boxes must be a 2D tensor, but was of rank '" + boxes.rank + "'"; }); util.assert(boxes.shape[1] === 4, function () { return "boxes must have 4 columns, but 2nd dimension was " + boxes.shape[1]; }); util.assert(scores.rank === 1, function () { return 'scores must be a 1D tensor'; }); util.assert(scores.shape[0] === numBoxes, function () { return "scores has incompatible shape with boxes. Expected " + numBoxes + ", " + ("but was " + scores.shape[0]); }); util.assert(0 <= softNmsSigma && softNmsSigma <= 1, function () { return "softNmsSigma must be in [0, 1], but was '" + softNmsSigma + "'"; }); return { maxOutputSize: maxOutputSize, iouThreshold: iouThreshold, scoreThreshold: scoreThreshold, softNmsSigma: softNmsSigma }; } /** * Extracts crops from the input image tensor and resizes them using bilinear * sampling or nearest neighbor sampling (possibly with aspect ratio change) * to a common output size specified by crop_size. * * @param image 4d tensor of shape `[batch,imageHeight,imageWidth, depth]`, * where imageHeight and imageWidth must be positive, specifying the * batch of images from which to take crops * @param boxes 2d float32 tensor of shape `[numBoxes, 4]`. Each entry is * `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the normalized * coordinates of the box in the boxInd[i]'th image in the batch * @param boxInd 1d int32 tensor of shape `[numBoxes]` with values in range * `[0, batch)` that specifies the image that the `i`-th box refers to. * @param cropSize 1d int32 tensor of 2 elements `[cropHeigh, cropWidth]` * specifying the size to which all crops are resized to. * @param method Optional string from `'bilinear' | 'nearest'`, * defaults to bilinear, which specifies the sampling method for resizing * @param extrapolationValue A threshold for deciding when to remove boxes based * on score. Defaults to 0. * @return A 4D tensor of the shape `[numBoxes,cropHeight,cropWidth,depth]` */ /** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */ function cropAndResize_(image, boxes, boxInd, cropSize, method, extrapolationValue) { var $image = tensor_util_env_1.convertToTensor(image, 'image', 'cropAndResize'); var $boxes = tensor_util_env_1.convertToTensor(boxes, 'boxes', 'cropAndResize', 'float32'); var $boxInd = tensor_util_env_1.convertToTensor(boxInd, 'boxInd', 'cropAndResize', 'int32'); method = method || 'bilinear'; extrapolationValue = extrapolationValue || 0; var numBoxes = $boxes.shape[0]; util.assert($image.rank === 4, function () { return 'Error in cropAndResize: image must be rank 4,' + ("but got rank " + $image.rank + "."); }); util.assert($boxes.rank === 2 && $boxes.shape[1] === 4, function () { return "Error in cropAndResize: boxes must be have size [" + numBoxes + ",4] " + ("but had shape " + $boxes.shape + "."); }); util.assert($boxInd.rank === 1 && $boxInd.shape[0] === numBoxes, function () { return "Error in cropAndResize: boxInd must be have size [" + numBoxes + "] " + ("but had shape " + $boxes.shape + "."); }); util.assert(cropSize.length === 2, function () { return "Error in cropAndResize: cropSize must be of length 2, but got " + ("length " + cropSize.length + "."); }); util.assert(cropSize[0] >= 1 && cropSize[1] >= 1, function () { return "cropSize must be atleast [1,1], but was " + cropSize; }); util.assert(method === 'bilinear' || method === 'nearest', function () { return "method must be bilinear or nearest, but was " + method; }); var forward = function (backend, save) { return backend.cropAndResize($image, $boxes, $boxInd, cropSize, method, extrapolationValue); }; var res = engine_1.ENGINE.runKernelFunc(forward, { images: $image, boxes: $boxes, boxInd: $boxInd }, null /* der */, 'CropAndResize', { method: method, extrapolationValue: extrapolationValue, cropSize: cropSize }); return res; } exports.resizeBilinear = operation_1.op({ resizeBilinear_: resizeBilinear_ }); exports.resizeNearestNeighbor = operation_1.op({ resizeNearestNeighbor_: resizeNearestNeighbor_ }); exports.nonMaxSuppression = operation_1.op({ nonMaxSuppression_: nonMaxSuppression_ }); exports.nonMaxSuppressionAsync = nonMaxSuppressionAsync_; exports.nonMaxSuppressionWithScore = operation_1.op({ nonMaxSuppressionWithScore_: nonMaxSuppressionWithScore_ }); exports.nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_; exports.cropAndResize = operation_1.op({ cropAndResize_: cropAndResize_ }); //# sourceMappingURL=image_ops.js.map