code stringlengths 2 1.05M |
|---|
// Generated on 2015-03-06 using
// generator-webapp 0.5.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// If you want to recursively match all subfolders, use:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Configurable paths
var config = {
app: 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
config: config,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= config.app %>/scripts/{,*/}*.js'],
tasks: ['jshint'],
options: {
livereload: true
}
},
jstest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['test:watch']
},
gruntfile: {
files: ['Gruntfile.js']
},
styles: {
files: ['<%= config.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= config.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= config.app %>/images/{,*/}*'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
open: true,
livereload: 35729,
// Change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
test: {
options: {
open: false,
port: 9001,
middleware: function(connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
dist: {
options: {
base: '<%= config.dist %>',
livereload: false
}
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= config.dist %>/*',
'!<%= config.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: [
'Gruntfile.js',
'<%= config.app %>/scripts/{,*/}*.js',
'!<%= config.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
// Mocha testing framework configuration options
mocha: {
all: {
options: {
run: true,
urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/index.html']
}
}
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the HTML file
wiredep: {
app: {
ignorePath: /^\/|\.\.\//,
src: ['<%= config.app %>/index.html'],
exclude: ['bower_components/bootstrap/dist/js/bootstrap.js']
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'<%= config.dist %>/images/{,*/}*.*',
'<%= config.dist %>/styles/fonts/{,*/}*.*',
'<%= config.dist %>/*.{ico,png}'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
options: {
dest: '<%= config.dist %>'
},
html: '<%= config.app %>/index.html'
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
options: {
assetsDirs: [
'<%= config.dist %>',
'<%= config.dist %>/images',
'<%= config.dist %>/styles'
]
},
html: ['<%= config.dist %>/{,*/}*.html'],
css: ['<%= config.dist %>/styles/{,*/}*.css']
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.{gif,jpeg,jpg,png}',
dest: '<%= config.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.svg',
dest: '<%= config.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
removeAttributeQuotes: true,
removeCommentsFromCDATA: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
useShortDoctype: true
},
files: [{
expand: true,
cwd: '<%= config.dist %>',
src: '{,*/}*.html',
dest: '<%= config.dist %>'
}]
}
},
// By default, your `index.html`'s <!-- Usemin block --> will take care
// of minification. These next options are pre-configured if you do not
// wish to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= config.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= config.app %>/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= config.dist %>/scripts/scripts.js': [
// '<%= config.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= config.app %>',
dest: '<%= config.dist %>',
src: [
'*.{ico,png,txt}',
'images/{,*/}*.webp',
'{,*/}*.html',
'styles/fonts/{,*/}*.*'
]
}, {
src: 'node_modules/apache-server-configs/dist/.htaccess',
dest: '<%= config.dist %>/.htaccess'
}, {
expand: true,
dot: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= config.dist %>'
},{
expand: true,
dot: true,
cwd: '<%= config.app %>/data',
src: '{,*/}*.*',
dest: '<%= config.dist %>/data'
}]
},
styles: {
expand: true,
dot: true,
cwd: '<%= config.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Generates a custom Modernizr build that includes only the tests you
// reference in your app
modernizr: {
dist: {
devFile: 'bower_components/modernizr/modernizr.js',
outputFile: '<%= config.dist %>/scripts/vendor/modernizr.js',
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'!<%= config.dist %>/scripts/vendor/*'
]
},
uglify: true
}
},
// Run some tasks in parallel to speed up build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
}
});
grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
if (grunt.option('allow-remote')) {
grunt.config.set('connect.options.hostname', '0.0.0.0');
}
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run([target ? ('serve:' + target) : 'serve']);
});
grunt.registerTask('test', function (target) {
if (target !== 'watch') {
grunt.task.run([
'clean:server',
'concurrent:test',
'autoprefixer'
]);
}
grunt.task.run([
'connect:test',
'mocha'
]);
});
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'cssmin',
'uglify',
'copy:dist',
// 'modernizr',
'rev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
import React, { Component } from 'react'
import './Header.scss'
export default class Header extends Component {
render() {
return (
<div className='header'>
<h1>ningjs</h1>
<p>{__('Hello World')}</p>
</div>
)
}
}
|
/* global AFRAME, assert, process, suite, test, setup, sinon, HTMLElement */
var buildData = require('core/component').buildData;
var components = require('index').components;
var helpers = require('../helpers');
var registerComponent = require('index').registerComponent;
var processSchema = require('core/schema').process;
var CloneComponent = {
init: function () {
var object3D = this.el.object3D;
var clone = object3D.clone();
clone.uuid = 'Bubble Fett';
object3D.add(clone);
}
};
var entityFactory = helpers.entityFactory;
suite('Component', function () {
suite('standard components', function () {
test('are registered', function () {
assert.ok('geometry' in components);
assert.ok('material' in components);
assert.ok('light' in components);
assert.ok('position' in components);
assert.ok('rotation' in components);
assert.ok('scale' in components);
});
});
suite('buildData', function () {
setup(function () {
components.dummy = undefined;
});
test('uses default values', function () {
var schema = processSchema({
color: {default: 'blue'},
size: {default: 5}
});
var el = document.createElement('a-entity');
var data = buildData(el, 'dummy', 'dummy', schema, {}, null);
assert.equal(data.color, 'blue');
assert.equal(data.size, 5);
});
test('uses default values for single-property schema', function () {
var schema = processSchema({
default: 'blue'
});
var el = document.createElement('a-entity');
var data = buildData(el, 'dummy', 'dummy', schema, undefined, null);
assert.equal(data, 'blue');
});
test('preserves type of default values', function () {
var schema = processSchema({
list: {default: [1, 2, 3, 4]},
none: {default: null},
string: {default: ''}
});
var el = document.createElement('a-entity');
var data = buildData(el, 'dummy', 'dummy', schema, undefined, null);
assert.shallowDeepEqual(data.list, [1, 2, 3, 4]);
assert.equal(data.none, null);
assert.equal(data.string, '');
});
test('uses mixin values', function () {
var data;
var TestComponent = registerComponent('dummy', {
schema: {
color: {default: 'red'},
size: {default: 5}
}
});
var el = document.createElement('a-entity');
var mixinEl = document.createElement('a-mixin');
mixinEl.setAttribute('dummy', 'color: blue; size: 10');
el.mixinEls = [mixinEl];
data = buildData(el, 'dummy', 'dummy', TestComponent.prototype.schema, {}, null);
assert.equal(data.color, 'blue');
assert.equal(data.size, 10);
});
test('uses mixin values for single-property schema', function () {
var data;
var TestComponent = registerComponent('dummy', {
schema: {
default: 'red'
}
});
var el = document.createElement('a-entity');
var mixinEl = document.createElement('a-mixin');
mixinEl.setAttribute('dummy', 'blue');
el.mixinEls = [mixinEl];
data = buildData(el, 'dummy', 'dummy', TestComponent.prototype.schema, undefined, null);
assert.equal(data, 'blue');
});
test('uses defined values', function () {
var data;
var TestComponent = registerComponent('dummy', {
schema: {
color: {default: 'red'},
size: {default: 5}
}
});
var el = document.createElement('a-entity');
var mixinEl = document.createElement('a-mixin');
mixinEl.setAttribute('dummy', 'color: blue; size: 10');
el.mixinEls = [mixinEl];
data = buildData(el, 'dummy', 'dummy', TestComponent.prototype.schema, {
color: 'green', size: 20
}, 'color: green; size: 20');
assert.equal(data.color, 'green');
assert.equal(data.size, 20);
});
test('uses defined values for single-property schema', function () {
var data;
var TestComponent = registerComponent('dummy', {
schema: {default: 'red'}
});
var el = document.createElement('a-entity');
var mixinEl = document.createElement('a-mixin');
mixinEl.setAttribute('dummy', 'blue');
el.mixinEls = [mixinEl];
data = buildData(el, 'dummy', 'dummy', TestComponent.prototype.schema, 'green', 'green');
assert.equal(data, 'green');
});
test('returns default value for a single-property schema ' +
'when the attribute is empty string', function () {
var data;
var TestComponent = registerComponent('dummy', {
schema: {default: 'red'}
});
var el = document.createElement('a-entity');
el.setAttribute('dummy', '');
data = buildData(el, 'dummy', 'dummy', TestComponent.prototype.schema, 'red');
assert.equal(data, 'red');
});
test('multiple vec3 properties do not share same default value object', function (done) {
var data;
var el = entityFactory();
var TestComponent = registerComponent('dummy', {
schema: {
direction: {type: 'vec3'},
position: {type: 'vec3'}
}
});
el.addEventListener('loaded', function () {
el.setAttribute('dummy', '');
data = el.getAttribute('dummy');
assert.shallowDeepEqual(data.direction,
TestComponent.prototype.schema.direction.default);
assert.shallowDeepEqual(data.position,
TestComponent.prototype.schema.position.default);
assert.notEqual(data.direction, data.position);
done();
});
});
});
suite('updateProperties', function () {
var el;
setup(function () {
el = entityFactory();
});
test('emits componentchanged for multi-prop', function (done) {
el.setAttribute('material', 'color: red');
el.addEventListener('componentchanged', function (evt) {
if (evt.detail.name !== 'material') { return; }
assert.equal(evt.detail.oldData.color, 'red');
assert.equal(evt.detail.newData.color, 'blue');
assert.equal(evt.detail.name, 'material');
assert.ok('id' in evt.detail);
done();
});
setTimeout(() => {
el.setAttribute('material', 'color: blue');
});
});
test('emits componentchanged for single-prop', function (done) {
el.setAttribute('position', {x: 0, y: 0, z: 0});
el.addEventListener('componentchanged', function (evt) {
if (evt.detail.name !== 'position') { return; }
assert.shallowDeepEqual(evt.detail.oldData, {x: 0, y: 0, z: 0});
assert.shallowDeepEqual(evt.detail.newData, {x: 1, y: 2, z: 3});
assert.equal(evt.detail.name, 'position');
assert.ok('id' in evt.detail);
done();
});
setTimeout(() => {
el.setAttribute('position', {x: 1, y: 2, z: 3});
});
});
test('emits componentchanged for value', function (done) {
el.addEventListener('componentchanged', function (evt) {
if (evt.detail.name !== 'visible') { return; }
assert.shallowDeepEqual(evt.detail.oldData, true);
assert.shallowDeepEqual(evt.detail.newData, false);
assert.equal(evt.detail.name, 'visible');
done();
});
setTimeout(() => {
el.setAttribute('visible', false);
});
});
test('does not emit componentchanged for multi-prop if not changed', function (done) {
el.addEventListener('componentinitialized', function (evt) {
if (evt.detail.name !== 'material') { return; }
el.addEventListener('componentchanged', function (evt) {
if (evt.detail.name !== 'material') { return; }
// Should not reach here.
assert.equal(true, false, 'Component should not have emitted changed.');
});
// Update.
el.setAttribute('material', 'color', 'red');
// Have `done()` race with the failing assertion in the event handler.
setTimeout(() => {
done();
}, 100);
});
// Initialization.
el.setAttribute('material', 'color', 'red');
});
test('does not emit componentchanged for single-prop if not changed', function (done) {
el.addEventListener('componentinitialized', function (evt) {
if (evt.detail.name !== 'position') { return; }
el.addEventListener('componentchanged', function (evt) {
if (evt.detail.name !== 'position') { return; }
// Should not reach here.
assert.equal(true, false, 'Component should not have emitted changed.');
});
// Update.
el.setAttribute('position', {x: 1, y: 2, z: 3});
// Have `done()` race with the failing assertion in the event handler.
setTimeout(() => {
done();
}, 100);
});
// Initialization.
el.setAttribute('position', {x: 1, y: 2, z: 3});
});
test('does not emit componentchanged for value if not changed', function (done) {
el.addEventListener('componentinitialized', function (evt) {
if (evt.detail.name !== 'visible') { return; }
el.addEventListener('componentchanged', function (evt) {
if (evt.detail.name !== 'visible') { return; }
// Should not reach here.
assert.equal(true, false, 'Component should not have emitted changed.');
});
// Update.
el.setAttribute('visible', false);
// Have `done()` race with the failing assertion in the event handler.
setTimeout(() => {
done();
}, 100);
});
// Initialization.
el.setAttribute('visible', false);
});
test('emits componentinitialized', function (done) {
el.addEventListener('componentinitialized', function (evt) {
if (evt.detail.name !== 'material') { return; }
assert.ok(evt.detail.data);
assert.ok('id' in evt.detail);
assert.equal(evt.detail.name, 'material');
done();
});
el.setAttribute('material', '');
});
});
suite('resetProperty', function () {
var el;
setup(function (done) {
el = entityFactory();
el.addEventListener('loaded', () => { done(); });
});
test('resets property to default value', function () {
AFRAME.registerComponent('test', {
schema: {
bar: {default: 5},
foo: {default: 5}
}
});
el.setAttribute('test', {bar: 10, foo: 10});
el.components.test.resetProperty('bar');
assert.equal(el.getAttribute('test').bar, 5);
assert.equal(el.getAttribute('test').foo, 10);
});
test('resets property to default value for single-prop', function () {
AFRAME.registerComponent('test', {
schema: {default: 5}
});
el.setAttribute('test', 10);
el.components.test.resetProperty();
assert.equal(el.getAttribute('test'), 5);
});
});
suite('third-party components', function () {
var el;
setup(function () {
el = entityFactory();
delete components.clone;
});
test('can be registered', function () {
assert.notOk('clone' in components);
registerComponent('clone', CloneComponent);
assert.ok('clone' in components);
});
test('can change behavior of entity', function (done) {
registerComponent('clone', CloneComponent);
el.addEventListener('loaded', function () {
assert.notOk('clone' in el.components);
assert.notOk(el.object3D.children.length);
el.setAttribute('clone', '');
assert.ok('clone' in el.components);
assert.equal(el.object3D.children[0].uuid, 'Bubble Fett');
done();
});
});
test('cannot be registered if it uses the character __ in the name', function () {
assert.notOk('my__component' in components);
assert.throws(function register () {
registerComponent('my__component', CloneComponent);
}, Error);
assert.notOk('my__component' in components);
});
});
suite('schema', function () {
test('can be accessed', function () {
assert.ok(components.position.schema);
});
});
suite('parse', function () {
setup(function () {
components.dummy = undefined;
});
test('parses single value component', function () {
var TestComponent = registerComponent('dummy', {
schema: {default: '0 0 1', type: 'vec3'}
});
var el = document.createElement('a-entity');
var component = new TestComponent(el);
var componentObj = component.parse('1 2 3');
assert.deepEqual(componentObj, {x: 1, y: 2, z: 3});
});
test('parses component properties vec3', function () {
var TestComponent = registerComponent('dummy', {
schema: {
position: {type: 'vec3', default: '0 0 1'}
}
});
var el = document.createElement('a-entity');
var component = new TestComponent(el);
var componentObj = component.parse({position: '0 1 0'});
assert.deepEqual(componentObj.position, {x: 0, y: 1, z: 0});
});
});
suite('parseAttrValueForCache', function () {
setup(function () {
components.dummy = undefined;
});
test('parses single value component', function () {
var TestComponent = registerComponent('dummy', {
schema: {default: '0 0 1', type: 'vec3'}
});
var el = document.createElement('a-entity');
var component = new TestComponent(el);
var componentObj = component.parseAttrValueForCache('1 2 3');
assert.deepEqual(componentObj, {x: 1, y: 2, z: 3});
});
test('parses component using the style parser for a complex schema', function () {
var TestComponent = registerComponent('dummy', {
schema: {
position: {type: 'vec3', default: '0 0 1'},
color: {default: 'red'}
}
});
var el = document.createElement('a-entity');
var component = new TestComponent(el);
var componentObj = component.parseAttrValueForCache({position: '0 1 0', color: 'red'});
assert.deepEqual(componentObj, {position: '0 1 0', color: 'red'});
});
test('does not parse properties that parse to another string', function () {
var TestComponent = registerComponent('dummy', {
schema: {
url: {type: 'src', default: ''}
}
});
var el = document.createElement('a-entity');
var component = new TestComponent(el);
var componentObj = component.parseAttrValueForCache({url: 'url(www.mozilla.com)'});
assert.equal(componentObj.url, 'url(www.mozilla.com)');
});
});
suite('stringify', function () {
setup(function () {
components.dummy = undefined;
});
test('stringifies single value component', function () {
var TestComponent = registerComponent('dummy', {
schema: {default: '0 0 1', type: 'vec3'}
});
var el = document.createElement('a-entity');
var component = new TestComponent(el);
var componentString = component.stringify({x: 1, y: 2, z: 3});
assert.deepEqual(componentString, '1 2 3');
});
test('stringifies component property vec3', function () {
var TestComponent = registerComponent('dummy', {
schema: {
position: {type: 'vec3', default: '0 0 1'}
}
});
var el = document.createElement('a-entity');
var component = new TestComponent(el);
var componentObj = {position: {x: 1, y: 2, z: 3}};
var componentString = component.stringify(componentObj);
assert.deepEqual(componentString, 'position:1 2 3');
});
});
suite('extendSchema', function () {
setup(function () {
components.dummy = undefined;
});
test('extends the schema', function () {
var TestComponent = registerComponent('dummy', {
schema: {color: {default: 'red'}}
});
var el = document.createElement('a-entity');
var component = new TestComponent(el);
component.extendSchema({size: {default: 5}});
assert.ok(component.schema.size);
assert.ok(component.schema.color);
});
});
suite('updateProperties', function () {
setup(function (done) {
components.dummy = undefined;
var el = this.el = entityFactory();
if (el.hasLoaded) { done(); }
el.addEventListener('loaded', function () { done(); });
});
test('updates the schema of a component', function () {
var TestComponent = registerComponent('dummy', {
schema: {color: {default: 'red'}},
updateSchema: function (data) {
this.extendSchema({energy: {default: 100}});
}
});
var component = new TestComponent(this.el);
component.updateProperties(null);
assert.equal(component.schema.color.default, 'red');
assert.equal(component.schema.energy.default, 100);
assert.equal(component.data.color, 'red');
});
test('updates the properties with the new value', function () {
var TestComponent = registerComponent('dummy', {
schema: {color: {default: 'red'}}
});
var component = new TestComponent(this.el);
component.updateProperties(null);
assert.equal(component.data.color, 'red');
});
test('updates the properties with a null value', function () {
var TestComponent = registerComponent('dummy', {
schema: {color: {default: 'red'}}
});
var component = new TestComponent(this.el);
component.updateProperties({color: 'blue'});
assert.equal(component.data.color, 'blue');
});
});
suite('update', function () {
setup(function (done) {
components.dummy = undefined;
var el = this.el = entityFactory();
if (el.hasLoaded) { done(); }
el.addEventListener('loaded', function () { done(); });
});
test('not called if component data does not change', function () {
var updateStub = sinon.stub();
var TestComponent = registerComponent('dummy', {
schema: {color: {default: 'red'}}
});
var component = new TestComponent(this.el);
component.update = updateStub;
component.updateProperties({color: 'blue'});
component.updateProperties({color: 'blue'});
assert.ok(updateStub.calledOnce);
});
test('supports array properties', function () {
var updateStub = sinon.stub();
var TestComponent = registerComponent('dummy', {
schema: {list: {default: ['a']}}
});
var component = new TestComponent(this.el);
component.update = updateStub;
component.updateProperties({list: ['b']});
component.updateProperties({list: ['b']});
sinon.assert.calledOnce(updateStub);
});
});
suite('flushToDOM', function () {
setup(function () {
components.dummy = undefined;
});
test('updates component DOM attribute', function () {
registerComponent('dummy', {
schema: {color: {default: 'red'}}
});
var el = document.createElement('a-entity');
el.setAttribute('dummy', {color: 'blue'});
assert.equal(HTMLElement.prototype.getAttribute.call(el, 'dummy'), '');
el.components.dummy.flushToDOM();
assert.equal(HTMLElement.prototype.getAttribute.call(el, 'dummy'), 'color:blue');
});
test('init and update are not called for a not loaded entity', function () {
var updateStub = sinon.stub();
var initStub = sinon.stub();
var el = document.createElement('a-entity');
registerComponent('dummy', {
schema: {color: {default: 'red'}},
init: initStub,
update: updateStub
});
assert.notOk(el.hasLoaded);
el.setAttribute('dummy', {color: 'blue'});
assert.equal(HTMLElement.prototype.getAttribute.call(el, 'dummy'), '');
el.components.dummy.flushToDOM();
sinon.assert.notCalled(initStub);
sinon.assert.notCalled(updateStub);
assert.equal(HTMLElement.prototype.getAttribute.call(el, 'dummy'), 'color:blue');
});
});
suite('play', function () {
setup(function () {
components.dummy = undefined;
var playStub = this.playStub = sinon.stub();
registerComponent('dummy', {play: playStub});
});
test('not called if entity is not playing', function () {
var el = document.createElement('a-entity');
var dummyComponent;
el.isPlaying = false;
el.setAttribute('dummy', '');
dummyComponent = el.components.dummy;
dummyComponent.initialized = true;
dummyComponent.play();
sinon.assert.notCalled(this.playStub);
});
test('not called if component is not initialized', function () {
var el = document.createElement('a-entity');
el.isPlaying = true;
el.setAttribute('dummy', '');
el.components.dummy.play();
sinon.assert.notCalled(this.playStub);
});
test('not called if component is already playing', function () {
var el = document.createElement('a-entity');
var dummyComponent;
el.isPlaying = true;
el.setAttribute('dummy', '');
dummyComponent = el.components.dummy;
dummyComponent.initialized = true;
dummyComponent.play();
dummyComponent.play();
sinon.assert.calledOnce(this.playStub);
});
});
suite('pause', function () {
setup(function () {
components.dummy = undefined;
var pauseStub = this.pauseStub = sinon.stub();
registerComponent('dummy', {
schema: {color: {default: 'red'}},
pause: pauseStub
});
});
test('not called if component is not playing', function () {
var el = document.createElement('a-entity');
el.setAttribute('dummy', '');
el.components.dummy.pause();
sinon.assert.notCalled(this.pauseStub);
});
test('called if component is playing', function () {
var el = document.createElement('a-entity');
var dummyComponent;
el.setAttribute('dummy', '');
el.isPlaying = true;
dummyComponent = el.components.dummy;
dummyComponent.initialized = true;
dummyComponent.isPlaying = true;
dummyComponent.pause();
sinon.assert.called(this.pauseStub);
});
test('not called if component is already paused', function () {
var el = document.createElement('a-entity');
var dummyComponent;
el.setAttribute('dummy', '');
dummyComponent = el.components.dummy;
dummyComponent.isPlaying = true;
dummyComponent.pause();
dummyComponent.pause();
sinon.assert.calledOnce(this.pauseStub);
});
});
});
|
import PropTypes from 'prop-types';
import React from 'react';
import cx from 'classnames';
import cxBinder from 'classnames/bind';
import styles from './_styles.scss';
const cxStyles = cxBinder.bind(styles);
export const FlexVideo = ({
containerClassName,
containerStyle,
vimeo,
widescreen,
...restProps,
}) => {
const classNames = cx(containerClassName, cxStyles('flex-video', { vimeo, widescreen }));
return (
<div className={classNames} style={containerStyle}>
<iframe {...restProps} />
</div>
);
};
FlexVideo.propTypes = {
containerClassName: PropTypes.string,
containerStyle: PropTypes.shape({}),
vimeo: PropTypes.bool,
widescreen: PropTypes.bool,
};
export default FlexVideo;
|
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var port = process.env.PORT || 3000;
server.listen(port);
var mongoose = require('mongoose');
var models = require('./models'),
Actor = models.Actor,
Movie = models.Movie;
mongoose.connect('mongodb://localhost/bacon');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
app.get('/actorName/:actorName', function (req, res){
var actorName = req.params.actorName
Actor.findOne({name: actorName}).exec(function(err, actor){
console.log(actor);
console.log(actor.movies);
// search it up
function visit(frontier, fn) {
var level = 0;
var levels = {};
while (0 < frontier.length) {
var next = [];
for (var i = 0; i < frontier.length; i++) {
var node = frontier[i];
fn(node);
levels[node] = level;
//make a call for actors of movies
nodeActors = [];
for(var movie in node.movies){
Movie.findOne({name: movie}).exec(function(err, movie){
nodeActors.push(movie);
});
}
for (var adj in nodeActors) {
if(adj.name == "Kevin Bacon"){
return adj;
}
if (typeof levels[adj] === 'undefined') {
next.push(adj);
}
}
}
frontier = next;
level += 1;
}
}
function bfs(node, fn) {
visit([node], fn);
}
var visited = [];
if(actor){
bfs(actor, function (n) {
console.log(n);
visited.push(n);
});
}
});
res.send(actorName);
});
|
jQuery(document).ready(function() {
// App.init();
// App.initCounter();
// App.initParallaxBg();
// LoginForm.initLoginForm();
// ContactForm.initContactForm();
// OwlCarousel.initOwlCarousel();
// StyleSwitcher.initStyleSwitcher();
var revapi = jQuery('.fullscreenbanner').revolution({
delay: 1500000,
startwidth: 500,
startheight: 500,
hideThumbs: 10,
fullWidth: "on",
fullScreen: "on",
hideCaptionAtLimit: "",
// dottedOverlay: "twoxtwo",
navigationStyle: "preview1",
fullScreenOffsetContainer: ""
});
$('.hero-grid').masonry({
// options
itemSelector:".hero-grid__item",
// columnWidth:".hero-grid__grid-sizer",
// percentPosition:!0
});
if(is.desktop()) {
$('.hero-grid__item-content__secondary').slimScroll({
height: '100%',
railVisible: true,
// alwaysVisible: true,
allowPageScroll: true,
});
} else {
// noop
}
}); |
var Cart = Cart || {};
Cart.init = function() {
};
Cart.addToCart = function(chosenItem) {
var fragment = document.createDocumentFragment();
var div1 = document.createElement('div');
fragment.appendChild(div1);
var div2 = document.createElement('div');
div1.appendChild(div2);
var editBtn = document.createElement('button');
editBtn.setAttribute('class', 'edit-btn btn btn-xs btn-default');
editBtn.appendChild(document.createTextNode('Edit'));
div2.appendChild(editBtn);
var removeBtn = document.createElement('button');
removeBtn.setAttribute('class', 'remove-btn btn btn-xs btn-danger');
removeBtn.appendChild(document.createTextNode('Remove'));
div2.appendChild(removeBtn);
var title = document.createElement('h3');
title.setAttribute('class', 'cart-title');
title.appendChild(document.createTextNode(chosenItem.item.name));
div1.appendChild(title);
var extras = document.createElement('p');
extras.setAttribute('class', 'cart-extras');
div1.appendChild(extras);
var price = document.createElement('p');
price.setAttribute('class', 'cart-price');
price.appendChild(document.createTextNode('$'+chosenItem.item.price));
div1.appendChild(price);
$('.cart').append(fragment);
};
|
$( function() {
var queryParams = getQueryParams();
var layout = queryParams.layout || '';
var config = null;
switch( layout.toLowerCase() ) {
case 'responsive':
config = createResponsiveConfig();
break;
case 'tab-dropdown':
config = createTabDropdownConfig();
break;
default:
config = createStandardConfig();
break;
}
window.myLayout = new GoldenLayout( config );
var rotate = function( container ) {
if( !container ) return;
while( container.parent && container.type != 'stack' )
container = container.parent;
if( container.parent ) {
var p = container.header.position();
var sides = [ 'top', 'right', 'bottom', 'left', false ];
var n = sides[ ( sides.indexOf( p ) + 1 ) % sides.length ];
container.header.position( n );
}
}
var nexttheme = function() {
var link = $( 'link[href*=theme]' ), href = link.attr( 'href' ).split( '-' );
var themes = [ 'dark', 'light', 'soda', 'translucent' ];
href[ 1 ] = themes[ ( themes.indexOf( href[ 1 ] ) + 1 ) % themes.length ];
link.attr( 'href', href.join( '-' ) );
}
myLayout.registerComponent( 'html', function( container, state ) {
container
.getElement()
.html( state.html ? state.html.join( '\n' ) : '<p>' + container._config.title + '</p>' );
if( state.style ) {
$( 'head' ).append( '<style type="text/css">\n' + state.style.join( '\n' ) + '\n</style>' );
}
if( state.className ) {
container.getElement().addClass( state.className );
}
if( state.bg ) {
container
.getElement()
.text( 'hey' )
.append( '<br/>' )
.append( $( '<button>' ).on( 'click', function() {
rotate( container )
} ).text( 'rotate header' ) )
.append( '<br/>' )
.append( $( '<button>' ).on( 'click', nexttheme ).text( 'next theme' ) );
}
} );
myLayout.init();
function getQueryParams() {
var params = {};
window.location.search.replace( /^\?/, '' ).split( '&' ).forEach( function( pair ) {
var parts = pair.split( '=' );
if( parts.length > 1 ) {
params[ decodeURIComponent( parts[ 0 ] ).toLowerCase() ] = decodeURIComponent( parts[ 1 ] );
}
} );
return params;
}
function createStandardConfig() {
return {
content: [
{
type: 'row',
content: [
{
width: 80,
type: 'column',
content: [
{
title: 'Fnts 100',
header: { show: 'bottom' },
type: 'component',
componentName: 'html',
},
{
type: 'row',
content: [
{
type: 'component',
title: 'Golden',
header: { show: 'left', dock:'docking', docked: true },
isClosable: false,
componentName: 'html',
width: 30,
componentState: { bg: 'golden_layout_spiral.png' }
},
{
title: 'Layout',
header: { show: 'right', popout: false, dock:'docking' },
type: 'component',
componentName: 'html',
componentState: { bg: 'golden_layout_text.png' }
}
]
},
{
type: 'stack',
content: [
{
type: 'component',
title: 'Acme, inc.',
componentName: 'html',
componentState: {
companyName: 'Stock X'
}
},
{
type: 'component',
title: 'LexCorp plc.',
componentName: 'html',
componentState: {
companyName: 'Stock Y'
}
},
{
type: 'component',
title: 'Springshield plc.',
componentName: 'html',
componentState: {
companyName: 'Stock Z'
}
}
]
}
]
},
{
width: 20,
type: 'column',
content: [
{
type: 'component',
title: 'Performance',
componentName: 'html'
},
{
height: 40,
type: 'component',
title: 'Market',
componentName: 'html'
}
]
}
]
}
]
};
}
function createResponsiveConfig() {
return {
settings: {
responsiveMode: 'always'
},
dimensions: {
minItemWidth: 250
},
content: [
{
type: 'row',
content: [
{
width: 30,
type: 'column',
content: [
{
title: 'Fnts 100',
type: 'component',
componentName: 'html',
},
{
type: 'row',
content: [
{
type: 'component',
title: 'Golden',
componentName: 'html',
width: 30,
componentState: { bg: 'golden_layout_spiral.png' }
}
]
},
{
type: 'stack',
content: [
{
type: 'component',
title: 'Acme, inc.',
componentName: 'html',
componentState: {
companyName: 'Stock X'
}
},
{
type: 'component',
title: 'LexCorp plc.',
componentName: 'html',
componentState: {
companyName: 'Stock Y'
}
},
{
type: 'component',
title: 'Springshield plc.',
componentName: 'html',
componentState: {
companyName: 'Stock Z'
}
}
]
}
]
},
{
width: 30,
title: 'Layout',
type: 'component',
componentName: 'html',
componentState: { bg: 'golden_layout_text.png' }
},
{
width: 20,
type: 'component',
title: 'Market',
componentName: 'html',
componentState: {
className: 'market-content',
style: [
'.market-content label {',
' margin-top: 10px;',
' display: block;',
' text-align: left;',
'}',
'.market-content input {',
' width: 250px;',
' border: 1px solid red',
'}'
],
html: [
'<label for="name">Name<label>',
'<input id="name" type="text"></input>'
]
}
},
{
width: 20,
type: 'column',
content: [
{
height: 20,
type: 'component',
title: 'Performance',
componentName: 'html'
},
{
height: 80,
type: 'component',
title: 'Profile',
componentName: 'html'
}
]
}
]
}
]
};
}
function createTabDropdownConfig() {
return {
settings: {
tabOverlapAllowance: 25,
reorderOnTabMenuClick: false,
tabControlOffset: 5
},
content: [
{
type: 'row',
content: [
{
width: 30,
type: 'column',
content: [
{
title: 'Fnts 100',
type: 'component',
componentName: 'html',
},
{
type: 'row',
content: [
{
type: 'component',
title: 'Golden',
componentName: 'html',
width: 30,
componentState: { bg: 'golden_layout_spiral.png' }
}
]
},
{
type: 'stack',
content: [
{
type: 'component',
title: 'Acme, inc.',
componentName: 'html',
componentState: {
companyName: 'Stock X'
}
},
{
type: 'component',
title: 'LexCorp plc.',
componentName: 'html',
componentState: {
companyName: 'Stock Y'
}
},
{
type: 'component',
title: 'Springshield plc.',
componentName: 'html',
componentState: {
companyName: 'Stock Z'
}
}
]
}
]
},
{
width: 20,
type: 'stack',
content: [
{
type: 'component',
title: 'Market',
componentName: 'html'
},
{
type: 'component',
title: 'Performance',
componentName: 'html'
},
{
type: 'component',
title: 'Trend',
componentName: 'html'
},
{
type: 'component',
title: 'Balance',
componentName: 'html'
},
{
type: 'component',
title: 'Budget',
componentName: 'html'
},
{
type: 'component',
title: 'Curve',
componentName: 'html'
},
{
type: 'component',
title: 'Standing',
componentName: 'html'
},
{
type: 'component',
title: 'Lasting',
componentName: 'html',
componentState: { bg: 'golden_layout_spiral.png' }
},
{
type: 'component',
title: 'Profile',
componentName: 'html'
}
]
},
{
width: 30,
title: 'Layout',
type: 'component',
componentName: 'html',
componentState: { bg: 'golden_layout_text.png' }
}
]
}
]
};
}
} );
|
var gulp = require('gulp');
var paths = require('../paths');
var watch = require('gulp-watch');
var jadeMarko = require('jade-marko');
// custom jade compilation to Marko
gulp.task('jade:marko', function() {
gulp.src(paths.jade)
.pipe(jadeMarko())
.pipe(gulp.dest('./' + paths.components))
});
gulp.task('jade:watch', function () {
gulp.watch(paths.jade, ['jade:marko']);
});
|
/*!
* scram-sha1.js - implementation of SCRAM-SHA1 mechanism
*
* Copyright (c) 2013 Matthew A. Miller
*
* 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 crypto = require("crypto"),
q = require("q"),
helpers = require("../lib/helpers.js"),
pbkdf2 = require("../lib/pbkdf2.js").pbkdf2;
// helpers
var calcClientKey = function(spwd) {
return crypto.createHmac("sha1", spwd).
update("Client Key").
digest("binary");
}
var calcClientSig = function(key, msg) {
// calculate StoredKey
key = crypto.createHash("sha1").
update(key).
digest("binary");
return crypto.createHmac("sha1", key).
update(msg).
digest("binary");
}
var calcClientProof = function(key, sig) {
return helpers.XOR(key, sig).toString("base64");
}
var calcServerKey = function(spwd) {
return crypto.createHmac("sha1", spwd).
update("Server Key").
digest("binary");
}
var calcServerSig = function(key, msg) {
return crypto.createHmac("sha1", key).
update(msg).
digest("binary");
}
// fields parsing
var PTN_FIELD = /^([^\=]+)\=(.+)$/;
var __parseServerFields = function(fields, input, expected, allowed) {
var unexpected = [],
empty = 0;
expected = expected.slice();
try {
input.forEach(function(f) {
if (!f) {
empty++;
return;
}
f = PTN_FIELD.exec(f);
if (!f) {
throw new Error("invalid field");
}
var pos;
pos = expected.indexOf(f[1]);
if (pos !== -1) {
expected.splice(pos, 1);
}
switch (f[1]) {
case "i": // iterations
fields["iterations"] = parseInt(f[2]);
break;
case "r": // nonce
fields["nonce"] = f[2];
break;
case "s": // salt
fields["salt"] = new Buffer(f[2], "base64").
toString("binary");
break;
case "v": // verification
fields["verification"] = new Buffer(f[2], "base64").
toString("binary");
break;
default:
unexpected.push(f[1]);
break;
}
});
} catch (ex) {
return q.reject(ex);
}
if (unexpected.length) {
var err = new Error("unexpected fields");
err.fields = unexpected;
return q.reject(err);
} else if (expected.length || empty > 0) {
var err = new Error("missing fields");
err.fields = expected;
return q.reject(err);
} else {
return q.resolve(fields);
}
};
var __parseClientFields = function(fields, input, expected, allowed) {
var unexpected = [];
expected = expected.slice();
allowed = (allowed || []).slice();
try {
input.forEach(function(f) {
if (!f) {
return;
}
f = PTN_FIELD.exec(f);
if (!f) {
throw new Error("invalid field");
}
var pos;
pos = expected.indexOf(f[1]);
if (pos !== -1) {
expected.splice(pos, 1);
}
pos = allowed.indexOf(f[1]);
if (pos !== -1) {
allowed.splice(pos, 1);
}
switch (f[1]) {
case "a": // authorization id
fields["authzid"] = f[2];
break;
case "c": // channel binding
fields["binding"] = f[2];
break;
case "n": // username
fields["username"] = f[2];
break;
case "p": // (client) proof
fields["proof"] = f[2];
break;
case "r": // nonce
fields["nonce"] = f[2];
break;
default:
unexpected.push(f[1]);
break;
}
});
} catch (ex) {
return q.reject(ex);
}
if (unexpected.length) {
var err = new Error("unexpected fields");
err.fields = unexpected;
return q.reject(err);
} else if (expected.length) {
var err = new Error("missing fields");
err.fields = expected;
return q.reject(err);
} else {
return q.resolve(fields);
}
};
/**
* client config properties:
* - username : string || function(config) { return string || promise }
* + if missing, CONTINUE
* - nonce : string || function(config, username) { return string || promise }
* + if missing, generate random then CONTINUE
* - authzid : string || function(config, username, salt, iterations) { return string || promise }
* + if missing, CONTINUE
* - password : string || function(config, username) { return string || promise }
* + if missing, CONTINUE
*/
exports.client = {
name: "SCRAM-SHA1",
stepStart: function(config) {
return helpers.promisedValue(config, "username").
then(function(usr) {
return q.all([
q.resolve(usr),
helpers.promisedValue(config, "nonce"),
helpers.promisedValue(config, "authzid", usr)
]);
}).
then(function(factors) {
var fields = config.authScram = {};
fields.username = factors[0];
fields.nonce = factors[1];
fields.authzid = factors[2];
fields.binding = [
"n",
(fields.authzid ? "a=" + fields.authzid : ""),
""
].join(",");
if (!fields.nonce) {
fields.nonce = crypto.randomBytes(24).
toString("base64");
}
var data = [
"n=" + fields.username,
"r=" + fields.nonce
].join(",");
fields.messages = [data];
data = fields.binding + data;
return q.resolve({
state:"auth",
data:data
});
});
},
stepAuth: function(config, input) {
input = input.toString("binary").
split(",");
var message = [];
var fields = config.authScram;
var nonce = fields.nonce;
delete fields.nonce;
return q.all([
__parseServerFields(fields, input, ["r", "s", "i"]),
helpers.promisedValue(config, "password", fields.username)
]).then(function(factors) {
var fields = factors[0];
var pwd = factors[1];
// store server-first-message
fields.messages.push(input.join(","));
// finish calculating binding
fields.binding = new Buffer(fields.binding, "binary").
toString("base64");
// validate server nonce starts with client nonce
if (fields.nonce.substring(0, nonce.length) !== nonce) {
return q.reject(new Error("nonce mismatch"));
}
// validate iterations is greater than 0
if (isNaN(fields.iterations) || fields.iterations <= 0) {
return q.reject(new Error("invalid iteration"));
}
// (start to) construct client-final-message
message.push("c=" + fields.binding);
message.push("r=" + fields.nonce);
// store client-final-message-without-proof
fields.messages.push(message.join(","));
// calculate SaltedPassword
return pbkdf2("sha1")(pwd, fields.salt, fields.iterations, 20);
}).then(function(spwd) {
// calculate ClientKey, ClientSig, ClientProof
var key, proof, sig;
key = calcClientKey(spwd);
sig = calcClientSig(key, fields.messages.join(","));
proof = calcClientProof(key, sig);
// store SaltedPassword for verify
fields.password = spwd;
message.push("p=" + proof);
return q.resolve({
state:"verify",
data:message.join(",")
});
});
},
stepVerify: function(config, input) {
input = input.toString("binary").
split(",");
var fields = config.authScram;
return __parseServerFields(fields, input, ["v"]).
then(function(fields) {
// Calculate ServerKey, ServerSignature
var key, sig;
key = calcServerKey(fields.password);
sig = calcServerSig(key, fields.messages.join(","));
if (fields.verification !== sig) {
return q.reject(new Error("verification failed"));
} else {
return q.resolve({
state:"complete",
username:fields.username,
authzid:fields.authzid || fields.username
});
}
});
}
};
/**
* server config properties:
* - username : string || function(config) { return string || promise }
* + if missing, CONTINUE
* + if present, input value MUST match (or FAIL)
* - nonce : string || function(config, username) { return string || promise }
* + if missing, generate random then CONTINUE
* - iterations : integer || function(config, username) { return integer || promise }
* + if missing, default to 4096 then CONTINUE
* - salt : string || function(config, username) { return string || promise }
* + if missing, generate random then CONTINUE
* !! NOTE: string is expected to be binary, NOT base64
* - derivedKey : string || function(config, username) { return string || promise }
* + if missing, then CONTINUE
* + if present, use instead of "password"
* - password : string || function(config, username) { return string || promise }
* + if missing, input value MUST be "" (or FAIL)
* + if present, input value MUST match (or FAIL)
* - authorize : function(config, username, authzid) { return boolean || promise }
* + if missing, then
* + if authzid missing, SUCCEED
* + if authzid matches username, SUCCEED
* + else FAIL
* + if present; true == SUCCEED, false == FAIL
*/
exports.server = {
name:"SCRAM-SHA1",
stepStart: function(config, input) {
// deconstruct input
input = input.toString("binary").
split(",");
// input[0] == binding request
if (input[0] !== "n") {
return q.reject(new Error("channel binding not supported"));
}
input.splice(0, 1);
var fields = config.authScram = {};
return q.all([
__parseClientFields(fields, input, ["n", "r"], ["a"]),
helpers.promisedValue(config, "username")
]).then(function(factors) {
var usr = fields.username,
cfgUsr = factors[1];
if (cfgUsr && usr !== cfgUsr) {
return q.reject(new Error("invalid username"));
}
return q.all([
helpers.promisedValue(config, "nonce", usr),
helpers.promisedValue(config, "iterations", usr),
helpers.promisedValue(config, "salt", usr)
]);
}).then(function(factors) {
var nonce = factors[0],
itrs = factors[1],
salt = factors[2];
// remember messages
fields.messages = [];
// recalculate client-first-message-bare
fields.messages.push([
"n=" + fields.username,
"r=" + fields.nonce
].join(","));
// calculate nonce/salt/iterations
if (!nonce) {
nonce = crypto.randomBytes(24).
toString("base64");
}
fields.nonce = fields.nonce + nonce;
if (!salt) {
salt = crypto.randomBytes(16).
toString("binary");
}
fields.salt = salt;
if (!itrs) {
itrs = 4096;
}
fields.iterations = itrs;
// pre-calculate binding
fields.binding = [
"n",
fields.authzid ? "a=" + fields.authzid : "",
""
].join(",");
fields.binding = new Buffer(fields.binding, "binary").
toString("base64");
// generate & remember server-first-message
var data = [
"r=" + fields.nonce,
"s=" + new Buffer(fields.salt, "binary").toString("base64"),
"i=" + fields.iterations
].join(",");
// remember server-first-message
fields.messages.push(data);
return q.resolve({
state:"auth",
data:data
});
});
},
stepAuth: function(config, input) {
var fields = config.authScram,
usr = fields.username;
input = input.toString("binary").
split(",");
var binding = fields.binding,
nonce = fields.nonce;
// remove pre-conceived notions
delete fields.binding;
delete fields.nonce;
return __parseClientFields(
fields,
input,
["c", "r", "p"]
).then(function(parsed) {
// validate binding/nonce
if (fields.binding !== binding) {
return q.reject(new Error("invalid binding"));
}
if (fields.nonce !== nonce) {
return q.reject(new Error("invalid nonce"));
}
// recalculate client-final-message-without-proof
fields.messages.push([
"c=" + fields.binding,
"r=" + fields.nonce
].join(","));
return helpers.promisedValue(config,
"derivedKey",
fields.username,
fields.salt,
fields.iterations);
}).then(function(salted) {
// calculate SaltedPassword
if (salted) {
return q.resolve(salted);
}
return helpers.promisedValue(
config,
"password",
fields.username
).then(function(pwd) {
return pbkdf2("sha1")(pwd,
fields.salt,
fields.iterations,
20);
});
}).then(function(spwd) {
// calculate proof
var key,
sig,
proof;
key = calcClientKey(spwd);
sig = calcClientSig(key, fields.messages.join(","));
proof = calcClientProof(key, sig);
if (proof !== fields.proof) {
return q.reject(new Error("not authorized"));
}
// calculate ServerSignature
key = calcServerKey(spwd);
sig = calcServerSig(key, fields.messages.join(","));
fields.verification = sig;
var authz = config.authorize;
if (typeof(authz) === "function") {
authz = authz(config, usr, fields.authzid);
} else if (authz == null) {
authz = !fields.authzid || (usr === fields.authzid);
} else {
return q.reject(new Error("bad internal authzid"));
}
return q.resolve(authz);
}).then(function(result) {
if (!result) {
return q.reject(new Error("not authorized"));
}
var data = "v=" + new Buffer(fields.verification, "binary").
toString("base64");
return q.resolve({
state:"complete",
data:data,
username:fields.username,
authzid:fields.authzid || fields.username
});
});
}
};
|
export { default } from 'ember-ui-kit/utils/microstate';
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Packet = mongoose.model('Packet'),
_ = require('lodash'),
fs = require('fs'),
path = require('path'),
replace = require('replace');
exports.gen = function(req, res){
var payload = req.body;
console.log(payload);
var statics = fs.readFileSync("./app/shell/main.sh", 'utf8')
if (Buffer.isBuffer(statics)) statics = statics.toString('utf8') ;
if (payload.shell) statics = statics.replace("<% packets.shell %>", payload.shell.join(" "))
if (payload.node){
var npm = fs.readFileSync("./app/shell/npm.sh", "utf8");
if (Buffer.isBuffer(npm)) npm = npm.toString('utf8') ;
npm = npm.replace("<% packets.npm %>", payload.node.join(" "))
statics = statics.replace("<% packets.node %>", npm)
}
if (payload.dpkg) {
var str = "";
for (var pkg in payload.dpkg) {
var dpkgtmpl = fs.readFileSync("./app/shell/dpkg.sh", "utf8");
if (Buffer.isBuffer(dpkgtmpl)) dpkgtmpl = dpkgtmpl.toString('utf8') ;
dpkgtmpl= dpkgtmpl
.replace("<% dpkg.name %>", payload.dpkg[pkg].name)
.replace("<% dpkg.link %>", payload.dpkg[pkg].link)
console.log(dpkgtmpl)
str += dpkgtmpl;
};
statics = statics.replace("<% packets.dpkg %>", str)
};
if (payload.other){
for(var thing in payload.other ) {
var other = fs.readFileSync("./app/shell/"+payload.other[thing].tmpl, "utf8");
if (Buffer.isBuffer(other)) other = other.toString('utf8') ;
statics = statics.replace("<% packet.other."+payload.other[thing].tmpl+" %>", other)
}
}
statics = statics.replace(/\<\% .* \%\>/g , "")
res.send(statics)
}
function temper(file , search, replace){
var regex = new RegExp("\<\% \w.\w \%\>", "gi");
console.log(1,2,file.match(regex))
file.replace(regex , replace);
console.info(file)
}
/**
* Create a Packet
*/
exports.create = function(req, res) {
var packet = new Packet(req.body);
packet.user = req.user;
packet.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(packet);
}
});
};
/**
* Show the current Packet
*/
exports.read = function(req, res) {
res.jsonp(req.packet);
};
/**
* Update a Packet
*/
exports.update = function(req, res) {
var packet = req.packet ;
packet = _.extend(packet , req.body);
packet.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(packet);
}
});
};
/**
* Delete an Packet
*/
exports.delete = function(req, res) {
var packet = req.packet ;
packet.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(packet);
}
});
};
/**
* List of Packets
*/
exports.list = function(req, res) {
Packet.find().sort('-created').populate('user', 'displayName').exec(function(err, packets) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(packets);
}
});
};
/**
* Packet middleware
*/
exports.packetByID = function(req, res, next, id) {
Packet.findById(id).populate('user', 'displayName').exec(function(err, packet) {
if (err) return next(err);
if (! packet) return next(new Error('Failed to load Packet ' + id));
req.packet = packet ;
next();
});
};
/**
* Packet authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.packet.user.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
next();
};
|
import React from 'react';
import cx from 'classnames';
import Player from '../player';
const { PropTypes, Component } = React;
class Progress extends Component {
static propTypes= {
buffered: PropTypes.number,
progress: PropTypes.number,
player: PropTypes.instanceOf(Player),
className: PropTypes.string,
}
static defaultProps = {
buffered: 0,
progress: 0,
}
shouldComponentUpdate(nextProps) {
let { buffered, progress } = this.props;
return (buffered !== nextProps.buffered || progress !== nextProps.progress);
}
handleSeek = (e) => {
e.preventDefault();
let { player } = this.props;
if (player && !isNaN(player.video.duration)) {
player.seek(e);
}
}
render() {
let { buffered, progress, className } = this.props;
if (progress < 0) {
progress = 0;
}
if (progress > 100) {
progress = 100;
}
let barStyle = {width: `${progress}%`};
let bufferStyle = {width: `${buffered}%`};
const classNames = cx('rp-progress', className);
return (
<div
className={classNames}
onClick={this.handleSeek}>
<div className="rp-progress-bar" style={barStyle}>
<div className="rp-progress-scrub" />
</div>
<div className="rp-progress-buffer" style={bufferStyle} />
</div>
);
}
}
export default Progress;
|
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("../chain"));
__export(require("./block"));
__export(require("./transaction"));
__export(require("./chain"));
__export(require("./handler"));
__export(require("./miner"));
var executor_1 = require("./executor");
exports.ValueTransactionExecutor = executor_1.ValueTransactionExecutor;
exports.ValueBlockExecutor = executor_1.ValueBlockExecutor;
|
$(document).ready(function() {
console.log($location);
$('body').css({'background-image': 'url("dist/img/'+$location+'.jpg")'});
//Ajax requesting weather information of cities
$.post("controllers/Weather_helper.php", {'post':$location}, function(data){
var formattedJson = $.parseJSON(data);
console.log(formattedJson);
var table = ($('table.weather_template').clone().removeClass('weather_template').attr('id', 'weather').show())[0];
var rows = document.createDocumentFragment();
var current = formattedJson[0]['item']['pubDate'];
$('#current').html(current);
for(var i in formattedJson){
var row = $('table.weather_template tr.template').clone().removeClass('template').addClass('worksheet').show();
row.find('td.date').html(formattedJson[i]['item']['forecast']['date']);
row.find('td.img img').attr('src','http://l.yimg.com/a/i/us/we/52/'+formattedJson[i]['item']['forecast']['code']+'.gif');
row.find('td.detail').html(formattedJson[i]['item']['forecast']['text']);
row.find('td.high_temp').html(formattedJson[i]['item']['forecast']['high']);
row.find('td.low_temp').html(formattedJson[i]['item']['forecast']['low']);
rows.appendChild(row[0]);
}
table.appendChild(rows);
$('#content').html(table);
});
}); |
(function($, _) {
$(function() {
var drawBoard = function(width, height) {
$('#all-fields').empty();
var cells = _.map(
_.range(height), function(row_i) {
var cells = _.map(
_.range(width), function(col_i) {
return '<div class="cell" id="' + (row_i * width + col_i) + '"></div>'
});
return '<div class="row">' + cells.join('') + '</div>'
}).join('');
$('#all-fields').html(cells);
};
drawBoard(50, 20);
var ws = new WebSocket('ws://' + window.location.host + '/client');
ws.onopen = function() { console.log('websocket opened'); };
ws.onclose = function() { console.log('websocket closed'); }
ws.onmessage = function(m) { console.log('websocket message: ' + m.data); };
})
})(jQuery, _);
|
const DrawCard = require('../../../drawcard.js');
class Right extends DrawCard {
constructor(owner, cardData) {
super(owner, cardData);
this.registerEvents(['onDefendersDeclared']);
}
setupCardAbilities(ability) {
this.persistentEffect({
condition: () => this.controller.findCardByName(this.controller.cardsInPlay, 'Left'),
match: this,
effect: [
ability.effects.modifyStrength(1),
ability.effects.addIcon('intrigue')
]
});
}
onDefendersDeclared(event, challenge) {
if(this.isBlank() || !challenge.isDefending(this)) {
return;
}
if(this.controller.findCardByName(this.controller.cardsInPlay, 'Left')) {
this.controller.standCard(this);
}
}
}
Right.code = '01184';
module.exports = Right;
|
/*jshint indent: 4, browser:true*/
/*global L*/
/*
* L.Control.TimeDimension: Leaflet control to manage a timeDimension
*/
L.UI = L.ui = L.UI || {};
L.UI.Knob = L.Draggable.extend({
options: {
className: 'knob',
step: 1,
rangeMin: 0,
rangeMax: 10
//minValue : null,
//maxValue : null
},
initialize: function(slider, options) {
L.setOptions(this, options);
this._element = L.DomUtil.create('div', this.options.className || 'knob', slider);
L.Draggable.prototype.initialize.call(this, this._element, this._element);
this._container = slider;
this.on('predrag', function() {
this._newPos.y = 0;
this._newPos.x = this._adjustX(this._newPos.x);
}, this);
this.on('dragstart', function() {
L.DomUtil.addClass(slider, 'dragging');
});
this.on('dragend', function() {
L.DomUtil.removeClass(slider, 'dragging');
});
L.DomEvent.on(this._element, 'dblclick', function(e) {
this.fire('dblclick', e);
}, this);
L.DomEvent.disableClickPropagation(this._element);
this.enable();
},
_getProjectionCoef: function() {
return (this.options.rangeMax - this.options.rangeMin) / (this._container.offsetWidth || this._container.style.width);
},
_update: function() {
this.setPosition(L.DomUtil.getPosition(this._element).x);
},
_adjustX: function(x) {
var value = this._toValue(x) || this.getMinValue();
return this._toX(this._adjustValue(value));
},
_adjustValue: function(value) {
value = Math.max(this.getMinValue(), Math.min(this.getMaxValue(), value)); //clamp value
value = value - this.options.rangeMin; //offsets to zero
//snap the value to the closet step
value = Math.round(value / this.options.step) * this.options.step;
value = value + this.options.rangeMin; //restore offset
value = Math.round(value * 100) / 100; // *100/100 to avoid floating point precision problems
return value;
},
_toX: function(value) {
var x = (value - this.options.rangeMin) / this._getProjectionCoef();
//console.log('toX', value, x);
return x;
},
_toValue: function(x) {
var v = x * this._getProjectionCoef() + this.options.rangeMin;
//console.log('toValue', x, v);
return v;
},
getMinValue: function() {
return this.options.minValue || this.options.rangeMin;
},
getMaxValue: function() {
return this.options.maxValue || this.options.rangeMax;
},
setStep: function(step) {
this.options.step = step;
this._update();
},
setPosition: function(x) {
L.DomUtil.setPosition(this._element,
L.point(this._adjustX(x), 0));
this.fire('positionchanged');
},
getPosition: function() {
return L.DomUtil.getPosition(this._element).x;
},
setValue: function(v) {
//console.log('slider value', v);
this.setPosition(this._toX(v));
},
getValue: function() {
return this._adjustValue(this._toValue(this.getPosition()));
}
});
/*
* L.Control.TimeDimension: Leaflet control to manage a timeDimension
*/
L.Control.TimeDimension = L.Control.extend({
options: {
styleNS: 'leaflet-control-timecontrol',
position: 'bottomleft',
title: 'Time Control',
backwardButton: true,
forwardButton: true,
playButton: true,
playReverseButton: false,
loopButton: false,
displayDate: true,
timeSlider: true,
timeSliderDragUpdate: false,
limitSliders: false,
limitMinimumRange: 5,
speedSlider: true,
minSpeed: 0.1,
maxSpeed: 10,
speedStep: 0.1,
timeSteps: 1,
autoPlay: false,
playerOptions: {
transitionTime: 1000
},
timeZones: ['UTC', 'Local']
},
initialize: function(options) {
L.setOptions(options);
L.Control.prototype.initialize.call(this, options);
this._timeZoneIndex = 0;
this._timeDimension = this.options.timeDimension || null;
},
onAdd: function(map) {
var container;
this._map = map;
if (!this._timeDimension && map.timeDimension) {
this._timeDimension = map.timeDimension;
}
this._initPlayer();
container = L.DomUtil.create('div', 'leaflet-bar leaflet-bar-horizontal leaflet-bar-timecontrol');
if (this.options.backwardButton) {
this._buttonBackward = this._createButton('Backward', container);
}
if (this.options.playReverseButton) {
this._buttonPlayReversePause = this._createButton('Play Reverse', container);
}
if (this.options.playButton) {
this._buttonPlayPause = this._createButton('Play', container);
}
if (this.options.forwardButton) {
this._buttonForward = this._createButton('Forward', container);
}
if (this.options.loopButton) {
this._buttonLoop = this._createButton('Loop', container);
}
if (this.options.displayDate) {
this._displayDate = this._createButton('Date', container);
}
if (this.options.timeSlider) {
this._sliderTime = this._createSliderTime(this.options.styleNS + ' timecontrol-slider timecontrol-dateslider', container);
}
if (this.options.speedSlider) {
this._sliderSpeed = this._createSliderSpeed(this.options.styleNS + ' timecontrol-slider timecontrol-speed', container);
}
this._steps = this.options.timeSteps || 1;
this._timeDimension.on('timeload', this._update, this);
this._timeDimension.on('timeload', this._onPlayerStateChange, this);
this._timeDimension.on('timeloading', this._onTimeLoading, this);
this._timeDimension.on('limitschanged availabletimeschanged', this._onTimeLimitsChanged, this);
L.DomEvent.disableClickPropagation(container);
return container;
},
addTo: function() {
//To be notified AFTER the component was added to the DOM
L.Control.prototype.addTo.apply(this, arguments);
this._onPlayerStateChange();
this._onTimeLimitsChanged();
this._update();
return this;
},
onRemove: function() {
this._player.off('play stop running loopchange speedchange', this._onPlayerStateChange, this);
this._player.off('waiting', this._onPlayerWaiting, this);
//this._player = null; keep it for later re-add
this._timeDimension.off('timeload', this._update, this);
this._timeDimension.off('timeload', this._onPlayerStateChange, this);
this._timeDimension.off('timeloading', this._onTimeLoading, this);
this._timeDimension.off('limitschanged availabletimeschanged', this._onTimeLimitsChanged, this);
},
_initPlayer: function() {
if (!this._player){ // in case of remove/add
if (this.options.player) {
this._player = this.options.player;
} else {
this._player = new L.TimeDimension.Player(this.options.playerOptions, this._timeDimension);
}
}
if (this.options.autoPlay) {
this._player.start(this._steps);
}
this._player.on('play stop running loopchange speedchange', this._onPlayerStateChange, this);
this._player.on('waiting', this._onPlayerWaiting, this);
this._onPlayerStateChange();
},
_onTimeLoading : function(data) {
if (data.time == this._timeDimension.getCurrentTime()) {
if (this._displayDate) {
L.DomUtil.addClass(this._displayDate, 'loading');
}
}
},
_onTimeLimitsChanged: function() {
var lowerIndex = this._timeDimension.getLowerLimitIndex(),
upperIndex = this._timeDimension.getUpperLimitIndex(),
max = this._timeDimension.getAvailableTimes().length - 1;
if (this._limitKnobs) {
this._limitKnobs[0].options.rangeMax = max;
this._limitKnobs[1].options.rangeMax = max;
this._limitKnobs[0].setValue(lowerIndex || 0);
this._limitKnobs[1].setValue(upperIndex || max);
}
if (this._sliderTime) {
this._sliderTime.options.rangeMax = max;
this._sliderTime._update();
}
},
_onPlayerWaiting: function(evt) {
if (this._buttonPlayPause && this._player.getSteps() > 0) {
L.DomUtil.addClass(this._buttonPlayPause, 'loading');
this._buttonPlayPause.innerHTML = this._getDisplayLoadingText(evt.available, evt.buffer);
}
if (this._buttonPlayReversePause && this._player.getSteps() < 0) {
L.DomUtil.addClass(this._buttonPlayReversePause, 'loading');
this._buttonPlayReversePause.innerHTML = this._getDisplayLoadingText(evt.available, evt.buffer);
}
},
_onPlayerStateChange: function() {
if (this._buttonPlayPause) {
if (this._player.isPlaying() && this._player.getSteps() > 0) {
L.DomUtil.addClass(this._buttonPlayPause, 'pause');
L.DomUtil.removeClass(this._buttonPlayPause, 'play');
} else {
L.DomUtil.removeClass(this._buttonPlayPause, 'pause');
L.DomUtil.addClass(this._buttonPlayPause, 'play');
}
if (this._player.isWaiting() && this._player.getSteps() > 0) {
L.DomUtil.addClass(this._buttonPlayPause, 'loading');
} else {
this._buttonPlayPause.innerHTML = '';
L.DomUtil.removeClass(this._buttonPlayPause, 'loading');
}
}
if (this._buttonPlayReversePause) {
if (this._player.isPlaying() && this._player.getSteps() < 0) {
L.DomUtil.addClass(this._buttonPlayReversePause, 'pause');
} else {
L.DomUtil.removeClass(this._buttonPlayReversePause, 'pause');
}
if (this._player.isWaiting() && this._player.getSteps() < 0) {
L.DomUtil.addClass(this._buttonPlayReversePause, 'loading');
} else {
this._buttonPlayReversePause.innerHTML = '';
L.DomUtil.removeClass(this._buttonPlayReversePause, 'loading');
}
}
if (this._buttonLoop) {
if (this._player.isLooped()) {
L.DomUtil.addClass(this._buttonLoop, 'looped');
} else {
L.DomUtil.removeClass(this._buttonLoop, 'looped');
}
}
if (this._sliderSpeed && !this._draggingSpeed) {
var speed = this._player.getTransitionTime() || 1000;//transitionTime
speed = Math.round(10000 / speed) /10; // 1s / transition
this._sliderSpeed.setValue(speed);
}
},
_update: function() {
if (!this._timeDimension) {
return;
}
if (this._timeDimension.getCurrentTimeIndex() >= 0) {
var date = new Date(this._timeDimension.getCurrentTime());
if (this._displayDate) {
L.DomUtil.removeClass(this._displayDate, 'loading');
this._displayDate.innerHTML = this._getDisplayDateFormat(date);
}
if (this._sliderTime && !this._slidingTimeSlider) {
this._sliderTime.setValue(this._timeDimension.getCurrentTimeIndex());
}
} else {
if (this._displayDate) {
this._displayDate.innerHTML = this._getDisplayNoTimeError();
}
}
},
_createButton: function(title, container) {
var link = L.DomUtil.create('a', this.options.styleNS + ' timecontrol-' + title.toLowerCase(), container);
link.href = '#';
link.title = title;
L.DomEvent
.addListener(link, 'click', L.DomEvent.stopPropagation)
.addListener(link, 'click', L.DomEvent.preventDefault)
.addListener(link, 'click', this['_button' + title.replace(/ /i, '') + 'Clicked'], this);
return link;
},
_createSliderTime: function(className, container) {
var sliderContainer,
sliderbar,
max,
knob, limits;
sliderContainer = L.DomUtil.create('div', className, container);
/*L.DomEvent
.addListener(sliderContainer, 'click', L.DomEvent.stopPropagation)
.addListener(sliderContainer, 'click', L.DomEvent.preventDefault);*/
sliderbar = L.DomUtil.create('div', 'slider', sliderContainer);
max = this._timeDimension.getAvailableTimes().length - 1;
if (this.options.limitSliders) {
limits = this._limitKnobs = this._createLimitKnobs(sliderbar);
}
knob = new L.UI.Knob(sliderbar, {
className: 'knob main',
rangeMin: 0,
rangeMax: max
});
knob.on('dragend', function(e) {
var value = e.target.getValue();
this._sliderTimeValueChanged(value);
this._slidingTimeSlider = false;
}, this);
knob.on('drag', function(e) {
this._slidingTimeSlider = true;
var time = this._timeDimension.getAvailableTimes()[e.target.getValue()];
if (time) {
var date = new Date(time);
if (this._displayDate) {
this._displayDate.innerHTML = this._getDisplayDateFormat(date);
}
if (this.options.timeSliderDragUpdate){
this._sliderTimeValueChanged(e.target.getValue());
}
}
}, this);
knob.on('predrag', function() {
var minPosition, maxPosition;
if (limits) {
//limits the position between lower and upper knobs
minPosition = limits[0].getPosition();
maxPosition = limits[1].getPosition();
if (this._newPos.x < minPosition) {
this._newPos.x = minPosition;
}
if (this._newPos.x > maxPosition) {
this._newPos.x = maxPosition;
}
}
}, knob);
L.DomEvent.on(sliderbar, 'click', function(e) {
if (L.DomUtil.hasClass(e.target, 'knob')) {
return; //prevent value changes on drag release
}
var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
x = L.DomEvent.getMousePosition(first, sliderbar).x;
if (limits) { // limits exits
if (limits[0].getPosition() <= x && x <= limits[1].getPosition()) {
knob.setPosition(x);
this._sliderTimeValueChanged(knob.getValue());
}
} else {
knob.setPosition(x);
this._sliderTimeValueChanged(knob.getValue());
}
}, this);
knob.setPosition(0);
return knob;
},
_createLimitKnobs: function(sliderbar) {
L.DomUtil.addClass(sliderbar, 'has-limits');
var max = this._timeDimension.getAvailableTimes().length - 1;
var rangeBar = L.DomUtil.create('div', 'range', sliderbar);
var lknob = new L.UI.Knob(sliderbar, {
className: 'knob lower',
rangeMin: 0,
rangeMax: max
});
var uknob = new L.UI.Knob(sliderbar, {
className: 'knob upper',
rangeMin: 0,
rangeMax: max
});
L.DomUtil.setPosition(rangeBar, 0);
lknob.setPosition(0);
uknob.setPosition(max);
//Add listeners for value changes
lknob.on('dragend', function(e) {
var value = e.target.getValue();
this._sliderLimitsValueChanged(value, uknob.getValue());
}, this);
uknob.on('dragend', function(e) {
var value = e.target.getValue();
this._sliderLimitsValueChanged(lknob.getValue(), value);
}, this);
//Add listeners to position the range bar
lknob.on('drag positionchanged', function() {
L.DomUtil.setPosition(rangeBar, L.point(lknob.getPosition(), 0));
rangeBar.style.width = uknob.getPosition() - lknob.getPosition() + 'px';
}, this);
uknob.on('drag positionchanged', function() {
rangeBar.style.width = uknob.getPosition() - lknob.getPosition() + 'px';
}, this);
//Add listeners to prevent overlaps
uknob.on('predrag', function() {
//bond upper to lower
var lowerPosition = lknob._toX(lknob.getValue() + this.options.limitMinimumRange);
if (uknob._newPos.x <= lowerPosition) {
uknob._newPos.x = lowerPosition;
}
}, this);
lknob.on('predrag', function() {
//bond lower to upper
var upperPosition = uknob._toX(uknob.getValue() - this.options.limitMinimumRange);
if (lknob._newPos.x >= upperPosition) {
lknob._newPos.x = upperPosition;
}
}, this);
lknob.on('dblclick', function() {
this._timeDimension.setLowerLimitIndex(0);
}, this);
uknob.on('dblclick', function() {
this._timeDimension.setUpperLimitIndex(this._timeDimension.getAvailableTimes().length - 1);
}, this);
return [lknob, uknob];
},
_createSliderSpeed: function(className, container) {
var sliderContainer = L.DomUtil.create('div', className, container);
/* L.DomEvent
.addListener(sliderContainer, 'click', L.DomEvent.stopPropagation)
.addListener(sliderContainer, 'click', L.DomEvent.preventDefault);
*/
var speedLabel = L.DomUtil.create('span', 'speed', sliderContainer);
var sliderbar = L.DomUtil.create('div', 'slider', sliderContainer);
var initialSpeed = Math.round(10000 / (this._player.getTransitionTime() || 1000)) / 10;
speedLabel.innerHTML = this._getDisplaySpeed(initialSpeed);
var knob = new L.UI.Knob(sliderbar, {
step: this.options.speedStep,
rangeMin: this.options.minSpeed,
rangeMax: this.options.maxSpeed
});
knob.on('dragend', function(e) {
var value = e.target.getValue();
this._draggingSpeed = false;
speedLabel.innerHTML = this._getDisplaySpeed(value);
this._sliderSpeedValueChanged(value);
}, this);
knob.on('drag', function(e) {
this._draggingSpeed = true;
speedLabel.innerHTML = this._getDisplaySpeed(e.target.getValue());
}, this);
knob.on('positionchanged', function (e) {
speedLabel.innerHTML = this._getDisplaySpeed(e.target.getValue());
}, this);
L.DomEvent.on(sliderbar, 'click', function(e) {
if (e.target === knob._element) {
return; //prevent value changes on drag release
}
var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
x = L.DomEvent.getMousePosition(first, sliderbar).x;
knob.setPosition(x);
speedLabel.innerHTML = this._getDisplaySpeed(knob.getValue());
this._sliderSpeedValueChanged(knob.getValue());
}, this);
return knob;
},
_buttonBackwardClicked: function() {
this._timeDimension.previousTime(this._steps);
},
_buttonForwardClicked: function() {
this._timeDimension.nextTime(this._steps);
},
_buttonLoopClicked: function() {
this._player.setLooped(!this._player.isLooped());
},
_buttonPlayClicked: function() {
if (this._player.isPlaying()) {
this._player.stop();
} else {
this._player.start(this._steps);
}
},
_buttonPlayReverseClicked: function() {
if (this._player.isPlaying()) {
this._player.stop();
} else {
this._player.start(this._steps * (-1));
}
},
_buttonDateClicked: function(){
this._switchTimeZone();
},
_sliderTimeValueChanged: function(newValue) {
this._timeDimension.setCurrentTimeIndex(newValue);
},
_sliderLimitsValueChanged: function(lowerLimit, upperLimit) {
this._timeDimension.setLowerLimitIndex(lowerLimit);
this._timeDimension.setUpperLimitIndex(upperLimit);
},
_sliderSpeedValueChanged: function(newValue) {
this._player.setTransitionTime(1000 / newValue);
},
_getCurrentTimeZone: function() {
return this.options.timeZones[this._timeZoneIndex];
},
_switchTimeZone: function() {
if (this._getCurrentTimeZone().toLowerCase() == 'utc') {
L.DomUtil.removeClass(this._displayDate, 'utc');
}
this._timeZoneIndex = (this._timeZoneIndex + 1) % this.options.timeZones.length;
var timeZone = this._getCurrentTimeZone();
if (timeZone.toLowerCase() == 'utc') {
L.DomUtil.addClass(this._displayDate, 'utc');
this._displayDate.title = 'UTC Time';
} else if (timeZone.toLowerCase() == 'local') {
this._displayDate.title = 'Local Time';
} else {
this._displayDate.title = timeZone;
}
this._update();
},
_getDisplayDateFormat: function(date) {
var timeZone = this._getCurrentTimeZone();
if (timeZone.toLowerCase() == 'utc') {
return date.toISOString();
}
if (timeZone.toLowerCase() == 'local') {
return date.toLocaleString();
}
return date.toLocaleString([], {timeZone: timeZone, timeZoneName: "short"});
},
_getDisplaySpeed: function(fps) {
return fps + 'fps';
},
_getDisplayLoadingText: function(available, buffer) {
return '<span>' + Math.floor(available / buffer * 100) + '%</span>';
},
_getDisplayNoTimeError: function() {
return 'Time not available';
}
});
L.Map.addInitHook(function() {
if (this.options.timeDimensionControl) {
this.timeDimensionControl = L.control.timeDimension(this.options.timeDimensionControlOptions || {});
this.addControl(this.timeDimensionControl);
}
});
L.control.timeDimension = function(options) {
return new L.Control.TimeDimension(options);
};
|
/*!
* JSMovieclip V1.0 jQuery version
* https://github.com/jeremypetrequin/jsMovieclip
* Copyright 2013 Jeremy Petrequin
* Released under the MIT license
* https://github.com/jeremypetrequin/jsMovieclip/blob/master/MIT-license.txt
*/
(function() {
"use strict";
function JSMovieclip(elmts, params) {
if(!elmts) {return this;}
var t = this,
str = elmts.toString();
t.elmts = str === '[object Array]' || str === '[object NodeList]' || str === '[object HTMLCollection]' || str === '[object Object]' ? elmts : [elmts];
str = null;
t.playing = false;
t.framerate = params.framerate || 25;
t.frames = [];
t.loop = false;
t.elmtsLength = t.elmts.length;
t.stopCallback = params.stopCallback || null;
t.firstFrame = 1;
t.lastFrame = 1;
t._label = '';
t._idx = 0;
t._timer = null;
t._tmpFrames = [];
t._way = 1;
t._framesNumber = params.frames_number || 0;
t.updateFrames(params.frames, params.direction, params.width, params.height, params.frames_number);
}
//you can extend and override what you want
JSMovieclip.prototype = {
//"protected" method
_render : function() {
var i = this.elmtsLength, t = this;
while(i--) { this.elmts[i].style.backgroundPosition = this._tmpFrames[this._idx]; }
if(t.playing) {
if(t._idx >= t.lastFrame -1) {
if(!t.loop) {
t.stop();
return;
}
t._idx = t.firstFrame - 1;
} else {
t._idx++;
}
}
},
_enterFrame : function() {
var t = this;
t._render.call(t);
if(t.playing){
t._timer = setTimeout(function() {
t._enterFrame.call(t);
}, 1000/t.framerate);
}
},
_calculateFrames : function() {
this._tmpFrames = [];
if(this._way === 1) {
this._tmpFrames = this.frames;
} else {
var i = this.frames.length;
while(i--) {
this._tmpFrames.push(this.frames[i]);
}
}
this._framesNumber = this.frames.length;
return this.clearLoopBetween();
},
/**
* concat each frame as a string, to better performance
*/
_cacheFrames : function() {
var frames = this.frames,
i = frames.length;
this.frames = [];
while(i--) {this.frames[i] = '-'+frames[i].x+'px -'+frames[i].y+'px'; }
return this;
},
//public method
/**
* @param frames array (optional)
* @param direction string (h for horyzontal of v for vertical) (optional)
* @param width float (in case of a horizontal sprite) (optional)
* @param height float height of a frame (in case of a vertical sprite)(optional)
* @param nbframe float number of frames (optional)
*/
updateFrames : function(frames, direction, width, height, nbframe) {
if(frames) {
this.frames = frames;
return this._cacheFrames()._calculateFrames();
}
//some error reporting
if(!frames && !direction) {throw "JSMovieclip need at least frames array or a direction "; }
if(direction === 'v' && !height) {throw "If you want to use a vertical sprite, JSMoviclip need a height"; }
if(direction === 'h' && !width) {throw "If you want to use a horizontal sprite, JSMoviclip need a width"; }
if(!nbframe) {throw "If you want to use a horizontal of vertical sprite, JSMoviclip need a number of frame"; }
var i = 0;
for(;i<nbframe;i++) {
this.frames.push({
x : (direction === 'h' ? i * width : 0),
y : (direction === 'v' ? i * height : 0)
});
}
i=null;
return this._cacheFrames()._calculateFrames();
},
/**
* @return way (int) of playing : 1 normal way, -1 inverted way
*/
getWay : function() {
return this._way;
},
/**
* change the way of playing
* @param way int : 1 normal way, -1 inverted way
* @return current JSMovieclip object
*/
changeWay : function(way, keepFrame) {
if(way === this._way) {return this;}
keepFrame = !!keepFrame;
if(keepFrame === true) {
this._idx = this._framesNumber - this._idx;
}
this._way = way;
return this._calculateFrames();
},
clearLoopBetween : function() {
this.firstFrame = 1;
this.lastFrame = this._framesNumber;
return this;
},
loopBetween : function(firstFrame, lastFrame) {
if(firstFrame >= lastFrame) {firstFrame = lastFrame;throw 'Firstframe and lastframe are equals or inverted';}
this.firstFrame = Math.max(firstFrame, 1);
this.lastFrame = Math.min(lastFrame, this._framesNumber);
if(this._idx < this.firstFrame - 1 || this._idx > this.lastFrame -1) {this._idx = this.firstFrame -1;}
return this;
},
currentFrame : function() {
return this._idx + 1;
},
prevFrame : function() {
var current = this.currentFrame();
return this.gotoAndStop( current <= this.firstFrame ? this.lastFrame : current -1);
},
nextFrame : function() {
var current = this.currentFrame();
return this.gotoAndStop(current >= this.lastFrame ? 1 : current +1);
},
toggle : function(loop) {
return !this.playing ? this.play(loop) : this.stop();
},
play : function(loop) {
if(this.playing) {return this;}
if(this._idx === this.lastFrame-1) { this._idx = this.firstFrame-1; }
this.playing = true;
this.loop = !!loop;
this._enterFrame();
return this;
},
stop : function() {
this.playing = false;
if(this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
if(this.stopCallback) { this.stopCallback();}
return this;
},
gotoAndPlay : function(frame, loop) {
this._idx = Math.min(Math.max(frame, this.firstFrame), this.lastFrame) -1;
return this.play(loop);
},
gotoAndStop : function(frame) {
this._idx = Math.min(Math.max(frame, this.firstFrame), this.lastFrame) -1;
this.loop = false;
this.playing = false;
this._enterFrame();
return this;
}
};
/**
* jQuery plugin wrapper
*/
$.fn.JSMovieclip= function(options) {
return this.length ? this.data('JSMovieclip', new JSMovieclip(this, options)) : null;
};
})(); |
const path = require('path');
const shell = require('shelljs');
const chalk = require('chalk');
const packageJson = require('../package.json');
shell.echo(chalk.bold(`${packageJson.name}@${packageJson.version}`));
shell.echo(chalk.gray('\n=> Clean dist.'));
shell.rm('-rf', 'dist');
const babel = path.join(__dirname, '..', 'node_modules', '.bin', 'babel');
const args = [
'--ignore tests,__tests__,test.js,stories/,story.jsx',
'./src --out-dir ./lib',
'--copy-files',
].join(' ');
const command = `${babel} ${args}`;
shell.echo(chalk.gray('\n=> Transpiling "src" into ES5 ...\n'));
shell.echo(chalk.gray(command));
shell.echo('');
const code = shell.exec(command).code;
if (code === 0) {
shell.echo(chalk.gray('\n=> Transpiling completed.'));
} else {
shell.exit(code);
}
const licence = path.join(__dirname, '..', 'LICENSE');
shell.echo(chalk.gray('\n=> Copy LICENSE.'));
shell.cp(licence, './'); |
'use strict';
// This demonstrates the difference between a synchronous and an asynchronous function call in NodeJS.
var fs = require('fs');
var greet = fs.readFileSync(__dirname + '/50-greet.txt', 'utf8'); // Synchronous file read. I.e. waits til file
// is read before moving on to next line of
console.log(greet); // code. Now outputs what it read.
var greet2 = fs.readFile(__dirname + '/50-greet.txt', 'utf8', function(err, data) { // Asynchronous file read. Sends libuv out to
console.log(data); // get data from the file, while it moves on
}); // to the next instruction in the script
// before logging the data to the screen.
console.log('Done!'); // NOTE that 'Done!' is logged to the screen
// BEFORE the data from the async call is.
|
import 'whatwg-fetch';
const localStorageMock = (function () {
let store = {};
return {
getItem (key) {
return store[key];
},
setItem (key, value) {
store[key] = value.toString();
},
clear () {
store = {};
}
};
})();
global.__DEV__ = false;
global.localStorage = localStorageMock;
global.requestAnimationFrame = cb => process.nextTick(cb);
global.require = require;
// Don't console log real logs that start with a tag (eg. [db] ...). It's annoying
const log = console.log;
global.console.log = (...args) => {
if (!(typeof args[0] === 'string' && args[0][0] === '[')) {
log(...args);
}
};
|
Hyperspace.prototype.addOwnShip = function(data) {
// Create the ship that the current player drives. It differs from all other
// ships in that it has an update loop (called every tick) that takes in
// directions from the keyboard.
var extra = {
ownShip: true,
pressed: {
forward: false,
down: false,
left: false,
right: false,
},
lastEventId: 0,
lastProjectileId: 0,
// Movement is based off of this SO article which basically reminded me how
// vectors work: http://stackoverflow.com/a/3639025/1063
update: function(elapsedMillis) {
this.checkInputs();
if (this.game.clientUpdatesEnabled) {
this.applyPhysics(elapsedMillis);
}
},
checkInputs: function() {
var last_pressed = {};
for (i in this.pressed) {
last_pressed[i] = this.pressed[i];
}
// Key pressed booleans
this.pressed["forward"] =
this.c.inputter.isDown(this.c.inputter.UP_ARROW) ||
this.c.inputter.isDown(this.c.inputter.W) ||
this.c.inputter.isDown(this.c.inputter.COMMA);
this.pressed["down"] =
this.c.inputter.isDown(this.c.inputter.DOWN_ARROW) ||
this.c.inputter.isDown(this.c.inputter.S) ||
this.c.inputter.isDown(this.c.inputter.O);
this.pressed["left"] =
this.c.inputter.isDown(this.c.inputter.LEFT_ARROW) ||
this.c.inputter.isDown(this.c.inputter.A);
this.pressed["right"] =
this.c.inputter.isDown(this.c.inputter.RIGHT_ARROW) ||
this.c.inputter.isDown(this.c.inputter.D) ||
this.c.inputter.isDown(this.c.inputter.E);
// Send server events for key press changes (and update local state).
if (last_pressed['forward'] !== this.pressed['forward']) {
var direction = this.pressed['forward'] ? 1 : 0;
this.acceleration = direction;
this.send("changeAcceleration", { direction: direction });
}
if (last_pressed['left'] !== this.pressed['left'] || last_pressed['right'] !== this.pressed['right']) {
var direction = (this.pressed['left'] ? -1 : (this.pressed['right'] ? 1 : 0));
this.rotation = direction;
this.send("changeRotation", { direction: direction });
}
// Fire the lasers! Say Pew Pew Pew every time you press the space bar
// please.
if (this.c.inputter.isPressed(this.c.inputter.SPACE)) {
var projectileId = this.nextProjectileId();
if (this.game.clientUpdatesEnabled) {
var projectile = this.game.addProjectile({
id: projectileId,
alive: true,
center: { x:this.center.x, y:this.center.y },
velocity: utils.addVectors(this.velocity, utils.angleAndSpeedToVector(this.angle, this.game.constants.projectile_speed)),
angle: this.angle,
owner: this.id,
});
// Send an event (a cause of a thing) that describes what just happened.
this.send("fire", {
projectileId: projectile.id,
created: projectile.created,
});
} else {
// Send an event (a cause of a thing) that describes what just happened.
this.send("fire", {
projectileId: projectileId,
created: this.conn.now(),
});
}
}
},
send: function(type, data) {
var eventId = ++this.lastEventId;
data.eventId = eventId;
this.conn.send(type, data);
},
nextProjectileId: function() {
this.lastProjectileId++;
return this.id + "." + this.lastProjectileId;
},
};
for (k in extra) { data[k] = extra[k]; }
var ship = this.c.entities.create(Ship, data);
this.ships[data.id] = ship;
return ship;
};
Hyperspace.prototype.addEnemyShip = function(data) {
var extra = {
ownShip: false,
update: function(elapsedMillis) {
if (this.game.clientUpdatesEnabled) {
this.applyPhysics(elapsedMillis);
}
},
};
for (k in extra) { data[k] = extra[k]; }
var ship = this.c.entities.create(Ship, data);
ship.indicator = this.c.entities.create(ShipIndicator, { ship: ship });
this.ships[data.id] = ship;
return ship;
};
// This defines the basic ship shape as a series of verices for a path to
// follow.
var ship_shape = [
{ x: 0, y: -5},
{ x: -5, y: 5},
{ x: 0, y: 2},
{ x: 5, y: 5},
{ x: 0, y: -5},
]
// The actual ship entity. One of these will be created for every single player
// in the game. Please set the color.
var Ship = function(game, settings) {
this.game = game;
this.c = game.c;
this.conn = game.conn;
for (var i in settings) {
this[i] = settings[i];
}
// This is the size of the ship.
this.scale = 1.5;
this.size = { x: 10 * this.scale, y: 10 * this.scale }
// This is run every tick to draw the ship.
this.draw = function(ctx) {
if (!this.c.renderer.onScreen(this)) {
return;
}
// The color of the outline of the ship.
ctx.strokeStyle = settings.color;
ctx.fillStyle = increaseBrightness(settings.color, 10);
// Draw the actual ship body.
ctx.beginPath();
for (i in ship_shape) {
var v = ship_shape[i];
var x = (v.x * this.scale) + this.center.x;
var y = (v.y * this.scale) + this.center.y;
ctx.lineTo(x, y);
}
ctx.stroke();
ctx.fill();
};
};
var ShipIndicator = function(game, settings) {
this.c = game.c;
for (var i in settings) {
this[i] = settings[i];
}
this.zindex = -2;
this.width = 3 + (Math.random() * 4);
this.size = {x: this.width, y: this.width};
this.update = function() {
};
this.draw = function(ctx) {
// Draw indication of off-screen ship
if (this.c.renderer.onScreen(this.ship)) {
return
}
var viewSize = this.c.renderer.getViewSize();
var viewCenter = this.c.renderer.getViewCenter();
// var viewCenter = this.game.ships[this.game.playerId].center;
var halfWidth = viewSize.x / 2;
var halfHeight = viewSize.y / 2
var viewTopLeftAngle = utils.vectorToAngle({ x: -halfWidth, y: -halfHeight });
var viewTopRightAngle = utils.vectorToAngle({ x: halfWidth, y: -halfHeight });
var viewBottomLeftAngle = utils.vectorToAngle({ x: -halfWidth, y: halfHeight });
var viewBottomRightAngle = utils.vectorToAngle({ x: halfWidth, y: halfHeight });
var vecToEnemy = {
x: this.ship.center.x - viewCenter.x,
y: this.ship.center.y - viewCenter.y,
};
var angle = utils.vectorToAngle(vecToEnemy);
var dx, dy;
if (angle >= viewTopLeftAngle || angle <= viewTopRightAngle) {
dy = -halfHeight;
dx = (halfHeight) * Math.tan(angle);
} else if (angle >= viewTopRightAngle && angle <= viewBottomRightAngle) {
dx = halfWidth;
dy = -((halfWidth) * Math.tan(Math.PI/2 - angle));
} else if (angle >= viewBottomRightAngle && angle <= viewBottomLeftAngle) {
dy = halfHeight;
dx = (halfHeight) * Math.tan(Math.PI - angle);
} else {
dx = -halfWidth;
dy = (halfWidth) * Math.tan(3*Math.PI/2 - angle);
}
var x = viewCenter.x + Math.round(dx);
var y = viewCenter.y + Math.round(dy);
// draw offscreen indicator
ctx.fillStyle = this.ship.color;
ctx.beginPath();
ctx.moveTo(x-8, y);
ctx.lineTo(x, y-8);
ctx.lineTo(x+8, y);
ctx.lineTo(x, y+8);
ctx.lineTo(x-8, y);
ctx.fill();
};
};
Ship.prototype.applyPhysics = function(elapsedMillis) {
var elapsed = elapsedMillis / 1000;
// Apply rotation
if (this.rotation != 0) {
this.angle += this.game.constants.ship_rotation * elapsed * this.rotation;
while (this.angle < 0) { this.angle += 360 }
while (this.angle >= 360) { this.angle -= 360 }
this.angle = utils.roundToPlaces(this.angle, 1);
}
var newVelocity = { x: this.velocity.x, y: this.velocity.y };
// Apply acceleration
if (this.acceleration != 0) {
var vector = utils.angleToVector(this.angle);
newVelocity.x += vector.x * this.game.constants.ship_acceleration * elapsed;
newVelocity.y += vector.y * this.game.constants.ship_acceleration * elapsed;
}
// Apply drag
newVelocity.x += this.velocity.x * this.game.constants.ship_drag * elapsed;
newVelocity.y += this.velocity.y * this.game.constants.ship_drag * elapsed;
// Apply velocity
this.velocity = newVelocity;
this.center.x = utils.roundToPlaces(this.center.x + this.velocity.x * elapsed, 1);
this.center.y = utils.roundToPlaces(this.center.y + this.velocity.y * elapsed, 1);
// This keeps the player's ship always in the center.
if (this.ownShip && this.alive) {
this.c.renderer.setViewCenter(this.center);
}
};
|
'use strict';
var AV = require('leanengine');
var chalk = require('chalk');
var fs = require('fs');
// 兼容Promise/A+
AV.Promise.setPromisesAPlusCompliant(true);
var APP_ID = process.env.LC_APP_ID;
var APP_KEY = process.env.LC_APP_KEY;
var MASTER_KEY = process.env.LC_APP_MASTER_KEY;
if (!(APP_ID && APP_KEY && MASTER_KEY)) {
var appKeys = getAppKeys();
APP_ID = appKeys.LC_APP_ID;
APP_KEY = appKeys.LC_APP_KEY;
MASTER_KEY = appKeys.LC_APP_MASTER_KEY;
}
AV.initialize(APP_ID, APP_KEY, MASTER_KEY);
function getAppKeys() {
var keysPath = './../.avoscloud/keys' + (process.env.NODE_ENV === 'test' ? '-test' : '') + '.json';
try {
return require(keysPath);
} catch (e) {
try {
fs.mkdirSync('.avoscloud');
} catch (e) {}
var appKeysSample = {
LC_APP_ID: '[App ID]',
LC_APP_KEY: '[App Key]',
LC_APP_MASTER_KEY: '[Master Key]'
};
fs.writeFileSync('.avoscloud/keys.sample.json', JSON.stringify(appKeysSample));
console.error(chalk.red('找不到leancloude相关的key。请到项目后台【设置-应用Key】将相应的key写入【' + keysPath + '】,参考【.avoscloud/keys.sample.json】。'));
throw e;
}
}
|
var chai = require('chai');
chai.use(require('chai-change'));
var expect = require("chai").expect;
var should = require('chai').should;
describe("SmlGetProfilePackResponse", function() {
var SmlGetProfilePackResponse = require("../../lib/messages/SmlGetProfilePackResponse");
var Constants = require('../../lib/Constants');
describe("SmlGetProfilePackResponse()", function(){
});
describe("write()", function(){
});
describe("getSize()", function(){
});
describe("parse()", function(){
});
}); |
import version from './version';
import Thread from './thread';
import WorkerBroker from './worker_broker';
const LEVELS = {
silent: -1,
error: 0,
warn: 1,
info: 2,
debug: 3,
trace: 4
};
const methods = {};
function methodForLevel (level) {
if (Thread.is_main) {
methods[level] = methods[level] || (console[level] ? console[level] : console.log).bind(console);
return methods[level];
}
}
export default function log (msg_level, ...msg) {
if (LEVELS[msg_level] <= LEVELS[log.level]) {
if (Thread.is_worker) {
// Proxy to main thread
WorkerBroker.postMessage('_logProxy', msg_level, ...msg);
}
else {
let logger = methodForLevel(msg_level);
// Write to console (on main thread)
if (msg.length > 1) {
logger(`Tangram ${version} [${msg_level}]: ${msg[0]}`, ...msg.slice(1));
}
else {
logger(`Tangram ${version} [${msg_level}]: ${msg[0]}`);
}
}
}
}
log.level = 'info';
log.workers = null;
log.setLevel = function (level) {
log.level = level;
if (Thread.is_main && Array.isArray(log.workers)) {
WorkerBroker.postMessage(log.workers, '_logSetLevelProxy', level);
}
};
if (Thread.is_main) {
log.setWorkers = function (workers) {
log.workers = workers;
};
}
WorkerBroker.addTarget('_logProxy', log); // proxy log messages from worker to main thread
WorkerBroker.addTarget('_logSetLevelProxy', log.setLevel); // proxy log level setting from main to worker thread
|
const tintColor = '#29235C'
export default {
tintColor,
tabIconDefault: '#a7aaaa',
tabIconSelected: 'rgba(41, 35, 92, .85)',
tabBar: '#fefefe',
errorBackground: '#e25a36',
successBackground: '#1bb461',
darkRed: '#a20737',
errorText: '#fff',
warningBackground: '#EAEB5E',
warningText: '#666804',
noticeBackground: '#29235C',
noticeText: '#fff',
white: '#fff',
gray: '#b9bdbd',
gray2: '#86939e',
grey3: '#f7f7f7',
grey4: '#d7d7d7',
grey5: '#eeeeee',
grey6: '#c7c7c7',
grey7: '#43484d',
darkGrey: '#444242',
background: '#eef0f3',
transparent: 'rgba(0, 0, 0, 0)',
searchHomeBackground: 'rgba(181, 182, 180, .4)',
tabNavigationBackground: '#f9f9f9',
tabNavigationBorder: 'rgba(157, 161, 161, .3)',
}
|
module.exports = function(app){
app.get('/user',function(req,res){
var user_id = req.param('id');
var connection = app.infra.connectionFactory();
var UserDao = new app.infra.UserDao(connection,user_id);
UserDao.pupilo(function(erros,resultados){
res.render('user/user',{pupilo:resultados});
});
connection.end();
});
};
|
import React, { Component } from 'react';
const VideoDetail = ({ video }) => {
if (!video) {
return <div>Loading...</div>
}
const videoId = video.id.videoId;
const vidUrl = `https://www.youtube.com/embed/${videoId}`;
return (
<div className="video-detail col-md-8">
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src={vidUrl}></iframe>
</div>
<div className="details">
<div>{video.snippet.title}</div>
<div>{video.snippet.description}</div>
</div>
</div>
);
};
export default VideoDetail; |
import styled from "styled-components/native";
export default styled.View`
padding-horizontal: 8
`;
|
'use strict';
var directives = angular.module('directiveTutorial.directives', []);
directives.directive('helloWorld', function() {
return {
restrict: 'E',
template: '<div>Hello World!</div>',
replace: true
};
});
directives.directive('helloWorld2', function() {
return {
restrict: 'E',
template: '<div>Hello {{name}}!</div>',
replace: true,
scope: {name: '@'}
};
});
directives.directive('helloWorld3', function() {
return {
restrict: 'EA',
templateUrl: 'templates/hello-world-template.html',
replace: true,
scope: {name: '@'}
};
});
directives.directive('digitalClock', function($timeout, dateFilter) {
return {
restrict: 'EA',
template: '{{time}}',
replace: false,
scope: true,
link: function(scope, element, attrs) {
var getFormattedDate = function() {
return dateFilter(new Date(), scope.format);
};
var delayedUpdate = function() {
$timeout(function() {
scope.time = getFormattedDate();
delayedUpdate(scope);
}, 1000);
};
scope.format = attrs.format || 'HH:mm:ss';
scope.time = getFormattedDate();
delayedUpdate();
}
};
});
directives.directive('clock', function($timeout, dateFilter) {
return {
restrict: 'EA',
templateUrl: 'templates/clock.html',
replace: false,
scope: true,
link: function(scope, element, attrs) {
var getFormattedDate = function() {
return dateFilter(new Date(), scope.format);
};
var delayedUpdate = function() {
$timeout(function() {
scope.time = getFormattedDate();
delayedUpdate(scope);
}, 1000);
};
scope.analog = typeof (attrs.analog) !== 'undefined';
if (scope.analog) {
CoolClock.findAndCreateClocks();
} else {
scope.format = attrs.format || 'HH:mm:ss';
scope.time = getFormattedDate();
delayedUpdate();
}
}
};
});
|
'use strict'
describe('Unit Tests', function() {
require('./tests/crossbrowsertesting-platform-status')
})
|
define(["require", "exports", "./mainmenu", "uimanager"], function (require, exports, mainmenu_1, uimanager_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
uimanager_1.uiManager.add(new mainmenu_1.MainMenu());
});
|
'use strict';
(function() {
function AuthService($location, $http, $cookies, $q, appConfig, Util, User) {
var safeCb = Util.safeCb;
var currentUser = {};
var userRoles = appConfig.userRoles || [];
if ($cookies.get('token') && $location.path() !== '/logout') {
currentUser = User.get();
}
var Auth = {
/**
* Authenticate user and save token
*
* @param {Object} user - login info
* @param {Function} callback - optional, function(error, user)
* @return {Promise}
*/
login({email, password}, callback) {
return $http.post('/auth/local', {
email: email,
password: password
})
.then(res => {
$cookies.put('token', res.data.token);
currentUser = User.get();
return currentUser.$promise;
})
.then(user => {
safeCb(callback)(null, user);
return user;
})
.catch(err => {
Auth.logout();
safeCb(callback)(err.data);
return $q.reject(err.data);
});
},
/**
* Delete access token and user info
*/
logout() {
$cookies.remove('token');
currentUser = {};
},
/**
* Create a new user
*
* @param {Object} user - user info
* @param {Function} callback - optional, function(error, user)
* @return {Promise}
*/
createUser(user, callback) {
return User.save(user,
function(data) {
$cookies.put('token', data.token);
currentUser = User.get();
return safeCb(callback)(null, user);
},
function(err) {
Auth.logout();
return safeCb(callback)(err);
}).$promise;
},
/**
* Change password
*
* @param {String} oldPassword
* @param {String} newPassword
* @param {Function} callback - optional, function(error, user)
* @return {Promise}
*/
changePassword(oldPassword, newPassword, callback) {
return User.changePassword({ id: currentUser._id }, {
oldPassword: oldPassword,
newPassword: newPassword
}, function() {
return safeCb(callback)(null);
}, function(err) {
return safeCb(callback)(err);
}).$promise;
},
/**
* Gets all available info on a user
* (synchronous|asynchronous)
*
* @param {Function|*} callback - optional, funciton(user)
* @return {Object|Promise}
*/
getCurrentUser(callback) {
if (arguments.length === 0) {
return currentUser;
}
var value = (currentUser.hasOwnProperty('$promise')) ?
currentUser.$promise : currentUser;
return $q.when(value)
.then(user => {
safeCb(callback)(user);
return user;
}, () => {
safeCb(callback)({});
return {};
});
},
/**
* Check if a user is logged in
* (synchronous|asynchronous)
*
* @param {Function|*} callback - optional, function(is)
* @return {Bool|Promise}
*/
isLoggedIn(callback) {
if (arguments.length === 0) {
return currentUser.hasOwnProperty('role');
}
return Auth.getCurrentUser(null)
.then(user => {
var is = user.hasOwnProperty('role');
safeCb(callback)(is);
return is;
});
},
/**
* Check if a user has a specified role or higher
* (synchronous|asynchronous)
*
* @param {String} role - the role to check against
* @param {Function|*} callback - optional, function(has)
* @return {Bool|Promise}
*/
hasRole(role, callback) {
var hasRole = function(r, h) {
return userRoles.indexOf(r) >= userRoles.indexOf(h);
};
if (arguments.length < 2) {
return hasRole(currentUser.role, role);
}
return Auth.getCurrentUser(null)
.then(user => {
var has = (user.hasOwnProperty('role')) ?
hasRole(user.role, role) : false;
safeCb(callback)(has);
return has;
});
},
/**
* Check if a user is an admin
* (synchronous|asynchronous)
*
* @param {Function|*} callback - optional, function(is)
* @return {Bool|Promise}
*/
isAdmin() {
return Auth.hasRole
.apply(Auth, [].concat.apply(['admin'], arguments));
},
/**
* Get auth token
*
* @return {String} - a token string used for authenticating
*/
getToken() {
return $cookies.get('token');
}
};
return Auth;
}
angular.module('flickrScannerApp.auth')
.factory('Auth', AuthService);
})();
|
/*!
* jQuery - Spectragram by Adrian Quevedo
* http://adrianquevedo.com/ - http://lab.adrianquevedo.com/ - http://elnucleo.com.co/
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* You are free to use this plugin in commercial projects as long as the copyright header is left intact.
*
* This plugin uses the Instagram(tm) API and is not endorsed or certified by Instagram or Burbn, inc.
* All Instagram(tm) logos and trademarks displayed on this plugin are property of Burbn, Inc.
*
* Date: Thu Jul 15 14:05:02 2012 -0500
*/
/*!
*
* 6 April 2018: Altered by Medium Rare
* Bypassed search API endpoint in getUserFeed to use "self" as user ID due to Instagram API changes.
*
*/
// Utility for older browsers
if (typeof Object.create !== 'function') {
Object.create = function (obj) {
function F() {};
F.prototype = obj;
return new F();
};
}
(function ($, window, document, undefined) {
var Instagram = {
//Initialize function
init: function (options, elem) {
var self = this;
self.elem = elem;
self.$elem = $(elem);
self.api = 'https://api.instagram.com/v1',
self.accessData = $.fn.spectragram.accessData,
self.options = $.extend({}, $.fn.spectragram.options, options);
},
//Users
//Get the most recent media published by a user.
getRecentMedia: function ( userID ) {
var self = this,
getData = '/users/' + userID + '/media/recent/?' + self.accessData.clientID + '&access_token='+ self.accessData.accessToken +'';
self.fetch(getData).done(function ( results ) {
self.display(results);
});
},
//Search for a user by name.
getUserFeed: function () {
var self = this;
self.getRecentMedia('self');
/* getData = '/users/search?q=' + self.options.query + '&count=' + self.options.max + '&access_token='+ self.accessData.accessToken + '';
self.fetch(getData).done(function ( results ) {
if(results.data.length){
self.getRecentMedia(results.data[0].id);
}else{
$.error('Spectagram.js - Error: the username ' + self.options.query + ' does not exist.');
};
}); */
},
//Media
//Get a list of what media is most popular at the moment
getPopular: function () {
var self = this,
getData = '/media/popular?client_id=' + self.accessData.clientID + '&access_token='+ self.accessData.accessToken + '';
self.fetch(getData).done(function ( results ) {
self.display(results);
});
},
//Tags
//Get a list of recently tagged media
getRecentTagged: function () {
var self = this,
getData = '/tags/' + self.options.query + '/media/recent?client_id=' + self.accessData.clientID + '&access_token='+ self.accessData.accessToken + '';
self.fetch(getData).done(function ( results ) {
if(results.data.length){
self.display(results);
}else{
$.error('Spectagram.js - Error: the tag ' + self.options.query + ' does not have results.');
};
});
},
fetch: function (getData) {
var self = this,
getUrl = self.api + getData;
return $.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: getUrl
});
},
display: function (results) {
var self = this,
setSize = self.options.size,
size, max = (self.options.max >= results.data.length) ? results.data.length : self.options.max;
if (results.data.length === 0) {
self.$elem.append($(self.options.wrapEachWith).append(self.options.notFoundMsg));
}
else {
for (var i = 0; i < max; i++) {
if (setSize == "small") {
size = results.data[i].images.thumbnail.url;
}
else if (setSize == "medium") {
size = results.data[i].images.low_resolution.url;
}
else {
size = results.data[i].images.standard_resolution.url;
}
var titleIMG;
// Skip if the caption is empty.
if ( results.data[i].caption != null ) {
/**
* 1. First it creates a dummy element <span/>
* 2. And then puts the caption inside the element created previously.
* 3. Extracts the html caption (this allows html codes to be included).
* 4. Lastly, the most important part, create the Title attribute using double quotes
* to enclose the text. This fixes the bug when the caption retrieved from Instagram
* includes single quotes which breaks the Title attribute.
*/
titleIMG = 'title="' + $('<span/>').text(results.data[i].caption.text).html() +'"';
}
// Now concatenate the titleIMG generated.
self.$elem.append($(self.options.wrapEachWith).append("<a " + titleIMG + " target='_blank' href='" + results.data[i].link + "'><img src='" + size + "'></img></a>"));
}
}
if (typeof self.options.complete === 'function') {
self.options.complete.call(self);
}
}
};
jQuery.fn.spectragram = function ( method, options ) {
if(jQuery.fn.spectragram.accessData.clientID){
this.each( function () {
var instagram = Object.create( Instagram );
instagram.init( options, this );
if( instagram[method] ) {
return instagram[method]( this );
}else{
$.error( 'Method ' + method + ' does not exist on jQuery.spectragram' );
}
});
}else{
$.error( 'You must define an accessToken and a clientID on jQuery.spectragram' );
}
};
//Plugin Default Options
jQuery.fn.spectragram.options = {
max: 10,
query: 'coffee',
size: 'medium',
wrapEachWith: '<li></li>',
complete : null
};
//Instagram Access Data
jQuery.fn.spectragram.accessData = {
accessToken: null,
clientID: null
};
})(jQuery, window, document); |
'use strict';
/**
* Module dependencies.
*/
const mongoose = require('mongoose');
const { wrap: async } = require('co');
const { respond } = require('../utils');
const Article = mongoose.model('Article');
/**
* List items tagged with a tag
*/
exports.index = async(function* (req, res) {
const criteria = { tags: req.params.tag };
const page = (req.params.page > 0 ? req.params.page : 1) - 1;
const limit = 30;
const options = {
limit: limit,
page: page,
conditions: criteria
};
const articles = yield Article.list(options);
const count = yield Article.count(criteria);
respond(res, 'articles/index', {
title: 'Articles tagged ' + req.params.tag,
articles: articles,
page: page + 1,
pages: Math.ceil(count / limit)
});
});
|
/* @flow */
import './Body.css';
import * as React from 'react';
import Footer from './Footer';
import type { Todo } from './Types';
import TodoList from './TodoList';
// Main Component
// --------------
interface Props {
onClearCompletedTodos: () => void;
onDestroyTodo: (Todo: Todo) => void;
onSetTodoTitle: (Todo: Todo, title: string) => void;
onToggleTodoCompleted: (Todo: Todo, done: boolean) => void;
onToggleAllTodosCompleted: (toggle: boolean) => void;
todos: Array<Todo>;
}
// The main component contains the list of todos and the footer.
export default function Body(props: Props) {
// Tell the **App** to toggle the *done* state of all **Todo** items.
const toggleAllTodosCompleted = (event: SyntheticInputEvent<HTMLInputElement>) => {
props.onToggleAllTodosCompleted(event.target.checked);
};
return (
<section id="main">
<input
id="toggle-all"
type="checkbox"
checked={props.todos.every(t => t.done)}
onChange={toggleAllTodosCompleted}
/>
<label htmlFor="toggle-all">Mark all as complete</label>
<TodoList
onDestroyTodo={props.onDestroyTodo}
onSetTodoTitle={props.onSetTodoTitle}
onToggleTodoCompleted={props.onToggleTodoCompleted}
todos={props.todos}
/>
<Footer
clearCompletedItems={props.onClearCompletedTodos}
itemsRemainingCount={props.todos.reduce((count, t) => {
if (!t.done) count += 1;
return count;
}, 0)}
itemsDoneCount={props.todos.reduce((count, t) => {
if (t.done) count += 1;
return count;
}, 0)}
/>
</section>
);
}
|
const areaService = require('../data/entityServices/areaService')
const createArea = (req, res) => {
return areaService.createArea(req.body)
.then(area => {
res.send(area)
})
}
const getAreaById = (req, res) => {
return areaService.getAreaById(req.params.id)
.then(area => {
res.send(area);
})
}
const createNoteForArea = (req, res) => {
return areaService.createNoteForArea(req.body)
.then(areaNote => {
res.send(areaNote)
})
}
const addTagToArea = (req, res) => {
const {areaId, tagId} = req.params;
return areaService.addTagToArea(areaId, tagId)
.then(() => {
res.send()
})
}
const removeTagFromArea = (req, res) => {
const {areaId, tagId} = req.params;
return areaService.removeTagFromArea(areaId, tagId)
.then(() => {
res.send()
})
}
const getAllAreas = (req, res) => {
return areaService.getAllAreas()
.then(areas => {
res.send(areas)
})
}
module.exports = app => {
const url = '/api/area';
app.post(`${url}/note`, createNoteForArea)
app.put(`${url}/:areaId/tag/:tagId`, addTagToArea)
app.delete(`${url}/:areaId/tag/:tagId`, removeTagFromArea)
app.post(url, createArea)
app.get(`${url}/:id`, getAreaById)
app.get(url, getAllAreas)
} |
'use strict';
angular.module('ngModuleIntrospector', []);
|
define(function(require, exports, module) {
"use strict";
var assert = require("chai").assert;
var testTools = require("../../testTools");
var cc = require("./cc");
var node = require("./node");
var Group = node.Group;
var Synth = node.Synth;
var ir = C.SCALAR, kr = C.CONTROL, ar = C.AUDIO;
describe("server/node.js", function() {
var actual, expected;
var world, nodes, rootNode;
var processed;
testTools.mock("server", {
timeline: {
push: function(func) { func(); }
},
sendToLang: function() {}
});
beforeEach(function() {
world = { defs:[] };
world.nodes = [
new Group(world, 0), new Synth(world, 1), new Group(world, 2), new Synth(world, 3), new Synth(world, 4),
new Group(world, 5), new Synth(world, 6), new Synth(world, 7), new Group(world, 8), new Synth(world, 9),
];
nodes = world.nodes.slice();
rootNode = nodes[0];
nodes[0].head = nodes[1]; nodes[0].tail = nodes[3];
nodes[1].parent = nodes[0]; nodes[1].next = nodes[2];
nodes[2].parent = nodes[0]; nodes[2].prev = nodes[1]; nodes[2].next = nodes[3]; nodes[2].head = nodes[4]; nodes[2].tail = nodes[6];
nodes[3].parent = nodes[0]; nodes[3].prev = nodes[2];
nodes[4].parent = nodes[2]; nodes[4].next = nodes[5];
nodes[5].parent = nodes[2]; nodes[5].prev = nodes[4]; nodes[5].next = nodes[6]; nodes[5].head = nodes[7]; nodes[5].tail = nodes[9];
nodes[6].parent = nodes[2]; nodes[6].prev = nodes[5];
nodes[7].parent = nodes[5]; nodes[7].next = nodes[8];
nodes[8].parent = nodes[5]; nodes[8].prev = nodes[7]; nodes[8].next = nodes[9];
nodes[9].parent = nodes[5]; nodes[9].prev = nodes[8];
processed = [];
nodes[1].unitList = [ {rate:{ bufLength:64 }, process:function() { processed.push(1) }} ];
nodes[3].unitList = [ {rate:{ bufLength:64 }, process:function() { processed.push(3) }} ];
nodes[4].unitList = [ {rate:{ bufLength:64 }, process:function() { processed.push(4) }} ];
nodes[6].unitList = [ {rate:{ bufLength:64 }, process:function() { processed.push(6) }} ];
nodes[7].unitList = [ {rate:{ bufLength:64 }, process:function() { processed.push(7) }} ];
nodes[9].unitList = [ {rate:{ bufLength:64 }, process:function() { processed.push(9) }} ];
});
var walk = (function() {
var _walk = function(node, sort, list) {
if (node) {
list.push(node.nodeId);
if (node instanceof Group) {
if (sort === "DESC") {
_walk(node.tail, sort, list);
} else {
_walk(node.head, sort, list);
}
}
if (sort === "DESC") {
_walk(node.prev, sort, list);
} else {
_walk(node.next, sort, list);
}
}
return list;
}
return function(node, sort) { return _walk(node, sort, []); }
})();
describe("Node", function() {
describe("#end", function() {
it("nodes[0].end()", function() {
nodes[0].end();
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
assert.isFalse(nodes[0].running);
});
it("nodes[1].end()", function() {
nodes[1].end();
actual = walk(rootNode, "ASC");
expected = [ 0, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4 ];
assert.deepEqual(actual, expected);
assert.isFalse(nodes[1].running);
});
it("nodes[2].end()", function() {
nodes[2].end();
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 1 ];
assert.deepEqual(actual, expected);
assert.isFalse(nodes[2].running);
});
it("nodes[3].end()", function() {
nodes[3].end();
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 2, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
assert.isFalse(nodes[3].running);
});
it("nodes[4].end()", function() {
nodes[4].end();
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 1 ];
assert.deepEqual(actual, expected);
assert.isFalse(nodes[4].running);
});
it("nodes[5].end()", function() {
nodes[5].end();
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 4, 1 ];
assert.deepEqual(actual, expected);
assert.isFalse(nodes[5].running);
});
it("nodes[6].end()", function() {
nodes[6].end();
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
assert.isFalse(nodes[6].running);
});
});
});
describe("Group", function() {
it("createRootNode", function() {
var g = cc.createServerRootNode({});
assert.instanceOf(g, Group);
assert.equal(g.nodeId, 0);
});
it("createNode", function() {
var g = cc.createServerGroup({}, 100, nodes[9], C.ADD_AFTER);
assert.instanceOf(g, Group);
assert.equal(g.nodeId, 100);
actual = walk(nodes[9], "ASC");
expected = [ 9, 100 ];
assert.deepEqual(actual, expected);
});
it("#process", function() {
nodes[0].process(1);
assert.deepEqual(processed, [ 1, 4, 7, 9, 6, 3 ]);
});
});
describe("Synth", function() {
testTools.mock("createUnit", function(synth, spec) {
var u = {};
u.specs = spec;
u.inputs = new Array(spec[3].length >> 1);
u.outputs = [ [], [] ];
u.inRates = [];
u.outRates = spec[4];
u.fromUnits = [];
u.init = function() {
if (spec[4].length) {
u.process = function() {};
}
};
return u;
});
it("createSynth", function() {
var s = cc.createServerSynth({defs:[]}, 100, nodes[9], C.ADD_AFTER, 0, []);
assert.instanceOf(s, Synth);
assert.equal(s.nodeId, 100);
actual = walk(nodes[9], "ASC");
expected = [ 9, 100 ];
assert.deepEqual(actual, expected);
});
it("new with build", function() {
world = {
defs: [
{
name : "test",
consts: [ 0, 880 ],
params: {
names : [],
indices: [],
length : [],
values : [],
},
defList: [
[ "Scalar", ir, 0, [ -1, 1 ], [ ir ] ],
[ "SinOsc", ar, 0, [ 0, 0, -1, 0 ], [ ar ] ],
[ "Pass" , ar, 0, [ 1, 0 ], [ ar ] ],
[ "Out" , ar, 0, [ -1, 0, 2, 0 ], [ ] ],
],
variants: {},
heapSize: 100
}
],
getFixNum: function(value) {
return { outputs:[new Float32Array([value])] };
}
};
var s = new Synth(world, 0, null, 0, 0, [0, 1, 1, 2]);
assert.equal(s.unitList[0].inputs[0][0], 880);
assert.equal(s.unitList[0].inRates[0], C.SCALAR);
assert.equal(s.unitList[1].fromUnits[0], s.unitList[0]);
assert.equal(s.unitList[1].inputs[0], s.unitList[0].outputs[0]);
assert.equal(s.unitList[1].inputs[1][0], 0);
assert.equal(s.unitList[1].inRates[0], C.SCALAR);
assert.equal(s.unitList[1].inRates[1], C.SCALAR);
assert.equal(s.unitList[2].fromUnits[0], s.unitList[1]);
assert.equal(s.unitList[2].inputs[0], s.unitList[1].outputs[0]);
assert.equal(s.unitList[2].inRates[0], C.AUDIO);
assert.isUndefined(s.unitList[3]);
});
it("#set", function() {
var s = new Synth({defs:[]}, 0);
s.controls = [];
s.set([0,1, 1,2, 2,3]);
assert.deepEqual(s.controls, [ 1, 2, 3 ]);
});
it("#process", function() {
nodes[4].process(1);
assert.deepEqual(processed, [ 4, 7, 9, 6 ]);
});
it("#process (run:false)", function() {
nodes[4].run(false);
nodes[4].process(1);
assert.deepEqual(processed, [ 7, 9, 6 ]);
});
});
describe("graphFunction", function() {
describe("addToHead", function() {
it("first item", function() {
new Synth(world, 10, nodes[8], C.ADD_TO_HEAD);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 10, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 10, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
it("subsequent item", function() {
new Synth(world, 10, nodes[2], C.ADD_TO_HEAD);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 10, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4, 10, 1 ];
assert.deepEqual(actual, expected);
});
it("add to a synth", function() {
new Synth(world, 10, nodes[9], C.ADD_TO_HEAD);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
});
describe("addToTail", function() {
it("first item", function() {
new Synth(world, 10, nodes[8], C.ADD_TO_TAIL);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 10, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 10, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
it("subsequent item", function() {
new Synth(world, 10, nodes[2], C.ADD_TO_TAIL);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 10, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 10, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
it("add to a synth", function() {
new Synth(world, 10, nodes[9], C.ADD_TO_TAIL);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
});
describe("addBefore", function() {
it("append", function() {
new Synth(world, 10, nodes[1], C.ADD_BEFORE);
actual = walk(rootNode, "ASC");
expected = [ 0, 10, 1, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4, 1, 10 ];
assert.deepEqual(actual, expected);
});
it("insert", function() {
new Synth(world, 10, nodes[3], C.ADD_BEFORE);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 10, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 10, 2, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
it("add to the root", function() {
new Synth(world, 10, nodes[0], C.ADD_BEFORE);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
});
describe("addAfter", function() {
it("append", function() {
new Synth(world, 10, nodes[3], C.ADD_AFTER);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 3, 10 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 10, 3, 2, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
it("insert", function() {
new Synth(world, 10, nodes[1], C.ADD_AFTER);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 10, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4, 10, 1 ];
assert.deepEqual(actual, expected);
});
it("add to the root", function() {
new Synth(world, 10, nodes[0], C.ADD_AFTER);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
});
describe("replace", function() {
it("replace a synth(head)", function() {
new Synth(world, 10, nodes[1], C.REPLACE);
actual = walk(rootNode, "ASC");
expected = [ 0, 10, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4, 10 ];
assert.deepEqual(actual, expected);
});
it("replace a synth(tail)", function() {
new Synth(world, 10, nodes[3], C.REPLACE);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 10 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 10, 2, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
it("replace a group", function() {
new Group(world, 10, nodes[2], C.REPLACE);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 10, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 10, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
it("replace a root", function() {
new Synth(world, 10, nodes[0], C.REPLACE);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected);
actual = walk(rootNode, "DESC");
expected = [ 0, 3, 2, 6, 5, 9, 8, 7, 4, 1 ];
assert.deepEqual(actual, expected);
});
});
});
describe("doneAction", function() {
var desc;
it("0", function() {
desc = "do nothing when the UGen is finished";
nodes[2].doneAction(0);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, true);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("1", function() {
desc = "pause the enclosing synth, but do not free it";
nodes[2].doneAction(1);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("2", function() {
desc = "free the enclosing synth";
nodes[2].doneAction(2);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 3 ];
assert.deepEqual(actual, expected, desc);
actual = walk(nodes[2], "ASC");
expected = [ 2, 4, 5, 7, 8, 9, 6 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("3", function() {
desc = "free both this synth and the preceding node";
nodes[2].doneAction(3);
actual = walk(rootNode, "ASC");
expected = [ 0, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("3 (preceding node is not exists)", function() {
desc = "free both this synth and the preceding node";
nodes[1].doneAction(3);
actual = walk(rootNode, "ASC");
expected = [ 0, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, true);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("4", function() {
desc = "free both this synth and the following node";
nodes[2].doneAction(4);
actual = walk(rootNode, "ASC");
expected = [ 0, 1 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("4 (following node is not exists)", function() {
desc = "free both this synth and the following node";
nodes[3].doneAction(4);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, true);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("5", function() {
desc = "free this synth; if the preceding node is a group then do g_freeAll on it, else free it";
nodes[3].doneAction(5);
actual = walk(rootNode, "ASC");
expected = [ 0, 1 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, false);
assert.equal(nodes[5].running, false);
assert.equal(nodes[6].running, false);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], null);
assert.equal(world.nodes[5], null);
assert.equal(world.nodes[6], null);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("5 (preceding is not a group)", function() {
desc = "free this synth; if the preceding node is a group then do g_freeAll on it, else free it";
nodes[2].doneAction(5);
actual = walk(rootNode, "ASC");
expected = [ 0, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("5 (preceding node is not exists)", function() {
desc = "free this synth; if the preceding node is a group then do g_freeAll on it, else free it";
nodes[1].doneAction(5);
actual = walk(rootNode, "ASC");
expected = [ 0, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, true);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("6", function() {
desc = "free this synth; if the following node is a group then do g_freeAll on it, else free it";
nodes[1].doneAction(6);
actual = walk(rootNode, "ASC");
expected = [ 0, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, false);
assert.equal(nodes[5].running, false);
assert.equal(nodes[6].running, false);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], null);
assert.equal(world.nodes[5], null);
assert.equal(world.nodes[6], null);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("6 (following is not a group)", function() {
desc = "free this synth; if the following node is a group then do g_freeAll on it, else free it";
nodes[2].doneAction(6);
actual = walk(rootNode, "ASC");
expected = [ 0, 1 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("6 (following node is not exists)", function() {
desc = "free this synth; if the following node is a group then do g_freeAll on it, else free it";
nodes[3].doneAction(6);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, true);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("7", function() {
desc = "free this synth and all preceding nodes in this group";
nodes[3].doneAction(7);
actual = walk(rootNode, "ASC");
expected = [ 0 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("8", function() {
desc = "free this synth and all following nodes in this group";
nodes[1].doneAction(8);
actual = walk(rootNode, "ASC");
expected = [ 0 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("9", function() {
desc = "free this synth and pause the preceding node";
nodes[2].doneAction(9);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("9 (preceding node is not exists)", function() {
desc = "free this synth and pause the preceding node";
nodes[1].doneAction(9);
actual = walk(rootNode, "ASC");
expected = [ 0, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, true);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("10", function() {
desc = "free this synth and pause the following node";
nodes[2].doneAction(10);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("10 (following node is not exists)", function() {
desc = "free this synth and pause the preceding node";
nodes[3].doneAction(10);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, true);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("11", function() {
desc = "free this synth and if the preceding node is a group then do g_deepFree on it, else free it";
nodes[3].doneAction(11);
actual = walk(rootNode, "ASC");
expected = [ 0, 1 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, false);
assert.equal(nodes[5].running, false);
assert.equal(nodes[6].running, false);
assert.equal(nodes[7].running, false);
assert.equal(nodes[8].running, false);
assert.equal(nodes[9].running, false);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], null);
assert.equal(world.nodes[5], null);
assert.equal(world.nodes[6], null);
assert.equal(world.nodes[7], null);
assert.equal(world.nodes[8], null);
assert.equal(world.nodes[9], null);
});
it("11 (preceding is not a group)", function() {
desc = "free this synth and if the preceding node is a group then do g_deepFree on it, else free it";
nodes[2].doneAction(11);
actual = walk(rootNode, "ASC");
expected = [ 0, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("11 (preceding node is not exists)", function() {
desc = "free this synth and if the preceding node is a group then do g_deepFree on it, else free it";
nodes[1].doneAction(11);
actual = walk(rootNode, "ASC");
expected = [ 0, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, true);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("12", function() {
desc = "free this synth and if the following node is a group then do g_deepFree on it, else free it";
nodes[1].doneAction(12);
actual = walk(rootNode, "ASC");
expected = [ 0, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, false);
assert.equal(nodes[5].running, false);
assert.equal(nodes[6].running, false);
assert.equal(nodes[7].running, false);
assert.equal(nodes[8].running, false);
assert.equal(nodes[9].running, false);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], null);
assert.equal(world.nodes[5], null);
assert.equal(world.nodes[6], null);
assert.equal(world.nodes[7], null);
assert.equal(world.nodes[8], null);
assert.equal(world.nodes[9], null);
});
it("12 (following is not a group)", function() {
desc = "free this synth and if the following node is a group then do g_deepFree on it, else free it";
nodes[2].doneAction(12);
actual = walk(rootNode, "ASC");
expected = [ 0, 1 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("12 (following node is not exists)", function() {
desc = "free this synth and if the following node is a group then do g_deepFree on it, else free it";
nodes[3].doneAction(12);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, true);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("13", function() {
desc = "free this synth and all other nodes in this group (before and after)";
nodes[2].doneAction(13);
actual = walk(rootNode, "ASC");
expected = [ 0 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
it("14", function() {
desc = "free the enclosing group and all nodes within it (including this synth)";
nodes[2].doneAction(14);
actual = walk(rootNode, "ASC");
expected = [ 0 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, false);
assert.equal(nodes[1].running, false);
assert.equal(nodes[2].running, false);
assert.equal(nodes[3].running, false);
assert.equal(nodes[4].running, false);
assert.equal(nodes[5].running, false);
assert.equal(nodes[6].running, false);
assert.equal(nodes[7].running, false);
assert.equal(nodes[8].running, false);
assert.equal(nodes[9].running, false);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], null);
assert.equal(world.nodes[2], null);
assert.equal(world.nodes[3], null);
assert.equal(world.nodes[4], null);
assert.equal(world.nodes[5], null);
assert.equal(world.nodes[6], null);
assert.equal(world.nodes[7], null);
assert.equal(world.nodes[8], null);
assert.equal(world.nodes[9], null);
});
it("none", function() {
nodes[2].doneAction(100);
actual = walk(rootNode, "ASC");
expected = [ 0, 1, 2, 4, 5, 7, 8, 9, 6, 3 ];
assert.deepEqual(actual, expected, desc);
assert.equal(nodes[0].running, true);
assert.equal(nodes[1].running, true);
assert.equal(nodes[2].running, true);
assert.equal(nodes[3].running, true);
assert.equal(nodes[4].running, true);
assert.equal(nodes[5].running, true);
assert.equal(nodes[6].running, true);
assert.equal(nodes[7].running, true);
assert.equal(nodes[8].running, true);
assert.equal(nodes[9].running, true);
assert.equal(world.nodes[0], nodes[0]);
assert.equal(world.nodes[1], nodes[1]);
assert.equal(world.nodes[2], nodes[2]);
assert.equal(world.nodes[3], nodes[3]);
assert.equal(world.nodes[4], nodes[4]);
assert.equal(world.nodes[5], nodes[5]);
assert.equal(world.nodes[6], nodes[6]);
assert.equal(world.nodes[7], nodes[7]);
assert.equal(world.nodes[8], nodes[8]);
assert.equal(world.nodes[9], nodes[9]);
});
});
});
});
|
/*
* grunt-cordova-setup
* https://github.com/juzaun/grunt-cordova-setup
*
* Copyright (c) 2014 Justin Zaun
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js'
],
options: {
jshintrc: '.jshintrc'
},
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint']);
};
|
import React from 'react';
import SVG from './svg';
export default class Empty extends React.Component {
render() {
return (
<span>
<SVG
xmlns="http://www.w3.org/2000/svg"
width="917.561"
height="894.44"
viewBox="62.584 127.157 917.561 894.44"
>
<path d="M257.904 1021.597a32 32 0 0 1-31.183-39.199l66.82-289.402L71.855 469.33a32 32 0 0 1 22.664-54.526l283.17-.57L495.804 146.33a32.003 32.003 0 0 1 29.054-19.17h.264a32 32 0 0 1 29.102 18.693l123.624 268.386 270.365.568a31.997 31.997 0 0 1 29.286 19.26 32.003 32.003 0 0 1-5.936 34.546L766.18 689.187l63.86 293.61a32.001 32.001 0 0 1-47.424 34.423L525.314 866.744l-250.97 150.308a31.974 31.974 0 0 1-16.44 4.545zM525.12 797.56c5.58 0 11.162 1.458 16.153 4.377L752.01 925.18l-51.927-238.748a31.989 31.989 0 0 1 7.85-28.607L874.767 478.65l-217.564-.457a31.996 31.996 0 0 1-29.034-18.694L525.76 237.513l-97.81 221.508a31.997 31.997 0 0 1-29.25 19.17l-227.497.46 180.214 181.824a32.005 32.005 0 0 1 8.452 29.726l-53.863 233.286 202.67-121.38a31.988 31.988 0 0 1 16.442-4.548z" />
</SVG>
</span>
);
}
}
|
// Code generator: generates JS list of all git log fields
import {inspect} from 'util';
import * as fs from 'fs';
import * as Path from 'path';
import {groupBy, each} from 'lodash';
// Copy-pasted from https://git-scm.com/docs/pretty-formats, with all formatting-related codes removed.
const gitLogFieldDocs = `
'%H': commit hash
'%h': abbreviated commit hash
'%T': tree hash
'%t': abbreviated tree hash
'%P': parent hashes
'%p': abbreviated parent hashes
'%an': author name
'%aN': author name (respecting .mailmap, see git-shortlog[1] or git-blame[1])
'%ae': author email
'%aE': author email (respecting .mailmap, see git-shortlog[1] or git-blame[1])
'%ad': author date (format respects --date= option)
'%aD': author date, RFC2822 style
'%ar': author date, relative
'%at': author date, UNIX timestamp
'%ai': author date, ISO 8601-like format
'%aI': author date, strict ISO 8601 format
'%cn': committer name
'%cN': committer name (respecting .mailmap, see git-shortlog[1] or git-blame[1])
'%ce': committer email
'%cE': committer email (respecting .mailmap, see git-shortlog[1] or git-blame[1])
'%cd': committer date (format respects --date= option)
'%cD': committer date, RFC2822 style
'%cr': committer date, relative
'%ct': committer date, UNIX timestamp
'%ci': committer date, ISO 8601-like format
'%cI': committer date, strict ISO 8601 format
'%d': ref names, like the --decorate option of git-log[1]
'%D': ref names without the " (", ")" wrapping.
'%e': encoding
'%s': subject
'%f': sanitized subject line, suitable for a filename
'%b': body
'%B': raw body (unwrapped subject and body)
'%N': commit notes
'%GG': raw verification message from GPG for a signed commit
'%G?': show "G" for a good (valid) signature, "B" for a bad signature, "U" for a good signature with unknown validity, "X" for a good signature that has expired, "Y" for a good signature made by an expired key, "R" for a good signature made by a revoked key, "E" if the signature cannot be checked (e.g. missing key) and "N" for no signature
'%GS': show the name of the signer for a signed commit
'%GK': show the key used to sign a signed commit
'%gD': reflog selector, e.g., refs/stash@{1} or refs/stash@{2 minutes ago}; the format follows the rules described for the -g option. The portion before the @ is the refname as given on the command line (so git log -g refs/heads/master would yield refs/heads/master@{0}).
'%gd': shortened reflog selector; same as %gD, but the refname portion is shortened for human readability (so refs/heads/master becomes just master).
'%gn': reflog identity name
'%gN': reflog identity name (respecting .mailmap, see git-shortlog[1] or git-blame[1])
'%ge': reflog identity email
'%gE': reflog identity email (respecting .mailmap, see git-shortlog[1] or git-blame[1])
'%gs': reflog subject
// '%Cred': switch color to red
//
// '%Cgreen': switch color to green
//
// '%Cblue': switch color to blue
//
// '%Creset': reset color
//
// '%C(…)': color specification, as described under Values in the "CONFIGURATION FILE" section of git-config[1]; adding auto, at the beginning will emit color only when colors are enabled for log output (by color.diff, color.ui, or --color, and respecting the auto settings of the former if we are going to a terminal). auto alone (i.e. %C(auto)) will turn on auto coloring on the next placeholders until the color is switched again.
//
// '%m': left (<), right (>) or boundary (-) mark
//
// '%n': newline
//
// '%%': a raw '%'
//
// '%x00': print a byte from a hex code
//
// '%w([<w>[,<i1>[,<i2>]]])': switch line wrapping, like the -w option of git-shortlog[1].
//
// '%<(<N>[,trunc|ltrunc|mtrunc])': make the next placeholder take at least N columns, padding spaces on the right if necessary. Optionally truncate at the beginning (ltrunc), the middle (mtrunc) or the end (trunc) if the output is longer than N columns. Note that truncating only works correctly with N >= 2.
//
// '%<|(<N>)': make the next placeholder take at least until Nth columns, padding spaces on the right if necessary
//
// '%>(<N>)', '%>|(<N>)': similar to '%<(<N>)', '%<|(<N>)' respectively, but padding spaces on the left
//
// '%>>(<N>)', '%>>|(<N>)': similar to '%>(<N>)', '%>|(<N>)' respectively, except that if the next placeholder takes more spaces than given and there are spaces on its left, use those spaces
//
// '%><(<N>)', '%><|(<N>)': similar to '% <(<N>)', '%<|(<N>)' respectively, but padding both sides (i.e. the text is centered)
`;
const fields = gitLogFieldDocs.split(/\r\n|\n/).filter(line => (
line && line.indexOf('//') != 0
)).map(line => {
const [, code, fullDescription, name, description] = line.match(/'(.*?)': ((.*?)((?:,|;| \(|$).*))/);
return {
code,
name,
fullDescription,
description,
identifier: name.replace(/ /g, '_')
};
});
// For fields that end up with identical identifiers, give them longer, unique identifiers
each(groupBy(fields, 'identifier'), group => {
if(group.length < 2) return;
group.forEach(field => {
field.identifier = field.fullDescription.replace(/[,;]? /g, '_');
});
});
const output = `
export const fields = ${ inspect(fields) };
`;
fs.writeFileSync(Path.join(__dirname, 'git-log-fields.es'), output); |
const KingsOfSummer = require('../../../../server/game/cards/04.2-CtA/KingsOfSummer.js');
describe('Kings Of Summer', function() {
beforeEach(function() {
this.gameSpy = jasmine.createSpyObj('game', ['addMessage', 'getPlayers', 'on']);
this.plot1 = jasmine.createSpyObj('plot1', ['hasTrait']);
this.plot2 = jasmine.createSpyObj('plot2', ['hasTrait']);
this.plot3 = jasmine.createSpyObj('plot3', ['hasTrait']);
this.plot1.hasTrait.and.callFake(trait => {
return trait === 'Summer';
});
this.plot2.hasTrait.and.returnValue(false);
this.player1Fake = {};
this.player1Fake.game = this.gameSpy;
this.player1Fake.activePlot = this.plot1;
this.player1Fake.activePlot.reserveModifier = 0;
this.player1Fake.activePlot.goldModifier = 0;
this.plot1.controller = this.player1Fake;
this.plot3.controller = this.player1Fake;
this.player2Fake = {};
this.player2Fake.game = this.gameSpy;
this.player2Fake.activePlot = this.plot2;
this.player2Fake.activePlot.reserveModifier = 0;
this.player2Fake.activePlot.goldModifier = 0;
this.plot2.controller = this.player2Fake;
this.gameSpy.getPlayers.and.returnValue([this.player1Fake, this.player2Fake]);
this.agenda = new KingsOfSummer(this.player1Fake, {});
});
describe('reserve persistent effect', function() {
beforeEach(function() {
this.reserveEffect = this.agenda.abilities.persistentEffects[0];
});
it('should target all players', function() {
expect(this.reserveEffect.targetController).toBe('any');
});
it('should match with active plots', function() {
expect(this.reserveEffect.match(this.plot1)).toBe(true);
// Belongs to player 1 but is not active.
expect(this.reserveEffect.match(this.plot3)).toBe(false);
});
it('should increase the plots reserve', function() {
this.reserveEffect.effect.apply(this.plot1);
expect(this.plot1.reserveModifier).toBe(1);
});
});
describe('gold persistent effect', function() {
beforeEach(function() {
this.goldEffect = this.agenda.abilities.persistentEffects[1];
});
it('should increase the gold on the plot', function() {
this.goldEffect.effect.apply(this.plot1);
expect(this.plot1.goldModifier).toBe(1);
});
describe('when a Winter plot is revealed', function() {
beforeEach(function() {
this.plot2.hasTrait.and.callFake(trait => trait === 'Winter');
});
it('should not pass the activation condition', function() {
expect(this.goldEffect.condition()).toBe(false);
});
});
describe('when no Winter plot is revealed', function() {
describe('and the current player has a Summer plot', function() {
beforeEach(function() {
this.plot1.hasTrait.and.callFake(trait => trait === 'Summer');
});
it('should pass the activation condition', function() {
expect(this.goldEffect.condition()).toBe(true);
});
it('should match the plot', function() {
expect(this.goldEffect.match(this.plot1)).toBe(true);
});
});
describe('and the current player does not have a Summer plot', function() {
beforeEach(function() {
this.plot1.hasTrait.and.returnValue(false);
});
it('should pass the activation condition', function() {
expect(this.goldEffect.condition()).toBe(true);
});
it('should not match the plot', function() {
expect(this.goldEffect.match(this.plot1)).toBe(false);
});
});
});
});
});
|
var ListenerProcess = require('./libs/listenerprocess');
var listener = new ListenerProcess();
listener.listenForLogicProcesses('./clients.sock');
// Report back with the number of connected clients we have
setInterval(() => {
process.send({pid: process.pid, client_count: listener.clientCount()});
}, 1000);
/**
* TCP Server example
*/
var net = require('net');
net.createServer((socket) => {
listener.addClient(socket);
}).listen(6000);
/**
* Sockjs example
*/
var http = require('http');
var fs = require('fs');
var sockjs = require('sockjs');
var server = http.createServer(function (req, res) {
fs.readFile(__dirname + '/public/sockjs_example.html',
function (err, data) {
res.writeHead(200);
res.end(data);
});
});
server.listen(5002);
var echo = sockjs.createServer({ sockjs_url: 'http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js', log:function(){} });
echo.on('connection', function(socket) {
listener.addClient(socket);
});
echo.installHandlers(server, {prefix:'/transport'});
/**
* Socket.io example
*/
/*
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(5001);
function handler (req, res) {
fs.readFile(__dirname + '/public/socketio_example.html',
function (err, data) {
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
listener.addClient(socket, {
onData: 'message',
onClose: 'disconnect',
write: (data) => { socket.emit('message', data); }
});
});
*/ |
var rx = require('../bower_components/rxjs/dist/rx.lite.js');
var equipmentProfileAPI = (function(promiseAPI, baseAPIAddress) {
var getAllProfiles = function() {
var url = baseAPIAddress + 'equipmentprofile';
return Rx.Observable.fromPromise(
promiseAPI.get(url, 'text').then(function(response) {
var equipmentProfileNames = response.split("\r\n")
.filter(function(arg) {
return arg !== "";
});
return equipmentProfileNames;
}));
};
var getProfile = function(name) {
var url = baseAPIAddress + 'equipmentprofile?name=' + name;
return Rx.Observable.fromPromise(
promiseAPI.get(url, 'arraybuffer').then(function(response) {
return parseEquipmentProfile(response);
}));
};
var parseEquipmentProfile = function(response) {
var dv = new DataView(response);
var aryOffset = 0;
var calcF16 = fletcherChecksum(response, 0, response.byteLength - 2);
var equipmentProfile = {};
equipmentProfile.regulationMode = dv.getInt8(aryOffset, true);
aryOffset += 1;
equipmentProfile.probe0Assignment = dv.getInt8(aryOffset, true);
aryOffset += 1;
equipmentProfile.probe1Assignment = dv.getInt8(aryOffset, true);
aryOffset += 1;
aryOffset += 1; //dummy byte
equipmentProfile.heatMinTimeOn = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.heatMinTimeOff = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.coolMinTimeOn = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.coolMinTimeOff = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.processKp = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.processKi = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.processKd = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.targetKp = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.targetKi = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.targetKd = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.targetOutputMaxC = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.targetOutputMinC = dv.getUint32(aryOffset, true);
aryOffset += 4;
equipmentProfile.thresholdDeltaC = dv.getUint32(aryOffset, true);
aryOffset += 4;
var recordF16 = dv.getUint16(aryOffset, true);
aryOffset += 2;
if (calcF16 !== recordF16) {
console.warning("Checksums to do not match Calculated=" + CalcF16 + " Record=" + RecordF16 + "sourceData");
}
return equipmentProfile;
};
var setEquipmentProfile = function() {
};
var deleteEquipmentProfile = function(equipmentProfileName) {
var url = baseAddress + 'deleteequipmentprofile?name=' + equipmentProfileName;
return Rx.Observable.fromPromise(promiseAPI.put(url));
};
return {
getAllProfiles: getAllProfiles,
getProfile: getProfile,
setEquipmentProfile: setEquipmentProfile,
deleteEquipmentProfile: deleteEquipmentProfile
};
})(promiseAPI);
|
var express = require('express');
var passport = require('passport');
var router = express.Router();
var User = require('../models/user');
router.route('/signin').post(function(req, res) {
var newUser = new User({
username: req.body.username,
mail: req.body.mail,
password: req.body.password
});
newUser.save(function (err, result) {
if(err) return res.redirect('/');
passport.authenticate('local')(req, res, function () {
res.redirect('/handling');
});
});
});
router.route('/login').post(
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/'})
);
router.route('/logout').get(function(req, res) {
req.logout();
req.session.destroy();
res.redirect('/login');
});
module.exports = router;
|
"use strict";
const log = require('./log');
const proxy = require('./proxy');
const stats = require('./stats');
const block = require('./block');
const transaction = require('./transaction');
const contract = require('./contract');
const account = require('./account');
/**
* @module etherscan/api
*/
/**
* @param {string} apiKey - (optional) Your Etherscan APIkey
* @param {string} chain - (optional) Testnet chain keys [ropsten, rinkeby, kovan]
* @param {number} timeout - (optional) Timeout in milliseconds for requests, default 10000
*/
module.exports = function(apiKey, chain, timeout) {
if (!apiKey) {
apiKey = 'YourApiKeyToken';
}
if (!timeout) {
timeout = 10000;
}
var getRequest = require('./get-request')(chain, timeout);
/** @lends module:etherscan/api */
return {
/**
* @namespace
*/
log: log(getRequest, apiKey),
/**
* @namespace
*/
proxy: proxy(getRequest, apiKey),
/**
* @namespace
*/
stats: stats(getRequest, apiKey),
/**
* @namespace
*/
block: block(getRequest, apiKey),
/**
* @namespace
*/
transaction: transaction(getRequest, apiKey),
/**
* @namespace
*/
contract: contract(getRequest, apiKey),
/**
* @namespace
*/
account: account(getRequest, apiKey)
};
};
|
define (['mmirf/commonUtils','mmirf/viewConstants','mmirf/yield','mmirf/storageUtils','mmirf/contentElement','require' ],
//this comment is needed by jsdoc2 [copy of comment for: function Layout(...]
/**
* The Layout class
* The constructor parses the layout and divides them into containers (headerContents, bodyContents, dialogsContents).
*
* @param {String} name
* Name of the Layout (usually the same name as the Layout's controller).
* @param {String} definition
* Layout description, i.e. the raw template code that will be processed.
* May be empty: in this case the processed contents must be
* added manually (cf. parser.StorageUtils)
*
* @requires if param definition is NOT empty: parser.RenderUtils (must be loaded beforehand via <code>require(["mmirf/renderUtils"]...</code>)
*
* @requires if param definition is NOT empty: parser.ParseUtils (must be loaded beforehand via <code>require(["mmirf/parseUtils"]...</code>)
*
* @name Layout
* @class
*/
function(
commonUtils, ViewConstants, YieldDeclaration, storageUtils, ContentElement, require
) {
/** @scope Layout.prototype *///for jsdoc2
//set to @ignore in order to avoid doc-duplication in jsdoc3
/**
* The Layout class
* The constructor parses the layout and divides them into containers (headerContents, bodyContents, dialogsContents).
*
* @constructs Layout
* @param {String} name
* Name of the Layout (usually the same name as the Layout's controller).
* @param {String} definition
* Layout description, i.e. the raw template code that will be processed.
* May be empty: in this case the processed contents must be
* added manually (cf. parser.StorageUtils)
*
* @requires if param <code>definition</code> is NOT empty: parser.RenderUtils (must be loaded beforehand via <code>require(["mmirf/renderUtils"]...</code>)
*
* @requires if param <code>definition</code> is NOT empty: parser.ParseUtils (must be loaded beforehand via <code>require(["mmirf/parseUtils"]...</code>)
*
* @ignore
*/
function Layout(name, definition, remote, ignoreMissingBody){
// console.log("[Layout] initialize '"+name+"'.");
//FIXME MODIFICATIONS for "remote content layout object":
this.remoteaccess = false;
if ((typeof remote !== 'undefined') && (remote == true)){
this.remoteaccess = true;
}
/**
* The definition string of the layout (ehtml-format, taken from assets/www/views/layout/*.ehtml)
*
* @type Object
* @public
*/
this.def = definition? definition.replace(commonUtils.regexHTMLComment, '') : definition;//remove HTML comments!
/**
* The name of the layout.
*
* @type String
* @public
*/
this.name = name;
/**
* This variable holds the contents of the header part of the layout.
*
* @type String
* @public
* @deprecated unused
*/
this.headerContents = '';
/**
* List for extracted & parsed SCRIPT, LINK and STYLE tags
*
* @type Array<Layout.TagElement>
* @public
*/
this.headerElements = [];
/**
* The page / layout title
*
* Will be extracted from <em>definition</em>'s TITLE-tag, if present.
*
* @type String
* @public
*/
this.title = '';
/**
* This variable holds the contents of the body part of the layout.
*
* @type String
* @public
* @deprecated unused
*/
this.bodyContents = "";
/**
* This variable holds the contents of the dialogs part of the layout.
*
* @type String
* @public
*/
this.dialogsContents = '';
/**
* The (parsed) content for the body-container.
*
* @type ContentElement
* @public
*/
this.bodyContentElement = void(0);
/**
* A list holding the content-references (yield declarations)
* for the containers (except for body):
* header, footer, and dialogs
*
* @type Array
* @public
*/
this.yields = [];
/**
* A JSON-like object containing the attributes of the BODY-tag as String values.
*
* For example, for the following BODY-tag:
* <pre>
* <body onload="handleOnLoad()" class = 'some css-classes' >
* </pre>
* the bodyAttributes would be
* <pre>
* {
* "onload": "handleOnLoad()",
* "class": "some css-classes"
* }
* </pre>
*
* @type Object
* @default undefined
* @public
*/
this.bodyAttributes = void(0);
if(this.def){
//console.debug('Layout<constructor>: start rendering layout for "'+this.name+'"'+(remote?' (REMOTE)':'')+', RAW: '+this.def);
var parser = typeof WEBPACK_BUILD !== 'undefined' && WEBPACK_BUILD? __webpack_require__('mmirf/parseUtils') : require('mmirf/parseUtils');
var parseResult = parser.parse(this.def, this);
var renderer = typeof WEBPACK_BUILD !== 'undefined' && WEBPACK_BUILD? __webpack_require__('mmirf/renderUtils') : require('mmirf/renderUtils');
var renderedLayout = renderer.renderLayout(parseResult, null/*FIXME?*/);
//DISABLED: parsing a string as HTML via jQuery etc. does not work (removes head, body,... tags):
// var doc = new DOMParser().parseFromString(renderedLayout, "text/html");
// if(!doc){
// doc = document.implementation.createHTMLDocument('LAYOUT');
// }
// var $layout = $(doc);//$.parseHTML(renderedLayout, doc);
//
// var headerElements = $('head', $layout);
// for(var i=0, size = headerElements.length; i < size; ++i){
// this.headerContents += headerElements[i].outerHTML;
// }
//
// var bodyElement = $('body', $layout);
// this.bodyContents = bodyElement.html();
// var dialogElement = $('dialogs', $layout);
// this.dialogsContents = dialogElement.html();
//TODO remove this (replace with real HTML parser?)
var self = this;
this.markerAttributeName = ViewConstants.REMOTE_RESOURCES_ATTR_NAME;
this.markerAttributeValue = ViewConstants.REMOTE_RESOURCES_ATTR_VALUE;
this.markerUseSingleQuotes = false;//<- set value enclosed in single-quotes (true) or double-quotes (false)
//appends the marker attribute for "signaling"/marking that a
// script/style/link-TAG was parsed&evaluated by this layout object
var addMarkerAttribute = function(strStartOfTag){
return strStartOfTag + ' '
+ self.markerAttributeName + '='
+ (self.markerUseSingleQuotes? '\'': '"')
+ self.markerAttributeValue
+ (self.markerUseSingleQuotes? '\'': '"');
};
//pure HTML:
// (1) removed all HTML comments (via RegExpr)
// (2) removed template comments (via parser/renderer)
var pureHtml = renderedLayout;
var regExprTagContent = //match one of the following (as groups):
'(('+ //match as groups
'('+ //(1) CDATA: this may contain anything, even a closing script-statement
'<!\\[CDATA\\['+ //CDATA open: <![CDATA[
'(.|[\\r\\n])*?'+ //allow anything within CDATA, but match non-greedily...
'\\]\\]>'+ //...for the CDATA-closing statement: ]]>
// (i.e. the first time we encounter this, we stop)
')'+ //close group for CDATA-matching
'|[\\r\\n]'+ //(2) OR line breaks \r and \n (in any combination)
//DISABLED (using . instead!): '|[^<]'+ //(3) OR any symbol that is NOT <
'|.'+ //(4) OR any symbol (REQUIRED for allowing <-symbol within script!
')'+ //close group
'*'+ //match this any number of times (or even none)
'?'+ //do matching non-greedy (i.e. until the next pattern in the RegExpr can be matched the first time)
')'; //close outer group (i.e. one group for ALL content that is matched)
//_non-greedy_ RegExpr for
// * any line-break: \r or \n or a combination of them
// * any other character but < (less-symbol); note that this itself does not include line breaks
var regExprTagInternal = '('+ //open group: match as a group (i.e. give access to the matched content via an index in the RegExpr object)
'[\\r\\n]'+ //line breaks \r and \n
'|'+ //OR
'[^<]'+ //any symbol that is NOT <
')'+ //close group
'*'+ //match this any number of times (or even none)
'?'; //do matching non-greedy (i.e. until the next pattern in the RegExpr can be matched the first time)
//matching: <script some attributes...> some content and '<!CDATA[' with any content allowed </script>
// or: <script some attributes... />
// var regExpScriptTag = /((<script([\r\n]|[^<])*?>)(((<!\[CDATA\[(.|[\r\n])*?\]\]>)|[\r\n]|.)*?)(<\/script>))|(<script([\r\n]|[^<])*?\/>)/igm;// /((<script([\r\n]|[^<])*?>)((<!\[CDATA|[\r\n]|[^<])*?)(<\/script>))|(<script([\r\n]|[^<])*?\/>)/igm;
var strRegExpScriptTag = '((<script'+regExprTagInternal+'>)'+regExprTagContent+'(</script>))'+ //DETECT "normal" script-TAG with optional content
'|(<script'+regExprTagInternal+'/>)'; //OR DETECT "self-closing" script TAG
var regExpScriptTag = new RegExp(strRegExpScriptTag,'igm');
//change to the following RegExpr (change the ones for link/style etc too)
// from
// /((<script([\r\n]|[^<])*?>)(([\r\n]|[^<])*?)(<\/script>))|(<script([\r\n]|[^<])*?\/>)/igm;
// to
// /((<script([\r\n]|[^<])*?>)(((<!\[CDATA\[(.|[\r\n])*?\]\]>)|[\r\n]|.)*?)(<\/script>))|(<script([\r\n]|[^<])*?\/>)/igm
//
// -> this RegExpr additionally
// * respects CDATA (<![CDTATA[ ... ]]>), with any content within its boundaries, even a "closing" </script>-TAG
// * allows opening < within the script-TAGs
// LIMITATIONS: both this and the current one do not allow a < within the script-TAGS attributes, e.g.
// NOT: <script data-condition=" i < 5">
// WORKAROUND: encode the <-symbol, i.e. instead use <script data-condition=" i < 5">
// ==> use "<" or "<" instead of "<" in TAG attributes!
// regExpScriptTag[0]: complete match
// regExpScriptTag[1]: script with start and end tag (if matched)
// regExpScriptTag[4]: TEXT content of script-tag (if present/matched)
// regExpScriptTag[9]: self-closing script (if matched)
var matchScriptTag = null;
self.headerContents = '';
var removedScriptAndLinkHmtl = new Array();
// var matchIndex;
while(matchScriptTag = regExpScriptTag.exec(pureHtml)){
// matchIndex = matchScriptTag[1] ? 1 : (matchScriptTag[9]? 9 : -1);
if(matchScriptTag[0]){//matchIndex != -1){
// console.warn("Remote: " + self.remoteaccess);
if (self.remoteaccess) {
// self.headerContents += matchScriptTag[0].replace("<script", "<script loc=\"remote\"");//[matchIndex];
self.headerContents += addMarkerAttribute('<script') + matchScriptTag[0].substring('<script'.length);
} else {
self.headerContents += matchScriptTag[0];
}
//remove script tag, and continue search
// pureHtml = pureHtml.substring(0,matchScriptTag.index) + pureHtml.substring(matchScriptTag.index + matchScriptTag[0].length);// pureHtml.replace(matchScriptTag[matchIndex], '');
removedScriptAndLinkHmtl.push({start: matchScriptTag.index, end: matchScriptTag.index + matchScriptTag[0].length});
self.headerElements.push(new Layout.TagElement(matchScriptTag[2] || matchScriptTag[9], matchScriptTag[4], 'SCRIPT'));
}
}
//matching: <link some attributes...> some content and '<!CDATA[' with any content allowed </link>
// or: <link some attributes... />
// var regExpLinkTag = /((<link([\r\n]|[^<])*?>)(((<!\[CDATA\[(.|[\r\n])*?\]\]>)|[\r\n]|.)*?)(<\/link>))|(<link([\r\n]|[^<])*?\/>)/igm;
var strRegExpLinkTag = '((<link'+regExprTagInternal+'>)'+regExprTagContent+'(</link>))'+ //DETECT "normal" script-TAG with optional content
'|(<link'+regExprTagInternal+'/>)'; //OR DETECT "self-closing" script TAG
var regExpLinkTag = new RegExp(strRegExpLinkTag,'igm');
// regExpLinkTag[0]: complete match
// regExpLinkTag[1]: link with start and end tag (if matched)
// regExpLinkTag[4]: TEXT content of link-tag (if present/matched)
// regExpLinkTag[9]: self-closing link (if matched)
var matchLinkTag = null;
while(matchLinkTag = regExpLinkTag.exec(pureHtml)){
// console.warn("Matchlinktag: " + matchLinkTag[0]);
if(matchLinkTag[0]){
// console.warn("Remote: " + self.remoteaccess);
if (self.remoteaccess) {
// self.headerContents += matchLinkTag[0].replace("<link", "<link loc=\"remote\"");
self.headerContents += addMarkerAttribute('<link') + matchLinkTag[0].substring('<link'.length);
} else {
self.headerContents += matchLinkTag[0];
}
removedScriptAndLinkHmtl.push({start: matchLinkTag.index, end: matchLinkTag.index + matchLinkTag[0].length});
self.headerElements.push(new Layout.TagElement(matchLinkTag[2] || matchLinkTag[9], matchLinkTag[4], 'LINK'));
}
}
//matching: <style type="text/css" some attributes...> some content and '<!CDATA[' with any content allowed </style>
// var regExpStyleTag = /((<style([\r\n]|[^<])*?type="text\/css"([\r\n]|[^<])*?>)(((<!\[CDATA\[(.|[\r\n])*?\]\]>)|[\r\n]|.)*?)(<\/style>))/igm;
var strRegExpStyleTag = '((<style'+regExprTagInternal+'>)'+regExprTagContent+'(</style>))'; //DETECT only "normal" style-TAG with content
var regExpStyleTag = new RegExp(strRegExpStyleTag,'igm');
// regExpStyleTag[0]: complete match
// regExpStyleTag[1]: script with start and end tag (if matched)
// regExpStyleTag[4]: TEXT content of style-tag (if present/matched)
var matchStyleTag = null;
while(matchStyleTag = regExpStyleTag.exec(pureHtml)){
// matchIndex = matchStyleTag[1] ? 1 : -1;
if(matchStyleTag[0]){//matchIndex != -1){
// console.warn("Remote: " + self.remoteaccess);
if (self.remoteaccess) {
// self.headerContents += matchStyleTag[0].replace("<style", "<style loc=\"remote\"");//[matchIndex];
self.headerContents += addMarkerAttribute('<style') + matchStyleTag[0].substring('<style'.length);
} else {
self.headerContents += matchStyleTag[0];
}
//remove script tag, and continue search
// pureHtml = pureHtml.substring(0,matchStyleTag.index) + pureHtml.substring(matchStyleTag.index + matchStyleTag[0].length);// pureHtml.replace(matchStyleTag[matchIndex], '');
removedScriptAndLinkHmtl.push({start: matchStyleTag.index, end: matchStyleTag.index + matchStyleTag[0].length});
self.headerElements.push(new Layout.TagElement(matchStyleTag[2], matchStyleTag[4], 'STYLE'));
}
}
//only need to "process" removed script/link tags, if some were found:
if(removedScriptAndLinkHmtl.length > 0){
removedScriptAndLinkHmtl.sort(function(a,b){
return a.start - b.start;
});
var cleanedHtml = new Array();
var remPos = 0;
var removalElement = removedScriptAndLinkHmtl[0];
for(var i=0, size = removedScriptAndLinkHmtl.length; i < size; ++i){
removalElement = removedScriptAndLinkHmtl[i];
var text = pureHtml.substring(remPos, removalElement.start);
cleanedHtml.push(text);
remPos = removalElement.end;
}
//add rest of the HTML if necessary
if(removalElement.end < pureHtml.length){
cleanedHtml.push(pureHtml.substring(removalElement.end));
}
//replace HTML with the removed/clean version:
pureHtml = cleanedHtml.join('');
}
//TODO this is needed my be of interest for further processing
// (for processing partial HTML responses)
//-> should this be part of the framework? (i.e. "public" property for Layout; TODO add to stringify()?)
this._processedDef = pureHtml;
//FIXME reg-expr does not detect body-TAG, if body has no content (i.e. body="<body></body>")
var regExpBodyTag = /(<body([\r\n]|.)*?>)(([\r\n]|.)*?)(<\/body>)/igm;
// matchBodyTag[0]: complete match
// matchBodyTag[1]: body start tag
// matchBodyTag[2]: last CHAR within body start tag, before closing, e.g. "...lskdjf>" -> "f"
// matchBodyTag[3]: body text content
// matchBodyTag[4]: last CHAR within body text content, before closing, e.g. "...lsk</body>" -> "k"
// matchBodyTag[5]: body end tag
var matchBodyTag = regExpBodyTag.exec(pureHtml);
self.bodyContents = '';
if(matchBodyTag && matchBodyTag[3]){
self.bodyContents += matchBodyTag[3];
}
else if(!ignoreMissingBody) {
//TODO throw error?
console.error('Layout.<constructor>: Layout template does not contain a <body> element!');
}
//TEST: experimental -> "remember" attributes of body tag
//NOTE this assumes that matchBodyTag-RegExpr starts with: /(<body([\r\n]|.)*?>) ...
if(matchBodyTag && matchBodyTag[1] && matchBodyTag[1].length > '<body>'.length){
// //NOTE: 1st case should really never occur.
// var reTagSelfClose = /\/>$/;
// var bodyAttrEnd = reTagSelfClose.test(matchBodyTag[1])? matchBodyTag[1].length-2 : matchBodyTag[1].length-1;
// var bodyAttr = '<div ' + matchBodyTag[1].substring('<body'.length, bodyAttrEnd) + '</div>';
// bodyAttr = jQuery(bodyAttr);
self.bodyAttributes = Layout.getTagAttr(matchBodyTag[1]);
}
//Extract title-tag
var regExpTitleTag = /(<title([\r\n]|.)*?>)(([\r\n]|.)*?)(<\/title>)/igm;
// matchTitleTag[0]: complete match
// matchTitleTag[1]: title start tag
// matchTitleTag[2]: last CHAR within title start tag, before closing, e.g. "...lskdjf>" -> "f"
// matchTitleTag[3]: title text content
// matchTitleTag[4]: last CHAR within title text content, before closing, e.g. "...lsk</title>" -> "k"
// matchTitleTag[5]: title end tag
var matchTitleTag = regExpTitleTag.exec(pureHtml);
if(matchTitleTag && matchTitleTag[3]){
self.title = matchTitleTag[3];
}
var regExpDialogsTag = /(<dialogs([\r\n]|.)*?>)(([\r\n]|.)*?)(<\/dialogs>)/igm;
// matchDialogsTag[0]: complete match
// matchDialogsTag[1]: dialogs start tag
// matchDialogsTag[2]: last CHAR within dialogs start tag, before closing, e.g. "...lskdjf>" -> "f"
// matchDialogsTag[3]: dialogs text content
// matchDialogsTag[4]: last CHAR within dialogs text content, before closing, e.g. "...lsk</dialogs>" -> "k"
// matchDialogsTag[5]: dialogs end tag
var matchDialogsTag = regExpDialogsTag.exec(pureHtml);
self.dialogsContents = '';
if(matchDialogsTag && matchDialogsTag[3]){
self.dialogsContents += matchDialogsTag[3];
}
var parseBodyResult = new ContentElement({name: this.name, content: this.bodyContents}, this, parser, renderer);// parser.parse(this.bodyContents, this);
// for(var i=0, size = parseBodyResult.yields.length; i < size ; ++i){
// this.yields.push(new YieldDeclaration(parseBodyResult.yields[i], ViewConstants.CONTENT_AREA_BODY));
// }
// parseBodyResult.yields = void(0);
var all = parseBodyResult.allContentElements.concat(parseBodyResult.yields);
all.sort(function(parsedElem1, parsedElem2){
return parsedElem1.getStart() - parsedElem2.getStart();
});
parseBodyResult.allContentElements = all;
parseBodyResult.getController = function(){ return {//FIXME
name: null,
getName: function(){
return this.name;
}
}};
this.bodyContentElement = parseBodyResult;
var parseDialogResult = parser.parse(this.dialogsContents, this);
for(var i=0, size = parseDialogResult.yields.length; i < size ; ++i){
this.yields.push(new YieldDeclaration(parseDialogResult.yields[i], ViewConstants.CONTENT_AREA_DIALOGS));
}
}//END: if(this.def)
}//END: Layout()
/**
* HELPER: extracts TAG attributes into an JSON-object
*
* @memberOf Layout
* @private
* @static
*
* @param {String} str
* the start-TAG as String
* @param {Object} [target] OPTIONAL
* the target-object to which the extracted attributes will be attached
* if omitted, a new, empty object will be created
*
* @return {Object} the object with the extracted attributes as properties
* (if <em>target</em> was provided, then this is the <em>target</em> object)
*
* @example
* e.g. <body onload="on_load();" class = 'biggestFont'>
* -->
* {"onload": "on_load()", "class": "biggestFont"}
*
*/
Layout.getTagAttr = function(str, target){
//RegExp for:
// name = "..."
//or
// name = '...'
//
//NOTE: the RegExp does not extract "single properties", as e.g. <tag required>
// ... instead, for extraction, they must be specified as follows: <tag required="...">
//NOTE: values MUST be enclosed in double-quotes or quotes, "quote-less" attribute values cannot be extracted!
// ... e.g. NOT: <tag name=value>, instead: <tag name="value"> or <tag name='value'>
//NOTE: the RegExp also detects escaped double-quotes and quotes respectively
var regExpr = /\s+([^=]*?)\s*=\s*(("((\\"|[^"])*)")|('((\\'|[^'])*)'))/igm;
var result = target || {};
var match;
while(match = regExpr.exec(str)){
if(match[4]){
result[match[1]] = match[4];
}
else if(match[7]){
result[match[1]] = match[7];
}
}
return result;
};
/**
* HELPER class: extract raw TAG Strings into a property-object
*
* @public
* @constructor
* @param {String} tag
* the start TAG
* @param {String} content
* the TEXT content of the TAG (may be empty)
* @param {String} tagType
* the TAG type, e.g. "SCRIPT"
*
* @returns {Layout.TagElement}
*
* prop {String} tagName: the TAG type, e.g. "SCRIPT"
* prop {String} textContent: the TEXT content of the TAG (may be an empty String)
* prop EXTRACTED ATTRIBUTES: the extracted attributes form the start-TAG
*
* func {String} attr(STRING name): returns the attribute-value for name (may be undefined)
* func {String} html(): returns the TEXT content of the TAG (may be an empty String)
*
* func {Boolean} isScript(): returns TRUE if tagType is SCRIPT
* func {Boolean} isStyle(): returns TRUE if tagType is STYLE
* func {Boolean} isLink(): returns TRUE if tagType is LINK
*/
Layout.TagElement = function TagElement(tag, content, tagType){
/** the TAG type, e.g. "SCRIPT" */
this.tagName = tagType;
/** the TEXT content of the TAG (may be an empty String) */
this.textContent = content || '';
var tis = this;
// tis.attr = function(name){
// return this[name];
// };
// tis.html = function(){
// return this.textContent;
// };
// tis.isScript = function(){return this.tagName === 'SCRIPT';};
// tis.isStyle = function(){return this.tagName === 'STYLE'; };
// tis.isLink = function(){return this.tagName === 'LINK'; };
//extract attributes as properties from TAG string:
Layout.getTagAttr(tag, tis);
return tis;
};
/**
* Prototype for TagElement
*
* func {String} attr(STRING name): returns the attribute-value for name (may be undefined)
* func {String} html(): returns the TEXT content of the TAG (may be an empty String)
*
* func {Boolean} isScript(): returns TRUE if tagType is SCRIPT
* func {Boolean} isStyle(): returns TRUE if tagType is STYLE
* func {Boolean} isLink(): returns TRUE if tagType is LINK
*
* @augments Layout.TagElement#
*/
Layout.TagElement.prototype = {
/**
* @param {String} name the attribute name
* @returns {any} the attribute-value for name (may be undefined)
*/
attr: function(name){
return this[name];
},
/** @returns {String} the TEXT content of the TAG (may be an empty String) */
html: function(){
return this.textContent;
},
/** @returns {Boolean} returns TRUE if tagType is SCRIPT */
isScript: function(){return this.tagName === 'SCRIPT';},
/** @returns {Boolean} returns TRUE if tagType is STYLE */
isStyle: function(){return this.tagName === 'STYLE'; },
/** @returns {Boolean} returns TRUE if tagType is LINK */
isLink: function(){return this.tagName === 'LINK'; }
};
/**
* This methods returns an associative array holding the contents of the different containers: header, body, footer and dialogs.
*
* @function
* @returns {Array} An associative array holding the contents of the different containers: header, body, footer and dialogs
* @public
*/
Layout.prototype.getYields = function(){
return this.yields;
};
/**
* This methods returns the contents of the header part of the layout.
*
* @function
* @returns {String} The contents of the header part of the layout
* @public
*/
Layout.prototype.getHeaderContents = function(){
return this.headerContents;
};
/**
* This methods returns the contents of the dialog part of the layout.
*
* @function
* @returns {String} The contents of the dialog part of the layout
* @public
*/
Layout.prototype.getDialogsContents = function(){
return this.dialogsContents;
};
/**
* This methods returns the contents of the body part of the layout.
*
* @function
* @returns {String} The contents of the body part of the layout
* @public
*/
Layout.prototype.getBodyContents = function(){
return this.bodyContents;
};
/**
* Gets the name of the layout.
*
* @function
* @returns {String} The name of the layout.
* @public
*/
Layout.prototype.getName = function(){
return this.name;
};
/**
* HELPER: add prototype functions of Layout.TagElement to the #headerElements
*
* @function
* @protected
*/
Layout.prototype._extHeaderElements = function(){
var prot = Layout.TagElement.prototype;
var funcs = Object.keys(prot);
var len = funcs.length -1;
var i, j, elem, fname;
for(i = this.headerElements.length-1; i >= 0; --i){
elem = this.headerElements[i];
for(j = len; j >= 0; --j){
fname = funcs[j];
elem[fname] = prot[fname];
}
}
};
Layout.prototype.stringify = function(){
// "plain properties" list
var propList = [
'name',
'remoteaccess',
'def',
'headerElements',
'headerContents',
'title',
// 'bodyContents', //DISABLED: store in this.bodyContentElement.definition now
'dialogsContents',
'markerAttributeName',
'markerAttributeValue',
'markerUseSingleQuotes',
'bodyAttributes'
];
//stringify-able properties
var stringifyPropList = [
'bodyContentElement' //element type: ContentElement (stringify-able)
];
//complex Array-properties
var arrayPropList = [
'yields' //element type: YieldDeclaration (stringify-able)
];
//function for iterating over the property-list and generating JSON-like entries in the string-buffer
var appendStringified = storageUtils.appendStringified;
var moduleNameString = '"'+this.name+'Layout"';
var sb = [storageUtils.STORAGE_CODE_WRAP_PREFIX, 'require("mmirf/storageUtils").restoreObject({ classConstructor: "mmirf/layout"', ','];
appendStringified(this, propList, sb);
//NOTE the use of require() here, assumes that the dependency has already been loaded (i.e. has already been request by some other module!)
sb.push( 'initPublish: function(){ this._extHeaderElements(); this.bodyContents=this.bodyContentElement.definition; require("mmirf/presentationManager").addLayout(this); }');
sb.push(',');
//non-primitives properties with stringify() function:
appendStringified(this, stringifyPropList, sb, null, function stringifyValueExtractor(name, obj){
return obj.stringify();
});
//non-primitives array-properties with stringify() function:
appendStringified(this, arrayPropList, sb, null, function arrayValueExtractor(name, arrayValue){
var buf =['['];
for(var i=0, size = arrayValue.length; i < size; ++i){
buf.push(arrayValue[i].stringify());
buf.push(',');
}
//remove last comma
if(arrayValue.length > 0){
buf.splice( buf.length - 1, 1);
}
buf.push(']');
return buf.join('');
});
//if last element is a comma, remove it
if(sb[sb.length - 1] === ','){
sb.splice( sb.length - 1, 1);
}
//TODO use requirejs mechanism? (see remark above)
// sb.push(' }, true); });\n require(['//<- add require-call, so that this JS-file adds itself to the loaded dependencies in requirejs
// + moduleNameString + ']);');
sb.push(' }, true, '+storageUtils.STORAGE_FILE_FORMAT_NUMBER+');');
sb.push(storageUtils.STORAGE_CODE_WRAP_SUFFIX);
return sb.join('');
};
return Layout;
});
|
document.write('<a href="http://www.guilin.com"><img src="docs/images/asd/2010/3.jpg" width="200" height="120" alt="广告"></a>'); |
angular.module('sprite', [
'ngAnimate',
'ngRoute',
'ngResource',
'ui.bootstrap',
'angularFileUpload',
'checklist-model'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/cssSprite', {
controller: 'cssSpriteCtrl',
templateUrl: 'views/cssSprite.html'
})
.otherwise({
redirectTo: '/cssSprite'
});
}]);
|
module.exports = function(lang) {
return require('./'+lang);
}; |
import stackElements from './stack-elements';
import createStackElements from './create-stack-elements';
export default function stack(elements) {
stackElements(createStackElements(elements), "x", "y", "width");
}
//# sourceMappingURL=stack.js.map
|
/**
* Lo-Dash 2.3.0 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize underscore exports="node" -o ./underscore/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
var baseIsEqual = require('../internals/baseIsEqual');
/**
* Performs a deep comparison between two values to determine if they are
* equivalent to each other. If a callback is provided it will be executed
* to compare values. If the callback returns `undefined` comparisons will
* be handled by the method instead. The callback is bound to `thisArg` and
* invoked with two arguments; (a, b).
*
* @static
* @memberOf _
* @category Objects
* @param {*} a The value to compare.
* @param {*} b The other value to compare.
* @param {Function} [callback] The function to customize comparing values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'name': 'fred' };
* var copy = { 'name': 'fred' };
*
* object == copy;
* // => false
*
* _.isEqual(object, copy);
* // => true
*
* var words = ['hello', 'goodbye'];
* var otherWords = ['hi', 'goodbye'];
*
* _.isEqual(words, otherWords, function(a, b) {
* var reGreet = /^(?:hello|hi)$/i,
* aGreet = _.isString(a) && reGreet.test(a),
* bGreet = _.isString(b) && reGreet.test(b);
*
* return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
* });
* // => true
*/
function isEqual(a, b) {
return baseIsEqual(a, b);
}
module.exports = isEqual;
|
(function(){
'use strict';
console.log('Hello world with AngularJS');
})(); |
// generated on 2017-05-11 using generator-chrome-extension 0.6.1
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import del from 'del';
import runSequence from 'run-sequence';
import {stream as wiredep} from 'wiredep';
const $ = gulpLoadPlugins();
gulp.task('extras', () => {
return gulp.src([
'app/*.*',
'app/_locales/**',
'!app/*.json',
'!app/*.html',
], {
base: 'app',
dot: true
}).pipe(gulp.dest('dist'));
});
function lint(files, options) {
return () => {
return gulp.src(files)
.pipe($.eslint(options))
.pipe($.eslint.format());
};
}
gulp.task('lint', lint('app/scripts/**/*.js', {
env: {
es6: false
},
rules: {
'quotes': 0
}
}));
gulp.task('images', () => {
return gulp.src('app/images/**/*')
.pipe($.if($.if.isFile, $.cache($.imagemin({
progressive: true,
interlaced: true,
// don't remove IDs from SVGs, they are often used
// as hooks for embedding and styling
svgoPlugins: [{cleanupIDs: false}]
}))
.on('error', function (err) {
console.log(err);
this.end();
})))
.pipe(gulp.dest('dist/images'));
});
gulp.task('html', () => {
return gulp.src('app/*.html')
.pipe($.useref({searchPath: ['.tmp', 'app', '.']}))
.pipe($.sourcemaps.init())
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', $.cleanCss({compatibility: '*'})))
.pipe($.sourcemaps.write())
.pipe($.if('*.html', $.htmlmin({removeComments: true, collapseWhitespace: true})))
.pipe(gulp.dest('dist'));
});
gulp.task('chromeManifest', () => {
return gulp.src('app/manifest.json')
.pipe($.chromeManifest({
buildnumber: true,
}))
.pipe($.if('*.css', $.cleanCss({compatibility: '*'})))
.pipe($.if('*.js', $.sourcemaps.init()))
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.js', $.sourcemaps.write('.')))
.pipe(gulp.dest('dist'));
});
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));
gulp.task('watch', ['lint'], () => {
$.livereload.listen();
gulp.watch([
'app/*.html',
'app/scripts/**/*.js',
'app/images/**/*',
'app/styles/**/*',
'app/_locales/**/*.json'
]).on('change', $.livereload.reload);
gulp.watch('app/scripts/**/*.js', ['lint']);
gulp.watch('bower.json', ['wiredep']);
});
gulp.task('size', () => {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('wiredep', () => {
gulp.src('app/*.html')
.pipe(wiredep({
ignorePath: /^(\.\.\/)*\.\./
}))
.pipe(gulp.dest('app'));
});
gulp.task('package', function () {
var manifest = require('./dist/manifest.json');
return gulp.src('dist/**')
.pipe($.zip('Trackit-' + manifest.version + '.zip'))
.pipe(gulp.dest('package'));
});
gulp.task('build', (cb) => {
runSequence(
'lint', 'chromeManifest',
['html', 'images', 'extras'],
'size', cb);
});
gulp.task('default', ['clean'], cb => {
runSequence('build', cb);
});
|
/*!
* Start Bootstrap - Creative Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
(function($) {
"use strict"; // Start of use strict
// jQuery for page scrolling feature - requires jQuery Easing plugin
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 51
})
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
// Fit Text Plugin for Main Header
$("h1").fitText(
1.2, {
minFontSize: '35px',
maxFontSize: '65px'
}
);
// Offset for Main Navigation
$('#mainNav').affix({
offset: {
top: 51
}
})
// Initialize WOW.js Scrolling Animations
new WOW().init();
})(jQuery); // End of use strict
|
import external from '../../externalModules.js';
import { xhrRequest } from '../internal/index.js';
/**
* This object supports loading of DICOM P10 dataset from a uri and caching it so it can be accessed
* by the caller. This allows a caller to access the datasets without having to go through cornerstone's
* image loader mechanism. One reason a caller may need to do this is to determine the number of frames
* in a multiframe sop instance so it can create the imageId's correctly.
*/
let cacheSizeInBytes = 0;
let loadedDataSets = {};
let promises = {};
// returns true if the wadouri for the specified index has been loaded
function isLoaded(uri) {
return loadedDataSets[uri] !== undefined;
}
function get(uri) {
if (!loadedDataSets[uri]) {
return;
}
return loadedDataSets[uri].dataSet;
}
// loads the dicom dataset from the wadouri sp
function load(uri, loadRequest = xhrRequest, imageId) {
const { cornerstone, dicomParser } = external;
// if already loaded return it right away
if (loadedDataSets[uri]) {
// console.log('using loaded dataset ' + uri);
return new Promise(resolve => {
loadedDataSets[uri].cacheCount++;
resolve(loadedDataSets[uri].dataSet);
});
}
// if we are currently loading this uri, increment the cacheCount and return its promise
if (promises[uri]) {
// console.log('returning existing load promise for ' + uri);
promises[uri].cacheCount++;
return promises[uri];
}
// This uri is not loaded or being loaded, load it via an xhrRequest
const loadDICOMPromise = loadRequest(uri, imageId);
// handle success and failure of the XHR request load
const promise = new Promise((resolve, reject) => {
loadDICOMPromise
.then(function(dicomPart10AsArrayBuffer /* , xhr*/) {
const byteArray = new Uint8Array(dicomPart10AsArrayBuffer);
// Reject the promise if parsing the dicom file fails
let dataSet;
try {
dataSet = dicomParser.parseDicom(byteArray);
} catch (error) {
return reject(error);
}
loadedDataSets[uri] = {
dataSet,
cacheCount: promise.cacheCount,
};
cacheSizeInBytes += dataSet.byteArray.length;
resolve(dataSet);
cornerstone.triggerEvent(cornerstone.events, 'datasetscachechanged', {
uri,
action: 'loaded',
cacheInfo: getInfo(),
});
}, reject)
.then(
() => {
// Remove the promise if success
delete promises[uri];
},
() => {
// Remove the promise if failure
delete promises[uri];
}
);
});
promise.cacheCount = 1;
promises[uri] = promise;
return promise;
}
// remove the cached/loaded dicom dataset for the specified wadouri to free up memory
function unload(uri) {
const { cornerstone } = external;
// console.log('unload for ' + uri);
if (loadedDataSets[uri]) {
loadedDataSets[uri].cacheCount--;
if (loadedDataSets[uri].cacheCount === 0) {
// console.log('removing loaded dataset for ' + uri);
cacheSizeInBytes -= loadedDataSets[uri].dataSet.byteArray.length;
delete loadedDataSets[uri];
cornerstone.triggerEvent(cornerstone.events, 'datasetscachechanged', {
uri,
action: 'unloaded',
cacheInfo: getInfo(),
});
}
}
}
export function getInfo() {
return {
cacheSizeInBytes,
numberOfDataSetsCached: Object.keys(loadedDataSets).length,
};
}
// removes all cached datasets from memory
function purge() {
loadedDataSets = {};
promises = {};
}
export default {
isLoaded,
load,
unload,
getInfo,
purge,
get,
};
|
/* */
module.exports = LinkReader;
var fs = require('graceful-fs');
var inherits = require('inherits');
var Reader = require('./reader');
inherits(LinkReader, Reader);
function LinkReader(props) {
var self = this;
if (!(self instanceof LinkReader)) {
throw new Error('LinkReader must be called as constructor.');
}
if (!((props.type === 'Link' && props.Link) || (props.type === 'SymbolicLink' && props.SymbolicLink))) {
throw new Error('Non-link type ' + props.type);
}
Reader.call(self, props);
}
LinkReader.prototype._stat = function(currentStat) {
var self = this;
fs.readlink(self._path, function(er, linkpath) {
if (er)
return self.error(er);
self.linkpath = self.props.linkpath = linkpath;
self.emit('linkpath', linkpath);
Reader.prototype._stat.call(self, currentStat);
});
};
LinkReader.prototype._read = function() {
var self = this;
if (self._paused)
return;
if (!self._ended) {
self.emit('end');
self.emit('close');
self._ended = true;
}
};
|
(function(){
'use strict';
spoti.service('Tabs',
['GlobalFilter', '$emit', Tabs]);
function Tabs(GlobalFilter, $emit) {
var self = this;
this.tabs = [];
this.state = {selectedIndex: 0};
this.select = function(i) {
self.mute_current_tab();
var current_tab = self.tabs[i];
if (current_tab.type != 'tracks')
GlobalFilter.remove_tag(current_tab.type, false);
self.load_tab(current_tab);
$emit('tab_changed', current_tab);
return current_tab;
};
musicTab('Playlists', 'playlists', [
{name: 'Name', field: 'name', default: true},
{name: 'Followers', field: 'followers', reverse: true},
{name: 'Total tracks', field: 'total', reverse: true}
]);
musicTab('Artists', 'artists', [
{name: 'Name', field: 'name', default: true},
{name: 'Total tracks', field: 'tracks', reverse: true}
]);
musicTab('Tracks', 'tracks', [
{name: 'Name', field: 'name'},
{name: 'Playlist order', field: 'idx', default: true}
]);
musicTab('Albums', 'albums', [
{name: 'Name', field: 'name', default: true},
{name: 'Total tracks', field: 'tracks', reverse: true}
]);
musicTab('Countries report', 'report', [
{name: 'Missing tracks', field: 'missing_tracks', default: true}
]);
function musicTab(title, type, arrange_options) {
var tab = {
title: title,
type: type,
fields: {name: ''}
};
var arrange_by;
arrange_options.forEach(function(o){
if (o.default == true) arrange_by = o.field;
});
tab.filter = {
arrange_by: arrange_by,
reverse: false,
limit:30,
arrange_options: arrange_options,
limit_options: [30, 100, 300, 1000]
};
self.tabs.push(tab);
}
}
})(); |
Template.abstract_input.helpers({
atts() {
return this.atts;
},
name() {
this.atts.name;
},
hasLabel() {
return !!this.label;
},
label() {
return this.label;
},
isRequired() {
return !!this.atts.required;
}
}); |
function PageNav (el, options) {
var $container = $(el),
$target = $('<ul class="pages">'),
$window = $(window),
pageElements = [],
currentContents,
currentIndex = 0,
noImages,
reader;
$container.append($target);
if (options.reader) {
reader = options.reader;
$target.on('click', 'a', function (ev) {
ev.preventDefault();
ev.stopImmediatePropagation();
var index = $(this).data('index');
if (!options.readerNav) reader.show(currentContents);
// we need to wait until Safari knows the height of the indiviual pages.
window.setTimeout(function () { reader.goTo(index); }, 1);
});
$(options.reader).on('reader:pagechange', function (ev, index) {
try {
pageElements[currentIndex].removeClass('active');
var $el = pageElements[index];
$el.addClass('active');
// make sure the element remains within view
var top = $el.position().top, height = $el.height();
if (top + height > $window.height()) {
var $parent = $target.parent(), s = $parent.scrollTop();
$parent.scrollTop(s + top - $window.height() + height);
} else if (top < 0) {
var $parent = $target.parent();
$parent.scrollTop($parent.scrollTop() + top);
}
}
catch (e) {
}
currentIndex = index;
});
}
function pageElement (pgNumber, index) {
var $li = $('<li>');
$li.html('<span class="page-number">'+pgNumber+'</span>');
if (!noImages) {
var $img = $('<img>'),
$a = $('<a>');
$img.attr({
src: H.imgSrc(pgNumber, true),
alt: '' + pgNumber
});
$a.attr('href', '#reader-'+pgNumber);
$a.data('index', index);
$a.append($img);
$li.append($a);
}
pageElements.push($li);
return $li;
}
this.update = function (contents, argNoImages) {
$container.addClass('result');
currentContents = contents;
noImages = !!argNoImages;
$('h2').text(contents[0]);
this.clear();
contents[1].forEach(function (page, index) { $target.append(pageElement(page, index)); });
}
this.clear = function () {
$container.addClass('empty');
$target.empty();
pageElements = [];
currentIndex = 0;
}
}
|
import { applyMiddleware, createStore, compose } from "redux"
import logger from "redux-logger"
import thunk from "redux-thunk"
import promise from "redux-promise-middleware"
// import { composeWithDevTools } from 'redux-devtools-extension';
import reducer from "./reducers"
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const middleware = applyMiddleware(promise(), thunk, logger())
export default createStore(
reducer, composeEnhancers(middleware)
)
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import App from './components/App';
import Login from './components/Login';
import LOG_IN_KEY from './consts/consts';
import { hasLocalStorageItem } from './utils/localStorageUtils';
import TodoList from './components/TodoList';
function requireAuth(nextState, replace) {
if (!hasLocalStorageItem(LOG_IN_KEY)) {
replace('/login');
}
}
const rootEl = document.getElementById('app');
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="/login" component={Login} />
<Route path="/todo" component={TodoList} onEnter={requireAuth}>
<Router name="todo" path="/todo/:filter" component={TodoList} />
</Route>
</Route>
</Router>
), rootEl);
|
'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var mkdirp = require('mkdirp');
var path = require('path');
module.exports = yeoman.generators.Base.extend({
prompting: function() {
var done = this.async();
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the great ' + chalk.red('gulp-typescript-sass') + ' generator! ' +
'This will set up an empty project with Gulp, Typescript and Sass. I will also add ' +
'VSCode settings. For debugging I suggest you install the VSCode Chrome Debugger. ' +
chalk.yellow('Have fun!')
));
this.log('You can find the VSCode Chrome Debugger at:');
this.log(chalk.cyan('https://github.com/Microsoft/vscode-chrome-debug'));
this.log();
// var prompts = [{
// type: 'confirm',
// name: 'someOption',
// message: 'Would you like to enable this option?',
// default: true
// }];
var prompts = [{
type: 'input',
name: 'name',
message: 'How do you want to name your project',
default: this.appname
}, {
type: 'input',
name: 'author',
message: 'What is your name',
default: 'Maurits Elbers <magicmau@gmail.com>'
}, {
type: 'input',
name: 'license',
message: 'What license shall we put on it',
default: 'UNLICENSED'
}, {
type: 'confirm',
name: 'disableChromeSessionRestore',
message: 'Disable session restore warning when debugging in Chrome',
default: true
}]
this.prompt(prompts, function(props) {
this.props = props;
// To access props later use this.props.someOption;
done();
}.bind(this));
},
writing: function() {
var tpls = ['_package.json', '_bower.json'];
tpls.forEach(function(element) {
this.fs.copyTpl(this.templatePath(element), this.destinationPath(element.replace("_", "")), this.props);
}, this);
this.fs.copy(this.templatePath('gulpfile.js'), this.destinationPath('gulpfile.js'));
var dirs = ['.vscode', 'app', 'app/css', 'app/fonts', 'app/images', 'app/js', 'app/scss', 'app/ts', 'dist', 'bower_components']
dirs.forEach(function(dir) {
mkdirp.sync(path.join(this.destinationPath(), dir));
this.directory(dir, dir);
}, this);
},
install: function() {
this.installDependencies();
}
});
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'removeformat', 'eo', {
toolbar: 'Forigi Formaton'
} );
|
export function numbers() {
return [ 0, -0, 1, -1, 1.1, -1.1, Infinity, -Infinity ]
}
export function numberObjects({ Object: _Object }) {
return [ _Object(0), _Object(-0), _Object(1), _Object(-1), _Object(1.1), _Object(-1.1), _Object(Infinity), _Object(-Infinity)]
}
|
$(document).ready(function(){
console.log("It's ready");
}); |
var bleno = require('bleno');
var BlenoPrimaryService = bleno.PrimaryService;
var DeviceInformationService = require('./device-information-service');
var deviceInformationService = new DeviceInformationService();
console.log('SPARK - Smart meter');
bleno.on('stateChange', function(state) {
console.log('on -> stateChange: ' + state);
if (state === 'poweredOn') {
console.log("on -> Smart meter is ready, let's start advertising!");
bleno.startAdvertising('smart-meter', ['ec00']);
}
else {
if(state === 'unsupported'){
console.log("NOTE: BLE and Bleno configurations not enabled on board, see README.md for more details...");
}
bleno.stopAdvertising();
}
});
bleno.on('advertisingStart', function(error) {
console.log('on -> advertisingStart: ' + (error ? 'error ' + error : 'success'));
if (!error) {
bleno.setServices([
deviceInformationService
]);
}
});
bleno.on('accept', function(clientAddress) {
console.log("Accepted Connection with Client Address: " + clientAddress);
});
bleno.on('disconnect', function(clientAddress) {
console.log("Disconnected Connection with Client Address: " + clientAddress);
}); |
#!/usr/bin/env node
const axios = require('axios');
const itemHash = 'M4A1-S%20%7C%20Hot%20Rod%20%28Factory%20New%29';
const getApiUrl = (start, end) => `http://steamcommunity.com/market/listings/730/${itemHash}/render?start=${start}&count=${end}¤cy=23&language=english`;
(async () => {
const res = await axios.get(getApiUrl(100, 100));
const listings = res.data.listinginfo;
console.log(Object.keys(listings).length);
})();
|
'use strict'
var utils = require('../utils')
/**
* Distribute events within canvas.
*
* - No events may visually overlap.
* - If two events collide in time, they MUST have the same width.
* This is an invariant. Call this width W.
* - W should be the maximum value possible without breaking the previous invariant.
*
* @param {Array} events
* @param {Canvas} canvas
* @return {Array} events
*/
module.exports = function (events, canvas) {
function setStyle(column, nr, columns) {
var width = canvas.getContentWidth() / columns.length
column.forEach(function (event) {
var top = utils.minToY(event.start)
var height = utils.minToY(event.end) - top
event.setStyle({
width: width + 'px',
height: height + 'px',
top: top + 'px',
left: nr * width + 'px'
})
})
}
createGroups(events).forEach(function (group) {
createColumns(group).forEach(setStyle)
})
return events
}
/**
* Create groups of events which do not overlap. Events within this groups
* will be rendered in columns if they overlap.
*
* @param {Array} events
* @return {Array}
*/
function createGroups(events) {
var groups = []
var eventGroupMap = {}
events.forEach(function createGroup(event) {
var group = eventGroupMap[event.id]
if (!group) {
group = eventGroupMap[event.id] = [event]
groups.push(group)
}
events.forEach(function addToGroup(_event) {
if (_event === event) return
if (collide(event, _event)) {
if (!eventGroupMap[_event.id]) {
eventGroupMap[_event.id] = group
group.push(_event)
}
}
})
})
return groups
}
/**
* Create columns within a group. To avoid visual overlap.
*
* @param {Array} events
* @return {Array}
*/
function createColumns(group) {
var columns = []
var eventStackMap = {}
group.forEach(function createColumn(event) {
var column = eventStackMap[event.id]
if (!column) {
column = eventStackMap[event.id] = [event]
columns.push(column)
}
group.forEach(function addToColumn(_event) {
if (_event === event) return
if (!collide(event, _event)) {
if (!eventStackMap[_event.id]) {
eventStackMap[_event.id] = column
column.push(_event)
}
}
})
})
return columns
}
/**
* Check if 2 events collide in time.
*
* @param {Event} event1
* @param {Event} event2
* @return {Boolean}
*/
function collide(event1, event2) {
var startInside = event1.start >= event2.start && event1.start <= event2.end
var endInside = event1.end <= event2.end && event1.end > event2.start
return startInside || endInside
}
|
export {LineGraph as LineGraph} from './linegraph';
export {AreaGraph as AreaGraph} from './areagraph';
export {BarGraph as BarGraph} from './bargraph';
export {PieChart as PieChart} from './piechart';
export {ScatterPlot as ScatterPlot} from './scatterplot';
|
/**
* Combinations
*
* Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
*
* For example,
* If n = 4 and k = 2, a solution is:
*
* [
* [2,4],
* [3,4],
* [2,3],
* [1,2],
* [1,3],
* [1,4],
* ]
*/
/**
* @param {number} n
* @param {number} k
* @return {number[][]}
*/
const combine = (n, k) => {
const results = [];
backtracking(n, k, 1, [], results);
return results;
};
const backtracking = (n, k, start, solution, results) => {
if (solution.length === k) {
return results.push(solution.slice());
}
for (let i = start; i <= n; i++) {
solution.push(i);
backtracking(n, k, i + 1, solution, results);
solution.pop();
}
};
export default combine;
|
var http = require('http'),
port = process.env.PORT || 8080,
app = require('./app'),
server = require('http').createServer(app()),
io = require('socket.io')(server);
var messages = [];
var users = [];
var storeMessage = function(data){
messages.push(data);
if(messages.length > 10){
messages.shift();
}
};
var storeUsers = function(name){
users.push(name);
};
io.on('connection',function(client){
// console.log('client connected');
// client.emit('chat',{hello:'world'});
client.on('join',function(data){
client.name = data; //add a new property to client to identify it during deletion
console.log(messages);
storeMessage({'name':null,'status':'joined'});
storeUsers(data);
console.log('user ' +data+' joined!');
// console.log(users);
client.broadcast.emit("addUser",data);
client.emit("addAllUsers",users);
client.emit("addAllMessage",messages);
});
client.on('messageOut',function(data){
console.log(data)
storeMessage(data);
if(data.id=="0") //echo message
{
var obj = JSON.parse(JSON.stringify(data));
obj.incoming=true;
storeMessage(obj);
client.emit("AddMessage",obj);
}
//else..normal chat broadcast
});
client.on("disconnect",function(){
console.log("user "+client.name+" left..");
var i = users.indexOf(client.name);
users.splice(i, 1);
storeMessage({'name':null,'status':'left'});
client.broadcast.emit("removeUser",client.name);
});
});
server.listen(port, function () {
console.log('Server listening on port ' + port);
});
|
import {test} from '../qunit';
import {localeModule} from '../qunit-locale';
import moment from '../../moment';
localeModule('en-ie');
test('parse', function (assert) {
var tests = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'), i;
function equalTest(input, mmm, i) {
assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
}
for (i = 0; i < 12; i++) {
tests[i] = tests[i].split(' ');
equalTest(tests[i][0], 'MMM', i);
equalTest(tests[i][1], 'MMM', i);
equalTest(tests[i][0], 'MMMM', i);
equalTest(tests[i][1], 'MMMM', i);
equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
}
});
test('format', function (assert) {
var a = [
['dddd, MMMM Do YYYY, h:mm:ss a', 'Sunday, February 14th 2010, 3:25:50 pm'],
['ddd, hA', 'Sun, 3PM'],
['M Mo MM MMMM MMM', '2 2nd 02 February Feb'],
['YYYY YY', '2010 10'],
['D Do DD', '14 14th 14'],
['d do dddd ddd dd', '0 0th Sunday Sun Su'],
['DDD DDDo DDDD', '45 45th 045'],
['w wo ww', '6 6th 06'],
['h hh', '3 03'],
['H HH', '15 15'],
['m mm', '25 25'],
['s ss', '50 50'],
['a A', 'pm PM'],
['[the] DDDo [day of the year]', 'the 45th day of the year'],
['LTS', '15:25:50'],
['L', '14/02/2010'],
['LL', '14 February 2010'],
['LLL', '14 February 2010 15:25'],
['LLLL', 'Sunday 14 February 2010 15:25'],
['l', '14/2/2010'],
['ll', '14 Feb 2010'],
['lll', '14 Feb 2010 15:25'],
['llll', 'Sun 14 Feb 2010 15:25']
],
b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
i;
for (i = 0; i < a.length; i++) {
assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
}
});
test('format ordinal', function (assert) {
assert.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st');
assert.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd');
assert.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd');
assert.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th');
assert.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th');
assert.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th');
assert.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th');
assert.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th');
assert.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th');
assert.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th');
assert.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th');
assert.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th');
assert.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th');
assert.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th');
assert.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th');
assert.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th');
assert.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th');
assert.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th');
assert.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th');
assert.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th');
assert.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st');
assert.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd');
assert.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd');
assert.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th');
assert.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th');
assert.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th');
assert.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th');
assert.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th');
assert.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th');
assert.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th');
assert.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st');
});
test('format month', function (assert) {
var expected = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'), i;
for (i = 0; i < expected.length; i++) {
assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
}
});
test('format week', function (assert) {
var expected = 'Sunday Sun Su_Monday Mon Mo_Tuesday Tue Tu_Wednesday Wed We_Thursday Thu Th_Friday Fri Fr_Saturday Sat Sa'.split('_'), i;
for (i = 0; i < expected.length; i++) {
assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
}
});
test('from', function (assert) {
var start = moment([2007, 1, 28]);
assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'a few seconds', '44 seconds = a few seconds');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'a minute', '45 seconds = a minute');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'a minute', '89 seconds = a minute');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'an hour', '45 minutes = an hour');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'an hour', '89 minutes = an hour');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hours', '90 minutes = 2 hours');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hours', '5 hours = 5 hours');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hours', '21 hours = 21 hours');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'a day', '22 hours = a day');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'a day', '35 hours = a day');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 days', '36 hours = 2 days');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'a day', '1 day = a day');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 days', '5 days = 5 days');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 days', '25 days = 25 days');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'a month', '26 days = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'a month', '30 days = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'a month', '43 days = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 months', '46 days = 2 months');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 months', '75 days = 2 months');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 months', '76 days = 3 months');
assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'a month', '1 month = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 months', '5 months = 5 months');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'a year', '345 days = a year');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 years', '548 days = 2 years');
assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'a year', '1 year = a year');
assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 years', '5 years = 5 years');
});
test('suffix', function (assert) {
assert.equal(moment(30000).from(0), 'in a few seconds', 'prefix');
assert.equal(moment(0).from(30000), 'a few seconds ago', 'suffix');
});
test('now from now', function (assert) {
assert.equal(moment().fromNow(), 'a few seconds ago', 'now from now should display as in the past');
});
test('fromNow', function (assert) {
assert.equal(moment().add({s: 30}).fromNow(), 'in a few seconds', 'in a few seconds');
assert.equal(moment().add({d: 5}).fromNow(), 'in 5 days', 'in 5 days');
});
test('calendar day', function (assert) {
var a = moment().hours(12).minutes(0).seconds(0);
assert.equal(moment(a).calendar(), 'Today at 12:00', 'today at the same time');
assert.equal(moment(a).add({m: 25}).calendar(), 'Today at 12:25', 'Now plus 25 min');
assert.equal(moment(a).add({h: 1}).calendar(), 'Today at 13:00', 'Now plus 1 hour');
assert.equal(moment(a).add({d: 1}).calendar(), 'Tomorrow at 12:00', 'tomorrow at the same time');
assert.equal(moment(a).subtract({h: 1}).calendar(), 'Today at 11:00', 'Now minus 1 hour');
assert.equal(moment(a).subtract({d: 1}).calendar(), 'Yesterday at 12:00', 'yesterday at the same time');
});
test('calendar next week', function (assert) {
var i, m;
for (i = 2; i < 7; i++) {
m = moment().add({d: i});
assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days end of day');
}
});
test('calendar last week', function (assert) {
var i, m;
for (i = 2; i < 7; i++) {
m = moment().subtract({d: i});
assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days end of day');
}
});
test('calendar all else', function (assert) {
var weeksAgo = moment().subtract({w: 1}),
weeksFromNow = moment().add({w: 1});
assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago');
assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week');
weeksAgo = moment().subtract({w: 2});
weeksFromNow = moment().add({w: 2});
assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago');
assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks');
});
test('weeks year starting sunday formatted', function (assert) {
assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52nd', 'Jan 1 2012 should be week 52');
assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1st', 'Jan 2 2012 should be week 1');
assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1st', 'Jan 8 2012 should be week 1');
assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2nd', 'Jan 9 2012 should be week 2');
assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2nd', 'Jan 15 2012 should be week 2');
});
|
import React from "react";
import { mount } from "enzyme";
import { Modal } from "../index";
import renderer from "react-test-renderer";
describe("Test correct render", () => {
it("Test correct render", function() {
const tree = renderer
.create(
<Modal>
<div>
<p>
This is Modal example<br />Any child components could be put here.
</p>
</div>
</Modal>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
});
describe("Modal component - Basic tests", () => {
it("Modal component - test defaults", function() {
const modal = mount(
<Modal>
<div>
<p>
This is Modal example<br />Any child components could be put here.
</p>
</div>
</Modal>
);
expect(modal.props().active).toEqual(false);
expect(modal.find("Portal").exists()).toEqual(false);
expect(modal.props().overlay).toEqual(false);
expect(modal.props().lockScroll).toEqual(true);
expect(modal.props().className).toEqual("");
expect(modal.state().isHaveScrollbar).toEqual(false);
});
it("Modal component - test active displays modal when true", function() {
let active = true;
const modal = mount(
<Modal active={active}>
<div>
<p>
This is Modal example<br />Any child components could be put here.
</p>
</div>
</Modal>
);
expect(modal.props().active).toEqual(true);
expect(modal.find("Portal").exists()).toEqual(true);
});
it("Modal component - className applies css class", function() {
const modal = mount(
<Modal className="myClass anotherClass">
<div>
<p>
This is Modal example<br />Any child components could be put here.
</p>
</div>
</Modal>
);
expect(modal.props().className).toEqual("myClass anotherClass");
expect(modal.find(".myClass").exists()).toBe(true);
expect(modal.find(".anotherClass").exists()).toBe(true);
});
it("Modal component - lockScroll applies properly", function() {
const modal = mount(
<Modal active overlay lockScroll={false}>
<div>
<p>
This is Modal example<br />Any child components could be put here.
</p>
</div>
</Modal>
);
expect(modal.props().lockScroll).toEqual(false);
expect(modal.state().isHaveScrollbar).toEqual(false);
});
it("Modal component - onEscKeyDown", function() {
const handleEscKey = jest.fn();
const modal = mount(
<Modal active onEscKeyDown={handleEscKey} overlay>
<p>
This is Modal example<br />Any child components could be put here.
</p>
</Modal>
);
expect(modal.props().onEscKeyDown).toEqual(handleEscKey);
const overlayProps = modal
.children()
.first()
.props().children[0].props;
expect(overlayProps.onEscKeyDown).toEqual(handleEscKey);
});
it("Modal component - onOverlayClick", function() {
const handleOverlayClick = jest.fn();
const modal = mount(
<Modal active onOverlayClick={handleOverlayClick} overlay>
<p>
This is Modal example<br />Any child components could be put here.
</p>
</Modal>
);
expect(modal.props().onOverlayClick).toEqual(handleOverlayClick);
const overlayProps = modal
.children()
.first()
.props().children[0].props;
expect(overlayProps.onClick).toEqual(handleOverlayClick);
});
it("Modal component - cancelClickHandler", function() {
const event = {
"type": "click",
"stopPropagation": jest.fn()
};
const modal = mount(
<Modal active>
<p>
This is Modal example<br />Any child components could be put here.
</p>
</Modal>
);
modal.instance().cancelClickHandler(event);
expect(event.stopPropagation).toBeCalled();
});
});
|
var React = require('react');
var uiBadge = React.createClass({
propTypes: {
color: React.PropTypes.string,
notification: React.PropTypes.bool,
tag: React.PropTypes.oneOf(['div', 'span'])
},
getDefaultProps: function(){
return {
notification: false,
tag: 'div'
}
},
render: function(){
var props = this.props;
var filledClassName = [];
var {color,notification,tag,className, ...options} = props;
filledClassName.push('uk-badge');
// color of button (primary,danger,success,link)
if(color){
filledClassName.push('uk-badge-'+color);
}
if(notification){
filledClassName.push('uk-badge-notification');
}
if(className){
filledClassName.push(className);
}
filledClassName = filledClassName.join(' ');
var Badge = tag;
return <Badge className={filledClassName} {...options}>{props.children}</Badge>
}
});
module.exports = uiBadge;
|
module.exports = function(config) {
'use strict';
var browsers = ['Chrome', 'Firefox'];
var reporters = ['clear-screen', 'mocha', 'coverage'];
config.set({
basePath: '',
frameworks: ['mocha', 'sinon-chai'],
files: [
'src/boa.js',
'tests/**/*.coffee'
],
preprocessors: {
'src/**/*.js': 'coverage',
'**/*.coffee': ['coffee']
},
reporters: reporters,
coverageReporter: {
reporters: [
{type: 'text-summary'},
{type: 'html'},
{type: 'lcov'}
]
},
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
browsers: browsers,
singleRun: false
});
};
|
var fs = require('fs'),
path = require('path');
module.exports = function (testname, params, req, done) {
var txt = fs.readFileSync(path.join(__dirname, 'basic.json'), 'utf8'),
data;
try {
data = JSON.parse(txt);
} catch (e) {
return done(e);
}
done(null, data);
};
|
var connect = require("connect"),
connectJade = require("connect-jade");
connect()
.use(connectJade({
root: __dirname + "/views",
defaults: {
title: "MyApp"
}
}))
.use(function(req, res) {
res.render("index", { heading: "Welcome to My App"});
}).listen(3000);
|
//@flow weak
var moment = require('moment-timezone');
var config = require('config')
const { init } = require(`../../../node_modules/devicehive/src/api.js`);
const token = config.DeviceHive.token
var dhNode = null;
var mongoSchedule = null;
var mongoSubs = null;
//var mongodb = require("mongodb").MongoClient;
async function start() {
try {
dhNode = await init(config.DeviceHive.url)
//let mongo = await mongodb.connect('mongodb://' + config.device_config.mongo.host + ':' + config.device_config.mongo.port + '/' + config.device_config.mongo.database);
//mongoSubs = await mongo.collection(config.device_config.mongo.collection);
//let mongo2 = await mongodb.connect('mongodb://' + config.device_config.mongoSchedule.host + ':' + config.device_config.mongoSchedule.port + '/' + config.device_config.mongoSchedule.database);
//mongoSchedule = await mongo2.collection(config.device_config.mongoSchedule.collection);
let newToken = await dhNode.refreshToken(token)
dhNode.setTokens({accessToken:newToken['accessToken'],refreshToken:token})
let save = await dhNode.saveDevice('TestDevice', {
name: 'TestDevice'
})
let getInfo = await dhNode.getInfo()
let timestamp = getInfo['serverTimestamp']
poll(timestamp, 'TestDevice')
//TESTS
console.log('***************************************** ')
console.log('* Integration test for Schedule Service * ')
console.log('***************************************** \n')
console.log("Send schedule/create command to create schedule with paramters:")
let newSchedule = await createSchedule()
console.log('\nRecieved: ')
console.log(JSON.stringify(newSchedule.result,null,2))
console.log('\n\n')
let delay0 = await delay(5)
console.log('Send schedule/showSubs command to see all subscriptions')
let ShowSubs = await sendCommand('homeassist', 'schedule/showSubs', {})
console.log('Recieved: ')
console.log(JSON.stringify(ShowSubs.result,null,2))
console.log('\n\n')
let del = await delay(5)
console.log("Send Notification with power and energy measurements. Power 1000 Energy 1000")
let notif1 = await sendNotification('TestDevice', "device/init", {
DeviceID: 'TestDevice',
power: 1000.0,
energy: 1000.0
})
console.log('Recieved: ')
console.log(JSON.stringify(notif1,null,2))
console.log('\n\n')
let delay1 = await delay(5)
console.log('Send schedule/showAll to see all schedules')
let showAll = await sendCommand('homeassist', 'schedule/showAll', {})
console.log('Recieved: ')
console.log(JSON.stringify(showAll.result,null,2))
console.log('\n\n')
let delay2 = await delay(5)
console.log("Send Notification with power and energy measurements. Power 1000 Energy 1000 \n Expecting switch OFF command")
let notif2 = await sendNotification('TestDevice', "device/init", {
DeviceID: 'TestDevice',
power: 1000.0,
energy: 1000.0
})
console.log(JSON.stringify(notif2,null,2))
console.log('\n\n')
let delay3 = await delay(5)
console.log("Send schedule/remove command." )
let removeSchedule = await sendCommand('homeassist', 'schedule/remove', {
"DeviceID": "TestDevice"
})
console.log('Parameters sent:\n'+JSON.stringify(removeSchedule.parameters,null,2))
console.log('Recieved: ')
console.log(JSON.stringify(removeSchedule.result,null,2))
console.log('\n\n')
process.exit()
} catch (err) {
console.log(err)
}
}
function sendCommand(device, cmd, params) {
return new Promise(async function(resolve, reject) {
try {
let send = await dhNode.createDeviceCommand(device, {
command: cmd,
parameters: params
})
let poll = await dhNode.getDeviceCommandPoll(device, send.id.toString(), 15)
resolve(poll)
} catch (err) {
reject(err)
}
})
}
function sendNotification(device, notif, params) {
return new Promise(async function(resolve, reject) {
try {
let notif1 = await dhNode.createDeviceNotification(device, {
notification: notif,
parameters: params
})
resolve(notif1)
} catch (err) {
reject(err)
}
})
}
function delay(t) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, t * 1000)
});
}
function calcTime(hour, minute, second) {
let _hour = 0,
_second = 0,
_minute = 0;
if (second > 59) {
_minute = minute + 1;
_second = second - 60;
} else {
_minute = minute;
_second = second;
}
if (_minute > 59) {
_hour = hour + 1;
_minute = _minute - 60;
} else {
_hour = hour;
}
if (_hour > 23) {
_hour = _hour - 23;
}
_hour = _hour < 10 ? '0' + _hour.toString() : _hour.toString()
_minute = _minute < 10 ? '0' + _minute.toString() : _minute.toString()
_second = _second < 10 ? '0' + _second.toString() : _second.toString()
return _hour + ':' + _minute + ':' + _second
}
function createSchedule() {
return new Promise(function(resolve, reject) {
try {
let time = moment();
let begin1 = calcTime(time.hour(), time.minute(), time.second() + 5)
let end1 = calcTime(time.hour(), time.minute() + 1, time.second() + 5)
let schedule = {
"DeviceID": "TestDevice",
"start": {
"command":"device/control",
"parameters":{
"state":"On"
}
},
"stop": {
"command":"device/control",
"parameters":{
"state":"Off"
}
},
"schedule": [{
"beginTime": begin1,
"endTime": end1
}],
"maxEnergy": 1500.0,
"notification": "device/init"
}
console.log(schedule)
let result = sendCommand('homeassist', "schedule/create", schedule)
resolve(result)
} catch (err) {
reject(err)
}
})
}
async function poll(_timestamp, deviceID) {
try {
let timestamp = null
let id = null
let result = null
let commands = await dhNode.getDevicesCommandPoll({
timestamp: _timestamp,
deviceIds: deviceID
})
//console.log(JSON.stringify(commands))
//timestamp = commands[0]['timestamp']
if (commands.length > 0) {
console.log('TestDevice recieved command:')
console.log(commands[0])
console.log('\n\n')
timestamp = commands[0]['timestamp']
id = commands[0]['id']
let update = await dhNode.updateCommand(deviceID, id.toString(), {})
}
poll(timestamp, deviceID)
} catch (err) {
console.error(err)
}
}
start()
|
function multiply(first, second) {
return (first * second);
};
module.exports = {multiply};
|
var fs = require('fs');
var os = require('os');
var BrigCore = null;
try {
BrigCore = require('../build/Release/brig.node');
} catch(err) {}
if (!BrigCore) {
var apiVer = process.versions.modules;
var arch = process.arch;
// Support ARM architecture
if (arch == 'arm') {
arch += 'v' + process.config.variables.arm_version;
if (os.endianness() == 'LE') {
arch += 'l';
} else {
arch += 'b';
}
}
if (!BrigCore) {
try {
// Try to use the last version
BrigCore = require('../native/' + process.platform + '-' + arch + '-' + apiVer + '/brig.node');
} catch(err) {
throw new Error('Please use \'node-gyp rebuild\' to compile binary by yourself.');
}
}
}
module.exports = BrigCore;
|
// Backbone.bind.js 1.0.1
// For all details and documentation:
// https://github.com/klypkan/backbone.bind
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['underscore', 'jquery', 'backbone'], factory);
} else {
// Browser globals
factory(_, $, Backbone);
}
}(function (_, $, Backbone) {
Backbone.View.prototype.bind = function (options) {
setBindingOptions.call(this, options);
var propNameAttr = this.bindingOptions.propNameAttr;
var eventsAttr = this.bindingOptions.eventsAttr;
var defaultElEvents = "change";
var elEvents = null;
var el = null;
var propName = null;
var viewContext = this;
this.$el.find('[' + propNameAttr + ']').each(function (index) {
el = $(this);
propName = el.attr(propNameAttr);
var proxy = $.proxy(getModelPropVal, viewContext, propName);
var propVal = proxy();
proxy = $.proxy(setElVal, viewContext, el, propVal);
proxy();
elEvents = el.attr(eventsAttr);
elEvents = elEvents || defaultElEvents;
el.on(elEvents, { propName: propName, el: el }, function (event) {
var proxy = $.proxy(getElVal, viewContext, event.data.el, event.data.propName);
var elVal = proxy();
proxy = $.proxy(setModelPropVal, viewContext, event.data.propName, elVal);
proxy();
});
});
if (this.bindingOptions.observeModel) {
this.model.on("change", modelChangeHandler, this);
}
}
function modelChangeHandler() {
var changedAttributes = this.model.changedAttributes();
var propNameAttr = this.bindingOptions.propNameAttr;
var viewContext = this;
for (var propName in changedAttributes) {
this.$el.find('[' + propNameAttr + '="' + propName + '"]').each(function (index) {
el = $(this);
var proxy = $.proxy(getElVal, viewContext, el, propName);
var elVal = proxy();
if (elVal != changedAttributes[propName]) {
proxy = $.proxy(setElVal, viewContext, el, changedAttributes[propName]);
proxy();
}
});
}
}
Backbone.View.prototype.unbind = function () {
if (this.bindingOptions) {
if (this.bindingOptions.observeModel) {
this.model.off("change", modelChangeHandler, this);
}
var propNameAttr = this.bindingOptions.propNameAttr;
this.$el.find('[' + propNameAttr + ']').each(function (index) {
$(this).off();
});
}
}
function setElVal(el, propVal) {
var handler = el.attr(this.bindingOptions.handlerAttr);
if (handler) {
this[handler]({ type: "setElVal", data: { el: el, propVal: propVal } });
return;
}
var tagName = el.prop("tagName").toLowerCase();
if (tagName == 'input' || tagName == 'select' || tagName == 'textarea') {
attrType = el.attr('type');
if (attrType == 'radio') {
el.val([propVal]);
}
else if (attrType == 'checkbox') {
if (typeof (propVal) == 'boolean') {
el.prop('checked', propVal);
}
else {
el.val([propVal]);
}
}
else {
el.val(propVal);
}
}
else {
el.html(propVal);
}
}
function getElVal(el, propName) {
var handler = el.attr(this.bindingOptions.handlerAttr);
if (handler) {
return this[handler]({ type: "getElVal", data: { el: el, propName: propName } });
}
var elVal = null;
var tagName = el.prop("tagName").toLowerCase();
if (tagName == 'input' || tagName == 'select' || tagName == 'textarea') {
var attrType = el.attr('type');
if (attrType == 'radio') {
if (el.prop('checked')) {
elVal = el.val();
}
else {
elVal = getModelPropVal(propName);
}
}
else if (attrType == 'checkbox') {
if (el.prop('checked')) {
if (el.val() == 'on') {
elVal = true;
}
else {
elVal = el.val();
}
}
else {
if (el.val() == 'on') {
elVal = false;
}
else {
elVal = null;
}
}
}
else {
elVal = el.val();
}
}
else {
elVal = el.html();
}
return elVal;
}
function getModelPropVal(propName) {
var props = propName.split('.');
var propsLength = props.length;
if (propsLength == 1) {
return this.model.get(propName);
}
else {
var currObj = this.model;
var currPropVal = null;
var currPropName = '';
var currArrayName = '';
var indexStartArray = -1;
var indexEndArray = -1;
var indexItemArray = -1;
for (var i = 0; i < propsLength; i++) {
currPropName = props[i];
indexStartArray = currPropName.indexOf('[');
if (indexStartArray < 0) {
if (currObj instanceof Backbone.Model) {
currPropVal = currObj.get(currPropName);
}
else {
currPropVal = currObj[currPropName];
}
if (!currPropVal) {
return null;
}
currObj = currPropVal;
}
else {
currArrayName = currPropName.substring(0, indexStartArray);
if (currObj instanceof Backbone.Model) {
currObj = currObj.get(currArrayName);
}
else {
currObj = currObj[currArrayName];
}
indexEndArray = currPropName.indexOf(']');
indexItemArray = parseInt(currPropName.substring(indexStartArray + 1, indexEndArray));
currObj = currObj[indexItemArray];
}
}
return currPropVal;
}
}
function setModelPropVal(propName, propVal) {
var newVal = propVal;
var props = propName.split('.');
var propsLength = props.length;
if (propsLength == 1) {
this.model.set(propName, propVal);
}
else {
var currObj = this.model;
var currPropVal = null;
var currPropName = '';
var currArrayName = '';
var indexStartArray = -1;
var indexEndArray = -1;
var keyItemArray = '';
var indexItemArray = -1;;
for (var i = 0, itemsLength = propsLength - 1; i < itemsLength; i++) {
currPropName = props[i];
keyItemArray = keyItemArray + (keyItemArray == '' ? '' : '.') + currPropName;
indexStartArray = currPropName.indexOf('[');
if (indexStartArray < 0) {
if (currObj instanceof Backbone.Model) {
currPropVal = currObj.get(currPropName);
if (!currPropVal) {
currObj.set(currPropName, {});
currPropVal = currObj.get(currPropName);
}
currObj = currPropVal;
}
else {
currPropVal = currObj[currPropName];
if (!currPropVal) {
currObj[currPropName] = {};
currPropVal = currObj[currPropName];
}
currObj = currPropVal;
}
}
else {
currArrayName = currPropName.substring(0, indexStartArray);
if (currObj instanceof Backbone.Model) {
currObj = currObj.get(currArrayName);
}
else {
currObj = currObj[currArrayName];
}
indexEndArray = currPropName.indexOf(']');
indexItemArray = parseInt(currPropName.substring(indexStartArray + 1, indexEndArray));
currObj = currObj[indexItemArray];
}
}
currPropName = props[propsLength - 1];
if (currObj instanceof Backbone.Model) {
currObj.set(currPropName, propVal);
}
else {
currObj[currPropName] = propVal;
}
}
}
function setBindingOptions(options) {
this.bindingOptions = $.extend({ propNameAttr: 'name', eventsAttr: 'data-bind-events', handlerAttr: 'data-bind-handler', observeModel: true }, options);
}
return Backbone.View;
}));
|
var check = require('check-types');
var code = require('../../../utils/code');
function parseEqualArguments(equal) {
check.verify.string(equal, 'equal is not a string');
var split = code.split(equal);
check.verify.array(split, 'did not get array from', equal);
var result = {
op: split[0],
expected: split[1]
};
return result;
}
function transformSingleArgument(args) {
check.verify.string(args, 'args is not a string');
var split = code.split(args);
check.verify.array(split, 'did not get array from', args);
var result = {
op: split[0]
};
return result;
}
// top level parsers for individual assertions
function parseExpectToEqual(line) {
var isEqualReg = /^\s*expect\(([\W\w]+)\)\.toEqual\(([\W\w]+)\)/;
// var isStrictEqualReg = /(?:^\s*QUnit\.|^\s*)strictEqual\(([\W\w]+)\);/;
// var isDeeptEqualReg = /(?:^\s*QUnit\.|^\s*)deepEqual\(([\W\w]+)\);/;
var equalRegs = [isEqualReg/*, isStrictEqualReg, isDeeptEqualReg*/];
// console.log('jasmine testing line\n' + line);
var matchingReg = null;
equalRegs.some(function (reg) {
if (reg.test(line)) {
// console.log('jasmine line\n' + line + 'matches\n' + reg);
matchingReg = reg;
return true;
}
});
if (!matchingReg) {
return null;
}
var matches = matchingReg.exec(line);
var computed = matches[1];
var expected = matches[2];
check.verify.string(computed, 'invalid computed expression');
check.verify.string(expected, 'invalid expected expression');
var computedTransformed = transformSingleArgument(computed);
check.verify.object(computedTransformed, 'count not transform\n' + computed);
var expectedTransformed = transformSingleArgument(expected);
check.verify.object(expectedTransformed, 'count not transform\n' + expected);
return computedTransformed.op + '; // ' + expectedTransformed.op;
}
function parseExpectToBeTruthy(line) {
var reg = /^\s*expect\(([\W\w]+)\).toBeTruthy()/;
if (!reg.test(line)) {
return null;
}
var matches = reg.exec(line);
// console.log('ok matches', matches);
var args = matches[1];
check.verify.string(args, 'invalid number arguments');
var parsed = transformSingleArgument(args);
check.verify.object(parsed, 'did not get parsed arguments');
return parsed.op + '; // true';
}
function parseExpectToBeTruthy(line) {
var reg = /^\s*expect\(([\W\w]+)\).toBeTruthy()/;
if (!reg.test(line)) {
return null;
}
var matches = reg.exec(line);
var args = matches[1];
check.verify.string(args, 'invalid number arguments');
var parsed = transformSingleArgument(args);
check.verify.object(parsed, 'did not get parsed arguments');
return parsed.op + '; // true';
}
function parseExpectToBeFalsy(line) {
var reg = /^\s*expect\(([\W\w]+)\).toBeFalsy()/;
if (!reg.test(line)) {
return null;
}
var matches = reg.exec(line);
var args = matches[1];
check.verify.string(args, 'invalid number arguments');
var parsed = transformSingleArgument(args);
check.verify.object(parsed, 'did not get parsed arguments');
return parsed.op + '; // false';
}
var lineParsers = [
parseExpectToBeTruthy,
parseExpectToBeFalsy,
parseExpectToEqual
];
function transformAssertion(line) {
check.verify.string(line, 'missing line');
var parsed = null;
lineParsers.some(function (method) {
return parsed = method(line);
});
if (check.string(parsed)) {
return parsed;
}
return line;
}
module.exports = transformAssertion; |
var React = require('react');
var request = require('superagent');
var RSVPStore = require('../stores/RSVPStore');
var HeroApp = React.createClass({
getInitialState: function() {
return {
user: SydJS.user,
isReady: RSVPStore.isLoaded(),
meetup: RSVPStore.getMeetup(),
rsvp: RSVPStore.getRSVP()
};
},
componentDidMount: function() {
RSVPStore.addChangeListener(this.updateStateFromStore);
},
componentWillUnmount: function() {
RSVPStore.removeChangeListener(this.updateStoreFromState);
},
updateStateFromStore: function() {
this.setState({
isReady: RSVPStore.isLoaded(),
meetup: RSVPStore.getMeetup(),
rsvp: RSVPStore.getRSVP()
});
},
toggleRSVP: function(attending) {
var self = this;
RSVPStore.rsvp(attending);
},
renderWelcome: function() {
if (this.state.rsvp.attending) {
return <h4 className="hero-button-title"><span className = "welcome-message">See you there!</span></h4>
} else {
return <h4 className="hero-button-title">Are you coming? <br /> <span className="spots-left">{this.state.meetup.remainingRSVPs}<span className="text-thin"> spots left</span></span><br /></h4>
}
},
renderLoading: function() {
return (
<div className="hero-button">
<div className="alert alert-success mb-0 text-center">loading...</div>
</div>
);
},
renderRSVPButton: function() {
return (
<div className="hero-button" onClick={this.toggleRSVP.bind(this, true)}>
<a className="btn btn-primary btn-lg btn-block">
RSVP Now (<span className="text-thin">{this.state.meetup.remainingRSVPs} spots left</span>)
</a>
</div>
);
},
renderRSVPToggle: function() {
var attending = this.state.rsvp.attending ? ' btn-success btn-default active' : null;
var notAttending = this.state.rsvp.attending ? null : ' btn-danger btn-default active';
return (
<div>
{this.renderWelcome()}
<div className="hero-button">
<div id="next-meetup" data-id={this.state.meetup._id} className="form-row meetup-toggle">
<div className="col-xs-6">
<button type="button" onClick={this.toggleRSVP.bind(this, true)} className={"btn btn-lg btn-block btn-default js-rsvp-attending" + attending}>Yes</button>
</div>
<div className="col-xs-6">
<button type="button" onClick={this.toggleRSVP.bind(this, false)} className={"btn btn-lg btn-block btn-default js-rsvp-decline" + notAttending}>No</button>
</div>
</div>
</div>
</div>
);
},
// MAKESHIFT WAY TO EXPOSE JQUERY AUTH LOGIC TO REACT
signinModalTrigger: function (e) {
e.preventDefault;
window.signinModalTrigger(e);
},
renderRSVPSignin: function() {
return (
<div className="hero-button">
<a className="btn btn-primary btn-lg btn-block js-auth-trigger" onClick={this.signinModalTrigger}>RSVP Now <span className="text-thin">({this.state.meetup.remainingRSVPs} spots left)</span></a>
</div>
);
},
renderNoMoreTickets: function() {
return (
<div className="hero-button">
<div className="alert alert-success mb-0 text-center">No more tickets...</div>
</div>
);
},
render: function() {
if (!this.state.isReady) {
return this.renderLoading();
}
if (this.state.user) {
if (this.state.meetup.rsvpsAvailable) {
if (this.state.rsvp.exists) {
return this.renderRSVPToggle();
} else {
return this.renderRSVPButton();
}
} else {
return this.renderNoMoreTickets();
}
} else {
return this.state.meetup.rsvpsAvailable ? this.renderRSVPSignin() : this.renderNoMoreTickets();
}
},
});
module.exports = HeroApp;
|
var uuid = require('node-uuid');
var bucker = require('bucker');
var log = bucker.createLogger({app: 'server.log', console: true}, 'http');
function Session(pie, ws) {
this.pie = pie;
this.user = null;
this.domain = null;
this.id = uuid();
this.ws = ws;
this.domain = this.ws.upgradeReq.headers.host.split(':')[0];
log.debug("Websocket connection for " + this.domain);
this.ws.on('error', this.handleError.bind(this));
this.ws.on('message', this.handleMessage.bind(this));
this.ws.on('close', function () {
log.debug('websocket closed');
});
}
(function () {
this.handleError = function (error) {
};
this.handleMessage = function (msg) {
msg = JSON.parse(msg);
console.log(msg);
if (typeof this['rpc_' + msg.rpc] === 'function') {
this['rpc_' + msg.rpc](msg);
}
};
this.sendEvent = function (event) {
var id = uuid();
event.id = id;
this.ws.send(JSON.stringify(event));
};
this.rpc_tokenAuth = function (msg) {
console.log("tokenAuth", msg);
this.pie.db.auth(this.domain).validateToken(msg.token, function (err, user, domain) {
console.log(err, user, domain);
if (!err) {
this.ws.send(JSON.stringify({
id: msg.id,
authed: true,
user: user + '@' + domain,
}));
this.user = user;
this.domain = domain;
if (!this.pie.sessions.hasOwnProperty(user + '@' + domain)) {
this.pie.sessions[user + '@' + domain] = {};
}
this.pie.sessions[user + '@' + domain][this.id] = this;
} else {
}
}.bind(this));
};
}).call(Session.prototype);
module.exports = Session;
|
/**
* Startup
*/
Meteor.startup(function() {
Session.setDefault('issues', undefined);
Session.setDefault('githubRepo', undefined);
Session.setDefault('githubUser', undefined);
});
/**
* Global functions
*/
// Check if a GitHub repository exists for a given user
function repoExists (user, repo, callback) {
Meteor.apply(
'listUserRepos',
[
user,
Meteor.user().profile.github.accessToken
],
onResultReceived = function (error, result) {
var response = false;
for (var i = 0; i < result.length; i++) {
if (result[i].name == repo) {
response = true;
}
}
if (response)
console.log('Repo "' + repo + '" exists.');
else
console.log('Repo "' + repo + '" does not exist.');
if (callback && typeof(callback) === 'function') {
callback(error, response);
}
}
);
}
// Change user and repository
function changeUserAndRepo () {
if (!Meteor.user()) return;
var githubUser = Meteor.user().profile.github.username;
var githubRepo = document.getElementById('repo').value;
repoExists(githubUser, githubRepo, function (error, exists) {
if (exists) {
Session.set('githubRepo', githubRepo);
Session.set('githubUser', githubUser);
console.log('Changed GitHub repo to ' + Session.get('githubRepo'));
console.log('Changed GitHub user to ' + Session.get('githubUser'));
Meteor.apply(
'listIssues',
[
Session.get('githubUser'),
Session.get('githubRepo'),
Meteor.user().profile.github.accessToken
],
function (error, issues) {
if (error) {
console.log('An error occurred retrieving issues: ' + error);
Session.set(
'listIssuesError',
'An error occurred retrieving issues. Please try again');
} else {
console.log('Retrieved issues');
Session.set('issues', issues);
Session.set('listIssuesError', undefined);
}
}
);
} else {
Session.set(
'listIssuesError',
'Repository "' + githubUser + '/' + githubRepo + '" does not exist');
}
})
}
/**
* Template main
*/
Template.main.user = function () { return Meteor.user(); }
/**
* Template repository
*/
Template.repository.user = function () { return Meteor.user(); }
Template.repository.rendered = function () {
document.getElementById('repo').value = Session.get('githubRepo');
}
Template.repository.events = {
'keydown input#repo' : function (event) {
if (event.which == 13)
changeUserAndRepo();
}
}
/**
* Template issues
*/
Template.board.issues = function () { return Session.get('issues'); }
Template.board.listIssuesError = function () { return Session.get('listIssuesError'); }
/**
* Dependencies
*/
Deps.autorun(function(comp) {
if (Meteor.user()) {
Session.set('githubUser', Meteor.user().profile.github.username);
}
});
/**
* jQuery-ui hacks
*/
$(function() {
$('.issues').sortable({
connectWith: '.issues',
distance: 20,
placeholder: 'ui-sortable-placeholder'
});
$('.issues').disableSelection();
});
|
module.exports = {
ampEnv: {
attack: {
displayName: "A",
id: "ampEnvAttack",
max: 1, // 1000
min: 0,
step: 0.01, // 10
val: 0.1 // 1
},
decay: {
displayName: "D",
id: "ampEnvDecay",
max: 1,
min: 0, // 1000
step: 0.01, // 10
val: 0.05 // .5
},
sustain: {
displayName: "S",
id: "ampEnvSustain",
max: 1, // 100
min: 0,
step: 0.01, // 1
val: 0.04 // .4
},
release: {
displayName: "R",
id: "ampEnvRelease",
max: 1, // 4000
min: 0,
step: 0.01, // 40
val: 0 // 0
}
},
filterEnv: {
attack: {
displayName: "A",
id: "filterEnvAttack",
max: 1, // 1000
min: 0,
step: 0.01, // 10
val: 0.1 // 1
},
decay: {
displayName: "D",
id: "filterEnvDecay",
max: 1,
min: 0, // 1000
step: 0.01, // 10
val: 0.05 // .5
},
sustain: {
displayName: "S",
id: "filterEnvSustain",
max: 1, // 100
min: 0,
step: 0.01, // 1
val: 0.04 // .4
},
release: {
displayName: "R",
id: "filterEnvRelease",
max: 1, // 4000
min: 0,
step: 0.01, // 40
val: 0 // 0
}
},
detune: {
fineTune: {
osc1: {
displayName: "Fine",
id: "osc1FineTune",
max: 50,
min: -50,
step: 1,
val: 0
},
osc2: {
displayName: "Fine",
id: "osc2FineTune",
max: 50,
min: -50,
step: 1,
val: 0
}
},
semitoneTune: {
osc1: {
displayName: "Semitone",
id: "osc1SemitoneTune",
max: 12,
min: -12,
step: 1,
val: 0
},
osc2: {
displayName: "Semitone",
id: "osc2SemitoneTune",
max: 12,
min: -12,
step: 1,
val: 0
}
},
octaveTune: {
osc1: {
displayName: "Octave",
id: "osc2OctaveTune",
max: 12,
min: 0,
step: 1,
val: 3
},
osc2: {
displayName: "Octave",
id: "osc2OctaveTune",
max: 12,
min: 0,
step: 1,
val: 3
}
}
},
gain: {
masterGain: {
displayName: "Master",
id: "gain",
max: 1,
min: 0,
step: .1,
val: .5
},
noiseGain: {
displayName: "Noise",
id: "gain",
max: 1,
min: 0,
step: .1,
val: .5
},
osc1Gain: {
displayName: "Osc 1",
id: "gain",
max: 1,
min: 0,
step: .1,
val: .5
},
osc2Gain: {
displayName: "Osc 2",
id: "gain",
max: 1,
min: 0,
step: .1,
val: .5
}
},
pan: {
displayName: "Pan",
id: "pan",
max: 1,
min: 0,
step: .1,
val: .5
},
drive: {
displayName: "Drive",
id: "drive",
max: 1,
min: 0,
step: .1,
val: .5
},
oscs: {
osc1: {
sine: {
displayName: "Sine",
id: "osc1Sine",
on: true,
val: 0
},
square: {
displayName: "Sq",
id: "osc1Square",
on: false,
val: 1
},
saw: {
displayName: "Saw",
id: "osc1Saw",
on: false,
val: 2
},
triangle: {
displayName: "Tri",
id: "osc1Triangle",
on: false,
val: 3
}
},
osc2: {
sine: {
displayName: "Sine",
id: "osc2Sine",
on: true,
val: 0
},
square: {
displayName: "Sq",
id: "osc2Square",
on: false,
val: 1
},
saw: {
displayName: "Saw",
id: "osc2Saw",
on: false,
val: 2
},
triangle: {
displayName: "Tri",
id: "osc2Triangle",
on: false,
val: 3
}
}
},
temperaments: {
eq: {
displayName: "Equal",
id: "equalTemperament",
on: true,
val: 0
},
py: {
displayName: "Py",
id: "pythagoreanTemperament",
on: false,
val: 1
},
just: {
displayName: "Just",
id: "justTemperament",
on: false,
val: 2
},
mt: {
displayName: "MT",
id: "meanToneTemperament",
on: false,
val: 3
}
},
compressor: {
attack: {
displayName: "Attack",
id: "compAttack",
max: 100,
min: -100,
step: 1,
val: 0.003
},
knee: {
displayName: "Knee",
id: "compKnee",
max: 100,
min: -100,
step: 1,
val: 30
},
ratio: {
displayName: "Ratio",
id: "compRatio",
max: 100,
min: -100,
step: 1,
val: 12
},
reduction: {
displayName: "Reduction",
id: "compReduction",
max: 100,
min: -100,
step: 1,
val: 0
},
release: {
displayName: "Release",
id: "compRelease",
max: 100,
min: -100,
step: 1,
val: 0.25
},
threshold: {
displayName: "Threshold",
id: "compThreshold",
max: 100,
min: -100,
step: 1,
val: -24
}
},
lfo: {
osc: {
sine: {
displayName: "Sine",
id: "lfoSine",
on: true,
val: 0
},
square: {
displayName: "Sq",
id: "lfoSquare",
on: false,
val: 1
},
saw: {
displayName: "Saw",
id: "lfoSaw",
on: false,
val: 2
},
triangle: {
displayName: "Tri",
id: "lfoTriangle",
on: false,
val: 3
}
},
lfoRate: {
displayName: "Rate",
id: "lfoRate",
max: 20,
min: 0.2,
step: 1,
val: 0
},
lfoDepth: {
displayName: "Depth",
id: "lfoDepth",
max: 20,
min: 0.2,
step: 1,
val: 0
}
},
tremolo: {
tremoloDepth: {
displayName: "Depth",
id: "tremoloDepth",
max: 1,
min: 0,
step: .1,
val: 0
},
tremoloRate: {
displayName: "Rate",
id: "tremoloRate",
max: 1,
min: 0,
step: .1,
val: 0
},
},
filter: {
filterTypes: {
lowpass: {
displayName: "Lowpass",
id: "lowpassFilter",
on: false,
val: 0
},
highpass: {
displayName: "Highpass",
id: "highpassFilter",
on: false,
val: 1
},
bandpass: {
displayName: "Bandpass",
id: "bandpassFilter",
on: false,
val: 2
}
},
filterCutoffFreq: {
displayName: "Cutoff",
id: "filterCutoffFreq",
max: 10000,
min: 0,
step: 1,
val: 0
},
filterRes: {
displayName: "Res",
id: "filterRes",
max: 100,
min: 0,
step: 1,
val: 0
}
},
delay: {
delayAttack: {
displayName: "Attack",
id: "delayAttack",
max: 1,
min: 0,
on: false,
step: .01,
val: 0
},
delayDry: {
displayName: "Dry",
id: "delayDry",
max: 1,
min: 0,
on: false,
step: .01,
val: 0
},
delayWet: {
displayName: "Wet",
id: "delayWet",
max: 1,
min: 0,
on: false,
step: .01,
val: 0
},
delayRelease: {
displayName: "Release",
id: "delayRelease",
max: 1,
min: 0,
on: false,
step: .01,
val: 0
},
delayRepeat: {
displayName: "Repeat",
id: "delayRepeat",
max: 1,
min: 0,
on: false,
step: .01,
val: 0
},
delayTime: {
displayName: "Time",
id: "delayTime",
max: 1,
min: 0,
on: false,
step: .01,
val: 0
}
},
vibrato: {
vibratoDepth: {
displayName: "Depth",
id: "vibratoDepth",
max: 1,
min: 0,
on: false,
step: .1,
val: 0
},
vibratoRate: {
displayName: "Rate",
id: "vibratoRate",
max: 1,
min: 0,
on: false,
step: .1,
val: 0
}
},
noise: {
whiteNoise: {
displayName: "White",
id: "whiteNoise",
on: false,
val: "white"
},
pinkNoise: {
displayName: "Pink",
id: "pinkNoise",
on: false,
val: "pink"
},
brownNoise: {
displayName: "Brown",
id: "brownNoise",
on: false,
val: "brown"
}
}
}; |
// LICENSE : MIT
"use strict";
import { RuleHelper } from "textlint-rule-helper";
export default function (context) {
const helper = new RuleHelper(context);
const { Syntax, getSource, RuleError, report } = context;
return {
/*
Match pattern
# Header
TODO: quick fix this.
^^^^^
Hit!
*/
[Syntax.Str](node) {
if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote])) {
return;
}
// get text from node
const text = getSource(node);
// does text contain "todo:"?
const match = text.match(/todo:/i);
if (match) {
const todoText = text.substring(match.index);
report(
node,
new RuleError(`Found TODO: '${todoText}'`, {
index: match.index
})
);
}
},
/*
Match Pattern
# Header
- [ ] Todo
^^^
Hit!
*/
[Syntax.ListItem](node) {
const text = context.getSource(node);
const match = text.match(/\[\s+\]\s/i);
if (match) {
report(
node,
new context.RuleError(`Found TODO: '${text}'`, {
index: match.index
})
);
}
}
};
}
|
/*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.TimelineObserver = function () {
WebInspector.Object.call(this);
};
WebInspector.TimelineObserver.prototype = {
constructor: WebInspector.TimelineObserver,
// Events defined by the "Timeline" domain.
eventRecorded: function eventRecorded(record) {
WebInspector.timelineManager.eventRecorded(record);
},
recordingStarted: function recordingStarted() {
WebInspector.timelineManager.capturingStarted();
},
recordingStopped: function recordingStopped() {
WebInspector.timelineManager.capturingStopped();
}
};
WebInspector.TimelineObserver.prototype.__proto__ = WebInspector.Object.prototype;
|
var path = require('path');
var webpack = require('webpack');
var node_modules = path.resolve(__dirname, 'node_modules');
module.exports = {
devtool: 'source-map',
entry: [
'./src/app'
],
output: {
path: path.join(__dirname, 'public/js'),
filename: 'bundle.js',
publicPath: '/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: [node_modules],
include: path.join(__dirname, 'src')
}]
}
};
|
/**
* Takes a type and returns a function that constructs a new object of that type.
*/
export const construct = Type => (...args) => new Type(...args);
/**
*
*/
export const delegate = fn => (...args) => fn(...args)(...args);
|
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
ScrollView,
Image,
} from 'react-native';
import Util from './../util';
import List from './list';
class Search extends Component{
render(){
return (
<View style={{height:70, borderBottomWidth:Util.pixel,borderColor:'#ccc'}}>
<TextInput style={styles.search} placeholder="搜索"
onSubmitEditing={this._onSubmitEditing.bind(this)}
returnKeyType="search"
placeholderTextColor="#494949" autoFocus={false} onChangeText={this._onChangeText}/>
</View>
);
}
_onChangeText(){}
_onSubmitEditing() {
this.props.navigator.push({
component: List,
barTintColor: '#fff',
title: '互联网资讯',
passProps:{
type: 'it'
}
});
}
}
const styles = StyleSheet.create({
search: {
marginLeft: 10,
marginRight: 10,
height: 35,
borderWidth: Util.pixel,
borderColor: '#ccc',
borderRadius:3,
marginTop:25,
paddingLeft:10,
fontSize:15
}
});
module.exports = Search; |
var orm = require('orm');
var prompt = require('prompt');
require('dotenv').load();
var models = require('../models');
orm.connect((process.env.DATABASE_URL || ('postgresql://' +
process.env.PSQL_USER + ':' +
process.env.PSQL_PASS + '@' +
process.env.PSQL_HOST + '/' +
process.env.PSQL_DB)), function(err, db) {
if (err) {
console.error('Error in connection');
console.error(err);
return;
}
models.define(db, db.models);
var u = new db.models.user();
var _prompt = [
{
name: 'username',
required: true
},
{
name: 'password',
required: true,
hidden: true
},
{
name: 'is_admin',
type: 'boolean',
description: 'admin?',
default: false
}
];
prompt.get(_prompt, function(err, result) {
if (err) {
console.error('Error in reading input');
console.error(err);
db.close();
return;
}
u.username = result.username;
u.is_admin = result.is_admin;
u.setPassword(result.password, function() {
u.save(function(err) {
if (err) {
console.error('Error in saving user');
console.error(err);
db.close();
return;
}
console.log('Created new user with ID ' + u.id);
u.checkPassword(result.password, function(result) {
console.log(result);
})
db.close();
});
});
});
}
)
|
/// <reference types="Cypress" />
context('Spies, Stubs, and Clock', () => {
it('cy.spy() - wrap a method in a spy', () => {
// https://on.cypress.io/spy
cy.visit('https://example.cypress.io/commands/spies-stubs-clocks')
let obj = {
foo () {},
}
let spy = cy.spy(obj, 'foo').as('anyArgs')
obj.foo()
expect(spy).to.be.called
})
it('cy.stub() - create a stub and/or replace a function with stub', () => {
// https://on.cypress.io/stub
cy.visit('https://example.cypress.io/commands/spies-stubs-clocks')
let obj = {
foo () {},
}
let stub = cy.stub(obj, 'foo').as('foo')
obj.foo('foo', 'bar')
expect(stub).to.be.called
})
it('cy.clock() - control time in the browser', () => {
// https://on.cypress.io/clock
// create the date in UTC so its always the same
// no matter what local timezone the browser is running in
let now = new Date(Date.UTC(2017, 2, 14)).getTime()
cy.clock(now)
cy.visit('https://example.cypress.io/commands/spies-stubs-clocks')
cy.get('#clock-div').click()
.should('have.text', '1489449600')
})
it('cy.tick() - move time in the browser', () => {
// https://on.cypress.io/tick
// create the date in UTC so its always the same
// no matter what local timezone the browser is running in
let now = new Date(Date.UTC(2017, 2, 14)).getTime()
cy.clock(now)
cy.visit('https://example.cypress.io/commands/spies-stubs-clocks')
cy.get('#tick-div').click()
.should('have.text', '1489449600')
cy.tick(10000) // 10 seconds passed
cy.get('#tick-div').click()
.should('have.text', '1489449610')
})
})
|
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = require('react');
var _ = require('lodash');
var KeyCodez = require('keycodez');
var Validation = require('./lib/validation');
var ErrorMessages = require('./lib/errors');
var Button = require('./button');
var QuestionSet = require('./questionSet');
var QuestionPanel = (function (_React$Component) {
_inherits(QuestionPanel, _React$Component);
function QuestionPanel(props) {
_classCallCheck(this, QuestionPanel);
_get(Object.getPrototypeOf(QuestionPanel.prototype), 'constructor', this).call(this, props);
this.state = {
validationErrors: this.props.validationErrors
};
}
_createClass(QuestionPanel, [{
key: 'handleAnswerValidate',
value: function handleAnswerValidate(questionId, questionAnswer, validations) {
var _this = this;
if (typeof validations === 'undefined' || validations.length === 0) {
return;
}
/*
* Run the question through its validations and
* show any error messages if invalid.
*/
var questionValidationErrors = [];
validations.forEach(function (validation) {
if (Validation.validateAnswer(questionAnswer, validation, _this.props.questionAnswers)) {
return;
}
questionValidationErrors.push({
type: validation.type,
message: ErrorMessages.getErrorMessage(validation)
});
});
var validationErrors = _.chain(this.state.validationErrors).set(questionId, questionValidationErrors).value();
this.setState({
validationErrors: validationErrors
});
}
}, {
key: 'handleMainButtonClick',
value: function handleMainButtonClick() {
var _this2 = this;
var action = this.props.action['default'];
var conditions = this.props.action.conditions || [];
/*
* We need to get all the question sets for this panel.
* Collate a list of the question set IDs required
* and run through the schema to grab the question sets.
*/
var questionSetIds = this.props.questionSets.map(function (qS) {
return qS.questionSetId;
});
var questionSets = _.chain(this.props.schema.questionSets).filter(function (qS) {
return questionSetIds.indexOf(qS.questionSetId) > -1;
}).value();
/*
* Get any incorrect fields that need erorr messages.
*/
var invalidQuestions = Validation.getQuestionPanelInvalidQuestions(questionSets, this.props.questionAnswers);
/*
* If the panel isn't valid...
*/
if (Object.keys(invalidQuestions).length > 0) {
var validationErrors = _.mapValues(invalidQuestions, function (validations) {
return validations.map(function (validation) {
return {
type: validation.type,
message: ErrorMessages.getErrorMessage(validation)
};
});
});
this.setState({
validationErrors: validationErrors
});
return;
}
/*
* Panel is valid. So what do we do next?
* Check our conditions and act upon them, or the default.
*/
conditions.forEach(function (condition) {
var answer = _this2.props.questionAnswers[condition.questionId];
action = answer == condition.value ? {
action: condition.action,
target: condition.target
} : action;
});
/*
* Decide which action to take depending on
* the action decided upon.
*/
switch (action.action) {
case 'GOTO':
this.props.onSwitchPanel(action.target);
break;
case 'SUBMIT':
this.props.onSubmit(action.target);
break;
}
}
}, {
key: 'handleBackButtonClick',
value: function handleBackButtonClick() {
if (this.props.panelHistory.length == 0) {
return;
}
this.props.onPanelBack();
}
}, {
key: 'handleAnswerChange',
value: function handleAnswerChange(questionId, questionAnswer, validations, validateOn) {
this.props.onAnswerChange(questionId, questionAnswer);
this.setState({
validationErrors: _.chain(this.state.validationErrors).set(questionId, []).value()
});
if (validateOn === 'change') {
this.handleAnswerValidate(questionId, questionAnswer, validations);
}
}
}, {
key: 'handleQuestionBlur',
value: function handleQuestionBlur(questionId, questionAnswer, validations, validateOn) {
if (validateOn === 'blur') {
this.handleAnswerValidate(questionId, questionAnswer, validations);
}
}
}, {
key: 'handleInputKeyDown',
value: function handleInputKeyDown(e) {
if (KeyCodez[e.keyCode] === 'enter') {
e.preventDefault();
this.handleMainButtonClick.call(this);
}
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var questionSets = this.props.questionSets.map(function (questionSetMeta) {
var questionSet = _.find(_this3.props.schema.questionSets, {
questionSetId: questionSetMeta.questionSetId
});
if (!questionSet) {
return undefined;
}
return React.createElement(QuestionSet, { key: questionSet.questionSetId,
id: questionSet.questionSetId,
name: questionSet.name,
questions: questionSet.questions,
classes: _this3.props.classes,
questionAnswers: _this3.props.questionAnswers,
renderError: _this3.props.renderError,
validationErrors: _this3.state.validationErrors,
onAnswerChange: _this3.handleAnswerChange.bind(_this3),
onQuestionBlur: _this3.handleQuestionBlur.bind(_this3),
onKeyDown: _this3.handleInputKeyDown.bind(_this3) });
});
return React.createElement(
'div',
{ className: this.props.classes.questionPanel },
typeof this.props.panelHeader !== 'undefined' || typeof this.props.panelText !== 'undefined' ? React.createElement(
'div',
{ className: this.props.classes.questionPanelHeaderContainer },
typeof this.props.panelHeader ? React.createElement(
'h3',
{ className: this.props.classes.questionPanelHeaderText },
this.props.panelHeader
) : undefined,
typeof this.props.panelText ? React.createElement(
'p',
{ className: this.props.classes.questionPanelText },
this.props.panelText
) : undefined
) : undefined,
React.createElement(
'div',
{ className: this.props.classes.questionSets },
questionSets
),
React.createElement(
'div',
{ className: this.props.classes.buttonBar },
this.props.panelHistory.length > 1 ? React.createElement(Button, { text: this.props.backButtonText,
onClick: this.handleBackButtonClick.bind(this),
className: this.props.classes.backButton }) : undefined,
React.createElement(Button, { text: this.props.button.text,
onClick: this.handleMainButtonClick.bind(this),
className: this.props.classes.controlButton })
)
);
}
}]);
return QuestionPanel;
})(React.Component);
;
QuestionPanel.defaultProps = {
validationErrors: {},
schema: {},
classes: {},
panelId: undefined,
panelIndex: undefined,
panelHeader: undefined,
panelText: undefined,
action: {
'default': {},
conditions: []
},
button: {
text: 'Submit'
},
questionSets: [],
questionAnswers: {},
renderError: undefined,
onAnswerChange: function onAnswerChange() {},
onSwitchPanel: function onSwitchPanel() {},
onPanelBack: function onPanelBack() {},
panelHistory: [],
backButtonText: 'Back'
};
module.exports = QuestionPanel; |
function editorInitConfig(el,settings){
/*
@el - selector
@settings - object
@settings.theme - string
@settings.mode - string
? - экземпляр этого редактора
Создаёт на странице новый редактор ace
*/
var editor = window.ace.edit(el);
editor.$blockScrolling = Infinity;
if(settings){
editor.setTheme(settings.theme);
editor.getSession().setMode(settings.mode);
}else{
editor.setTheme('ace/theme/clouds');
editor.getSession().setMode('ace/mode/sql');
}
return editor;
}
function setTextEd(ed,val){
/*
@ed - editor
@val - string
Установливает указанному редактору значение
*/
ed.setValue(val);
}
function getTextEd(ed,val){
/*
@ed - editor
@val - string
Получает значение указанного редактора
*/
return ed.getValue();
}
module.exports.setText = setTextEd;
module.exports.getText = getTextEd;
module.exports.create = editorInitConfig; |
import React from 'react';
import Headline from './headline'
import Following from './following'
import ArticlesView from '../article/articlesView'
const Main = () => (
// This is the main view.
// On this view we display the user's avatar, their headline,
// their feed of articles (with a search fiilter),
// and their list of followers.
<div className="row">
<div className="row"> </div>
<div className="row"> </div>
<div className="row"> </div>
<div className="col-md-3 col-xs-3" id="contain-setting">
<Headline/>
<Following/>
</div>
<div className="col-md-9 col-xs-9">
<ArticlesView />
</div>
</div>
)
export default Main
|
class microsoft_mediacenter_internal_launchmediacenter {
constructor() {
}
// System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateObjRef() {
}
// bool Equals(System.Object obj)
Equals() {
}
// int GetHashCode()
GetHashCode() {
}
// System.IntPtr GetLaunchDelegate(string args)
GetLaunchDelegate() {
}
// System.Object GetLifetimeService()
GetLifetimeService() {
}
// type GetType()
GetType() {
}
// System.Object InitializeLifetimeService()
InitializeLifetimeService() {
}
// void ReleaseLaunchMaterial()
ReleaseLaunchMaterial() {
}
// string ToString()
ToString() {
}
}
module.exports = microsoft_mediacenter_internal_launchmediacenter;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.