commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
4a7604daa26d9c79585aa3ba249f879b31f6eaa2
remove , at end of js. IE8 chokes on this
core/js/config.js
core/js/config.js
/** * Copyright (c) 2011, Robin Appelman <[email protected]> * This file is licensed under the Affero General Public License version 3 or later. * See the COPYING-README file. */ OC.AppConfig={ url:OC.filePath('core','ajax','appconfig.php'), getCall:function(action,data,callback){ data.action=action; $.getJSON(OC.AppConfig.url,data,function(result){ if(result.status='success'){ if(callback){ callback(result.data); } } }); }, postCall:function(action,data,callback){ data.action=action; $.post(OC.AppConfig.url,data,function(result){ if(result.status='success'){ if(callback){ callback(result.data); } } },'json'); }, getValue:function(app,key,defaultValue,callback){ if(typeof defaultValue=='function'){ callback=defaultValue; defaultValue=null; } OC.AppConfig.getCall('getValue',{app:app,key:key,defaultValue:defaultValue},callback); }, setValue:function(app,key,value){ OC.AppConfig.postCall('setValue',{app:app,key:key,value:value}); }, getApps:function(callback){ OC.AppConfig.getCall('getApps',{},callback); }, getKeys:function(app,callback){ OC.AppConfig.getCall('getKeys',{app:app},callback); }, hasKey:function(app,key,callback){ OC.AppConfig.getCall('hasKey',{app:app,key:key},callback); }, deleteKey:function(app,key){ OC.AppConfig.postCall('deleteKey',{app:app,key:key}); }, deleteApp:function(app){ OC.AppConfig.postCall('deleteApp',{app:app}); }, }; //TODO OC.Preferences
JavaScript
0
@@ -1457,17 +1457,16 @@ pp%7D);%0A%09%7D -, %0A%7D;%0A//TO
869d7cc762ef7b59846730eff66f2a8130ebb4c0
fix mapping of log level
tasks/acetate.js
tasks/acetate.js
/* * grunt-acetate * https://github.com/patricklocal/grunt-acetate * * Copyright (c) 2014 Patrick Arlt * Licensed under the MIT license. */ 'use strict'; var Acetate = require('acetate'); var path = require('path'); var _ = require('lodash'); var gaze = require('gaze'); var util = require('util'); module.exports = function(grunt) { var logHeader = false; grunt.event.on('watch', function() { grunt.log.writeln(); logHeader = true; }); grunt.registerMultiTask('acetate', 'Grunt plugin for the Acetate static site builter.', function() { var done = this.async(); var data = this.data || grunt.config('acetate'); var target = this.target; var configPath = path.join(process.cwd(), data.config); var options = this.options({ keepalive: false, server: false, watch: false, port: 3000, host: 'localhost', findPort: true, logLevel: 'info' }); var acetate; function build() { logHeader = true; acetate.build(function(){ if(!options.keepalive) { done(); } }); } function run() { acetate = new Acetate(configPath); _.defaults(acetate.args, data.args); acetate.log.on('log', function(e){ if(e.show && logHeader){ logHeader = false; grunt.log.header('Task "acetate:"'+target+'" running'); } }); acetate.log.logLevel = options.logLevel; if(options.watch){ acetate.watcher.start(); } if(options.server && options.port){ acetate.server.start(options.host, options.port, options.findPort); } acetate.load(function(){ if(options.clean){ acetate.clean(build); } else { build(); } }); } if(options.watch){ gaze(data.config, function(error, watcher){ // whenever it chagnes watcher.on('changed', function() { // stop the server if we were running it if(options.server && options.port){ acetate.server.stop(); } // stop the watcher if we were running it if(options.watch){ acetate.watcher.stop(); } // rerun everything run(); }); }); } run(); }); };
JavaScript
0.000002
@@ -1417,19 +1417,16 @@ te.log.l -ogL evel = o
ed83c2da0977dbea08e98d9c74d7a790e5d3c153
Remove unused function in test
test/PriorityQueue.test.js
test/PriorityQueue.test.js
import { PriorityQueue } from '../src/utilities/PriorityQueue.js'; const nextFrame = () => new Promise( resolve => requestAnimationFrame( resolve ) ); const nextTick = () => new Promise( resolve => process.nextTick( resolve ) ); describe( 'PriorityQueue', () => { it( 'should run jobs automatically in the correct order.', async () => { const queue = new PriorityQueue(); queue.maxJobs = 6; queue.priorityCallback = item => item.priority; queue.add( { priority: 6 }, () => new Promise( () => {} ) ); queue.add( { priority: 3 }, () => new Promise( () => {} ) ); queue.add( { priority: 4 }, () => new Promise( () => {} ) ); queue.add( { priority: 0 }, () => new Promise( () => {} ) ); queue.add( { priority: 8 }, () => new Promise( () => {} ) ); queue.add( { priority: 2 }, () => new Promise( () => {} ) ); queue.add( { priority: 1 }, () => new Promise( () => {} ) ); await nextFrame(); expect( queue.items.map( item => item.priority ) ).toEqual( [ 0 ] ); expect( queue.currJobs ).toEqual( 6 ); } ); it( 'should run jobs in the correct order.', async () => { const result = []; const cb = item => new Promise( resolve => { result.push( item.priority ); resolve(); } ); const queue = new PriorityQueue(); queue.maxJobs = 1; queue.priorityCallback = item => item.priority; queue.add( { priority: 6 }, cb ); queue.add( { priority: 3 }, cb ); queue.add( { priority: 4 }, cb ); queue.add( { priority: 0 }, cb ); queue.add( { priority: 8 }, cb ); queue.add( { priority: 2 }, cb ); queue.add( { priority: 1 }, cb ); expect( queue.items.length ).toEqual( queue.callbacks.size ); // We require a new frame to trigger each subsequent task for ( let i = 0; i < 7; i ++ ) { await nextFrame(); } expect( result ).toEqual( [ 8, 6, 4, 3, 2, 1, 0 ] ); expect( queue.items.length ).toEqual( queue.callbacks.size ); } ); it( 'should remove an item from the queue correctly.', () => { const A = { priority: 0 }; const B = { priority: 1 }; const C = { priority: 2 }; const D = { priority: 3 }; const queue = new PriorityQueue(); queue.priorityCallback = item => item.priority; queue.add( A, () => new Promise( () => {} ) ); queue.add( B, () => new Promise( () => {} ) ); queue.add( C, () => new Promise( () => {} ) ); queue.add( D, () => new Promise( () => {} ) ); queue.sort(); expect( queue.items ).toEqual( [ A, B, C, D ] ); queue.remove( C ); expect( queue.items ).toEqual( [ A, B, D ] ); queue.remove( A ); expect( queue.items ).toEqual( [ B, D ] ); queue.remove( B ); expect( queue.items ).toEqual( [ D ] ); queue.remove( D ); expect( queue.items ).toEqual( [] ); expect( queue.items.length ).toEqual( queue.callbacks.size ); } ); it( 'should automatically run new jobs when one is finished.', async () => { let called = 0; let resolveFunc = null; const queue = new PriorityQueue(); queue.maxJobs = 1; queue.priorityCallback = item => item.priority; queue.add( { priority: 1 }, () => new Promise( resolve => { resolveFunc = resolve; called ++; } ) ); queue.add( { priority: 0 }, () => new Promise( () => { called ++; } ) ); expect( queue.currJobs ).toEqual( 0 ); await nextFrame(); expect( queue.currJobs ).toEqual( 1 ); expect( resolveFunc ).not.toEqual( null ); expect( called ).toEqual( 1 ); resolveFunc(); // one frame for resolving the promise, one frame schedule new // tasks, and one frame to complete the last one. await nextFrame(); await nextFrame(); expect( queue.currJobs ).toEqual( 1 ); expect( called ).toEqual( 2 ); } ); it( 'should fire the callback with the item and priority.', async () => { const A = { priority: 100 }; const queue = new PriorityQueue(); queue.priorityCallback = item => item.priority; queue.add( A, item => new Promise( () => { expect( item ).toEqual( A ); } ) ); await nextFrame(); } ); it( 'should return a promise that resolves from the add function.', async () => { const queue = new PriorityQueue(); queue.priorityCallback = item => item.priority; let result = null; queue.add( { priority: 0 }, item => Promise.resolve( 1000 ) ).then( res => result = res ); expect( result ).toEqual( null ); await nextFrame(); expect( result ).toEqual( 1000 ); } ); it( 'should not automatically run if autoUpdate is false.', async () => { const queue = new PriorityQueue(); queue.priorityCallback = () => 0; queue.autoUpdate = false; queue.maxJobs = 1; queue.add( {}, async () => {} ); queue.add( {}, async () => {} ); expect( queue.items ).toHaveLength( 2 ); await nextFrame(); expect( queue.items ).toHaveLength( 2 ); queue.scheduleJobRun(); await nextFrame(); expect( queue.items ).toHaveLength( 1 ); await nextFrame(); expect( queue.items ).toHaveLength( 1 ); queue.scheduleJobRun(); await nextFrame(); expect( queue.items ).toHaveLength( 0 ); } ); } );
JavaScript
0.000001
@@ -148,86 +148,8 @@ ) ); -%0Aconst nextTick = () =%3E new Promise( resolve =%3E process.nextTick( resolve ) ); %0A%0Ade
545a3da962f6e7e121059d851f1042ddcda9e149
fix test
test/compiler/axis.test.js
test/compiler/axis.test.js
'use strict'; var expect = require('chai').expect; var axis = require('../../src/compiler/axis'), Encoding = require('../../src/Encoding'); describe('Axis', function() { var stats = {a: {distinct: 5}, b: {distinct: 32}}, layout = { cellWidth: 60, // default characterWidth = 6 cellHeight: 60 }; describe('(X) for Time Data', function() { var field = 'a', timeUnit = 'month', encoding = Encoding.fromSpec({ encoding: { x: {name: field, type: 'T', timeUnit: timeUnit} } }); var _axis = axis.def('x', encoding, { width: 200, height: 200, cellWidth: 200, cellHeight: 200, x: { axisTitleOffset: 60 }, y: { axisTitleOffset: 60 } }, stats); //FIXME decouple the test here it('should use custom label', function() { expect(_axis.properties.labels.text.scale).to.equal('time-'+ timeUnit); }); it('should rotate label', function() { expect(_axis.properties.labels.angle.value).to.equal(270); }); }); describe('grid()', function () { // FIXME(kanitw): Jul 19, 2015 - write test }); describe('labels.scale()', function () { // FIXME(kanitw): Jul 19, 2015 - write test }); describe('labels.format()', function () { // FIXME(kanitw): Jul 19, 2015 - write test }); describe('labels.angle()', function () { it('should set explicitly specified angle', function () { var def = axis.labels.angle({}, Encoding.fromSpec({ encoding: { x: {name: 'a', type: 'T', axis:{labelAngle: 90}} } }), 'x'); expect(def.properties.labels.angle).to.eql({value: 90}); }); }); describe('labels.rotate()', function () { // FIXME(kanitw): Jul 19, 2015 - write test }); describe('orient()', function () { it('should return specified orient', function () { var orient = axis.orient(Encoding.fromSpec({ encoding: { x: {name: 'a', axis:{orient: 'bottom'}} } }), 'x', {}, stats); expect(orient).to.eql('bottom'); }); it('should return undefined by default', function () { var orient = axis.orient(Encoding.fromSpec({ encoding: { x: {name: 'a'} } }), 'x', {}, stats); expect(orient).to.eql(undefined); }); it('should return top for COL', function () { var orient = axis.orient(Encoding.fromSpec({ encoding: { x: {name: 'a'}, col: {name: 'a'} } }), 'col', {}, stats); expect(orient).to.eql('top'); }); it('should return top for X with high cardinality, ordinal Y', function () { var orient = axis.orient(Encoding.fromSpec({ encoding: { x: {name: 'a'}, y: {name: 'b', type: 'O'} } }), 'x', {}, stats); expect(orient).to.eql('top'); }); }); describe('title()', function () { it('should add explicitly specified title', function () { var title = axis.title(Encoding.fromSpec({ encoding: { x: {name: 'a', axis: {title: 'Custom'}} } }), 'x', stats, layout); expect(title).to.eql('Custom'); }); it('should add return fieldTitle by default', function () { var title = axis.title(Encoding.fromSpec({ encoding: { x: {name: 'a', axis: {titleMaxLength: '3'}} } }), 'x', layout); expect(title).to.eql('a'); }); it('should add return fieldTitle by default', function () { var title = axis.title(Encoding.fromSpec({ encoding: { x: {name: 'a', aggregate: 'sum', axis: {titleMaxLength: '10'}} } }), 'x', layout); expect(title).to.eql('SUM(a)'); }); it('should add return fieldTitle by default and truncate', function () { var title = axis.title(Encoding.fromSpec({ encoding: { x: {name: 'a', aggregate: 'sum', axis: {titleMaxLength: '3'}} } }), 'x', layout); expect(title).to.eql('SU…'); }); it('should add return fieldTitle by default and truncate', function () { var title = axis.title(Encoding.fromSpec({ encoding: { x: {name: 'abcdefghijkl'} } }), 'x', layout); expect(title).to.eql('abcdefghi…'); }); }); describe('titleOffset()', function () { // FIXME(kanitw): Jul 19, 2015 - write test }); });
JavaScript
0.000002
@@ -1166,650 +1166,8 @@ );%0A%0A - describe('labels.scale()', function () %7B%0A // FIXME(kanitw): Jul 19, 2015 - write test%0A %7D);%0A%0A describe('labels.format()', function () %7B%0A // FIXME(kanitw): Jul 19, 2015 - write test%0A %7D);%0A%0A describe('labels.angle()', function () %7B%0A it('should set explicitly specified angle', function () %7B%0A var def = axis.labels.angle(%7B%7D, Encoding.fromSpec(%7B%0A encoding: %7B%0A x: %7Bname: 'a', type: 'T', axis:%7BlabelAngle: 90%7D%7D%0A %7D%0A %7D), 'x');%0A expect(def.properties.labels.angle).to.eql(%7Bvalue: 90%7D);%0A %7D);%0A %7D);%0A%0A describe('labels.rotate()', function () %7B%0A // FIXME(kanitw): Jul 19, 2015 - write test%0A %7D);%0A%0A de
6186568e7149e799c0652e65eda244e9a7f3c3fe
fix tests
test/compiler/data.spec.js
test/compiler/data.spec.js
'use strict'; var expect = require('chai').expect; var data = require('../../src/compiler/data'), Encoding = require('../../src/Encoding'); describe('data', function () { describe('for aggregate encoding', function () { it('should contain two tables', function() { var encoding = Encoding.fromSpec({ encoding: { x: {name: 'a', type: 'T'}, y: {name: 'b', type: 'Q', scale: {type: 'log'}, aggregate: 'sum'} } }); var _data = data(encoding); expect(_data.length).to.equal(2); }); }); describe('when contains log in non-aggregate', function () { var rawEncodingWithLog = Encoding.fromSpec({ encoding: { x: {name: 'a', type: 'T'}, y: {name: 'b', type: 'Q', scale: {type: 'log'}} } }); var _data = data(rawEncodingWithLog); it('should contains one table', function() { expect(_data.length).to.equal(1); }); it('should have filter non-positive in raw', function() { var rawTransform = _data[0].transform; expect(rawTransform[rawTransform.length - 1]).to.eql({ type: 'filter', test: 'datum.b > 0' }); }); }); }); describe('data.raw', function() { describe('with explicit values', function() { var encoding = Encoding.fromSpec({ data: { values: [{a: 1, b:2, c:3}, {a: 4, b:5, c:6}] } }); var raw = data.raw(encoding, {}); it('should have values', function() { expect(raw.name).to.equal('raw'); expect(raw.values).to.deep.equal([{a: 1, b:2, c:3}, {a: 4, b:5, c:6}]); }); it('should have raw.format if not required', function(){ expect(raw.format).to.eql(undefined); }); }); describe('with link to url', function() { var encoding = Encoding.fromSpec({ data: { url: 'http://foo.bar' } }); var raw = data.raw(encoding); it('should have format json', function() { expect(raw.name).to.equal('raw'); expect(raw.format.type).to.equal('json'); }); it('should have correct url', function() { expect(raw.url).to.equal('http://foo.bar'); }); }); describe('formatParse', function () { it('should have correct parse', function() { var encoding = Encoding.fromSpec({ encoding: { x: {name: 'a', type: 'T'}, y: {name: 'b', type: 'Q'}, color: {name: '*', type: 'Q', aggregate: 'count'} } }); var raw = data.raw(encoding); expect(raw.format.parse).to.eql({ 'a': 'date', 'b': 'number' }); }); }); describe('transform', function () { var encoding = Encoding.fromSpec({ data: { filter: 'datum.a > datum.b && datum.c === datum.d' }, encoding: { x: {name: 'a', type:'T', timeUnit: 'year'}, y: { 'bin': {'maxbins': 15}, 'name': 'Acceleration', 'type': 'Q' } } }); describe('bin', function() { it('should add bin transform', function() { var transform = data.raw.transform.bin(encoding); expect(transform[0]).to.eql({ type: 'bin', field: 'Acceleration', output: {bin: 'bin_Acceleration'}, maxbins: 15 }); }); }); describe('nullFilter', function() { var spec = { marktype: 'point', encoding: { y: {name: 'Q', type:'Q'}, x: {name: 'T', type:'T'}, color: {name: 'O', type:'O'} } }; it('should add filterNull for Q and T by default', function () { var encoding = Encoding.fromSpec(spec); expect(data.raw.transform.nullFilter(encoding)) .to.eql([{ type: 'filter', test: 'datum.T!==null && datum.Q!==null' }]); }); it('should add filterNull for O when specified', function () { var encoding = Encoding.fromSpec(spec, { config: { filterNull: {O: true} } }); expect(data.raw.transform.nullFilter(encoding)) .to.eql([{ type: 'filter', test:'datum.T!==null && datum.Q!==null && datum.O!==null' }]); }); // }); }); describe('filter', function () { it('should return array that contains a filter transform', function () { expect(data.raw.transform.filter(encoding)) .to.eql([{ type: 'filter', test: 'datum.a > datum.b && datum.c === datum.d' }]); }); }); describe('time', function() { it('should add formula transform', function() { var transform = data.raw.transform.time(encoding); expect(transform[0]).to.eql({ type: 'formula', field: 'year_a', expr: 'utcyear(datum.a)' }); }); }); it('should have null filter, timeUnit, bin then filter', function () { var transform = data.raw.transform(encoding); expect(transform[0].type).to.eql('filter'); expect(transform[1].type).to.eql('formula'); expect(transform[2].type).to.eql('bin'); expect(transform[3].type).to.eql('filter'); }); }); }); describe('data.aggregated', function () { it('should return correct aggregation', function() { var encoding = Encoding.fromSpec({ encoding: { 'y': { 'aggregate': 'sum', 'name': 'Acceleration', 'type': 'Q' }, 'x': { 'name': 'origin', "type": "O" }, color: {name: '*', type: 'Q', aggregate: 'count'} } }); var aggregated = data.aggregate(encoding); expect(aggregated ).to.eql({ "name": AGGREGATE, "source": "raw", "transform": [{ "type": "aggregate", "groupby": ["origin"], "summarize": { '*': ['count'], 'Acceleration': ['sum'] } }] }); }); });
JavaScript
0.000001
@@ -2986,32 +2986,121 @@ %7D%0A %7D);%0A%0A + var stats = %7B%0A Acceleration: %7B%0A min: 0,%0A max: 100%0A %7D%0A %7D;%0A%0A describe('bi @@ -3213,35 +3213,43 @@ orm.bin(encoding +, stats );%0A +%0A expect(t @@ -3392,16 +3392,54 @@ bins: 15 +,%0A min: 0,%0A max: 100 %0A @@ -5167,32 +5167,39 @@ ansform(encoding +, stats );%0A expect(
33056a24182c45157e6bd6aad96fc42691b7e02c
Remove print
test/compiler/time.spec.js
test/compiler/time.spec.js
'use strict'; var expect = require('chai').expect; var time = require('../../src/compiler/time'), Encoding = require('../../src/Encoding'); describe('Time', function() { var fieldName = 'a', timeUnit = 'month', encoding = Encoding.fromSpec({ encoding: { x: {name: fieldName, type: 'T', timeUnit: timeUnit} } }), spec = time({data: [{name: RAW}, {name: TABLE}]}, encoding, {}); it('should add formula transform', function() { var data = spec.data[1]; console.log(data.transform); expect(data.transform).to.be.ok; expect(data.transform.filter(function(t) { return t.type === 'formula' && t.field === encoding.field('x') && t.expr === time.formula(encoding._enc.x); }).length).to.be.above(0); }); it('should add custom axis scale', function() { expect(spec.scales.filter(function(scale) { return scale.name == 'time-'+ timeUnit; }).length).to.equal(1); }); });
JavaScript
0.000016
@@ -497,41 +497,8 @@ 1%5D;%0A - console.log(data.transform);%0A
90a51c00259e79213aeb02025cd3265c29e2671b
delete lively.lang._prevLivelyGlobal for compat with new lively.lang
core/lively/Base.js
core/lively/Base.js
/* * Copyright (c) 2006-2009 Sun Microsystems, Inc. * Copyright (c) 2008-2011 Hasso Plattner Institute * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function installLivelyLangGlobals() { var isNodejs = typeof UserAgent !== "undefined" && UserAgent.isNodejs; var livelyLang = isNodejs ? require("lively.lang") : lively.lang; if (isNodejs) { if (!global.lively) global.lively = {}; global.lively.lang = livelyLang; } livelyLang.deprecatedLivelyPatches(); })(); (function defineFunctionPrototypeName() { if (Function.prototype.name === undefined) { Function.prototype.__defineGetter__("name", function () { // TODO: find a better method, this is just a heuristic if (this.displayName) { var splitted = this.displayName.split("."); return splitted[splitted.length - 1]; } var md = String(this).match(/function\s+(.*)\s*\(\s*/); return md ? md[1] : "Empty"; }); } })(); Object.extend(Global, { dbgOn: function dbgOn(cond, optMessage) { if (cond && optMessage) console.warn(optMessage); if (cond) debugger; // also call as: throw dbgOn(new Error(....)) return cond; }, assert: function assert(value, message) { if (value) { return; } // capture the stack var stack; try { throw new Error() } catch(e) { stack = e.stack || '' }; alert('Assertion failed' + (message ? ': ' + message : '!') + '\n' + stack); } });
JavaScript
0
@@ -1502,16 +1502,59 @@ ches();%0A + %0A delete lively.lang._prevLivelyGlobal;%0A %7D)();%0A%0A(
24dee001be213846ce220cabcb8e9c5787f5d2d4
add GSJS helper functions to game object class
src/model/GameObject.js
src/model/GameObject.js
'use strict'; module.exports = GameObject; var config = require('config'); var utils = require('utils'); GameObject.prototype.TSID_INITIAL = 'G'; GameObject.prototype.__isGO = true; /** * Generic constructor for both instantiating an existing game object * (from JSON data), and creating a new object. * * @param {object} [data] initialization values (properties are * shallow-copied into the game object) * @constructor */ function GameObject(data) { if (!data) data = {}; // initialize TSID/class ID (use deprecated properties if necessary, and // keep them as non-enumerable so they are available, but not persisted) this.tsid = data.tsid || data.id || utils.makeTsid(this.TSID_INITIAL, config.getGsid()); utils.addNonEnumerable(this, 'id', this.tsid); // deprecated if (data.class_tsid || data.class_id) { this.class_tsid = data.class_tsid || data.class_id; utils.addNonEnumerable(this, 'class_id', this.class_tsid); // deprecated } // add non-enumerable internal properties utils.addNonEnumerable(this, 'deleted', false); // copy supplied data // TODO: remove 'dynamic' partition in fixture data, and get rid of special handling here var key; for (key in data.dynamic) { if (!(key in this)) { this[key] = data.dynamic[key]; } } for (key in data) { if (key !== 'dynamic' && !(key in this)) { this[key] = data[key]; } } if (!this.ts) { this.ts = new Date().getTime(); } } /** * Creates a processed shallow copy of this game object's data, * prepared for serialization. * * The returned data only contains non-function-type direct ("own") * properties whose name does not start with a "!". Complex * `object`-type properties (specifically, references to other game * objects) are not handled separately here, i.e. the caller may need * to replace those with appropriate reference structures before actual * serialization (see {@link module:data/objrefProxy~refify| * objrefProxy.refify}). * * @returns {object} shallow copy of the game object, prepared for * serialization */ GameObject.prototype.serialize = function serialize() { var ret = {}; var keys = Object.keys(this); // Object.keys only includes own properties for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (k[0] !== '!') { var val = this[k]; if (typeof val !== 'function') { ret[k] = val; } } } return ret; }; /** * @returns {string} */ GameObject.prototype.toString = function toString() { return '[' + this.constructor.name + '#' + this.tsid + ']'; }; /** * Schedules this object for deletion after the current request. */ GameObject.prototype.del = function del() { this.deleted = true; };
JavaScript
0
@@ -2680,12 +2680,1172 @@ = true;%0A%7D;%0A +%0A%0A/**%0A * Helper function originally defined in %3Cgsjs/common.js%3E. All the%0A * functions there should really be added to all game object prototypes%0A * in gsjsBridge (then this here wouldn't be necessary), but that would%0A * require prefixing a zillion calls in GSJS code with 'this.'.%0A * @private%0A */%0AGameObject.prototype.getProp = function getProp(key) %7B%0A%09return this%5Bkey%5D;%0A%7D;%0A%0A%0A/**%0A * Helper function originally defined in %3Cgsjs/common.js%3E. All the%0A * functions there should really be added to all game object prototypes%0A * in gsjsBridge (then this here wouldn't be necessary), but that would%0A * require prefixing a zillion calls in GSJS code with 'this.'.%0A * @private%0A */%0AGameObject.prototype.setProp = function setProp(key, val) %7B%0A%09this%5Bkey%5D = val;%0A%7D;%0A%0A%0A/**%0A * Helper function originally defined in %3Cgsjs/common.js%3E. All the%0A * functions there should really be added to all game object prototypes%0A * in gsjsBridge (then this here wouldn't be necessary), but that would%0A * require prefixing a zillion calls in GSJS code with 'this.'.%0A * @private%0A */%0AGameObject.prototype.setProps = function setProps(props) %7B%0A%09for (var k in props) %7B%0A%09%09this%5Bk%5D = props%5Bk%5D;%0A%09%7D%0A%7D;%0A
8993e5ad0753ea398c1e16fccde99a186b141c66
remove console.log
static/js/live_editor.js
static/js/live_editor.js
/* global $ */ (function (window, document, $) { 'use strict'; var LiveEditor = function LiveEditor (params) { console.log('Live Editor Init...'); this.init(params); console.log('Live Editor Done...'); } LiveEditor.prototype.init = function (params) { this.initVars(params); this.domOutlineInit(); this.floatingMenuInit(); this.bindEvents(); }; LiveEditor.prototype.initVars = function (params) { this.$editor = $(params.editor).find('iframe'); this.$codePainel = $('#code-painel').find('textarea'); this.domOutline = null; this.scriptList = []; }; LiveEditor.prototype.domOutlineInit = function () { this.domOutline = DomOutline({ realtime: true, onClick: this.sendEventOnClick, elem: this.$editor.contents().find('html body'), initialPosition: this.$editor.offset() }); this.domOutline.start(); }; LiveEditor.prototype.floatingMenuInit = function () { window.floatingMenu = new FloatingMenu(); }; LiveEditor.prototype.bindEvents = function () { var self = this; document.addEventListener('domOutlineOnClick', function (e) { self.setCurrentElement(self.domOutline.element); self.openCurrentSettings(); self.domOutline.pause(); }, false); document.addEventListener('floatingMenuItemClicked', function (e) { self.operationInit(e.detail.operation); }, false); this.$editor.contents().find('html').on('click', function(e) { if (e.toElement != liveEditor.$currentSelected[0]) { floatingMenu.close(); self.domOutline.start(); } }); }; LiveEditor.prototype.sendEventOnClick = function () { var _event = new Event('domOutlineOnClick'); document.dispatchEvent(_event); } LiveEditor.prototype.setCurrentElement = function (elem) { this.currentSelected = this.getElementPath(elem); this.$currentSelected = this.$editor.contents().find(this.currentSelected); console.log('Current: ' + this.currentSelected); }; LiveEditor.prototype.getElementPath = function (elem) { console.log('Getting element path...: ' + elem); if (elem.length != 1) elem = $(elem); var path, node = elem; while (node.length) { var realNode = node[0], name = realNode.localName; if (!name) break; name = name.toLowerCase(); var parent = node.parent(); var siblings = parent.children(name); if (siblings.length > 1) { name += ':eq(' + siblings.index(realNode) + ')'; } path = name + (path ? '>' + path : ''); node = parent; } return path; }; LiveEditor.prototype.getCurrentParentPath = function () { var a = this.$currentSelected[0]; var els = []; while (a) { els.unshift(a); a = a.parentNode; } return els }; LiveEditor.prototype.openCurrentSettings = function () { if (this.currentSelected) { var $DomOutlineBox = $('.DomOutline_box'); floatingMenu.create({ name: this.$currentSelected.prop('tagName').toLowerCase(), posLeft: $DomOutlineBox.offset().left + $DomOutlineBox.width(), posTop: $DomOutlineBox.offset().top, container: this.containerFormat() }); floatingMenu.open(); } else { console.log('No item has been selected...'); } }; LiveEditor.prototype.containerFormat = function () { var pathList = this.getCurrentParentPath(), _list = []; for (var i=0; i <= pathList.length - 1; i++) { if (pathList[i].tagName) { _list.push({ 'value': pathList[i].tagName.toLowerCase(), 'name': this.getElementPath(pathList[i]) }); } } return _list; }; LiveEditor.prototype.operationInit = function (operation) { if (operation === 'remove') { this.currentSelectedRemove(); } this.domOutline.start(); floatingMenu.close(); this.codePainelUpdate(); }; LiveEditor.prototype.currentSelectedRemove = function () { var str = '$("' + this.currentSelected + '").remove();'; this.addToScript(str); this.$editor.contents().find(this.currentSelected).remove(); }; LiveEditor.prototype.addToScript = function (str) { this.scriptList.push(str); }; LiveEditor.prototype.codePainelUpdate = function () { this.$codePainel.html(this.scriptList); }; window.LiveEditor = LiveEditor; })(window, document, $);
JavaScript
0.000006
@@ -2306,66 +2306,8 @@ ) %7B%0A - console.log('Getting element path...: ' + elem);%0A%0A
e93e7bf4b1715a08311b688a5fa3b51a0a1d3331
Change `composedUrl` to use the abstracted s/ URL
src/models/HiveModel.js
src/models/HiveModel.js
/** * HiveModel.js */ (function (spiderOakApp, window, undefined) { "use strict"; var console = window.console || {}; console.log = console.log || function(){}; var Backbone = window.Backbone, _ = window._, $ = window.$, s = window.s; spiderOakApp.HiveModel = spiderOakApp.FolderModel.extend({ defaults: { hasHive: true }, parse: function(resp, xhr) { if (resp.syncfolder) { resp.syncfolder.name = s("SpiderOak Hive"); return resp.syncfolder; } else { this.set("hasHive", false); return this.attributes; } }, composedUrl: function(bare) { var urlTail = encodeURI(this.get("device_path")); var urlHead = this.url.replace("s\/","") + this.get("device_encoded"); if (bare) { urlHead = urlHead && urlHead.split("?")[0]; urlTail = urlTail && urlTail.split("?")[0]; } return (urlHead || "") + (urlTail || ""); } }); })(window.spiderOakApp = window.spiderOakApp || {}, window);
JavaScript
0
@@ -702,119 +702,53 @@ l = -encodeURI(this.get(%22device_path%22));%0A var urlHead = this.url.replace(%22s%5C/%22,%22%22) + this.get(%22device_encoded%22) +this.get(%22url%22);%0A var urlHead = this.url ;%0A
1c54b2f98991ee98ca357479cacd8e44ad6bd6eb
Remove consoles in frontend
static/scripts/script.js
static/scripts/script.js
function renderVoteData(vote) { console.log('rendering vote', vote); var skript = $('#skript-' + vote.id); skript.find('.vote-number').text(vote.votes); skript.find('.vote-bar').animate( { width: '' + (vote.votePercentage * 100) + '%'}, 300); if (vote.channel) { skript .find('.channel').text(vote.channel) .removeClass('choose').addClass('fixed'); } else { var channel = skript.find('.channel'); if (vote.setup){ channel.html(vote.setup.irc.channel); } channel.removeClass('fixed').addClass('choose'); } } function renderSkript(skript) { console.log(skript); $('#templates .skript'). clone(). attr('id', 'skript-' + skript.id). find('.title').text(skript.title).end(). find('.author').text(skript.author).end(). find('.vote').click(function() { castVote(skript.id); }).end(). appendTo('#skript-list'); renderVoteData(skript); } function loadSkripts(skripts) { $.each(skripts, function(id, skript) { renderSkript(skript); }); } function castVote(id) { var input = $('#skript-' + id + ' input'); var span = $('<span>' + input.val() + '</span>'); input.replaceWith(span); $.post('/api/vote/' + id, { channel: input.val() }, function(res) { highlightVote(id); }); } function highlightVote(id) { if (id) { $('#skript-' + id).addClass('voted-for'); $('#skript-list').addClass('vote-casted') } else { $('.skript').removeClass('voted-for'); $('#skript-list').removeClass('vote-casted') } } function handleShowTimes(data) { handleNextShow(data.next); handleCurrentShow(data.current); } function handleCurrentShow(currentShow) { console.log("current show", currentShow); if (currentShow.status == 'running') { $('#show') .removeClass('stopped').addClass('running') .find('#current-show') .find('.current-show-title').html(currentShow.skript.title).end() .find('.current-show-author').html(currentShow.skript.author).end() .find('span.channel').text(currentShow.skript.channel).end() .find('a.channel').attr('href', 'irc://chat.freenode.net/' + currentShow.skript.channel); } else { $('#show').removeClass('running').addClass('stopped'); } } function handleNextShow(time) { time = new Date(time); console.log("Next show: ", time); $('#next-show'). find('.countdown').removeClass('hasCountdown').html('').end(). find('.countdown').countdown({ until: time, layout: '<span class="clock-letter">{m10}</span>' + '<span class="clock-letter">{m1}</span>' + ':' + '<span class="clock-letter">{s10}</span>' + '<span class="clock-letter">{s1}</span>' }); } var openLightBox = function(openId){ var box = $(openId); if (openId == '#irc') { var channel = $('#current-show .channel:first').text().slice(1); if (!box.hasClass('running') || (box.hasClass('running') && box.attr('channel') != channel)) { box.html('<iframe src="http://webchat.freenode.net?nick=onlooker-.&channels=' + channel + '&uio=MT1mYWxzZSY3PWZhbHNlJjk9dHJ1ZSYxMT0yMQ7f" width="647" height="400"></iframe>'); box.addClass('running'); box.attr('channel', channel); }; }; box.fadeIn(); box.css({ 'margin-top' : -(box.height() + 80) / 2, 'margin-left' : -(box.width() + 80) / 2 }); $('#lightbox-background').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); var closeLightBox = function(){ location.hash = ""; $("body").css({"overflow": "auto"}); $('#lightbox-background, .lightbox').fadeOut(); }; $('#lightbox-background').live('click', function(e){ e.preventDefault(); closeLightBox(); }); $('.lightbox a.close').live('click', function(e){ e.preventDefault(); closeLightBox(); }); $("body").css({"overflow": "hidden"}); }; $(document).ready(function() { $(".open-lightbox").click(function(e){ openLightBox($(this).attr("href")); }); if (location.hash.length > 1){ openLightBox(location.hash); } $.getJSON('/api/skripts', function(skripts) { loadSkripts(skripts); }); document.socket = io.connect('/'); document.socket.on('show times', handleShowTimes); document.socket.on('votes', function(votes) { $.each(votes, function(id, vote) { renderVoteData(vote); }); }); document.socket.on('next show', function(show) { if (show) { console.log('next show is', show) $('#next-show'). addClass('upcoming-show').removeClass('no-upcoming-show'). find('.next-show-title').text(show.title).end(). find('.next-show-author').text(show.author); } else { $('#next-show'). removeClass('upcoming-show').addClass('no-upcoming-show') } }) document.socket.on('my vote', function(id) { highlightVote(id); var hasVoted = id !== null; if (!hasVoted) { $('#skript-list span.channel').click(function() { var input = $('<input />', {'type': 'text', 'name': 'channel', 'value': $(this).html()}); $(this).replaceWith(input); input.focus(); }); } }); });
JavaScript
0.000001
@@ -21,32 +21,34 @@ ata(vote) %7B%0A +// console.log('ren @@ -64,24 +64,24 @@ te', vote);%0A - var skri @@ -631,16 +631,18 @@ pt) %7B%0A +// console. @@ -1792,24 +1792,26 @@ Show) %7B%0A +// console.log( @@ -2443,24 +2443,26 @@ (time);%0A +// console.log( @@ -4712,32 +4712,32 @@ if (show) %7B%0A - cons @@ -4732,16 +4732,18 @@ +// console.
67ff7e31e4fdb03db5558b15dfd660ba7c4ad864
missing semicolon
src/patterns/bumper.js
src/patterns/bumper.js
define([ "jquery", "../core/parser", "../registry" ], function($, Parser, registry) { var parser = new Parser("bumper"); parser.add_argument("margin", 0); var _ = { name: "bumper", trigger: ".pat-bumper", init: function($el, options) { // initialize the elements $el.each(function() { var $this = $(this), opts = parser.parse($this, options), top = $this.offset().top - parseFloat($this.css('marginTop').replace(/auto/, 0)); $this.data('patterns.bumper', {'top': top, 'margin': opts.margin, 'threshold': top - opts.margin}); }); $(window).scroll(function() { _._testBump($el, $(this).scrollTop()); }); _._testBump($el, $(window).scrollTop()); }, _testBump: function($el, y) { $el.each(function() { var $this = $(this), top = $this.data('patterns.bumper').threshold; if (y > top) { $this.addClass('bumped'); } else { $this.removeClass('bumped'); } }); } } registry.register(_); return _; }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
JavaScript
0.999988
@@ -1214,24 +1214,25 @@ %7D%0A %7D +; %0A registr
e4f2399f10749b3e2ddfc3929ab66fc207a8dd4b
create separate module for image features
stitch/js/imgfeatures.js
stitch/js/imgfeatures.js
//imgfeatures /*/////////////////////////////////////////////////////////////////// Make getters and setters for width and hight in order to make the canvas outside this object ////////////////////////////////////////////////////////////////////*/ (function(_this){ "use strict"; var imgOpt = function(imgsrc){ this.dummy = 12; this.img = new Image(); this.img.src = imgsrc; } //function myPowerConstructor(x){ _this['myPowerConstructor'] = function(x, stat){ stat.add("load image into browser"); stat.add("fast corners"); stat.add("gradientVectors"); stat.add("descriptors"); stat.start("load image into browser"); var that = new imgOpt(x); stat.stop("load image into browser"); var myCtx; var myImageW; var myImageH; var myImg_u8; //var myCorners = []; that.corners = []; that.descriptors = []; ///////////////////////////////////////////////////////// //corner stuff // This is sets up the intrestpoint detector stuff function setupFastkeypointdetector(my_opt, callback) { myImg_u8 = new jsfeat.matrix_t(myImageW, myImageH, jsfeat.U8_t | jsfeat.C1_t); //set corners var i = myImageW*myImageH; while(--i >= 0) { that.corners[i] = new jsfeat.point2d_t(0,0,0,0); } jsfeat.fast_corners.set_threshold(my_opt.corner_threshold); callback(0 , my_opt); }; function computeFast(xoffset, my_opt) { var border = my_opt.descriptor_radius; //is relative to the descriptor radius var imageData = myCtx.getImageData(xoffset, 0, myImageW, myImageH); jsfeat.imgproc.grayscale(imageData.data, myImg_u8.data); //prev_count = count; that.count = jsfeat.fast_corners.detect(myImg_u8, that.corners, border); }; ///////END corner stuff///////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// Descriptor stuff function computeDetectors(this_canvas, descriptor_radius) { var windowRadius = descriptor_radius;//my_opt.descriptor_radius; var numout = 0; stat.start("gradientVectors"); var vectors = processing.gradientVectors(this_canvas); stat.stop("gradientVectors"); stat.start("descriptors"); var desc = new Array(that.count); for(var i =0; i < that.count; i++) { var xpos = that.corners[i].x; var ypos = that.corners[i].y; that.descriptors[i] = [[xpos, ypos], extractHistogramsFromWindow(xpos,ypos,windowRadius, vectors)]; } stat.stop("descriptors"); }; function extractHistogramsFromWindow(x,y, radius, vectors){ var cellradius = radius / 2; var histograms = extractHistogramsFromCell(x-radius, y-radius, cellradius, vectors).concat( extractHistogramsFromCell(x-(radius/2), y-radius, cellradius, vectors), extractHistogramsFromCell(x, y-radius, cellradius, vectors), extractHistogramsFromCell(x+(radius/2), y-radius, cellradius, vectors), extractHistogramsFromCell(x-radius, y-(radius/2), cellradius, vectors), extractHistogramsFromCell(x-(radius/2), y-(radius/2), cellradius, vectors), extractHistogramsFromCell(x, y-(radius/2), cellradius, vectors), extractHistogramsFromCell(x+(radius/2), y-(radius/2), cellradius, vectors), extractHistogramsFromCell(x-radius, y, cellradius, vectors), extractHistogramsFromCell(x-(radius/2), y, cellradius, vectors), extractHistogramsFromCell(x, y, cellradius, vectors), extractHistogramsFromCell(x+(radius/2), y, cellradius, vectors), extractHistogramsFromCell(x-radius, y+(radius/2), cellradius, vectors), extractHistogramsFromCell(x-(radius/2), y+(radius/2), cellradius, vectors), extractHistogramsFromCell(x, y+(radius/2), cellradius, vectors), extractHistogramsFromCell(x+(radius/2), y+(radius/2), cellradius, vectors) ); norm.L2(histograms); return histograms; } /* Provide the x, y cordinates of the upper left corner of the cell */ function extractHistogramsFromCell(x,y, cellradius, gradients) { //from x-rad, y-rad till x,y var histogram = zeros(8); for (var i = 0; i < cellradius; i++) { for (var j = 0; j < cellradius; j++) { var vector = gradients[y + i][x + j]; var bin = binFor(vector.orient, 8); histogram[bin] += vector.mag; //console.log("y : ", y + i, "x :", x + j); } } //console.log("my hist : ", histogram); return histogram; }; function binFor(radians, bins) { var angle = radians * (180 / Math.PI); if (angle < 0) { angle += 180; } // center the first bin around 0 angle += 90 / bins; angle %= 180; var bin = Math.floor(angle / 180 * bins); return bin; } function zeros(size) { var array = new Array(size); for (var i = 0; i < size; i++) { array[i] = 0; } return array; } ///////END descriptor stuff////////////////////////////////////// return { set: function(this_canvas, my_opt, callback) { //initialize the image resolution that.img.onload = function() { myImageW = that.img.width; myImageH = that.img.height; this_canvas.width = myImageW; this_canvas.height = myImageH; myCtx = this_canvas.getContext('2d'); myCtx.drawImage(this, 0, 0); stat.start("fast corners"); setupFastkeypointdetector(my_opt, computeFast); stat.stop("fast corners"); computeDetectors(this_canvas, my_opt.descriptor_radius); callback(); }; return myImageW; }, set_threshold: function(threshold) { _threshold = Math.min(Math.max(threshold, 0), 255); return _threshold; }, getNuberOfPoints: function() { var npts = that.count; return that.count; }, getDescriptor: function() { var descr = that.descriptors; return descr; } }; }; }(this));
JavaScript
0
@@ -677,48 +677,8 @@ (x); -%0A%09%09stat.stop(%22load image into browser%22); %0A%0A%09%09 @@ -5612,16 +5612,60 @@ 0, 0);%0A +%09%09%09 %09%09stat.stop(%22load image into browser%22);%0A %09%09%09 %09%09st
df91fcef732ab2176835f982f6f2d8f293fc0157
response is suck
listeners/events/app_mention.js
listeners/events/app_mention.js
module.exports = app => { app.event('app_mention', async ({ event, context }) => { try { const result = await app.client.chat.postMessage({ token: context.botToken, text: `<@${event.user.id}> はーい` }); console.log(result); } catch (error) { console.error(error); } }); };
JavaScript
0.999999
@@ -178,16 +178,50 @@ tToken,%0A + channel: context.channel,%0A
a7f32136deb299b0a9a1499f073199b33695707e
Improve geostamp api docs
local_modules/geostamp/index.js
local_modules/geostamp/index.js
/* eslint-disable no-var */ // A HTML markup module for GeoJSON points. In addition to well formatted // coordinate output, it creates a Wikipedia-favoured link to // tools.wmflabs.org/geohack // // Usage example: // var p = { type: 'Point', coordinates: [-118.25013445, 34.05394492] } // var html = geostamp.geohack(p); // // Looks like: // 34.053944° N, 118.250134° E // // Resulting markup: // <a href="https://tools.wmflabs.org/geohack/geohack.php // ?language=en&params=34.05394492;-118.25013445_type:landmark" // target="_blank">34.053944° N, 118.250134° E</a> var DEFAULT_PRECISION = 6 var MINUTE_PRECISION = 4 var SECOND_PRECISION = 2 var MINUTES = 60 var SECONDS = 60 exports.latitudeDirection = function (lat) { return (lat >= 0) ? 'N' : 'S' } exports.longitudeDirection = function (lng) { return (lng >= 0) ? 'E' : 'W' } exports.getDecimal = function (degrees) { // Get degrees in decimal degree format. // // Parameters: // degrees // number // return degrees.toFixed(DEFAULT_PRECISION) + '&deg;' } exports.getDM = function (degrees) { // Get degrees in degree minute format. var degs = Math.floor(degrees) var degsRemainder = degrees - degs var mins = degsRemainder * MINUTES return degs + '&deg; ' + mins.toFixed(MINUTE_PRECISION) + '\'' } exports.getDMS = function (degrees) { // Get degrees in degree minute second format. // // Parameters: // degrees // number // var degs = Math.floor(degrees) var degsRemainder = degrees - degs var mins = Math.floor(degsRemainder * MINUTES) var minsRemainder = degsRemainder - (mins / MINUTES) var secs = minsRemainder * MINUTES * SECONDS return degs + '&deg; ' + mins + '\' ' + secs.toFixed(SECOND_PRECISION) + '"' } exports.geomDecimal = function (geom) { // Get geom in decimal degree format var lng = geom.coordinates[0] var lat = geom.coordinates[1] var lngStr = exports.getDecimal(lng) var latStr = exports.getDecimal(lat) var lngChar = exports.longitudeDirection(lng) var latChar = exports.latitudeDirection(lat) return latStr + ' ' + latChar + ', ' + lngStr + ' ' + lngChar } exports.geomDM = function (geom) { // Get geom in degree minute format. var lng = geom.coordinates[0] var lat = geom.coordinates[1] var lngStr = exports.getDM(lng) var latStr = exports.getDM(lat) var lngChar = exports.longitudeDirection(lng) var latChar = exports.latitudeDirection(lat) return latStr + ' ' + latChar + ', ' + lngStr + ' ' + lngChar } exports.geomDMS = function (geom) { // Get geom in degree minute second format. var lng = geom.coordinates[0] var lat = geom.coordinates[1] var lngStr = exports.getDMS(lng) var latStr = exports.getDMS(lat) var lngChar = exports.longitudeDirection(lng) var latChar = exports.latitudeDirection(lat) return latStr + ' ' + latChar + ', ' + lngStr + ' ' + lngChar }
JavaScript
0.000001
@@ -748,86 +748,293 @@ %7B%0A -return (lat %3E= 0) ? 'N' : 'S'%0A%7D%0A%0Aexports.longitudeDirection = function (lng) %7B +// Parameters%0A // lat%0A // number, latitude%0A //%0A // Return%0A // string in %5B'N', 'S'%5D%0A //%0A return (lat %3E= 0) ? 'N' : 'S'%0A%7D%0A%0Aexports.longitudeDirection = function (lng) %7B%0A // Parameters%0A // lng%0A // number, longitude%0A //%0A // Return%0A // string in %5B'E', 'W'%5D%0A // %0A r @@ -1204,24 +1204,73 @@ number%0A //%0A + // Return%0A // string, e.g %6012.345678%C2%B0%60%0A //%0A return deg @@ -1393,16 +1393,125 @@ format.%0A + //%0A // Parameters:%0A // degrees%0A // number%0A //%0A // Return%0A // string, e.g %6012%C2%B0 34.5678'%60%0A //%0A var de @@ -1823,16 +1823,68 @@ er%0A //%0A + // Return%0A // string, e.g %6012%C2%B0 34' 56.78%22%60%0A // %0A var d
5ca52c531a0c3fbde5f7fb184a0a564ecd46005e
fix a test order bug, see diff for more
test/discovery_api_test.js
test/discovery_api_test.js
'use strict'; var chai = require('chai'); var chaihttp = require('chai-http'); var expect = chai.expect; chai.use(chaihttp); var server = require('../server.js'); describe('Music Discovery for the win', function() { it('should search for an artist', function(done) { chai.request('localhost:3000') .get('/api/discovery/artist/snsd') .end(function(err, res) { expect(err).to.eql(null); expect(res.body.artists[0].name).to.eql("Girls' Generation"); done(); }); }); it('should search for a genre', function(done) { chai.request('localhost:3000') .get('/api/discovery/genre/k-pop') .end(function(err, res) { expect(err).to.eql(null); expect(res.body.artists[0].name).to.eql("PSY"); done(); }); }); it('should give a list of related artists', function(done) { chai.request('localhost:3000') .get('/api/discovery/related/2uWcrwgWmZcQc3IPBs3tfU') .end(function(err, res) { expect(err).to.eql(null); expect(res.body.artists[0].name).to.eql('B1A4'); done(); }); }); it('should give a list of top tracks', function(done) { chai.request('localhost:3000') .get('/api/discovery/top-tracks/2uWcrwgWmZcQc3IPBs3tfU') .end(function(err, res) { expect(err).to.eql(null); expect(res.body.tracks[0].name).to.eql('Let Us Just Love'); done(); }); }); it('should give a list related youtube videos', function(done) { chai.request('localhost:3000') .get('/api/discovery/youtube/girlsday') .end(function(err, res) { expect(err).to.eql(null); expect(res.body.videos[0].id).to.eql('9lSJMKi184c'); done(); }); }); });
JavaScript
0
@@ -119,16 +119,18 @@ ihttp);%0A +// var serv @@ -158,16 +158,84 @@ er.js'); + huh, turns out mocha will run whatever server requires this, first. %0A%0A%0Adescr @@ -544,24 +544,83 @@ neration%22);%0A + expect(res.body.artists%5B0%5D.popularity).to.eql(65);%0A done @@ -885,24 +885,83 @@ eql(%22PSY%22);%0A + expect(res.body.artists%5B0%5D.popularity).to.eql(67);%0A done @@ -1274,630 +1274,56 @@ -done();%0A %7D);%0A %7D);%0A%0A it('should give a list of top tracks', function(done) %7B%0A chai.request('localhost:3000')%0A .get('/api/discovery/top-tracks/2uWcrwgWmZcQc3IPBs3tfU')%0A .end(function(err, res) %7B%0A expect(err).to.eql(null);%0A expect(res.body.tracks%5B0%5D.name).to.eql('Let Us Just Love');%0A done();%0A %7D);%0A %7D);%0A%0A it('should give a list related youtube videos', function(done) %7B%0A chai.request('localhost:3000')%0A .get('/api/discovery/youtube/girlsday')%0A .end(function(err, res) %7B%0A expect(err).to.eql(null);%0A expect(res.body.videos%5B0%5D.id).to.eql('9lSJMKi184c' +expect(res.body.artists%5B0%5D.popularity).to.eql(53 );%0A @@ -1343,22 +1343,24 @@ ;%0A %7D);%0A + %7D);%0A%7D);%0A
02b89d816989a401de8b532d084cabb3ced2ce73
test :: encode & decode longs and ulongs
test/encode.decode.long.js
test/encode.decode.long.js
var fs = require('fs') , concat = require('concat-stream') , encoder = require('../lib/encoder') , decoder = require('../lib/decoder') , ei = require('../lib/const') , tap = require('tap') , test = tap.test ; test('encode/decode/long', function(t) { 'use strict'; var enc = encoder(); enc.encodeVersion(); enc.encodeLong(3000); enc.pipe(concat(function(data) { var dec = decoder(data); t.ok(dec.decodeVersion(), 'version'); t.equals(dec.getType(), ei.INTEGER_EXT, 'type'); t.deepEqual(dec.decodeLong(), 3000, 'value'); t.equals(dec.index, data.length, 'eof'); t.end(); })); }); test('encode/decode/long-small', function(t) { 'use strict'; var enc = encoder(); enc.encodeVersion(); enc.encodeLong(54); enc.pipe(concat(function(data) { var dec = decoder(data); t.ok(dec.decodeVersion(), 'version'); t.equals(dec.getType(), ei.SMALL_INTEGER_EXT, 'type'); t.deepEqual(dec.decodeLong(), 54, 'value'); t.equals(dec.index, data.length, 'eof'); t.end(); })); });
JavaScript
0.000002
@@ -673,16 +673,920 @@ ;%0A%7D);%0A%0A%0A +test('encode/decode/long-negative', function(t) %7B%0A 'use strict';%0A%0A var enc = encoder();%0A enc.encodeVersion();%0A enc.encodeLong(-3000);%0A%0A enc.pipe(concat(function(data) %7B%0A var dec = decoder(data);%0A%0A t.ok(dec.decodeVersion(), 'version');%0A t.equals(dec.getType(), ei.INTEGER_EXT, 'type');%0A t.deepEqual(dec.decodeLong(), -3000, 'value');%0A t.equals(dec.index, data.length, 'eof');%0A t.end();%0A %7D));%0A%7D);%0A%0Atest('encode/decode/ulong', function(t) %7B%0A 'use strict';%0A%0A var enc = encoder();%0A enc.encodeVersion();%0A enc.encodeULong(3000);%0A%0A enc.pipe(concat(function(data) %7B%0A var dec = decoder(data);%0A%0A t.ok(dec.decodeVersion(), 'version');%0A t.equals(dec.getType(), ei.INTEGER_EXT, 'type');%0A t.deepEqual(dec.decodeULong(), 3000, 'value');%0A t.equals(dec.index, data.length, 'eof');%0A t.end();%0A %7D));%0A%7D);%0A%0A test('en
42f992b66b56a71e58f2114142bb9dca8a3cea44
Add exporting of root navigation ref and functions
src/navigation/index.js
src/navigation/index.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ export { ROUTES } from './constants'; export { getCurrentRouteName, getCurrentParams } from './selectors'; export { MainStackNavigator } from './Navigator';
JavaScript
0
@@ -217,8 +217,75 @@ gator';%0A +export %7B RootNavigator, rootNavigatorRef %7D from './RootNavigator';%0A
751205be23761f7c8d9e83e3bf2304ed62e6a9e3
Switch LambdaCD text to pipeline Name. Add link to lambdacd homepage
frontend/src/js/main/Header.es6
frontend/src/js/main/Header.es6
import React, {PropTypes} from "react"; import {connect} from "react-redux"; import App from "App.es6"; import logo from "../../img/logo.png"; import "../../sass/header.sass"; import R from "ramda"; export const HeaderLinks = (props) => { if(!props) { return null; } const {links} = props; if(!links || links.length < 1){ return null; } const linkComponent = (link) => { return <a target="_blank" key={link.url} href={link.url}>{link.text}</a>; }; const linkComponents = links.map((link) => { return linkComponent(link); }); if (links.length === 1){ return <div className="linksHeader">{linkComponent(links[0])}</div>; } return <div className="linksHeader">{linkComponents}</div>; }; HeaderLinks.propTypes = { links: PropTypes.array }; export const Header = ({pipelineName, links}) => { const triggerNewFn = () => App.backend().triggerNewBuild(); let headerLinks; if(links) { headerLinks = <HeaderLinks links={links} />; } else { headerLinks = ""; } return <div className="appHeader"> <div className="logo"> <img src={logo} className="logoImage" alt="logo"/> <span className="logoText">LAMBDA CD</span> </div> <span className="pipelineName">{pipelineName}</span> {headerLinks} <button className="runButton" onClick={triggerNewFn}>Start Build</button> </div>; }; Header.propTypes = { pipelineName: PropTypes.string.isRequired, links: PropTypes.array }; export const mapStateToProps = (state) => { const headerLinks = R.view(R.lensPath(["config", "navbar", "links"]))(state) || []; return { pipelineName: state.config.name, links: headerLinks }; }; const mapDispatchToProps = (dispatch, ownProps) => { return ownProps; }; export default connect(mapStateToProps, mapDispatchToProps)(Header);
JavaScript
0
@@ -1152,16 +1152,65 @@ %22logo%22%3E%0A + %3Ca href=%22http://www.lambda.cd/%22%3E%0A @@ -1281,74 +1281,24 @@ %3C -span className=%22logoText%22%3ELAMBDA CD%3C/span%3E%0A %3C/div%3E%0A +/a%3E%0A - %3Cspa @@ -1310,28 +1310,24 @@ ssName=%22 -pipelineName +logoText %22%3E%7Bpipel @@ -1342,16 +1342,31 @@ %3C/span%3E%0A + %3C/div%3E%0A
c7b533e52e25590bb4a81a97b6bddeb109a50c5b
Remove <title> from _document.js
frontend/src/pages/_document.js
frontend/src/pages/_document.js
import React from 'react'; import Document, { Head, Main, NextScript } from 'next/document'; import JssProvider from 'react-jss/lib/JssProvider'; import getPageContext from '../utils/getPageContext'; class MyDocument extends Document { render() { const { pageContext } = this.props; return ( <html lang="en" dir="ltr"> <Head> <title>My page</title> <meta charSet="utf-8" /> {/* Use minimum-scale=1 to enable GPU rasterization */} <meta name="viewport" content={ 'user-scalable=0, initial-scale=1, ' + 'minimum-scale=1, width=device-width, height=device-height' } /> {/* PWA primary color */} <meta name="theme-color" content={pageContext.theme.palette.primary[500]} /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" /> <link rel="shortcut icon" href="/static/favicon.ico" /> </Head> <body> <Main /> <NextScript /> </body> </html> ); } } MyDocument.getInitialProps = ctx => { // Resolution order // // On the server: // 1. page.getInitialProps // 2. document.getInitialProps // 3. page.render // 4. document.render // // On the server with error: // 2. document.getInitialProps // 3. page.render // 4. document.render // // On the client // 1. page.getInitialProps // 3. page.render // Get the context of the page to collected side effects. const pageContext = getPageContext(); const page = ctx.renderPage(Component => props => ( <JssProvider registry={pageContext.sheetsRegistry} generateClassName={pageContext.generateClassName} > <Component pageContext={pageContext} {...props} /> </JssProvider> )); return { ...page, pageContext, styles: ( <style id="jss-server-side" // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: pageContext.sheetsRegistry.toString() }} /> ), }; }; export default MyDocument;
JavaScript
0.000011
@@ -349,41 +349,8 @@ ad%3E%0A - %3Ctitle%3EMy page%3C/title%3E%0A
fdc029eca29f834d8429d014daad1a0bc23ec467
Fix conversion of string to int
res/main.js
res/main.js
var baseN; $(function() { rebuildBase(); $('#base').spinner({ min: 2, max: alphabets['max'].length, step: 1, start: 85, change: function(event, ui) { var alphabet = alphabets['max'].substr(0, $("#base").spinner("value")); $('#alphabet').val(alphabet); $('#base').val(alphabet.length); rebuildBase(); } }); $("#base").bind('spin', function (event, ui) { var alphabet = alphabets['max'].substr(0, ui.value); $('#alphabet').val(alphabet); $('#base').val(alphabet.length); rebuildBase(); }); $('#maxBitsCount').spinner({ min: 2, max: 512, step: 1, start: 64, change: function(event, ui) { rebuildBase(); } }); $("#maxBitsCount").bind('spin', function (event, ui) { rebuildBase(); }); $('#btnEncode').addClass('active'); $('#btnEncodeDecode .btn').click(function() { if (this.id === 'btnEncode') { $('#btnDecode').removeClass('active'); } else { $('#btnEncode').removeClass('active'); } }); $('.gen_alphabet').click(function() { var alphabet = alphabets[$(this).val()]; $('#alphabet').val(alphabet); $('#base').val(alphabet.length); rebuildBase(); }); $('#alphabet').on('change keyup paste', function() { $('#base').val($('#alphabet').val().length); rebuildBase(); }); $('#convert').click(function() { try { var alphabet = $('#alphabet').val(); for (var i = 0; i < alphabet.length; i++) { for (var j = i + 1; j < alphabet.length; j++) { if (alphabet[i] === alphabet[j]) { throw new Error("Alphabet should contains distinct chars"); } } } baseN = new BaseN(alphabet, $('#maxBitsCount').val(), $('#btnReverseOrder').hasClass('active'), $('#btnOneBigNumber').hasClass('active')); var input = $('#input').val(); var converted; if ($('#btnEncode').hasClass('active')) { converted = baseN.encodeString(input); } else { converted = baseN.decodeToString(input); } $('#output').val(converted); printBlockSize(); } catch (er) { alert(er.message); } }); }); function rebuildBase() { baseN = new BaseN($('#alphabet').val(), parseInt($('#maxBitsCount').val()), $('#btnReverseOrder').hasClass('active'), $('#btnOneBigNumber').hasClass('active')); printBlockSize(); $('#output').val(''); } function printBlockSize() { $('#info').html('<strong>Block size: ' + baseN.blockBitsCount + ' bits per ' + baseN.blockCharsCount + ' chars. Redundancy: ' + ((baseN.blockCharsCount * 8) / baseN.blockBitsCount).toFixed(4) + '</strong>'); }
JavaScript
0.999992
@@ -330,26 +330,25 @@ %09%09%7D%0A %7D);%0A -%09 %0A + %09$(%22#base%22). @@ -523,26 +523,25 @@ ase();%0A%09%7D);%0A -%09 %0A + %09$('#maxBits @@ -666,18 +666,17 @@ %7D);%0A -%09 %0A + %09$(%22#max @@ -741,26 +741,25 @@ ase();%0A%09%7D);%0A -%09 %0A + %09$('#btnEnco @@ -963,26 +963,25 @@ );%0A%09%09%7D%0A%09%7D);%0A -%09 %0A + %09$('.gen_alp @@ -1135,26 +1135,25 @@ ase();%0A%09%7D);%0A -%09 %0A + %09$('#alphabe @@ -1263,18 +1263,17 @@ );%0A%09%7D);%0A -%09 %0A + %09$('#con @@ -1600,16 +1600,25 @@ phabet, +parseInt( $('#maxB @@ -1633,16 +1633,17 @@ ').val() +) , $('#bt @@ -1721,19 +1721,16 @@ ive'));%0A -%09%09%09 %0A%09%09%09var @@ -1924,19 +1924,16 @@ );%0A%09%09%09%7D%0A -%09%09%09 %0A%09%09%09$('#
725a61cb40babb6dacab91f9d60b0c63ced99242
add info window anchor data
scripted/src/extensions/map/scripts/marker.js
scripted/src/extensions/map/scripts/marker.js
/** * @fileOverview Utility functions for generating a marker suitable for * external libraries to use in making a marker. * @author <a href="mailto:[email protected]">Ryan Lee</a> */ /** * @class * @constructor * @param {Object} icon * @param {Array} icon.anchor * @param {Array} icon.size * @param {String} icon.url * @param {Object} shadow * @param {Array} shadow.anchor * @param {Array} shadow.size * @param {String} shadow.url * @param {Object} shape * @param {String} shape.type * @param {Array} shape.coords * @param {Object} settings */ Exhibit.MapExtension.Marker = function(icon, shadow, shape, settings) { this.icon = icon; this.shadow = shadow; this.shape = shape; this.settings = settings; }; /** * Sets Exhibit.MapExtension.hasCanvas */ Exhibit.MapExtension.Marker.detectCanvas = function() { var canvas = $('<canvas>'); Exhibit.MapExtension.hasCanvas = (typeof canvas.get(0).getContext !== "undefined" && canvas.get(0).getContext("2d") !== null); canvas = null; }; /** * @static * @param {String} shape * @param {String} color * @param {Numeric} iconSize * @param {String} iconURL * @param {String} label * @returns {String} */ Exhibit.MapExtension.Marker._makeMarkerKey = function(shape, color, iconSize, iconURL, label) { return "#" + [shape, color, iconSize, iconURL, label].join("#"); }; /** * @static * @param {String} shape * @param {String} color * @param {Numeric} iconSize * @param {String} iconURL * @param {String} label * @param {Object} settings * @param {Exhibit.View} view * @returns {Exhibit.MapExtension.Marker} */ Exhibit.MapExtension.Marker.makeMarker = function(shape, color, iconSize, iconURL, label, settings, view) { var extra, halfWidth, bodyHeight, width, height, pin, markerImage, markerShape, shadowImage, pinHeight, pinHalfWidth, markerPair, marker, image; extra = label.length * 3; halfWidth = Math.ceil(settings.shapeWidth / 2) + extra; bodyHeight = settings.shapeHeight+2*extra; // try to keep circular width = halfWidth * 2; height = bodyHeight; pin = settings.pin; if (iconSize > 0) { width = iconSize; halfWidth = Math.ceil(iconSize / 2); height = iconSize; bodyHeight = iconSize; } markerImage = { "anchor": null, "size": null, "url": null }; markerShape = { "type": "poly", "coords": null }; shadowImage = { "anchor": null, "size": null, "url": null }; if (pin) { pinHeight = settings.pinHeight; pinHalfWidth = Math.ceil(settings.pinWidth / 2); height += pinHeight; markerImage.anchor = [halfWidth, height]; shadowImage.anchor = [halfWidth, height]; markerShape.coords = [ 0, 0, 0, bodyHeight, halfWidth - pinHalfWidth, bodyHeight, halfWidth, height, halfWidth + pinHalfWidth, bodyHeight, width, bodyHeight, width, 0 ]; } else { markerImage.anchor = [halfWidth, Math.ceil(height / 2)]; shadowImage.anchor = [halfWidth, Math.ceil(height / 2)]; markerShape.coords = [ 0, 0, 0, bodyHeight, width, bodyHeight, width, 0 ]; } markerImage.size = [width, height]; shadowImage.size = [width + height / 2, height]; if (!Exhibit.MapExtension.hasCanvas) { markerPair = Exhibit.MapExtension.Painter.makeIcon(width, bodyHeight, color, label, iconURL, iconSize, settings); } else { markerPair = Exhibit.MapExtension.Canvas.makeIcon(width, bodyHeight, color, label, null, iconSize, settings); } markerImage.url = markerPair.iconURL; shadowImage.url = markerPair.shadowURL; marker = new Exhibit.MapExtension.Marker(markerImage, shadowImage, markerShape, settings); if (iconURL !== null) { // canvas needs to fetch image: // - return a marker without the image // - add a callback that adds the image when available. image = new Image(); image.onload = function() { var url, icon, key; try { url = Exhibit.MapExtension.Canvas.makeIcon(width, bodyHeight, color, label, image, iconSize, settings).iconURL; } catch (e) { // remote icon fetch caused canvas tainting, fall to painter url = Exhibit.MapExtension.Painter.makeIcon(width, bodyHeight, color, label, iconURL, iconSize, settings).iconURL; } icon = marker.getIcon(); icon .url = url; marker.setIcon(icon); key = Exhibit.MapExtension.Marker._makeMarkerKey(shape, color, iconSize, iconURL, label); view._markerCache[key] = marker; }; image.src = iconURL; } return marker; }; /** * @returns {Boolean} */ Exhibit.MapExtension.Marker.prototype.hasShadow = function() { return this.shadow !== null; }; /** * @param {Object} icon */ Exhibit.MapExtension.Marker.prototype.setIcon = function(icon) { this.icon = icon; }; /** * @returns {Object} */ Exhibit.MapExtension.Marker.prototype.getIcon = function() { return this.icon; }; /** * @param {Object} shadow */ Exhibit.MapExtension.Marker.prototype.setShadow = function(shadow) { this.shadow = shadow; }; /** * @returns {Object} */ Exhibit.MapExtension.Marker.prototype.getShadow = function() { return this.shadow; }; /** * @param {Object} shape */ Exhibit.MapExtension.Marker.prototype.setShape = function(shape) { this.shape = shape; }; /** * @returns {Object} */ Exhibit.MapExtension.Marker.prototype.getShape = function() { return this.shape; }; /** * @param {Object} settings */ Exhibit.MapExtension.Marker.prototype.setSettings = function(settings) { this.settings = settings; }; /** * @returns {Object} */ Exhibit.MapExtension.Marker.prototype.getSettings = function() { return this.settings; }; /** * */ Exhibit.MapExtension.Marker.prototype.dispose = function() { this.icon = null; this.shadow = null; this.shape = null; this.settings = null; };
JavaScript
0
@@ -3050,24 +3050,162 @@ 0%0A %5D; +%0A%0A markerImage.infoWindowAnchor = (settings.bubbleTip === %22bottom%22) ?%0A %5BhalfWidth, height%5D :%0A %5BhalfWidth, 0%5D; %0A %7D else @@ -3465,16 +3465,71 @@ %5D;%0A + markerImage.infoWindowAnchor = %5BhalfWidth, 0%5D;%0A %7D%0A%0A
41948bd48c24576f6a5ef4bde381dba918cffbe2
make helper functions global #145
client/devel.js
client/devel.js
var addSelfToGame = function (gameId) { if (! gameId) { return; } var path = Router.current().path; var inviteeId = path.split('?')[1] Meteor.call("addSelf", { gameId: gameId, name: Meteor.user().profile.name }, function (err) { if (!err) { Session.set("joined-game", gameId); Session.set("unauth-join", null); Alerts.throw({ message: "You've joined this game -- be sure to invite your friends!", type: "success", where: gameId, autoremove: 5000 }); var fullName = Meteor.user().profile.name; var email = Meteor.user().emails[0].address; if (inviteeId) { Meteor.call( "dev.notifyInviter", gameId, email, fullName, inviteeId, function (error, result) { if (error) { console.log(error); } }); } } else { console.log(err); Alerts.throw({ message: "Hmm, something went wrong: \""+err.reason+"\". Try again?", type: "danger", where: gameId }); } }); }; var inputValue = function (element) { return element.value; }; var inputValues = function (selector) { return _.map($(selector).get(), inputValue); }; Deps.autorun(function () { // autorun Games subscription currently depends on Session 'gameTypes' Session.set("gameTypes", Session.get("game-types")); }); var ppConjunction = function (array) { var out = ""; for (var i=0, l=array.length; i<l; i++) { out = out + array[i]; if (i === l-2 && l === 2) { out = out + " and "; } else if (i === l-2) { out = out + ", and "; } else if (i < l-2) { out = out + ", "; } } return out; }; var ppRegion = function (formatted_address) { return formatted_address; }; var whosPlayingHelpers = { userPlayers: function () { var isUser = function (player) { return !! player.userId; }; return _.select(this.players, isUser); }, friends: function (players) { var self = this; return _.select(players, function (p) { return (! p.userId) && p.friendId === self.userId; }); }, numFriends: function () { return this.length; } }; Template.whosPlayingSummary.helpers(whosPlayingHelpers); Template.whosPlayingEditable.helpers(whosPlayingHelpers); // selector is either a String, e.g. "#name", or a [String, function] that // takes the value and then feeds it to the (one-argument) function for // a final value var selectorValuesFromTemplate = function (selectors, templ) { var result = {}; _.each(selectors, function (selector, key) { if (typeof selector === "string") { result[key] = templ.find(selector).value; } else { result[key] = (selector[1])(templ.find(selector[0]).value); } }); return result; }; var asNumber = function (str) { return +str; }; // Set several Template.settings.events of the form: // // "click .sign-in.trigger": function () { // Session.toggle("settings-sign-in"); // } var sessionToggler = function (action) { return function () { Session.toggle("settings-"+action); }; }; _.each([ 'sign-in', 'sign-up', 'forgot-password', 'set-password', 'subscriptions', 'change-email-address', 'change-password', 'change-location', 'help-and-feedback' ], function (action) { var key = "click ."+action+".trigger"; var eventMap = {}; eventMap[key] = sessionToggler(action); Template.settings.events(eventMap); });
JavaScript
0.000001
@@ -2457,20 +2457,16 @@ l value%0A -var selector @@ -2781,20 +2781,17 @@ ult;%0A%7D;%0A -var +%0A asNumber @@ -2972,20 +2972,16 @@ );%0A// %7D%0A -var sessionT
d6a0ea976b247d76e2a607f099cb82f5ddc09c2e
Add CSS id to login link to aide in test selectors
troposphere/static/js/components/Header.react.js
troposphere/static/js/components/Header.react.js
define(function (require) { var React = require('react/addons'), Backbone = require('backbone'), actions = require('actions'), modals = require('modals'), MaintenanceMessageBanner = require('./MaintenanceMessageBanner.react'), globals = require('globals'), Router = require('react-router'), // plugin: required to enable the drop-down, but not used directly bootstrap = require('bootstrap'); var Link = Router.Link; var links = [ { name: "Dashboard", linksTo: "dashboard", href: "/application/dashboard", icon: "stats", requiresLogin: true, isEnabled: true, }, { name: "Projects", linksTo: "projects", href: "/application/projects", icon: "folder-open", requiresLogin: true, isEnabled: true }, { name: "Images", linksTo: "images", href: "/application/images", icon: "floppy-disk", requiresLogin: false, isEnabled: true }, { name: "Providers", linksTo: "providers", href: "/application/providers", icon: "cloud", requiresLogin: true, isEnabled: true }, { name: "Help", linksTo: "help", href: "/application/help", icon: "question-sign", requiresLogin: false, isEnabled: true }, { name: "Admin", linksTo: "admin", href: "/application/admin", icon: "cog", requiresLogin: true, requiresStaff: true, isEnabled: true }, { name: "Badges", linksTo: "my-badges", href: "/application/badges", icon: "star", requiresLogin: true, requiresStaff: false, isEnabled: globals.BADGES_ENABLED } ]; var LoginLink = React.createClass({ render: function () { return ( <li className="dropdown"> <a href="/login?redirect=/application?beta=true&airport_ui=false">Login</a> </li> ); } }); var LogoutLink = React.createClass({ propTypes: { username: React.PropTypes.string.isRequired }, onShowVersion: function (e) { e.preventDefault(); modals.VersionModals.showVersion(); }, render: function () { var username = this.props.username; if (!username && show_public_site) { username = "AnonymousUser" } return ( <li className="dropdown"> <a className="dropdown-toggle" href="#" data-toggle="dropdown"> {username} <b className="caret"></b> </a> <ul className="dropdown-menu"> <li> <Link to="settings">Settings</Link> </li> <li> <Link to="my-requests-resources">My requests</Link> </li> <li className="divider"></li> <li> <a href="#" onClick={this.onShowVersion}>Version</a> </li> <li> <a href="http://atmosphere.status.io" target="_blank">Status</a> </li> <li> <a href="/logout?cas=True&airport_ui=false">Sign out</a> </li> </ul> </li> ); } }); var Header = React.createClass({ displayName: "Header", propTypes: { profile: React.PropTypes.instanceOf(Backbone.Model), currentRoute: React.PropTypes.array.isRequired }, // We need the screen size for handling the opening and closing of our menu on small screens //See navLinks below for implementation. getInitialState: function() { return {windowWidth: window.innerWidth}; }, handleResize: function(e) { this.setState({windowWidth: window.innerWidth}); }, componentDidMount: function() { window.addEventListener('resize', this.handleResize); }, componentWillUnmount: function() { window.removeEventListener('resize', this.handleResize); }, renderBetaToggle: function () { if (!window.show_troposphere_only) { return ( <div className="beta-toggle"> <a href="/application?beta=false&airport_ui=true"> <div className="toggle-wrapper"> <div className="toggle-background"> <div className="toggle-text">View Old UI</div> </div> <div className="toggle-switch"></div> </div> </a> </div> ) } }, render: function () { var profile = this.props.profile; var loginLogoutDropdown = profile.get('selected_identity') ? <LogoutLink username={profile.get('username')}/> : <LoginLink/>; if (!profile.get('selected_identity')) { links = links.filter(function (link) { return !link.requiresLogin && link.isEnabled; }) } else { links = links.filter(function (link) { if (link.requiresStaff) return profile.get('is_staff'); return link.isEnabled; }) } var navLinks = links.map(function (link) { var isCurrentRoute = (link.name.toLowerCase() === this.props.currentRoute[0]); var className = isCurrentRoute ? "active" : null; //We need to only trigger the toggle menu on small screen sizes to avoid buggy behavior when selecting menu items on larger screens var smScreen = (this.state.windowWidth < 768); var toggleMenu = smScreen ? {toggle: 'collapse',target:'.navbar-collapse'} : {toggle: null, target: null}; return ( <li key={link.name} data-toggle={toggleMenu.toggle} data-target={toggleMenu.target} > <Link to={link.linksTo}> <i className={"glyphicon glyphicon-" + link.icon}></i> {link.name} </Link> </li> ); }.bind(this)); var brandLink; if (profile.get('selected_identity')) { brandLink = <Link to="dashboard" className="navbar-brand"/>; } else { brandLink = <Link to="images" className="navbar-brand"/>; } return ( <div className="navbar navbar-default navbar-fixed-top" role="navigation"> <MaintenanceMessageBanner maintenanceMessages={this.props.maintenanceMessages}/> <div className="container"> <div className="navbar-header"> <button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> {brandLink} </div> <div className="navbar-collapse collapse"> <ul className="nav navbar-nav"> {navLinks} </ul> <ul className="nav navbar-nav navbar-right"> {loginLogoutDropdown} </ul> </div> {this.renderBetaToggle()} </div> </div> ); } }); return Header; });
JavaScript
0
@@ -1852,32 +1852,48 @@ n%22%3E%0A %3Ca + id=%22login_link%22 href=%22/login?re
3bf0b5b238ae53f717083988f67f7962f41e0f05
change info text
client/index.js
client/index.js
$(document).ready(function(){ var socket = io(); var attachFastClick = Origami.fastclick; attachFastClick(document.body); var DEAD_COLOR = '#eeeeee'; var TEST_DEAD_COLOR = 'rgb(238, 238, 238)'; var USER_COLOR = "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);}); window.songjack = window.songjack || {}; var isMousedown = false; // Tracks status of mouse button $(document).mousedown(function() { isMousedown = true; // When mouse goes down, set isDown to true }) .mouseup(function() { isMousedown = false; // When mouse goes up, set isDown to false }); //vanilla JS for speed var colorCell = function(cellData) { var cell = document.getElementById(cellData.x + '-' + cellData.y); cell.style.backgroundColor = cellData.alive ? cellData.css : DEAD_COLOR; } //assumes 'this' is the DOM element //vanilla JS for speeeed var requestCell = function() { //only proceed if cell is dead //jquery only returns a stupid rgb string if(!this.style.backgroundColor || this.style.backgroundColor == TEST_DEAD_COLOR) { var coords = this.id.split('-'); socket.emit('requestCell', { x: coords[0], y: coords[1], alive: true, css: USER_COLOR } ); } } var setCells = function (cells) { cells.forEach(function (cell) { window.songjack.game.addCell(cell); colorCell(cell); }); } var setCursor = function (allowed) { document.getElementsByTagName('table')[0].style.cursor = allowed ? 'cell' : 'not-allowed'; } //set up DOM listeners $('td').click(requestCell).mousedown(requestCell).mouseover(function () { if(isMousedown) { requestCell.call(this); } }); socket.on('init', function(bundle) { window.songjack.game = new window.songjack.GameOfLife(bundle.map.cols, bundle.map.rows); setCells(bundle.cells); if(bundle.running) { window.songjack.gameIntervalID = setInterval(iterateGame, bundle.running); } setCursor(!bundle.running); }); //set up socket listeners socket.on('newCell', function(cellData){ window.songjack.game.addCell(cellData); colorCell(cellData); }); socket.on('setup', function(){ // clear the current game running id if(window.songjack.gameIntervalID) { clearInterval(window.songjack.gameIntervalID); window.songjack.gameIntervalID = null; } window.songjack.game.clear(); $('td').css('background-color', DEAD_COLOR); setCursor(true); }); socket.on('simulate', function(bundle){ window.songjack.game.clear(); setCells(bundle.cells); window.songjack.gameIntervalID = setInterval(iterateGame, bundle.interval); setCursor(false); }); socket.on('countdown', function(data){ var message = data.running ? 'Simulating! Next round in: ' : 'Place your cells! Round starts in: '; $('#alert').text(message + data.time); }); var iterateGame = function() { var changedCells = window.songjack.game.iterate(); changedCells.forEach(function(cell) { colorCell(cell); }) } });
JavaScript
0.000001
@@ -2884,24 +2884,77 @@ : ' -Place your cells +Click & drag or tap to place cells, refresh for more when you run out ! Ro
fcb8ca7441a200cad3d09cf430307966bda5f573
Add `yauzl` to the snapshot blacklist
script/lib/generate-startup-snapshot.js
script/lib/generate-startup-snapshot.js
const childProcess = require('child_process') const fs = require('fs') const path = require('path') const electronLink = require('electron-link') const CONFIG = require('../config') module.exports = function (packagedAppPath) { const snapshotScriptPath = path.join(CONFIG.buildOutputPath, 'startup.js') const coreModules = new Set(['electron', 'atom', 'shell', 'WNdb', 'lapack', 'remote']) const baseDirPath = path.join(CONFIG.intermediateAppPath, 'static') let processedFiles = 0 return electronLink({ baseDirPath, mainPath: path.resolve(baseDirPath, '..', 'src', 'initialize-application-window.js'), cachePath: path.join(CONFIG.atomHomeDirPath, 'snapshot-cache'), auxiliaryData: CONFIG.snapshotAuxiliaryData, shouldExcludeModule: ({requiringModulePath, requiredModulePath}) => { if (processedFiles > 0) { process.stdout.write('\r') } process.stdout.write(`Generating snapshot script at "${snapshotScriptPath}" (${++processedFiles})`) const requiringModuleRelativePath = path.relative(baseDirPath, requiringModulePath) const requiredModuleRelativePath = path.relative(baseDirPath, requiredModulePath) return ( requiredModulePath.endsWith('.node') || coreModules.has(requiredModulePath) || requiringModuleRelativePath.endsWith(path.join('node_modules/xregexp/xregexp-all.js')) || (requiredModuleRelativePath.startsWith(path.join('..', 'src')) && requiredModuleRelativePath.endsWith('-element.js')) || requiredModuleRelativePath.startsWith(path.join('..', 'node_modules', 'dugite')) || requiredModuleRelativePath.endsWith(path.join('node_modules', 'coffee-script', 'lib', 'coffee-script', 'register.js')) || requiredModuleRelativePath.endsWith(path.join('node_modules', 'fs-extra', 'lib', 'index.js')) || requiredModuleRelativePath.endsWith(path.join('node_modules', 'graceful-fs', 'graceful-fs.js')) || requiredModuleRelativePath.endsWith(path.join('node_modules', 'htmlparser2', 'lib', 'index.js')) || requiredModuleRelativePath.endsWith(path.join('node_modules', 'minimatch', 'minimatch.js')) || requiredModuleRelativePath.endsWith(path.join('node_modules', 'request', 'index.js')) || requiredModuleRelativePath.endsWith(path.join('node_modules', 'request', 'request.js')) || requiredModuleRelativePath === path.join('..', 'exports', 'atom.js') || requiredModuleRelativePath === path.join('..', 'src', 'electron-shims.js') || requiredModuleRelativePath === path.join('..', 'src', 'safe-clipboard.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'atom-keymap', 'lib', 'command-event.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'babel-core', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'cached-run-in-this-context', 'lib', 'main.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'decompress-zip', 'lib', 'decompress-zip.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'debug', 'node.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'git-utils', 'src', 'git.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'glob', 'glob.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'iconv-lite', 'lib', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'less', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'less', 'lib', 'less', 'fs.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'less', 'lib', 'less-node', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'lodash.isequal', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'node-fetch', 'lib', 'fetch-error.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'superstring', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'oniguruma', 'src', 'oniguruma.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'resolve', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'resolve', 'lib', 'core.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'settings-view', 'node_modules', 'glob', 'glob.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'spellchecker', 'lib', 'spellchecker.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'spelling-manager', 'node_modules', 'natural', 'lib', 'natural', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'tar', 'tar.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'temp', 'lib', 'temp.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'tmp', 'lib', 'tmp.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'tree-sitter', 'index.js') || requiredModuleRelativePath === path.join('..', 'node_modules', 'winreg', 'lib', 'registry.js') ) } }).then(({snapshotScript}) => { fs.writeFileSync(snapshotScriptPath, snapshotScript) process.stdout.write('\n') console.log('Verifying if snapshot can be executed via `mksnapshot`') const verifySnapshotScriptPath = path.join(CONFIG.repositoryRootPath, 'script', 'verify-snapshot-script') let nodeBundledInElectronPath if (process.platform === 'darwin') { const executableName = CONFIG.channel === 'beta' ? 'Atom Beta' : 'Atom' nodeBundledInElectronPath = path.join(packagedAppPath, 'Contents', 'MacOS', executableName) } else if (process.platform === 'win32') { nodeBundledInElectronPath = path.join(packagedAppPath, 'atom.exe') } else { nodeBundledInElectronPath = path.join(packagedAppPath, 'atom') } childProcess.execFileSync( nodeBundledInElectronPath, [verifySnapshotScriptPath, snapshotScriptPath], {env: Object.assign({}, process.env, {ELECTRON_RUN_AS_NODE: 1})} ) const generatedStartupBlobPath = path.join(CONFIG.buildOutputPath, 'snapshot_blob.bin') console.log(`Generating startup blob at "${generatedStartupBlobPath}"`) childProcess.execFileSync( path.join(CONFIG.repositoryRootPath, 'script', 'node_modules', 'electron-mksnapshot', 'bin', 'mksnapshot'), ['--no-use_ic', snapshotScriptPath, '--startup_blob', generatedStartupBlobPath] ) let startupBlobDestinationPath if (process.platform === 'darwin') { startupBlobDestinationPath = `${packagedAppPath}/Contents/Frameworks/Electron Framework.framework/Resources/snapshot_blob.bin` } else { startupBlobDestinationPath = path.join(packagedAppPath, 'snapshot_blob.bin') } console.log(`Moving generated startup blob into "${startupBlobDestinationPath}"`) fs.unlinkSync(startupBlobDestinationPath) fs.renameSync(generatedStartupBlobPath, startupBlobDestinationPath) }) }
JavaScript
0
@@ -5169,32 +5169,127 @@ 'index.js') %7C%7C%0A + requiredModuleRelativePath === path.join('..', 'node_modules', 'yauzl', 'index.js') %7C%7C%0A required
717880fd3e803cbf4ae1fe38d5e8cf0a13ed3692
fix hostname resolving when using something like Electron (#594)
client/index.js
client/index.js
/* global __resourceQuery */ var url = require('url'); var stripAnsi = require('strip-ansi'); var socket = require('./socket'); function getCurrentScriptSource() { // `document.currentScript` is the most accurate way to find the current script, // but is not supported in all browsers. if(document.currentScript) return document.currentScript.getAttribute("src"); // Fall back to getting all scripts in the document. var scriptElements = document.scripts || []; var currentScript = scriptElements[scriptElements.length - 1]; if(currentScript) return currentScript.getAttribute("src"); // Fail as there was no script to use. throw new Error("[WDS] Failed to get current script source"); } var urlParts; if(typeof __resourceQuery === "string" && __resourceQuery) { // If this bundle is inlined, use the resource query to get the correct url. urlParts = url.parse(__resourceQuery.substr(1)); } else { // Else, get the url from the <script> this file was called with. var scriptHost = getCurrentScriptSource(); scriptHost = scriptHost.replace(/\/[^\/]+$/, ""); urlParts = url.parse((scriptHost ? scriptHost : "/"), false, true); } var hot = false; var initial = true; var currentHash = ""; var logLevel = "info"; function log(level, msg) { if(logLevel === "info" && level === "info") return console.log(msg); if(["info", "warning"].indexOf(logLevel) >= 0 && level === "warning") return console.warn(msg); if(["info", "warning", "error"].indexOf(logLevel) >= 0 && level === "error") return console.error(msg); } var onSocketMsg = { hot: function() { hot = true; log("info", "[WDS] Hot Module Replacement enabled."); }, invalid: function() { log("info", "[WDS] App updated. Recompiling..."); }, hash: function(hash) { currentHash = hash; }, "still-ok": function() { log("info", "[WDS] Nothing changed.") }, "log-level": function(level) { logLevel = level; }, ok: function() { if(initial) return initial = false; reloadApp(); }, warnings: function(warnings) { log("info", "[WDS] Warnings while compiling."); for(var i = 0; i < warnings.length; i++) console.warn(stripAnsi(warnings[i])); if(initial) return initial = false; reloadApp(); }, errors: function(errors) { log("info", "[WDS] Errors while compiling."); for(var i = 0; i < errors.length; i++) console.error(stripAnsi(errors[i])); if(initial) return initial = false; reloadApp(); }, "proxy-error": function(errors) { log("info", "[WDS] Proxy error."); for(var i = 0; i < errors.length; i++) log("error", stripAnsi(errors[i])); if(initial) return initial = false; }, close: function() { log("error", "[WDS] Disconnected!"); } }; var socketUrl = url.format({ protocol: (window.location.protocol === "https:" || urlParts.hostname === '0.0.0.0') ? window.location.protocol : urlParts.protocol, auth: urlParts.auth, hostname: (urlParts.hostname === '0.0.0.0') ? window.location.hostname : urlParts.hostname, port: (urlParts.port === '0') ? window.location.port : urlParts.port, pathname: urlParts.path == null || urlParts.path === '/' ? "/sockjs-node" : urlParts.path }); socket(socketUrl, onSocketMsg); function reloadApp() { if(hot) { log("info", "[WDS] App hot update..."); var hotEmitter = require("webpack/hot/emitter"); hotEmitter.emit("webpackHotUpdate", currentHash); if(typeof window !== "undefined") { // broadcast update to window window.postMessage("webpackHotUpdate" + currentHash, "*"); } } else { log("info", "[WDS] App updated. Reloading..."); window.location.reload(); } }
JavaScript
0
@@ -2674,16 +2674,381 @@ %0A%09%7D%0A%7D;%0A%0A +var hostname = urlParts.hostname;%0A%0Aif(urlParts.hostname === '0.0.0.0') %7B%0A%09// why do we need this check?%0A%09// hostname n/a for file protocol (example, when using electron, ionic)%0A%09// see: https://github.com/webpack/webpack-dev-server/pull/384%0A%09if(window.location.hostname && !!~window.location.protocol.indexOf('http')) %7B%0A%09%09hostname = window.location.hostname;%0A%09%7D%0A%7D%0A%0A var sock @@ -3068,16 +3068,16 @@ ormat(%7B%0A - %09protoco @@ -3224,16 +3224,16 @@ s.auth,%0A + %09hostnam @@ -3239,80 +3239,8 @@ me: -(urlParts.hostname === '0.0.0.0') ? window.location.hostname : urlParts. host
805f7546c0cafd6e8a5b704eea52fd6b892e4a8c
Add MM size to Button Demo Page (#36)
src/page/button-demo.js
src/page/button-demo.js
import React from 'react'; import { Page, Panel, Button } from 'react-blur-admin'; import {Row, Col} from 'react-flex-proto'; export class ButtonDemo extends React.Component { render() { return ( <Page title='Buttons'> <Row> <Col> <Panel title='Large Buttons' size='md'> <Button type='default' size='lg' /> <Button type='add' size='lg' /> <Button type='remove' size='lg' /> <Button type='info' size='lg' /> <Button type='warning' size='lg' /> <Button type='success' size='lg' /> </Panel> </Col> <Col> <Panel title='Extra Medium Buttons' size='md'> <Button type='default' size='xm' /> <Button type='add' size='xm' /> <Button type='remove' size='xm' /> <Button type='info' size='xm' /> <Button type='warning' size='xm' /> <Button type='success' size='xm' /> </Panel> </Col> <Col> <Panel title='Medium Buttons' size='md'> <Button type='default' /> <Button type='add' /> <Button type='remove' /> <Button type='info' /> <Button type='warning' /> <Button type='success' /> </Panel> </Col> <Col> <Panel title='Small Buttons' size='md'> <Button type='default' size='sm' /> <Button type='add' size='sm' /> <Button type='remove' size='sm' /> <Button type='info' size='sm' /> <Button type='warning' size='sm' /> <Button type='success' size='sm' /> </Panel> </Col> <Col> <Panel title='XS Buttons' size='md'> <Button type='default' size='xs' /> <Button type='add' size='xs' /> <Button type='remove' size='xs' /> <Button type='info' size='xs' /> <Button type='warning' size='xs' /> <Button type='success' size='xs' /> </Panel> </Col> <Col> <Panel title='Disabled Buttons' size='md'> <Button type='default' disabled={true} /> <Button type='add' disabled={true} /> <Button type='remove' disabled={true} /> <Button type='info' disabled={true} /> <Button type='warning' disabled={true} /> <Button type='success' disabled={true} /> </Panel> </Col> </Row> </Page> ); } }
JavaScript
0
@@ -1391,32 +1391,436 @@ %3CCol%3E%0A + %3CPanel title='Mini Medium Buttons' size='md'%3E%0A %3CButton type='default' size='mm' /%3E%0A %3CButton type='add' size='mm' /%3E%0A %3CButton type='remove' size='mm' /%3E%0A %3CButton type='info' size='mm' /%3E%0A %3CButton type='warning' size='mm' /%3E%0A %3CButton type='success' size='mm' /%3E%0A %3C/Panel%3E%0A %3C/Col%3E%0A %3CCol%3E%0A %3CPan
17b66a9510f3ad0c6a9ff45884d40ecffcda2c0b
update plugin ctx definition
flow/common.js
flow/common.js
declare type MapObject = { [string]: any }; declare type ValidatingVM = { $validator: Validator }; declare type PluginContext = { Validator: Validator, ErrorBag: ErrorBag, Rules: Object, VM: Vue };
JavaScript
0
@@ -192,19 +192,8 @@ ject -,%0A VM: Vue %0A%7D;%0A
647aea807a092b552fb6dcf77fe56bdc7e5cf0d1
Fix silly javascript bug - was using global variables
resources/public/js/fractal-maths.js
resources/public/js/fractal-maths.js
function smoothed_count( iterations, final_modulus_squared){ final_modulus = Math.sqrt(final_modulus_squared); if (final_modulus< 1){ return iterations } else{ return iterations - (Math.log(Math.log(final_modulus)) / Math.log(2)) } } function mandelbrot_smoothed_iteration_count( escape_radius_squared, max_iterations, initial_real, initial_imaginary){ mod_z = (initial_real * initial_real) + (initial_imaginary * initial_imaginary); real = initial_real; imaginary = initial_imaginary; iterations = 0; while (mod_z < escape_radius_squared && iterations != max_iterations){ new_real = (real * real) - (imaginary * imaginary) + initial_real; imaginary = (2 * real * imaginary) + initial_imaginary; real = new_real; mod_z = (real * real) + (imaginary * imaginary); iterations++; } return smoothed_count(iterations, mod_z) }
JavaScript
0.000021
@@ -411,24 +411,28 @@ nary)%7B%0A%0A +var mod_z = (ini @@ -501,24 +501,28 @@ nary);%0A%0A +var real = initi @@ -530,24 +530,28 @@ l_real;%0A +var imaginary = @@ -570,24 +570,28 @@ inary;%0A%0A +var iterations = @@ -679,16 +679,20 @@ +var new_real
57116f85e0a99a5c511d18b817fe94efc3fe90bd
fix change PageSize and SrtOrder
public/javascripts/render-voicebanks.js
public/javascripts/render-voicebanks.js
$(function () { $('.selectpicker').selectpicker({ 'selectedText': 'cat' }); showVoicebanks(page); }); var showVoicebanks = function(page){ $.ajax({ url: "/json/getAllVoicebanks", data: { page: page, pageSize: $pageSize.val(), sortCode: $sortOrder.find(':selected').data('sort'), orderCode: $sortOrder.find(':selected').data('order') }, beforeSend: function(){ $('#voicebanks').html($("img").attr("src","../images/ajax-loader.gif")); } }).done(function(data){ var values = data; page = data.pageNow; // Global var pagesCount = Math.ceil(values.voicebanksCount / $pageSize.val()); var pagesCountArray = new Array(); for(var i=0; i<pagesCount; i++){ pagesCountArray[i] = {page:i}; if(values.pageNow == i){ pagesCountArray[i].active = true; } } values.pagesCount = pagesCountArray; if(page-1>=0){ values.prev = { exist: true, page: page-1 }; } if(page+1<pagesCount){ values.next ={ exist: true, page: page+1 }; } template = Handlebars.compile($('#all-voicebanks-tmpl').html()); $('#voicebanks').html(template(values)); history.pushState("","","/voicebanks?page="+page); }).fail(function(e){ console.log('error!!!'); console.log(e); }).always(function(){ $('.page-button').on('click', function(){ showVoicebanks($(this).data('page')); }); $pageSize.on('change', function(){ showVoicebanks(page); }); $sortOrder.on('change', function(){ showVoicebanks(page); }) }); }
JavaScript
0
@@ -1532,36 +1532,33 @@ %09showVoicebanks( -page +0 );%0D%0A%09 %7D);%0D%0A%09 @@ -1625,20 +1625,17 @@ cebanks( -page +0 );%0D%0A%09
344055e7da0b4ae061f4b45077ae7c74621a5675
add instruction for enabling flash player
public/js/p3/widget/HeatmapContainer.js
public/js/p3/widget/HeatmapContainer.js
define([ "dojo/_base/declare", "dojo/_base/lang", "swfobject/swfobject" ], function(declare, lang, swfobject){ return declare([], { flashDom: null, currentData: null, initializeFlash: function(domName){ var flashVars = { showLog: false, startColor: '0x6666ff', endColor: '0x00ff00' }; var params = { quality: 'high', bgcolor: "#ffffff", allowscriptaccess: 'sameDomain', allowfullscreen: false, wmode: 'transparent' }; var attributes = { id: domName, name: domName }; var target = document.getElementById("flashTarget"); // binding flash functions window.flashReady = lang.hitch(this, "flashReady"); window.flashRequestsData = lang.hitch(this, "flashRequestsData"); window.flashCellClicked = lang.hitch(this, "flashCellClicked"); window.flashCellsSelected = lang.hitch(this, "flashCellsSelected"); swfobject.embedSWF('/js/p3/resources/HeatmapViewer.swf', target, '99%', '100%', 19, '/js/swfobject/lib/expressInstall.swf', flashVars, params, attributes); this.flashDom = document.getElementById(domName); }, exportCurrentData: function(isTransposed){ // compose heatmap raw data in tab delimited format // this de-transpose (if it is transposed) so that cluster algorithm can be applied to a specific data type var cols, rows, id_field_name, data_field_name, tablePass = [], header = ['']; if(isTransposed){ cols = this.currentData.rows; rows = this.currentData.columns; id_field_name = 'rowID'; data_field_name = 'colID'; }else{ cols = this.currentData.columns; rows = this.currentData.rows; id_field_name = 'colID'; data_field_name = 'rowID'; } cols.forEach(function(col){ header.push(col[id_field_name]); }); tablePass.push(header.join('\t')); for(var i = 0, iLen = rows.length; i < iLen; i++){ var r = []; r.push(rows[i][data_field_name]); for(var j = 0, jLen = cols.length; j < jLen; j++){ if(isTransposed){ r.push(parseInt(rows[i].distribution[j * 2] + rows[i].distribution[j * 2 + 1], 16)); }else{ r.push(parseInt(cols[j].distribution[i * 2] + cols[j].distribution[i * 2 + 1], 16)); } } tablePass.push(r.join('\t')); } return tablePass.join('\n'); }, // flash interface functions flashReady: function(){ // update this.currentData // this.flashDom.refreshData(); }, flashRequestsData: function(){ return this.currentData; }, flashCellClicked: function(flashObjectID, colID, rowID){ // implement }, flashCellsSelected: function(flashObjectID, colIDs, rowIDs){ // implement } }); });
JavaScript
0.000001
@@ -588,16 +588,416 @@ rget%22);%0A +%09%09%09// add alternative text for instruction on enable flash player%0A%09%09%09target.setAttribute(%22class%22, %22msg-box-below-topnav%22);%0A%09%09%09target.innerHTML = %22If you don't see heatmap image, you need to enable Adobe flash player. %3Ca href='https://helpx.adobe.com/search.html#q=enable%2520flash%2520player%2520for&t=All&sort=relevancy&f:@CommonProduct=%5BFlash%2520Player%5D' target='_blank'%3EClick here for instructions.%3C/a%3E%22%0A %09%09%09// bi
60992a07c9871a5ee6bb36ed89313d2eee0be4e2
Change alert text in gender page
public/templates/quiz/quizController.js
public/templates/quiz/quizController.js
angular.module("personaApp") .controller('quizController', ['$http', function($http){ var quiz = this; quiz.questionNumber = 0; quiz.gender = -1; quiz.questions = []; quiz.results = []; quiz.personalityCounters = [0,0,0,0,0,0,0,0,0]; quiz.highest = 0; quiz.isGenderPage = function(){ return quiz.questionNumber == 0; } quiz.setGender = function(gender) { quiz.gender = gender; } quiz.setAnswer = function(number) { var n = quiz.questions[quiz.questionNumber-1].points[number]; quiz.personalityCounters[n-1]++; var changeHighest = quiz.personalityCounters[n-1] >= quiz.personalityCounters[quiz.highest]; if(changeHighest){ quiz.highest = n-1; } } quiz.start = function() { $http.get('/assets/data/quizData.json').success(function(data){ quiz.questions = data; console.log("Successfully loaded " + quiz.questions.length + " questions"); quiz.showNextQuestion(); }); }; quiz.showNextQuestion = function() { if(quiz.gender < 0){ alert("Pilih cowo apa cewe dulu"); return; } quiz.questionNumber++; if(quiz.questionNumber > quiz.questions.length){ $http.get('/assets/data/quizResults.json').success(function(data){ quiz.results = data; console.log("Successfully loaded " + quiz.results.length + " results"); }); } }; }]);
JavaScript
0.000001
@@ -1160,26 +1160,47 @@ lih -cowo apa cewe dulu +dahulu gender kamu sebelum melanjutkan. %22);%0A
348c3e4f146d1d3b2bda87a8cd67c036e5e41d14
Allow https://people.epfl.ch/*
EPFL_People.user.js
EPFL_People.user.js
// ==UserScript== // @name EPFL People // @namespace none // @description A script to improve browsing on people.epfl.ch // @include http://people.epfl.ch/* // @version 1.0.7 // @grant GM_xmlhttpRequest // @grant GM_addStyle // @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js // @author EPFL-dojo // @downloadURL https://raw.githubusercontent.com/epfl-dojo/EPFL_People_UserScript/master/EPFL_People.user.js // @updateURL https://raw.githubusercontent.com/epfl-dojo/EPFL_People_UserScript/master/EPFL_People.user.js // ==/UserScript== //Avoid conflicts this.$ = this.jQuery = jQuery.noConflict(true); $(document).ready(function() { // get the h1 name content $.epfl_user = { "name": $("h1").text(), "sciper": $('a[href*="http://people.epfl.ch/cgi-bin/people?id="]').attr('href').match(/id=([0-9]{6})/)[1] }; // change the main title content to add the sciper in it $("h1").text($.epfl_user["name"] + " #" + $.epfl_user["sciper"] + " ()"); $.get("/cgi-bin/people/showcv?id=" + $.epfl_user["sciper"] + "&op=admindata&type=show&lang=en&cvlang=en", function(data){ $.epfl_user["username"] = data.match(/Username: (\w+)\s/)[1]; $("h1").text($.epfl_user["name"] + " #" + $.epfl_user["sciper"] + " (" + $.epfl_user["username"]+ ")"); $('.presentation').append('Username : ' + $.epfl_user["username"]+'<br />'); }); $('.presentation').append('Sciper : ' + $.epfl_user["sciper"]+'<br />'); // Add user's mailing list in the right column var cadiURL = 'http://cadiwww.epfl.ch/listes?sciper='+$.epfl_user["sciper"]; GM_xmlhttpRequest({ method: "GET", url: cadiURL, onload: function(response) { html = $.parseHTML( response.responseText ); // Mailing list emails mailinglistUL = $(html).contents('ul').not(':last'); if (0 < mailinglistUL.length) { $('.right-col').append('<h4>Mailing Lists</h4><div id="cadiMLdiv"><ul id="cadiML">test</ul></div>'); $('#cadiML').html(mailinglistUL); } // Group list emails grouplistUL = $(html).contents('ul').last(); if (0 < grouplistUL.length) { $('.right-col').append('<br /><h4>Groups Lists</h4><div id="cadiGLdiv"><ul id="cadiGL">test</ul></div>'); $('#cadiGL').html(grouplistUL); } } }); GM_addStyle("#cadiMLdiv{ padding-left: 20px; } #cadiML ul ul { margin-left: 10px; }" ); GM_addStyle("#cadiGLdiv{ padding-left: 20px; } #cadiGL ul ul { margin-left: 10px; }" ); // var adminDataURL = "http://people.epfl.ch/cgi-bin/people?id="+sciper+"&op=admindata&lang=en&cvlang=en"; /* Idea => add accred link <div class="button accred"> <a href="http://accred.epfl.ch/accred/accreds.pl/userinfo?thescip=136597"> <button class="icon"></button> <span class="label"> Accreditations of Jean-Claude&nbsp;De Giorgi (fr)</span> </a> </div>*/ });
JavaScript
0.000002
@@ -163,16 +163,57 @@ fl.ch/*%0A +// @include https://people.epfl.ch/*%0A // @vers
42a1ea44130284d8041c9bcdb3010d2c1d9f9863
Use async.series instead of nested callbacks
test/functional/run-all.js
test/functional/run-all.js
var path = require('path'); var lodash = require('lodash'); var run = require('../../src/index.js'); var capabilities = [{browserName: 'phantomjs'}]; var driver = 'phantomjs'; var configSeleniumWebdriverJasmine = { driver: driver, capabilities: capabilities, tests: [ path.join(__dirname, 'selenium-webdriver', 'jasmine-github.js'), path.join(__dirname, 'selenium-webdriver', 'jasmine-google-search.js') ] }; var configSeleniumWebdriverJasmineWithHelper = { driver: driver, capabilities: capabilities, tests: [ path.join(__dirname, 'selenium-webdriver', 'jasmine-selenium-webdriver', 'jasmine-github.js'), path.join(__dirname, 'selenium-webdriver', 'jasmine-selenium-webdriver', 'jasmine-google-search.js') ], runnerModules: [ 'jasmine-selenium-webdriver' ] }; var configPlainJasmine = { driver: driver, capabilities: capabilities, tests: [ path.join(__dirname, 'selenium-webdriver', 'plain-github.js') ], runner: 'plain' }; var configSeleniumWebdriverMochaWithHelper = { driver: driver, capabilities: capabilities, tests: [ path.join(__dirname, 'selenium-webdriver', 'mocha-selenium-webdriver', 'mocha-github.js'), path.join(__dirname, 'selenium-webdriver', 'mocha-selenium-webdriver', 'mocha-google-search.js') ], runnerModules: [ 'mocha-selenium-webdriver' ], runnerOptions: { reporter: 'dot' }, runner: 'mocha' }; var configWdMocha = { driver: driver, capabilities: capabilities, tests: [ path.join(__dirname, 'wd', 'mocha-github.js'), path.join(__dirname, 'wd', 'mocha-google-search.js') ], runner: 'mocha', runnerOptions: { reporter: 'spec' }, client: 'wd' }; var configWdPromiseMocha = { driver: driver, capabilities: capabilities, tests: [ path.join(__dirname, 'wd-promise', 'mocha-github.js'), path.join(__dirname, 'wd-promise', 'mocha-google-search.js') ], runner: 'mocha', runnerOptions: { reporter: 'nyan' }, client: 'wd-promise' }; var configCabbieMocha = { // executing with selenium because cabbie in combination with Ghostdriver // currently fails with the initial session-request capabilities: capabilities, tests: [ path.join(__dirname, 'cabbie', 'mocha-github.js'), path.join(__dirname, 'cabbie', 'mocha-google-search.js') ], runner: 'mocha', runnerOptions: { reporter: 'spec' }, client: 'cabbie' }; run(configSeleniumWebdriverJasmine, function(error, results) { handleErrorCallback(error, results); run(configSeleniumWebdriverJasmineWithHelper, function(error, results) { handleErrorCallback(error, results); run(configPlainJasmine, function(error, results) { handleErrorCallback(error, results); run(configSeleniumWebdriverMochaWithHelper, function(error, results) { handleErrorCallback(error, results); run(configWdMocha, function(error, results) { handleErrorCallback(error, results); run(configWdPromiseMocha, function(error, results) { handleErrorCallback(error, results); run(configCabbieMocha, function(error, results) { handleErrorCallback(error, results); process.exit(0); }); }); }); }); }); }); }); function handleErrorCallback(error, results) { var passed = lodash.every(results, 'passed'); if (error || !passed) { process.exit(1); } }
JavaScript
0.000001
@@ -1,12 +1,42 @@ +var async = require('async');%0A var path = r @@ -2430,581 +2430,339 @@ %7D;%0A%0A -run(configSeleniumWebdriverJasmine, function(error, results) %7B%0A handleErrorCallback(error, results);%0A run(configSeleniumWebdriverJasmineWithHelper, function(error, results) %7B%0A handleErrorCallback(error, results);%0A run(configPlainJasmine, function(error, results) %7B%0A handleErrorCallback(error, results);%0A run(configSeleniumWebdriverMochaWithHelper, function(error, results) %7B%0A handleErrorCallback(error, results);%0A run(configWdMocha, function(error, results) %7B%0A handleErrorCallback(error, results);%0A run(configWdPromis +async.series(%5B%0A run.bind(null, configSeleniumWebdriverJasmine),%0A run.bind(null, configSeleniumWebdriverJasmineWithHelper),%0A run.bind(null, configPlainJasmine),%0A run.bind(null, configSeleniumWebdriverMochaWithHelper),%0A run.bind(null, configWdMocha),%0A run.bind(null, configWdPromiseMocha),%0A run.bind(null, configCabbi eMocha +)%0A%5D , fu @@ -2792,88 +2792,52 @@ %7B%0A - handleErrorCallback(error, results);%0A run(configCabbieMocha +var passed = lodash.every(lodash.map(results , fu @@ -2847,30 +2847,22 @@ ion( -error, result -s ) %7B%0A @@ -2861,275 +2861,204 @@ - handleErrorCallback(error, results);%0A process.exit(0);%0A %7D);%0A %7D);%0A %7D);%0A %7D);%0A %7D);%0A %7D);%0A%7D);%0A%0Afunction handleErrorCallback(error, results) %7B%0A var passed = lodash.every(results, 'passed');%0A if (error %7C%7C !passed) +return lodash.every(result, 'passed');%0A %7D));%0A if (!passed) %7B%0A error = new Error('One or more tests did not pass.');%0A %7D%0A%0A if (error) %7B%0A console.error(error);%0A process.exit(1);%0A %7D else %7B%0A @@ -3077,14 +3077,14 @@ xit( -1 +0 );%0A %7D%0A%7D %0A @@ -3082,9 +3082,11 @@ );%0A %7D%0A%7D +); %0A
e55df06bc4e0d1ed484e54e31687bc13abe0c2b7
Switch templates correctly
gatsby-node.js
gatsby-node.js
/** * Implement Gatsby's Node APIs in this file. * * See: https://www.gatsbyjs.org/docs/node-apis/ */ const path = require('path') const fs = require('fs') const fetch = require('node-fetch') const yaml = require('js-yaml') exports.onCreateWebpackConfig = ({ stage: _stage, actions }) => { actions.setWebpackConfig({ resolve: { alias: { '../../theme.config$': path.join(__dirname, 'src/semantic/theme.config') } } }) } exports.onPreBootstrap = async () => { async function createPageFromRemoteMd(url, pagePath, frontmatter) { const res = await fetch(url) const md = await res.text() const fm = yaml.safeDump(frontmatter) fs.writeFileSync(path.resolve(pagePath), `---\n${fm}---\n\n${md}`) } /* * Generate release notes */ await createPageFromRemoteMd( `https://unpkg.com/inkdrop-version-history-beta@latest/README.md`, `src/pages/releases.md`, { index: 20, category: 'info', path: '/releases', title: 'Release Notes' } ) await createPageFromRemoteMd( `https://unpkg.com/inkdrop-version-history-mobile@latest/README.md`, `src/pages/releases-mobile.md`, { index: 30, category: 'info', path: '/releases-mobile', title: 'Release Notes (Mobile)' } ) await createPageFromRemoteMd( `https://raw.githubusercontent.com/inkdropapp/inkdrop-model/master/docs/schema.md`, `src/pages/reference/data-models.md`, { index: 20, category: 'data', path: '/reference/data-models', title: 'Data Models' } ) } exports.createPages = async ({ actions, graphql }) => { const { createPage } = actions const manualTemplate = path.resolve(`src/templates/manual-template.js`) const referenceTemplate = path.resolve(`src/templates/reference-template.js`) const infoTemplate = path.resolve(`src/templates/info-template.js`) function getTemplateForCategory(category) { switch (category) { case 'info': return infoTemplate case 'reference': return referenceTemplate default: return manualTemplate } } /* * Generate pages from Markdown */ const result = await graphql(` { allMarkdownRemark( sort: { order: ASC, fields: [frontmatter___index] } limit: 1000 ) { edges { node { frontmatter { path category } } } } } `) if (result.errors) { throw result.errors } result.data.allMarkdownRemark.edges.forEach(({ node }) => { const { path, category } = node.frontmatter createPage({ path, component: getTemplateForCategory(category), context: {} // additional data can be passed via context }) }) }
JavaScript
0.000004
@@ -2022,25 +2022,42 @@ case ' -reference +data':%0A case 'classes ':%0A
b4b345f9b300afcb6280d9b3e7397bf0dc074fc9
remove comments
src/plugins/Informer.js
src/plugins/Informer.js
const Plugin = require('./Plugin') const html = require('yo-yo') /** * Informer * Shows rad message bubbles * used like this: `core.emit('informer', 'hello world', 'info', 5000)` * or for errors: `core.emit('informer', 'Error uploading img.jpg', 'error', 5000)` * */ module.exports = class Informer extends Plugin { constructor (core, opts) { super(core, opts) this.type = 'progressindicator' this.id = 'Informer' this.title = 'Informer' // this.timeoutID = undefined // set default options const defaultOptions = { typeColors: { info: { text: '#fff', bg: '#000' }, warning: { text: '#fff', bg: '#F6A623' }, error: { text: '#fff', bg: '#e74c3c' }, success: { text: '#fff', bg: '#7ac824' } } } // merge default options with the ones set by user this.opts = Object.assign({}, defaultOptions, opts) this.render = this.render.bind(this) } // showInformer (msg, type, duration) { // this.core.setState({ // informer: { // isHidden: false, // type: type, // msg: msg // } // }) // window.clearTimeout(this.timeoutID) // if (duration === 0) { // this.timeoutID = undefined // return // } // // hide the informer after `duration` milliseconds // this.timeoutID = setTimeout(() => { // const newInformer = Object.assign({}, this.core.getState().informer, { // isHidden: true // }) // this.core.setState({ // informer: newInformer // }) // }, duration) // } // hideInformer () { // const newInformer = Object.assign({}, this.core.getState().informer, { // isHidden: true // }) // this.core.setState({ // informer: newInformer // }) // } render (state) { const isHidden = state.info.isHidden const msg = state.info.msg const type = state.info.type || 'info' const style = `background-color: ${this.opts.typeColors[type].bg}; color: ${this.opts.typeColors[type].text};` // @TODO add aria-live for screen-readers return html`<div class="Uppy UppyTheme--default UppyInformer" style="${style}" aria-hidden="${isHidden}"> <p>${msg}</p> </div>` } install () { // this.core.setState({ // informer: { // isHidden: true, // type: '', // msg: '' // } // }) // this.core.on('informer', (msg, type, duration) => { // this.showInformer(msg, type, duration) // }) // this.core.on('informer:hide', () => { // this.hideInformer() // }) const target = this.opts.target const plugin = this this.target = this.mount(target, plugin) } }
JavaScript
0
@@ -1047,860 +1047,8 @@ %7D%0A%0A - // showInformer (msg, type, duration) %7B%0A // this.core.setState(%7B%0A // informer: %7B%0A // isHidden: false,%0A // type: type,%0A // msg: msg%0A // %7D%0A // %7D)%0A%0A // window.clearTimeout(this.timeoutID)%0A // if (duration === 0) %7B%0A // this.timeoutID = undefined%0A // return%0A // %7D%0A%0A // // hide the informer after %60duration%60 milliseconds%0A // this.timeoutID = setTimeout(() =%3E %7B%0A // const newInformer = Object.assign(%7B%7D, this.core.getState().informer, %7B%0A // isHidden: true%0A // %7D)%0A // this.core.setState(%7B%0A // informer: newInformer%0A // %7D)%0A // %7D, duration)%0A // %7D%0A%0A // hideInformer () %7B%0A // const newInformer = Object.assign(%7B%7D, this.core.getState().informer, %7B%0A // isHidden: true%0A // %7D)%0A // this.core.setState(%7B%0A // informer: newInformer%0A // %7D)%0A // %7D%0A%0A re @@ -1505,349 +1505,8 @@ ) %7B%0A - // this.core.setState(%7B%0A // informer: %7B%0A // isHidden: true,%0A // type: '',%0A // msg: ''%0A // %7D%0A // %7D)%0A%0A // this.core.on('informer', (msg, type, duration) =%3E %7B%0A // this.showInformer(msg, type, duration)%0A // %7D)%0A%0A // this.core.on('informer:hide', () =%3E %7B%0A // this.hideInformer()%0A // %7D)%0A%0A
8dd6f88ab133ec6aace935c2c3403172fbedc925
fix test case
test/queries/type-query.js
test/queries/type-query.js
import termQuery from '../../src/queries/type-query' import {expect} from 'chai' describe('typeQuery', () => { it('should create a type query', () => { let result = termQuery('custom_type') expect(result).to.eql({ type: { value: 'custom-type' } }) }) })
JavaScript
0.000022
@@ -187,9 +187,9 @@ stom -_ +- type
e7675253e5ba26c399882b3034d32255d391e79e
Make serialisation methods work with current URL, and use default values
src/probabilitydrive.js
src/probabilitydrive.js
(function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else { root.probabilitydrive = factory(); } }(this, function () { function ProbabilityDrive() { this.currentUrl; this.store = {}; this.routeUrls = []; this.blacklistUrls = []; } ProbabilityDrive.prototype.observe = function(url) { if (!this.currentUrl || this.currentUrl === url) { this.currentUrl = url; return this; } incrementUrl.call(this, url); analyse.call(this, this.currentUrl); this.currentUrl = url; return this; } ProbabilityDrive.prototype.determine = function(url) { url = url || this.currentUrl; var minCount = 0; var result = []; for (var i in this.store[url]) { if (minCount <= this.store[url][i].count) { result.push(this.store[url][i]); minCount = this.store[url][i].count } else { break; } } return result; } ProbabilityDrive.prototype.percentile = function(percentile) { percentile = percentile / 100; var data = this.store[this.currentUrl]; var first = data.splice(0, 1)[0]; var multiplier = 1 / first.probability; var results = [first]; for (var i in data) { var urlData = data[i]; if (urlData.probability * multiplier >= percentile) { results.push(urlData); } else { break; } } return results; } ProbabilityDrive.prototype.threshold = function(probability) { var data = this.store[this.currentUrl]; var result = []; for (var i in data) { var urlData = data[i]; if (urlData.probability >= probability) { result.push(urlData); } else { break; } } return result; } ProbabilityDrive.prototype.routes = function(routes) { for (var i = 0; i < routes.length; i++) { this.routeUrls.push( stripAndBreakUrl(routes[i], '/') ) } } ProbabilityDrive.prototype.blacklist = function(routes) { for (var i = 0; i < routes.length; i++) { this.blacklistUrls.push( stripAndBreakUrl(routes[i], '/') ) } } ProbabilityDrive.prototype.getData = function() { return this.store; } ProbabilityDrive.prototype.setData = function(data) { this.store = data; } // Aliases ProbabilityDrive.prototype.here = ProbabilityDrive.prototype.observe ProbabilityDrive.prototype.next = ProbabilityDrive.prototype.determine function incrementUrl(url) { if (matchRoute(url, this.blacklistUrls)) { // Route is blacklisted return; } var matchResult = matchRoute(url, this.routeUrls); if (matchResult) { // Use parameterised route url = matchResult; } this.store[this.currentUrl] = this.store[this.currentUrl] || []; var found = false; for (var i in this.store[this.currentUrl]) { if (this.store[this.currentUrl][i].url === url) { found = true; this.store[this.currentUrl][i].count += 1; break; } } if (!found) { this.store[this.currentUrl].push({ url: url, count: 1, probability: 0 }); } } function analyse(url) { if (!this.store[url]) { return; } var total = this.store[url].reduce(function(total, urlData) { return total += urlData.count; }, 0); this.store[url].forEach(function(urlData) { urlData.probability = urlData.count / total; }); this.store[url].sort(function(a, b) { return a.count < b.count; }); } function matchRoute(url, list) { var urlParts = stripAndBreakUrl(url, '/'); for (var i = 0; i < list.length; i++) { var routeUrlParts = list[i]; if (isMatchRouteParts(urlParts, routeUrlParts)) { return '/' + routeUrlParts.join('/'); } } return false; } function isMatchRouteParts(urlParts, routeUrlParts) { for (var i = 0; i < routeUrlParts.length; i++) { if (!urlParts[i] || (routeUrlParts[i] !== urlParts[i] && routeUrlParts[i].indexOf(':') === -1) ) { break; } return true; } return false; } function stripAndBreakUrl(string, character) { string = string.charAt(0) !== character ? string : string.substring(1); return string.split('/'); } return ProbabilityDrive; }));
JavaScript
0
@@ -2600,26 +2600,98 @@ return -this.store +%7B%0A currentUrl: this.currentUrl,%0A store: this.store%0A %7D ;%0A %7D%0A @@ -2741,32 +2741,102 @@ unction(data) %7B%0A + data = data %7C%7C %7B%7D;%0A this.currentUrl = data.currentUrl;%0A this.sto @@ -2844,16 +2844,28 @@ e = data +.store %7C%7C %7B%7D ;%0A %7D%0A
8a5668c4e0f003f7b5635805ae421e411e8d5afa
update tests of main duck
test/redux/modules/main.js
test/redux/modules/main.js
import test from 'ava'; import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import mainReducer, {setInterfaceFontSizeScalingFactor, SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, setAppFont, SET_APP_FONT, setAppLocale, SET_APP_LOCALE, setWriteDelay, SET_WRITE_DELAY, setIntl, openExternal, OPEN_EXTERNAL, setContentFontSizeScalingFactor, SET_CONTENT_FONT_SIZE_SCALING_FACTOR, getAppVersion, GET_APP_VERSION_SUCCESS} from './../../../src/redux/modules/main'; import zhTwMessages from './../../../src/langs/zh-TW'; import enMessages from './../../../src/langs/en'; import clientMiddleware from './../../../src/redux/middlewares/clientMiddleware'; import ipc from './../../../src/helpers/ipc'; const middlewares = [thunk, clientMiddleware(ipc)]; const mockStore = configureMockStore(middlewares); const electron = window.require('electron'); const {ipcMain} = electron; test('should create an action to set interface font size scaling factor', (t) => { const interfaceFontSizeScalingFactor = 1; const expectedAction = { type: SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, interfaceFontSizeScalingFactor }; t.deepEqual(setInterfaceFontSizeScalingFactor(interfaceFontSizeScalingFactor), expectedAction); }); test('should create an action to set app font', (t) => { const appFont = 'Tibetan Machine Uni'; const expectedAction = { type: SET_APP_FONT, appFont }; t.deepEqual(setAppFont(appFont), expectedAction); }); test('should create an action to set app locale', (t) => { const appLocale = 'bo'; const expectedAction = { type: SET_APP_LOCALE, appLocale }; t.deepEqual(setAppLocale(appLocale), expectedAction); }); test('should create an action to set write delay', (t) => { const writeDelay = 25; const expectedAction = { type: SET_WRITE_DELAY, writeDelay }; t.deepEqual(setWriteDelay(writeDelay), expectedAction); }); test('should create an action to set content font size scaling factor', (t) => { const contentFontSizeScalingFactor = 1.5; const expectedAction = { type: SET_CONTENT_FONT_SIZE_SCALING_FACTOR, contentFontSizeScalingFactor }; t.deepEqual(setContentFontSizeScalingFactor(contentFontSizeScalingFactor), expectedAction); }); test('should create an action to get app version', async (t) => { const appVersion = '0.0.1'; const store = mockStore({}); const expectedAction = { type: GET_APP_VERSION_SUCCESS }; const eventName = 'get-app-version'; ipcMain.once(eventName, (event, args) => { const id = args._id; delete args._id; args.appVersion = appVersion; event.sender.send(`${eventName}::${id}`, args); }); const result = await store.dispatch(getAppVersion()) t.is(result.appVersion, appVersion); }); test('should create an action to set react intl', (t) => { const store = mockStore({}); const locale = 'zh-TW'; const expectedAction = { type: '@@intl/UPDATE', payload: { locale, messages: zhTwMessages } }; const resultAction = store.dispatch(setIntl(locale)); t.deepEqual(resultAction, expectedAction); }); test('should create an action to set react intl if no locale is provided', (t) => { const store = mockStore({}); const expectedAction = { type: '@@intl/UPDATE', payload: { locale: 'en', messages: enMessages } }; const resultAction = store.dispatch(setIntl()); t.deepEqual(resultAction, expectedAction); }); test('should open external url without any errors', (t) => { const store = mockStore({}); const url = 'https://www.google.com'; store.dispatch(openExternal(url)); t.pass(); }); test('should get app version without any errors', (t) => { const store = mockStore({}); store.dispatch(getAppVersion()); t.pass(); }); test('main reducer should handle action SET_APP_LOCALE', (t) => { const appLocale = 'en'; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_APP_LOCALE, appLocale}); t.deepEqual(result.toJS(), {appLocale}); }); test('main reducer should handle action SET_WRITE_DELAY', (t) => { const writeDelay = 50; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_WRITE_DELAY, writeDelay}); t.deepEqual(result.toJS(), {writeDelay}); }); test('main reducer should handle action SET_APP_FONT', (t) => { const appFont = 'Tibetan Machine Uni'; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_APP_FONT, appFont}); t.deepEqual(result.toJS(), {appFont}); }); test('main reducer should handle action SET_INTERFACE_FONT_SIZE_SCALING_FACTOR', (t) => { const interfaceFontSizeScalingFactor = 1.5; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, interfaceFontSizeScalingFactor}); t.deepEqual(result.toJS(), {interfaceFontSizeScalingFactor}); }); test('main reducer should handle action SET_CONTENT_FONT_SIZE_SCALING_FACTOR', (t) => { const contentFontSizeScalingFactor = 1.5; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_CONTENT_FONT_SIZE_SCALING_FACTOR, contentFontSizeScalingFactor}); t.deepEqual(result.toJS(), {contentFontSizeScalingFactor}); });
JavaScript
0
@@ -2271,43 +2271,42 @@ uld -create an action to get app version +get app version without any errors ', a @@ -3660,60 +3660,106 @@ st(' -should get app version without any errors', (t) =%3E %7B +main reducer should handle action GET_APP_VERSION_SUCCESS', (t) =%3E %7B%0A const appVersion = '0.0.1'; %0A c @@ -3788,35 +3788,103 @@ (%7B%7D);%0A +con st -ore.dispatch(getA + result = mainReducer(store.getState(), %7Btype: GET_APP_VERSION_SUCCESS, result: %7Ba ppVersio @@ -3888,22 +3888,54 @@ sion -() +%7D%7D );%0A t. -pass( +deepEqual(result.toJS(), %7BappVersion%7D );%0A%7D
d8c4f4bd1920a9353f6708cb71490a0f969464b1
Update test msg
test/remoteMethods.test.js
test/remoteMethods.test.js
var request = require('supertest'); var loopback = require('loopback'); var expect = require('chai').expect; var JSONAPIComponent = require('../'); var app, Post; describe('loopback json api remote methods', function () { beforeEach(function () { app = loopback(); app.set('legacyExplorer', false); var ds = loopback.createDataSource('memory'); Post = ds.createModel('post', { id: {type: Number, id: true}, title: String, content: String }); Post.greet = function (msg, cb) { cb(null, 'Greetings... ' + msg); }; Post.remoteMethod( 'greet', { accepts: {arg: 'msg', type: 'string'}, returns: {arg: 'greeting', type: 'string'} } ); app.model(Post); app.use(loopback.rest()); JSONAPIComponent(app); }); describe('status codes', function () { it('POST /models should return a 201 CREATED status code', function (done) { request(app).post('/posts') .send({'msg': 'John'}) .set('Content-Type', 'application/json') .expect(201) .end(function (err, res) { expect(err).to.equal(null); expect(res.body).to.equal('Greetings... John!'); done(); }); }); }); });
JavaScript
0.000001
@@ -886,32 +886,28 @@ urn -a 201 CREATED status cod +remote method messag e', @@ -1060,9 +1060,9 @@ t(20 -1 +0 )%0A
9ea58e1d191b6ee6f92aba2a443469c29f58a1f2
update bs.common.spec.js
test/sdk/bs.common.spec.js
test/sdk/bs.common.spec.js
import { common } from '../../src/dove.sdk/bs/common' describe('SDK.BS.common', () => { it('Tool getType', () => { var cbName1 = common._get_callback(function () {}, true) var cbName2 = common._get_callback(function () {}, true) expect(cbName1).not.toEqual(cbName2) }) })
JavaScript
0.000001
@@ -92,20 +92,21 @@ it(' -Tool getType +_get_callback ', ( @@ -280,12 +280,107 @@ e2)%0A %7D) +%0A%0A it('getJQuery$', () =%3E %7B%0A var $ = common.getJQuery$()%0A expect($).toBeUndefined()%0A %7D) %0A%7D)%0A
9935fa30c65ed71b5226e9b15ab0182da1cabb7c
Resolve author urls!
get-chapter.js
get-chapter.js
'use strict' module.exports = getChapter var url = require('url') var cheerio = require('cheerio') function getChapter (fetch, chapter) { return fetch(chapter).spread(function (finalURL, html) { var chapterHash = url.parse(chapter).hash var parsed = url.parse(finalURL) var id if (/^#post/.test(chapterHash)) { id = chapterHash || parsed.hash || '' } else { id = parsed.hash || chapterHash || '' } if (id) { parsed.hash = id finalURL = url.format(parsed) } var $ = cheerio.load(html) var content if (id !== '') { content = $(id + ' article') } else { content = $($('article')[0]) } if (content.length === 0) { var error = $('div.errorPanel') if (error.length === 0) { throw new Error('No chapter found at ' + chapter) } else { throw new Error('Error fetching ' + chapter + ': ' + error.text().trim()) } } var base = $('base').attr('href') || finalURL var author = $($('a.username')[0]) var authorUrl = author.attr('href') var authorName = author.text() // sv, sb var workTitle = $('meta[property="og:title"]').attr('content') var threadDate = $('abbr.DateTime') // qq if (!workTitle) workTitle = $('div.titleBar h1').text().replace(/^\[\w+\] /, '') if (!threadDate.length) threadDate = $('span.DateTime') if (threadDate.length) { var started = +($(threadDate).attr('data-time')) || $(threadDate).attr('datestring') } return { chapterLink: chapter, finalURL: finalURL, base: base, workTitle: workTitle || '', author: authorName, authorUrl: authorUrl, content: content.html(), started: started } }) }
JavaScript
0
@@ -1045,16 +1045,34 @@ horUrl = + url.resolve(base, author. @@ -1083,16 +1083,17 @@ ('href') +) %0A var
d214c651f274b977238007c76ee0ad8299644a6d
Fix tests for hash updates
test/spec/renderer/hash.js
test/spec/renderer/hash.js
describe("hash", function () { var hash, map; beforeEach(function () { hash = iD.Hash(); map = { on: function () { return map; }, off: function () { return map; }, zoom: function () { return arguments.length ? map : 0; }, center: function () { return arguments.length ? map : [0, 0] }, centerZoom: function () { return arguments.length ? map : [0, 0] } }; }); afterEach(function () { hash.map(null); location.hash = ""; }); describe("#map()", function () { it("gets and sets map", function () { expect(hash.map(map)).to.equal(hash); expect(hash.map()).to.equal(map); }); it("sets hadHash if location.hash is present", function () { location.hash = "map=20.00/38.87952/-77.02405"; hash.map(map); expect(hash.hadHash).to.be.true; }); it("centerZooms map to requested level", function () { location.hash = "map=20.00/38.87952/-77.02405"; sinon.spy(map, 'centerZoom'); hash.map(map); expect(map.centerZoom).to.have.been.calledWith([-77.02405,38.87952], 20.0); }); it("binds the map's move event", function () { sinon.spy(map, 'on'); hash.map(map); expect(map.on).to.have.been.calledWith('move', sinon.match.instanceOf(Function)); }); it("unbinds the map's move event", function () { sinon.spy(map, 'on'); sinon.spy(map, 'off'); hash.map(map); hash.map(null); expect(map.off).to.have.been.calledWith('move', map.on.firstCall.args[1]); }); }); describe("on window hashchange events", function () { beforeEach(function () { hash.map(map); }); function onhashchange(fn) { d3.select(window).one("hashchange", fn); } it("centerZooms map at requested coordinates", function (done) { onhashchange(function () { expect(map.centerZoom).to.have.been.calledWith([-77.02405,38.87952], 20.0); done(); }); sinon.spy(map, 'centerZoom'); location.hash = "#map=20.00/38.87952/-77.02405"; }); }); describe("on map move events", function () { it("stores the current zoom and coordinates in location.hash", function () { sinon.stub(map, 'on').yields(); hash.map(map); expect(location.hash).to.equal("#map=0.00/0/0"); }); }); });
JavaScript
0
@@ -41,18 +41,30 @@ ash, map +, controller ;%0A - %0A bef @@ -369,16 +369,17 @@ : %5B0, 0%5D +; %7D,%0A @@ -450,16 +450,162 @@ : %5B0, 0%5D +; %7D%0A %7D;%0A controller = %7B%0A on: function () %7B return controller; %7D,%0A off: function () %7B return controller; %7D%0A @@ -783,32 +783,32 @@ , function () %7B%0A - expe @@ -811,24 +811,47 @@ expect(hash. +controller(controller). map(map)).to
23aa0cc7e071f439a18134fc61522654ed124514
Fix bug on progress map reduce
server/app/guildKills/guildKillModel.js
server/app/guildKills/guildKillModel.js
"use strict"; var async = require("async"); var applicationStorage = process.require("core/applicationStorage.js"); var validator = process.require("core/utilities/validators/validator.js"); /** * Upsert a kill * @param region * @param realm * @param name * @param raid * @param boss * @param bossWeight * @param difficulty * @param timestamp * @param source * @param callback */ module.exports.upsert = function (region, realm, name, raid, boss, bossWeight, difficulty, timestamp, source, progress, callback) { async.series([ function (callback) { //Format value region = region.toLowerCase(); callback(); }, function (callback) { //Validate Params validator.validate({ region: region, realm: realm, name: name, raid: raid, boss: boss, bossWeight: bossWeight, difficulty: difficulty, timestamp: timestamp, source: source }, function (error) { callback(error); }); }, function (callback) { //Upsert var guildKill = { region: region, realm: realm, name: name, boss: boss, bossWeight: bossWeight, difficulty: difficulty, timestamp: timestamp, source: source, updated: new Date().getTime() } var collection = applicationStorage.mongo.collection(raid); async.series([ function (callback) { collection.updateOne({ region: region, realm: realm, name: name, boss: boss, bossWeight: bossWeight, difficulty: difficulty, timestamp: timestamp, source: source }, {$set: guildKill}, {upsert: true}, function (error) { callback(error); }); }, function (callback) { if (progress) { collection.updateOne({ region: region, realm: realm, name: name, boss: boss, difficulty: difficulty, timestamp: timestamp, source: source, "roster.name": {$ne: progress.name} }, {$push: {roster: progress}}, function (error) { callback(error); }); } else { callback(); } } ], function (error) { callback(error); }) } ], function (error) { callback(error); }); }; /** * Map reduce for * @param region * @param realm * @param name * @param raid * @param callback */ module.exports.computeProgress = function (region, realm, name, raid, callback) { async.waterfall([ function (callback) { //Format value region = region.toLowerCase(); callback(); }, function (callback) { //Validate Params validator.validate({region: region, realm: realm, name: name, raid: raid}, function (error) { callback(error); }); }, function (callback) { //Upsert var map = function () { var mapped = { timestamp: this.timestamp, roster: this.roster, source: this.source }; var key = {difficulty: this.difficulty, boss: this.boss}; emit(key, mapped); }; var reduce = function (key, values) { var reduced = {timestamps: []}; if (values && values[0] && values[0].timestamps) { reduced = values[0]; } for (var idx = 0; idx < values.length; idx++) { if (values[idx].source === "wowprogress") { if (idx < values.length - 1 && values[idx].timestamp + 1000 >= values[idx + 1].timestamp) { if (values[idx + 1].source != "progress") { //no progress found in + or - 1 sec of wowprogress entry reduced.timestamps.push([values[idx].timestamp]); } else if (values[idx].timestamp < 1451602800000) { //Before 2016/01/01 wowprogress is mandatory reduced.timestamps.push([values[idx].timestamp]); idx++; } } else { reduced.timestamps.push([values[idx].timestamp]); } } else if (values[idx].source === "progress") { if (idx < values.length - 1 && values[idx].timestamp + 1000 >= values[idx + 1].timestamp && values[idx + 1].source == "progress") { var rosterLength = values[idx].roster.length + values[idx + 1].roster.length; if ((key.difficulty == "mythic" && rosterLength >= 16) || ((key.difficulty == "normal" || key.difficulty == "heroic") && rosterLength >= 8)) { reduced.timestamps.push([values[idx].timestamp, values[idx + 1].timestamp]); } idx++; } else { if (values[idx].roster && ((key.difficulty == "mythic" && values[idx].roster.length >= 16) || ((key.difficulty == "normal" || key.difficulty == "heroic") && values[idx].roster.length >= 8 ))) { reduced.timestamps.push([values[idx].timestamp]); } } } } return reduced; }; var finalize = function (key, value) { if (value.timestamp) { if ((value.source == "progress" && ((key.difficulty == "mythic" && value.roster.length >= 16 ) || ((key.difficulty == "normal" || key.difficulty == "heroic") && value.roster.length >= 8))) || value.source == "wowprogress") { return {timestamps: [[value.timestamp]]}; } else if (value.source == "wowprogress") { return {timestamps: [[value.timestamp]]}; } else { return {timestamps: []}; } } return value; }; var collection = applicationStorage.mongo.collection(raid); collection.mapReduce(map, reduce, { out: {inline: 1}, finalize: finalize, query: {region: region, realm: realm, name: name}, sort: {timestamp: 1, source: -1} }, function (error, result) { callback(error, result); }); } ], function (error, result) { callback(error, result); }); };
JavaScript
0
@@ -5586,32 +5586,59 @@ ce == %22progress%22 + && values%5Bidx + 1%5D.roster ) %7B%0A
a90601e77b027e39ef7a7920c05830978e6f07c4
Remove the associated PaperScope when a Project is removed.
src/project/Project.js
src/project/Project.js
/* * Paper.js * * This file is part of Paper.js, a JavaScript Vector Graphics Library, * based on Scriptographer.org and designed to be largely API compatible. * http://paperjs.org/ * http://scriptographer.org/ * * Distributed under the MIT license. See LICENSE file for details. * * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey * http://lehni.org/ & http://jonathanpuckey.com/ * * All rights reserved. */ /** * @name Project * * @class The Project item refers to.. * * The currently active project can be accessed through the global {@code * project} variable. * * An array of all open projects is accessible through the global {@code * projects} variable. */ var Project = this.Project = Base.extend(/** @lends Project# */{ // TODO: Add arguments to define pages // DOCS: Document Project constructor and class /** * Creates a Paper.js project */ initialize: function() { // Store reference to the currently active global paper scope: this._scope = paper; // Push it onto this._scope.projects and set index: this._index = this._scope.projects.push(this) - 1; this._currentStyle = new PathStyle(); this._selectedItems = {}; this._selectedItemCount = 0; // Activate straight away so paper.project is set, as required by // Layer and DoumentView constructors. this.activate(); this.layers = []; this.symbols = []; this.activeLayer = new Layer(); }, _needsRedraw: function() { if (this._scope) this._scope._needsRedraw(); }, /** * The currently active path style. All selected items and newly * created items will be styled with this style. * * @type PathStyle * @bean * * @example {@paperscript} * project.currentStyle = { * fillColor: 'red', * strokeColor: 'black', * strokeWidth: 5 * } * * // The following paths will take over all style properties of * // the current style: * var path = new Path.Circle(new Point(75, 50), 30); * var path2 = new Path.Circle(new Point(175, 50), 20); * * @example {@paperscript} * project.currentStyle.fillColor = 'red'; * * // The following path will take over the fill color we just set: * var path = new Path.Circle(new Point(75, 50), 30); * var path2 = new Path.Circle(new Point(175, 50), 20); */ getCurrentStyle: function() { return this._currentStyle; }, setCurrentStyle: function(style) { // TODO: Style selected items with the style: this._currentStyle.initialize(style); }, /** * Activates this project, so all newly created items will be placed * in it. */ activate: function() { if (this._scope) { this._scope.project = this; return true; } return false; }, remove: function() { if (this._scope) { Base.splice(this._scope.projects, null, this._index, 1); this._scope = null; return true; } return false; }, /** * The index of the project in the global projects array. * * @type Number * @bean */ getIndex: function() { return this._index; }, /** * The selected items contained within the project. * * @type Item[] * @bean */ getSelectedItems: function() { // TODO: Return groups if their children are all selected, // and filter out their children from the list. // TODO: The order of these items should be that of their // drawing order. var items = []; Base.each(this._selectedItems, function(item) { items.push(item); }); return items; }, // TODO: Implement setSelectedItems? _updateSelection: function(item) { if (item._selected) { this._selectedItemCount++; this._selectedItems[item.getId()] = item; } else { this._selectedItemCount--; delete this._selectedItems[item.getId()]; } }, /** * Selects all items in the project. */ selectAll: function() { for (var i = 0, l = this.layers.length; i < l; i++) this.layers[i].setSelected(true); }, /** * Deselects all selected items in the project. */ deselectAll: function() { for (var i in this._selectedItems) this._selectedItems[i].setSelected(false); }, /** * {@grouptitle Project Hierarchy} * * The layers contained within the project. * * @name Project#layers * @type Layer[] */ /** * The layer which is currently active. New items will be created on this * layer by default. * * @name Project#activeLayer * @type Layer */ /** * The symbols contained within the project. * * @name Project#symbols * @type Symbol[] */ /** * The views contained within the project. * * @name Project#views * @type View[] */ /** * The view which is currently active. * * @name Project#activeView * @type View */ draw: function(ctx) { ctx.save(); var param = { offset: new Point(0, 0) }; for (var i = 0, l = this.layers.length; i < l; i++) Item.draw(this.layers[i], ctx, param); ctx.restore(); // Draw the selection of the selected items in the project: if (this._selectedItemCount > 0) { ctx.save(); ctx.strokeWidth = 1; // TODO: use Layer#color ctx.strokeStyle = ctx.fillStyle = '#009dec'; param = { selection: true }; Base.each(this._selectedItems, function(item) { item.draw(ctx, param); }); ctx.restore(); } } });
JavaScript
0
@@ -2774,16 +2774,41 @@ ex, 1);%0A +%09%09%09this._scope.remove();%0A %09%09%09this.
43dc1df23c4660156ad39675679e89ab0cbfa4dd
Fix an indentation
src/public/js/const.js
src/public/js/const.js
define([], function () { 'use strict'; return { 'tooltip': { 'showDelay': 500, // ms 'hideDelay': 0, // ms }, }; });
JavaScript
0.999961
@@ -67,17 +67,16 @@ : %7B%0A%0A%09%09%09 -%09 'showDel @@ -91,17 +91,16 @@ , // ms%0A -%09 %09%09%09'hide
f583e08bb16b4143372a2499d9f9f341bc9b2dc4
Handle errors in bundle uploads better.
lib/cast-client/commands/bundles/upload.js
lib/cast-client/commands/bundles/upload.js
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var sys = require('sys'); var fs = require('fs'); var path = require('path'); var crypto = require('crypto'); var async = require('async'); var sprintf = require('sprintf').sprintf; var http = require('util/http'); var pumpfile = require('util/http_pumpfile'); var clientConfig = require('util/config'); var dotfiles = require('util/client_dotfiles'); var misc = require('util/misc'); var spinner = require('util/spinner'); var manifest = require('manifest/index'); var MANIFEST_FILENAME = require('manifest/constants').MANIFEST_FILENAME; /** Configuration options for upload subcommand */ var config = { shortDescription: 'Upload an application bundle.', longDescription: 'Upload an application bundle to a remote server.', requiredArguments: [], optionalArguments: [['version', 'The bundle version to upload, defaults to the newest available']], usesGlobalOptions: ['remote'] }; /** * Handler for uploading a bundle. * @param {Object} args Command line arguments. * @param {String} args.version Application version number to create. */ function handleCommand(args) { var cwd = process.cwd(); var manifestPath = path.join(cwd, MANIFEST_FILENAME); var version = args.version; var bundlename; var fpath; var size = 0; var request; async.series([ // Validate the manifest and get the bundle name function(callback) { manifest.validateManifest(manifestPath, function(err, appManifest) { if (!err) { bundlename = misc.getValidBundleName(appManifest.name); } callback(err); return; }); }, function(callback) { // If no version was specified then look up the most recently modified bundle if (!version) { dotfiles.getNewestBundle(cwd, function(err, bundle) { fpath = dotfiles.getBundlePath(cwd, bundle); callback(err); }); } // If a version was specified, make sure it exists else { var fullBundlename = misc.getFullBundleName(bundlename, version); fpath = dotfiles.getBundlePath(cwd, fullBundlename); callback(); } }, // Get the bundles size function(callback) { fs.stat(fpath, function(err, stats) { if (err || !stats.isFile()) { err = new Error('Specified version does not exist.'); } else { size = stats.size; } callback(err); return; }); }, function(callback) { var completed = false; var remotepath = path.join.apply(null, [ '/', '1.0', 'bundles', bundlename, path.basename(fpath) ]); var opts = { method: 'PUT', path: remotepath, headers: { 'trailer': 'x-content-sha1', 'expect': '100-continue' } }; var pbarString = sprintf('Uploading %s (%d bytes)', path.basename(fpath), size); var pbar = spinner.percentbar(pbarString, size); http.buildRequest(args.remote, opts, function(err, request) { function tick(bytes) { pbar.tick(bytes); } // In case of an error server-side we can get a response before the // pump finishes. Because we only want to have a single response // handler, we go ahead and add the handler here in order to catch // things that occur either during or after pumping. request.on('response', function(response) { if (completed) { return; } request.abort(); completed = true; // We *should* get a 204 if (response.statusCode === 204) { callback(); return; } var chunks = []; response.on('data', function(data) { chunks.push(data); }); response.on('end', function() { try { var err = JSON.parse(chunks.join('')); callback(new Error(err.message)); return; } catch (err2) { callback(new Error('Invalid response from agent')); return; } }); }); request.on('error', function(err) { if (!completed) { completed = true; callback(err); } }); function afterPump(err, sha1) { if (completed) { return; } pbar.end(); // Only fire the callback if an error occurred, otherwise we wait for // a response if (err) { completed = true; callback(err); } else { sys.puts('Waiting for response...'); request.addTrailers({'x-content-sha1': sha1.digest('base64')}); request.end(); } } function startPump() { pbar.start(); pumpfile.pumpfileout(fpath, request, tick, afterPump); } request.on('continue', startPump); }); } ], function(err) { if (err) { sys.puts('Error: ' + err.message); } else { sys.puts('Upload Successful'); } }); } exports.config = config; exports.handleCommand = handleCommand;
JavaScript
0
@@ -3825,24 +3825,97 @@ request) %7B%0A + if (err) %7B%0A callback(err);%0A return;%0A %7D%0A%0A func
9a62d2b43823f25474954b5123adfcc468444719
fix tests
test/exceptions/exceptionHandler.spec.js
test/exceptions/exceptionHandler.spec.js
var ServiceFactory = require('../../src/common/serviceFactory') var Config = require('../../src/lib/config') var TransportMock = require('../utils/transportMock') describe('ExceptionHandler', function () { var exceptionHandler var config var opbeatBackend var logger var transport beforeEach(function () { var serviceFactory = new ServiceFactory() config = Object.create(Config) config.init() serviceFactory.services['ConfigService'] = config transport = serviceFactory.services['Transport'] = new TransportMock() exceptionHandler = serviceFactory.getExceptionHandler() logger = serviceFactory.getLogger() }) it('should process errors', function (done) { // in IE 10, Errors are given a stack once they're thrown. config.setConfig({ appId: 'test', orgId: 'test', isInstalled: true }) expect(config.isValid()).toBe(true) spyOn(logger, 'warn').and.callThrough() try { throw new Error('unittest error') } catch (error) { // error['_opbeat_extra_context'] = {test: 'hamid'} error.test = 'hamid' error.aDate = new Date('2017-01-12T00:00:00.000Z') var obj = {test: 'test'} obj.obj = obj error.anObject = obj error.aFunction = function noop () {} error.null = null exceptionHandler.processError(error) .then(function () { expect(logger.warn).not.toHaveBeenCalled() expect(transport.errors.length).toBe(1) var errorData = transport.errors[0] expect(errorData.data.extra.test).toBe('hamid') expect(errorData.data.extra.aDate).toBe('2017-01-12T00:00:00.000Z') // toISOString() expect(errorData.data.extra.anObject).toBeUndefined() expect(errorData.data.extra.aFunction).toBeUndefined() expect(errorData.data.extra.null).toBeUndefined() done() }, function (reason) { fail(reason) }) } }) it('should capture extra data', function () { config.setConfig({ appId: 'test', orgId: 'test', isInstalled: true }) expect(config.isValid()).toBe(true) try { throw new Error('unittest error') } catch (error) { // error['_opbeat_extra_context'] = {test: 'hamid'} error.test = 'hamid' error.aDate = new Date('2017-01-12T00:00:00.000Z') var obj = {test: 'test'} obj.obj = obj error.anObject = obj error.aFunction = function noop () {} error.null = null exceptionHandler.processError(error, {extra: {extraObject: {test: 'test'}}}) .then(function () { expect(logger.warn).not.toHaveBeenCalled() expect(transport.errors.length).toBe(1) var errorData = transport.errors[0] expect(errorData.data.extra.test).toBe('hamid') expect(errorData.data.extra.aDate).toBe('2017-01-12T00:00:00.000Z') // toISOString() expect(errorData.data.extra.anObject).toBeUndefined() expect(errorData.data.extra.aFunction).toBeUndefined() expect(errorData.data.extra.null).toBeUndefined() expect(errorData.data.extra.extraObject).toEqual({test: 'test'}) done() }, function (reason) { fail(reason) }) } }) })
JavaScript
0.002923
@@ -1967,32 +1967,36 @@ ata', function ( +done ) %7B%0A config.s @@ -2572,61 +2572,8 @@ ) %7B%0A - expect(logger.warn).not.toHaveBeenCalled()%0A
8959203bb1e7f51a102106438938de8a44fbdd6b
reset fake port object for every test
test/frontend/addressbook/google_test.js
test/frontend/addressbook/google_test.js
/*global sinon, chai, GoogleContacts */ /* jshint expr:true, camelcase:false */ var expect = chai.expect; describe("GoogleContacts", function() { var sandbox, fakePort, fakeGApi, sampleFeed; function caller(cb) { cb(); } fakePort = { postEvent: sinon.spy() }; fakeGApi = { auth: { init: caller, authorize: function(config, cb) { cb({access_token: "token"}); } } }; sampleFeed = { feed: { entry: [{ "gd$email": [{ address: "[email protected]", primary: "true", rel: "http://schemas.google.com/g/2005#other" }, { address: "[email protected]", "rel": "http://schemas.google.com/g/2005#other" }] }, { "gd$email": [{ address: "[email protected]", primary: "true", rel: "http://schemas.google.com/g/2005#other" }] }, { /* empty record */ }] } }; beforeEach(function() { $.removeCookie("tktest"); sandbox = sinon.sandbox.create(); }); afterEach(function() { delete window.gapi; sandbox.restore(); }); describe("#constructor", function() { it("should construct an object", function() { expect(new GoogleContacts()).to.be.a("object"); }); it("should accept a port option", function() { expect(new GoogleContacts({port: fakePort}).port).eql(fakePort); }); it("should accept a token option", function() { expect(new GoogleContacts({token: "plop"}).token).eql("plop"); }); it("should accept a authCookieName option", function() { expect(new GoogleContacts({ authCookieName: "plop" }).authCookieName).eql("plop"); }); it("should accept a authCookieTTL option", function() { expect(new GoogleContacts({ authCookieTTL: 42 }).authCookieTTL).eql(42); }); it("should retrieve existing token from cookie by default", function() { sandbox.stub($, "cookie", function() { return "ok"; }); expect(new GoogleContacts().token).eql("ok"); }); }); describe("#authorize", function() { it("should pass an error if the google api client is unavailable", function(done) { new GoogleContacts({authCookieName: "tktest"}).authorize(function(err) { expect(err).to.be.an.instanceOf(Error); done(); }); }); it("should request authorization to access user's contact", function(done) { window.gapi = fakeGApi; new GoogleContacts({authCookieName: "tktest"}).authorize(function(err) { // if we reach this point, we know gapi has been used as expected expect(err).to.be.a("null"); done(); }); }); it("should store received authorization token as a property", function(done) { window.gapi = fakeGApi; new GoogleContacts({authCookieName: "tktest"}).authorize(function() { expect(this.token).eql("token"); done(); }); }); it("should store received authorization token in a cookie", function(done) { window.gapi = fakeGApi; sandbox.stub($, "cookie"); new GoogleContacts({ authCookieName: "tktest", authCookieTTL: 42 }).authorize(function() { sinon.assert.calledTwice($.cookie); // first call for reading cookie sinon.assert.calledWithExactly($.cookie, "tktest", "token", { expires: 42 }); done(); }); }); it("should pass back auth errors", function(done) { window.gapi = fakeGApi; fakeGApi.auth.authorize = function(config, cb) { cb({access_token: undefined}); }; var gc = new GoogleContacts(); gc.authorize(function(err) { expect(err).to.match(/missing auth token/); done(); }); }); }); describe("#all", function() { var xhr, request; beforeEach(function() { xhr = sinon.useFakeXMLHttpRequest(); xhr.onCreate = function (xhrRequest) { request = xhrRequest; }; }); afterEach(function() { xhr.restore(); }); it("should pass an error back if auth token isn't set", function(done) { new GoogleContacts({authCookieName: "tktest"}).all(function(err) { expect(err.toString()).to.match(/Missing/); done(); }); }); it("should load, parse and normalize google contacts", function() { var callback = sinon.spy(); new GoogleContacts({token: "foo"}).all(callback); request.respond(200, { "Content-Type": "application/json" }, JSON.stringify(sampleFeed)); sinon.assert.calledOnce(callback); sinon.assert.calledWith(callback, null, [ {username: "[email protected]"}, {username: "[email protected]"}, {username: "[email protected]"} ]); }); it("should pass back encountered an HTTP error", function() { var callback = sinon.spy(); new GoogleContacts({token: "foo"}).all(callback); request.respond(401, { "Content-Type": "application/json" }, JSON.stringify({})); sinon.assert.calledOnce(callback); expect(callback.args[0][0].message).eql("Unauthorized"); }); it("should pass back a feed data normalization error", function() { var callback = sinon.spy(); new GoogleContacts({token: "foo"}).all(callback); request.respond(200, { "Content-Type": "application/json" }, "{malformed}"); sinon.assert.calledOnce(callback); expect(callback.args[0][0].message).to.match(/JSON\.parse/); }); }); describe("#loadContacts", function() { it("should notify port with retrieved list of contacts", function() { var contacts = [{username: "foo"}, {username: "bar"}]; sandbox.stub(GoogleContacts.prototype, "authorize", caller); sandbox.stub(GoogleContacts.prototype, "all", function(cb) { cb(null, contacts); }); new GoogleContacts({port: fakePort}).loadContacts(); sinon.assert.calledOnce(fakePort.postEvent); sinon.assert.calledWithExactly(fakePort.postEvent, "talkilla.contacts", {contacts: contacts}); }); it("should notify port with auth errors", function() { var error = new Error("auth error"); sandbox.stub(GoogleContacts.prototype, "authorize", function(cb) { cb(error); }); new GoogleContacts({port: fakePort}).loadContacts(); sinon.assert.calledWithExactly(fakePort.postEvent, "talkilla.contacts-error", error); }); }); describe("Importer", function() { describe("#constructor", function() { it("should construct an object", function() { expect(new GoogleContacts.Importer()).to.be.an("object"); }); it("should attach data feed", function() { var feed = {}; expect(new GoogleContacts.Importer(feed).dataFeed).eql(feed); }); }); describe("#normalize", function() { it("should normalize data feed", function() { var normalized = new GoogleContacts.Importer(sampleFeed).normalize(); expect(normalized).eql([ {username: "[email protected]"}, {username: "[email protected]"}, {username: "[email protected]"} ]); }); }); }); });
JavaScript
0
@@ -232,56 +232,8 @@ %7D%0A%0A - fakePort = %7B%0A postEvent: sinon.spy()%0A %7D;%0A%0A fa @@ -984,24 +984,79 @@ x.create();%0A + fakePort = %7B%0A postEvent: sandbox.spy()%0A %7D;%0A %7D);%0A%0A aft
6024fd00e7a56fe027a33768b6867fe51337ee53
Use prefixName abstraction in nano.use
NanoProxyDbFunctions.js
NanoProxyDbFunctions.js
var NanoProxyDbFunctions = function(nano, prefix) { this.nano = nano; this.prefix = prefix; }; NanoProxyDbFunctions.prototype.create = function(name, callback) { return this.nano.db.create(prefixName.call(this, name), callback); }; function prefixName(name) { return [this.prefix, name].join("_"); } NanoProxyDbFunctions.prototype.get = function(name, callback) { }; NanoProxyDbFunctions.prototype.destroy = function(name, callback) { }; NanoProxyDbFunctions.prototype.list = function(callback) { }; NanoProxyDbFunctions.prototype.compact = function(name, designname, callback) { }; NanoProxyDbFunctions.prototype.replicate = function(source, target, opts, callback) { }; NanoProxyDbFunctions.prototype.changes = function(name, params, callback) { }; NanoProxyDbFunctions.prototype.follow = function(name, params, callback) { }; NanoProxyDbFunctions.prototype.use = function(name) { return this.nano.use([this.prefix, name].join("_")); }; module.exports = NanoProxyDbFunctions;
JavaScript
0.000004
@@ -970,36 +970,34 @@ use( -%5Bthis.prefix, name%5D.join(%22_%22 +prefixName.call(this, name ));%0D
f220a2390d2f597b83d73e29b714408c2948190b
correct gulp config
gulp/config.js
gulp/config.js
var src = './src'; var dest = './dist'; var demo = './demo'; module.exports = { build: { src: src, deps: './node_modules' dest: dest }, demo: { src: { demo: demo, build: dest }, dest: demo + '/build', watch: [ src + '/**/*', demo + '/!(build)/**/*.*' ], webserver: { livereload: true } }, jshint: { src: src } };
JavaScript
0.000003
@@ -126,16 +126,17 @@ modules' +, %0A des
a6aa664adf985c03312b8b1c3af55f294180a826
Update remote origin for deploy github pages
gulp/config.js
gulp/config.js
module.exports = { // Autoprefixer autoprefixer: { // https://github.com/postcss/autoprefixer#browsers browsers: [ 'Explorer >= 10', 'ExplorerMobile >= 10', 'Firefox >= 30', 'Chrome >= 34', 'Safari >= 7', 'Opera >= 23', 'iOS >= 7', 'Android >= 4.4', 'BlackBerry >= 10' ] }, // BrowserSync browserSync: { browser: 'default', // or ["google chrome", "firefox"] https: false, // Enable https for localhost development. notify: false, // The small pop-over notifications in the browser. port: 9000 }, // GitHub Pages ghPages: { branch: 'gh-pages', domain: 'polymer-starter-kit.startpolymer.org', // change it! origin: 'origin' }, // PageSpeed Insights // Please feel free to use the `nokey` option to try out PageSpeed // Insights as part of your build process. For more frequent use, // we recommend registering for your own API key. For more info: // https://developers.google.com/speed/docs/insights/v1/getting_started pageSpeed: { key: '', // need uncomment in task nokey: true, site: 'http://polymer-starter-kit.startpolymer.org', // change it! strategy: 'mobile' // or desktop } };
JavaScript
0
@@ -716,16 +716,40 @@ origin: + 'origin2' // default is 'origin
97d28e688b0fe58cfd3ba5dd4793c9963b9e1239
Update namespace
lib/node_modules/@stdlib/iter/lib/index.js
lib/node_modules/@stdlib/iter/lib/index.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace ns */ var ns = {}; /** * @name iterAny * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/any} */ setReadOnly( ns, 'iterAny', require( '@stdlib/iter/any' ) ); /** * @name iterAnyBy * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/any-by} */ setReadOnly( ns, 'iterAnyBy', require( '@stdlib/iter/any-by' ) ); /** * @name iterConstant * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/constant} */ setReadOnly( ns, 'iterConstant', require( '@stdlib/iter/constant' ) ); /** * @name iterEmpty * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/empty} */ setReadOnly( ns, 'iterEmpty', require( '@stdlib/iter/empty' ) ); /** * @name iterEvery * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/every} */ setReadOnly( ns, 'iterEvery', require( '@stdlib/iter/every' ) ); /** * @name iterEveryBy * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/every-by} */ setReadOnly( ns, 'iterEveryBy', require( '@stdlib/iter/every-by' ) ); /** * @name iterFirst * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/first} */ setReadOnly( ns, 'iterFirst', require( '@stdlib/iter/first' ) ); /** * @name iterForEach * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/for-each} */ setReadOnly( ns, 'iterForEach', require( '@stdlib/iter/for-each' ) ); /** * @name iterHead * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/head} */ setReadOnly( ns, 'iterHead', require( '@stdlib/iter/head' ) ); /** * @name iterLast * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/last} */ setReadOnly( ns, 'iterLast', require( '@stdlib/iter/last' ) ); /** * @name iterMap * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/map} */ setReadOnly( ns, 'iterMap', require( '@stdlib/iter/map' ) ); /** * @name iterNone * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/none} */ setReadOnly( ns, 'iterNone', require( '@stdlib/iter/none' ) ); /** * @name iterNoneBy * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/none-by} */ setReadOnly( ns, 'iterNoneBy', require( '@stdlib/iter/none-by' ) ); /** * @name iterNth * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/nth} */ setReadOnly( ns, 'iterNth', require( '@stdlib/iter/nth' ) ); /** * @name iterThunk * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/pipeline-thunk} */ setReadOnly( ns, 'iterThunk', require( '@stdlib/iter/pipeline-thunk' ) ); /** * @name iterSlice * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/slice} */ setReadOnly( ns, 'iterSlice', require( '@stdlib/iter/slice' ) ); /** * @name iterSome * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/some} */ setReadOnly( ns, 'iterSome', require( '@stdlib/iter/some' ) ); /** * @name iterSomeBy * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/iter/some-by} */ setReadOnly( ns, 'iterSomeBy', require( '@stdlib/iter/some-by' ) ); // EXPORTS // module.exports = ns;
JavaScript
0.000001
@@ -3399,32 +3399,222 @@ iter/nth' ) );%0A%0A +/**%0A* @name iterPipeline%0A* @memberof ns%0A* @readonly%0A* @type %7BFunction%7D%0A* @see %7B@link module:@stdlib/iter/pipeline%7D%0A*/%0AsetReadOnly( ns, 'iterPipeline', require( '@stdlib/iter/pipeline' ) );%0A%0A /**%0A* @name iter
a52515ea4f52fc7243b3daeebbf99245b267b725
introduce failing test case
test/tests/strings_test.js
test/tests/strings_test.js
import virtualizeString from '../../src/strings'; import h from 'snabbdom/h'; describe("#virtualizeString", () => { it("should convert a single node with no children", () => { expect(virtualizeString("<div />")).to.deep.equal( h('div') ); }); it("should convert nodes with children", () => { expect( virtualizeString("<ul><li>One</li><li>Fish</li><li>Two</li><li>Fish</li></ul>") ).to.deep.equal( h('ul', [ h('li', ['One']), h('li', ['Fish']), h('li', ['Two']), h('li', ['Fish']) ]) ); }); it("should handle attributes on nodes", () => { expect(virtualizeString("<div title='This is it!' data-test-attr='cool' />")) .to.deep.equal( h('div', { attrs: { title: 'This is it!', 'data-test-attr': 'cool' } }) ); }); it("should handle the special style attribute on nodes", () => { expect(virtualizeString("<div title='This is it!' style='display: none' />")).to.deep.equal( h('div', { attrs: { title: 'This is it!' }, style: { display: 'none' } }) ); expect(virtualizeString("<div style='display: none ; z-index: 17; top: 0px;' />")).to.deep.equal( h('div', { style: { display: 'none', zIndex: '17', top: '0px' } }) ); expect(virtualizeString("<div style='' />")).to.deep.equal(h('div')); }); it("should remove !important value from style values", () => { expect(virtualizeString("<div style='display: none !important; z-index: 17' />")).to.deep.equal( h('div', { style: { display: 'none', zIndex: '17' } }) ); }); it("should handle the special class attribute on nodes", () => { expect(virtualizeString("<div class='class1 class2 class3 ' />")).to.deep.equal( h('div', { class: { class1: true, class2: true, class3: true } }) ); expect(virtualizeString("<div class='class1' />")).to.deep.equal( h('div', { class: { class1: true } }) ); expect(virtualizeString("<div class='' />")).to.deep.equal(h('div')); }); it("should handle comments in HTML strings", () => { expect( virtualizeString('<div> <!-- First comment --> <span>Hi</span> <!-- Another comment --> Something</div>') ).to.deep.equal( h('div', [ h('span', ['Hi']), ' Something' ]) ); }); it("should decode HTML entities, since VNodes just deal with text content", () => { expect(virtualizeString("<div>&amp; is an ampersand! and &frac12; is 1/2!</div>")).to.deep.equal( h('div', [ '& is an ampersand! and ½ is 1/2!' ]) ); expect(virtualizeString("<a href='http://example.com?test=true&amp;something=false'>Test</a>")).to.deep.equal( h('a', { attrs: { href: 'http://example.com?test=true&something=false' } },[ 'Test' ]) ); }); it("should call the 'create' hook for each VNode that was created after the virtualization process is complete", () => { const createSpy = sinon.spy(); const vnodes = virtualizeString("<ul><li>One</li><li>Fish</li><li>Two</li><li>Fish</li></ul><p>Red Fish, Blue Fish</p>", { hooks: { create: createSpy } }); // Helper to check that the create hook was called once for each created // vnode. function checkVNode(vnode) { expect(createSpy).to.have.been.calledWithExactly(vnode); if (vnode.children) { vnode.children.forEach((cvnode) => { checkVNode(cvnode); }); } } expect(createSpy).to.have.callCount(11); vnodes.forEach(checkVNode); }); });
JavaScript
0.000003
@@ -1029,32 +1029,511 @@ );%0A %7D);%0A%0A + it(%22should handle control characters in attribute values%22, () =%3E %7B%0A const input = %22%3Ctextarea placeholder='Hey Usher, %5Cn%5CnAre these modals for real?!' class='placeholder-value'%3E%3C/textarea%3E%22;%0A expect(virtualizeString(input)).to.deep.equal(h('textarea', %7B%0A attrs: %7B%0A placeholder: 'Hey Usher, %5Cn%5CnAre these modals for real?!'%0A %7D,%0A class: %7B%0A 'placeholder-value': true%0A %7D%0A %7D))%0A %7D);%0A%0A it(%22should h
5da3221b53aba88bab50e52c903d3cf355696db1
Add test for entities in attributes.
test/tests/strings_test.js
test/tests/strings_test.js
import virtualizeString from '../../src/strings'; import h from 'snabbdom/h'; describe("#virtualizeString", () => { it("should convert a single node with no children", () => { expect(virtualizeString("<div />")).to.deep.equal( h('div') ); }); it("should convert nodes with children", () => { expect( virtualizeString("<ul><li>One</li><li>Fish</li><li>Two</li><li>Fish</li></ul>") ).to.deep.equal( h('ul', [ h('li', ['One']), h('li', ['Fish']), h('li', ['Two']), h('li', ['Fish']) ]) ); }); it("should handle attributes on nodes", () => { expect(virtualizeString("<div title='This is it!' data-test-attr='cool' />")) .to.deep.equal( h('div', { attrs: { title: 'This is it!', 'data-test-attr': 'cool' } }) ); }); it("should handle the special style attribute on nodes", () => { expect(virtualizeString("<div title='This is it!' style='display: none' />")).to.deep.equal( h('div', { attrs: { title: 'This is it!' }, style: { display: 'none' } }) ); expect(virtualizeString("<div style='display: none ; z-index: 17; top: 0px;' />")).to.deep.equal( h('div', { style: { display: 'none', zIndex: '17', top: '0px' } }) ); expect(virtualizeString("<div style='' />")).to.deep.equal(h('div')); }); it("should remove !important value from style values", () => { expect(virtualizeString("<div style='display: none !important; z-index: 17' />")).to.deep.equal( h('div', { style: { display: 'none', zIndex: '17' } }) ); }); it("should handle the special class attribute on nodes", () => { expect(virtualizeString("<div class='class1 class2 class3 ' />")).to.deep.equal( h('div', { class: { class1: true, class2: true, class3: true } }) ); expect(virtualizeString("<div class='class1' />")).to.deep.equal( h('div', { class: { class1: true } }) ); expect(virtualizeString("<div class='' />")).to.deep.equal(h('div')); }); it("should handle comments in HTML strings", () => { expect( virtualizeString('<div> <!-- First comment --> <span>Hi</span> <!-- Another comment --> Something</div>') ).to.deep.equal( h('div', [ h('span', ['Hi']), ' Something' ]) ); }); it("should decode HTML entities, since VNodes just deal with text content", () => { expect(virtualizeString("<div>&amp; is an ampersand! and &frac12; is 1/2!</div>")).to.deep.equal( h('div', [ '& is an ampersand! and ½ is 1/2!' ]) ); }); it("should call the 'create' hook for each VNode that was created after the virtualization process is complete", () => { const createSpy = sinon.spy(); const vnodes = virtualizeString("<ul><li>One</li><li>Fish</li><li>Two</li><li>Fish</li></ul><p>Red Fish, Blue Fish</p>", { hooks: { create: createSpy } }); // Helper to check that the create hook was called once for each created // vnode. function checkVNode(vnode) { expect(createSpy).to.have.been.calledWithExactly(vnode); if (vnode.children) { vnode.children.forEach((cvnode) => { checkVNode(cvnode); }); } } expect(createSpy).to.have.callCount(11); vnodes.forEach(checkVNode); }); });
JavaScript
0
@@ -3387,32 +3387,353 @@ ' %5D)%0A );%0A + expect(virtualizeString(%22%3Ca href='http://example.com?test=true&amp;something=false'%3ETest%3C/a%3E%22)).to.deep.equal(%0A h('a', %7B%0A attrs: %7B%0A href: 'http://example.com?test=true&something=false'%0A %7D%0A %7D,%5B%0A 'Test'%0A %5D)%0A );%0A %7D);%0A%0A it(
186b42b08e8b73da19ba639da265b30b2df9f87d
Update test name
test/unformat-usd-tests.js
test/unformat-usd-tests.js
var unFormatUSD = require('../index.js'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.formatUSD = { setUp: function(done) { // setup here done(); }, 'Strip dollar sign': function(test) { test.strictEqual( unFormatUSD('$123'), 123 ); test.strictEqual( unFormatUSD('$123.4'), 123.4 ); test.strictEqual( unFormatUSD('$123.45'), 123.45 ); test.strictEqual( unFormatUSD('$123.456'), 123.456 ); test.done(); }, 'Deal with extraneous characters': function(test) { test.strictEqual( unFormatUSD('$%123'), 123 ); test.strictEqual( unFormatUSD('123.45.67'), 123.45 ); test.strictEqual( unFormatUSD('79aaasdfa69s89'), 796989 ); test.done(); }, 'Ignore non-parseable strings': function(test) { var obj = {"foo":"bar"}, func = function(a){return a}; test.strictEqual( unFormatUSD('blah'), 'blah' ); test.strictEqual( unFormatUSD(obj), obj ); test.strictEqual( unFormatUSD(func), func ); test.strictEqual( unFormatUSD(Date), Date ); test.done(); } };
JavaScript
0.000002
@@ -664,17 +664,19 @@ exports. -f +unF ormatUSD
f8a8de937465426633b56e4c5b209cc4282a9e73
Rename cesium compinent to hscesium in common_paths for browserify
common_paths.js
common_paths.js
exports.paths = [ __dirname + '/components/toolbar', __dirname + '/node_modules', __dirname + '/node_modules/openlayers/dist', __dirname + '/node_modules/requirejs', __dirname + '/node_modules/cesium/Build/Cesium', __dirname + '/node_modules/angular-cookies/angular-cookies', __dirname + '/node_modules/angular-socialshare/dist/angular-socialshare', __dirname + '/node_modules/angular-material', __dirname + '/node_modules/angular-gettext/dist/angular-gettext', __dirname + '/node_modules/angular-drag-and-drop-lists/angular-drag-and-drop-lists', __dirname + '/components/api', __dirname + '/node_modules/angular-material-bottom-sheet-collapsible', __dirname + '/components/cesium', __dirname + '/components/compositions', __dirname + '/components/core', __dirname + '/components/customhtml', __dirname + '/components/datasource_selector', __dirname + '/components/drag', __dirname + '/components/draw', __dirname + '/components/feature_crossfilter', __dirname + '/components/floating_action_button', __dirname + '/components/format', __dirname + '/components/geolocation', __dirname + '/components/info', __dirname + '/components/layermanager', __dirname + '/components/layers', __dirname + '/components/layout', __dirname + '/components/legend', __dirname + '/components/lodexplorer', __dirname + '/components/map', __dirname + '/components/utils', __dirname + '/components/measure', __dirname + '/components/mobile_settings', __dirname + '/components/mobile_toolbar', __dirname + '/components/ows', __dirname + '/components/permalink', __dirname + '/components/print', __dirname + '/components/query', __dirname + '/components/routing', __dirname + '/components/rtserver', __dirname + '/components/search', __dirname + '/components/sidebar', __dirname + '/components/status_creator', __dirname + '/components/styles', __dirname + '/components/tracking', __dirname + '/components/translations/js', __dirname + '/components/trip_planner', __dirname + '/components/wirecloud' ];
JavaScript
0.000236
@@ -719,16 +719,18 @@ ponents/ +hs cesium',
e993d5497fd86cdee28ddb5258ce5004fa4c23c4
Add labelStyle support to native Buttons
shared/common-adapters/button.native.js
shared/common-adapters/button.native.js
/* @flow */ import React, {Component} from 'react' import {TouchableHighlight, View} from 'react-native' import {globalColors, globalStyles} from '../styles/style-guide' import Text from './text' import ProgressIndicator from './progress-indicator' import type {Props} from './button' const Progress = () => ( <View style={{...progress}}> <ProgressIndicator /> </View> ) class Button extends Component { props: Props; render () { let style = { Primary, Secondary, Danger, Follow, Following, Unfollow }[this.props.type] if (this.props.fullWidth) { style = {...style, ...fullWidth} } if (this.props.disabled || this.props.waiting) { style = {...style, ...disabled[this.props.type]} } const labelStyle = { PrimaryLabel, SecondaryLabel, DangerLabel, FollowLabel, FollowingLabel, UnfollowLabel }[this.props.type + 'Label'] const onPress = (!this.props.disabled && !this.props.waiting && this.props.onClick) || null // Need this nested view to get around this RN issue: https://github.com/facebook/react-native/issues/1040 return ( <TouchableHighlight disabled={!onPress} onPress={onPress || (() => {})} activeOpacity={0.2} underlayColor={style.backgroundColor} style={{...style, ...this.props.style}}> <View style={{alignItems: 'center', justifyContent: 'center'}}> <Text type='BodySemibold' style={labelStyle}>{this.props.label}</Text> {this.props.waiting && <Progress />} </View> </TouchableHighlight> ) } } const regularHeight = 40 const fullWidthHeight = 48 const common = { ...globalStyles.flexBoxColumn, alignItems: 'center', justifyContent: 'center', height: regularHeight, borderRadius: 50, paddingLeft: 32, paddingRight: 32 } const commonLabel = { color: globalColors.white, textAlign: 'center' } const fullWidth = { height: fullWidthHeight, width: null } const disabled = { Primary: {opacity: 0.2}, Secondary: {opacity: 0.3}, Danger: {opacity: 0.2}, Follow: {opacity: 0.3}, Following: {opacity: 0.3}, Unfollow: {opacity: 0.3} } const Primary = { ...common, backgroundColor: globalColors.blue } const PrimaryLabel = { ...commonLabel } const Secondary = { ...common, backgroundColor: globalColors.lightGrey2 } const SecondaryLabel = { ...commonLabel, color: globalColors.black_75 } const Danger = { ...common, backgroundColor: globalColors.red } const DangerLabel = { ...commonLabel } const followCommon = { width: 154, paddingLeft: 32, paddingRight: 32 } const Follow = { ...common, ...followCommon, backgroundColor: globalColors.green } const FollowLabel = { ...commonLabel } const Following = { ...common, ...followCommon, backgroundColor: globalColors.white, borderColor: globalColors.green, paddingTop: 5, borderWidth: 2 } const FollowingLabel = { ...commonLabel, color: globalColors.green } const Unfollow = { ...common, ...followCommon, backgroundColor: globalColors.blue } const UnfollowLabel = { ...commonLabel } const progress = { marginTop: -regularHeight / 2 } export default Button
JavaScript
0
@@ -1501,16 +1501,20 @@ style=%7B +%7B... labelSty @@ -1515,16 +1515,43 @@ belStyle +, ...this.props.labelStyle%7D %7D%3E%7Bthis.
fc07b9e372be447cc894d5f0ea5a7c6e5220cd01
reset theme on logout
ui/src/store/modules/user.js
ui/src/store/modules/user.js
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. import Vue from 'vue' import md5 from 'md5' import { login, logout, api } from '@/api' import { ACCESS_TOKEN, CURRENT_PROJECT, ASYNC_JOB_IDS } from '@/store/mutation-types' import { welcome } from '@/utils/util' const user = { state: { token: '', name: '', welcome: '', avatar: '', info: {}, apis: {}, project: {}, asyncJobIds: [] }, mutations: { SET_TOKEN: (state, token) => { state.token = token }, SET_PROJECT: (state, project) => { Vue.ls.set(CURRENT_PROJECT, project) state.project = project }, SET_NAME: (state, { name, welcome }) => { state.name = name state.welcome = welcome }, SET_AVATAR: (state, avatar) => { state.avatar = avatar }, SET_INFO: (state, info) => { state.info = info }, SET_APIS: (state, apis) => { state.apis = apis }, SET_ASYNC_JOB_IDS: (state, jobsJsonArray) => { Vue.ls.set(ASYNC_JOB_IDS, jobsJsonArray) state.asyncJobIds = jobsJsonArray } }, actions: { SetProject ({ commit }, project) { commit('SET_PROJECT', project) }, Login ({ commit }, userInfo) { return new Promise((resolve, reject) => { login(userInfo).then(response => { const result = response.loginresponse Vue.ls.set(ACCESS_TOKEN, result.sessionkey, 60 * 60 * 1000) commit('SET_TOKEN', result.sessionkey) commit('SET_PROJECT', {}) commit('SET_ASYNC_JOB_IDS', []) resolve() }).catch(error => { reject(error) }) }) }, GetInfo ({ commit }) { return new Promise((resolve, reject) => { // Discover allowed APIs api('listApis').then(response => { const apis = {} const apiList = response.listapisresponse.api for (var idx = 0; idx < apiList.length; idx++) { const api = apiList[idx] const apiName = api.name apis[apiName] = { params: api.params, response: api.response } } commit('SET_APIS', apis) resolve(apis) }).catch(error => { reject(error) }) // Find user info api('listUsers').then(response => { const result = response.listusersresponse.user[0] commit('SET_INFO', result) commit('SET_NAME', { name: result.firstname + ' ' + result.lastname, welcome: welcome() }) if ('email' in result) { commit('SET_AVATAR', 'https://www.gravatar.com/avatar/' + md5(result.email)) } else { commit('SET_AVATAR', 'https://www.gravatar.com/avatar/' + md5('[email protected]')) } }).catch(error => { reject(error) }) }) }, Logout ({ commit, state }) { return new Promise((resolve) => { commit('SET_TOKEN', '') commit('SET_PROJECT', {}) commit('SET_APIS', {}) Vue.ls.remove(CURRENT_PROJECT) Vue.ls.remove(ACCESS_TOKEN) Vue.ls.remove(ASYNC_JOB_IDS) logout(state.token).then(() => { resolve() }).catch(() => { resolve() }) }) }, AddAsyncJob ({ commit }, jobJson) { var jobsArray = Vue.ls.get(ASYNC_JOB_IDS, []) jobsArray.push(jobJson) commit('SET_ASYNC_JOB_IDS', jobsArray) } } } export default user
JavaScript
0
@@ -921,16 +921,31 @@ PROJECT, + DEFAULT_THEME, ASYNC_J @@ -1829,16 +1829,94 @@ onArray%0A + %7D,%0A RESET_THEME: (state) =%3E %7B%0A Vue.ls.set(DEFAULT_THEME, 'light')%0A %7D%0A @@ -3876,24 +3876,54 @@ _APIS', %7B%7D)%0A + commit('RESET_THEME')%0A Vue.
ed46ac1d268437cf576208889b1b91675373b617
Print version link
gui/all.js
gui/all.js
'use strict'; (function (document, window) { document.addEventListener('DOMContentLoaded', function () { // Multi-checkbox required fix const form = document.getElementsByTagName('form'); for (let a = 0; a < form.length; a++) { let sel = 'input[type=checkbox][multiple]'; let multi = form[a].querySelectorAll(sel + '[required]'); for (let b = 0; b < multi.length; b++) { multi[b].addEventListener('change', function () { let req = !!this.form.querySelector(sel + '[name="' + this.name + '"]:checked'); let sib = this.form.querySelectorAll(sel + '[name="' + this.name + '"]'); for (let c = 0; c < sib.length; c++) { if (req) { sib[c].removeAttribute('required'); } else { sib[c].setAttribute('required', 'required'); } } }); } } // Details const details = document.getElementsByTagName('details'); if (details.length > 0) { if (typeof details[0].open === 'boolean') { const before = function () { for (let a = 0; a < details.length; a++) { details[a].setAttribute('open', ''); } }; const after = function () { for (let a = 0; a < details.length; a++) { details[a].removeAttribute('open'); } }; const mql = window.matchMedia('print'); mql.addListener(function (media) { if (media.matches) { before(); } else { after(); } }); window.addEventListener('beforeprint', before); window.addEventListener('afterprint', after); } else { document.documentElement.setAttribute('data-shim-details', 'true'); for (let a = 0; a < details.length; a++) { // Define open property Object.defineProperty(details[a], 'open', { get: function () { return this.hasAttribute('open'); }, set: function (state) { if (state) { this.setAttribute('open', ''); } else { this.removeAttribute('open'); } } }); // Summary element let summary = details[a].firstChild; if (!summary || summary.tagName.toLowerCase() !== 'summary') { summary = document.createElement('summary'); summary.innerText = 'Summary'; details[a].insertBefore(summary, details[a].firstChild); } summary.addEventListener('click', function () { this.parentNode.open = !this.parentNode.hasAttribute('open'); }); // Wrap text nodes let b = 0; let child; while (child = details[a].childNodes[b++]) { if (child.nodeType === 3 && /[^\t\n\r ]/.test(child.data)) { let span = document.createElement('span'); details[a].insertBefore(span, child); span.textContent = child.data; details[a].removeChild(child); } } } } } }); window.addEventListener('load', function () { // Sticky navigation polyfill const nav = document.getElementById('menu'); if (!!nav && window.getComputedStyle(nav).getPropertyValue('position') !== 'sticky') { setTimeout(function() { const pos = nav.offsetTop; const width = window.getComputedStyle(nav.parentElement).getPropertyValue('width'); window.addEventListener('scroll', function () { if (window.pageYOffset >= pos) { nav.setAttribute('data-sticky', ''); nav.style.width = width; } else { nav.removeAttribute('data-sticky'); nav.removeAttribute('style'); } }); }); } }); })(document, window);
JavaScript
0
@@ -1042,32 +1042,300 @@ %7D%0A %7D%0A%0A + // Print version%0A const print = document.querySelectorAll('span%5Bdata-act=print%5D');%0A%0A for (let a = 0; a %3C print.length; a++) %7B%0A print%5Ba%5D.addEventListener('click', function () %7B%0A window.print();%0A %7D);%0A %7D%0A%0A // Detai
207f59912d811e3f6db873c54f6e677eb4b6220b
Convert js watcher to browserify-only (backend will use nodemon that has its own separate watcher anyway)
gulp/js.js
gulp/js.js
var browserify = require('browserify'), browserSync = require('browser-sync'), buffer = require('vinyl-buffer'), source = require('vinyl-source-stream'), extend = require('util-extend'), watchify = require('watchify'); module.exports = function(gulp, plugins) { var paths = { 'watch': [ // js files to watch for changes 'assets/scripts/**/*.js' ], 'lint': [ // js files to lint (ignore vendor) 'gulp/*.js', 'assets/scripts/**/*.js', '!assets/scripts/vendor/**/*' ], 'build': [ // js files to build './assets/scripts/index.js' ], // destination folder 'output': 'build/js' }; var bundler = browserify(paths.build, extend(watchify.args, { // browserify options 'extensions': ['.jsx'], 'debug': true, 'fullPaths': true, 'insertGlobals': true, 'transform': ['brfs', 'bulkify'] })); var bundle = function() { bundler.bundle() .on('error', plugins.notify.onError(function(err) { return err.message + ' in ' + err.fileName + ' at line ' + err.lineNumber; })) .pipe(source('bundle.js')) .pipe(buffer()) .pipe(plugins.sourcemaps.init({'loadMaps': true})) .pipe(plugins.uglify()) .pipe(plugins.sourcemaps.write('.')) .pipe(gulp.dest(paths.output)) .pipe(browserSync.reload({'stream': true})) .pipe(plugins.notify({'message': 'JS compilation complete', 'onLast': true})); }; gulp.task('build:js', 'bundles all client-side javascript files into the build folder via ' + 'browserify', bundle); gulp.task('watch:js:browserify', 'waits for client-side javascript files to change, then ' + 'rebuilds them', function() { watchify(bundler).on('update', bundle); return bundle(); }); // gulp.task('watch:js:serve', 'waits for server-side javascript files to change, then ' + // 'restarts the development server', function() { // }); gulp.task('watch:js', 'waits for both server-side and client-side javascript files to ' + 'change, then redeploys them', [ // 'watch:js:serve', 'watch:js:browserify' ]); gulp.task('lint:js', 'lints all non-vendor js files against .jshintrc and ' + '.jscsrc', function() { return gulp .src(paths.lint) .pipe(plugins.jshint()) .pipe(plugins.jscs()) .on('error', function() {}) .pipe(plugins.jscsStylish.combineWithHintResults()) .pipe(plugins.jshint.reporter('jshint-stylish')) .pipe(plugins.jshint.reporter('fail')); }); };
JavaScript
0.000001
@@ -1831,27 +1831,16 @@ watch:js -:browserify ', 'wait @@ -1890,29 +1890,29 @@ e, then -' +%0A +rebuilds ' +%0A @@ -1933,20 +1933,9 @@ - 'rebuilds +' them @@ -2038,422 +2038,8 @@ ;%0A%0A%0A - // gulp.task('watch:js:serve', 'waits for server-side javascript files to change, then ' +%0A // 'restarts the development server', function() %7B%0A // %7D);%0A%0A%0A gulp.task('watch:js', 'waits for both server-side and client-side javascript files to ' +%0A 'change, then redeploys them', %5B%0A // 'watch:js:serve',%0A 'watch:js:browserify'%0A %5D);%0A%0A%0A
4435408cdc5d38f9df4f012dde56306aafa5ea8a
Revert "Add mode"
src/redux/navigation.js
src/redux/navigation.js
const keyMirror = require('keymirror'); const Types = keyMirror({ SET_MODE: null, SET_SEARCH_TERM: null }); module.exports.navigationReducer = (state, action) => { if (typeof state === 'undefined') { state = ''; } switch (action.type) { case Types.SET_MODE: return action.mode; case Types.SET_SEARCH_TERM: return action.searchTerm; default: return state; } }; module.exports.setMode = mode => ({ type: Types.SET_MODE, mode: mode }); module.exports.setSearchTerm = searchTerm => ({ type: Types.SET_SEARCH_TERM, searchTerm: searchTerm });
JavaScript
0
@@ -64,28 +64,8 @@ r(%7B%0A - SET_MODE: null,%0A @@ -86,16 +86,16 @@ M: null%0A + %7D);%0A%0Amod @@ -244,61 +244,8 @@ ) %7B%0A - case Types.SET_MODE:%0A return action.mode;%0A @@ -351,94 +351,12 @@ %7D%0A + %7D;%0A%0A -module.exports.setMode = mode =%3E (%7B%0A type: Types.SET_MODE,%0A mode: mode%0A%7D);%0A%0A modu
dca6f1979dcd78773f75891c8b0345ba8440dc34
add experimental support for WebSockets to SimpleRestService
src/rest/hooks/index.js
src/rest/hooks/index.js
'use strict'; const hooks = require('feathers-hooks'); exports.before = { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] }; exports.after = { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] };
JavaScript
0
@@ -51,16 +51,463 @@ oks');%0A%0A +/*%0Awebsockets requires passing in path vars on the query%0A* so we move them off the query into the params%0A* this might%0A* */%0Aconst socketfix = (hook)=%3E%7B%0A if(hook.params.provider === 'socketio')%7B%0A%0A if(hook.params.query._db)%7B%0A hook.params%5B'_db'%5D=hook.params.query._db;%0A delete hook.params.query._db%0A %7D%0A%0A if(hook.params.query._lay)%7B%0A hook.params%5B'_lay'%5D=hook.params.query._lay;%0A delete hook.params.query._lay%0A %7D%0A %7D%0A%7D;%0A %0Aexports @@ -518,32 +518,41 @@ ore = %7B%0A all: %5B +socketfix %5D,%0A find: %5B%5D,%0A
9039f9f0aeedbe0f1a1dab2aa93f6840e12af71f
improve stability of andThen()
src/result.andThen.c.js
src/result.andThen.c.js
'use strict'; const H = require('../interface/result.h').prototype; const sym = require('../interface/result-sym.h'); H.andThen = function ($resultEmitter) { if (this[sym.isOk]) { this[sym.value] = $resultEmitter(this[sym.value]); } return this; };
JavaScript
0.000002
@@ -14,17 +14,17 @@ %0A%0Aconst -H +h = requi @@ -50,16 +50,34 @@ sult.h') +;%0Aconst hProto = h .prototy @@ -136,9 +136,14 @@ ;%0A%0A%0A -H +hProto .and @@ -185,12 +185,15 @@ -if ( +return this @@ -202,19 +202,16 @@ ym.isOk%5D -) %7B %0A @@ -215,26 +215,20 @@ -this%5Bsym.value%5D = +? h.fromTry( $res @@ -258,32 +258,29 @@ ue%5D) -; +) %0A -%7D%0A%0A -return this +: this%0A ;%0A%7D;
77c483780744a602696ad198e0908032542438ad
fix to unwrap parens at the repl
src/sc/node-cli/repl.js
src/sc/node-cli/repl.js
"use strict"; var nodeREPL = require("repl"); var vm = require("vm"); var SCScript = require("./scscript"); function isSCObject(obj) { return obj && typeof obj._ !== "undefined"; } function toString(obj) { if (isSCObject(obj)) { return obj.toString(); } return obj; } var replOptions = { prompt: "scsc> ", eval: function(input, context, filename, callback) { try { var js = SCScript.compile(input, { loc: true, range: true }); var result; if (context === global) { result = vm.runInThisContext(js, filename); } else { result = vm.runInContext(js, context, filename); } callback(null, toString(result.valueOf())); } catch (err) { callback(err); } } }; function countCodeDepth(code) { var tokens = SCScript.tokenize(code).filter(function(token) { return token.type === "Punctuator"; }); var depth = 0; for (var i = 0, imax = tokens.length; i < imax; ++i) { if ([ "(", "{", "[" ].indexOf(tokens[i].value) !== -1) { depth += 1; } if ([ "]", "}", ")" ].indexOf(tokens[i].value) !== -1) { depth -= 1; } if (depth < 0) { return -1; } } return depth; } function addMultilineHandler(repl) { var rli = repl.rli; var buffer = ""; var nodeLineListener = rli.listeners("line")[0]; rli.removeListener("line", nodeLineListener); rli.on("line", function(line) { buffer += line; var depth = countCodeDepth(buffer); if (depth === 0) { rli.setPrompt(replOptions.prompt); nodeLineListener(buffer); buffer = ""; return; } if (depth > 0) { rli.setPrompt("... "); return rli.prompt(true); } buffer = ""; rli.setPrompt(replOptions.prompt); return rli.prompt(true); }); } module.exports = { start: function() { var repl = nodeREPL.start(replOptions); repl.on("exit", function() { repl.outputStream.write("\n"); }); addMultilineHandler(repl); } };
JavaScript
0
@@ -368,24 +368,189 @@ callback) %7B%0A + // Node's REPL sends the input ending with a newline and then wrapped in%0A // parens. Unwrap all that.%0A input = input.replace(/%5E%5C((%5B%5Cs%5CS%5D*)%5Cn%5C)$/m, %22$1%22);%0A%0A try %7B%0A
91e08d2ff75b26beb5abf5a4ec8503e8fe0372e2
update backgroundTexture on before render
src/scenes/vgl-scene.js
src/scenes/vgl-scene.js
import { Scene } from 'three'; import VglObject3d from '../core/vgl-object3d'; import { parseFog, parseColor } from '../parsers'; import { string, fog } from '../validators'; /** * This is where you place objects, * corresponding [THREE.Scene](https://threejs.org/docs/index.html#api/scenes/Scene). * * Properties of [VglObject3d](vgl-object3d) are also available as mixin. */ export default { mixins: [VglObject3d], props: { /** the color, near and far parameters of the scene's fog */ fog: { type: fog, }, /** * Expecting to accept a string representing a color. * Will be overwrited by backgroundTexture prop if both props are set */ backgroundColor: string, /** Expecting to accept a string representing a texture name. */ backgroundTexture: string, }, computed: { inst: () => new Scene(), }, watch: { inst: { handler(inst) { this.vglNamespace.scenes[this.name] = inst; if (this.fog) this.inst.fog = parseFog(this.fog); if (this.backgroundColor) this.inst.background = parseColor(this.backgroundColor); if (this.backgroundTexture) { this.inst.background = this.vglNamespace.textures[this.backgroundTexture] || null; } }, immediate: true, }, name(name, oldName) { const { vglNamespace: { scenes }, inst } = this; if (scenes[oldName] === inst) delete scenes[oldName]; scenes[name] = inst; }, fog(newFog) { this.inst.fog = parseFog(newFog); }, backgroundColor(color) { this.inst.background = parseColor(color); }, backgroundTexture(name) { this.inst.background = this.vglNamespace.textures[name] || null; }, }, beforeDestroy() { const { vglNamespace: { scenes }, inst } = this; if (scenes[this.name] === inst) delete scenes[this.name]; }, };
JavaScript
0
@@ -859,16 +859,376 @@ ),%0A %7D,%0A + methods: %7B%0A setBackgroundTexture() %7B%0A const %7B vglNamespace: %7B textures %7D, inst, backgroundTexture %7D = this;%0A if (backgroundTexture in textures) inst.background = textures%5BbackgroundTexture%5D;%0A %7D,%0A %7D,%0A created() %7B%0A const %7B vglNamespace: %7B beforeRender %7D, setBackgroundTexture %7D = this;%0A beforeRender.unshift(setBackgroundTexture);%0A %7D,%0A watch: @@ -2132,32 +2132,68 @@ ce: %7B scenes - %7D, inst +, beforeRender %7D, inst, setBackgroundTexture %7D = this;%0A @@ -2253,16 +2253,88 @@ .name%5D;%0A + beforeRender.splice(beforeRender.indexOf(setBackgroundTexture), 1);%0A %7D,%0A%7D;%0A
4b812dd917fd825f101705a6335adc15454678a1
Remove log
src/scripts/prettify.js
src/scripts/prettify.js
;(() => { 'use strict' const entityMapObject = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '/': '&#x2F;', } const $codeSnippets = document.querySelectorAll('.code-content') for (let index = 0; index < $codeSnippets.length; index++) { console.log($codeSnippets[index].parentNode.classList.contains('lang-html'), $codeSnippets[index].parentNode) if ($codeSnippets[index].parentNode.classList.contains('lang-html')) $codeSnippets[index].innerHTML = changeCommet($codeSnippets[index].innerHTML) $codeSnippets[index].innerHTML = escapeHTML($codeSnippets[index].innerHTML) } function escapeHTML (string) { return String(string) .replace(/[&<>"']/g, caracter => entityMapObject[caracter]) } function changeCommet (string) { return String(string) .replace(/\/\*/g, '<!--') .replace(/\*\//g, '-->') } })()
JavaScript
0.000001
@@ -295,122 +295,8 @@ ) %7B%0A - console.log($codeSnippets%5Bindex%5D.parentNode.classList.contains('lang-html'), $codeSnippets%5Bindex%5D.parentNode)%0A
e44d89d3eda9410857e7ecf9ed603e19dabec7d8
Fix localisation plugin sourcemaps
tooling/rollup/rollup-plugin-localise.js
tooling/rollup/rollup-plugin-localise.js
import { createFilter } from '@rollup/pluginutils'; import parseDb from '../i18n/parse-db.js'; import { readFileSync } from 'fs'; const isId = /^[A-Z0-9_]+$/; const enumerateStrings = function (code, idsInUse, db) { const locRegex = /\bloc\(\s*['"`]([A-Z0-9_]+)['"`]/g; return code.replace(locRegex, (_, id) => { if (!isId.test(id)) { const entry = db.find(({ string }) => id === string); if (!entry) { throw new Error('String not in en.db: ' + id); } id = entry.id; } let index = idsInUse.indexOf(id); if (index === -1) { index = idsInUse.length; idsInUse.push(id); } return 'loc(' + index; }); }; export default function localise(options) { const idsInUse = options.idsInUse; const data = readFileSync(options.enDbPath, 'utf-8'); const db = parseDb(data); const filter = createFilter(options.include, options.exclude); return { transform(code, id) { if (!filter(id)) { return; } return { code: enumerateStrings(code, idsInUse, db), map: { mappings: '' }, }; }, }; }
JavaScript
0
@@ -1,16 +1,60 @@ +import parseDb from '../i18n/parse-db.js';%0A%0A import %7B createF @@ -100,76 +100,73 @@ ort -parseDb from '../i18n/parse-db.js';%0Aimport %7B readFileSync %7D from 'fs +%7B readFileSync %7D from 'fs';%0Aimport MagicString from 'magic-string ';%0A%0A @@ -230,16 +230,22 @@ nction ( +file, code, id @@ -324,50 +324,124 @@ -return code.replace(locRegex, (_, +const source = new MagicString(code);%0A%0A for (const match of code.matchAll(locRegex)) %7B%0A let id -) = -%3E %7B + match%5B1%5D; %0A @@ -821,24 +821,25 @@ %7D%0A +%0A return ' @@ -830,22 +830,124 @@ -return +const start = match.index;%0A const end = start + match%5B0%5D.length;%0A source.overwrite(start, end, 'loc(' @@ -957,16 +957,159 @@ ndex +) ;%0A %7D -) +%0A%0A const map = source.generateMap(%7B%0A source: file,%0A includeContent: true,%0A %7D);%0A%0A return %7B code: source.toString(), map %7D ;%0A%7D; @@ -1482,32 +1482,8 @@ turn - %7B%0A code: enu @@ -1496,16 +1496,20 @@ Strings( +id, code, id @@ -1523,62 +1523,8 @@ db) -,%0A map: %7B mappings: '' %7D,%0A %7D ;%0A
264aad1cf7259975ca2a1b1043f28ebc5620ae45
Fix Ember.merge/assign deprecation warnings
tests/helpers/start-app.js
tests/helpers/start-app.js
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; export default function startApp(attrs) { let application; let attributes = Ember.merge({}, config.APP); attributes = Ember.merge(attributes, attrs); // use defaults, but you can override; Ember.run(() => { application = Application.create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); return application; }
JavaScript
0.000003
@@ -192,21 +192,22 @@ = Ember. -merge +assign (%7B%7D, con @@ -241,13 +241,14 @@ ber. -merge +assign (att
de25b0f471de1eba87803f3ba3dcc70de72468b7
Add todos in comments.
tests/highlighting_test.js
tests/highlighting_test.js
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. 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. * * ***** END LICENSE BLOCK ***** */ if (typeof process !== "undefined") { require("amd-loader"); } define(function(require, exports, module) { "use strict"; var assert = require("./assertions"); var requirejs = require('../r'); var XQueryParser = requirejs('../lib/XQueryParser').XQueryParser; var JSONParseTreeHandler = requirejs('../lib/JSONParseTreeHandler').JSONParseTreeHandler; var SyntaxHighlighter = requirejs('../lib/visitors/SyntaxHighlighter').SyntaxHighlighter; function getTokens(code) { var h = new JSONParseTreeHandler(code); var parser = new XQueryParser(code, h); parser.parse_XQuery(); var ast = h.getParseTree(); var visitor = new SyntaxHighlighter(ast); return visitor.getTokens(); } module.exports = { name: "Semantic Highlighter", "test: simple flwor": function() { var code = "for $i in (let, for)\nreturn return"; var tokens = getTokens(code); var reference = { "lines":[ [ {"value":"","type":"text"},{"value":"","type":"text"},{"value":"for","type":"keyword"},{"value":" ","type":"text"}, {"value":"$i","type":"variable"},{"value":" ","type":"text"},{"value":"in","type":"keyword"},{"value":" ","type":"text"}, {"value":"(","type":"text"},{"value":"let","type":"support.function"},{"value":"","type":"text"},{"value":",","type":"text"}, {"value":" ","type":"text"},{"value":"for","type":"support.function"},{"value":"","type":"text"},{"value":")","type":"text"},{"value":"","type":"text"} ], [{"value":"","type":"text"},{"value":"return","type":"keyword"},{"value":" ","type":"text"},{"value":"return","type":"support.function"},{"value":"","type":"text"},{"value":"","type":"text"}] ], "states":["start"] }; assert.equal(JSON.stringify(tokens), JSON.stringify(reference)); } }; }); if (typeof module !== "undefined" && module === require.main) { require("asyncjs").test.testcase(module.exports).exec() }
JavaScript
0
@@ -2360,16 +2360,165 @@ s();%0A%7D%0A%0A +//TODO: test highlighting of: replace json value of $tweet(%22created_at%22) with $dateTime;%0A//TODO: check highlighting for true, null, false in JSONiq.%0A module.e
88bb7db54831233056822d84bec037a2ed7dfbc7
add comba
QCLean-Chrome/qclean.js
QCLean-Chrome/qclean.js
var qclean = qclean || {}; qclean.removeADsLink = function(){ var adsLink = document.getElementsByClassName("adsCategoryTitleLink"); while(adsLink.length>0){ for(var i=0;i<adsLink.length;i++){ var target = adsLink[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode; target.parentNode.removeChild(target); console.log('Remove ads'); } adsLinkk = document.getElementsByClassName("adsCategoryTitleLink"); } }; qclean.removeSponsored = function(){ var sp = document.getElementsByClassName("uiStreamAdditionalLogging"); var combo = 0; while(sp.length>0){ for(var i = 0;i<sp.length;i++){ var n = sp[i]; var found = false; while(n.parentNode.nodeName!="BODY"){ if(n.parentNode.nodeName=="LI"){ if(n.parentNode.hasAttribute("class")&&n.parentNode.getAttribute("class").match("uiStreamStory")){ //for fb old ui user found = true; break; } }else if(n.parentNode.nodeName=="DIV"){ if(n.parentNode.hasAttribute("class")){ if(n.parentNode.getAttribute("class").match("_6ns _8ru _59hp")){ //for new fb newsfeed found = true; break; }else if(n.parentNode.getAttribute("class").match("_5jmm _5pat _5srp")){ //fb change its class name, jizz found = true; break; } } } n = n.parentNode; } if(found){ n = n.parentNode; n.parentNode.removeChild(n); console.log('Remove sponsored post'); } } sp = document.getElementsByClassName("uiStreamAdditionalLogging"); combo++; if(combo>3){ //TODO - notify there is some thing new/unknow break; } } } qclean.removeSponsored(); qclean.removeADsLink(); //Override xhr if(XMLHttpRequest.prototype.overrideByQCLean===undefined){ var originXHRopen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(){ /* arguments[0] - method arguments[1] - url, but some ajax request is not a string (facebook graph api?), so need to check this argument's type. */ if(arguments.length>2&&typeof arguments[1] == "string" &&arguments[1].match("/ajax/pagelet/generic.php/WebEgoPane")){ console.log('Block ads ajax request'); }else{ originXHRopen.apply(this,arguments); } } XMLHttpRequest.prototype.overrideByQCLean = true; } //Override DIV appendChild if(HTMLDivElement.prototype.overrideByQCLean===undefined){ var originDivAppend = HTMLDivElement.prototype.appendChild; HTMLDivElement.prototype.appendChild = function(){ originDivAppend.apply(this,arguments); qclean.removeADsLink(); //For new fb newsfeed qclean.removeSponsored(); } HTMLDivElement.prototype.overrideByQCLean = true; } //Override UL appendChild if(HTMLUListElement.prototype.overrideByQCLean===undefined){ var originUlAppend = HTMLUListElement.prototype.appendChild; HTMLUListElement.prototype.appendChild = function(){ originUlAppend.apply(this,arguments); qclean.removeSponsored(); } HTMLUListElement.prototype.overrideByQCLean = true; }
JavaScript
0.998571
@@ -136,16 +136,36 @@ Link%22);%0D +%0A var combo = 0;%0D %0A%0D%0A w @@ -524,24 +524,95 @@ tleLink%22);%0D%0A + combo++;%0D%0A if(combo%3E3)%7B%0D%0A break;%0D%0A %7D%0D%0A %7D%0D%0A%7D;%0D%0A%0D
3560cb5839514148f05c038639714d766d1e80b1
Update keycode.js
js/keycode.js
js/keycode.js
(function() { var mainSpan, shiftSpan, ctrlSpan, altSpan, nameSpan; //, metaSpan function startup() { mainSpan = document.getElementById("keydisplay"); nameSpan = document.getElementById("namedisplay"); shiftSpan = document.getElementById("shiftkey"); ctrlSpan = document.getElementById("ctrlkey"); altSpan = document.getElementById("altkey"); //metaSpan = document.getElementById("metakey"); document.addEventListener("keydown", keyCheck); document.addEventListener("keyup", keyUpCheck); } function keyCheck(e) { if (e.keyCode != 16 && e.keyCode != 17 && e.keyCode != 18) { var name = ""; if (e.key == undefined) { name = e.key; if (e.keyCode >= 96 && e.keyCode <= 105) { name = "Numpad " + name; } else if (!e.shiftKey && e.keyCode >= 48 && e.keyCode <= 57) { name = "Digit " + name; } else if (e.keyCode >= 65 && e.keyCode <= 90) { name = name.toUpperCase(); } displayKey(e.keyCode, name); } } modifier(shiftSpan, e.shiftKey); modifier(ctrlSpan, e.ctrlKey); modifier(altSpan, e.altKey); //modifier(metaSpan, e.metaKey); if (checkboxIsChecked()) { e.preventDefault(); } } function keyUpCheck(e) { modifier(shiftSpan, e.shiftKey); modifier(ctrlSpan, e.ctrlKey); modifier(altSpan, e.altKey); //modifier(metaSpan, e.metaKey); if (checkboxIsChecked()) { e.preventDefault(); } } function displayKey(code, name) { mainSpan.innerHTML = code; nameSpan.innerHTML = name; } function modifier(elem, on) { if (on) { elem.className = ""; } else { elem.className = "off"; } } function checkboxIsChecked() { return document.getElementById("blockCheckbox").checked; } document.addEventListener("DOMContentLoaded", startup); }).call();
JavaScript
0.000001
@@ -655,17 +655,17 @@ (e.key -= +! = undefi
f21cdcf84e306c32b2a1152384f457e4ab40ee55
add new keyword
interpreter.js
interpreter.js
var Ξ=[],//stack //I/O functions ô=i=>document.getElementById('o').value+=i!=[]._?i:(Ξ.shift(),Ξ.shift(),Ξ.join`\n`),//output ℹ=i=>[i=i!=[]._?document.getElementById("c").value[i]:document.getElementById("c").value,Ξ.push(i)][0],//source //stack functions ᵖ=(i=0)=>{Array.prototype.slice.call(arguments).map(x=>Ξ.push(x))}, ᵍ=i=>i!=[]._?Ξ[i<0?Ξ.length+i:i]:Ξ[Ξ.length-1], ʳ=(i=Ξ.length-1)=>Ξ.splice(i), ᶜ=i=>Ξ=[], //super-basic aliasing ī=Infinity, ü=[]._, М=math, Ϛ=String, Ѧ=Array, П=Number, Ø=Object, Ĵ=JSON, ɼ=RegExp, Ɗ=Date, ɘ=i=>LZString.decompress(i); [Ϛ,Ѧ,П,Ø,ɼ,Ɗ].map(v=>Object.getOwnPropertyNames(v).map((x,y)=>v.prototype[String.fromCharCode(y+248)]=v.prototype[x])); [М,Ϛ,Ѧ,П,Ø,Ĵ,ɼ,Ɗ].map(v=>Object.getOwnPropertyNames(v).map((x,y)=>v[String.fromCharCode(y+248)]=v[x])); var Σ=(c,asdf=0)=>{ //syntax from esmin to es6 c=c .replace(/([ᵖᵍʳᶜôℹΣɘϚѦПØɼƊ])(-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?|[A-Za-z]+)/g,'$1($2)') .replace(/([ᵖᵍʳᶜôℹΣɘϚѦПØɼƊ])(.+)⦆/g,'$1($2)') .replace(/⬮/g,'()') .replace(/⬯/g,'(``)') .replace(/⇏/g,'(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>') .replace(/↛/g,'=(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>') .replace(/↪/g,'($,_,ã)=>') .replace(/⤤/g,'=($,_,ã)=>') .replace(/→/g,'=>') .replace(/“/g,'(`') .replace(/”/g,'`)') .replace(/‘/g,'(\\`') .replace(/’/g,'\\`)') .replace(/⸨/g,'((') .replace(/⸩/g,'))') .replace(/⎛/g,'(/') .replace(/⎞/g,'/)') .replace(/⦃/g,'${') .replace(/…/g,'...') .replace(/˖/g,'+=') .replace(/⧺/g,'++') .replace(/˗/g,'-=') .replace(/‡/g,'--') .replace(/×/g,'*=') .replace(/÷/g,'/=') .replace(/٪/g,'%=') .replace(/¡/g,'!!') .replace(/≔/g,'==') .replace(/≠/g,'!=') .replace(/≤/g,'<=') .replace(/≥/g,'>=') .replace(/⅋/g,'&&') .replace(/ǁ/g,'||') .replace(/↺/g,'for(') .replace(/Ʀ/g,'return ') .replace(/\((.+)\)²/g,'Math.pow($1,2)') .replace(/\((.+)\)³/g,'Math.pow($1,3)') .replace(/(-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)²/g,'Math.pow($1,2)') .replace(/(-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)³/g,'Math.pow($1,3)') .replace(/\((.+)\)ⁿ\((.+)\)/g,'Math.pow($1,$2)') .replace(/(-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)ⁿ\((.+)\)/g,'Math.pow($1,$2)') .replace(/(-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)ⁿ(-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/g,'Math.pow($1,$2)') .replace(/\((.+)\)ⁿ(-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/g,'Math.pow($1,$2)') .replace(/√\((.+)\)/g,'Math.sqrt($1)') .replace(/√(-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/g,'Math.sqrt($1)') .replace(/∛\((.+)\)/g,'Math.cbrt($1)') .replace(/∛(-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/g,'Math.cbrt($1)') .replace(/½/g,'0.5') .replace(/¼/g,'0.25') .replace(/¾/g,'0.75') .replace(/⅐/g,'(1/7)') .replace(/⅑/g,'(1/9)') .replace(/⅒/g,'0.1') .replace(/⅓/g,'(1/3)') .replace(/⅔/g,'(2/3)') .replace(/⅕/g,'0.2') .replace(/⅖/g,'0.4') .replace(/⅗/g,'0.6') .replace(/⅘/g,'0.8') .replace(/⅙/g,'(1/6)') .replace(/⅚/g,'(5/6)') .replace(/⅛/g,'(1/8)') .replace(/⅜/g,'(3/8)') .replace(/⅝/g,'(5/8)') .replace(/⅞/g,'(7/8)') ; if(asdf==1e4&&!c.match(/ô/g))c+=';ô()';console.log(c),eval(c) } onload=function(){document.getElementById('c').value=decodeURIComponent((/c=(.+)/.exec(location.search)||[,""])[1]);document.getElementById('i').value=decodeURIComponent((/i=([^&]+)/.exec(location.search)||[,""])[1])}
JavaScript
0.000002
@@ -1966,16 +1966,40 @@ turn ')%0A +%09%09.replace(/%C5%8B/g,'new ')%0A %09%09.repla
fa64eb8b71d929e3766e3d8c2a011d9bee3588cc
Fix for "Cannot read property 'processName' of undefined"
tasks/json.js
tasks/json.js
/* * grunt-json * https://github.com/wilsonpage/grunt-json * * Copyright (c) 2012 Wilson Page * * Licensed under the MIT license. */ "use strict"; module.exports = function (grunt) { var path = require('path'); var defaultProcessNameFunction = function (name) { return name; }; var concatJson = function (files, data) { var options = data.options; var namespace = options && options.namespace || 'myjson'; // Allows the user to customize the namespace but will have a default if one is not given. var includePath = options && options.includePath || false; // Allows the user to include the full path of the file and the extension. var processName = options.processName || defaultProcessNameFunction; // Allows the user to modify the path/name that will be used as the identifier. var commonjs = options.commonjs || false; var basename; var filename; var NEW_LINE_REGEX = /\r*\n/g; var varDeclecation; if (commonjs) { varDeclecation = 'var ' + namespace + ' = {};\nmodule.exports = ' + namespace + ';'; } else { varDeclecation = (namespace.indexOf('.') === -1 ? 'var ' : '') + namespace + ' = ' + namespace + ' || {};'; } return varDeclecation + files.map(function (filepath) { basename = path.basename(filepath, '.json'); filename = (includePath) ? processName(filepath) : processName(basename); return '\n' + namespace + '["' + filename + '"] = ' + grunt.file.read(filepath).replace(NEW_LINE_REGEX, '') + ';'; }).join(''); }; // Please see the grunt documentation for more information regarding task and // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md // ========================================================================== // TASKS // ========================================================================== grunt.registerMultiTask('json', 'Concatenating JSON into JS', function () { var data = this.data; grunt.util.async.forEachSeries(this.files, function (f, nextFileObj) { var destFile = f.dest; var files = f.src.filter(function (filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }); var json = concatJson(files, data); grunt.file.write(destFile, json); grunt.log.write('File "' + destFile + '" created.'); }); }); };
JavaScript
0
@@ -383,16 +383,22 @@ .options + %7C%7C %7B%7D ;%0A @@ -414,27 +414,16 @@ espace = - options && options @@ -580,19 +580,8 @@ th = - options && opt
4b63ce1dba9a695675e102ae8628aa4313a2b927
add alarm middleware
test/alarm.js
test/alarm.js
var chai = require('chai'); var expect = chai.expect; var request = require('supertest'); var muk = require('muk'); var connect = require('connect'); var sinon = require('sinon'); var template = require('./supporter').template; var app = connect(); var APPID = "wxd930ea5d5a258f4f"; var PAYSIGNKEY = "L8LrMqqeGRxST5reouB0K66CaYAWpqhAVsq7ggKkxHCOastWksvuX1uvmvQclxaHoYd3ElNBrNO2DHnnzgfVG9Qs473M3DTOZug5er46FhuGofumV8H2FVR9qkjSlC5K"; var PARTNERID = '1900090055'; var PARTNERKEY = '8934e7d15453e97507ef794cf7b0519d'; var middleware = require('../lib/middleware'); var Alarm = middleware.Alarm; var common = require('../lib/common'); var errorHandler = function (err, req, res, next) { if (err) { console.error(err); } res.writeHead(403); res.end(err.message); }; describe('bizpaygetpackage', function () { var spy = sinon.spy(); before(function () { app.use('/', Alarm(APPID, PAYSIGNKEY, PARTNERID, PARTNERKEY) .done(function (message, req, res, next) { spy.apply(this, arguments); res.reply(); }) ); app.use('/', errorHandler); }); afterEach(function () { spy.reset(); }); it('defaults', function (done) { request(app) .post('/') .send(template.require('alarm')) .end(function (err, result) { expect(err).to.be.null; expect(result.text).to.be.deep.equal(''); expect(spy.args[0][0]).to.be.deep.equal({ AppId: 'wxd930ea5d5a258f4f', ErrorType: '1001', Description: '错误描述', AlarmContent: '错误详情', TimeStamp: '1393860740', AppSignature: 'a7fdeb6930a2a070da542d2da9c674a55d10972c', SignMethod: 'sha1' }); done(); }); }); });
JavaScript
0.000001
@@ -785,24 +785,13 @@ be(' -bizpaygetpackage +alarm ', f
adcc551bd073efefbb1bc45cda41f7eb314b10b2
Use assert instead of should
test/index.js
test/index.js
var http = require('http') var should = require('should') var client = require('@request/client') var purest = require('../')(client) describe('aliases', () => { var server before((done) => { server = http.createServer() server.on('request', (req, res) => { res.end(req.url) }) server.listen(6767, done) }) it('absolute URL', (done) => { var provider = purest({provider: 'purest', config: {purest: { 'http://localhost:6767': { 'api/{endpoint}': { __path: {alias: '__default'} } } }}}) provider .select('http://localhost:6767') .where({a: 'b'}) .callback((err, res, body) => { should.equal(body, '/?a=b') done() }) .submit() }) it('__default', (done) => { var provider = purest({provider: 'purest', config: {purest: { 'http://localhost:6767': { 'api/{endpoint}': { __path: {alias: '__default'} } } }}}) provider .select('user/profile') .where({a: 'b'}) .callback((err, res, body) => { should.equal(body, '/api/user/profile?a=b') done() }) .submit() }) it('named', (done) => { var provider = purest({provider: 'purest', config: {purest: { 'http://localhost:6767': { 'api/{endpoint}': { __path: {alias: '__default'} }, 'api/[version]/{endpoint}': { __path: {alias: 'picture', version: '1.0'} } } }}}) provider .query('picture') .select('uploads') .where({a: 'b'}) .callback((err, res, body) => { should.equal(body, '/api/1.0/uploads?a=b') done() }) .submit() }) it('named - array', (done) => { var provider = purest({provider: 'purest', config: {purest: { 'http://localhost:6767': { 'api/{endpoint}': { __path: {alias: '__default'} }, 'api/[version]/{endpoint}': { __path: {alias: ['picture', 'thumb'], version: '1.0'} } } }}}) provider .query('thumb') .select('uploads') .where({a: 'b'}) .callback((err, res, body) => { should.equal(body, '/api/1.0/uploads?a=b') done() }) .submit() }) after((done) => { server.close(done) }) })
JavaScript
0.000002
@@ -1,17 +1,14 @@ %0Avar -http +t = requi @@ -15,25 +15,25 @@ re(' -http +assert ')%0Avar -should +http = r @@ -40,22 +40,20 @@ equire(' -should +http ')%0Avar c @@ -667,38 +667,33 @@ y) =%3E %7B%0A -should +t .equal(body, '/? @@ -1071,38 +1071,33 @@ y) =%3E %7B%0A -should +t .equal(body, '/a @@ -1608,38 +1608,33 @@ y) =%3E %7B%0A -should +t .equal(body, '/a @@ -2173,14 +2173,9 @@ -should +t .equ
91204d050b105223e3b59e5d21d134b9686bf296
Fix bad fixture key
test/index.js
test/index.js
/* global describe, it */ var chai = require('chai'); var expect = chai.expect; var builder = require('../dist/'); const options = { template: { partials: `${__dirname}/fixtures/partials/*`, helpers: `${__dirname}/fixtures/helpers/*.js` } }; describe ('drizzle builder integration', () => { it ('should return opts used for building', () => { builder(options).then(opts => { expect(opts).to.be.an.object; expect(opts.templates).to.be.an.object; expect(opts.templates.handlebars).to.be.an.object; }); }); });
JavaScript
0.000001
@@ -137,16 +137,17 @@ template +s : %7B%0A
06e13eade60f390c663f88999e1a29c830e702e1
Fix listing errors
test/index.js
test/index.js
'use strict'; var expect = require('chai').expect; var plugin = require('..'); var sinon = require('sinon'); var child = require('child_process'); describe('plugin', function() { beforeEach(function() { var spawn = child.spawn; sinon.stub(child, 'spawn', function(cmd, args) { var versionMatch = args[1].match(/source \$NVM_DIR\/nvm\.sh; nvm version "(v*\d+[\.\d]*)"/) if (args[1] === 'source $NVM_DIR/nvm.sh; nvm version "lts/boron"') { // Mock return for an aliased version return spawn('echo', ['v6.12.0']) } else if (versionMatch) { // Mock return for a normal version numver var version = versionMatch[1]; version = 'v' + version.replace('v', ''); return spawn('echo', [version]); } else if (args[1] === 'source $NVM_DIR/nvm.sh; nvm list') { // Mock the version list command return spawn('echo', ['v0.7.12\n0.10.26\nv0.10.28\nv0.10.29\nv0.10.101\nv0.11.13\nv6.12.0']); } else { // Assume all other commands are nvm version "<uninstalled_version>" return spawn('echo', ['N/A']) } }); }); afterEach(function() { child.spawn.restore(); }); it('matches exact version', function(done) { plugin.match('0.11.13').then(function(result) { expect(result).to.eql({ version: 'v0.11.13', command: 'nvm use v0.11.13 > /dev/null;' }); }) .done(done); }); it('matches with semver syntax', function(done) { plugin.match('>=0.10 < 0.10.29').then(function(result) { expect(result).to.eql({ version: 'v0.10.28', command: 'nvm use v0.10.28 > /dev/null;' }); }) .done(done); }); it('chooses greatest match', function(done) { plugin.match('0.10').then(function(result) { expect(result).to.eql({ version: 'v0.10.101', command: 'nvm use v0.10.101 > /dev/null;' }); }) .done(done); }); it('rejects versions not installed', function(done) { plugin.match('0.9').then( function() { throw new Error('Plugin should have rejected invalid version.'); }, function(e) { expect(e).to.match(/no version matching 0\.9/); }) .done(done); }); it('rejects when command fails', function(done) { child.spawn.restore(); var spawn = child.spawn; sinon.stub(child, 'spawn', function(/*cmd, args*/) { return spawn('ls', ['/nowhere']); // intentional command failure }); plugin.match('0.9').then( function() { throw new Error('Plugin should have rejected bad command.'); }, function(e) { expect(e).to.match(/nvm exited with status: \d+/); }) .done(done); }); it('parses nvm@dc53a37 output', function() { var output = { stdout: new Buffer(' v0.7.12\n v0.8.26\n v0.9.12\n v0.10.26\n v0.10.28\n v0.11.11\n v0.11.12\n v0.11.13\ncurrent: \tv0.10.26\n0.10 -> 0.10.26 (-> v0.10.26)\ndefault -> 0.10 (-> v0.10.26)\n') }; expect(plugin._parseVersions(output)).to.eql([ 'v0.7.12', 'v0.8.26', 'v0.9.12', 'v0.10.26', 'v0.10.28', 'v0.11.11', 'v0.11.12', 'v0.11.13' ]); }); it('parses nvm@1ee708b output', function() { var output = { stdout: new Buffer(' v0.7.12\n v0.8.26\n v0.9.12\n-> v0.10.26\n v0.10.28\n v0.11.11\n v0.11.12\n v0.11.13\n system\nstable -> 0.10 (-> v0.10.26) (default)\nunstable -> 0.11 (-> v0.11.13) (default)\n') }; expect(plugin._parseVersions(output)).to.eql([ 'v0.7.12', 'v0.8.26', 'v0.9.12', 'v0.10.26', 'v0.10.28', 'v0.11.11', 'v0.11.12', 'v0.11.13' ]); }); it('parses output that includes iojs', function() { var output = { stdout: new Buffer(' iojs-v1.1.0\n-> v0.10.36\n v0.12.0\n') }; expect(plugin._parseVersions(output)).to.eql([ 'iojs-v1.1.0', 'v0.10.36', 'v0.12.0', ]); }); it('finds versions when iojs is installed', function() { expect(plugin._findVersion(['iojs-v1.1.0', 'v0.12.0'], 'v0.12')) .to.eql('v0.12.0'); }); it('finds iojs versions', function() { expect(plugin._findVersion(['iojs-v1.1.0', 'v0.12.0'], 'iojs-v1.1')) .to.eql('iojs-v1.1.0'); }); it('finds aliased versions', function (done) { plugin.match('lts/boron').then(function(result) { expect(result).to.eql({ version: 'v6.12.0', command: 'nvm use v6.12.0 > /dev/null;' }) }).done(done) }) });
JavaScript
0.000002
@@ -380,16 +380,17 @@ %5Cd%5D*)%22/) +; %0A i @@ -544,16 +544,17 @@ .12.0'%5D) +; %0A %7D @@ -1099,16 +1099,17 @@ %5B'N/A'%5D) +; %0A %7D @@ -4469,24 +4469,25 @@ l;'%0A %7D) +; %0A %7D).done @@ -4492,18 +4492,20 @@ ne(done) +; %0A %7D) +; %0A%7D);%0A
26a9cad65a7a60ffb31fdea65af26a0d3e72a9dd
Update the path to Amanda in the ‘except.js’ file
tests/validators/except.js
tests/validators/except.js
// Load dependencies var amanda = require('../../src/amanda.js'); /** * Test #1 */ exports['Test #1'] = function(test) { var count = 0; var schema = { required: true, type: 'string', except: [ 'admin', 'administrator', 'superadmin' ] }; [ 'admin', 'administrator', 'superadmin' ].forEach(function(user) { amanda.validate(user, schema, function(error) { count += 1; test.ok(error); }); }); amanda.validate('superadmin2', schema, function(error) { count += 1; test.equal(error, undefined); }); test.equal(count, 4); test.done(); };
JavaScript
0
@@ -46,18 +46,19 @@ /../ -src/amanda +dist/latest .js'
727b0a148007ee4366bf6d024b3bac7b3e7fc0ce
Update pbckcode.js
dialogs/pbckcode.js
dialogs/pbckcode.js
CKEDITOR.dialog.add('pbckcodeDialog', function (editor) { "use strict"; var tab_sizes = ["1", "2", "4", "8"]; // CKEditor variables var dialog; var shighlighter = new PBSyntaxHighlighter(editor.settings.highlighter); // ACE variables var aceEditor, aceSession, whitespace; // EDITOR panel var editorPanel = { id : 'editor', label : editor.lang.pbckcode.editor, elements : [ { type : 'hbox', children : [ { type : 'select', id : 'code-select', className : 'cke_pbckcode_form', label : editor.lang.pbckcode.mode, items : editor.settings.modes, 'default' : editor.settings.modes[0][1], setup : function (element) { if (element) { element = element.getAscendant('pre', true); this.setValue(element.getAttribute("data-pbcklang")); } }, commit : function (element) { if (element) { element = element.getAscendant('pre', true); element.setAttribute("data-pbcklang", this.getValue()); } }, onChange : function () { aceSession.setMode("ace/mode/" + this.getValue()); } }, { type : 'select', id : 'code-tabsize-select', className : 'cke_pbckcode_form', label : editor.lang.pbckcode.tabSize, items : tab_sizes, 'default' : editor.settings.tab_size, setup : function (element) { if (element) { element = element.getAscendant('pre', true); this.setValue(element.getAttribute("data-pbcktabsize")); } }, commit : function (element) { if (element) { element = element.getAscendant('pre', true); element.setAttribute("data-pbcktabsize", this.getValue()); } }, onChange : function (element) { if (element) { whitespace.convertIndentation(aceSession, " ", this.getValue()); aceSession.setTabSize(this.getValue()); } } } ] }, { type : 'html', html : '<div></div>', id : 'code-textarea', className : 'cke_pbckcode_ace', style : 'position: absolute; top: 80px; left: 10px; right: 10px; bottom: 50px;', setup : function (element) { // get the value of the editor var code = element.getHtml(); // replace some regexp code = code.replace(new RegExp('<br/>', 'g'), '\n') .replace(new RegExp('<br>', 'g'), '\n') .replace(new RegExp('&lt;', 'g'), '<') .replace(new RegExp('&gt;', 'g'), '>') .replace(new RegExp('&amp;', 'g'), '&') .replace(new RegExp('&nbsp;', 'g'), ' '); aceEditor.setValue(code); }, commit : function (element) { element.setText(aceEditor.getValue()); } } ] }; // dialog code return { // Basic properties of the dialog window: title, minimum size. title : editor.lang.pbckcode.title, minWidth : 600, minHeight : 400, // Dialog window contents definition. contents : [ editorPanel ], onLoad : function () { dialog = this; // we load the ACE plugin to our div aceEditor = ace.edit(dialog.getContentElement('editor', 'code-textarea') .getElement().getId()); // save the aceEditor into the editor object for the resize event editor.aceEditor = aceEditor; // set default settings aceEditor.setTheme("ace/theme/" + editor.settings.theme); aceEditor.setHighlightActiveLine(true); aceSession = aceEditor.getSession(); aceSession.setMode("ace/mode/" + editor.settings.modes[0][1]); aceSession.setTabSize(editor.settings.tab_size); aceSession.setUseSoftTabs(true); // load ace extensions whitespace = ace.require('ace/ext/whitespace'); }, onShow : function () { // get the selection var selection = editor.getSelection(); // get the entire element var element = selection.getStartElement(); // looking for the pre parent tag if (element) { element = element.getAscendant('pre', true); } // if there is no pre tag, it is an addition. Therefore, it is an edition if (!element || element.getName() !== 'pre') { element = new CKEDITOR.dom.element('pre'); if (shighlighter.getTag() !== 'pre') { element.append(new CKEDITOR.dom.element('code')); } this.insertMode = true; } else { if (shighlighter.getTag() !== 'pre') { element = element.getChild(0); } this.insertMode = false; } // get the element to fill the inputs this.element = element; // focus on the editor aceEditor.focus(); // we empty the editor aceEditor.setValue(''); // we fill the inputs if (!this.insertMode) { this.setupContent(this.element); } }, // This method is invoked once a user clicks the OK button, confirming the dialog. onOk : function () { var pre, element; pre = element = this.element; if (this.insertMode) { if (shighlighter.getTag() !== 'pre') { element = this.element.getChild(0); } } else { pre = element.getAscendant('pre', true); } this.commitContent(element); // set the full class to the code tag shighlighter.setCls(pre.getAttribute("data-pbcklang") + " " + editor.settings.cls); element.setAttribute('class', shighlighter.getCls()); // we add a new code tag into ckeditor editor if (this.insertMode) { editor.insertElement(pre); } } }; }); /* * Resize the ACE Editor */ CKEDITOR.dialog.on('resize', function (evt) { var AceEditor = evt.editor.aceEditor; if (AceEditor !== undefined) { AceEditor.resize(); } });
JavaScript
0.000001
@@ -4998,24 +4998,71 @@ eLine(true); +%0A aceEditor.setShowInvisibles(true); %0A%0A
d39fcc02438e55a483c050f0db313a68dc0c2bfb
Remove unnecessary Chai lib
test/APITests.js
test/APITests.js
/* eslint-env node, mocha */ import { expect } from 'chai'; // Utils import { waitForTransitionsFinished, waitForTilesLoaded, removeHGComponent, } from '../app/scripts/utils'; import { simpleCenterViewConfig, } from './view-configs'; import createElementAndApi from './utils/create-element-and-api'; describe('Simple HiGlassComponent', () => { let div = null; let api = null; describe('Options tests', () => { it('creates an editable component', () => { ([div, api] = createElementAndApi(simpleCenterViewConfig)); const component = api.getComponent(); expect(Object.keys(component.viewHeaders).length).to.be.above(0); }); it('zooms to negative domain', (done) => { ([div, api] = createElementAndApi(simpleCenterViewConfig, { editable: false })); api.zoomTo('a', 6.069441699652629, 6.082905691828387, -23.27906532393644, -23.274695776773807, 100); waitForTransitionsFinished(api.getComponent(), () => { expect(api.getComponent().yScales.a.domain()[0]).to.be.below(0); done(); }); }); it('zooms to just x and y', (done) => { ([div, api] = createElementAndApi(simpleCenterViewConfig, { editable: false })); api.zoomTo('a', 6.069441699652629, 6.082905691828387, null, null, 100); waitForTransitionsFinished(api.getComponent(), () => { waitForTilesLoaded(api.getComponent(), () => { expect(api.getComponent().yScales.a.domain()[0]).to.be.above(2); const trackObj = api.getTrackObject('a', 'heatmap1'); const rd = trackObj.getVisibleRectangleData(285, 156, 11, 11); expect(rd.data.length).to.eql(1); done(); }); }); }); it('zoom to a nonexistent view', () => { // complete me, should throw an error rather than complaining // "Cannot read property 'copy' of undefined thrown" ([div, api] = createElementAndApi(simpleCenterViewConfig, { editable: false })); expect(() => api.zoomTo('nonexistent', 6.069441699652629, 6.082905691828387, -23.274695776773807, -23.27906532393644)) .to.throw('Invalid viewUid. Current present uuids: a'); }); it('creates a non editable component', () => { ([div, api] = createElementAndApi(simpleCenterViewConfig, { editable: false })); const component = api.getComponent(); expect(Object.keys(component.viewHeaders).length).to.eql(0); }); it('retrieves a track', () => { ([div, api] = createElementAndApi(simpleCenterViewConfig, { editable: false })); const viewconf = api.getViewConfig(); const trackObj = api.getTrackObject(viewconf.views[0].tracks.center[0].uid); expect(trackObj).to.exist; }); it('zooms to a negative location', (done) => { ([div, api] = createElementAndApi(simpleCenterViewConfig, { editable: false, bounded: true })); api.zoomTo('a', -10000000, 10000000); waitForTransitionsFinished(api.getComponent(), () => { waitForTilesLoaded(api.getComponent(), () => { done(); }); }); }); afterEach(() => { removeHGComponent(div); }); // it('creates a new component with different options and checks' // + 'whether the global options object of the first object has changed', () => { // // create one div and set an auth header // const div = global.document.createElement('div'); // global.document.body.appendChild(div); // const api = viewer(div, simpleCenterViewConfig, { a: 'x' }); // api.setViewConfig(simpleCenterViewConfig); // api.setAuthHeader('blah'); // // create a second component and set a different auth header // const div1 = global.document.createElement('div'); // global.document.body.appendChild(div1); // const api1 = viewer(div1, simpleCenterViewConfig, { a: 'y' }); // api1.setAuthHeader('wha'); // // check to make sure that the two components have different // // auth headers // }); }); });
JavaScript
0.000092
@@ -17,57 +17,18 @@ de, -mocha */%0Aimport %7B expect %7D from 'chai';%0A%0A// Utils +jasmine */ %0Aimp @@ -601,25 +601,29 @@ ngth).to -.be.above +BeGreaterThan (0);%0A @@ -1011,17 +1011,18 @@ ).to -.be.below +BeLessThan (0); @@ -1457,17 +1457,21 @@ ).to -.be.above +BeGreaterThan (2); @@ -1645,19 +1645,20 @@ ngth).to -.eq +Equa l(1);%0A%0A @@ -2117,18 +2117,17 @@ .to -.t +T hrow('In @@ -2432,11 +2432,12 @@ ).to -.eq +Equa l(0) @@ -2736,14 +2736,19 @@ ).to -.exist +BeDefined() ;%0A
160fbf4afbcd696d9f044d1570084444cbf78e35
fix issue #6: if target is only moving in one direction, hasItem moved failed to detect movement
src/CirclePacker.js
src/CirclePacker.js
import { sendWorkerMessage, processWorkerMessage, isCircleValid, isBoundsValid } from './util.js'; // this class keeps track of the drawing loop in continuous drawing mode // and passes messages to the worker export default class CirclePacker { constructor ( params = { } ) { this.worker = new Worker( 'src/CirclePackWorker.js' ); this.worker.addEventListener( 'message', this.receivedWorkerMessage.bind( this ) ); this.isContinuousModeActive = typeof params.continuousMode === 'boolean' ? params.continuousMode : true; this.onMoveStart = params.onMoveStart || null; this.onMove = params.onMove || null; this.onMoveEnd = params.onMoveEnd || null; this.lastCirclePositions = [ ]; if ( params.centeringPasses ) { this.setCenteringPasses( params.centeringPasses ); } if ( params.collisionPasses ) { this.setCollisionPasses( params.collisionPasses ); } this.addCircles( params.circles || [ ] ); this.setBounds( params.bounds || { width: 100, height: 100 } ); this.setTarget( params.target || { x: 50, y: 50 } ); this.isLooping = false; this.areItemsMoving = true; this.animationFrameId = NaN; this.initialized = true; if ( this.isContinuousModeActive ) { this.startLoop(); } } receivedWorkerMessage ( event ) { const msg = processWorkerMessage( event ); if ( msg.type === 'move' ) { const newPositions = msg.message; this.areItemsMoving = this.hasItemMoved( newPositions ); if ( ! this.areItemsMoving && this.isLooping && this.initialized && this.isContinuousModeActive ) { this.stopLoop(); } } this.updateListeners( msg ); } updateWorker ( type, message ) { sendWorkerMessage( this.worker, { type, message } ); } updateListeners ( { type, message } ) { if ( type === 'movestart' && typeof this.onMoveStart === 'function' ) { this.onMoveStart( message ); } if ( type === 'move' && typeof this.onMove === 'function' ) { this.lastCirclePositions = message; this.onMove( message ); } if ( type === 'moveend' && typeof this.onMoveEnd === 'function' ) { this.onMoveEnd( message ); } } addCircles ( circles ) { if ( Array.isArray( circles ) && circles.length ) { const circlesToAdd = circles.filter( isCircleValid ); if ( circlesToAdd.length ) { this.updateWorker( 'addcircles', circlesToAdd ); } } this.startLoop(); } addCircle ( circle ) { this.addCircles( [ circle ] ); } removeCircle ( circle ) { if ( circle ) { if ( circle.id ) { this.updateWorker( 'removecircle', circle.id ); } else { this.updateWorker( 'removecircle', circle ); } this.startLoop(); } } pinCircle ( circle ) { if ( circle ) { if ( circle.id ) { this.updateWorker( 'pincircle', circle.id ); } else { this.updateWorker( 'pincircle', circle ); } this.startLoop(); } } unpinCircle ( circle ) { if ( circle ) { if ( circle.id ) { this.updateWorker( 'unpincircle', circle.id ); } else { this.updateWorker( 'unpincircle', circle ); } this.startLoop(); } } setCircleRadius ( circle, radius ) { if ( circle && radius >= 0 ) { if ( circle.id ) { this.updateWorker( 'circleradius', { id: circle.id, radius } ); } else { this.updateWorker( 'circleradius', { id: circle, radius } ); } this.startLoop(); } } setCircleCenterPull ( circle, centerPull ) { if ( circle ) { if ( circle.id ) { this.updateWorker( 'circlecenterpull', { id: circle.id, centerPull: !! centerPull } ); } else { this.updateWorker( 'circlecenterpull', { id: circle, centerPull: !! centerPull } ); } this.startLoop(); } } setCenterPull ( centerPull ) { this.updateWorker( 'centerpull', { centerPull: !! centerPull } ); this.startLoop(); } setBounds ( bounds ) { if ( isBoundsValid( bounds ) ) { this.updateWorker( 'bounds', bounds ); this.startLoop(); } } setTarget ( targetPos ) { this.updateWorker( 'target', targetPos ); this.startLoop(); } setCenteringPasses ( numberOfCenteringPasses ) { this.updateWorker( 'centeringpasses', numberOfCenteringPasses ); } setCollisionPasses ( numberOfCollisionPasses ) { this.updateWorker( 'collisionpasses', numberOfCollisionPasses ); } setDamping ( damping ) { this.updateWorker( 'damping', damping ); } update () { this.updateWorker( 'update' ); } dragStart( id ) { this.updateWorker( 'dragstart', { id } ); this.startLoop(); } drag ( id, position ) { this.updateWorker( 'drag', { id, position } ); this.startLoop(); } dragEnd ( id ) { this.updateWorker( 'dragend', { id } ); this.startLoop(); } updateLoop () { this.update(); if ( this.isLooping ) { if ( this.areItemsMoving ) { this.animationFrameId = requestAnimationFrame( this.updateLoop.bind( this ) ); } else { this.stopLoop(); } } } startLoop () { if ( ! this.isLooping && this.initialized && this.isContinuousModeActive ) { this.isLooping = true; // in case we just added another circle: // keep going, even if nothing has moved since the last message from the worker if ( this.isContinuousModeActive ) { this.areItemsMoving = true; } this.updateListeners( { type: 'movestart' } ); this.animationFrameId = requestAnimationFrame( this.updateLoop.bind( this ) ); } } stopLoop () { if ( this.isLooping ) { this.isLooping = false; this.updateListeners( { type: 'moveend', message: this.lastCirclePositions } ); cancelAnimationFrame( this.animationFrameId ); } } hasItemMoved ( positions ) { let result = false; for ( let id in positions ) { if ( Math.abs( positions[id].delta.x ) > 0.005 && Math.abs( positions[id].delta.y ) > 0.005 ) { result = true; } } return result; } destroy () { if ( this.worker ) { this.worker.terminate(); } this.stopLoop(); this.onMove = null; this.onMoveStart = null; this.onMoveEnd = null; } }
JavaScript
0
@@ -5690,18 +5690,18 @@ %3E 0.005 -&& +%7C%7C %0A%09%09%09%09Ma
80e20f6d4315c1a4ce8b4d9bf06d99d556467676
Fix condition to get animations
core/imagefile.js
core/imagefile.js
function ImageFile(_game) { this.game = _game; this.name = new Array(); this.data = new Array(); this.counter = 0; return this; }; ImageFile.prototype.image = function(_imageSrc) { var _name = _imageSrc.substring(0, _imageSrc.length - 4); if(!this.getImageDataByName(_name)) { var self = this; var _image = new Image(); _image.addEventListener('load', function(){self.counter++}); _image.src = _imageSrc; this.name.push(_name); this.data.push(_image); } return this.getImageDataByName(_name); }; ImageFile.prototype.load = function(_imageSrc, _width, _height) { var s = new Sprite(_imageSrc, _width, _height); s.game = this.game; s.image = this.image(_imageSrc); if(this.isLoaded()); s.getAnimation(); this.game.scene.sprite.push(s); return s; }; ImageFile.prototype.reset = function() { this.game.scene.sprite = []; }; ImageFile.prototype.isLoaded = function() { if(this.counter === this.data.length) { return true; } return false; }; ImageFile.prototype.getImageDataByName = function(_imageName) { return this.data[this.name.indexOf(_imageName)]; };
JavaScript
0
@@ -733,17 +733,16 @@ oaded()) -; %0D%0A%09%09s.ge
b44a8a0f055df687c26364bdf7251195468238c1
fix get screen sizes on the move
core/move/move.js
core/move/move.js
document.addEventListener('appload', function() { var currentElement = null; var cursorOffsetLeft, cursorOffsetTop; var minOffsetTop = 0, maxOffsetTop = document.documentElement.clientHeight; var minOffsetLeft = 0, maxOffsetLeft = document.documentElement.clientWidth; [].forEach.call(document.querySelectorAll('.widget'), function(element) { element.addEventListener('mousedown', function(event) { var isNotLeftClick = event.which !== 1; if (isNotLeftClick) { return; } var isResizeBlock = event.target.classList.contains('resize'); if (isResizeBlock) { return; } cursorOffsetLeft = event.pageX - element.offsetLeft; cursorOffsetTop = event.pageY - element.offsetTop; currentElement = element; currentElement.classList.add('move'); currentElement.querySelector('.widget__item').classList.add('move'); }); }); document.addEventListener('mouseup', function() { if (currentElement === null) { return; } currentElement.classList.remove('move'); currentElement.querySelector('.widget__item').classList.remove('move'); currentElement = null; }); document.addEventListener('mousemove', function(event) { if (currentElement === null) { return; } var newLeft = event.pageX - cursorOffsetLeft; var newTop = event.pageY - cursorOffsetTop; // check on borders var resizeOffset = currentElement.widget().resize('get'); var minLeft = minOffsetLeft + resizeOffset; var maxLeft = maxOffsetLeft - currentElement.offsetWidth - resizeOffset; if (newLeft < minLeft) { newLeft = minLeft; } else if (newLeft > maxLeft) { newLeft = maxLeft; } var minTop = minOffsetTop + resizeOffset; var maxTop = maxOffsetTop - currentElement.offsetHeight - resizeOffset; if (newTop < minTop) { newTop = minTop; } else if (newTop > maxTop) { newTop = maxTop; } // update position currentElement.style.left = newLeft + 'px'; currentElement.style.top = newTop + 'px'; }); });
JavaScript
0
@@ -112,19 +112,21 @@ etTop;%0A%09 -var +const minOffs @@ -141,137 +141,24 @@ 0, m -axOffsetTop = document.documentElement.clientHeight;%0A%09var minOffsetLeft = 0, maxOffsetLeft = document.documentElement.clientWidth +inOffsetLeft = 0 ;%0A%0A%09 @@ -1099,24 +1099,155 @@ eturn;%0A%09%09%7D%0A%0A +%09%09// vars%0A%09%09var maxOffsetTop = document.documentElement.clientHeight;%0A%09%09var maxOffsetLeft = document.documentElement.clientWidth;%0A%0A %09%09var newLef @@ -1282,16 +1282,16 @@ etLeft;%0A - %09%09var ne @@ -1333,30 +1333,8 @@ p;%0A%0A -%09%09// check on borders%0A %09%09va @@ -1390,16 +1390,38 @@ get');%0A%0A +%09%09// check on borders%0A %09%09var mi
64460694714fba896f64c47dd071ab8eafb25dce
send to proper channel for list rooms
core/socket-io.js
core/socket-io.js
'use strict'; var express = require('express'), ioServer = require('socket.io'), ioRedis = require('redis'), passportSocketIo = require('passport.socketio'), ioRedisStore = require('socket.io/lib/stores/redis'), RedisStore = require('connect-redis')(express); exports.name = 'kabam-core-socket-io'; exports.app = function(kernel){ if (!kernel.config.IO || !kernel.config.IO.ENABLED) { return; } /** * @ngdoc function * @name kabamKernel.io * @description * Socket.io main object, binded to http server of kabamKernel.app. * This is fully working socket.io object, that supports all socket.io functions and events. * Further reading - [https://github.com/LearnBoost/socket.io/wiki/Exposed-events](https://github.com/LearnBoost/socket.io/wiki/Exposed-events) * * Also the socket.io adds few listeners to kabamKernel object, so we can do this things * Broadcast to all users online * ```javascript * * kabam.emit('broadcast',{'time': new Date().toLocaleTimeString()}); * * ``` * * Notify one of users, if he/she is online with simple text message (or JSON object) * * ```javascript * * kabamKernel.model.User.findOne({'username':'john'},function(err,userFound){ * userFound.notify('sio','Hello, '+userFound.username+'!'); * }); * * ``` * Socket.io runs from the box on heroku, nodejitsu, and from behing of nginx and Pound reverse proxies * [https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku](https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku) * * We can enable socket.io support in application by edint field of `io` on config object like here * ```javascript * 'io':{ 'loglevel':1 }; * ``` * Loglevel is like this 9 - very verbose, 8 - less verbose, 7,6,5,4,3,2, 1 - not verbose */ kernel.io = ioServer.listen(kernel.httpServer); kernel.io.enable('browser client cache'); kernel.io.enable('browser client gzip'); kernel.io.enable('browser client etag'); kernel.io.enable('browser client minification'); kernel.io.set('browser client expires', (24 * 60 * 60)); ////for heroku or Pound reverse proxy // kernel.io.set('transports', ['xhr-polling']); kernel.io.set('polling duration', 6); //verbosity level - default is 3 kernel.io.set('log level', (kernel.config.IO.LOGLEVEL || 3)); kernel.app.locals.javascripts.push({'url': '/socket.io/socket.io.js'}); kernel.io.set('store', new ioRedisStore({ redis: ioRedis, redisPub: kernel.createRedisClient(), //it works in pub mode, it cannot access database redisSub: kernel.createRedisClient(), //it works in sub mode, it cannot access database redisClient: kernel.redisClient })); var sessionStorage = new RedisStore({prefix: 'kabam_sess_', client: kernel.redisClient}); kernel.io.set('authorization', passportSocketIo.authorize({ cookieParser: express.cookieParser, secret: kernel.config.SECRET, store: sessionStorage, // there is no passportJS user present for this session! fail: function (data, accept) { data.user = null; accept(null, true); }, // the passportJS user is present for this session! success: function (data, accept) { sessionStorage.get(data.sessionID, function (err, session) { kernel.model.User.findOneByApiKey(session.passport.user, function (err, user) { if (user) { data.user = user; accept(err, true); } else { accept(err, false); //we break the session, because someone tryes to tamper it) } }); }); } } )); //socket.io settings //emit event to all (authorized and anonimus) users online kernel.on('broadcast', function (message) { kernel.io.sockets.emit('broadcast', message); }); kernel.on('notify:sio', function (message) { var activeUsers = kernel.io.sockets.manager.handshaken, x; for (x in activeUsers) { if (activeUsers[x].user && message.user && activeUsers[x].user.username === message.user.username) { if (kernel.io.sockets.manager.sockets.sockets[x]) { kernel.io.sockets.manager.sockets.sockets[x].emit('notify', { 'user': message.user, 'message': message.message, 'type': message.type }); } } } }); // socket.io event handlers kernel.io.sockets.on('connection', function (socket) { // receive message from frontend socket.on('backend', function(data) { if (data.action === 'notify:sio') { // relay notify:sio message from client kernel.emit('notify:sio', data); } else if (data.action === 'subscribe' && data.channel) { // subscribe client socket.join(data.channel); } else if (data.action === 'unsubscribe' && data.channel) { // unsubscribe client socket.leave(data.channel); } else if (data.action === 'publish' && data.channel) { // publish an event socket.broadcast.to(data.channel).emit(data.event, data); } }); }); // publish to room for model changes kernel.on('update', function(data) { if (!data.channel || !/\w+:\w+/.test(data.channel)) { return; } // single object room if (kernel.io.sockets.manager.rooms['/' + data.channel]) { kernel.io.sockets.in(data.channel).emit('update', data); } // list room var arr = /(\w+):/.exec(data.channel); if (arr && kernel.io.sockets.manager.rooms['/' + arr[1]]) { kernel.io.sockets.in(arr[1]).emit('update', data); } }); kernel.on('delete', function(data) { if (!data.channel || !/\w+:\w+/.test(data.channel)) { return; } // single object room if (kernel.io.sockets.manager.rooms['/' + data.channel]) { kernel.io.sockets.in(data.channel).emit('delete', data); } var arr = /(\w+):/.exec(data.channel); if (arr && kernel.io.sockets.manager.rooms['/' + arr[1]]) { kernel.io.sockets.in(arr[1]).emit('delete', data); } }); kernel.on('create', function(data) { if (!data.channel) { return; } if (kernel.io.sockets.manager.rooms['/' + data.channel]) { kernel.io.sockets.in(data.channel).emit('create', data); } }); };
JavaScript
0
@@ -5586,32 +5586,61 @@ /' + arr%5B1%5D%5D) %7B%0A + data.channel = arr%5B1%5D;%0A kernel.io. @@ -6073,24 +6073,53 @@ arr%5B1%5D%5D) %7B%0A + data.channel = arr%5B1%5D;%0A kernel
934c858c8e25fc96fcd9e0d3077a743ddf7b4dff
add test for Redux Store
test/app.spec.js
test/app.spec.js
/** eslint-env mocha */ const { expect } = require('chai') const React = require('react') const Search = require('../js/Search') const ShowCard = require('../js/ShowCard') const { shallow, mount } = require('enzyme') const { shows } = require('../public/data') describe('<Search />', () => { it('It should render brand', () => { const wrapper = shallow(<Search/>) expect(wrapper.contains(<h1 className='brand'>svideo</h1>)).to.be.true }) it('shold render as many shows as there are data for', () => { const wrapper = shallow(<Search/>) expect(wrapper.find(ShowCard).length).to.equal(shows.length) }) it('should filter correctly given new state', () => { const wrapper = mount(<Search/>) const input = wrapper.find('.search-input') input.node.value = 'house' input.simulate('change') expect(wrapper.state('searchTerm')).to.equal('house') expect(wrapper.find('.show-card').length).to.equal(2) }) })
JavaScript
0
@@ -164,16 +164,74 @@ owCard') +%0Aconst %7B store, rootReducer %7D = require('../js/Store.jsx') %0A%0Aconst @@ -315,16 +315,17 @@ ata')%0A%0A%0A +x describe @@ -1002,14 +1002,507 @@ 2)%0A%0A %7D) +%0A%0A%7D)%0A%0Adescribe('Store', () =%3E %7B%0A it('Should bootstrap', () =%3E %7B%0A // goes from having nothing%0A const state = rootReducer(undefined, %7B type: '@@redux/INIT'%7D)%0A // creat this initial state to test%0A expect(state).to.deep.equal(%7BsearchTerm: ''%7D)%0A %7D)%0A it('Should handle setSearchTerm action', () =%3E %7B%0A const state = rootReducer(%7BsearchTerm: 'some random string'%7D, %7Btype: 'setSearchTerm', value: 'correct string'%7D)%0A expect(state).to.deep.equal(%7BsearchTerm: 'correct string'%7D)%0A %7D) %0A%7D)%0A%0A%0A
c5b0e01ff5abacfd455b087bf0c87236550638bc
Use fs-extra to remove outputDir
bin/clean.js
bin/clean.js
#!/usr/bin/env node import fs from 'fs-extra' import colors from 'colors' import { isSite, exists } from '../lib/etc' import config from '../lib/config' if (!isSite()) { console.error('No site in here!'.red) process.exit(1) } if (!exists(config.outputDir)) { console.error('There\'s a site in here, but it hasn\'t been built yet.') console.error('Run ' + 'cory build'.gray + ' to build it.') process.exit(1) } etc.deleteDir(config.outputDir, false, () => console.log('Everything cleaned up!'.green))
JavaScript
0.000004
@@ -82,22 +82,33 @@ t %7B -isSite, exists +exists, isSite, deleteDir %7D f @@ -434,21 +434,17 @@ %0A%7D%0A%0A -etc.deleteDir +fs.remove (con @@ -462,20 +462,39 @@ ir, -false, () =%3E +err =%3E %7B%0A if (err) throw err%0A con @@ -533,10 +533,12 @@ '.green) +%0A%7D )%0A
34595f8bf0f40e412ce2a2b7fc0865bec9ce43d4
Test against id search
test/app_test.js
test/app_test.js
var spawn = require('child_process').spawn , request = require('request'); describe('app', function() { var child; before(function(done) { child = spawn('node', ['app.js']); child.stdout.on('data', function(data) { setTimeout(done, 50); }); child.stderr.pipe(process.stderr); }); after(function(done) { child.on('exit', function() { done(); }); child.kill(); }); it('should have a home page', function(done) { request('http://localhost:3000/', function(err, resp, body) { resp.statusCode.should.equal(200); done(); }); }); it('looks up an id', function(done) { request({url:'http://localhost:3000/', json: {ids:['http://twitter.com/person']}}, function(err, resp, body) { resp.statusCode.should.equal(200); body.should.have.property('http://twitter.com/person'); body['http://twitter.com/person'].should.be.empty(); done(); }); }); });
JavaScript
0
@@ -757,16 +757,24 @@ st:3000/ +v0.1/ids ',%0A
ed4f0e57a9c569ef8116c51dd7662638b4f1cb10
Test uses _parentFolderPath property
tests/js/testNodeTransaction3.js
tests/js/testNodeTransaction3.js
(function($) { module("nodeTransaction3"); // Test case : Node Transaction 3 _asyncTest("Node Transaction 3", function() { expect(3); var gitana = GitanaTest.authenticateFullOAuth(); gitana.then(function() { // create a repository and get the master branch var branch = null; this.createRepository().readBranch("master").then(function() { branch = this; }); this.then(function() { // create a transaction // TODO: this syntax doesn't work var t = Gitana.transactions().create(); t.for(branch); // TEMP var t = Gitana.transactions().create(branch); // create the following hierarchy // // / // /folder1 // /folder2 // /file1.txt // /file2.txt // /folder3 // /file3.txt // /file4.txt t.create({ "title": "folder1", "_parentPath": "/" }); t.create({ "title": "folder2", "_parentPath": "/folder1" }); t.create({ "title": "file1.txt", "p1": "v1", "_parentPath": "/folder1/folder2" }); t.create({ "title": "file2.txt", "p1": "v1", "_parentPath": "/folder1/folder2" }); t.create({ "title": "folder3", "_parentPath": "/" }); t.create({ "title": "file3.txt", "_parentPath": "/folder3" }); t.create({ "title": "file4.txt", "_parentPath": "/" }); // callback for success t.success = function(results) { // now do some verification // find the two files (file1.txt and file2.txt, both which have property p1 == v1) Chain(branch).query({ "p1": "v1" }).each(function() { // for each, find the parent folder // should be 1 parent folder this.listRelatives({ "type": "n:node", "direction": "incoming" }).each(function() { ok(this.title == "folder2"); }); }).then(function() { success(); }); }; // commit t.commit(); }); }); var success = function() { start(); }; }); }(jQuery) );
JavaScript
0.000001
@@ -595,32 +595,34 @@ +// var t = Gitana.t @@ -661,16 +661,18 @@ +// t.for(br @@ -1214,32 +1214,38 @@ %22_parent +Folder Path%22: %22/%22%0A @@ -1346,32 +1346,38 @@ %22_parent +Folder Path%22: %22/folder1 @@ -1519,32 +1519,38 @@ %22_parent +Folder Path%22: %22/folder1 @@ -1700,32 +1700,38 @@ %22_parent +Folder Path%22: %22/folder1 @@ -1847,32 +1847,38 @@ %22_parent +Folder Path%22: %22/%22%0A @@ -1981,32 +1981,38 @@ %22_parent +Folder Path%22: %22/folder3 @@ -2098,24 +2098,24 @@ file4.txt%22,%0A - @@ -2130,16 +2130,22 @@ %22_parent +Folder Path%22: %22
d69f00b245afc65495abaf39102d3bae89f3d91e
Use standard node for bin
bin/mason.js
bin/mason.js
#!/usr/bin/env babel-node 'use strict' import Mason from '../lib/index' import Arguments from '../lib/cli/Arguments' try { let input = new Arguments(); Mason.run(input.command(), input.all()); } catch(e) { console.error('Error: ' + e.message); console.log(e.stack); } Mason.finally(() => { console.log(' '); });
JavaScript
0.000001
@@ -12,19 +12,13 @@ env -babel- node%0A + %0A'us @@ -32,26 +32,28 @@ t'%0A%0A -import +var Mason -from += require( '../ @@ -66,15 +66,14 @@ dex' -%0Aimport +);%0Avar Arg @@ -83,13 +83,18 @@ nts -from += require( '../ @@ -111,16 +111,18 @@ guments' +); %0A%0Atry %7B%0A @@ -126,11 +126,11 @@ %7B%0A%09 -let +var inp
86b77a2cca57d6ee6487f482ea6c63e77cd34c78
Update labs.js
js/labs.js
js/labs.js
;(function(win,doc,head,body){ if(!('addEventListener' in win)) return; win.z = function(a){ var x=a.data.length, b=0, c=doc.getElementById("repos"); c.removeAttribute("hidden"); for(;x>b;b++){ var e=doc.createElement("div"), f=a.data[b].homepage?a.data[b].homepage:a.data[b].html_url; e.className=(b%6===0?'cell cell-sm-12 cell-md-4 cell-lg-3 repo block':(b%5===0?'cell cell-sm-12 cell-md-6 cell-lg-7 block repo':'cell cell-sm-12 cell-md-6 cell-lg-5 block repo')); e.style.animationDelay=(win.Math.floor(win.Math.random()*500)+300)+'ms'; e.innerHTML='<a href="'+f+'" title="'+a.data[b].name+'"><h4>'+a.data[b].name+'</h4>'+'<small class="desc">'+a.data[b].description+'</small>'+'<small class="tags">'+a.data[b].language+'</small>'+'</a>'; c.appendChild(e); } }; win.addEventListener('load',handleLoad,false); loadStylesheets(['https://amdouglas.com/assets/css/fonts.css','https://amdouglas.com/assets/css/labs.css']); function loadStylesheets(urls){ for(var i = 0;i<urls.length;++i){ var css = doc.createElement('link'); css.rel = 'stylesheet'; css.href = urls[i]; head.appendChild(css); } } function loadScripts(urls){ for(var i = 0;i<urls.length;++i){ var js = doc.createElement('script'); js.async = !0; js.src = urls[i]; head.appendChild(js); } } function handleLoad(){ win.removeEventListener('load',handleLoad,false); loadScripts(['https://api.github.com/users/wnda/repos?callback=z','https://www.google-analytics.com/analytics.js']); if('devicePixelRatio' in win && win.devicePixelRatio > 1 && wdth < 992){ appendTouchIcons(); } if('serviceWorker' in navigator){ navigator.serviceWorker.register('https://amdouglas.com/sw.js', { scope: '/' }).then(function(registration){ console.info("SW registered [" + registration.scope + "]"); }).catch(function(err){ console.warn("SW failed to register [" + err + "]"); }); } win.GoogleAnalyticsObject = win.ga; win.ga = win.ga || function(){ for(var p = 0; p < arguments.length; ++p){ (win.ga.q = win.ga.q || []).push(arguments[p]); } }; win.ga.l = 1 * new Date(); win.ga('create','UA-70873652-1','auto'); win.ga('send','pageview'); } function appendTouchIcons(){ var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://amdouglas.com/manifest.json', true); xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status >= 200 && xhr.status < 300){ var data = JSON.parse(xhr.responseText); for(var j=0;j<data.icons.length;++j){ if(data.icons[j].src.indexOf('apple') > -1){ var icon = doc.createElement('link'); icon.rel = 'apple-touch-icon-precomposed'; icon.href = data.icons[j].src; icon.setAttribute('sizes', data.icons[j].sizes); head.appendChild(icon); } } } } }; xhr.send(); } })(window,window.document,window.document.head,window.document.body);
JavaScript
0.000001
@@ -912,32 +912,39 @@ heets(%5B'https:// +static. amdouglas.com/as @@ -964,32 +964,39 @@ s.css','https:// +static. amdouglas.com/as @@ -1750,24 +1750,26 @@ ;%0A %7D%0A +/* %0A if('ser @@ -1835,32 +1835,36 @@ gister('https:// +www. amdouglas.com/sw @@ -2103,24 +2103,26 @@ ;%0A %7D%0A +*/ %0A win.Goo @@ -2487,24 +2487,24 @@ pRequest();%0A - xhr.open @@ -2520,16 +2520,23 @@ https:// +static. amdougla
980252777fa9ed642b6694ef7ca1d564bb2e897a
Add correct duration params
src/selectors/fridge.js
src/selectors/fridge.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import moment from 'moment'; import { createSelector } from 'reselect'; import { UIDatabase } from '../database'; import { chunk } from '../utilities/chunk'; export const selectSelectedFridgeID = ({ fridge }) => { const { selectedFridge = {} } = fridge; const { id } = selectedFridge; return id; }; export const selectTemperatureLogsFromDate = ({ fridge }) => { const { fromDate } = fridge; return fromDate; }; export const selectTemperatureLogsToDate = ({ fridge }) => { const { toDate } = fridge; return toDate; }; export const selectSelectedFridge = createSelector([selectSelectedFridgeID], selectedFridgeID => { const selectedFridge = UIDatabase.get('Location', selectedFridgeID); return selectedFridge; }); export const selectFridgeTemperatureLogs = createSelector([selectSelectedFridge], fridge => { const { temperatureLogs = {} } = fridge ?? {}; return temperatureLogs.sorted?.('timestamp') ?? []; }); export const selectFridgeTemperatureLogsFromDate = createSelector( [selectFridgeTemperatureLogs, selectTemperatureLogsFromDate, selectTemperatureLogsToDate], (logs, fromDate, toDate) => { const temperatureLogs = logs?.filtered?.('timestamp >= $0 && timestamp =< $1', fromDate, toDate) ?? []; return temperatureLogs; } ); export const selectChunkedTemperatureLogs = createSelector( [selectFridgeTemperatureLogsFromDate], logs => { const { length: numberOfLogs } = logs; return numberOfLogs < 30 ? logs : chunk(logs, Math.ceil(numberOfLogs / 30)); } ); export const selectMinAndMaxLogs = createSelector([selectChunkedTemperatureLogs], logs => logs.reduce( (acc, logGroup) => { const temperatures = logGroup.map(({ temperature }) => temperature); const timestamps = logGroup.map(({ timestamp }) => timestamp); const maxTemperature = Math.max(...temperatures); const minTemperature = Math.min(...temperatures); const timestamp = Math.min(...timestamps); const { minLine, maxLine } = acc; return { minLine: [...minLine, { temperature: minTemperature, timestamp }], maxLine: [...maxLine, { temperature: maxTemperature, timestamp }], }; }, { minLine: [], maxLine: [] } ) ); export const selectMinAndMaxDomains = createSelector([selectMinAndMaxLogs], minAndMaxLogs => { const { minLine, maxLine } = minAndMaxLogs; return { minDomain: Math.min(...minLine.map(({ temperature }) => temperature)), maxDomain: Math.max(...maxLine.map(({ temperature }) => temperature)), }; }); export const selectBreaches = createSelector( [selectTemperatureLogsFromDate, selectTemperatureLogsToDate, selectSelectedFridge], (fromDate, toDate, fridge) => { const { breaches } = fridge ?? {}; const breachesInDateRange = breaches?.filtered( '(startTimestamp <= $0 && (endTimestamp <= $1 || endTimestamp == null)) || ' + '(startTimestamp >= $0 && endTimestamp <= $1)', fromDate, toDate ); const adjustedBreaches = breachesInDateRange.map(({ timestamp, id, temperature }) => ({ id, temperature, timestamp: moment(timestamp).isBefore(moment(fromDate)) ? fromDate : timestamp, })); return adjustedBreaches; } ); export const selectTimestampFormatter = createSelector( [selectTemperatureLogsFromDate, selectTemperatureLogsToDate], (fromDate, toDate) => { const durationInDays = moment(toDate).diff(moment(fromDate), 'day'); const justTime = 'HH:MM'; const dateAndTime = 'HH:MM - DD/MM'; const justDate = 'DD/MM'; const getTickFormat = format => tick => moment(tick).format(format); if (durationInDays <= 1) return getTickFormat(justTime); if (durationInDays <= 3) return getTickFormat(dateAndTime); return getTickFormat(justDate); } );
JavaScript
0.000007
@@ -3506,17 +3506,24 @@ e), 'day -' +s', true );%0A%0A
7447889ebaf7f7cb7bbf88b156f195d20907a91c
copy the found courses onto the children of <Student/>
src/screens/student.js
src/screens/student.js
import React, { Component, PropTypes, cloneElement } from 'react' import DocumentTitle from 'react-document-title' import { connect } from 'react-redux' import omit from 'lodash/object/omit' import Sidebar from './sidebar' import Loading from '../components/loading' import getStudentCourses from '../helpers/get-student-courses' import './student.scss' export class Student extends Component { static propTypes = { actions: PropTypes.object, areas: PropTypes.array, canRedo: PropTypes.bool, canUndo: PropTypes.bool, children: PropTypes.node.isRequired, // from react-router params: PropTypes.object, student: PropTypes.object, } constructor() { super() this.state = { courses: [], } } componentWillMount() { this.componentWillReceiveProps(this.props) } componentWillReceiveProps(nextProps) { if (nextProps.student) { window.stu = nextProps.student getStudentCourses(nextProps.student).then(courses => { this.setState({ courses: courses, }) return null }) } } componentWillUnmount() { delete window.stu } render() { // console.info('Student.render') if (!this.props.student) { return <Loading>{`Loading Student ${this.props.params.id}`}</Loading> } const childProps = omit(this.props, 'children') return ( <DocumentTitle title={`${this.props.student.name} | Gobbldygook`}> <div className='student'> <Sidebar {...childProps} /> {cloneElement(this.props.children, {...childProps, className: 'content'})} </div> </DocumentTitle> ) } } function mapStateToProps(state, ownProps) { // selects some state that is relevant to this component, and returns it. // redux-react will bind it to props. return { student: state.students.present[ownProps.params.id], } } export default connect(mapStateToProps)(Student)
JavaScript
0
@@ -1481,16 +1481,45 @@ ldProps, + courses: this.state.courses, classNa
422d71543128be2c0587eab5ad01f81cb708d0ff
Fix prelink script
src/scripts/prelink.js
src/scripts/prelink.js
var fs = require('fs'); var MANIFEST_PATH = process.cwd() + '/android/app/src/main/AndroidManifest.xml'; var PACKAGE_JSON = process.cwd() + '/package.json'; var hasNecessaryFile = fs.existsSync(MANIFEST_PATH) && fs.existsSync(MANIFEST_PATH); if (!hasNecessaryFile) { throw 'RNFetchBlob could not found link Android automatically, some files could not be found.' } var package = JSON.parse(fs.readFileSync(PACKAGE_JSON)); var APP_NAME = package.name; var APPLICATION_MAIN = process.cwd() + '/android/app/src/main/java/com/' + APP_NAME.toLocaleLowerCase() + '/MainApplication.java'; var PACKAGE_GRADLE = process.cwd() + '/node_modules/react-native-fetch-blob/android/build.gradle' var VERSION = checkVersion(); console.log('RNFetchBlob detected app version .. ' + VERSION); if(VERSION >= 0.29) { console.log('RNFetchBlob patching MainApplication.java .. '); if(!fs.existsSync(APPLICATION_MAIN)) { throw 'RNFetchBlob could not link Android automatically, MainApplication.java not found in path : ' + APPLICATION_MAIN } var main = fs.readFileSync(APPLICATION_MAIN); if(String(main).match('new RNFetchBlobPackage()') !== null) { console.log('skipped'); return } main = String(main).replace('new MainReactPackage()', 'new RNFetchBlobPackage(),\n new MainReactPackage()'); main = String(main).replace('import com.facebook.react.ReactApplication;', 'import com.facebook.react.ReactApplication;\nimport com.RNFetchBlob.RNFetchBlobPackage;') fs.writeFileSync(APPLICATION_MAIN, main); console.log('RNFetchBlob patching MainApplication.java .. ok') } if(VERSION < 0.28) { console.log('You project version is '+ VERSION + 'which does not meet requirement of react-native-fetch-blob 7.0+, please upgrade your application template to react-native 0.27+, otherwise Android application will not working.') add OkHttp3 dependency fo 0.28- project var main = fs.readFileSync(PACKAGE_GRADLE); console.log('adding OkHttp3 dependency to pre 0.28 project .. ') main = String(main).replace('//{RNFetchBlob_PRE_0.28_DEPDENDENCY}', "compile 'com.squareup.okhttp3:okhttp:3.4.1'"); fs.writeFileSync(PACKAGE_GRADLE, main); console.log('adding OkHttp3 dependency to pre 0.28 project .. ok') } // set file access permission for Android < 6.0 fs.readFile(MANIFEST_PATH, function(err, data) { if(err) console.log('failed to locate AndroidManifest.xml file, you may have to add file access permission manually.'); else { console.log('RNFetchBlob patching AndroidManifest.xml .. '); // append fs permission data = String(data).replace( '<uses-permission android:name="android.permission.INTERNET" />', '<uses-permission android:name="android.permission.INTERNET" />\n <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ' ) // append DOWNLOAD_COMPLETE intent permission data = String(data).replace( '<category android:name="android.intent.category.LAUNCHER" />', '<category android:name="android.intent.category.LAUNCHER" />\n <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>' ) fs.writeFileSync(MANIFEST_PATH, data); console.log('RNFetchBlob patching AndroidManifest.xml .. ok'); } }) function checkVersion() { console.log('RNFetchBlob checking app version ..'); return parseFloat(/\d\.\d+(?=\.)/.exec(package.dependencies['react-native'])); }
JavaScript
0.000001
@@ -1838,16 +1838,19 @@ ing.')%0A + // add OkH
2e5f12dfad2cb088c89e9d4f2bde1572250400b2
switch to prod
updateGroupsFromWordpress.js
updateGroupsFromWordpress.js
var fs = require('fs'), request = require('request-json'), argv = require('minimist')(process.argv.slice(2)); if (!argv.f) { console.log( "You must specify the JSON file that you want to merge with the -f flag!" ); process.exit() } fs.readFile(argv.f,{encoding:'utf-8'},function(err, data){ var staff_dir = JSON.parse(data); // Get Org descriptions from Wordpress and update the groups in the input JSON var client = request.createClient('http://godwit.lib.virginia.edu/'); client.get('api/get_recent_posts/?dev=1&count=0&post_type=uvalib_organization', function(err, res, body){ for (var i=0; i<body.posts.length; i++) { var post = body.posts[i]; if (post.additional_info && post.additional_info.my_groups_id && staff_dir.allGroups[post.additional_info.my_groups_id] ) { staff_dir.allGroups[post.additional_info.my_groups_id].wordpressId = post.id; staff_dir.allGroups[post.additional_info.my_groups_id].title = post.title; staff_dir.allGroups[post.additional_info.my_groups_id].description = post.content; staff_dir.allGroups[post.additional_info.my_groups_id].contactName = post.additional_info.contact_name; staff_dir.allGroups[post.additional_info.my_groups_id].contactEmail = post.additional_info.email_address; staff_dir.allGroups[post.additional_info.my_groups_id].children = post.children; } } // tell children groups about their parents for (var i=0; i<body.posts.length; i++) { var post = body.posts[i]; if (post.children) { var parent = post.id; for (var j=0; j<post.children.length; j++) { var child = post.children[j]; for (groupid in staff_dir.allGroups) { if (staff_dir.allGroups[groupid].wordpressId == child) { staff_dir.allGroups[groupid].parentId = parent; staff_dir.allGroups[groupid].parentName = post.title; } } } } } console.log( JSON.stringify(staff_dir) ); }); });
JavaScript
0.000001
@@ -465,18 +465,19 @@ p:// -godwit.lib +www.library .vir
451849f72393b9750d6b2b1d8e6fea600d995002
Fix tests
test/env-test.js
test/env-test.js
'use strict'; /*jshint node: true */ /*globals describe, it */ var _ = require('lodash'); var chai = require('chai'); var sinon = require('sinon'); var env = require('../lib/env'); var expect = chai.expect; describe('Infra Unit test for env', function () { var sandbox; beforeEach(function () { sandbox = sinon.sandbox.create(); }); afterEach(function () { sandbox.restore(); }); describe('getWorkingDirectory()', function () { it('should return working directory', function () { expect(env.getWorkingDirectory()).to.equal(process.cwd()); }); }); describe('getOS()', function () { it('should return windows', function () { sandbox.stub(process, 'platform', 'win32'); expect(env.getOS()).to.equal('windows'); }); it('should return mac', function () { sandbox.stub(process, 'platform', 'darwin'); expect(env.getOS()).to.equal('mac'); }); it('should return linux', function () { sandbox.stub(process, 'platform', 'linux'); expect(env.getOS()).to.equal('linux'); }); }); describe('getUserHome()', function () { it('should return windows home path', function () { sandbox.stub(process, 'platform', 'win32'); sandbox.stub(process, 'env', _.extend(process.env, { USERPROFILE: 'home_directory' })); expect(env.getUserHome()).to.equal('home_directory'); }); it('should return linux home path', function () { sandbox.stub(process, 'platform', 'linux'); sandbox.stub(process, 'env', _.extend(process.env, { HOME: 'home_directory' })); expect(env.getUserHome()).to.equal('home_directory'); }); }); describe('getOptions()', function () { it('should return an os option', function () { expect(env.getOptions()).to.have.property('os').that.equal(env.getOS()) }); }); });
JavaScript
0.000003
@@ -902,19 +902,22 @@ .equal(' -mac +darwin ');%0A
4f2650d694226649f01a3a0a37e34c598c046ec1
remove duplicate points display
tutor/src/screens/task/step/exercise-question.js
tutor/src/screens/task/step/exercise-question.js
import { React, PropTypes, observer, styled, action, observable, computed, modelize, runInAction, } from 'vendor'; import UX from '../ux'; import keymaster from 'keymaster'; import { StepFooter } from './footer'; import { Button } from 'react-bootstrap'; import { Question, AsyncButton } from 'shared'; import { StudentTaskStep } from '../../../models'; import QuestionModel from 'shared/model/exercise/question'; import { FreeResponseInput, FreeResponseReview } from './exercise-free-response'; import SavePracticeButton from '../../../components/buttons/save-practice'; import { breakpoint } from 'theme'; import ScoresHelper from '../../../helpers/scores'; const Footer = styled.div` margin: 2.5rem 0; display: flex; justify-content: space-between; font-size: 1.4rem; line-height: 2rem; button { width: 160px; } ${breakpoint.mobile` .controls { flex-grow: 1; } `} > * { width: 25%; } .points .attempts-left { color: #F36B32; } .controls { display: flex; justify-content: flex-end; flex-flow: column wrap-reverse; } .save-practice-button { margin-top: 2rem; } `; const StyledExerciseQuestion = styled.div` font-size: 2rem; line-height: 3.5rem; margin-left: 2rem; ${breakpoint.tablet` margin: ${breakpoint.margins.tablet}; `} ${breakpoint.mobile` margin: ${breakpoint.margins.mobile}; `} .openstax-answer { border-top: 1px solid #d5d5d5; margin: 10px 0; padding: 10px 0; } `; @observer export default class ExerciseQuestion extends React.Component { static propTypes = { ux: PropTypes.instanceOf(UX).isRequired, step: PropTypes.instanceOf(StudentTaskStep).isRequired, question: PropTypes.instanceOf(QuestionModel).isRequired, } @observable selectedAnswer = null; constructor(props) { super(props); modelize(this); window.eq = this; } @computed get needsSaved() { const { step } = this.props; return ( !step.is_completed || step.api.isPending || (this.answerId != step.answer_id) ); } componentDidMount() { keymaster('enter', 'multiple-choice', this.onEnter); } componentWillUnmount() { keymaster.unbind('enter', 'multiple-choice'); } @action.bound onEnter() { this.needsSaved && this.answerId ? this.onAnswerSave() : this.onNextStep(); } @action.bound onAnswerChange(answer) { const { ux, step } = this.props; ux.setCurrentMultiPartStep(step); this.selectedAnswer = answer; step.clearIncorrectFeedback(); } @action.bound async onAnswerSave() { const { ux, step } = this.props; ux.setCurrentMultiPartStep(step); await ux.onAnswerSave(step, this.selectedAnswer); runInAction(() => { this.selectedAnswer = null; }) } @action.bound onNextStep() { const { ux, step } = this.props; ux.onAnswerContinue(step); } @action.bound async addOrRemovePracticeQuestion() { if (this.practiceQuestion) { this.practiceQuestion.destroy(); } else { const { ux, step } = this.props; ux.course.practiceQuestions.create({ tasked_exercise_id: step.tasked_id }); } } @computed get answerId() { return this.selectedAnswer ? this.selectedAnswer.id : this.props.step.answer_id; } @computed get practiceQuestion() { const { ux, step } = this.props; return ux.course.practiceQuestions.findByExerciseId(step.exercise_id); } renderSaveButton() { const { step } = this.props; return ( <AsyncButton size="lg" waitingText="Saving…" disabled={!this.answerId} onClick={this.onAnswerSave} isWaiting={step.api.isPending} data-test-id="submit-answer-btn" > Submit </AsyncButton> ); } renderNextButton() { const { canUpdateCurrentStep } = this.props.ux; return ( <Button size="lg" onClick={this.onNextStep} data-test-id="continue-btn"> {canUpdateCurrentStep ? 'Continue' : 'Next'} </Button> ); } renderMultipleAttempts(step) { const word = 'attempt'; const count = step.attempts_remaining; return ( <div>{count} {word}{count === 1 ? '' : 's'} left</div> ); } render() { const { ux, question, step, ux: { course } } = this.props; const questionNumber = ux.questionNumberForStep(step); if (step.canEditFreeResponse) { return ( <FreeResponseInput step={step} question={question} questionNumber={questionNumber} taskUX={ux} key={question.id} course={course} /> ); } return ( <StyledExerciseQuestion data-test-id="student-exercise-question"> <Question task={ux.task} question={question} choicesEnabled={!ux.isReadOnly && step.canAnswer} answer_id={this.answerId} focus={!step.multiPartGroup} questionNumber={questionNumber} onChange={this.onAnswerChange} feedback_html={step.feedback_html} correct_answer_feedback_html={step.correct_answer_feedback_html} hasCorrectAnswer={step.hasCorrectAnswer} correct_answer_id={step.is_completed ? step.correct_answer_id : null} incorrectAnswerId={step.incorrectAnswerId} > <FreeResponseReview course={course} step={step} /> </Question> <Footer> <div className="points"> <strong>Points: {ScoresHelper.formatPoints(step.available_points)}</strong> <span className="attempts-left">{ux.hasMultipleAttempts && this.renderMultipleAttempts(step)}</span> </div> <div className="controls"> {step.canAnswer && this.needsSaved ? this.renderSaveButton() : this.renderNextButton()} {ux.canSaveToPractice && ( <SavePracticeButton practiceQuestions={ux.course.practiceQuestions} taskStep={step} />)} </div> </Footer> <StepFooter course={course} step={step} /> </StyledExerciseQuestion> ); } }
JavaScript
0.000002
@@ -612,60 +612,8 @@ me'; -%0Aimport ScoresHelper from '../../../helpers/scores'; %0A%0Aco @@ -6041,108 +6041,8 @@ s%22%3E%0A - %3Cstrong%3EPoints: %7BScoresHelper.formatPoints(step.available_points)%7D%3C/strong%3E%0A
fb844cc3db94af6ec33d25d1d09bdc30c3c9623b
Replace redirect to pipe image to res, to support MultiMC
Routes/API/Skin/File.js
Routes/API/Skin/File.js
/** * Created by Indexyz on 2017/4/15. */ 'use strict'; const db = require('mongoose'); const grid = require('gridfs-stream'); const profileService = require("../../../Db/Service/profileService"); const userService = require("../../../Db/Service/userService"); grid.mongo = db.mongo; module.exports.get = (req, res, next) => { if (!req.params.fileId || req.params.fileId === "undefined"){ return res.status(404).send(); } res.redirect('/resources/' + req.params.fileId) }; let getSkin = (username, func) => { profileService.getProfileByUserName(username, profile => { if (!profile) { return func(new Error("user not found")) } userService.getProfileOwner(profile._id, user => { func(null, user.skin) }) }); }; module.exports.getSkin = (req, res, next) => { getSkin(req.params.username, (err, doc) => { if (err) { return res.sendStatus(404) } res.redirect('/resources/' + doc.skin) }) }; module.exports.getSkinByUUID = (req, res, next) => { profileService.getProfileByProfileId(req.params.profileId, profile => { if (!profile){ res.redirect("https://public.hyperworld.xyz/Gamer/Minecraft/public.png") } else { userService.getProfileOwner(profile._id, user => { if (!user.skin.skin){ return res.redirect("https://public.hyperworld.xyz/Gamer/Minecraft/public.png") } res.redirect('/resources/' + user.skin.skin) }) } }) }; module.exports.getCup = (req, res, next) => { getSkin(req.params.username, (err, doc) => { if (err) { return res.sendStatus(404) } res.redirect('/resources/' + doc.cap) }) };
JavaScript
0
@@ -1470,51 +1470,473 @@ -res.redirect('/resources/' + user.skin.skin +let gfs = grid(db.connection.db);%0A gfs.exist(%7B%0A _id: db.Types.ObjectId(user.skin.skin)%0A %7D, (err, found) =%3E %7B%0A if (!found %7C%7C err) %7B res.status(404).send(); return %7D%0A // res.setHeader(%22Content-disposition%22, %22attachment;%22);%0A gfs.createReadStream(%7B%0A _id: db.Types.ObjectId(user.skin.skin)%0A %7D).pipe(res);%0A %7D )%0A
c41eeb1ebadf0c13eeffc7b9e27c0327f444b2a0
Fix markdown handling
usability/python-markdown.js
usability/python-markdown.js
// Allow Python-code in markdown cells // Encapsulate using {{...}} // - You can also return html or markdown from your Python code // - You can embed images, however they will be sanitized on reload. "using strict"; var python_markdown_extension = (function() { var security = IPython.security; var execute_python = function(cell,text) { // search for code in double curly braces: {{}} text = text.replace(/{{(.*?)}}/g, function(match,tag,cha) { var code = tag; var id = 'python_'+cell.cell_id+'_'+cha; var thiscell = cell; var thismatch = tag; /* there a two possible options: a) notebook dirty: execute b) notebook clean: only display */ if (IPython.notebook.dirty == true) { cell.metadata.variables = {}; this.callback = function (out_data) { var has_math = false; var ul = out_data.content.data; if (ul != undefined) { if ( ul['image/jpeg'] != undefined) { var jpeg = ul['image/jpeg']; var result = '<img src="data:image/jpeg;base64,'+ jpeg + '"/>'; } else if ( ul['image/png'] != undefined) { var png = ul['image/png']; var result = '<img src="data:image/png;base64,'+ png + '"/>'; } else if ( ul['text/html'] != undefined) { var result = ul['text/html']; } else if ( ul['text/latex'] != undefined) { var result = ul['text/latex']; has_math = true; } else { var result = (ul['text/plain']); // we could also use other MIME types here ? } thiscell.metadata.variables[thismatch] = result; var html = marked.parser(marked.lexer(result)); var el = document.getElementById(id); el.innerHTML = el.innerHTML + html; // output result if (has_math == true) MathJax.Hub.Queue(["Typeset",MathJax.Hub,el]); } } var callbacks = { iopub : { output: callback } }; if (IPython.notebook.kernel != null) { IPython.notebook.kernel.execute(code, callbacks, {silent: false}); return "<span id='"+id+"'></span>"; // add HTML tag with ID where output will be placed }; return match; } else { /* Notebook not dirty: replace tags with metadata */ var val = cell.metadata.variables[tag]; return "<span id='"+id+"'>"+val+"</span>"; } }); return text; }; // Override original markdown render function */ IPython.MarkdownCell.prototype.render = function () { var cont = IPython.TextCell.prototype.render.apply(this); cont = cont || (this.metadata.variables == undefined) || (Object.keys(this.metadata.variables).length > 0); if (cont) { var text = this.get_text(); var math = null; if (text === "") { text = this.placeholder; } text = execute_python(this,text); var text_and_math = IPython.mathjaxutils.remove_math(text); text = text_and_math[0]; math = text_and_math[1]; var html = marked.parser(marked.lexer(text)); html = IPython.mathjaxutils.replace_math(html, math); html = security.sanitize_html(html); html = $($.parseHTML(html)); // links in markdown cells should open in new tabs html.find("a[href]").not('[href^="#"]').attr("target", "_blank"); this.set_rendered(html); this.element.find('div.input_area').hide(); this.element.find("div.text_cell_render").show(); this.typeset(); } return cont; }; /* show values stored in metadata on reload */ doit = function() { var ncells = IPython.notebook.ncells() var cells = IPython.notebook.get_cells(); for (var i=0; i<ncells; i++) { var cell=cells[i]; if ( (cell.metadata.variables != undefined) && Object.keys(cell.metadata.variables).length > 0) { cell.render(); } }; } $([IPython.events]).on('status_started.Kernel',doit); })();
JavaScript
0.000001
@@ -1207,38 +1207,36 @@ var -result +html = '%3Cimg src=%22da @@ -1429,22 +1429,20 @@ var -result +html = '%3Cimg @@ -1576,38 +1576,36 @@ var -result +html = ul%5B'text/html @@ -1709,22 +1709,20 @@ var -result +html = ul%5B't @@ -1946,82 +1946,158 @@ -%7D%0A thiscell.metadata.variables%5Bthismatch%5D = result; + html = marked(result);%0A var t = html.match(/%3Cp%3E(.*?)%3C%5C/p%3E/)%5B1%5D; //strip %3Cp%3E and %3C/p%3E that marked adds and we don't want %0A @@ -2113,35 +2113,35 @@ -var + html = marked.parse @@ -2132,43 +2132,117 @@ l = -marked.parser(marked.lexer(result)) +t ? t : html;%0A %7D%0A thiscell.metadata.variables%5Bthismatch%5D = html ;%0A