code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
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();
}
| dotKom/onlineweb4 | assets/feedback/index.js | JavaScript | mit | 483 |
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; | davidkleriga/egyptian-number-system | Gruntfile.js | JavaScript | mit | 3,137 |
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');
});
});
| romankl/mission-log | test/test-missionlog.js | JavaScript | mit | 2,073 |
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);
| thibthib/maton | probe/probe.js | JavaScript | mit | 367 |
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)
})
})
| helpscout/blue | src/components/Stepper/Stepper.test.js | JavaScript | mit | 5,530 |
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;
}
| vstirbu/regio-camera | index.js | JavaScript | mit | 944 |
'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 () {
};
| IyadAssaf/portfol.io | app/util/object.js | JavaScript | mit | 261 |
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);
});
});
| jonwille/Frogger | test/pad-test.js | JavaScript | mit | 995 |
version https://git-lfs.github.com/spec/v1
oid sha256:fd2ad8a08df37f7b13dad35da22197faf51ef6887162bf5f74ce30df59fdba0f
size 15638
| yogeshsaroya/new-cdnjs | ajax/libs/deck.js/1.0.0/core/deck.core.js | JavaScript | mit | 130 |
// 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)}}}();
| MarkNijhof/client.express.js | dist/client.express-0.3.4.min.js | JavaScript | mit | 13,207 |
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);
| thedavisproject/davis-web | src/resolvers/entityLoaderFactory.js | JavaScript | mit | 661 |
'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'));
});
| shinnn/node-font2svg | test/test.js | JavaScript | mit | 9,142 |
'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: 'test@test.com',
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();
});
}); | hhkk/141118UsToDoV3 | app/tests/rawrecords3.server.routes.test.js | JavaScript | mit | 7,186 |
version https://git-lfs.github.com/spec/v1
oid sha256:b63ef97b9f85b0d4a07926b186083c9952568e26bbb65d610b592d15208f79a9
size 24953
| yogeshsaroya/new-cdnjs | ajax/libs/underscore.js/1.0.4/underscore.js | JavaScript | mit | 130 |
/* 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
| chromaway/blockchainjs | lib/blockchain/blockchain.js | JavaScript | mit | 4,218 |
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);
| calesce/tab-editor | src/components/editor/TimeSignaturePopover.js | JavaScript | mit | 5,636 |
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;
| minheq/grrupwa-boilerplate | scripts/build.js | JavaScript | mit | 563 |
export default from './unview.container'
| fabienjuif/react-redux-codelab | src/components/TVShow/Episodes/Episode/UnView/index.js | JavaScript | mit | 41 |
// 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*!|</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, '&').
replace(/</g, '<').
replace(/>/g, '>');
};
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> <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;
}());
| ept/bespin-on-rails | public/jsparse/fulljslint.js | JavaScript | mit | 175,398 |
(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);
};
}
]);
})();
| safaridato/travelite | assets/js/ng/ap.js | JavaScript | mit | 591 |
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)
}
}
| cchamberlain/redux-webpack-boilerplate | src/webpack/make.js | JavaScript | mit | 1,031 |
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"
},
]
},
]
});
| mrmicahcooper/taskdown | ember/app/controllers/shortcuts.js | JavaScript | mit | 1,568 |
/**
* @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);
}
}
};
}
};
| lauracurley/2016-08-ps-react | node_modules/eslint/lib/rules/no-shadow.js | JavaScript | mit | 6,853 |
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)
}
}
};
| Flexberry/ember-flexberry-designer | testem.js | JavaScript | mit | 555 |
/*
* 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);
| nickguletskii/OpenOlympus | src/main/resources/public/resources/js/services/userService.js | JavaScript | mit | 3,675 |
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;
});
| sailjs/overlay | overlay.js | JavaScript | mit | 924 |
"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": [] }] }; | xuan6/admin_dashboard_local_dev | node_modules/react-icons-kit/ionicons/androidUnlock.js | JavaScript | mit | 597 |
/* 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 });
}
}
*/
| infiniteschema/importio-query | js/my.js | JavaScript | mit | 5,121 |
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();
}
| marcos-sandim/phalcon-proj | public/js/app.js | JavaScript | mit | 1,175 |
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
});
});
| SKing7/extractor | index.js | JavaScript | mit | 257 |
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()
})
})
| pixelass/schachtel | scripts/build.js | JavaScript | mit | 1,530 |
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;
}
| unbug/generator-webappstarter | app/templates/app/src/lib/swing/vendor-prefix.js | JavaScript | mit | 1,162 |
'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
};
});
| mattlewis92/angular-bootstrap-calendar | src/directives/mwlCalendarHourList.js | JavaScript | mit | 4,724 |
'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);
});
});
| egonz/action-at-a-distance | test/spec/controllers/main.js | JavaScript | mit | 486 |
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
})
)
}; | Benguino/star-wars-project | src/components/CrawlChart.js | JavaScript | mit | 1,935 |
// 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];
});
}); | boolean99/gulp | src/webpack/main.js | JavaScript | mit | 3,459 |
version https://git-lfs.github.com/spec/v1
oid sha256:0f924f0bd38d3dfb7ebc34016ec96c018aee7fb62e1cd562898fdeb85ca7d283
size 2234
| yogeshsaroya/new-cdnjs | ajax/libs/timelinejs/2.26.1/js/locale/si.js | JavaScript | mit | 129 |
!(function(){
var spg = require('./simple-password-generator.js');
console.log(spg.generate({
length : 3
}));
})(); | edmarriner/simple-password-generator | example.js | JavaScript | mit | 124 |
/* @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 */
| TheCbac/MICA-Desktop | test/utils/dataStreams/graphBuffer.spec.js | JavaScript | mit | 13,026 |
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');
});
};
| samvandenberge/samvandenberge.github.io | Gruntfile.js | JavaScript | mit | 7,077 |
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);
});
});
| simplyianm/binarysearch-js | test.js | JavaScript | mit | 711 |
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);
})
}
} | auromota/easy-pizza-api | src/service/clientService.js | JavaScript | mit | 943 |
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([])
})
})
})
| KissKissBankBank/kitten | assets/javascripts/kitten/helpers/utils/range.test.js | JavaScript | mit | 1,232 |
/*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();
})();
| davidcunha/yo-backbone | app/scripts/collections/todos.js | JavaScript | mit | 1,325 |
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); | seraum/nectarjs | example/struct.js | JavaScript | mit | 489 |
// 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
};
})(); | gauravmm/AbacusMachineSim | machine.js | JavaScript | mit | 42,039 |
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;
}); | redexp/chat | js/view/rooms/users-rooms-list.js | JavaScript | mit | 979 |
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});
};
}; | Pranay92/collaborate-client | app/modules/messages/messages.controller.js | JavaScript | mit | 351 |
/**
* 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;
| hamxabaig/rfid-tags | client/src/containers/pages/LoginPage.js | JavaScript | mit | 4,990 |
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
$(function () {
$('[data-toggle="popover"]').popover()
}) | tochiton/NetBrigde | public/assets/js/script.js | JavaScript | mit | 120 |
'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;
| cablelabs/dev-portal | src/socket.io/custom.js | JavaScript | mit | 1,565 |
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;
} | kirill-kruchkov/tfl | src/app/tims.js | JavaScript | mit | 2,910 |
'use strict';
angular.module('cocoApp')
.directive('loginform', [function () {
return {
restrict: 'E',
controller: 'LoginInterceptCtrl',
scope: {
eventid: '='
},
templateUrl: 'partials/login.html'
};
}]);
| blang/coco | app/scripts/directives/loginform.js | JavaScript | mit | 256 |
/*
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);
| chatgris/sucreries | lib/vendor/assets/javascripts/sucreries/pow/pow.js | JavaScript | mit | 4,672 |
'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)
})
}
}
| okayumoka/Ponkan2 | src/macro/macro-stack.js | JavaScript | mit | 1,794 |
const interviewSchema = require('./interview.schema');
const InterviewModel = require('mongoose').model('Interview', interviewSchema);
module.exports = InterviewModel;
| JasonRammoray/interview-assistant | app/server/models/interview/interview.model.js | JavaScript | mit | 169 |
"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 | ManakCP/NestJs | node_modules/@tensorflow/tfjs-core/dist/ops/image_ops.js | JavaScript | mit | 21,358 |
(function(){
angular
.module("InteractionDesign")
.controller("ResultsChartController", ResultsChartController);
function ResultsChartController($scope, $location) {
$scope.$location = $location;
var data1 = [
{ x: new Date(2012, 00, 1), y: 12 },
{ x: new Date(2012, 00, 2), y: 13 },
{ x: new Date(2012, 00, 3), y: 16 },
{ x: new Date(2012, 00, 4), y: 37 },
{ x: new Date(2012, 00, 5), y: 39 },
{ x: new Date(2012, 00, 6), y: 42 },
{ x: new Date(2012, 00, 7), y: 25 },
{ x: new Date(2012, 00, 8), y: 18 },
{ x: new Date(2012, 00, 9), y: 22 },
{ x: new Date(2012, 00, 10), y: 25 },
{ x: new Date(2012, 00, 11), y: 25 },
{ x: new Date(2012, 00, 12), y: 28 }
];
var data2 = [
{ x: new Date(2012, 00, 1), y: 50 },
{ x: new Date(2012, 00, 2), y: 45 },
{ x: new Date(2012, 00, 3), y: 40 },
{ x: new Date(2012, 00, 4), y: 25 },
{ x: new Date(2012, 00, 5), y: 24 },
{ x: new Date(2012, 00, 6), y: 29 },
{ x: new Date(2012, 00, 7), y: 43 },
{ x: new Date(2012, 00, 8), y: 35 },
{ x: new Date(2012, 00, 9), y: 34 },
{ x: new Date(2012, 00, 10), y: 39 },
{ x: new Date(2012, 00, 11), y: 43 },
{ x: new Date(2012, 00, 12), y: 48 }
];
var data3 = [
{ x: new Date(2012, 00, 1), y: 26 },
{ x: new Date(2012, 00, 2), y: 25 },
{ x: new Date(2012, 00, 3), y: 23 },
{ x: new Date(2012, 00, 4), y: 20 },
{ x: new Date(2012, 00, 5), y: 17 },
{ x: new Date(2012, 00, 6), y: 17 },
{ x: new Date(2012, 00, 7), y: 17 },
{ x: new Date(2012, 00, 8), y: 18 },
{ x: new Date(2012, 00, 9), y: 12 },
{ x: new Date(2012, 00, 10), y: 8 },
{ x: new Date(2012, 00, 11), y: 8 },
{ x: new Date(2012, 00, 12), y: 12 }
];
var data4 = [
{ x: new Date(2012, 00, 1), y: 25 },
{ x: new Date(2012, 00, 2), y: 26 },
{ x: new Date(2012, 00, 3), y: 28 },
{ x: new Date(2012, 00, 4), y: 28 },
{ x: new Date(2012, 00, 5), y: 30 },
{ x: new Date(2012, 00, 6), y: 35 },
{ x: new Date(2012, 00, 7), y: 25 },
{ x: new Date(2012, 00, 8), y: 18 },
{ x: new Date(2012, 00, 9), y: 22 },
{ x: new Date(2012, 00, 10), y: 25 },
{ x: new Date(2012, 00, 11), y: 25 },
{ x: new Date(2012, 00, 12), y: 28 }
];
var data5 = [
{ x: new Date(2012, 00, 1), y: 25 },
{ x: new Date(2012, 00, 2), y: 24 },
{ x: new Date(2012, 00, 3), y: 45 },
{ x: new Date(2012, 00, 4), y: 29 },
{ x: new Date(2012, 00, 5), y: 24 },
{ x: new Date(2012, 00, 6), y: 29 },
{ x: new Date(2012, 00, 7), y: 18 },
{ x: new Date(2012, 00, 8), y: 22 },
{ x: new Date(2012, 00, 9), y: 25 },
{ x: new Date(2012, 00, 10), y: 25 },
{ x: new Date(2012, 00, 11), y: 28 },
{ x: new Date(2012, 00, 12), y: 28 }
];
var data6 = [
{ x: new Date(2012, 00, 1), y: 26 },
{ x: new Date(2012, 00, 2), y: 25 },
{ x: new Date(2012, 00, 3), y: 23 },
{ x: new Date(2012, 00, 4), y: 50 },
{ x: new Date(2012, 00, 5), y: 25 },
{ x: new Date(2012, 00, 6), y: 29 },
{ x: new Date(2012, 00, 7), y: 25 },
{ x: new Date(2012, 00, 8), y: 28 },
{ x: new Date(2012, 00, 9), y: 12 },
{ x: new Date(2012, 00, 10), y: 8 },
{ x: new Date(2012, 00, 11), y: 8 },
{ x: new Date(2012, 00, 12), y: 12 }
];
$scope.filters = [
{name: "Age", selected: false, options: [
{name: "18-24", selected: false},
{name: "25-34", selected: false},
{name: "35-49", selected: false},
{name: "50-65", selected: false},
{name: "65+", selected: false}
]},
{name: "Occupation", selected: false, options: [
{name: "Students", selected: false},
{name: "Blue-Collar", selected: false},
{name: "White-Collar", selected: false}
]},
{name: "Gender", selected: false, options: [
{name: "Male", selected: false},
{name: "Female", selected: false}
]},
{name: "State", selected: false, options: [
{name: "Alabama", selected: false},
{name: "Arkansas", selected: false},
{name: "New York", selected: false},
{name: "California", selected: false},
{name: "Massachusetts", selected: false}
]},
{name: "Political Party", selected: false, options: [
{name: "Democrat", selected: false},
{name: "Republican", selected: false}
]},
];
$scope.clickFilter = function(filter) {
for (filterIdx in $scope.filters) {
var theFilter = $scope.filters[filterIdx];
if (theFilter.name == filter.name && theFilter.selected == false) {
theFilter.selected = true;
}
else {
theFilter.selected = false;
for (optionIdx in theFilter.options) {
theFilter.options[optionIdx].selected = false;
}
}
}
}
$scope.clickSubOption = function(filter, subOption) {
for (filterIdx in $scope.filters) {
var theFilter = $scope.filters[filterIdx];
if (theFilter.name == filter.name && theFilter.selected == true) {
for (optionIdx in theFilter.options) {
var option = theFilter.options[optionIdx];
if (option.name == subOption.name && option.selected == false) {
option.selected = true;
}
else {
option.selected = false;
}
}
}
}
if (subOption.name == "18-24" && subOption.selected == true) {
reloadChart(data4, data5, data6, false, "Results 18-24");
}
else {
reloadChart(data1, data2, data3, false, "Results");
}
}
function reloadChart(data_1, data_2, data_3, animated, title) {
var chart = new CanvasJS.Chart("chartContainer",
{
theme: "theme2",
title:{
text: title
},
animationEnabled: animated,
axisX: {
valueFormatString: "MMM",
interval:1,
intervalType: "month"
},
axisY:{
includeZero: false
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Hillary Clinton",
dataPoints: data_1
},
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Bernie Sanders",
dataPoints: data_2
},
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Donald Trump",
dataPoints: data_3
}
]
});
chart.render();
}
reloadChart(data1, data2, data3, true, "Results");
}
})(); | lhaber9/RiskLegacyHCI | public/experiments/js/resultsChartController.js | JavaScript | mit | 7,139 |
// ch08-arrays--splice.js
'use strict';
// ADDING OR REMOVING ELEMENTS AT ANY POSITION
// SPLICE
// The first argument is the index you want to start modifying
// The second argument is the number of elements to remove (use 0 if you don’t want to remove any elements)
// The remaining arguments are the elements to be added
const arr = [1, 5, 7];
console.log(`arr: \t${arr}\tlength: \t${arr.length}`);
// arr: 1,5,7 length: 3
const arr1 = arr.splice(1, 0, 2, 3, 4);
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr1: \t${arr1}\tlength: ${arr1.length}`);
// arr: 1,2,3,4,5,7 length: 6 arr1: [] length: 0
const arr2 = arr.splice(5, 0, 6);
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr2: \t${arr2}\tlength: ${arr2.length}`);
// arr: 1,2,3,4,5,6,7 length: 7 arr2: [] length: 0
const arr3 = arr.splice(1, 2);
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr3: \t${arr3}\tlength: ${arr3.length}`);
// arr: 1,4,5,6,7 length: 5 arr3: 2,3 length: 2
const arr4 = arr.splice(2, 1, 'a', 'b');
console.log(`arr: \t${arr}\tlength: ${arr.length}\tarr4: \t${arr4}\tlength: ${arr4.length}`);
// arr: 1,4,a,b,6,7 length: 6 arr4: 5 length: 1
| Juantxo/learningJS | es6/ch08-arrays--splice.js | JavaScript | mit | 1,175 |
import { bind, unbind } from '@segmentstream/utils/eventListener'
import listenEvents from './listenEvents'
import Storage from '../Storage'
const timeout = 10 // 10 seconds
let interval = null
let hasActive = false
let events = []
const storagePrefix = 'timeOnSite:'
const storage = new Storage({ prefix: storagePrefix })
// Load from storage
let activeTime = storage.get('activeTime') || 0
let time = storage.get('time') || 0
const firedEventsJSON = storage.get('firedEvents')
let firedEvents = firedEventsJSON ? JSON.parse(firedEventsJSON) : []
const addEventsListener = () => {
listenEvents.forEach((eventName) => {
bind(window.document, eventName, setActive, false)
})
}
const removeEventsListener = () => {
listenEvents.forEach((eventName) => {
unbind(window.document, eventName, setActive, false)
})
}
const incActiveTime = () => {
activeTime += timeout
storage.set('activeTime', activeTime)
}
const incTime = () => {
time += timeout
storage.set('time', time)
}
const fireEvent = (eventName) => {
firedEvents.push(eventName)
storage.set('firedEvents', JSON.stringify(firedEvents))
}
const processEvents = () => {
if (hasActive) {
incActiveTime()
hasActive = false
}
incTime()
events.forEach((event) => {
const timeForEvent = event.isActiveTime ? activeTime : time
if (!firedEvents.includes(`${event.name}:${event.seconds}`) && event.seconds <= timeForEvent) {
event.handler(timeForEvent)
fireEvent(`${event.name}:${event.seconds}`)
}
})
}
const setActive = () => { hasActive = true }
const addEvent = (seconds, handler, eventName, isActiveTime) => {
events.push({ seconds, handler, isActiveTime, name: eventName })
}
const startTracking = () => {
interval = setInterval(processEvents, timeout * 1000)
addEventsListener()
}
const stopTracking = () => {
clearInterval(interval)
removeEventsListener()
}
startTracking()
export const reset = () => {
if (interval) {
stopTracking()
}
activeTime = 0
time = 0
hasActive = false
firedEvents = []
storage.remove('activeTime')
storage.remove('time')
storage.remove('firedEvents')
startTracking()
}
export default (seconds, handler, eventName, isActiveTime = false) => {
if (!seconds) return
if (typeof handler !== 'function') {
throw new TypeError('Must pass function handler to `ddManager.trackTimeOnSite`.')
}
String(seconds)
.replace(/\s+/mg, '')
.split(',')
.forEach((secondsStr) => {
const second = parseInt(secondsStr)
if (second > 0) {
addEvent(second, handler, eventName, isActiveTime)
}
})
}
| driveback/digital-data-manager | src/trackers/trackTimeOnSite.js | JavaScript | mit | 2,627 |
version https://git-lfs.github.com/spec/v1
oid sha256:81e9c9e173a9043e925313a488beecd37914141528b2ccf21df1fc5620343cb8
size 2512
| yogeshsaroya/new-cdnjs | ajax/libs/tinymce/3.5.8/plugins/advlink/langs/zh-tw_dlg.js | JavaScript | mit | 129 |
/* global bowlineApp */
function releaseModule($rootScope,$http,$timeout,login,ENV) {
console.log("!trace releaseModule instantiated, login status: ",login.status);
this.validator = {};
// This just gets all releases.
this.getReleases = function(mine,username,search,callback) {
var loginpack = {};
if (login.status) {
loginpack = login.sessionpack;
}
$http.post(ENV.api_url + '/api/getReleases', { session: loginpack, username: username, mineonly: mine, search: search })
.success(function(data){
// console.log("!trace getReleases data",data);
callback(null,data);
}.bind(this)).error(function(data){
callback("Had trouble with getReleases from API");
}.bind(this));
};
this.editRelease = function(release,add_release,callback) {
if (add_release) {
$http.post(ENV.api_url + '/api/addRelease', { release: release, session: login.sessionpack })
.success(function(addresult){
// console.log("!trace addRelease data",release);
callback(addresult.error,addresult.releaseid);
}.bind(this)).error(function(data){
callback("Had trouble with addRelease from API");
}.bind(this));
} else {
$http.post(ENV.api_url + '/api/editRelease', { release: release, session: login.sessionpack })
.success(function(release){
// console.log("!trace editRelease data",release);
callback(release.error,release.releaseid);
}.bind(this)).error(function(data){
callback("Had trouble with editRelease from API");
}.bind(this));
}
};
this.searchCollaborators = function(searchstring,callback) {
$http.post(ENV.api_url + '/api/searchCollaborators', { session: login.sessionpack, search: searchstring })
.success(function(users){
// console.log("!trace searchCollaborators release",release);
callback(null,users);
}.bind(this)).error(function(data){
callback("Had trouble with searchCollaborators from API");
}.bind(this));
};
// This just gets all releases.
this.getSingleRelease = function(id,callback) {
$http.post(ENV.api_url + '/api/getSingleRelease', { id: id, session: login.sessionpack })
.success(function(release){
// console.log("!trace getReleases release",release);
callback(null,release);
}.bind(this)).error(function(data){
callback("Had trouble with getSingleRelease from API");
}.bind(this));
};
// Get the tags for a release.
this.getTags = function(id,callback) {
$http.post(ENV.api_url + '/api/getTags', { releaseid: id, session: login.sessionpack })
.success(function(tags){
console.log("!trace getTags tags",tags);
callback(null,tags);
}.bind(this)).error(function(data){
callback("Had trouble with getTags from API");
}.bind(this));
};
// Get the validator for releases.
this.getReleaseValidator = function(callback) {
$http.post(ENV.api_url + '/api/getReleaseValidator', { session: login.sessionpack })
.success(function(data){
// console.log("!trace getReleaseValidator data",data);
callback(null,data);
this.validator = data;
}.bind(this)).error(function(data){
callback("Had trouble with getReleaseValidator from API");
}.bind(this));
};
this.forceUpdate = function(id,callback) {
$http.post(ENV.api_url + '/api/forceUpdate', { id: id, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace forceUpdate data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with forceUpdate from API");
}.bind(this));
};
this.getLogText = function(releaseid,logid,callback) {
$http.post(ENV.api_url + '/api/getLogText', { releaseid: releaseid, logid: logid, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace getLogText data",data);
callback(err,data.log);
}.bind(this)).error(function(data){
callback("Had trouble with getLogText from API");
}.bind(this));
};
this.getLogs = function(id,startpos,endpos,callback){
$http.post(ENV.api_url + '/api/getLogs', { id: id, session: login.sessionpack, startpos: startpos, endpos: endpos })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace getLogs data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with getLogs from API");
}.bind(this));
};
this.getFamily = function(id,callback){
$http.post(ENV.api_url + '/api/getFamily', { id: id, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace getFamily data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with getFamily from API");
}.bind(this));
};
this.validateJob = function(id,callback){
$http.post(ENV.api_url + '/api/validateJob', { id: id, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace validateJob data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with validateJob from API");
}.bind(this));
};
this.startJob = function(id,callback){
$http.post(ENV.api_url + '/api/startJob', { id: id, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace startJob data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with startJob from API");
}.bind(this));
};
this.stopJob = function(id,callback){
$http.post(ENV.api_url + '/api/stopJob', { id: id, session: login.sessionpack })
.success(function(data){
var err = null;
if (data.error) {
err = data.error;
}
// console.log("!trace stopJob data",data);
callback(err,data);
}.bind(this)).error(function(data){
callback("Had trouble with stopJob from API");
}.bind(this));
};
}
bowlineApp.factory('releaseModule', ["$rootScope", "$http", "$timeout", 'loginModule', 'ENV', function($rootScope,$http,$timeout,login,ENV) {
return new releaseModule($rootScope,$http,$timeout,login,ENV);
}]); | dougbtv/bowline | www/app/scripts/controllers/releaseModule.js | JavaScript | mit | 6,461 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//var winMae;
var wins;
//function mae2(idLink, maeNombre, winParent) {
// //alert(idLink.text());
//
// //alert($(idLink).text());
//
// var wins = new dhtmlXWindows();
// skin="dhx_terrace";
// wins.setSkin(skin);
// winId="win"+maeNombre;
// wins.createWindow(winId, 1, 1, 900, 530);
// wins.window(winId).setText("<h4>" + $(idLink).text() + "</h4>");
// wins.window(winId).setModal(true);
// wins.window(winId).button("minmax").disable();
// wins.window(winId).centerOnScreen();
// wins.window(winId).progressOn();
// wins.window(winId).setIconCss("without_icon");
// var urlParametros={'maeTipoId':maeTipoId, 'winParent': winParent, 'maeParametros': maeParametros};
// var url = Routing.generate('maestro', urlParametros);
// wins.window(winId).attachURL(url);
//
// wins.window(winId).attachEvent("onContentLoaded", function(id){
// //alert(id.id);
// id.progressOff();
// var ifr = id.getFrame();
// ifr.contentWindow.wins=wins;
// //ifr.contentWindow.winParent=winParent;
// //alert(ifr.contentWindow.winParent);
// });
//
//
//// alert(maeParametros);
//// var parametros = JSON.parse(maeParametros);
//// alert(parametros);
//////
//// for(x=0; x<parametros.length; x++) {
//// alert(parametros[x].maeNombre);
//// //console.log(parametros[x].description);
//// }
//}
function mae(maeTipoId, winParent, maeParametros) {
var wins = new dhtmlXWindows();
skin="dhx_terrace";
wins.setSkin(skin);
var url="";
switch (maeTipoId) {
case "1": //perfiles
winId="winPerfil";
//wins.createWindow(winId, 1, 1, 90, 60);
wins.createWindow(winId, 1, 1, 900, 630);
//wins.window(winId).setText("<h5>Perfil de cargo</h5>");
wins.window(winId).setText("Perfil de cargo");
var url = Routing.generate('perfil');
break;
case "2": //personas
winId="winPersona";
wins.createWindow(winId, 1, 1, 900, 530);
wins.window(winId).setText("Personas");
var url = Routing.generate('persona');
break;
case "3": //competencias
winId="winCompetencia";
wins.createWindow(winId, 1, 1, 900, 600);
wins.window(winId).setText("<h5>UCL's</h5>");
var url = Routing.generate('competencia');
break;
case "4": //actividadClave
winId="winActvidadClave";
wins.createWindow(winId, 1, 1, 700, 450);
wins.window(winId).setText("<h5>Competencia - Actividades Claves</h5>");
break;
case "5": //aprendizajes
winId="winAprendizaje";
wins.createWindow(winId, 1, 1, 900, 530);
wins.window(winId).setText("<h5>Conocimiento - Aprendizajes</h5>");
break;
case "6": //conocimientos
winId="winConocimiento";
wins.createWindow(winId, 1, 1, 900, 630);
wins.window(winId).setText("<h5>Competencias Conductuales</h5>");
var url = Routing.generate('conocimiento');
break;
case "7": //pregunta
winId="winPregunta";
wins.createWindow(winId, 1, 1, 900, 630);
wins.window(winId).setText("Cuestionario Evaluacion");
parametros=[{'preguntaTipoId': maeParametros}];
var maeParametros = JSON.stringify(parametros);
break;
case "8": //clientes
winId="winCliente";
wins.createWindow(winId, 1, 1, 900, 630);
wins.window(winId).setText("Clientes");
var url = Routing.generate('empresa');
break;
case "9": //cursos
winId="winCurso";
wins.createWindow(winId, 1, 1, 900, 630);
wins.window(winId).setText("Cursos");
break;
case "11": //evaluaciones
winId="winEvaluacion";
wins.createWindow(winId, 1, 1, 900, 630);
wins.window(winId).setText("Evaluaciones");
var url = Routing.generate('evaluacion');
break;
}
// switch (maeTipoId) {
// case 1:
// case 2:
// case 3:
// case 4:
// winId="winEntidad";
// wins.createWindow(winId, 1, 1, 900, 530);
// switch (maeTipoId) {
// case 1:
// wins.window(winId).setText("<h4>Clientes</h4>");
// break;
// case 2:
// wins.window(winId).setText("<h4>Proveedores</h4>");
// break;
// case 3:
// wins.window(winId).setText("<h4>Empresas de Factoring</h4>");
// break;
// case 4:
// wins.window(winId).setText("<h4>Empresas Mandantes</h4>");
// break;
// }
//
// break;
// case 5:
// winId="winEntidadDireccion";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Clientes - Direcciones</h4>");
// break;
// case 6:
// winId="winGlosaPago";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Glosas de Pago</h4>");
// break;
// case 7:
// winId="winVendedor";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Vendedores</h4>");
// break;
// case 8:
// winId="winComprador";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Compradores</h4>");
// break;
// case 9:
// winId="winObservacion";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Observaciones</h4>");
// break;
// case 10:
// winId="winSucursal";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Sucursales</h4>");
// break;
// case 11:
// winId="winBodega";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Bodegas</h4>");
// break;
// case 12:
// winId="winObra";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Obras</h4>");
// break;
// case 13:
// winId="winCuentaBanco";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Cuentas Bancos</h4>");
// break;
// case 14:
// winId="winProducto";
// wins.createWindow(winId, 1, 1, 900, 530);
// wins.window(winId).setText("<h4>Servicios o Productos</h4>");
// break;
// case 15:
// winId="winProductoFamilia";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Productos o Servicios - Familias</h4>");
// break;
// case 16:
// winId="winListaPrecio";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Lista de Precios</h4>");
// break;
// case 17:
// winId="winCentroCosto";
// wins.createWindow(winId, 1, 1, 800, 430);
// wins.window(winId).setText("<h4>Centros de Costo</h4>");
// break;
// case 18:
// winId="winCurso";
// wins.createWindow(winId, 1, 1, 900, 530);
// wins.window(winId).setText("<h4>Cursos</h4>");
// break;
// case 19:
// winId="winRelator";
// wins.createWindow(winId, 1, 1, 900, 530);
// wins.window(winId).setText("<h4>Relatores</h4>");
// break;
// }
//win.window("VtnResumenLibro").
wins.window(winId).setModal(true);
//winReferenciaForm.setText("<span class='text_title_header'>Header Text</span>");
//winReferenciaForm.button("close").disable();
wins.window(winId).button("minmax").disable();
//winFac.attachObject("dvReferencias", false);
wins.window(winId).centerOnScreen();
//winReferenciaForm.attachHTMLString("hola!");
//dhxWins.window(id).progressOn();
wins.window(winId).progressOn();
//dhxWins.window(id).setIconCss(css);
//wins.window(winId).setIconCss("without_icon");
//var urlParametros={'maeTipoId':maeTipoId, 'winParent': winParent, 'maeParametros': maeParametros};
//var url = Routing.generate('maestro', urlParametros);
//alert(url);
wins.window(winId).attachURL(url);
wins.window(winId).attachEvent("onContentLoaded", function(id){
//alert(id.id);
id.progressOff();
var ifr = id.getFrame();
ifr.contentWindow.wins=wins;
//ifr.contentWindow.winParent=winParent;
//alert(ifr.contentWindow.winParent);
});
}
function maeVolver(maeTipoId, winParent, winName, maeParametros) {
winId=winName;
wins.window(winId).progressOn();
var jsnParametros = JSON.stringify(maeParametros);
var urlParametros = {'maeTipoId': maeTipoId, 'winParent':winParent, 'maeParametros': jsnParametros};
var url=Routing.generate('maestro', urlParametros);
document.location.href=url;
}
| mujd/Tarea6 | web/public/js/mae/maeFunciones.js | JavaScript | mit | 10,330 |
// Generated by CoffeeScript 1.7.1
(function() {
var M, TRM, TYPES, alert, badge, debug, echo, help, info, log, njs_fs, options, rainbow, rpr, urge, warn, whisper,
__slice = [].slice;
njs_fs = require('fs');
TYPES = require('coffeenode-types');
TRM = require('coffeenode-trm');
rpr = TRM.rpr.bind(TRM);
badge = 'HOLLERITH/KEY';
log = TRM.get_logger('plain', badge);
info = TRM.get_logger('info', badge);
whisper = TRM.get_logger('whisper', badge);
alert = TRM.get_logger('alert', badge);
debug = TRM.get_logger('debug', badge);
warn = TRM.get_logger('warn', badge);
help = TRM.get_logger('help', badge);
urge = TRM.get_logger('urge', badge);
echo = TRM.echo.bind(TRM);
rainbow = TRM.rainbow.bind(TRM);
options = require('../../options');
M = options['marks'];
/*
*===========================================================================================================
888b 888 8888888888 888 888
8888b 888 888 888 o 888
88888b 888 888 888 d8b 888
888Y88b 888 8888888 888 d888b 888
888 Y88b888 888 888d88888b888
888 Y88888 888 88888P Y88888
888 Y8888 888 8888P Y8888
888 Y888 8888888888 888P Y888
*===========================================================================================================
*/
this.new_key = function() {
var complement, complement_esc, datatype, idx, idxs, index_count, pad, predicate, predicate_esc, schema, theme, theme_esc, topic, topic_esc, type;
schema = arguments[0], theme = arguments[1], topic = arguments[2], predicate = arguments[3], complement = arguments[4], idx = 6 <= arguments.length ? __slice.call(arguments, 5) : [];
/* TAINT should go to `hollerith/KEY` */
if ((datatype = schema[predicate]) == null) {
throw new Error("unknown datatype " + (rpr(predicate)));
}
index_count = datatype['index-count'], type = datatype.type, pad = datatype.pad;
if (index_count !== idx.length) {
throw new Error("need " + index_count + " indices for predicate " + (rpr(predicate)) + ", got " + idx.length);
}
theme_esc = KEY.esc(theme);
topic_esc = KEY.esc(topic);
predicate_esc = KEY.esc(predicate);
complement_esc = KEY.esc(complement);
/* TAINT parametrize */
idxs = index_count === 0 ? '' : idxs.join(',');
return 's' + '|' + theme_esc + '|' + topic_esc + '|' + predicate_esc + '|' + complement_esc + '|' + idxs;
};
/*
*===========================================================================================================
.d88888b. 888 8888888b.
d88P" "Y88b 888 888 "Y88b
888 888 888 888 888
888 888 888 888 888
888 888 888 888 888
888 888 888 888 888
Y88b. .d88P 888 888 .d88P
"Y88888P" 88888888 8888888P"
*===========================================================================================================
*/
this.new_route = function(realm, type, name) {
var R, part;
R = [realm, type];
if (name != null) {
R.push(name);
}
return ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = R.length; _i < _len; _i++) {
part = R[_i];
_results.push(this.esc(part));
}
return _results;
}).call(this)).join(M['slash']);
};
this.new_id = function(realm, type, idn) {
var slash;
slash = M['slash'];
return (this.new_route(realm, type)) + slash + (this.esc(idn));
};
this.new_node = function() {
var R, crumb, idn, joiner, realm, tail, type;
realm = arguments[0], type = arguments[1], idn = arguments[2], tail = 4 <= arguments.length ? __slice.call(arguments, 3) : [];
joiner = M['joiner'];
R = M['primary'] + M['node'] + joiner + (this.new_id(realm, type, idn));
if (tail.length > 0) {
R += M['slash'] + (((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = tail.length; _i < _len; _i++) {
crumb = tail[_i];
_results.push(this.esc(crumb));
}
return _results;
}).call(this)).join(M['slash']));
}
R += joiner;
return R;
};
this.new_secondary_node = function() {
var R, crumb, idn, joiner, realm, slash, tail, type;
realm = arguments[0], type = arguments[1], idn = arguments[2], tail = 4 <= arguments.length ? __slice.call(arguments, 3) : [];
joiner = M['joiner'];
slash = M['slash'];
R = M['secondary'] + M['node'] + slash + (this.esc(realm)) + (this.esc(type));
if (tail.length > 0) {
R += joiner + (((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = tail.length; _i < _len; _i++) {
crumb = tail[_i];
_results.push(this.esc(crumb));
}
return _results;
}).call(this)).join(slash));
}
R += joiner + (this.esc(idn)) + joiner;
return R;
};
this.new_facet_pair = function(realm, type, idn, name, value, distance) {
if (distance == null) {
distance = 0;
}
return [this.new_facet(realm, type, idn, name, value, distance), this.new_secondary_facet(realm, type, idn, name, value, distance)];
};
this.new_facet = function(realm, type, idn, name, value, distance) {
var joiner;
if (distance == null) {
distance = 0;
}
joiner = M['joiner'];
return M['primary'] + M['facet'] + joiner + (this.new_id(realm, type, idn)) + joiner + (this.esc(name)) + joiner + (this.esc(value)) + joiner + distance + joiner;
};
this.new_secondary_facet = function(realm, type, idn, name, value, distance) {
var joiner;
if (distance == null) {
distance = 0;
}
joiner = M['joiner'];
return M['secondary'] + M['facet'] + joiner + (this.new_route(realm, type)) + joiner + (this.esc(name)) + joiner + (this.esc(value)) + joiner + (this.esc(idn)) + joiner + distance + joiner;
};
this.new_link_pair = function(realm_0, type_0, idn_0, realm_1, type_1, idn_1, distance) {
if (distance == null) {
distance = 0;
}
return [this.new_link(realm_0, type_0, idn_0, realm_1, type_1, idn_1, distance), this.new_secondary_link(realm_0, type_0, idn_0, realm_1, type_1, idn_1, distance)];
};
this.new_link = function(realm_0, type_0, idn_0, realm_1, type_1, idn_1, distance) {
var joiner;
if (distance == null) {
distance = 0;
}
joiner = M['joiner'];
return M['primary'] + M['link'] + joiner + (this.new_id(realm_0, type_0, idn_0)) + joiner + (this.new_id(realm_1, type_1, idn_1)) + joiner + distance + joiner;
};
this.new_secondary_link = function(realm_0, type_0, idn_0, realm_1, type_1, idn_1, distance) {
var joiner;
if (distance == null) {
distance = 0;
}
joiner = M['joiner'];
return M['secondary'] + M['link'] + joiner + (this.new_route(realm_0, type_0)) + joiner + (this.new_id(realm_1, type_1, idn_1)) + joiner + (this.esc(idn_0)) + joiner + distance + joiner;
};
this.read = function(key) {
var R, fields, layer, type, _ref, _ref1;
_ref = key.split(M['joiner']), (_ref1 = _ref[0], layer = _ref1[0], type = _ref1[1]), fields = 2 <= _ref.length ? __slice.call(_ref, 1) : [];
switch (layer) {
case M['primary']:
switch (type) {
case M['node']:
R = this._read_primary_node.apply(this, fields);
break;
case M['facet']:
R = this._read_primary_facet.apply(this, fields);
break;
case M['link']:
R = this._read_primary_link.apply(this, fields);
break;
default:
throw new Error("unknown type mark " + (rpr(type)));
}
break;
case M['secondary']:
switch (type) {
case M['facet']:
R = this._read_secondary_facet.apply(this, fields);
break;
case M['link']:
R = this._read_secondary_link.apply(this, fields);
break;
default:
throw new Error("unknown type mark " + (rpr(type)));
}
break;
default:
throw new Error("unknown layer mark " + (rpr(layer)));
}
R['key'] = key;
return R;
};
this._read_primary_node = function(id) {
var R;
R = {
level: 'primary',
type: 'node',
id: id
};
return R;
};
this._read_primary_facet = function(id, name, value, distance) {
var R;
R = {
level: 'primary',
type: 'facet',
id: id,
name: name,
value: value,
distance: parseInt(distance, 10)
};
return R;
};
this._read_primary_link = function(id_0, id_1, distance) {
var R;
R = {
level: 'primary',
type: 'link',
id: id_0,
target: id_1,
distance: parseInt(distance, 10)
};
return R;
};
this._read_secondary_facet = function(route, name, value, idn, distance) {
var R;
R = {
level: 'secondary',
type: 'facet',
id: route + M['slash'] + idn,
name: name,
value: value,
distance: parseInt(distance, 10)
};
return R;
};
this._read_secondary_link = function(route_0, id_1, idn_0, distance) {
var R, id_0;
id_0 = route_0 + M['slash'] + idn_0;
R = {
level: 'secondary',
type: 'link',
id: id_0,
target: id_1,
distance: parseInt(distance, 10)
};
return R;
};
this.infer = function(key_0, key_1) {
return this._infer(key_0, key_1, 'primary');
};
this.infer_secondary = function(key_0, key_1) {
return this._infer(key_0, key_1, 'secondary');
};
this.infer_pair = function(key_0, key_1) {
return this._infer(key_0, key_1, 'pair');
};
this._infer = function(key_0, key_1, mode) {
var id_1, id_2, info_0, info_1, type_0, type_1;
info_0 = TYPES.isa_text(key_0) ? this.read(key_0) : key_0;
info_1 = TYPES.isa_text(key_1) ? this.read(key_1) : key_1;
if ((type_0 = info_0['type']) === 'link') {
if ((id_1 = info_0['target']) !== (id_2 = info_1['id'])) {
throw new Error("unable to infer link from " + (rpr(info_0['key'])) + " and " + (rpr(info_1['key'])));
}
switch (type_1 = info_1['type']) {
case 'link':
return this._infer_link(info_0, info_1, mode);
case 'facet':
return this._infer_facet(info_0, info_1, mode);
}
}
throw new Error("expected a link plus a link or a facet, got a " + type_0 + " and a " + type_1);
};
this._infer_facet = function(link, facet, mode) {
var distance, facet_idn, facet_realm, facet_type, link_idn, link_realm, link_type, name, slash, value, _ref, _ref1;
_ref = this.split_id(link['id']), link_realm = _ref[0], link_type = _ref[1], link_idn = _ref[2];
_ref1 = this.split_id(link['id']), facet_realm = _ref1[0], facet_type = _ref1[1], facet_idn = _ref1[2];
/* TAINT route not distinct from ID? */
/* TAINT should slashes in name be escaped? */
/* TAINT what happens when we infer from an inferred facet? do all the escapes get re-escaped? */
/* TAINT use module method */
slash = M['slash'];
/* TAINT make use of dash configurable */
name = (this.esc(facet_realm)) + '-' + (this.esc(facet_type)) + '-' + (this.esc(facet['name']));
value = facet['value'];
distance = link['distance'] + facet['distance'] + 1;
switch (mode) {
case 'primary':
return this.new_facet(link_realm, link_type, link_idn, name, value, distance);
case 'secondary':
return this.new_secondary_facet(link_realm, link_type, link_idn, name, value, distance);
case 'pair':
return this.new_facet_pair(link_realm, link_type, link_idn, name, value, distance);
default:
throw new Error("unknown mode " + (rpr(mode)));
}
};
this._infer_link = function(link_0, link_1, mode) {
/*
$^|gtfs/stoptime/876|0|gtfs/trip/456
+ $^|gtfs/trip/456|0|gtfs/route/777
----------------------------------------------------------------
= $^|gtfs/stoptime/876|1|gtfs/route/777
= %^|gtfs/stoptime|1|gtfs/route/777|876
*/
var distance, idn_0, idn_2, realm_0, realm_2, type_0, type_2, _ref, _ref1;
_ref = this.split_id(link_0['id']), realm_0 = _ref[0], type_0 = _ref[1], idn_0 = _ref[2];
_ref1 = this.split_id(link_1['target']), realm_2 = _ref1[0], type_2 = _ref1[1], idn_2 = _ref1[2];
distance = link_0['distance'] + link_1['distance'] + 1;
switch (mode) {
case 'primary':
return this.new_link(realm_0, type_0, idn_0, realm_2, type_2, idn_2, distance);
case 'secondary':
return this.new_secondary_link(realm_0, type_0, idn_0, realm_2, type_2, idn_2, distance);
case 'pair':
return this.new_link_pair(realm_0, type_0, idn_0, realm_2, type_2, idn_2, distance);
default:
throw new Error("unknown mode " + (rpr(mode)));
}
};
this.esc = (function() {
/* TAINT too complected */
var d, escape, joiner_matcher, joiner_replacer;
escape = function(text) {
var R;
R = text;
R = R.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1');
R = R.replace(/\x08/g, '\\x08');
return R;
};
joiner_matcher = new RegExp(escape(M['joiner']), 'g');
/* TAINT not correct, could be single digit if byte value < 0x10 */
joiner_replacer = ((function() {
var _i, _len, _ref, _results;
_ref = new Buffer(M['joiner']);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
d = _ref[_i];
_results.push('µ' + d.toString(16));
}
return _results;
})()).join('');
return function(x) {
var R;
if (x === void 0) {
throw new Error("value cannot be undefined");
}
R = TYPES.isa_text(x) ? x : rpr(x);
R = R.replace(/µ/g, 'µb5');
R = R.replace(joiner_matcher, joiner_replacer);
return R;
};
})();
this.unescape = function(text_esc) {
var matcher;
matcher = /µ([0-9a-f]{2})/g;
return text_esc.replace(matcher, function(_, cid_hex) {
return String.fromCharCode(parseInt(cid_hex, 16));
});
};
this.split_id = function(id) {
/* TAINT must unescape */
var R, slash;
R = id.split(slash = M['slash']);
if (R.length !== 3) {
throw new Error("expected three parts separated by " + (rpr(slash)) + ", got " + (rpr(id)));
}
if (!(R[0].length > 0)) {
throw new Error("realm cannot be empty in " + (rpr(id)));
}
if (!(R[1].length > 0)) {
throw new Error("type cannot be empty in " + (rpr(id)));
}
if (!(R[2].length > 0)) {
throw new Error("IDN cannot be empty in " + (rpr(id)));
}
return R;
};
this.split = function(x) {
return x.split(M['joiner']);
};
this.split_compound_selector = function(compound_selector) {
/* TAINT must unescape */
return compound_selector.split(M['loop']);
};
this._idn_from_id = function(id) {
var match;
match = id.replace(/^.+?([^\/]+)$/);
if (match == null) {
throw new Error("not a valid ID: " + (rpr(id)));
}
return match[1];
};
this.lte_from_gte = function(gte) {
var R, length;
length = Buffer.byteLength(gte);
R = new Buffer(1 + length);
R.write(gte);
R[length] = 0xff;
return R;
};
if (module.parent == null) {
help(this.new_id('gtfs', 'stop', '123'));
help(this.new_facet('gtfs', 'stop', '123', 'name', 1234));
help(this.new_facet('gtfs', 'stop', '123', 'name', 'foo/bar|baz'));
help(this.new_facet('gtfs', 'stop', '123', 'name', 'Bayerischer Platz'));
help(this.new_secondary_facet('gtfs', 'stop', '123', 'name', 'Bayerischer Platz'));
help(this.new_facet_pair('gtfs', 'stop', '123', 'name', 'Bayerischer Platz'));
help(this.new_link('gtfs', 'stoptime', '456', 'gtfs', 'stop', '123'));
help(this.new_secondary_link('gtfs', 'stoptime', '456', 'gtfs', 'stop', '123'));
help(this.new_link_pair('gtfs', 'stoptime', '456', 'gtfs', 'stop', '123'));
help(this.read(this.new_facet('gtfs', 'stop', '123', 'name', 'Bayerischer Platz')));
help(this.read(this.new_secondary_facet('gtfs', 'stop', '123', 'name', 'Bayerischer Platz')));
help(this.read(this.new_link('gtfs', 'stoptime', '456', 'gtfs', 'stop', '123')));
help(this.read(this.new_secondary_link('gtfs', 'stoptime', '456', 'gtfs', 'stop', '123')));
help(this.infer('$^|gtfs/stoptime/876|0|gtfs/trip/456', '$^|gtfs/trip/456|0|gtfs/route/777'));
help(this.infer('$^|gtfs/stoptime/876|0|gtfs/trip/456', '%^|gtfs/trip|0|gtfs/route/777|456'));
help(this.infer('$^|gtfs/trip/456|0|gtfs/stop/123', '$:|gtfs/stop/123|0|name|Bayerischer Platz'));
help(this.infer('$^|gtfs/stoptime/876|1|gtfs/stop/123', '$:|gtfs/stop/123|0|name|Bayerischer Platz'));
}
}).call(this);
| loveencounterflow/hollerith1 | lib/scratch/KEY.js | JavaScript | mit | 16,912 |
"use strict";
var Construct = require("can-construct");
var define = require("can-define");
var make = define.make;
var queues = require("can-queues");
var addTypeEvents = require("can-event-queue/type/type");
var ObservationRecorder = require("can-observation-recorder");
var canLog = require("can-log");
var canLogDev = require("can-log/dev/dev");
var defineHelpers = require("../define-helpers/define-helpers");
var assign = require("can-assign");
var diff = require("can-diff/list/list");
var ns = require("can-namespace");
var canReflect = require("can-reflect");
var canSymbol = require("can-symbol");
var singleReference = require("can-single-reference");
var splice = [].splice;
var runningNative = false;
var identity = function(x) {
return x;
};
// symbols aren't enumerable ... we'd need a version of Object that treats them that way
var localOnPatchesSymbol = "can.patches";
var makeFilterCallback = function(props) {
return function(item) {
for (var prop in props) {
if (item[prop] !== props[prop]) {
return false;
}
}
return true;
};
};
var onKeyValue = define.eventsProto[canSymbol.for("can.onKeyValue")];
var offKeyValue = define.eventsProto[canSymbol.for("can.offKeyValue")];
var getSchemaSymbol = canSymbol.for("can.getSchema");
var inSetupSymbol = canSymbol.for("can.initializing");
function getSchema() {
var definitions = this.prototype._define.definitions;
var schema = {
type: "list",
keys: {}
};
schema = define.updateSchemaKeys(schema, definitions);
if(schema.keys["#"]) {
schema.values = definitions["#"].Type;
delete schema.keys["#"];
}
return schema;
}
/** @add can-define/list/list */
var DefineList = Construct.extend("DefineList",
/** @static */
{
setup: function(base) {
if (DefineList) {
addTypeEvents(this);
var prototype = this.prototype;
var result = define(prototype, prototype, base.prototype._define);
define.makeDefineInstanceKey(this, result);
var itemsDefinition = result.definitions["#"] || result.defaultDefinition;
if (itemsDefinition) {
if (itemsDefinition.Type) {
this.prototype.__type = make.set.Type("*", itemsDefinition.Type, identity);
} else if (itemsDefinition.type) {
this.prototype.__type = make.set.type("*", itemsDefinition.type, identity);
}
}
this[getSchemaSymbol] = getSchema;
}
}
},
/** @prototype */
{
// setup for only dynamic DefineMap instances
setup: function(items) {
if (!this._define) {
Object.defineProperty(this, "_define", {
enumerable: false,
value: {
definitions: {
length: { type: "number" },
_length: { type: "number" }
}
}
});
Object.defineProperty(this, "_data", {
enumerable: false,
value: {}
});
}
define.setup.call(this, {}, false);
Object.defineProperty(this, "_length", {
enumerable: false,
configurable: true,
writable: true,
value: 0
});
if (items) {
this.splice.apply(this, [ 0, 0 ].concat(canReflect.toArray(items)));
}
},
__type: define.types.observable,
_triggerChange: function(attr, how, newVal, oldVal) {
var index = +attr;
// `batchTrigger` direct add and remove events...
// Make sure this is not nested and not an expando
if ( !isNaN(index)) {
var itemsDefinition = this._define.definitions["#"];
var patches, dispatched;
if (how === 'add') {
if (itemsDefinition && typeof itemsDefinition.added === 'function') {
ObservationRecorder.ignore(itemsDefinition.added).call(this, newVal, index);
}
patches = [{type: "splice", insert: newVal, index: index, deleteCount: 0}];
dispatched = {
type: how,
action: "splice",
insert: newVal,
index: index,
deleteCount: 0,
patches: patches
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
dispatched.reasonLog = [ canReflect.getName(this), "added", newVal, "at", index ];
}
//!steal-remove-end
this.dispatch(dispatched, [ newVal, index ]);
} else if (how === 'remove') {
if (itemsDefinition && typeof itemsDefinition.removed === 'function') {
ObservationRecorder.ignore(itemsDefinition.removed).call(this, oldVal, index);
}
patches = [{type: "splice", index: index, deleteCount: oldVal.length}];
dispatched = {
type: how,
patches: patches,
action: "splice",
index: index, deleteCount: oldVal.length,
target: this
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
dispatched.reasonLog = [ canReflect.getName(this), "remove", oldVal, "at", index ];
}
//!steal-remove-end
this.dispatch(dispatched, [ oldVal, index ]);
} else {
this.dispatch(how, [ newVal, index ]);
}
} else {
this.dispatch({
type: "" + attr,
target: this
}, [ newVal, oldVal ]);
}
},
get: function(index) {
if (arguments.length) {
if(isNaN(index)) {
ObservationRecorder.add(this, index);
} else {
ObservationRecorder.add(this, "length");
}
return this[index];
} else {
return canReflect.unwrap(this, Map);
}
},
set: function(prop, value) {
// if we are setting a single value
if (typeof prop !== "object") {
// We want change events to notify using integers if we're
// setting an integer index. Note that <float> % 1 !== 0;
prop = isNaN(+prop) || (prop % 1) ? prop : +prop;
if (typeof prop === "number") {
// Check to see if we're doing a .attr() on an out of
// bounds index property.
if (typeof prop === "number" &&
prop > this._length - 1) {
var newArr = new Array((prop + 1) - this._length);
newArr[newArr.length - 1] = value;
this.push.apply(this, newArr);
return newArr;
}
this.splice(prop, 1, value);
} else {
var defined = defineHelpers.defineExpando(this, prop, value);
if (!defined) {
this[prop] = value;
}
}
}
// otherwise we are setting multiple
else {
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
canLogDev.warn('can-define/list/list.prototype.set is deprecated; please use can-define/list/list.prototype.assign or can-define/list/list.prototype.update instead');
}
//!steal-remove-end
//we are deprecating this in #245
if (canReflect.isListLike(prop)) {
if (value) {
this.replace(prop);
} else {
canReflect.assignList(this, prop);
}
} else {
canReflect.assignMap(this, prop);
}
}
return this;
},
assign: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.assignList(this, prop);
} else {
canReflect.assignMap(this, prop);
}
return this;
},
update: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.updateList(this, prop);
} else {
canReflect.updateMap(this, prop);
}
return this;
},
assignDeep: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.assignDeepList(this, prop);
} else {
canReflect.assignDeepMap(this, prop);
}
return this;
},
updateDeep: function(prop) {
if (canReflect.isListLike(prop)) {
canReflect.updateDeepList(this, prop);
} else {
canReflect.updateDeepMap(this, prop);
}
return this;
},
_items: function() {
var arr = [];
this._each(function(item) {
arr.push(item);
});
return arr;
},
_each: function(callback) {
for (var i = 0, len = this._length; i < len; i++) {
callback(this[i], i);
}
},
splice: function(index, howMany) {
var args = canReflect.toArray(arguments),
added = [],
i, len, listIndex,
allSame = args.length > 2,
oldLength = this._length;
index = index || 0;
// converting the arguments to the right type
for (i = 0, len = args.length - 2; i < len; i++) {
listIndex = i + 2;
args[listIndex] = this.__type(args[listIndex], listIndex);
added.push(args[listIndex]);
// Now lets check if anything will change
if (this[i + index] !== args[listIndex]) {
allSame = false;
}
}
// if nothing has changed, then return
if (allSame && this._length <= added.length) {
return added;
}
// default howMany if not provided
if (howMany === undefined) {
howMany = args[1] = this._length - index;
}
runningNative = true;
var removed = splice.apply(this, args);
runningNative = false;
queues.batch.start();
if (howMany > 0) {
// tears down bubbling
this._triggerChange("" + index, "remove", undefined, removed);
}
if (args.length > 2) {
this._triggerChange("" + index, "add", added, removed);
}
this.dispatch('length', [ this._length, oldLength ]);
queues.batch.stop();
return removed;
},
/**
*/
serialize: function() {
return canReflect.serialize(this, Map);
}
}
);
for(var prop in define.eventsProto) {
Object.defineProperty(DefineList.prototype, prop, {
enumerable:false,
value: define.eventsProto[prop],
writable: true
});
}
var eventsProtoSymbols = ("getOwnPropertySymbols" in Object) ?
Object.getOwnPropertySymbols(define.eventsProto) :
[canSymbol.for("can.onKeyValue"), canSymbol.for("can.offKeyValue")];
eventsProtoSymbols.forEach(function(sym) {
Object.defineProperty(DefineList.prototype, sym, {
configurable: true,
enumerable:false,
value: define.eventsProto[sym],
writable: true
});
});
// Converts to an `array` of arguments.
var getArgs = function(args) {
return args[0] && Array.isArray(args[0]) ?
args[0] :
canReflect.toArray(args);
};
// Create `push`, `pop`, `shift`, and `unshift`
canReflect.eachKey({
push: "length",
unshift: 0
},
// Adds a method
// `name` - The method name.
// `where` - Where items in the `array` should be added.
function(where, name) {
var orig = [][name];
DefineList.prototype[name] = function() {
// Get the items being added.
var args = [],
// Where we are going to add items.
len = where ? this._length : 0,
i = arguments.length,
res, val;
// Go through and convert anything to a `map` that needs to be converted.
while (i--) {
val = arguments[i];
args[i] = this.__type(val, i);
}
// Call the original method.
runningNative = true;
res = orig.apply(this, args);
runningNative = false;
if (!this.comparator || args.length) {
queues.batch.start();
this._triggerChange("" + len, "add", args, undefined);
this.dispatch('length', [ this._length, len ]);
queues.batch.stop();
}
return res;
};
});
canReflect.eachKey({
pop: "length",
shift: 0
},
// Creates a `remove` type method
function(where, name) {
var orig = [][name];
DefineList.prototype[name] = function() {
if (!this._length) {
// For shift and pop, we just return undefined without
// triggering events.
return undefined;
}
var args = getArgs(arguments),
len = where && this._length ? this._length - 1 : 0,
oldLength = this._length ? this._length : 0,
res;
// Call the original method.
runningNative = true;
res = orig.apply(this, args);
runningNative = false;
// Create a change where the args are
// `len` - Where these items were removed.
// `remove` - Items removed.
// `undefined` - The new values (there are none).
// `res` - The old, removed values (should these be unbound).
queues.batch.start();
this._triggerChange("" + len, "remove", undefined, [ res ]);
this.dispatch('length', [ this._length, oldLength ]);
queues.batch.stop();
return res;
};
});
canReflect.eachKey({
"map": 3,
"filter": 3,
"reduce": 4,
"reduceRight": 4,
"every": 3,
"some": 3
},
function a(fnLength, fnName) {
DefineList.prototype[fnName] = function() {
var self = this;
var args = [].slice.call(arguments, 0);
var callback = args[0];
var thisArg = args[fnLength - 1] || self;
if (typeof callback === "object") {
callback = makeFilterCallback(callback);
}
args[0] = function() {
var cbArgs = [].slice.call(arguments, 0);
// use .get(index) to ensure observation added.
// the arguments are (item, index) or (result, item, index)
cbArgs[fnLength - 3] = self.get(cbArgs[fnLength - 2]);
return callback.apply(thisArg, cbArgs);
};
var ret = Array.prototype[fnName].apply(this, args);
if(fnName === "map") {
return new DefineList(ret);
}
else if(fnName === "filter") {
return new self.constructor(ret);
} else {
return ret;
}
};
});
assign(DefineList.prototype, {
includes: (function(){
var arrayIncludes = Array.prototype.includes;
if(arrayIncludes){
return function includes() {
return arrayIncludes.apply(this, arguments);
};
} else {
return function includes() {
throw new Error("DefineList.prototype.includes must have Array.prototype.includes available. Please add a polyfill to this environment.");
};
}
})(),
indexOf: function(item, fromIndex) {
for (var i = fromIndex || 0, len = this.length; i < len; i++) {
if (this.get(i) === item) {
return i;
}
}
return -1;
},
lastIndexOf: function(item, fromIndex) {
fromIndex = typeof fromIndex === "undefined" ? this.length - 1: fromIndex;
for (var i = fromIndex; i >= 0; i--) {
if (this.get(i) === item) {
return i;
}
}
return -1;
},
join: function() {
ObservationRecorder.add(this, "length");
return [].join.apply(this, arguments);
},
reverse: function() {
// this shouldn't be observable
var list = [].reverse.call(this._items());
return this.replace(list);
},
slice: function() {
// tells computes to listen on length for changes.
ObservationRecorder.add(this, "length");
var temp = Array.prototype.slice.apply(this, arguments);
return new this.constructor(temp);
},
concat: function() {
var args = [];
// Go through each of the passed `arguments` and
// see if it is list-like, an array, or something else
canReflect.eachIndex(arguments, function(arg) {
if (canReflect.isListLike(arg)) {
// If it is list-like we want convert to a JS array then
// pass each item of the array to this.__type
var arr = Array.isArray(arg) ? arg : canReflect.toArray(arg);
arr.forEach(function(innerArg) {
args.push(this.__type(innerArg));
}, this);
} else {
// If it is a Map, Object, or some primitive
// just pass arg to this.__type
args.push(this.__type(arg));
}
}, this);
// We will want to make `this` list into a JS array
// as well (We know it should be list-like), then
// concat with our passed in args, then pass it to
// list constructor to make it back into a list
return new this.constructor(Array.prototype.concat.apply(canReflect.toArray(this), args));
},
forEach: function(cb, thisarg) {
var item;
for (var i = 0, len = this.length; i < len; i++) {
item = this.get(i);
if (cb.call(thisarg || item, item, i, this) === false) {
break;
}
}
return this;
},
replace: function(newList) {
var patches = diff(this, newList);
queues.batch.start();
for (var i = 0, len = patches.length; i < len; i++) {
this.splice.apply(this, [
patches[i].index,
patches[i].deleteCount
].concat(patches[i].insert));
}
queues.batch.stop();
return this;
},
sort: function(compareFunction) {
var sorting = Array.prototype.slice.call(this);
Array.prototype.sort.call(sorting, compareFunction);
this.splice.apply(this, [0,sorting.length].concat(sorting) );
return this;
}
});
// Add necessary event methods to this object.
for (var prop in define.eventsProto) {
DefineList[prop] = define.eventsProto[prop];
Object.defineProperty(DefineList.prototype, prop, {
enumerable: false,
value: define.eventsProto[prop],
writable: true
});
}
Object.defineProperty(DefineList.prototype, "length", {
get: function() {
if (!this[inSetupSymbol]) {
ObservationRecorder.add(this, "length");
}
return this._length;
},
set: function(newVal) {
if (runningNative) {
this._length = newVal;
return;
}
// Don't set _length if:
// - null or undefined
// - a string that doesn't convert to number
// - already the length being set
if (newVal == null || isNaN(+newVal) || newVal === this._length) {
return;
}
if (newVal > this._length - 1) {
var newArr = new Array(newVal - this._length);
this.push.apply(this, newArr);
}
else {
this.splice(newVal);
}
},
enumerable: true
});
DefineList.prototype.attr = function(prop, value) {
canLog.warn("DefineMap::attr shouldn't be called");
if (arguments.length === 0) {
return this.get();
} else if (prop && typeof prop === "object") {
return this.set.apply(this, arguments);
} else if (arguments.length === 1) {
return this.get(prop);
} else {
return this.set(prop, value);
}
};
DefineList.prototype.item = function(index, value) {
if (arguments.length === 1) {
return this.get(index);
} else {
return this.set(index, value);
}
};
DefineList.prototype.items = function() {
canLog.warn("DefineList::get should should be used instead of DefineList::items");
return this.get();
};
var defineListProto = {
// type
"can.isMoreListLikeThanMapLike": true,
"can.isMapLike": true,
"can.isListLike": true,
"can.isValueLike": false,
// get/set
"can.getKeyValue": DefineList.prototype.get,
"can.setKeyValue": DefineList.prototype.set,
// Called for every reference to a property in a template
// if a key is a numerical index then translate to length event
"can.onKeyValue": function(key, handler, queue) {
var translationHandler;
if (isNaN(key)) {
return onKeyValue.apply(this, arguments);
}
else {
translationHandler = function() {
handler(this[key]);
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
Object.defineProperty(translationHandler, "name", {
value: "translationHandler(" + key + ")::" + canReflect.getName(this) + ".onKeyValue('length'," + canReflect.getName(handler) + ")",
});
}
//!steal-remove-end
singleReference.set(handler, this, translationHandler, key);
return onKeyValue.call(this, 'length', translationHandler, queue);
}
},
// Called when a property reference is removed
"can.offKeyValue": function(key, handler, queue) {
var translationHandler;
if ( isNaN(key)) {
return offKeyValue.apply(this, arguments);
}
else {
translationHandler = singleReference.getAndDelete(handler, this, key);
return offKeyValue.call(this, 'length', translationHandler, queue);
}
},
"can.deleteKeyValue": function(prop) {
// convert string key to number index if key can be an integer:
// isNaN if prop isn't a numeric representation
// (prop % 1) if numeric representation is a float
// In both of the above cases, leave as string.
prop = isNaN(+prop) || (prop % 1) ? prop : +prop;
if(typeof prop === "number") {
this.splice(prop, 1);
} else if(prop === "length" || prop === "_length") {
return; // length must not be deleted
} else {
this.set(prop, undefined);
}
return this;
},
// shape get/set
"can.assignDeep": function(source){
queues.batch.start();
canReflect.assignList(this, source);
queues.batch.stop();
},
"can.updateDeep": function(source){
queues.batch.start();
this.replace(source);
queues.batch.stop();
},
// observability
"can.keyHasDependencies": function(key) {
return !!(this._computed && this._computed[key] && this._computed[key].compute);
},
"can.getKeyDependencies": function(key) {
var ret;
if(this._computed && this._computed[key] && this._computed[key].compute) {
ret = {};
ret.valueDependencies = new Set();
ret.valueDependencies.add(this._computed[key].compute);
}
return ret;
},
/*"can.onKeysAdded": function(handler,queue) {
this[canSymbol.for("can.onKeyValue")]("add", handler,queue);
},
"can.onKeysRemoved": function(handler,queue) {
this[canSymbol.for("can.onKeyValue")]("remove", handler,queue);
},*/
"can.splice": function(index, deleteCount, insert){
this.splice.apply(this, [index, deleteCount].concat(insert));
},
"can.onPatches": function(handler,queue){
this[canSymbol.for("can.onKeyValue")](localOnPatchesSymbol, handler,queue);
},
"can.offPatches": function(handler,queue) {
this[canSymbol.for("can.offKeyValue")](localOnPatchesSymbol, handler,queue);
}
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
defineListProto["can.getName"] = function() {
return canReflect.getName(this.constructor) + "[]";
};
}
//!steal-remove-end
canReflect.assignSymbols(DefineList.prototype, defineListProto);
canReflect.setKeyValue(DefineList.prototype, canSymbol.iterator, function() {
var index = -1;
if(typeof this.length !== "number") {
this.length = 0;
}
return {
next: function() {
index++;
return {
value: this[index],
done: index >= this.length
};
}.bind(this)
};
});
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
// call `list.log()` to log all event changes
// pass `key` to only log the matching event, e.g: `list.log("add")`
DefineList.prototype.log = defineHelpers.log;
}
//!steal-remove-end
define.DefineList = DefineList;
module.exports = ns.DefineList = DefineList;
| canjs/can-define | list/list.js | JavaScript | mit | 21,262 |
version https://git-lfs.github.com/spec/v1
oid sha256:691b4033e555f469bcdba73a60c0e6a24b38ebffbbf94ebe7ba61e3edbf61601
size 6745
| yogeshsaroya/new-cdnjs | ajax/libs/blueimp-file-upload/9.5.2/jquery.fileupload-angular.min.js | JavaScript | mit | 129 |
'use strict';
const _ = require('lodash');
const Promise = require('bluebird');
const fs = require('fs-extra');
const wd = require('wd');
const StateError = require('../errors/state-error');
const find = require('./find-func').find;
module.exports = class ActionsBuilder {
static create(actions) {
return new ActionsBuilder(actions);
}
constructor(actions) {
this._actions = actions;
}
wait(milliseconds) {
this._pushAction(this.wait, (browser) => {
return browser.sleep(milliseconds);
});
return this;
}
waitForElementToShow(selector, timeout) {
this._waitElementAction(this.waitForElementToShow, selector, {
timeout: timeout,
asserter: wd.asserters.isDisplayed,
error: 'was not shown'
});
return this;
}
waitForElementToHide(selector, timeout) {
this._waitElementAction(this.waitForElementToHide, selector, {
timeout: timeout,
asserter: wd.asserters.isNotDisplayed,
error: 'was not hidden'
});
return this;
}
_waitElementAction(method, selector, options) {
options = _.defaults(options, {timeout: 1000});
if (typeof selector !== 'string') {
throw new TypeError(method.name + ' accepts only CSS selectors');
}
if (typeof options.timeout !== 'number') {
throw new TypeError(method.name + ' accepts only numeric timeout');
}
this._pushAction(method, (browser) => {
return browser.waitForElementByCssSelector(selector, options.asserter, options.timeout)
.catch(() => {
//assuming its timeout error, no way to distinguish
return Promise.reject(new StateError(
'Element ' + selector + ' ' + options.error + ' in ' + options.timeout + 'ms'));
});
});
return this;
}
waitForJSCondition(jsFunc, timeout) {
if (typeof jsFunc !== 'function') {
throw new TypeError('waitForCondition should accept function');
}
timeout = (typeof timeout === 'undefined' ? 1000 : timeout);
this._pushAction(this.waitForJSCondition, (browser) => {
return browser.waitFor(wd.asserters.jsCondition(serializeFunc(jsFunc)), timeout)
.catch(() => Promise.reject(new StateError('Condition was not met in ' + timeout + 'ms')));
});
return this;
}
_pushAction(method, action) {
let stackHolder = {};
// capture stack trace to use it later in case
// of an error.
Error.captureStackTrace(stackHolder, method);
this._actions.push(function() {
return action.apply(null, arguments)
.catch((e) => {
if (e instanceof StateError) {
// replace stack of the error, so that
// stacktrace will now link to user's
// test code wil call to the action instead
// of gemini's internals.
replaceStack(e, stackHolder.stack);
}
return Promise.reject(e);
});
});
}
click(element, button) {
button = acceptMouseButton(button);
if (isInvalidElement(element)) {
throw new TypeError('.click() must receive valid element or CSS selector');
}
this._pushAction(this.click, (browser) => {
return findElement(element, browser)
.then((element) => browser.moveTo(element))
.then(() => browser.click(button));
});
return this;
}
doubleClick(element) {
if (isInvalidElement(element)) {
throw new TypeError('.doubleClick() must receive valid element or CSS selector');
}
this._pushAction(this.doubleClick, (browser) => {
return findElement(element, browser)
.then((element) => {
return browser.moveTo(element)
.then(() => browser.doubleclick());
});
});
return this;
}
dragAndDrop(element, dragTo) {
if (isInvalidElement(element)) {
throw new TypeError('.dragAndDrop() "element" argument should be valid element or CSS selector');
}
if (isInvalidElement(dragTo)) {
throw new TypeError('.dragAndDrop() "dragTo" argument should be valid element or CSS selector');
}
return this.mouseDown(element)
.mouseMove(dragTo)
.mouseUp();
}
mouseDown(element, button) {
button = acceptMouseButton(button);
if (isInvalidElement(element)) {
throw new TypeError('.mouseDown() must receive valid element or CSS selector');
}
this._pushAction(this.mouseDown, (browser) => {
return findElement(element, browser)
.then((element) => browser.moveTo(element))
.then(() => browser.buttonDown(button));
});
return this;
}
mouseUp(element, button) {
button = acceptMouseButton(button);
this._pushAction(this.mouseUp, (browser) => {
let action;
if (element) {
action = findElement(element, browser)
.then((element) => browser.moveTo(element));
} else {
action = Promise.resolve();
}
return action.then(() => browser.buttonUp(button));
});
return this;
}
mouseMove(element, offset) {
if (isInvalidElement(element)) {
throw new TypeError('.mouseMove() must receive valid element or CSS selector');
}
if (offset) {
if ('x' in offset && typeof offset.x !== 'number') {
throw new TypeError('offset.x should be a number');
}
if ('y' in offset && typeof offset.y !== 'number') {
throw new TypeError('offset.y should be a number');
}
}
this._pushAction(this.mouseMove, (browser) => {
return findElement(element, browser)
.then((element) => {
if (offset) {
return browser.moveTo(element, offset.x, offset.y);
}
return browser.moveTo(element);
});
});
return this;
}
sendKeys(element, keys) {
let action;
if (typeof keys === 'undefined' || keys === null) {
keys = element;
action = (browser) => browser.keys(keys);
} else {
if (isInvalidElement(element)) {
throw new TypeError('.sendKeys() must receive valid element or CSS selector');
}
action = (browser) => {
return findElement(element, browser)
.then((element) => browser.type(element, keys));
};
}
if (isInvalidKeys(keys)) {
throw new TypeError('keys should be string or array of strings');
}
this._pushAction(this.sendKeys, action);
return this;
}
sendFile(element, path) {
if (typeof path !== 'string') {
throw new TypeError('path must be string');
}
if (isInvalidElement(element)) {
throw new TypeError('.sendFile() must receive valid element or CSS selector');
}
this._pushAction(this.sendFile, (browser) => {
return fs.statAsync(path)
.then((stat) => {
if (!stat.isFile()) {
return Promise.reject(new StateError(path + ' should be existing file'));
}
return findElement(element, browser);
})
.then((element) => element.sendKeys(path));
});
return this;
}
focus(element) {
if (isInvalidElement(element)) {
throw new TypeError('.focus() must receive valid element or CSS selector');
}
return this.sendKeys(element, '');
}
tap(element) {
if (isInvalidElement(element)) {
throw new TypeError('.tap() must receive valid element or CSS selector');
}
this._pushAction(this.tap, (browser) => {
return findElement(element, browser)
.then((elem) => browser.tapElement(elem));
});
return this;
}
flick(offsets, speed, element) {
if (element && isInvalidElement(element)) {
throw new TypeError('.flick() must receive valid element or CSS selector');
}
this._pushAction(this.flick, (browser) => {
if (element) {
return findElement(element, browser)
.then((elem) => browser.flick(elem, offsets.x, offsets.y, speed));
}
return browser.flick(offsets.x, offsets.y, speed);
});
return this;
}
executeJS(callback) {
if (typeof callback !== 'function') {
throw new TypeError('executeJS argument should be function');
}
this._pushAction(this.executeJS, (browser) => browser.execute(serializeFunc(callback)));
return this;
}
setWindowSize(width, height) {
this._pushAction(this.setWindowSize, (browser, postActions) => {
return (postActions ? mkRestoreAction_() : Promise.resolve())
.then(() => browser.setWindowSize(width, height));
function mkRestoreAction_() {
return browser.getWindowSize()
.then((size) => {
if (size.width !== width || size.height !== height) {
postActions.setWindowSize(size.width, size.height);
}
});
}
});
return this;
}
changeOrientation(options = {}) {
options = _.defaults(options, {timeout: 2500});
this._pushAction(this.changeOrientation, (browser, postActions) => {
if (postActions) {
postActions.changeOrientation(options);
}
return getBodyWidth()
.then((initialBodyWidth) => {
return rotate()
.then((result) => waitForOrientationChange(initialBodyWidth).then(() => result));
});
function getBodyWidth() {
return browser.evalScript(serializeFunc(function(window) {
return window.document.body.clientWidth;
}));
}
function rotate() {
const orientations = ['PORTRAIT', 'LANDSCAPE'];
const getAnotherOrientation = (orientation) => _(orientations).without(orientation).first();
return browser.getOrientation()
.then((initialOrientation) => browser.setOrientation(getAnotherOrientation(initialOrientation)));
}
function waitForOrientationChange(initialBodyWidth) {
return browser
.waitFor(wd.asserters.jsCondition(serializeFunc(function(window, initialBodyWidth) {
return window.document.body.clientWidth !== Number(initialBodyWidth);
}, [initialBodyWidth])), options.timeout)
.catch(() => Promise.reject(new StateError(`Orientation did not changed in ${options.timeout} ms`)));
}
});
return this;
}
};
function acceptMouseButton(button) {
if (typeof button === 'undefined') {
return 0;
}
if ([0, 1, 2].indexOf(button) === -1) {
throw new TypeError('Mouse button should be 0 (left), 1 (middle) or 2 (right)');
}
return button;
}
function isInvalidKeys(keys) {
if (typeof keys !== 'string') {
if (!Array.isArray(keys)) {
return true;
}
return keys.some((chunk) => typeof chunk !== 'string');
}
return false;
}
function isInvalidElement(element) {
return (!element || !element._selector) && typeof element !== 'string';
}
function replaceStack(error, stack) {
let message = error.stack.split('\n')[0];
error.stack = [message].concat(stack.split('\n').slice(1)).join('\n');
}
function serializeFunc(func, args) {
return '(' + func.toString() + (_.isEmpty(args) ? ')(window);' : `)(window, '${args.join('\', \'')}');`);
}
function findElement(element, browser) {
if (element.cache && element.cache[browser.sessionId]) {
return Promise.resolve(element.cache[browser.sessionId]);
}
if (typeof element === 'string') {
element = find(element);
}
return browser.findElement(element._selector)
.then((foundElement) => {
element.cache = element.cache || {};
element.cache[browser.sessionId] = foundElement;
return foundElement;
})
.catch((error) => {
if (error.status === 7) {
error = new StateError('Could not find element with css selector in actions chain: '
+ error.selector);
}
return Promise.reject(error);
});
}
| gemini-testing/gemini | lib/tests-api/actions-builder.js | JavaScript | mit | 13,442 |
// require(d) gulp for compatibility with sublime-gulp.
var gulp = require('gulp');
const { src, dest, series, parallel } = require('gulp');
const clean = require('gulp-clean');
const eslint = require('gulp-eslint');
const csso = require('gulp-csso');
const rename = require('gulp-rename');
const babel = require("gulp-babel");
const minify_babel = require("gulp-babel-minify");
const minify = require('gulp-minify');
const rollup = require('rollup');
// Erase build directory
function cleandist() {
return gulp.src(['build/*'], {read: false, allowEmpty: true})
.pipe(clean())
}
// Lint Task
function lint() {
return gulp.src('./src/*.js')
.pipe(eslint())
.pipe(eslint.format())
}
// Build ES6 module
function build_es6() {
return gulp.src('./src/*.js')
.pipe(minify({
ext: {
src:'.js',
min:'.min.js'
},
preserveComments: 'some',
noSource: true
}))
.pipe(gulp.dest('./build/es6/chordictionary'))
}
// Build CommonJS module
async function build_commonjs() {
const bundle = await rollup.rollup({
input: './src/main.js'
});
await bundle.write({
file: './tmp/chordictionary_cjs.js',
format: 'cjs',
name: 'chordictionary'
});
await gulp.src('./tmp/chordictionary_cjs.js', { allowEmpty: true })
.pipe(clean())
.pipe(babel())
.pipe(rename('chordictionary.min.js'))
.pipe(minify_babel())
.pipe(gulp.dest('./build/commonjs'))
}
// Build IIFE script
async function build_iife() {
const bundle = await rollup.rollup({
input: './src/main.js'
});
await bundle.write({
file: './tmp/chordictionary_iife.js',
format: 'iife',
name: 'chordictionary'
});
await gulp.src('./tmp/chordictionary_iife.js', { allowEmpty: true })
.pipe(clean())
.pipe(babel())
.pipe(rename('chordictionary.min.js'))
.pipe(minify_babel())
.pipe(gulp.dest('./build/iife'));
}
// CSS task
function css() {
return gulp.src('./src/chordictionary.css')
.pipe(csso())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('./build'));
}
const build = gulp.series(cleandist, gulp.parallel(css, lint), gulp.parallel(build_es6, build_commonjs, build_iife));
exports.lint = lint;
exports.css = css;
exports.clean = cleandist;
exports.build = build;
exports.default = build;
| greird/chordictionaryjs | gulpfile.js | JavaScript | mit | 2,191 |
var AIO = require('../../index');
// create an instance
aio = AIO(process.env.AIO_KEY || 'xxxxxxxxxxxx');
// get a list of all groups
aio.groups(function(err, data) {
if(err) {
return console.error(err);
}
// log data array
console.log(data);
});
// get a specific group by name
aio.groups('Test', function(err, data) {
if(err) {
return console.error(err);
}
// log data object
console.log(data);
});
| bbx10/io-client-node | examples/groups/read.js | JavaScript | mit | 435 |
module.exports = (env = "dev") =>
// you may extend to other env to produce a production build for example
require(`./webpack.${env}.config.js`);
| code0wl/Multiplayer-Phaser-game | webpack.config.js | JavaScript | mit | 154 |
'use strict';
// Configuring the Workouts module
angular.module('workouts').run(['Menus',
function(Menus) {
// Add the workouts dropdown item
Menus.addMenuItem('topbar', {
title: 'Workouts',
state: 'workouts',
type: 'dropdown',
position: 0
});
// Add the dropdown list item
Menus.addSubMenuItem('topbar', 'workouts', {
title: 'List Workouts',
state: 'workouts.list'
});
// Add the dropdown create item
Menus.addSubMenuItem('topbar', 'workouts', {
title: 'Create Workouts',
state: 'workouts.create'
});
}
]);
| grantgeorge/mean | modules/workouts/client/config/workouts.client.config.js | JavaScript | mit | 599 |
'use strict';
angular.module('angular-tabs', ['angular-tabs-utils'])
.provider('$uiTabs', function () {
/**
*
*/
var TabDefinition = function () {
this.$dirty = false;
this.$selected = false;
this.$volatile = true;
this.$data = {};
};
TabDefinition.prototype.onClose = ['$q', function ($q) {
return function () {
var deferred = $q.defer();
deferred.resolve();
return deferred.promise;
};
}];
/**
* Map of tab definitions
*/
var tabDefinitions = {
null: {template: ''}
};
/**
*
* @param type {string}
* @param definition {Object}
* @returns {Object} self
*/
this.tab = function (type, definition) {
var tabDefinition = angular.extend(
{}, definition
);
if (tabDefinition.volatile !== undefined) {
tabDefinition.$volatile = !!tabDefinition.volatile;
delete tabDefinition.volatile;
}
tabDefinitions[type] = tabDefinition;
return this;
};
/**
*
* @param definition {Object}
* @returns {Object} self
*/
this.welcome = function (definition) {
return this.tab(null, definition);
};
this.config = function(options) {
TabDefinition.prototype.tabHeaderItemTemplate = options.tabHeaderItemTemplate;
TabDefinition.prototype.tabHeaderMenuItemTemplate = options.tabHeaderMenuItemTemplate;
TabDefinition.prototype.tabHeaderItemTemplateUrl = options.tabHeaderItemTemplateUrl || 'src/templates/templateItemUrl.html';
TabDefinition.prototype.tabHeaderMenuItemTemplateUrl = options.tabHeaderMenuItemTemplateUrl || 'src/templates/templateMenuItemUrl.html';
};
/**
*
* @param handler {function}
*/
this.onClose = function (handler) {
TabDefinition.prototype.onClose = handler;
};
/*
*
*/
function initTab(type, options) {
var tabDefinition = tabDefinitions[type];
if (!tabDefinition) {
return undefined;
}
var tabDefInstance = angular.extend(new TabDefinition(), tabDefinition, options || {});
if (!!tabDefInstance.template && !!options && !!options.templateUrl) {
delete tabDefInstance.template;
}
return tabDefInstance;
}
this.$get = ["$rootScope", "$injector", "$sce", "$http", "$q", "$templateCache", "utils", function ($rootScope, $injector, $sce, $http, $q, $templateCache, utils) {
/**
* Basically TABS.arr & TABS.map contain the same tabs objects
*/
var TABS = {
arr : [],
map : {},
history : [],
activeTab: undefined
};
/**
* Return a tab object
* @param id tab id
* @returns {tab}
*/
var getTab = function (id) {
return TABS.map[id];
};
var removeTab = function (id) {
var tab = getTab(id);
$q.when(tab).
then(function () {
if (tab.onClose) {
var fn = angular.isString(tab.onClose) ? $injector.get(tab.onClose) : $injector.invoke(tab.onClose);
return fn(tab);
}
}).
// after tab close resolved
then(function () {
removeTabIntern(tab);
});
};
var removeTabIntern = function (tab) {
utils.remove(TABS.history, function (tabId) {
return tabId === tab.$$tabId;
});
if (tab.$selected && TABS.history.length > 0) {
selectTab(TABS.history[TABS.history.length - 1]);
}
cleanTabScope(tab);
TABS.arr.splice(TABS.arr.indexOf(tab), 1);
delete TABS.map[tab.$$tabId];
$rootScope.$broadcast('$tabRemoveSuccess', tab);
};
var getActiveTab = function () {
return TABS.activeTab;
};
/**
* Return all tabs
* @returns {*}
*/
var getTabs = function () {
return TABS.arr; // clone ?
};
/*
Private
*/
var cleanTabScope = function (tab) {
if (tab.scope) {
tab.scope.$destroy();
tab.scope = null;
}
};
/**
* Add a new tab
* @param type type of a tab described with $uiTabsProvider
* @param options init tab options (title, disabled)
* @param id (optional) tab's unique id. If 'id' exists, tab content of this tab will be replaced
* @returns {Promise(tab)}
*/
var addTab = function (type, options, id) {
var newTab = initTab(type, options);
if (!newTab) {
throw new Error('Unknown tab type: ' + type);
}
newTab.$$tabId = id || Math.random().toString(16).substr(2);
newTab.close = function () {
removeTab(this.$$tabId);
};
return loadTabIntern(newTab).then(function(newTab) {
var find = getTab(newTab.$$tabId);
if (!find) {
// Add Tab
if (type !== null) {
TABS.arr.push(newTab);
}
TABS.map[newTab.$$tabId] = newTab;
} else {
// Replace tab
cleanTabScope(find);
angular.copy(newTab, find);
}
return selectTab(newTab.$$tabId);
}, function (error) {
$rootScope.$broadcast('$tabAddError', newTab, error);
});
};
/**
* Select an existing tab
* @param tabId tab id
* @returns {tab}
*/
function loadTabIntern(tab) {
return $q.when(tab).
then(function () {
// Start loading template
$rootScope.$broadcast('$tabLoadStart', tab);
var locals = angular.extend({}, tab.resolve),
template, templateUrl;
angular.forEach(locals, function (value, key) {
locals[key] = angular.isString(value) ?
$injector.get(value) : $injector.invoke(value);
});
if (angular.isDefined(template = tab.template)) {
if (angular.isFunction(template)) {
template = template(tab);
}
} else if (angular.isDefined(templateUrl = tab.templateUrl)) {
if (angular.isFunction(templateUrl)) {
templateUrl = templateUrl(tab);
}
templateUrl = $sce.getTrustedResourceUrl(templateUrl);
if (angular.isDefined(templateUrl)) {
tab.loadedTemplateUrl = templateUrl;
template = $http.get(templateUrl, {cache: $templateCache}).
then(function (response) {
return response.data;
});
}
}
if (angular.isDefined(template)) {
locals.$template = template;
}
return $q.all(locals);
}).then(function(locals) {
tab.locals = locals;
$rootScope.$broadcast('$tabLoadEnd', tab);
return tab;
});
}
/**
* Select an existing tab
* @param tabId tab id
* @returns {tab}
*/
function selectTab(tabId) {
var next = getTab(tabId),
last = getActiveTab();
if (next && last && next.$$tabId === last.$$tabId) {
$rootScope.$broadcast('$tabUpdate', last);
} else if (next) {
$rootScope.$broadcast('$tabChangeStart', next, last);
if (last) {
last.$selected = false;
}
next.$selected = true;
TABS.activeTab = next;
utils.remove(TABS.history, function (id) {
return tabId === id;
});
TABS.history.push(tabId);
$rootScope.$broadcast('$tabChangeSuccess', next, last);
} else {
$rootScope.$broadcast('$tabChangeError', next, 'Cloud not found tab with id #' + tabId);
}
return next;
}
// Add welcome tab
addTab(null);
/**
* Public API
*/
return {
addTab: addTab,
getTabs: getTabs,
getTab: getTab,
removeTab: removeTab,
selectTab: selectTab,
getActiveTab: getActiveTab
};
}];
})
.directive('tabView', ["$uiTabs", "$anchorScroll", "$animate", function ($uiTabs, $anchorScroll, $animate) {
return {
restrict: 'ECA',
terminal: true,
priority: 400,
transclude: 'element',
link: function (scope, $element, attr, ctrl, $transclude) {
var currentScope,
currentElement,
previousElement,
autoScrollExp = attr.autoscroll,
onloadExp = attr.onload || '',
elems = {};
function onTabRemoveSuccess(event, tab) {
if (tab.$selected === false) {
var elem = elems[tab.$$tabId];
if (elem) {
delete elems[tab.$$tabId];
elem.remove();
elem = null;
}
}
}
function cleanupLastView() {
var id = currentElement && currentElement.data('$$tabId');
var tab = $uiTabs.getTab(id);
if (previousElement) {
previousElement.remove();
previousElement = null;
}
if (currentScope && tab === undefined) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
if (tab) {
$animate.addClass(currentElement, 'ng-hide');
previousElement = null;
} else {
$animate.leave(currentElement, function () {
previousElement = null;
});
previousElement = currentElement;
currentElement = null;
}
}
}
function onTabChangeSuccess(event, currentTab) {
var elem = elems[currentTab.$$tabId];
if (elem) {
$animate.removeClass(elem, 'ng-hide');
cleanupLastView();
currentElement = elem;
return;
}
var locals = currentTab && currentTab.locals,
template = locals && locals.$template;
if (angular.isDefined(template)) {
var newScope = scope.$new();
newScope.$$tabId = currentTab.$$tabId;
if (currentTab.$volatile !== false) {
newScope.$data = currentTab.$data;
}
newScope.$setTabDirty = function () {
currentTab.$dirty = true;
};
// Note: This will also link all children of tab-view that were contained in the original
// html. If that content contains controllers, ... they could pollute/change the scope.
// However, using ng-view on an element with additional content does not make sense...
// Note: We can't remove them in the cloneAttchFn of $transclude as that
// function is called before linking the content, which would apply child
// directives to non existing elements.
var clone = $transclude(newScope, function (clone) {
$animate.enter(clone, null, currentElement || $element, function onNgViewEnter() {
if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
});
cleanupLastView();
});
currentElement = clone;
currentScope = newScope;
if (currentTab.$volatile === false) {
currentElement.data('$$tabId', currentTab.$$tabId);
elems[currentTab.$$tabId] = currentElement;
currentTab.scope = newScope;
}
newScope.$emit('$tabContentLoaded');
newScope.$eval(onloadExp);
} else {
cleanupLastView();
}
}
scope.$on('$tabChangeSuccess', onTabChangeSuccess);
scope.$on('$tabRemoveSuccess', onTabRemoveSuccess);
}
};
}])
.directive('tabView', ["$compile", "$controller", "$uiTabs", function ($compile, $controller, $uiTabs) {
return {
restrict: 'ECA',
priority: -400,
link: function (scope, $element) {
var current = $uiTabs.getActiveTab(),
locals = current.locals;
scope.$$currentTab = current;
$element.html(locals.$template);
$element.addClass('ui-tab-system-view');
var link = $compile($element.contents());
if (current.controller) {
locals.$scope = scope;
var controller = $controller(current.controller, locals);
if (current.controllerAs) {
scope[current.controllerAs] = controller;
}
$element.data('$ngControllerController', controller);
$element.children().data('$ngControllerController', controller);
}
link(scope);
},
controller: ["$scope", function ($scope) {
this.$$getCurrentTab = function () {
return $scope.$$currentTab;
};
}]
};
}])
.directive('closeUiTab', function () {
return {
restrict: 'ECA',
priority: -400,
require: '^tabView',
link: function (scope, $element, attr, tabViewCtrl) {
$element.on('click', function () {
scope.$apply(function() {
tabViewCtrl.$$getCurrentTab().close();
});
});
}
};
})
.directive('closeUiTabHeader', function () {
return {
restrict: 'ECA',
priority: -401,
link: function (scope, $element, attr) {
$element.on('click', function () {
scope.$apply(function() {
scope.tab.close();
});
});
}
};
})
.directive('tabHeaderItem', ["$http", "$templateCache", "$compile", "$sce", "$q", function ($http, $templateCache, $compile, $sce, $q) {
return {
restrict: 'EA',
scope: {
index: '=',
tab: '='
},
priority: -402,
link: function (scope, element, attrs) {
var template, templateUrl;
if (attrs.type === 'menu') {
template = scope.tab.tabHeaderMenuItemTemplate;
templateUrl = scope.tab.tabHeaderMenuItemTemplateUrl;
} else {
template = scope.tab.tabHeaderItemTemplate;
templateUrl = scope.tab.tabHeaderItemTemplateUrl;
}
if (angular.isDefined(template)) {
if (angular.isFunction(template)) {
template = template(tab);
}
} else if (angular.isDefined(templateUrl)) {
if (angular.isFunction(templateUrl)) {
templateUrl = templateUrl(tab);
}
templateUrl = $sce.getTrustedResourceUrl(templateUrl);
if (angular.isDefined(templateUrl)) {
//tab.loadedTemplateUrl = templateUrl;
template = $http.get(templateUrl, {cache: $templateCache}).
then(function (response) {
return response.data;
});
}
}
$q.when(template).then(function(tplContent) {
element.replaceWith($compile(tplContent.trim())(scope));
});
/* xxxx
$http.get(tplUrl, {cache: $templateCache}).success(function (tplContent) {
element.replaceWith($compile(tplContent.trim())(scope));
});*/
}
};
}])
.directive('tabHeader', ["$uiTabs", "$window", "$timeout", "utils", function ($uiTabs, $window, $timeout, utils) {
return {
restrict: 'ECA',
priority: -400,
template: '<div class="ui-tab-header" ui-tab-menu-dropdown>\n <div class="ui-tab-header-wrapper">\n <ul class="ui-tab-header-container">\n <li class="ui-tab-header-item" ng-class="{active: tab.$selected}" data-ng-repeat="tab in tabs" data-ng-click="selectTab(tab, $index)">\n <span tab-header-item type="tab" tab="tab" index="$index"></span>\n </li>\n </ul>\n </div>\n\n <span class="ui-tab-header-menu-toggle" ui-tab-menu-dropdown-toggle ng-show="showTabMenuHandler"></span>\n <div class="ui-tab-header-menu">\n <ul>\n <li class="ui-tab-header-menu-item" data-ng-repeat="tab in tabs" data-ng-click="selectTab(tab, $index)">\n <span tab-header-item type="menu" tab="tab" index="$index"></span>\n </li>\n </ul>\n </div>\n</div>\n',
scope: {},
controller: function() {},
link: function (scope, elem, attr) {
var container = elem.find('ul.ui-tab-header-container');
var wrapper = elem.find('div.ui-tab-header-wrapper');
var lastSelectedIndex;
scope.tabs = $uiTabs.getTabs();
scope.selectTab = function (tab, index) {
$uiTabs.selectTab(tab.$$tabId);
scrollToTab(index);
};
scope.closeTab = function (tab) {
$uiTabs.removeTab(tab.$$tabId);
};
scope.$watchCollection('tabs', function (tabs) {
$timeout(function () {
var index = tabs.indexOf($uiTabs.getActiveTab());
if (index !== -1) {
scrollToTab(index);
}
});
});
var scrollToTab = function (index) {
var left;
if (container.outerWidth() + container.position().left < wrapper.innerWidth()) {
// Trim space in the right (when deletion or window resize)
left = Math.min((wrapper.innerWidth() - container.outerWidth() ), 0);
}
scope.showTabMenuHandler = wrapper.innerWidth() < container.outerWidth();
if (index !== undefined) {
var li = elem.find('li.ui-tab-header-item:nth-child(' + (index + 1) + ')');
var leftOffset = container.position().left;
if (leftOffset + li.position().left < 0) {
// Scroll to active tab at left
left = -li.position().left;
} else {
// Scroll to active tab at right
var liOffset = li.position().left + li.outerWidth() + leftOffset;
if (liOffset > wrapper.innerWidth()) {
left = wrapper.innerWidth() + leftOffset - liOffset;
}
}
}
if (left !== undefined) {
container.css({left: left});
}
lastSelectedIndex = index;
};
var w = angular.element($window);
w.bind('resize', utils.debounce(function (event) {
scope.$apply(scrollToTab(lastSelectedIndex));
}, 200));
}
};
}])
.constant('dropdownConfig', {
openClass: 'open'
})
.service('dropdownService', ['$document', function ($document) {
var openScope = null;
this.open = function (dropdownScope) {
if (!openScope) {
$document.bind('click', closeDropdown);
$document.bind('keydown', escapeKeyBind);
}
if (openScope && openScope !== dropdownScope) {
openScope.isOpen = false;
}
openScope = dropdownScope;
};
this.close = function (dropdownScope) {
if (openScope === dropdownScope) {
openScope = null;
$document.unbind('click', closeDropdown);
$document.unbind('keydown', escapeKeyBind);
}
};
var closeDropdown = function (evt) {
// This method may still be called during the same mouse event that
// unbound this event handler. So check openScope before proceeding.
if (!openScope) {
return;
}
var toggleElement = openScope.getToggleElement();
if (evt && toggleElement && toggleElement[0].contains(evt.target)) {
return;
}
openScope.$apply(function () {
openScope.isOpen = false;
});
};
var escapeKeyBind = function (evt) {
if (evt.which === 27) {
openScope.focusToggleElement();
closeDropdown();
}
};
}])
.controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', function ($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate) {
var self = this,
scope = $scope.$new(), // create a child scope so we are not polluting original one
openClass = dropdownConfig.openClass,
getIsOpen,
setIsOpen = angular.noop,
toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop;
this.init = function (element) {
self.$element = element;
if ($attrs.isOpen) {
getIsOpen = $parse($attrs.isOpen);
setIsOpen = getIsOpen.assign;
$scope.$watch(getIsOpen, function (value) {
scope.isOpen = !!value;
});
}
};
this.toggle = function (open) {
scope.isOpen = arguments.length ? !!open : !scope.isOpen;
return scope.isOpen;
};
// Allow other directives to watch status
this.isOpen = function () {
return scope.isOpen;
};
scope.getToggleElement = function () {
return self.toggleElement;
};
scope.focusToggleElement = function () {
if (self.toggleElement) {
self.toggleElement[0].focus();
}
};
scope.$watch('isOpen', function (isOpen, wasOpen) {
$animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass);
if (isOpen) {
scope.focusToggleElement();
dropdownService.open(scope);
} else {
dropdownService.close(scope);
}
setIsOpen($scope, isOpen);
if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
toggleInvoker($scope, {open: !!isOpen});
}
});
$scope.$on('$locationChangeSuccess', function () {
scope.isOpen = false;
});
$scope.$on('$destroy', function () {
scope.$destroy();
});
}])
.directive('uiTabMenuDropdown', function () {
return {
controller: 'DropdownController',
link: function (scope, element, attrs, dropdownCtrl) {
dropdownCtrl.init(element);
}
};
})
.directive('uiTabMenuDropdownToggle', function () {
return {
require: '?^uiTabMenuDropdown',
priority: -500,
link: function (scope, element, attrs, dropdownCtrl) {
if (!dropdownCtrl) {
return;
}
dropdownCtrl.toggleElement = element;
var toggleDropdown = function (event) {
event.preventDefault();
if (!element.hasClass('disabled') && !attrs.disabled) {
scope.$apply(function () {
dropdownCtrl.toggle();
});
}
};
element.bind('click', toggleDropdown);
// WAI-ARIA
element.attr({'aria-haspopup': true, 'aria-expanded': false});
scope.$watch(dropdownCtrl.isOpen, function (isOpen) {
element.attr('aria-expanded', !!isOpen);
});
scope.$on('$destroy', function () {
element.unbind('click', toggleDropdown);
});
}
};
})
.run(["$templateCache", function($templateCache) {
$templateCache.put('src/templates/templateItemUrl.html',
'<span class="asterisk" ng-show="tab.$dirty">*</span>' +
'<span class="ui-tab-header-title">{{tab.title}}</span>' +
'<span class="ui-tab-header-close" close-ui-tab-header></span>'
);
$templateCache.put('src/templates/templateMenuItemUrl.html',
'<span class="ui-tab-header-menu-item-title">{{tab.title}}</span>'
);
}]);
'use strict';
angular.module('angular-tabs-utils', [])
.service('utils', function () {
return {
remove: function (array, callback) {
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (callback && callback(value, index, array)) {
result.push(value);
[].splice.call(array, index--, 1);
length--;
}
}
return result;
},
debounce: function (func, wait, immediate) {
var args,
result,
thisArg,
timeoutId;
function delayed() {
timeoutId = null;
if (!immediate) {
result = func.apply(thisArg, args);
}
}
return function () {
var isImmediate = immediate && !timeoutId;
args = arguments;
thisArg = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(delayed, wait);
if (isImmediate) {
result = func.apply(thisArg, args);
}
return result;
};
}
};
}); | cagegit/DataTransFront | app/bower_components/angular-ui-tabs/dist/angular-tabs.js | JavaScript | mit | 30,352 |
// Deps is sort of a problem for us, maybe in the future we will ask the user to depend
// on modules for add-ons
var deps = ['ObjectPath'];
try {
//This throws an expection if module does not exist.
angular.module('ngSanitize');
deps.push('ngSanitize');
} catch (e) {}
try {
//This throws an expection if module does not exist.
angular.module('ui.sortable');
deps.push('ui.sortable');
} catch (e) {}
try {
//This throws an expection if module does not exist.
angular.module('angularSpectrumColorpicker');
deps.push('angularSpectrumColorpicker');
} catch (e) {}
angular.module('schemaForm', deps);
angular.module('schemaForm').provider('sfPath',
['ObjectPathProvider', function(ObjectPathProvider) {
var ObjectPath = {parse: ObjectPathProvider.parse};
// if we're on Angular 1.2.x, we need to continue using dot notation
if (angular.version.major === 1 && angular.version.minor < 3) {
ObjectPath.stringify = function(arr) {
return Array.isArray(arr) ? arr.join('.') : arr.toString();
};
} else {
ObjectPath.stringify = ObjectPathProvider.stringify;
}
// We want this to use whichever stringify method is defined above,
// so we have to copy the code here.
ObjectPath.normalize = function(data, quote) {
return ObjectPath.stringify(Array.isArray(data) ? data : ObjectPath.parse(data), quote);
};
this.parse = ObjectPath.parse;
this.stringify = ObjectPath.stringify;
this.normalize = ObjectPath.normalize;
this.$get = function() {
return ObjectPath;
};
}]);
/**
* @ngdoc service
* @name sfSelect
* @kind function
*
*/
angular.module('schemaForm').factory('sfSelect', ['sfPath', function(sfPath) {
var numRe = /^\d+$/;
/**
* @description
* Utility method to access deep properties without
* throwing errors when things are not defined.
* Can also set a value in a deep structure, creating objects when missing
* ex.
* var foo = Select('address.contact.name',obj)
* Select('address.contact.name',obj,'Leeroy')
*
* @param {string} projection A dot path to the property you want to get/set
* @param {object} obj (optional) The object to project on, defaults to 'this'
* @param {Any} valueToSet (opional) The value to set, if parts of the path of
* the projection is missing empty objects will be created.
* @returns {Any|undefined} returns the value at the end of the projection path
* or undefined if there is none.
*/
return function(projection, obj, valueToSet) {
if (!obj) {
obj = this;
}
//Support [] array syntax
var parts = typeof projection === 'string' ? sfPath.parse(projection) : projection;
if (typeof valueToSet !== 'undefined' && parts.length === 1) {
//special case, just setting one variable
obj[parts[0]] = valueToSet;
return obj;
}
if (typeof valueToSet !== 'undefined' &&
typeof obj[parts[0]] === 'undefined') {
// We need to look ahead to check if array is appropriate
obj[parts[0]] = parts.length > 2 && numRe.test(parts[1]) ? [] : {};
}
var value = obj[parts[0]];
for (var i = 1; i < parts.length; i++) {
// Special case: We allow JSON Form syntax for arrays using empty brackets
// These will of course not work here so we exit if they are found.
if (parts[i] === '') {
return undefined;
}
if (typeof valueToSet !== 'undefined') {
if (i === parts.length - 1) {
//last step. Let's set the value
value[parts[i]] = valueToSet;
return valueToSet;
} else {
// Make sure to create new objects on the way if they are not there.
// We need to look ahead to check if array is appropriate
var tmp = value[parts[i]];
if (typeof tmp === 'undefined' || tmp === null) {
tmp = numRe.test(parts[i + 1]) ? [] : {};
value[parts[i]] = tmp;
}
value = tmp;
}
} else if (value) {
//Just get nex value.
value = value[parts[i]];
}
}
return value;
};
}]);
angular.module('schemaForm').provider('schemaFormDecorators',
['$compileProvider', 'sfPathProvider', function($compileProvider, sfPathProvider) {
var defaultDecorator = '';
var directives = {};
var templateUrl = function(name, form) {
//schemaDecorator is alias for whatever is set as default
if (name === 'sfDecorator') {
name = defaultDecorator;
}
var directive = directives[name];
//rules first
var rules = directive.rules;
for (var i = 0; i < rules.length; i++) {
var res = rules[i](form);
if (res) {
return res;
}
}
//then check mapping
if (directive.mappings[form.type]) {
return directive.mappings[form.type];
}
//try default
return directive.mappings['default'];
};
var createDirective = function(name) {
$compileProvider.directive(name, ['$parse', '$compile', '$http', '$templateCache',
function($parse, $compile, $http, $templateCache) {
return {
restrict: 'AE',
replace: false,
transclude: false,
scope: true,
require: '?^sfSchema',
link: function(scope, element, attrs, sfSchema) {
//rebind our part of the form to the scope.
var once = scope.$watch(attrs.form, function(form) {
if (form) {
scope.form = form;
//ok let's replace that template!
//We do this manually since we need to bind ng-model properly and also
//for fieldsets to recurse properly.
var url = templateUrl(name, form);
$http.get(url, {cache: $templateCache}).then(function(res) {
var key = form.key ?
sfPathProvider.stringify(form.key).replace(/"/g, '"') : '';
var template = res.data.replace(
/\$\$value\$\$/g,
'model' + (key[0] !== '[' ? '.' : '') + key
);
element.html(template);
$compile(element.contents())(scope);
});
once();
}
});
//Keep error prone logic from the template
scope.showTitle = function() {
return scope.form && scope.form.notitle !== true && scope.form.title;
};
scope.listToCheckboxValues = function(list) {
var values = {};
angular.forEach(list, function(v) {
values[v] = true;
});
return values;
};
scope.checkboxValuesToList = function(values) {
var lst = [];
angular.forEach(values, function(v, k) {
if (v) {
lst.push(k);
}
});
return lst;
};
scope.buttonClick = function($event, form) {
if (angular.isFunction(form.onClick)) {
form.onClick($event, form);
} else if (angular.isString(form.onClick)) {
if (sfSchema) {
//evaluating in scope outside of sfSchemas isolated scope
sfSchema.evalInParentScope(form.onClick, {'$event': $event, form: form});
} else {
scope.$eval(form.onClick, {'$event': $event, form: form});
}
}
};
/**
* Evaluate an expression, i.e. scope.$eval
* but do it in sfSchemas parent scope sf-schema directive is used
* @param {string} expression
* @param {Object} locals (optional)
* @return {Any} the result of the expression
*/
scope.evalExpr = function(expression, locals) {
if (sfSchema) {
//evaluating in scope outside of sfSchemas isolated scope
return sfSchema.evalInParentScope(expression, locals);
}
return scope.$eval(expression, locals);
};
/**
* Evaluate an expression, i.e. scope.$eval
* in this decorators scope
* @param {string} expression
* @param {Object} locals (optional)
* @return {Any} the result of the expression
*/
scope.evalInScope = function(expression, locals) {
if (expression) {
return scope.$eval(expression, locals);
}
};
/**
* Error message handler
* An error can either be a schema validation message or a angular js validtion
* error (i.e. required)
*/
scope.errorMessage = function(schemaError) {
//User has supplied validation messages
if (scope.form.validationMessage) {
if (schemaError) {
if (angular.isString(scope.form.validationMessage)) {
return scope.form.validationMessage;
}
return scope.form.validationMessage[schemaError.code] ||
scope.form.validationMessage['default'];
} else {
return scope.form.validationMessage.number ||
scope.form.validationMessage['default'] ||
scope.form.validationMessage;
}
}
//No user supplied validation message.
if (schemaError) {
return schemaError.message; //use tv4.js validation message
}
//Otherwise we only have input number not being a number
return 'Not a number';
};
}
};
}
]);
};
var createManualDirective = function(type, templateUrl, transclude) {
transclude = angular.isDefined(transclude) ? transclude : false;
$compileProvider.directive('sf' + angular.uppercase(type[0]) + type.substr(1), function() {
return {
restrict: 'EAC',
scope: true,
replace: true,
transclude: transclude,
template: '<sf-decorator form="form"></sf-decorator>',
link: function(scope, element, attrs) {
var watchThis = {
'items': 'c',
'titleMap': 'c',
'schema': 'c'
};
var form = {type: type};
var once = true;
angular.forEach(attrs, function(value, name) {
if (name[0] !== '$' && name.indexOf('ng') !== 0 && name !== 'sfField') {
var updateForm = function(val) {
if (angular.isDefined(val) && val !== form[name]) {
form[name] = val;
//when we have type, and if specified key we apply it on scope.
if (once && form.type && (form.key || angular.isUndefined(attrs.key))) {
scope.form = form;
once = false;
}
}
};
if (name === 'model') {
//"model" is bound to scope under the name "model" since this is what the decorators
//know and love.
scope.$watch(value, function(val) {
if (val && scope.model !== val) {
scope.model = val;
}
});
} else if (watchThis[name] === 'c') {
//watch collection
scope.$watchCollection(value, updateForm);
} else {
//$observe
attrs.$observe(name, updateForm);
}
}
});
}
};
});
};
/**
* Create a decorator directive and its sibling "manual" use directives.
* The directive can be used to create form fields or other form entities.
* It can be used in conjunction with <schema-form> directive in which case the decorator is
* given it's configuration via a the "form" attribute.
*
* ex. Basic usage
* <sf-decorator form="myform"></sf-decorator>
**
* @param {string} name directive name (CamelCased)
* @param {Object} mappings, an object that maps "type" => "templateUrl"
* @param {Array} rules (optional) a list of functions, function(form) {}, that are each tried in
* turn,
* if they return a string then that is used as the templateUrl. Rules come before
* mappings.
*/
this.createDecorator = function(name, mappings, rules) {
directives[name] = {
mappings: mappings || {},
rules: rules || []
};
if (!directives[defaultDecorator]) {
defaultDecorator = name;
}
createDirective(name);
};
/**
* Creates a directive of a decorator
* Usable when you want to use the decorators without using <schema-form> directive.
* Specifically when you need to reuse styling.
*
* ex. createDirective('text','...')
* <sf-text title="foobar" model="person" key="name" schema="schema"></sf-text>
*
* @param {string} type The type of the directive, resulting directive will have sf- prefixed
* @param {string} templateUrl
* @param {boolean} transclude (optional) sets transclude option of directive, defaults to false.
*/
this.createDirective = createManualDirective;
/**
* Same as createDirective, but takes an object where key is 'type' and value is 'templateUrl'
* Useful for batching.
* @param {Object} mappings
*/
this.createDirectives = function(mappings) {
angular.forEach(mappings, function(url, type) {
createManualDirective(type, url);
});
};
/**
* Getter for directive mappings
* Can be used to override a mapping or add a rule
* @param {string} name (optional) defaults to defaultDecorator
* @return {Object} rules and mappings { rules: [],mappings: {}}
*/
this.directive = function(name) {
name = name || defaultDecorator;
return directives[name];
};
/**
* Adds a mapping to an existing decorator.
* @param {String} name Decorator name
* @param {String} type Form type for the mapping
* @param {String} url The template url
*/
this.addMapping = function(name, type, url) {
if (directives[name]) {
directives[name].mappings[type] = url;
}
};
//Service is just a getter for directive mappings and rules
this.$get = function() {
return {
directive: function(name) {
return directives[name];
},
defaultDecorator: defaultDecorator
};
};
//Create a default directive
createDirective('sfDecorator');
}]);
/**
* Schema form service.
* This service is not that useful outside of schema form directive
* but makes the code more testable.
*/
angular.module('schemaForm').provider('schemaForm',
['sfPathProvider', function(sfPathProvider) {
//Creates an default titleMap list from an enum, i.e. a list of strings.
var enumToTitleMap = function(enm) {
var titleMap = []; //canonical titleMap format is a list.
enm.forEach(function(name) {
titleMap.push({name: name, value: name});
});
return titleMap;
};
// Takes a titleMap in either object or list format and returns one in
// in the list format.
var canonicalTitleMap = function(titleMap, originalEnum) {
if (!angular.isArray(titleMap)) {
var canonical = [];
if (originalEnum) {
angular.forEach(originalEnum, function(value, index) {
canonical.push({name: titleMap[value], value: value});
});
} else {
angular.forEach(titleMap, function(name, value) {
canonical.push({name: name, value: value});
});
}
return canonical;
}
return titleMap;
};
var defaultFormDefinition = function(name, schema, options) {
var rules = defaults[schema.type];
if (rules) {
var def;
for (var i = 0; i < rules.length; i++) {
def = rules[i](name, schema, options);
//first handler in list that actually returns something is our handler!
if (def) {
return def;
}
}
}
};
//Creates a form object with all common properties
var stdFormObj = function(name, schema, options) {
options = options || {};
var f = options.global && options.global.formDefaults ?
angular.copy(options.global.formDefaults) : {};
if (options.global && options.global.supressPropertyTitles === true) {
f.title = schema.title;
} else {
f.title = schema.title || name;
}
if (schema.description) { f.description = schema.description; }
if (options.required === true || schema.required === true) { f.required = true; }
if (schema.maxLength) { f.maxlength = schema.maxLength; }
if (schema.minLength) { f.minlength = schema.maxLength; }
if (schema.readOnly || schema.readonly) { f.readonly = true; }
if (schema.minimum) { f.minimum = schema.minimum + (schema.exclusiveMinimum ? 1 : 0); }
if (schema.maximum) { f.maximum = schema.maximum - (schema.exclusiveMaximum ? 1 : 0); }
//Non standard attributes
if (schema.validationMessage) { f.validationMessage = schema.validationMessage; }
if (schema.enumNames) { f.titleMap = canonicalTitleMap(schema.enumNames, schema['enum']); }
f.schema = schema;
// Ng model options doesn't play nice with undefined, might be defined
// globally though
f.ngModelOptions = f.ngModelOptions || {};
return f;
};
var text = function(name, schema, options) {
if (schema.type === 'string' && !schema['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'text';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
//default in json form for number and integer is a text field
//input type="number" would be more suitable don't ya think?
var number = function(name, schema, options) {
if (schema.type === 'number') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'number';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var integer = function(name, schema, options) {
if (schema.type === 'integer') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'number';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var checkbox = function(name, schema, options) {
if (schema.type === 'boolean') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'checkbox';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var select = function(name, schema, options) {
if (schema.type === 'string' && schema['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'select';
if (!f.titleMap) {
f.titleMap = enumToTitleMap(schema['enum']);
}
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var checkboxes = function(name, schema, options) {
if (schema.type === 'array' && schema.items && schema.items['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'checkboxes';
if (!f.titleMap) {
f.titleMap = enumToTitleMap(schema.items['enum']);
}
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var fieldset = function(name, schema, options) {
if (schema.type === 'object') {
var f = stdFormObj(name, schema, options);
f.type = 'fieldset';
f.items = [];
options.lookup[sfPathProvider.stringify(options.path)] = f;
//recurse down into properties
angular.forEach(schema.properties, function(v, k) {
var path = options.path.slice();
path.push(k);
if (options.ignore[sfPathProvider.stringify(path)] !== true) {
var required = schema.required && schema.required.indexOf(k) !== -1;
var def = defaultFormDefinition(k, v, {
path: path,
required: required || false,
lookup: options.lookup,
ignore: options.ignore
});
if (def) {
f.items.push(def);
}
}
});
return f;
}
};
var array = function(name, schema, options) {
if (schema.type === 'array') {
var f = stdFormObj(name, schema, options);
f.type = 'array';
f.key = options.path;
options.lookup[sfPathProvider.stringify(options.path)] = f;
var required = schema.required &&
schema.required.indexOf(options.path[options.path.length - 1]) !== -1;
// The default is to always just create one child. This works since if the
// schemas items declaration is of type: "object" then we get a fieldset.
// We also follow json form notatation, adding empty brackets "[]" to
// signify arrays.
var arrPath = options.path.slice();
arrPath.push('');
f.items = [defaultFormDefinition(name, schema.items, {
path: arrPath,
required: required || false,
lookup: options.lookup,
ignore: options.ignore,
global: options.global
})];
return f;
}
};
//First sorted by schema type then a list.
//Order has importance. First handler returning an form snippet will be used.
var defaults = {
string: [select, text],
object: [fieldset],
number: [number],
integer: [integer],
boolean: [checkbox],
array: [checkboxes, array]
};
var postProcessFn = function(form) { return form; };
/**
* Provider API
*/
this.defaults = defaults;
this.stdFormObj = stdFormObj;
this.defaultFormDefinition = defaultFormDefinition;
/**
* Register a post process function.
* This function is called with the fully merged
* form definition (i.e. after merging with schema)
* and whatever it returns is used as form.
*/
this.postProcess = function(fn) {
postProcessFn = fn;
};
/**
* Append default form rule
* @param {string} type json schema type
* @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
* definition or undefined
*/
this.appendRule = function(type, rule) {
if (!defaults[type]) {
defaults[type] = [];
}
defaults[type].push(rule);
};
/**
* Prepend default form rule
* @param {string} type json schema type
* @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
* definition or undefined
*/
this.prependRule = function(type, rule) {
if (!defaults[type]) {
defaults[type] = [];
}
defaults[type].unshift(rule);
};
/**
* Utility function to create a standard form object.
* This does *not* set the type of the form but rather all shared attributes.
* You probably want to start your rule with creating the form with this method
* then setting type and any other values you need.
* @param {Object} schema
* @param {Object} options
* @return {Object} a form field defintion
*/
this.createStandardForm = stdFormObj;
/* End Provider API */
this.$get = function() {
var service = {};
service.merge = function(schema, form, ignore, options, readonly) {
form = form || ['*'];
options = options || {};
// Get readonly from root object
readonly = readonly || schema.readonly || schema.readOnly;
var stdForm = service.defaults(schema, ignore, options);
//simple case, we have a "*", just put the stdForm there
var idx = form.indexOf('*');
if (idx !== -1) {
form = form.slice(0, idx)
.concat(stdForm.form)
.concat(form.slice(idx + 1));
}
//ok let's merge!
//We look at the supplied form and extend it with schema standards
var lookup = stdForm.lookup;
return postProcessFn(form.map(function(obj) {
//handle the shortcut with just a name
if (typeof obj === 'string') {
obj = {key: obj};
}
if (obj.key) {
if (typeof obj.key === 'string') {
obj.key = sfPathProvider.parse(obj.key);
}
}
//If it has a titleMap make sure it's a list
if (obj.titleMap) {
obj.titleMap = canonicalTitleMap(obj.titleMap);
}
//
if (obj.itemForm) {
obj.items = [];
var str = sfPathProvider.stringify(obj.key);
var stdForm = lookup[str];
angular.forEach(stdForm.items, function(item) {
var o = angular.copy(obj.itemForm);
o.key = item.key;
obj.items.push(o);
});
}
//extend with std form from schema.
if (obj.key) {
var strid = sfPathProvider.stringify(obj.key);
if (lookup[strid]) {
obj = angular.extend(lookup[strid], obj);
}
}
// Are we inheriting readonly?
if (readonly === true) { // Inheriting false is not cool.
obj.readonly = true;
}
//if it's a type with items, merge 'em!
if (obj.items) {
obj.items = service.merge(schema, obj.items, ignore, options, obj.readonly);
}
//if its has tabs, merge them also!
if (obj.tabs) {
angular.forEach(obj.tabs, function(tab) {
tab.items = service.merge(schema, tab.items, ignore, options, obj.readonly);
});
}
// Special case: checkbox
// Since have to ternary state we need a default
if (obj.type === 'checkbox' && angular.isUndefined(obj.schema['default'])) {
obj.schema['default'] = false;
}
return obj;
}));
};
/**
* Create form defaults from schema
*/
service.defaults = function(schema, ignore, globalOptions) {
var form = [];
var lookup = {}; //Map path => form obj for fast lookup in merging
ignore = ignore || {};
globalOptions = globalOptions || {};
if (schema.type === 'object') {
angular.forEach(schema.properties, function(v, k) {
if (ignore[k] !== true) {
var required = schema.required && schema.required.indexOf(k) !== -1;
var def = defaultFormDefinition(k, v, {
path: [k], // Path to this property in bracket notation.
lookup: lookup, // Extra map to register with. Optimization for merger.
ignore: ignore, // The ignore list of paths (sans root level name)
required: required, // Is it required? (v4 json schema style)
global: globalOptions // Global options, including form defaults
});
if (def) {
form.push(def);
}
}
});
} else {
throw new Error('Not implemented. Only type "object" allowed at root level of schema.');
}
return {form: form, lookup: lookup};
};
//Utility functions
/**
* Traverse a schema, applying a function(schema,path) on every sub schema
* i.e. every property of an object.
*/
service.traverseSchema = function(schema, fn, path, ignoreArrays) {
ignoreArrays = angular.isDefined(ignoreArrays) ? ignoreArrays : true;
path = path || [];
var traverse = function(schema, fn, path) {
fn(schema, path);
angular.forEach(schema.properties, function(prop, name) {
var currentPath = path.slice();
currentPath.push(name);
traverse(prop, fn, currentPath);
});
//Only support type "array" which have a schema as "items".
if (!ignoreArrays && schema.items) {
var arrPath = path.slice(); arrPath.push('');
traverse(schema.items, fn, arrPath);
}
};
traverse(schema, fn, path || []);
};
service.traverseForm = function(form, fn) {
fn(form);
angular.forEach(form.items, function(f) {
service.traverseForm(f, fn);
});
if (form.tabs) {
angular.forEach(form.tabs, function(tab) {
angular.forEach(tab.items, function(f) {
service.traverseForm(f, fn);
});
});
}
};
return service;
};
}]);
/* Common code for validating a value against its form and schema definition */
/* global tv4 */
angular.module('schemaForm').factory('sfValidator', [function() {
var validator = {};
/**
* Validate a value against its form definition and schema.
* The value should either be of proper type or a string, some type
* coercion is applied.
*
* @param {Object} form A merged form definition, i.e. one with a schema.
* @param {Any} value the value to validate.
* @return a tv4js result object.
*/
validator.validate = function(form, value) {
if (!form) {
return {valid: true};
}
var schema = form.schema;
if (!schema) {
return {valid: true};
}
// Input of type text and textareas will give us a viewValue of ''
// when empty, this is a valid value in a schema and does not count as something
// that breaks validation of 'required'. But for our own sanity an empty field should
// not validate if it's required.
if (value === '') {
value = undefined;
}
// Numbers fields will give a null value, which also means empty field
if (form.type === 'number' && value === null) {
value = undefined;
}
// Version 4 of JSON Schema has the required property not on the
// property itself but on the wrapping object. Since we like to test
// only this property we wrap it in a fake object.
var wrap = {type: 'object', 'properties': {}};
var propName = form.key[form.key.length - 1];
wrap.properties[propName] = schema;
if (form.required) {
wrap.required = [propName];
}
var valueWrap = {};
if (angular.isDefined(value)) {
valueWrap[propName] = value;
}
return tv4.validateResult(valueWrap, wrap);
};
return validator;
}]);
/**
* Directive that handles the model arrays
*/
angular.module('schemaForm').directive('sfArray', ['sfSelect', 'schemaForm', 'sfValidator',
function(sfSelect, schemaForm, sfValidator) {
var setIndex = function(index) {
return function(form) {
if (form.key) {
form.key[form.key.indexOf('')] = index;
}
};
};
return {
restrict: 'A',
scope: true,
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
var formDefCache = {};
// Watch for the form definition and then rewrite it.
// It's the (first) array part of the key, '[]' that needs a number
// corresponding to an index of the form.
var once = scope.$watch(attrs.sfArray, function(form) {
// An array model always needs a key so we know what part of the model
// to look at. This makes us a bit incompatible with JSON Form, on the
// other hand it enables two way binding.
var list = sfSelect(form.key, scope.model);
// Since ng-model happily creates objects in a deep path when setting a
// a value but not arrays we need to create the array.
if (angular.isUndefined(list)) {
list = [];
sfSelect(form.key, scope.model, list);
}
scope.modelArray = list;
// Arrays with titleMaps, i.e. checkboxes doesn't have items.
if (form.items) {
// To be more compatible with JSON Form we support an array of items
// in the form definition of "array" (the schema just a value).
// for the subforms code to work this means we wrap everything in a
// section. Unless there is just one.
var subForm = form.items[0];
if (form.items.length > 1) {
subForm = {
type: 'section',
items: form.items.map(function(item){
item.ngModelOptions = form.ngModelOptions;
item.readonly = form.readonly;
return item;
})
};
}
}
// We ceate copies of the form on demand, caching them for
// later requests
scope.copyWithIndex = function(index) {
if (!formDefCache[index]) {
if (subForm) {
var copy = angular.copy(subForm);
copy.arrayIndex = index;
schemaForm.traverseForm(copy, setIndex(index));
formDefCache[index] = copy;
}
}
return formDefCache[index];
};
scope.appendToArray = function() {
var len = list.length;
var copy = scope.copyWithIndex(len);
schemaForm.traverseForm(copy, function(part) {
if (part.key && angular.isDefined(part['default'])) {
sfSelect(part.key, scope.model, part['default']);
}
});
// If there are no defaults nothing is added so we need to initialize
// the array. undefined for basic values, {} or [] for the others.
if (len === list.length) {
var type = sfSelect('schema.items.type', form);
var dflt;
if (type === 'object') {
dflt = {};
} else if (type === 'array') {
dflt = [];
}
list.push(dflt);
}
// Trigger validation.
if (scope.validateArray) {
scope.validateArray();
}
return list;
};
scope.deleteFromArray = function(index) {
list.splice(index, 1);
// Trigger validation.
if (scope.validateArray) {
scope.validateArray();
}
return list;
};
// Always start with one empty form unless configured otherwise.
// Special case: don't do it if form has a titleMap
if (!form.titleMap && form.startEmpty !== true && list.length === 0) {
scope.appendToArray();
}
// Title Map handling
// If form has a titleMap configured we'd like to enable looping over
// titleMap instead of modelArray, this is used for intance in
// checkboxes. So instead of variable number of things we like to create
// a array value from a subset of values in the titleMap.
// The problem here is that ng-model on a checkbox doesn't really map to
// a list of values. This is here to fix that.
if (form.titleMap && form.titleMap.length > 0) {
scope.titleMapValues = [];
// We watch the model for changes and the titleMapValues to reflect
// the modelArray
var updateTitleMapValues = function(arr) {
scope.titleMapValues = [];
arr = arr || [];
form.titleMap.forEach(function(item) {
scope.titleMapValues.push(arr.indexOf(item.value) !== -1);
});
};
//Catch default values
updateTitleMapValues(scope.modelArray);
scope.$watchCollection('modelArray', updateTitleMapValues);
//To get two way binding we also watch our titleMapValues
scope.$watchCollection('titleMapValues', function(vals) {
if (vals) {
var arr = scope.modelArray;
// Apparently the fastest way to clear an array, readable too.
// http://jsperf.com/array-destroy/32
while (arr.length > 0) {
arr.shift();
}
form.titleMap.forEach(function(item, index) {
if (vals[index]) {
arr.push(item.value);
}
});
}
});
}
// If there is a ngModel present we need to validate when asked.
if (ngModel) {
var error;
scope.validateArray = function() {
// The actual content of the array is validated by each field
// so we settle for checking validations specific to arrays
// Since we prefill with empty arrays we can get the funny situation
// where the array is required but empty in the gui but still validates.
// Thats why we check the length.
var result = sfValidator.validate(
form,
scope.modelArray.length > 0 ? scope.modelArray : undefined
);
if (result.valid === false &&
result.error &&
(result.error.dataPath === '' ||
result.error.dataPath === '/' + form.key[form.key.length - 1])) {
// Set viewValue to trigger $dirty on field. If someone knows a
// a better way to do it please tell.
ngModel.$setViewValue(scope.modelArray);
error = result.error;
ngModel.$setValidity('schema', false);
} else {
ngModel.$setValidity('schema', true);
}
};
scope.$on('schemaFormValidate', scope.validateArray);
scope.hasSuccess = function() {
return ngModel.$valid && !ngModel.$pristine;
};
scope.hasError = function() {
return ngModel.$invalid;
};
scope.schemaError = function() {
return error;
};
}
once();
});
}
};
}
]);
/**
* A version of ng-changed that only listens if
* there is actually a onChange defined on the form
*
* Takes the form definition as argument.
* If the form definition has a "onChange" defined as either a function or
*/
angular.module('schemaForm').directive('sfChanged', function() {
return {
require: 'ngModel',
restrict: 'AC',
scope: false,
link: function(scope, element, attrs, ctrl) {
var form = scope.$eval(attrs.sfChanged);
//"form" is really guaranteed to be here since the decorator directive
//waits for it. But best be sure.
if (form && form.onChange) {
ctrl.$viewChangeListeners.push(function() {
if (angular.isFunction(form.onChange)) {
form.onChange(ctrl.$modelValue, form);
} else {
scope.evalExpr(form.onChange, {'modelValue': ctrl.$modelValue, form: form});
}
});
}
}
};
});
/*
FIXME: real documentation
<form sf-form="form" sf-schema="schema" sf-decorator="foobar"></form>
*/
angular.module('schemaForm')
.directive('sfSchema',
['$compile', 'schemaForm', 'schemaFormDecorators', 'sfSelect',
function($compile, schemaForm, schemaFormDecorators, sfSelect) {
var SNAKE_CASE_REGEXP = /[A-Z]/g;
var snakeCase = function(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
};
return {
scope: {
schema: '=sfSchema',
initialForm: '=sfForm',
model: '=sfModel',
options: '=sfOptions'
},
controller: ['$scope', function($scope) {
this.evalInParentScope = function(expr, locals) {
return $scope.$parent.$eval(expr, locals);
};
}],
replace: false,
restrict: 'A',
transclude: true,
require: '?form',
link: function(scope, element, attrs, formCtrl, transclude) {
//expose form controller on scope so that we don't force authors to use name on form
scope.formCtrl = formCtrl;
//We'd like to handle existing markup,
//besides using it in our template we also
//check for ng-model and add that to an ignore list
//i.e. even if form has a definition for it or form is ["*"]
//we don't generate it.
var ignore = {};
transclude(scope, function(clone) {
clone.addClass('schema-form-ignore');
element.prepend(clone);
if (element[0].querySelectorAll) {
var models = element[0].querySelectorAll('[ng-model]');
if (models) {
for (var i = 0; i < models.length; i++) {
var key = models[i].getAttribute('ng-model');
//skip first part before .
ignore[key.substring(key.indexOf('.') + 1)] = true;
}
}
}
});
//Since we are dependant on up to three
//attributes we'll do a common watch
var lastDigest = {};
scope.$watch(function() {
var schema = scope.schema;
var form = scope.initialForm || ['*'];
//The check for schema.type is to ensure that schema is not {}
if (form && schema && schema.type &&
(lastDigest.form !== form || lastDigest.schema !== schema) &&
Object.keys(schema.properties).length > 0) {
lastDigest.schema = schema;
lastDigest.form = form;
var merged = schemaForm.merge(schema, form, ignore, scope.options);
var frag = document.createDocumentFragment();
//make the form available to decorators
scope.schemaForm = {form: merged, schema: schema};
//clean all but pre existing html.
element.children(':not(.schema-form-ignore)').remove();
//Create directives from the form definition
angular.forEach(merged,function(obj,i){
var n = document.createElement(attrs.sfDecorator || snakeCase(schemaFormDecorators.defaultDecorator,'-'));
n.setAttribute('form','schemaForm.form['+i+']');
var slot;
try {
slot = element[0].querySelector('*[sf-insert-field="' + obj.key + '"]');
} catch(err) {
// field insertion not supported for complex keys
slot = null;
}
if(slot) {
slot.innerHTML = "";
slot.appendChild(n);
} else {
frag.appendChild(n);
}
});
element[0].appendChild(frag);
//compile only children
$compile(element.children())(scope);
//ok, now that that is done let's set any defaults
schemaForm.traverseSchema(schema, function(prop, path) {
if (angular.isDefined(prop['default'])) {
var val = sfSelect(path, scope.model);
if (angular.isUndefined(val)) {
sfSelect(path, scope.model, prop['default']);
}
}
});
}
});
}
};
}
]);
angular.module('schemaForm').directive('schemaValidate', ['sfValidator', function(sfValidator) {
return {
restrict: 'A',
scope: false,
// We want the link function to be *after* the input directives link function so we get access
// the parsed value, ex. a number instead of a string
priority: 1000,
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
//Since we have scope false this is the same scope
//as the decorator
scope.ngModel = ngModel;
var error = null;
var getForm = function() {
if (!form) {
form = scope.$eval(attrs.schemaValidate);
}
return form;
};
var form = getForm();
// Validate against the schema.
// Get in last of the parses so the parsed value has the correct type.
if (ngModel.$validators) { // Angular 1.3
ngModel.$validators.schema = function(value) {
var result = sfValidator.validate(getForm(), value);
error = result.error;
return result.valid;
};
} else {
// Angular 1.2
ngModel.$parsers.push(function(viewValue) {
form = getForm();
//Still might be undefined
if (!form) {
return viewValue;
}
var result = sfValidator.validate(form, viewValue);
if (result.valid) {
// it is valid
ngModel.$setValidity('schema', true);
return viewValue;
} else {
// it is invalid, return undefined (no model update)
ngModel.$setValidity('schema', false);
error = result.error;
return undefined;
}
});
}
// Listen to an event so we can validate the input on request
scope.$on('schemaFormValidate', function() {
if (ngModel.$validate) {
ngModel.$validate();
if (ngModel.$invalid) { // The field must be made dirty so the error message is displayed
ngModel.$dirty = true;
ngModel.$pristine = false;
}
} else {
ngModel.$setViewValue(ngModel.$viewValue);
}
});
//This works since we now we're inside a decorator and that this is the decorators scope.
//If $pristine and empty don't show success (even if it's valid)
scope.hasSuccess = function() {
return ngModel.$valid && (!ngModel.$pristine || !ngModel.$isEmpty(ngModel.$modelValue));
};
scope.hasError = function() {
return ngModel.$invalid && !ngModel.$pristine;
};
scope.schemaError = function() {
return error;
};
}
};
}]); | Korkki/seo | project/static/js/vendor/schema-form.js | JavaScript | mit | 46,226 |
/*
Copyright (c) 2011, Chris Umbel
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.
*/
var natural = require('natural'),
classifier = new natural.BayesClassifier();
classifier.train([
{classification: 'software', text: "my unit-tests failed."},
{classification: 'software', text: "tried the program, but it was buggy."},
{classification: 'hardware', text: "the drive has a 2TB capacity."},
{classification: 'hardware', text: "i need a new power supply."}
]);
console.log(classifier.classify('did the tests pass?'));
console.log(classifier.classify('did you buy a new drive?'));
| tj/natural | examples/classification/basic.js | JavaScript | mit | 1,580 |
var helpers = require('./');
/** Boids is a lot like Castle in the way it treats elements. But it is more
predictable, and retains attribute information.
1. The root node is collapsed, but its name is preserved in document['*']
2. Attributes are stored in a Object<String -> String> mapping, called "$".
* XML elements that are named '$' will conflict with the way boids represents
attributes.
3. in between elements is discarded.
4. Namespacing is taken literally.
5. Relative order between siblings of different names (or text nodes) is
disregarded, though order between siblings of the same name will be
preserved.
*/
function convertNode(node) {
/** Convert a single node into a javascript object. */
var obj = {$: {}};
// save all attributes to the '$' field
node.attrs().forEach(function(attr) {
obj.$[helpers.fullName.apply(attr)] = attr.value();
});
var texts = [];
node.childNodes().forEach(function(node) {
var type = node.type();
if (type == 'element') {
var tag = helpers.fullName.apply(node);
if (obj[tag] === undefined) {
obj[tag] = [];
}
obj[tag].push(convertNode(node));
}
else {
texts.push(node.text());
}
});
// finally concatenate all the text nodes together and save them as the '_' field
obj._ = helpers.parseString(texts.join('').trim());
return obj;
}
function boids(xml, opts) {
var root = helpers.parseXML(xml);
var obj = convertNode(root);
// special root handling:
obj['*'] = root.name();
return obj;
}
module.exports = boids;
| chbrown/xmlconv | lib/boids.js | JavaScript | mit | 1,571 |
let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
module.exports = function() {
let app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use('/gallery', express.static('public'));
app.get('/gallery', function(req,res) {
res.sendFile(path.join(__dirname + '/../index.html'));
});
return app;
};
| owlsketch/the-gallery | config/express.js | JavaScript | mit | 413 |
import { module, test } from 'qunit';
module('Unit | Utility | fd common primitives');
// Replace this with your real tests.
test('it works', function(assert) {
assert.ok(true);
});
| Flexberry/ember-flexberry-designer | tests/unit/utils/fd-common-primitives-test.js | JavaScript | mit | 186 |
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var React = require('react');
var _1 = require("../../../");
var bemBlock = require('bem-cn');
var size = require('lodash/size');
var toArray = require('lodash/toArray');
var map = require('lodash/map');
var FilterGroupItem = (function (_super) {
__extends(FilterGroupItem, _super);
function FilterGroupItem(props) {
_super.call(this, props);
this.removeFilter = this.removeFilter.bind(this);
}
FilterGroupItem.prototype.removeFilter = function () {
var _a = this.props, removeFilter = _a.removeFilter, filter = _a.filter;
if (removeFilter) {
removeFilter(filter);
}
};
FilterGroupItem.prototype.render = function () {
var _a = this.props, bemBlocks = _a.bemBlocks, label = _a.label, itemKey = _a.itemKey;
return (React.createElement(_1.FastClick, {handler: this.removeFilter}, React.createElement("div", {className: bemBlocks.items("value"), "data-key": itemKey}, label)));
};
FilterGroupItem = __decorate([
_1.PureRender,
__metadata('design:paramtypes', [Object])
], FilterGroupItem);
return FilterGroupItem;
}(React.Component));
exports.FilterGroupItem = FilterGroupItem;
var FilterGroup = (function (_super) {
__extends(FilterGroup, _super);
function FilterGroup(props) {
_super.call(this, props);
this.removeFilters = this.removeFilters.bind(this);
}
FilterGroup.prototype.removeFilters = function () {
var _a = this.props, removeFilters = _a.removeFilters, filters = _a.filters;
if (removeFilters) {
removeFilters(filters);
}
};
FilterGroup.prototype.render = function () {
var _this = this;
var _a = this.props, mod = _a.mod, className = _a.className, title = _a.title, filters = _a.filters, removeFilters = _a.removeFilters, removeFilter = _a.removeFilter;
var bemBlocks = {
container: bemBlock(mod),
items: bemBlock(mod + "-items")
};
return (React.createElement("div", {key: title, className: bemBlocks.container().mix(className)}, React.createElement("div", {className: bemBlocks.items()}, React.createElement("div", {className: bemBlocks.items("title")}, title), React.createElement("div", {className: bemBlocks.items("list")}, map(filters, function (filter) { return _this.renderFilter(filter, bemBlocks); }))), this.renderRemove(bemBlocks)));
};
FilterGroup.prototype.renderFilter = function (filter, bemBlocks) {
var _a = this.props, translate = _a.translate, removeFilter = _a.removeFilter;
return (React.createElement(FilterGroupItem, {key: filter.value, itemKey: filter.value, bemBlocks: bemBlocks, filter: filter, label: translate(filter.value), removeFilter: removeFilter}));
};
FilterGroup.prototype.renderRemove = function (bemBlocks) {
if (!this.props.removeFilters)
return null;
return (React.createElement(_1.FastClick, {handler: this.removeFilters}, React.createElement("div", {className: bemBlocks.container("remove-action"), onClick: this.removeFilters}, "X")));
};
FilterGroup.defaultProps = {
mod: "sk-filter-group",
translate: function (str) { return str; }
};
return FilterGroup;
}(React.Component));
exports.FilterGroup = FilterGroup;
//# sourceMappingURL=FilterGroup.js.map | viktorkh/elastickit_express | node_modules/searchkit/lib/src/components/ui/filter-group/FilterGroup.js | JavaScript | mit | 4,385 |
/**古代战争
* 作者:YYC
* 日期:2014-02-12
* 电子邮箱:395976266@qq.com
* QQ: 395976266
* 博客:http://www.cnblogs.com/chaogex/
*/
var PlantsSprite = YYC.Class(TerrainSprite, {
Protected: {
},
Public: {
name: "plants"
}
}); | yyc-git/AncientWar | src/sprite/terrain/PlantsSprite.js | JavaScript | mit | 271 |
(function (root, undefined) {
"use strict";
| maniartech/framework-factory | src/(open).js | JavaScript | mit | 44 |
(function () {
'use strict';
/**
* Introduce the vendorAppApp.customer.list.edit module
* and configure it.
*
* @requires 'ui.router',
* @requires 'ngMaterial',
* @requires vendorAppApp.mongooseError
* @requires vendorAppApp.customer.service
*/
angular
.module('vendorAppApp.customer.list.edit', [
'ui.router',
'ngMaterial',
'vendorAppApp.mongooseError',
'vendorAppApp.customer.service'
])
.config(configureCustomerListEdit);
// inject configCustomerListEdit dependencies
configureCustomerListEdit.$inject = ['$stateProvider'];
/**
* Route configuration function configuring the passed $stateProvider.
* Register the customer.list.edit state with the edit template
* paired with the CustomerEditController as 'edit' for the
* 'detail@customer.list' view.
* 'customer' is resolved as the customer with the id found in
* the state parameters.
*
* @param {$stateProvider} $stateProvider - The state provider to configure
*/
function configureCustomerListEdit($stateProvider) {
// The edit state configuration.
var editState = {
name: 'customer.list.edit',
parent: 'customer.list',
url: '/edit/:id',
authenticate: true,
role: 'user',
onEnter: onEnterCustomerListEdit,
views: {
'detail@customer.list': {
templateUrl: 'app/customer/list/edit/edit.html',
controller: 'CustomerEditController',
controllerAs: 'edit',
resolve: {customer: resolveCustomerFromArray}
}
}
};
$stateProvider.state(editState);
}
// inject onCustomerListEditEnter dependencies
onEnterCustomerListEdit.$inject = ['$timeout', 'ToggleComponent'];
/**
* Executed when entering the customer.list.detail state. Open the component
* registered with the component id 'customer.detailView'.
*
* @params {$timeout} $timeout - The $timeout service to wait for view initialization
* @params {ToggleComponent} ToggleComponent - The service to toggle the detail view
*/
function onEnterCustomerListEdit($timeout, ToggleComponent) {
$timeout(showDetails, 0, false);
function showDetails() {
ToggleComponent('customer.detailView').open();
}
}
// inject resolveCustomerDetailRoute dependencies
resolveCustomerFromArray.$inject = ['customers', '$stateParams', '_'];
/**
* Resolve dependencies for the customer.list.edit state. Get the customer
* from the injected Array of customers by using the '_id' property.
*
* @params {Array} customers - The array of customers
* @params {Object} $stateParams - The $stateParams to read the customer id from
* @params {Object} _ - The lodash service to find the requested customer
* @returns {Object|null} The customer whose value of the _id property equals $stateParams._id
*/
function resolveCustomerFromArray(customers, $stateParams, _) {
// return Customer.get({id: $stateParams.id}).$promise;
return _.find(customers, {'_id': $stateParams.id});
}
})();
| AVEAutomation/vendor-app | client/app/customer/list/edit/edit.js | JavaScript | mit | 3,068 |
jQuery(function(){
'use strict';
var Test={};
var tests=[];
var messages={
success: 'Success',
failed: 'FAILED',
pending: 'Pending...'
};
var classes = {
success: 'success',
failed: 'danger',
pending: 'warning'
}
var row_id_prefix = 'tests_td_';
var textProperty = (document.createElement('span').textContent !== undefined) ? 'textContent' : 'innerText';
var row_template = document.createElement('tr');
row_template.appendChild(document.createElement('td'));
row_template.appendChild(document.createElement('td'));
row_template.appendChild(document.createElement('td'));
var tbody = document.getElementById('results_tbody');
Test.add = function(group, func){
var row;
tests.push({group: group, func: func});
row = row_template.cloneNode(true);
row.id = 'tests_td_' + (tests.length-1);
row.getElementsByTagName('td')[0][textProperty] = group;
tbody.appendChild(row);
};
function TestController(row){
this._row = row;
this._asserted = false;
this._status='pending';
}
var assertionFailed = {};
TestController.prototype._setStatus=function(status, extra){
var status_td = this._row.getElementsByTagName('td')[1];
var display_string = messages[status];
if(extra){
display_string += " (" + extra + ")";
}
status_td[textProperty] = display_string;
status_td.className = classes[status];
this._status = status;
};
TestController.prototype._setDescription=function(desc){
var desc_td = this._row.getElementsByTagName('td')[2];
desc_td[textProperty] = desc;
}
TestController.prototype.assert = function(value, desc){
this._asserted = true;
if(value !== true){
this._setStatus('failed');
this._setDescription('Assertion failed: ' + desc);
throw assertionFailed;
}
};
TestController.prototype.must_throw = function(func, desc){
var thrown = false;
if(!desc){
desc = 'expected to throw exception';
}
try{
func();
}catch(e){
thrown = true;
}
this.assert(thrown, desc);
};
TestController.prototype.must_not_be_called = function(desc){
var test_controller = this;
if(!desc){
desc = 'function is not called';
}
return function(){
test_controller.assert(false, desc);
};
}
Test.run = function(){
var i = 0, num_tests = tests.length;
var t;
for(; i< num_tests; ++i){
t = new TestController(document.getElementById('tests_td_' + i));
t._setStatus('pending');
try{
tests[i].func(t);
if(t._status === 'pending'){
if(t._asserted){
//Success all tests
t._setStatus('success');
}else{
t._setDescription('No assertion was given.');
}
}
}catch(e){
if(e !== assertionFailed){
t._setStatus('failed','exception');
t._setDescription(e.message);
}
}
}
};
window.Test=Test;
});
| jkr2255/grouped_callbacks | test_lib.js | JavaScript | mit | 2,809 |
'use strict';
var _ = require('underscore'),
through2 = require('through2'),
fs = require('fs'),
hdiff = require('hdiff'),
spawn = require('child_process').spawn,
which = require('which'),
gutil = require('gulp-util'),
path = require('path');
module.exports = function () {
var diffMapper = jsonDiffMapper();
return through2(
{objectMode: true},
function (file, enc, cb) {
log('Checking ' + file.path + 'for updates');
execCommands(_.map(_.filter(mapDiffToCommands(diffMapper(file)), filterEmptyCommands), commandToCurrentCwdMapper(path.dirname(file.path))), cb);
this.push(file);
}
)
}
function log() {
return gutil.log.apply(gutil, [].slice.call(arguments));
}
function filterEmptyCommands(cmd) {
return !!cmd.length;
}
function execCommands(cmds, cb) {
if (!cmds.length) return cb();
var cmd = cmds.shift();
which(cmd[0], function (err, cmdpath) {
if (err) {
log("Couldn't find the path to " + cmd[0]);
return cb(err);
}
log(cmd[0] + ' ' + cmd[1].join(' '));
cmd[0] = cmdpath;
cmd[2].stdio = 'inherit';
cmd = spawn.apply(spawn, cmd);
cmd.on('close', function onClose() { return execCommands(cmds, cb); })
})
}
function jsonDiffMapper() {
var cache = {};
return function (file) {
var oldJson = cache[file.path];
var newJson = JSON.parse(fs.readFileSync(file.path, {encoding: 'utf8'}));
cache[file.path] = newJson;
if (!oldJson)
return {'$new': newJson}
return hdiff(oldJson, newJson, {unchanged: false});
}
}
function commandToCurrentCwdMapper(cwd) {
return function (cmd) {
if (!cmd) return;
cmd[2] = cmd[2] || {};
cmd[2].cwd = cwd;
return cmd;
}
}
function mapDiffToCommands(diff) {
if (!diff) return [];
var mappers = [mapInstallToCmd, mapRemoveToCmd, mapUpdateToCmd];
return _.union(
mapNewToCmds(diff),
mapDependenciesToCmds(diff.dependencies, mappers),
_.map(mapDependenciesToCmds(diff.devDependencies, mappers), mapDevCmds)
);
}
function mapNewToCmds(diff) {
if (!diff['$new']) return [];
return [createCommand('npm',['install'])];
}
function mapDependenciesToCmds(deps, mappers) {
if (!_.isObject(deps)) return [];
var cmds = [];
_.each(mappers,function(mapper) {
cmds.push(_mapDependenciesToCmds(deps, mapper));
})
return _.union.apply(_, cmds);
}
function _mapDependenciesToCmds(deps, mapper) {
if (!_.isObject(deps)) return [];
var cmds = [];
_.each(deps,function(diff, pkg) {
var cmd = mapper(diff, pkg);
if (cmd)
cmds.push(cmd);
})
return cmds;
}
function mapRemoveToCmd(diff, pkg) {
if (!isRemove(diff)) return;
return createCommand('npm',['remove', pkg]);
}
function mapInstallToCmd(diff, pkg) {
if (!isInstall(diff)) return [];
return createCommand('npm',['install', resolveFullPackageName(diff, pkg)]);
}
function mapUpdateToCmd(diff, pkg) {
if (!isUpdate(diff)) return [];
return createCommand('npm',['install', resolveFullPackageName(diff, pkg)]);
}
function mapDevCmds(cmd) {
if (cmd.length)
cmd[1].push('--save-dev');
return cmd;
}
function isUpdate(diff){ return diff['$add'] && diff['$del']; }
function isInstall(diff){ return diff['$add'] && !diff['$del']; }
function isRemove(diff){ return !diff['$add'] && diff['$del']; }
function resolveFullPackageName(diff, pkg) {
if (!diff['$add']) return pkg;
return pkg + '@' + diff['$add'];
}
function createCommand(cmd, args, opts) {
return [cmd, args, opts || {}];
}
| tounano/gulp-update | index.js | JavaScript | mit | 3,562 |
import { FieldErrorProcessor } from "./processors/field-error-processor";
import { RuleResolver } from "./rulesets/rule-resolver";
import { ValidationGroupBuilder } from "./builders/validation-group-builder";
import { ruleRegistry } from "./rule-registry-setup";
import { RulesetBuilder } from "./builders/ruleset-builder";
import { DefaultLocaleHandler } from "./localization/default-locale-handler";
import { locale as defaultLocale } from "./locales/en-us";
import { Ruleset } from "./rulesets/ruleset";
const defaultLocaleCode = "en-us";
const defaultLocaleHandler = new DefaultLocaleHandler();
defaultLocaleHandler.registerLocale(defaultLocaleCode, defaultLocale);
defaultLocaleHandler.useLocale(defaultLocaleCode);
const fieldErrorProcessor = new FieldErrorProcessor(ruleRegistry, defaultLocaleHandler);
const ruleResolver = new RuleResolver();
export function createRuleset(basedUpon, withRuleVerification = false) {
const rulesetBuilder = withRuleVerification ? new RulesetBuilder(ruleRegistry) : new RulesetBuilder();
return rulesetBuilder.create(basedUpon);
}
export function mergeRulesets(rulesetA, rulesetB) {
const newRuleset = new Ruleset();
newRuleset.rules = Object.assign({}, rulesetA.rules, rulesetB.rules);
newRuleset.compositeRules = Object.assign({}, rulesetA.compositeRules, rulesetB.compositeRules);
newRuleset.propertyDisplayNames = Object.assign({}, rulesetA.propertyDisplayNames, rulesetB.propertyDisplayNames);
return newRuleset;
}
export function createGroup() { return new ValidationGroupBuilder(fieldErrorProcessor, ruleResolver, defaultLocaleHandler).create(); }
export const localeHandler = defaultLocaleHandler;
export function supplementLocale(localeCode, localeResource) {
defaultLocaleHandler.supplementLocaleFrom(localeCode, localeResource);
}
| grofit/treacherous | dist/es2015/exposer.js | JavaScript | mit | 1,813 |
define([],function(){
var config = {};
config.title="Domain Totals Report";
var backColor = '#ffffff';
var axisColor = '#3e3e3e';
var gridlinesColor = '#000000';
var axisTitleColor = '#333333';
var color1 = '#4BACC6';
var color2 = '#8064A2';
var color3 = '#eda637';
var color4 = '#a7a737';
var color5 = '#86aa65';
var color6 = '#8aabaf';
var color7 = '#69c8ff';
var color8 = '#3e3e3e';
var color9 = '#4bb3d3';
config.height=550,
config.width= '100%';
config.title="Domain Totals Report";
config.vAxis= {maxValue: 100};
config.backgroundColor= backColor;
config.chartArea={left: 165, width:"100%",height:"75%"};
config.hAxis= {title: 'Domain', textStyle: {color: axisTitleColor}};
config.vAxis= {title: '# of Visits', gridlines: {count: 5, color: gridlinesColor},format:0, baselineColor:axisColor, textStyle:{color: axisTitleColor}};
config.colors= [ color1, color2, color3, color4, color5, color6, color7, color8];
config.visType="PieChart";
return config;
}); | uoForms/quickforms3 | QF3 Apps/rpp/reports/js/totalDomain.js | JavaScript | mit | 1,016 |
/**
* @file A set of global functions available to all components.
* @author Rowina Sanela
*/
(bbn => {
"use strict";
if ( !bbn.vue ){
throw new Error("Impossible to find the library bbn-vue")
}
Vue.mixin({
computed: {
/**
* Return the object of the currentPopup.
* @computed currentPopup
* @return {Object}
*/
currentPopup(){
if ( !this._currentPopup ){
let e = bbn.vue._retrievePopup(this);
if ( e ){
this._currentPopup = e;
}
else{
let vm = this;
while (vm = vm.$parent) {
if ( vm._currentPopup ){
this._currentPopup = vm._currentPopup;
break;
}
else if ( vm ){
e = bbn.vue._retrievePopup(vm);
if ( e ){
this._currentPopup = e;
break;
}
}
if (vm === this.$root) {
break;
}
}
}
}
if ( this._currentPopup ){
return this._currentPopup;
}
return null;
}
},
methods: {
/**
* Return the function bbn._ for the strings' translation.
* @method _
* @return {Function}
*/
_: bbn._,
/**
* Returns the given ref (will return $refs[name] or $refs[name][0])
* @method getRef
* @param {String} name
* @fires bbn.vue.getRef
* @return {Function}
*/
getRef(name){
return bbn.vue.getRef(this, name);
},
/**
* Checks if the component corresponds to the selector
* @method is
* @fires bbn.vue.is
* @param {String} selector
* @return {Function}
*/
is(selector){
return bbn.vue.is(this, selector);
},
/**
* Returns the closest component matching the given selector
* @method closest
* @param {String} selector
* @param {Boolean} checkEle
* @return {Function}
*/
closest(selector, checkEle){
return bbn.vue.closest(this, selector, checkEle);
},
/**
* Returns an array of parent components until $root
* @method ancestors
* @param {String} selector
* @param {Boolean} checkEle
* @return {Function}
*/
ancestors(selector, checkEle){
return bbn.vue.ancestors(this, selector, checkEle);
},
/**
* Fires the function bbn.vue.getChildByKey.
* @method getChildByKey
* @param {String} key
* @param {String} selector
* @todo Remove for Vue3
* @return {Function}
*/
getChildByKey(key, selector){
return bbn.vue.getChildByKey(this, key, selector);
},
/**
* Fires the function bbn.vue.findByKey.
* @method findByKey
* @param {String} key
* @param {String} selector
* @param {Array} ar
* @todo Remove for Vue3
* @return {Function}
*/
findByKey(key, selector, ar){
return bbn.vue.findByKey(this, key, selector, ar);
},
/**
* Fires the function bbn.vue.findAllByKey.
* @method findAllByKey
* @param {String} key
* @param {String} selector
* @todo Remove for Vue3
* @return {Function}
*/
findAllByKey(key, selector){
return bbn.vue.findAllByKey(this, key, selector);
},
/**
* Fires the function bbn.vue.find.
* @method find
* @param {String} selector
* @param {Number} index
* @todo Remove for Vue3
* @return {Function}
*/
find(selector, index){
return bbn.vue.find(this, selector, index);
},
/**
* Fires the function bbn.vue.findAll.
* @method findAll
* @param {String} selector
* @param {Boolean} only_children
* @todo Remove for Vue3
* @return {Function}
*/
findAll(selector, only_children){
return bbn.vue.findAll(this, selector, only_children);
},
/**
* Extends an object with Vue.$set
* @method extend
* @param {Boolean} selector
* @param {Object} source The object to be extended
* @param {Object} obj1
* @return {Object}
*/
extend(deep, src, obj1){
let args = [this];
for ( let i = 0; i < arguments.length; i++ ){
args.push(arguments[i]);
}
return bbn.vue.extend(...args);
},
/**
* Fires the function bbn.vue.getComponents.
* @method getComponents
* @param {Array} ar
* @param {Boolean} only_children
* @todo Remove for Vue3
* @return {Function}
*/
getComponents(ar, only_children){
return bbn.vue.getComponents(this, ar, only_children);
},
/**
* Opens the closest object popup.
* @method getPopup
* @return {Object}
*/
getPopup(){
let popup = bbn.vue.getPopup(this);
if (arguments.length && popup) {
let cfg = arguments[0];
let args = [];
if (bbn.fn.isObject(cfg)) {
cfg.opener = this;
}
args.push(cfg);
for (let i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
return popup.open.apply(popup, args);
}
return popup;
},
/**
* Opens a confirmation from the closest popup
* @method confirm
*/
confirm(){
let popup = this.getPopup();
if (arguments.length && popup) {
let cfg = arguments[0];
let args = [];
if (bbn.fn.isObject(cfg)) {
cfg.opener = this;
}
args.push(cfg);
for (let i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
if (!bbn.fn.isObject(cfg)) {
args.push(this);
}
return popup.confirm.apply(popup, args)
}
},
/**
* Opens an alert from the closest popup
* @method alert
*/
alert(){
let popup = this.getPopup();
if (arguments.length && popup) {
let cfg = arguments[0];
let args = [];
if (bbn.fn.isObject(cfg)) {
cfg.opener = this;
}
args.push(cfg);
for (let i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
if (!bbn.fn.isObject(cfg)) {
args.push(this);
}
return popup.alert.apply(popup, args)
}
},
/**
* Executes bbn.fn.post
* @method post
* @see {@link https://bbn.io/bbn-js/doc/ajax/post|bbn.fn.post} documentation
* @todo Stupid idea, it should be removed.
* @return {Promise}
*/
post(){
return bbn.vue.post(this, arguments);
},
/**
* Executes bbn.fn.postOut
* @method postOut
* @see {@link https://bbn.io/bbn-js/doc/ajax/postOut|bbn.fn.postOut} documentation
* @todo Stupid idea, it should be removed.
* @return {void}
*/
postOut(){
return bbn.vue.postOut(this, ...arguments);
},
/**
* @method getComponentName
* @todo Returns a component name based on the name of the given component and a path.
* @memberof bbn.vue
* @param {Vue} vm The component from which the name is created.
* @param {String} path The relative path to the component from the given component.
*/
getComponentName(){
return bbn.vue.getComponentName(this, ...arguments);
},
}
});
})(window.bbn); | nabab/bbn-vue | src/mixins.js | JavaScript | mit | 7,844 |
/*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame
} = Assert;
// 22.2.1.2 %TypedArray%: Different [[Prototype]] for copied ArrayBuffer depending on element types
// https://bugs.ecmascript.org/show_bug.cgi?id=2175
class MyArrayBuffer extends ArrayBuffer {}
let source = new Int8Array(new MyArrayBuffer(10));
let copySameType = new Int8Array(source);
assertSame(copySameType.buffer.constructor, MyArrayBuffer);
assertSame(Object.getPrototypeOf(copySameType.buffer), MyArrayBuffer.prototype);
let copyDifferentType = new Uint8Array(source);
assertSame(copyDifferentType.buffer.constructor, MyArrayBuffer);
assertSame(Object.getPrototypeOf(copyDifferentType.buffer), MyArrayBuffer.prototype);
| rwaldron/es6draft | src/test/scripts/suite/regress/bug2175.js | JavaScript | mit | 841 |
/* * @felipe de jesus | iti_fjpp@hotmail.com */
var msj_beforeSend=function (){
bootbox.dialog({
title: 'Vive Pueblos Mágicos',
message: '<center><i class="fa fa-spinner fa-spin fa-3x msjOk"></i><br>Espere por favor.</center>'
,onEscape : function() {}
});
//fa fa-times
$('body .modal-body').addClass('text_25');
$('.modal-title').css({
'color' : 'white',
'text-align' : 'left'
});
$('.close').css({
'color' : 'white',
'font-size' : 'x-large'
});
};
var isValidEmail=function (mail){
return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(mail);
}
function ventana(){
coordx= screen.width ? (screen.width-200)/2 : 0;
coordy= screen.height ? (screen.height-150)/2 : 0;
window.open(base_url+ 'config/mapa','miventana','width=800,height=600,top=30,right='+coordx+',left='+coordy);
} ;
var msj_error_noti=function (msj){
Messenger().post({
message: msj,
type: 'error',
showCloseButton: true
});
}
var msj_error_serve=function (){
Messenger().post({
message: 'Error al procesar la petición al servidor',
type: 'error',
showCloseButton: true
});
}
var msj_success_noti=function (msj){
Messenger().post({
message: msj,
showCloseButton: true
});
}
var msj_ok=function (titulo,msj,redirec){
bootbox.dialog({
title: 'Vive Pueblos Mágicos | '+(titulo == undefined ? '' : titulo),
message: '<center><i class="fa fa-check fa-4x msjOk"></i><br>'+(msj == undefined ? 'Acción realizado correctamente' : msj)+'</center>',
closeButton: true,
buttons: {
success: {
label : 'Aceptar',
className : 'green-msj btn btn-primary btn-cons',
callback : function(result) {
if(redirec!=undefined){
location.replace(redirec);
}
}
}
},onEscape : function() {}
});
//fa fa-times
$('body .modal-body').addClass('text_25');
$('.modal-title').css({
'color' : 'white',
'text-align' : 'left'
});
$('.close').css({
'color' : 'white',
'font-size' : 'x-large'
});
}
var msj_error=function (titulo,msj){
bootbox.dialog({
title: 'Vive Pueblos Mágicos | '+(titulo == undefined ? '' : titulo),
message: '<center><i class="fa fa-times fa-4x msjOk"></i><br>'+(msj == undefined ? 'Error al realizar la acción' : msj)+'</center>',
closeButton: true,
buttons: {
success: {
label : 'Aceptar',
className : 'green-msj btn btn-primary btn-cons',
callback : function(result) {
//location.replace(base_url)
}
}
},onEscape : function() {}
});
//fa
$('body .modal-body').addClass('text_25');
$('.modal-title').css({
'color' : 'white',
'text-align' : 'left'
});
$('.close').css({
'color' : 'white',
'font-size' : 'x-large'
});
}
var title=function (titulo){
document.title=(titulo ==undefined ? 'Vive Pueblos Mágicos' :titulo );
}
var get_fecha=function (){
var meses = new Array ("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
var diasSemana = new Array("Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado");
var f=new Date();
return diasSemana[f.getDay()] + " " + f.getDate() + " de " + meses[f.getMonth()] + " de " + f.getFullYear();
}
var fecha_yyyy_mm_dd=function (){
var hoy = new Date();
var dd = hoy.getDate();
var mm = hoy.getMonth()+1; //hoy es 0!
var yyyy = hoy.getFullYear();
if(dd<10) {
dd='0'+dd;
}
if(mm<10) {
mm='0'+mm;
}
return yyyy+'/'+mm+'/'+dd;
}
var fecha_dd_mm_yyyy=function (){
var hoy = new Date();
var dd = hoy.getDate();
var mm = hoy.getMonth()+1; //hoy es 0!
var yyyy = hoy.getFullYear();
if(dd<10) {
dd='0'+dd;
}
if(mm<10) {
mm='0'+mm;
}
return dd+'/'+mm+'/'+yyyy;
}
| bienTICS/LuchaVSCancerInfantil | assets/js/mensajes.js | JavaScript | mit | 4,861 |
// @flow
import { Parser, DomHandler } from 'htmlparser2';
const textToDOM = (html: string): any => {
const handler = new DomHandler();
const parser = new Parser(handler);
parser.write(html);
parser.done();
return handler.dom;
};
export default textToDOM;
| RafalFilipek/jsxfromhtml | src/textToDOM.js | JavaScript | mit | 269 |
// Modules.
let gulp = require('gulp'),
config = require('../../config'),
path = require('path');
// Package libraries.
gulp.task('package:css', () => {
'use strict';
let sourcePath = path.join(config.development.paths.css, '**/*');
let destinationPath = config.package.paths.css;
return gulp
.src([sourcePath])
.pipe(gulp.dest(destinationPath));
});
| mpolizzotti/solitude | tasks/package/css.js | JavaScript | mit | 394 |
const escapeStringRegexp = require('escape-string-regexp');
const query = require('../query/query');
const Sort = require('../helpers/sort');
const StringScore = require('../helpers/string-score');
const DataSource = {
cells: (name) => {
return new Promise((resolve) => {
// calculate text search score
const textMatch = (matches) => {
const arrWithScores = matches.map((matchedTerm) => {
return Object.assign(
{},
matchedTerm,
{
score: StringScore(matchedTerm.name, name),
}
);
});
const sorted = Sort.arrayOfObjectByKeyNumber(arrWithScores, 'score', 'desc');
// add _id to name because some cell lines have the same name
return sorted.map((cell) => {
return Object.assign(
{},
cell,
{
name: `${cell.name}; ${cell._id}`,
}
);
});
};
if (!name) {
resolve({
status: 200,
clientResponse: {
status: 200,
data: [],
message: 'Species string searched',
},
});
} else {
const escapedString = escapeStringRegexp(name);
const re = new RegExp(`^${escapedString}`, 'i');
query.get('cells', { name: { $regex: re } }, { })
.then((matches) => {
const sortedResults = textMatch(matches);
resolve({
status: 200,
clientResponse: {
status: 200,
data: sortedResults,
message: 'Cell string searched',
},
});
})
.catch((error) => {
resolve({
status: 500,
clientResponse: {
status: 500,
message: `There was an error querying the text string ${name}: ${error}`,
},
});
})
;
}
});
},
species: (name) => {
return new Promise((resolve) => {
// calculate text search score
const textMatch = (matches) => {
const arrWithScores = matches.map((matchedTerm) => {
return Object.assign(
{},
matchedTerm,
{
score: StringScore(matchedTerm.name, name),
}
);
});
return Sort.arrayOfObjectByKeyNumber(arrWithScores, 'score', 'desc');
};
if (!name) {
resolve({
status: 200,
clientResponse: {
status: 200,
data: [],
message: 'Species string searched',
},
});
} else {
const escapedString = escapeStringRegexp(name);
const re = new RegExp(`^${escapedString}`, 'i');
query.get('species', { name: { $regex: re } }, { })
.then((matches) => {
const sortedResults = textMatch(matches);
resolve({
status: 200,
clientResponse: {
status: 200,
data: sortedResults,
message: 'Species string searched',
},
});
})
.catch((error) => {
resolve({
status: 500,
clientResponse: {
status: 500,
message: `There was an error querying the text string ${name}: ${error}`,
},
});
})
;
}
});
},
};
module.exports = DataSource;
| knightjdr/screenhits | api/app/modules/data-source/data-source.js | JavaScript | mit | 3,535 |
<%= grunt.util._.camelize(appname) %>.Routers.<%= _.classify(name) %>Router = Backbone.Router.extend({
routes: {
"login" : "login"
},
initialize : function(){
var self = this;
},
login: function(){
var self = this;
}
});
| posabsolute/backbone_generate | templates/router.js | JavaScript | mit | 235 |
class Ranking { //object for ranking in curiosity
constructor(){// in contructor set a values for default in this class
ranking.colorActive = "#2262ae";//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
}
show (color){
ranking.colorActive = color;//colors of active stars
ranking.colorUnActive = "rgba(46,46,46,0.75)";//colors for unactive stars
ranking.stars = 0;//number of stars in ranking
ranking.averageStars = 0;//average of ranking
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
ranking.runRankingSetColors($(object),ranking.stars);
});
}
init(){//init function
this.setDatasToRankings();
}
setDatasToRankings(){//this function set values to ranking this date get from attribute data-stars in html
var these = this;
$.each($(".curiosity-ranking"),function(indx,object){//rut to rankings
object.style = "display:block";//show rankings
ranking.averageStars = object.getAttribute("data-stars");// get data stars
ranking.stars = (Math.floor(ranking.averageStars));// convert to int data stars
$(object).find(".star-text").text(ranking.averageStars);
$.each($(object).children(),function(index,obj){
obj.addEventListener("mouseover",these.hoverStar,false);
obj.addEventListener("mouseout",these.mouseOut,false);
if(index <= ranking.stars){
obj.style = "color:"+ranking.colorActive+";";
}
});
});
}
uploadStars(itemRanking,averageStars){//upload data stars in ranking element
if(averageStars>5 && averageStars<0){//validate data parameter
console.error("El segundo parametros recivido tiene que ser menor que 5 y mayor que 0");
}else{//if data parameter is correct
var parent = itemRanking.parentNode;// get ranking element(ul)
var stars = Math.floor(averageStars);// convert to int data stars
parent.setAttribute("data-stars",averageStars);//set new data stars to ranking
$(parent).find(".star-text").text(averageStars);//set text of average stars
ranking.runRankingSetColors($(parent),stars);// paint stars
}
}
hoverStar(event){//hover event
var starIndex = $(event.target).index();
ranking.runRankingSetColors($(event.target.parentNode),starIndex);
}
mouseOut(event){// mouse over event
var limitStars = Math.floor(event.target.parentNode.getAttribute("data-stars"));
ranking.runRankingSetColors($(event.target.parentNode),limitStars);
}
setColorActive(color){//set new color in case active
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
}
setColorUnActive(color){//set new color in case unactive
if(/^#[0-9][a-fA-F]{6}$/.test(color) || /^rgb\([0-9]{1,3}\,[0-9]{1,3}\,[0-9]{1,3}\)$/.test(color)){
ranking.colorUnActive = color;
}
else{
console.error("El parametro de la funcion setBackgroundColor debe ser hexadecimal o rgb");
}
}
setEventClick(clickfunction){
if($.isFunction(clickfunction)){
$(".curiosity-ranking>li.item-ranking").click(clickfunction);
}else{
console.error("El parametro recibido tiene que ser una función");
}
}
};
var ranking = {//object with values to use in this class
colorActive : "",
colorUnActive : "",
stars : 0,
averageStars : 0,
runRankingSetColors : function(rankingElement,limitStars){//run to item ranking for set stars
$.each(rankingElement.children(),function(index,object){
if(index <= limitStars){
object.style = "color:"+ranking.colorActive+";";
}else{
object.style = "color:"+ranking.colorUnActive+";";
}
});
}
};
//end of document
| Curiosity-Education/curiosity-v.1.0 | public/packages/assets/js/ranking-curiosity.js | JavaScript | mit | 4,228 |
'use strict';
const ServiceEmitter = require('./lib/ServiceEmitter');
const ServiceProvider = require('./lib/ServiceProvider');
module.exports = { ServiceEmitter, ServiceProvider };
| protocoolmx/spokesman | index.js | JavaScript | mit | 184 |
const should = require('should');
var Regex = require('../');
var conStr = 'dHello World';
describe( 'replace test', function () {
it( 'left area', function () {
var regex = new Regex('H');
regex.replace(conStr,'h').should.equal('dhello World');
} );
it( 'middle area', function () {
var regex = new Regex('o\\sW');
regex.replace(conStr,'T').should.equal('dHellTorld');
} );
it( 'right area', function () {
var regex = new Regex('d$');
regex.replace(conStr,'P').should.equal('dHello WorlP');
} );
it( 'more match', function () {
var regex = new Regex('o','ig');
regex.replace(conStr,'').should.equal('dHell Wrld');
} );
} ); | kelvv/regexper.js | test/test.replace.js | JavaScript | mit | 726 |
/*global beforeEach, describe, it,*/
/*eslint no-unused-expressions: 0*/
'use strict';
require('./testdom')('<html><body></body></html>');
var expect = require('chai').expect;
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var BookmarkList = require('./../../react/component/BookmarkList');
var BookmarkListItem = require('./../../react/component/BookmarkListItem');
describe('BookmarkList', function() {
var component;
beforeEach(function() {
component = TestUtils.renderIntoDocument(<BookmarkList />);
});
it('renders a dom element', function() {
expect(component.getDOMNode().tagName.toLowerCase()).to.be.not.empty;
});
describe('with bookmarks', function() {
var bookmarks,
items;
beforeEach(function() {
bookmarks = [1, 23, 42, 678].map(v => ({
url: `http://some-url.com/${v}`,
tags: `#static #${v}`
}));
component.setProps({bookmarks: bookmarks});
items = TestUtils.scryRenderedComponentsWithType(component, BookmarkListItem);
});
it('displays a BookmarkListItem for each data element', function() {
expect(items).to.have.length.of(bookmarks.length);
});
it('passes the url as children to the BookmarkListItem', function() {
items.forEach((item, idx) =>
expect(item.props.children).to.equal(bookmarks[idx].url));
});
it('passes the tags via the tags attribute to the BookmarkListItem', function() {
items.forEach((item, idx) =>
expect(item.props.tags).to.equal(bookmarks[idx].tags));
});
});
});
| mlenkeit/animated-octo-sansa | react-test/component/BookmarkList-mocha.js | JavaScript | mit | 1,635 |
import Icon from '../components/Icon.vue'
Icon.register({
'mars-stroke-h': {
width: 480,
height: 512,
paths: [
{
d: 'M476.2 247.5c4.7 4.7 4.7 12.3 0.1 17l-55.9 55.9c-7.6 7.5-20.5 2.2-20.5-8.5v-23.9h-23.9v20c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-20h-27.6c-5.8 25.6-18.7 49.9-38.6 69.8-56.2 56.2-147.4 56.2-203.6 0s-56.2-147.4 0-203.6 147.4-56.2 203.6 0c19.9 19.9 32.8 44.2 38.6 69.8h27.6v-20c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v20h23.8v-23.9c0-10.7 12.9-16.1 20.5-8.5zM200.6 312.6c31.2-31.2 31.2-82 0-113.1-31.2-31.2-81.9-31.2-113.1 0s-31.2 81.9 0 113.1c31.2 31.2 81.9 31.2 113.1 0z'
}
]
}
})
| Justineo/vue-awesome | src/icons/mars-stroke-h.js | JavaScript | mit | 644 |
'use strict';
// Use application configuration module to register a new module
ApplicationConfiguration.registerModule('client');
| effello/Mean-S7 | public/modules/client/client.client.module.js | JavaScript | mit | 131 |
'use strict';
exports.port = process.env.PORT || 3000;
exports.mongodb = {
uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'localhost/lulucrawler'
};
exports.getThisUrl = '';
exports.companyName = '';
exports.projectName = 'luluCrawler';
exports.systemEmail = 'your@email.addy';
exports.cryptoKey = 'k3yb0ardc4t';
exports.loginAttempts = {
forIp: 50,
forIpAndUser: 7,
logExpiration: '20m'
};
exports.smtp = {
from: {
name: process.env.SMTP_FROM_NAME || exports.projectName +' Website',
address: process.env.SMTP_FROM_ADDRESS || 'your@email.addy'
},
credentials: {
user: process.env.SMTP_USERNAME || 'your@email.addy',
password: process.env.SMTP_PASSWORD || 'bl4rg!',
host: process.env.SMTP_HOST || 'smtp.gmail.com',
ssl: true
}
};
| s890506/LuLuCrawler | config.example.js | JavaScript | mit | 784 |
(function($){
$(document).ready(function(){
$('.rainbowcake').rainbowcake();
});
}(jQuery)); | jgett/rainbowcake | client/js/client.js | JavaScript | mit | 100 |