commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
995b6f66277d34bf19a6081b3d1fce62b5d61bd8
src/spec/preprocess_test.js
src/spec/preprocess_test.js
(function() { module('gpub.spec.preprocess'); test('Preprocess grouping', function() { var cache = new gpub.util.MoveTreeCache(); var sgf = '(;GM[1]AW[aa]AB[ba];B[bb]C[The End!])'; var o = new gpub.Options({ sgfs: [sgf], ids: ['z1'], grouping: { title: 'foo', description: 'bar', positionType: 'PROBLEM', positions: [ 'z1', ], } }, cache); var spec = gpub.spec.create(o); var gr = spec.rootGrouping; deepEqual(gr.title, o.grouping.title, 'title'); deepEqual(gr.description, o.grouping.description, 'description'); deepEqual(gr.positionType, o.grouping.positionType, 'description'); }) })();
(function() { module('gpub.spec.preprocess'); test('Preprocess grouping', function() { var cache = new gpub.util.MoveTreeCache(); var sgf = '(;GM[1]AW[aa]AB[ba];B[bb]C[The End!])'; var o = new gpub.Options({ sgfs: [sgf], ids: ['z1'], grouping: { title: 'foo', description: 'bar', positionType: 'PROBLEM', positions: [ 'z1', ], } }, cache); var spec = gpub.spec.create(o); var gr = spec.rootGrouping; deepEqual(gr.title, o.grouping.title, 'title'); deepEqual(gr.description, o.grouping.description, 'description'); deepEqual(gr.positionType, o.grouping.positionType, 'description'); }) test('Preprocess grouping', function() { var cache = new gpub.util.MoveTreeCache(); var sgf = '(;GM[1]AW[aa]AB[ba];B[bb]C[The End!])'; var o = new gpub.Options({ sgfs: [sgf, sgf], ids: ['z1', 'z2'], grouping: { title: 'foo', description: 'bar', positionType: 'PROBLEM', positions: [ 'z1' ], groupings: [{ title: 'bar', positions: [ 'z1' ], }, { title: 'biff', positions: [ 'z2' ], }] } }, cache); var spec = gpub.spec.create(o); var gr = spec.rootGrouping; deepEqual(gr.title, o.grouping.title, 'title'); deepEqual(gr.description, o.grouping.description, 'description'); deepEqual(gr.positionType, o.grouping.positionType, 'description'); deepEqual(gr.groupings.length, 2); deepEqual(gr.groupings[0].title, 'bar'); deepEqual(gr.groupings[0].positions[0].alias, 'z1'); deepEqual(gr.groupings[1].title, 'biff'); deepEqual(gr.groupings[1].positions[0].alias, 'z2'); }) })();
Add a test for pre-processing nested structures.
Add a test for pre-processing nested structures.
JavaScript
mit
Kashomon/gpub,Kashomon/gpub,Kashomon/gpub
--- +++ @@ -22,4 +22,37 @@ deepEqual(gr.description, o.grouping.description, 'description'); deepEqual(gr.positionType, o.grouping.positionType, 'description'); }) + + test('Preprocess grouping', function() { + var cache = new gpub.util.MoveTreeCache(); + var sgf = '(;GM[1]AW[aa]AB[ba];B[bb]C[The End!])'; + var o = new gpub.Options({ + sgfs: [sgf, sgf], + ids: ['z1', 'z2'], + grouping: { + title: 'foo', + description: 'bar', + positionType: 'PROBLEM', + positions: [ 'z1' ], + groupings: [{ + title: 'bar', + positions: [ 'z1' ], + }, { + title: 'biff', + positions: [ 'z2' ], + }] + } + }, cache); + var spec = gpub.spec.create(o); + var gr = spec.rootGrouping; + deepEqual(gr.title, o.grouping.title, 'title'); + deepEqual(gr.description, o.grouping.description, 'description'); + deepEqual(gr.positionType, o.grouping.positionType, 'description'); + + deepEqual(gr.groupings.length, 2); + deepEqual(gr.groupings[0].title, 'bar'); + deepEqual(gr.groupings[0].positions[0].alias, 'z1'); + deepEqual(gr.groupings[1].title, 'biff'); + deepEqual(gr.groupings[1].positions[0].alias, 'z2'); + }) })();
e52d1ead0f7ec36b3c18c8984c2d9f40fb78f557
scripts/console.js
scripts/console.js
define(['jquery'], function ($) { var colors = { log: '#000000', warn: '#cc9900', error: '#cc0000' }; var log = $('#log'); if (!console) { console = {}; } for (var name in colors) { console[name] = (function (original, color) { return function () { original.apply(console, arguments); var line = $('<div>'); log.append(line); for (var i = 0; i < arguments.length; i++) { var section = $('<span>'); section.text(arguments[i]); line.append(section); line.css('color', color); } }; })(console[name] || function() {}, colors[name]); } return console; });
define(['jquery'], function ($) { var stringify = function (x) { try { if (typeof x != 'object' || x instanceof String || x instanceof Number) { return x.toString(); } if (x instanceof Array) { return '[' + x.map(stringify).join(', ') + ']'; } if (x.length && x.length >= 0 && x.length == Math.floor(x.length)) { return stringify(Array.prototype.slice.call(x)); } if (x instanceof HTMLElement) { return '<' + x.tagName + ' ...>'; } return x.toString(); } catch (e) { return '' + x; } }; var colors = { log: '#000000', warn: '#cc9900', error: '#cc0000' }; var log = $('#log'); if (!console) { console = {}; } for (var name in colors) { console[name] = (function (original, color) { return function () { original.apply(console, arguments); var line = $('<div>'); log.append(line); for (var i = 0; i < arguments.length; i++) { var section = $('<span>'); section.text(stringify(arguments[i])); line.append(section); line.css('color', color); } }; })(console[name] || function() {}, colors[name]); } return console; });
Convert arguments to text before writing them out.
Convert arguments to text before writing them out.
JavaScript
mit
configurator/billbill,configurator/billbill
--- +++ @@ -1,4 +1,34 @@ define(['jquery'], function ($) { + var stringify = function (x) { + try { + if (typeof x != 'object' + || x instanceof String + || x instanceof Number) { + return x.toString(); + } + + if (x instanceof Array) { + return '[' + + x.map(stringify).join(', ') + + ']'; + } + + if (x.length + && x.length >= 0 + && x.length == Math.floor(x.length)) { + return stringify(Array.prototype.slice.call(x)); + } + + if (x instanceof HTMLElement) { + return '<' + x.tagName + ' ...>'; + } + + return x.toString(); + } catch (e) { + return '' + x; + } + }; + var colors = { log: '#000000', warn: '#cc9900', @@ -19,7 +49,7 @@ log.append(line); for (var i = 0; i < arguments.length; i++) { var section = $('<span>'); - section.text(arguments[i]); + section.text(stringify(arguments[i])); line.append(section); line.css('color', color); }
92fb0fea29bd8187256f8699f7422c8f3344cf2f
spec/variable-declarations-spec.js
spec/variable-declarations-spec.js
/* * Copyright (c) 2016 Steven Soloff * * This is free software: you can redistribute it and/or modify it under the * terms of the MIT License (https://opensource.org/licenses/MIT). * This software comes with ABSOLUTELY NO WARRANTY. */ 'use strict' const linting = require('./support/test-util').linting const source = require('./support/test-util').source describe('Linting variable declarations', () => { it('should report a violation when var declarations are not first in function scope', () => { const text = source([ 'while (1) {', ' var foo = 1;', ' foo;', '}' ]) expect(linting(text)).toReportViolationForRule('vars-on-top') }) it('should not report a violation when var declarations are first in function scope', () => { const text = source([ 'var foo = 1;', 'while (1) {', ' foo;', '}' ]) expect(linting(text)).toNotReportViolation() }) })
/* * Copyright (c) 2016 Steven Soloff * * This is free software: you can redistribute it and/or modify it under the * terms of the MIT License (https://opensource.org/licenses/MIT). * This software comes with ABSOLUTELY NO WARRANTY. */ 'use strict' const linting = require('./support/test-util').linting const source = require('./support/test-util').source describe('Linting variable declarations', () => { it('should report a violation when var declarations are not first in scope', () => { const text = source([ 'while (1) {', ' var foo = 1;', ' foo;', '}' ]) expect(linting(text)).toReportViolationForRule('vars-on-top') }) it('should not report a violation when var declarations are first in scope', () => { const text = source([ 'var foo = 1;', 'while (1) {', ' foo;', '}' ]) expect(linting(text)).toNotReportViolation() }) it('should not report a violation when multiple var declarations are used in same scope', () => { const text = source([ 'var foo = 1;', 'var bar = 2;', 'while (foo) {', ' bar;', '}' ]) expect(linting(text)).toNotReportViolation() }) })
Allow multiple var declarations per scope
Allow multiple var declarations per scope The Crockford style guide explicitly uses multiple var declarations as an example. However, the JSCS Crockford style config explicitly disallows multiple var declarations. I'll revisit in the future if it turns out this is required.
JavaScript
mit
ssoloff/eslint-config-crockford
--- +++ @@ -12,7 +12,7 @@ const source = require('./support/test-util').source describe('Linting variable declarations', () => { - it('should report a violation when var declarations are not first in function scope', () => { + it('should report a violation when var declarations are not first in scope', () => { const text = source([ 'while (1) {', ' var foo = 1;', @@ -22,7 +22,7 @@ expect(linting(text)).toReportViolationForRule('vars-on-top') }) - it('should not report a violation when var declarations are first in function scope', () => { + it('should not report a violation when var declarations are first in scope', () => { const text = source([ 'var foo = 1;', 'while (1) {', @@ -31,4 +31,15 @@ ]) expect(linting(text)).toNotReportViolation() }) + + it('should not report a violation when multiple var declarations are used in same scope', () => { + const text = source([ + 'var foo = 1;', + 'var bar = 2;', + 'while (foo) {', + ' bar;', + '}' + ]) + expect(linting(text)).toNotReportViolation() + }) })
cfbf2b47636695609ecdecbaf8ddad386025d11d
src/services/socket.js
src/services/socket.js
import socketio from 'socket.io-client' import log from 'services/log' import foodsharing from 'services/foodsharing' export let io = null export const subscribers = [] export default { /* * Subscribe to the websocket receive all messages * Returns an unsubscribe function */ subscribe (fn) { subscribers.push(fn) return () => { let idx = subscribers.indexOf(fn) if (idx !== -1) subscribers.splice(idx, 1) } }, /* * Connects to the socket.io socket if not already * Returns a promise that resolves when connected */ connect () { if (io) return Promise.resolve() return new Promise((resolve, reject) => { io = socketio({ path: '/foodsharing/socket' }) io.on('connect', () => { io.emit('register') log.info('connected to websocket!') resolve() }) io.on('conv', data => { if (!data.o) return log.info('recv', data) let message = foodsharing.convertMessage(JSON.parse(data.o)) subscribers.forEach(fn => fn(message)) }) }) }, /* * Disconnect from socket.io */ disconnect () { if (!io) return io.disconnect() io = null } }
import socketio from 'socket.io-client' import log from 'services/log' import foodsharing from 'services/foodsharing' export let io = null export const subscribers = [] export default { /* * Subscribe to the websocket receive all messages * Returns an unsubscribe function */ subscribe (fn) { subscribers.push(fn) return () => { let idx = subscribers.indexOf(fn) if (idx !== -1) subscribers.splice(idx, 1) } }, /* * Connects to the socket.io socket if not already * Returns a promise that resolves when connected */ connect () { if (io) return Promise.resolve() return new Promise((resolve, reject) => { io = socketio({ path: '/foodsharing/socket' }) io.on('connect', () => { io.emit('register') log.info('connected to websocket!') resolve() }) io.on('conv', data => { if (!data.o) return let message = foodsharing.convertMessage(JSON.parse(data.o)) subscribers.forEach(fn => fn(message)) }) }) }, /* * Disconnect from socket.io */ disconnect () { if (!io) return io.disconnect() io = null } }
Remove a bit of logging
Remove a bit of logging
JavaScript
mit
foodsharing-dev/foodsharing-light,foodsharing-dev/foodsharing-light,foodsharing-dev/foodsharing-light
--- +++ @@ -35,7 +35,6 @@ }) io.on('conv', data => { if (!data.o) return - log.info('recv', data) let message = foodsharing.convertMessage(JSON.parse(data.o)) subscribers.forEach(fn => fn(message)) })
00fe5c502fa715eeb1ac6707b1cffddcccf47585
tests/image.spec.js
tests/image.spec.js
var expect = require('chai').expect; var validator = require('../'); describe('Image Validator', function() { var rules = { imageInput: ['image'] }; it('should fail on non image type', function() { var result = validator.validate(rules, { imageInput: 'README.md' }); expect(result.success).to.equals(false); expect(result.messages.imageInput.image).to.equals('Image Input must be an image.'); }); it('should success on image type', function() { var result = validator.validate(rules, { imageInput: 'tests/fixtures/dummyimg.jpeg' }); expect(result.success).to.equals(true); }); });
var expect = require('chai').expect; var validator = require('../'); describe('Image Validator', function() { var rules = { imageInput: ['image'] }; it('should fail on non image type', function() { var result = validator.validate(rules, { imageInput: 'README.md' }); expect(result.success).to.equals(false); expect(result.messages.imageInput.image).to.equals('Image Input must be an image.'); }); it('should success on image type', function() { var result = validator.validate(rules, { imageInput: 'tests/fixtures/dummyimg.jpeg' }); expect(result.success).to.equals(true); }); it('should fail on non image type (object input)', function() { var result = validator.validate(rules, { imageInput: {path: 'README.md'} }); expect(result.success).to.equals(false); expect(result.messages.imageInput.image).to.equals('Image Input must be an image.'); }); it('should success on image type (object input)', function() { var result = validator.validate(rules, { imageInput: {path: 'tests/fixtures/dummyimg.jpeg'} }); expect(result.success).to.equals(true); }); });
Add tests for object input (image rule)
Add tests for object input (image rule)
JavaScript
mit
cermati/satpam,sendyhalim/satpam
--- +++ @@ -22,4 +22,21 @@ expect(result.success).to.equals(true); }); + + it('should fail on non image type (object input)', function() { + var result = validator.validate(rules, { + imageInput: {path: 'README.md'} + }); + + expect(result.success).to.equals(false); + expect(result.messages.imageInput.image).to.equals('Image Input must be an image.'); + }); + + it('should success on image type (object input)', function() { + var result = validator.validate(rules, { + imageInput: {path: 'tests/fixtures/dummyimg.jpeg'} + }); + + expect(result.success).to.equals(true); + }); });
24ad973b558b09623e0642956255296f3df1284f
routes/site_router.js
routes/site_router.js
"use strict"; /* global process */ /******************************************************************************* * Copyright (c) 2015 IBM Corp. * * All rights reserved. * * Contributors: * David Huffman - Initial implementation *******************************************************************************/ var express = require('express'); var router = express.Router(); var base64 = require('base64-js'); var fs = require("fs"); // Load our modules. var aux = require("./site_aux.js"); var rest = require("../utils/rest.js"); var b64 = require("../utils/b64.js"); // ============================================================================================================================ // Home // ============================================================================================================================ router.route("/").get(function(req, res){ var cc = {}; try{ cc = require('../utils/temp/cc.json'); } catch(e){ console.log('error loading cc.json', e); }; res.render('home', {title: 'Home', bag: cc} ); }); // ============================================================================================================================ // Chain Code Investigator // ============================================================================================================================ router.route("/investigate").get(function(req, res){ var cc = {}; try{ cc = require('../utils/temp/cc.json'); } catch(e){ console.log('error loading cc.json', e); }; res.render('investigate', {title: 'Investigator', bag: cc} ); }); module.exports = router;
"use strict"; /* global process */ /******************************************************************************* * Copyright (c) 2015 IBM Corp. * * All rights reserved. * * Contributors: * David Huffman - Initial implementation *******************************************************************************/ var express = require('express'); var router = express.Router(); var base64 = require('base64-js'); var fs = require("fs"); // Load our modules. var aux = require("./site_aux.js"); var rest = require("../utils/rest.js"); var b64 = require("../utils/b64.js"); // ============================================================================================================================ // Home // ============================================================================================================================ router.route("/old").get(function(req, res){ var cc = {}; try{ cc = require('../utils/temp/cc.json'); } catch(e){ console.log('error loading cc.json', e); }; res.render('home', {title: 'Home', bag: cc} ); }); // ============================================================================================================================ // Chain Code Investigator // ============================================================================================================================ router.route("/").get(function(req, res){ var cc = {}; try{ cc = require('../utils/temp/cc.json'); } catch(e){ console.log('error loading cc.json', e); }; res.render('investigate', {title: 'Investigator', bag: cc} ); }); module.exports = router;
Change it so / has the latest, greatest view.
Change it so / has the latest, greatest view.
JavaScript
apache-2.0
IBM-Blockchain/marbles,furuya-s/marbles,Serarmen/marbles,Serarmen/marbles,BlockChainPublicDemos/karachain-app-team2,JSakchai/KYC-Agent,DIACC/POC-corporate-registries,raphael-hoed/IFNMG-CERTIFICADOS,vmd90/marbles,furuya-s/marbles,dhyey20/cp-web,sj1chun/marbles,IBM-Blockchain/marbles,jparth11/marbles,swetabachhety/ekyc,sj1chun/marbles,IBM-Blockchain/marbles,jparth11/marbles,pedrocervantes/cp-web,vmd90/marbles,BlockChainPublicDemos/karachain-app-team2,furuya-s/marbles,mastersingh24/cp-web,dhyey20/cp-web,mastersingh24/cp-web,pedrocervantes/cp-web,Serarmen/marbles,mastersingh24/cp-web,IBM-Blockchain/marbles,JSakchai/KYC-Agent,sj1chun/marbles,jparth11/marbles,DIACC/POC-corporate-registries,DIACC/POC-corporate-registries,raphael-hoed/IFNMG-CERTIFICADOS,JSakchai/KYC-Agent,dhyey20/cp-web,BlockChainPublicDemos/karachain-app-team2,dhyey20/cp-web,vmd90/marbles,swetabachhety/ekyc,pedrocervantes/cp-web,pedrocervantes/cp-web,swetabachhety/ekyc
--- +++ @@ -22,7 +22,7 @@ // ============================================================================================================================ // Home // ============================================================================================================================ -router.route("/").get(function(req, res){ +router.route("/old").get(function(req, res){ var cc = {}; try{ cc = require('../utils/temp/cc.json'); @@ -37,7 +37,7 @@ // ============================================================================================================================ // Chain Code Investigator // ============================================================================================================================ -router.route("/investigate").get(function(req, res){ +router.route("/").get(function(req, res){ var cc = {}; try{ cc = require('../utils/temp/cc.json');
f2c21c1915a214ffa2ac0730631ce36988592dfc
unit_tests/sprite_spec.js
unit_tests/sprite_spec.js
'use strict'; GJS.Sprite.gfxPath = '../examples/assets/gfx/'; describe('Sprite', function() { it('can be used before it is loaded', function() { var s = new GJS.Sprite('carrot.png'); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); s.draw(ctx, 0, 0); s.drawRotated(ctx, 0, 0, 0); s.drawRotatedNonUniform(ctx, 0, 0, 0, 0, 0); expect(s.loaded).toBe(false); }); it('maintains a counter of loaded objects', function() { var s; runs(function() { s = new GJS.Sprite('carrot.png'); expect(GJS.Sprite.loadedFraction()).toBe(0); }); waitsFor(function() { return s.loaded; }); runs(function() { expect(GJS.Sprite.loadedFraction()).toBe(1); }); }); });
'use strict'; GJS.Sprite.gfxPath = '../examples/assets/gfx/'; describe('Sprite', function() { it('maintains a counter of loaded objects', function() { var s; runs(function() { s = new GJS.Sprite('carrot.png'); expect(GJS.Sprite.loadedFraction()).toBeLessThan(1); }); waitsFor(function() { return s.loaded; }); runs(function() { expect(GJS.Sprite.loadedFraction()).toBe(1); }); }); it('can be used before it is loaded', function() { var s = new GJS.Sprite('carrot.png'); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); s.draw(ctx, 0, 0); s.drawRotated(ctx, 0, 0, 0); s.drawRotatedNonUniform(ctx, 0, 0, 0, 0, 0); expect(s.loaded).toBe(false); }); });
Make sprite unit tests more robust
Make sprite unit tests more robust
JavaScript
mit
Oletus/gameutils.js,Oletus/gameutils.js
--- +++ @@ -3,6 +3,17 @@ GJS.Sprite.gfxPath = '../examples/assets/gfx/'; describe('Sprite', function() { + it('maintains a counter of loaded objects', function() { + var s; + runs(function() { + s = new GJS.Sprite('carrot.png'); + expect(GJS.Sprite.loadedFraction()).toBeLessThan(1); + }); + waitsFor(function() { return s.loaded; }); + runs(function() { + expect(GJS.Sprite.loadedFraction()).toBe(1); + }); + }); it('can be used before it is loaded', function() { var s = new GJS.Sprite('carrot.png'); var canvas = document.createElement('canvas'); @@ -12,15 +23,4 @@ s.drawRotatedNonUniform(ctx, 0, 0, 0, 0, 0); expect(s.loaded).toBe(false); }); - it('maintains a counter of loaded objects', function() { - var s; - runs(function() { - s = new GJS.Sprite('carrot.png'); - expect(GJS.Sprite.loadedFraction()).toBe(0); - }); - waitsFor(function() { return s.loaded; }); - runs(function() { - expect(GJS.Sprite.loadedFraction()).toBe(1); - }); - }); });
7f6a95fef44579330a63c359892b8b5d50e624f2
spec/index_spec.js
spec/index_spec.js
var path = require('path'); var childProcess = require('child_process'); function gulp(task) { return childProcess.execSync([ 'node_modules/.bin/gulp', '--gulpfile', path.resolve(__dirname, 'fixtures', 'gulpfile.js'), task ].join(' '), {encoding: 'utf8'}); } describe('gulp-jasmine-browser', function() { it('works', function() { expect(gulp('dummy')).toContain('2 specs, 1 failure'); }); });
var path = require('path'); var childProcess = require('child_process'); function gulp(task, callback) { return childProcess.exec([ 'node_modules/.bin/gulp', '--gulpfile', path.resolve(__dirname, 'fixtures', 'gulpfile.js'), task ].join(' '), {encoding: 'utf8'}, callback); } describe('gulp-jasmine-browser', function() { it('works', function(done) { gulp('dummy', function(error, stdout) { expect(stdout).toContain('2 specs, 1 failure'); done(); }); }); });
Stop using execSync for compatibility with Node 0.10
Stop using execSync for compatibility with Node 0.10 Signed-off-by: Nicole Sullivan <4ab7e2960369063855aad4ef791fa27066322d72@pivotal.io>
JavaScript
mit
jasmine/gulp-jasmine-browser,mdix/gulp-jasmine-browser,AOEpeople/gulp-jasmine-browser
--- +++ @@ -1,16 +1,19 @@ var path = require('path'); var childProcess = require('child_process'); -function gulp(task) { - return childProcess.execSync([ +function gulp(task, callback) { + return childProcess.exec([ 'node_modules/.bin/gulp', '--gulpfile', path.resolve(__dirname, 'fixtures', 'gulpfile.js'), task - ].join(' '), {encoding: 'utf8'}); + ].join(' '), {encoding: 'utf8'}, callback); } describe('gulp-jasmine-browser', function() { - it('works', function() { - expect(gulp('dummy')).toContain('2 specs, 1 failure'); + it('works', function(done) { + gulp('dummy', function(error, stdout) { + expect(stdout).toContain('2 specs, 1 failure'); + done(); + }); }); });
e2ef7b3589371e4a41d6dfca1f44fac4c9148521
test/load-json-spec.js
test/load-json-spec.js
/* global require, describe, it */ var assert = require('assert'); var urlPrefix = 'http://katas.tddbin.com/katas/es6/language/'; var katasUrl = urlPrefix + '__grouped__.json'; var GroupedKata = require('../src/grouped-kata.js'); describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { function onSuccess(groupedKatas) { assert.ok(groupedKatas); done(); } new GroupedKata(katasUrl).load(function() {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { function onError(err) { assert.ok(err); done(); } var invalidUrl = urlPrefix; new GroupedKata(invalidUrl).load(onError); }); it('for invalid data', function(done) { function onError(err) { assert.ok(err); done(); } var invalidData = urlPrefix + '__all__.json'; new GroupedKata(invalidData).load(onError); }); }); });
/* global require, describe, it */ import assert from 'assert'; var urlPrefix = 'http://katas.tddbin.com/katas/es6/language/'; var katasUrl = urlPrefix + '__grouped__.json'; var GroupedKata = require('../src/grouped-kata.js'); describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { function onSuccess(groupedKatas) { assert.ok(groupedKatas); done(); } new GroupedKata(katasUrl).load(function() {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { function onError(err) { assert.ok(err); done(); } var invalidUrl = urlPrefix; new GroupedKata(invalidUrl).load(onError); }); it('for invalid data', function(done) { function onError(err) { assert.ok(err); done(); } var invalidData = urlPrefix + '__all__.json'; new GroupedKata(invalidData).load(onError); }); }); });
Use one es6 feature, modules.
Use one es6 feature, modules.
JavaScript
mit
wolframkriesing/es6-react-workshop,wolframkriesing/es6-react-workshop
--- +++ @@ -1,6 +1,6 @@ /* global require, describe, it */ -var assert = require('assert'); +import assert from 'assert'; var urlPrefix = 'http://katas.tddbin.com/katas/es6/language/'; var katasUrl = urlPrefix + '__grouped__.json';
6e7878fa36251f9f8bd3ef2a5d0d37d7da626f8e
models/Tweet.js
models/Tweet.js
var mongoose = require('mongoose'); // Create a new schema for tweets var schema = new mongoose.Schema({ twid : String, active : Boolean, author : String, avatar : String, body : String, date : Date, screenname : String }); var Tweet = mongoose.model('Tweet', schema); // Return tweets from the database schema.statics.getTweets = function(page, skip, callback) { var tweets = []; var start = (page * 10) + (skip * 1); // Query the database (use skip and limit to achieve page chunks) Tweet.find( {}, 'twid active author avatar body date screenname', { skip: start, limit: 10 } ) .sort({ date: 'desc' }) .exec(function(err, docs) { if (!err) { tweets = docs; tweets.forEach(function(tweet) { tweet.active = true; }); } callback(tweets); }); }; module.exports = Tweet;
var mongoose = require('mongoose'); // Create a new schema for tweets var schema = new mongoose.Schema({ twid : String, active : Boolean, author : String, avatar : String, body : String, date : Date, screenname : String }); // Return tweets from the database schema.statics.getTweets = function(page, skip, callback) { var tweets = []; var start = (page * 10) + (skip * 1); // Query the database (use skip and limit to achieve page chunks) Tweet.find( {}, 'twid active author avatar body date screenname', { skip: start, limit: 10 } ) .sort({ date: 'desc' }) .exec(function(err, docs) { if (!err) { tweets = docs; tweets.forEach(function(tweet) { tweet.active = true; }); } callback(tweets); }); }; var Tweet = mongoose.model('Tweet', schema); module.exports = Tweet;
Create mongoose model after static methods are defined
Create mongoose model after static methods are defined
JavaScript
mit
thinkswan/react-twitter-stream,thinkswan/react-twitter-stream
--- +++ @@ -10,8 +10,6 @@ date : Date, screenname : String }); - -var Tweet = mongoose.model('Tweet', schema); // Return tweets from the database schema.statics.getTweets = function(page, skip, callback) { @@ -37,4 +35,6 @@ }); }; +var Tweet = mongoose.model('Tweet', schema); + module.exports = Tweet;
b985443298b001d7441662e6fa4aee22ef009f44
webpack.config.umd.babel.js
webpack.config.umd.babel.js
import path from 'path'; import webpack from 'webpack'; import autoprefixer from 'autoprefixer'; module.exports = { entry: { 'react-image-lightbox': './src/index', }, output: { path: path.join(__dirname, 'dist', 'umd'), filename: '[name].js', libraryTarget: 'umd', library: 'ReactImageLightbox', }, resolve: { extensions: ['', '.js'] }, devtool: 'source-map', plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.EnvironmentPlugin([ "NODE_ENV", ]), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, }), ], postcss: [ autoprefixer({ browsers: ['IE >= 9', '> 1%'] }), ], externals: { react: 'react', 'react-dom': 'react-dom', 'react-modal': 'react-modal', }, module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel'], include: path.join(__dirname, 'src') }, { test: /\.scss$/, loaders: [ 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[local]___[hash:base64:5]', 'postcss-loader', 'sass-loader', ], include: path.join(__dirname, 'src') }, ] } };
import path from 'path'; import webpack from 'webpack'; import autoprefixer from 'autoprefixer'; module.exports = { entry: { 'react-image-lightbox': './src/index', }, output: { path: path.join(__dirname, 'dist', 'umd'), filename: '[name].js', libraryTarget: 'umd', library: 'ReactImageLightbox', }, resolve: { extensions: ['', '.js'] }, devtool: 'source-map', plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.EnvironmentPlugin([ "NODE_ENV", ]), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, mangle: false, beautify: true, comments: true, }), ], postcss: [ autoprefixer({ browsers: ['IE >= 9', '> 1%'] }), ], externals: { react: 'react', 'react-dom': 'react-dom', 'react-modal': 'react-modal', }, module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel'], include: path.join(__dirname, 'src') }, { test: /\.scss$/, loaders: [ 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[local]___[hash:base64:5]', 'postcss-loader', 'sass-loader', ], include: path.join(__dirname, 'src') }, ] } };
Make compiled source file more readable
Make compiled source file more readable
JavaScript
mit
fritz-c/react-image-lightbox,c00kiemon5ter/react-image-lightbox,c00kiemon5ter/react-image-lightbox
--- +++ @@ -25,6 +25,9 @@ compress: { warnings: false }, + mangle: false, + beautify: true, + comments: true, }), ], postcss: [
4790d1e767e9aacd51dcb1a2b656ae099ca61459
module/index.js
module/index.js
import {NAMESPACE, PREFIX} from './constants'; const ast = require('parametric-svg-ast'); const arrayFrom = require('array-from'); const startsWith = require('starts-with'); const ELEMENT_NODE = 1; const getChildren = ({children, childNodes}) => (children ? arrayFrom(children) : arrayFrom(childNodes).filter(({nodeType}) => nodeType === ELEMENT_NODE) ); const nodeBelongsToNamespace = ({namespace, prefix = null}, node) => ( ('namespaceURI' in node ? node.namespaceURI === namespace : (prefix !== null && startsWith(node.name, `${prefix}:`)) ) ); const getLocalName = (node) => ('namespaceURI' in node ? node.localName : node.name.replace(new RegExp(`^.*?:`), '') ); const crawl = (parentAddress) => (attributes, element, indexInParent) => { const address = parentAddress.concat(indexInParent); const currentAttributes = arrayFrom(element.attributes) .filter((node) => nodeBelongsToNamespace({ namespace: NAMESPACE, prefix: PREFIX, }, node)) .map((attribute) => ({ address, name: getLocalName(attribute), dependencies: [], // Proof of concept relation: () => Number(attribute.value), // Proof of concept })); return getChildren(element).reduce( crawl(address), attributes.concat(currentAttributes) ); }; export default (root) => { const attributes = getChildren(root).reduce(crawl([]), []); return ast({attributes, defaults: []}); };
import {NAMESPACE, PREFIX} from './constants'; const ast = require('parametric-svg-ast'); const arrayFrom = require('array-from'); const startsWith = require('starts-with'); const ELEMENT_NODE = 1; const getChildren = ({children, childNodes}) => (children ? arrayFrom(children) : arrayFrom(childNodes).filter(({nodeType}) => nodeType === ELEMENT_NODE) ); const nodeBelongsToNamespace = ({namespace, prefix = null}, node) => ( (node.namespaceURI ? node.namespaceURI === namespace : (prefix !== null && startsWith(node.name, `${prefix}:`)) ) ); const getLocalName = (node) => (node.namespaceURI ? node.localName : node.name.replace(new RegExp(`^.*?:`), '') ); const crawl = (parentAddress) => (attributes, element, indexInParent) => { const address = parentAddress.concat(indexInParent); const currentAttributes = arrayFrom(element.attributes) .filter((node) => nodeBelongsToNamespace({ namespace: NAMESPACE, prefix: PREFIX, }, node)) .map((attribute) => ({ address, name: getLocalName(attribute), dependencies: [], // Proof of concept relation: () => Number(attribute.value), // Proof of concept })); return getChildren(element).reduce( crawl(address), attributes.concat(currentAttributes) ); }; export default (root) => { const attributes = getChildren(root).reduce(crawl([]), []); return ast({attributes, defaults: []}); };
Make it work more or less with HTML4
Make it work more or less with HTML4
JavaScript
mit
parametric-svg/parse,parametric-svg/parse
--- +++ @@ -12,13 +12,13 @@ ); const nodeBelongsToNamespace = ({namespace, prefix = null}, node) => ( - ('namespaceURI' in node ? + (node.namespaceURI ? node.namespaceURI === namespace : (prefix !== null && startsWith(node.name, `${prefix}:`)) ) ); -const getLocalName = (node) => ('namespaceURI' in node ? +const getLocalName = (node) => (node.namespaceURI ? node.localName : node.name.replace(new RegExp(`^.*?:`), '') );
f30e96066d22d7481fe587109ee0eec8035c8caa
src/Homepage/index.js
src/Homepage/index.js
import React from 'react'; import NextEvent from './NextEvent'; import UpcomingEvents from './UpcomingEvents'; import PreviousEvents from './PreviousEvents'; import ParseComponent from 'parse-react/class'; export default class Homepage extends ParseComponent { constructor(props) { super(props); } observe(props, state) { return { events: new Parse.Query('Events') }; } render() { return ( <div className="three-fourths column markdown-body"> <blockquote> <p>{this.props.description}</p> </blockquote> <NextEvent event={this.data.events[0]} /> <UpcomingEvents events={this.data.events} /> <PreviousEvents events={this.data.events} /> <br /> </div> ); } }
import React from 'react'; import NextEvent from './NextEvent'; import UpcomingEvents from './UpcomingEvents'; import PreviousEvents from './PreviousEvents'; import ParseComponent from 'parse-react/class'; export default class Homepage extends ParseComponent { constructor(props) { super(props); } observe(props, state) { return { events: new Parse.Query('Events') }; } render() { let eventsContent; if(this.pendingQueries().length !== 0) { eventsContent = <p>Loading...</p> } else { eventsContent = ( <div> <NextEvent event={this.data.events[0]} /> <UpcomingEvents events={this.data.events} /> <PreviousEvents events={this.data.events} /> </div> ); } return ( <div className="three-fourths column markdown-body"> <blockquote> <p>{this.props.description}</p> </blockquote> {eventsContent} <br /> </div> ); } }
Add loading text while Parse is fetching events
Add loading text while Parse is fetching events
JavaScript
apache-2.0
naltaki/naltaki-front,naltaki/naltaki-front
--- +++ @@ -17,14 +17,26 @@ render() { + let eventsContent; + + if(this.pendingQueries().length !== 0) { + eventsContent = <p>Loading...</p> + } else { + eventsContent = ( + <div> + <NextEvent event={this.data.events[0]} /> + <UpcomingEvents events={this.data.events} /> + <PreviousEvents events={this.data.events} /> + </div> + ); + } + return ( <div className="three-fourths column markdown-body"> <blockquote> <p>{this.props.description}</p> </blockquote> - <NextEvent event={this.data.events[0]} /> - <UpcomingEvents events={this.data.events} /> - <PreviousEvents events={this.data.events} /> + {eventsContent} <br /> </div> );
dcce6195539f457c6a0276e26caa7fca74e25ed5
src/array/index.js
src/array/index.js
import Class from '../class'; import Matreshka from '../matreshka'; import instanceMembers from './_prototype'; import matreshkaError from '../_helpers/matreshkaerror'; import initMK from '../_core/init'; import staticMembers from './_staticmembers'; instanceMembers.extends = Matreshka; instanceMembers.constructor = function MatreshkaArray(length) { if (!(this instanceof MatreshkaArray)) { throw matreshkaError('common:call_class'); } initMK(this); // repeat the same logic as for native Array if (arguments.length === 1 && typeof length === 'number') { this.length = length; } else { nofn.forEach(arguments, (arg, index) => { this[index] = arg; }); this.length = arguments.length; } // return is used to make possible to chain super() calls return this; }; const MatreshkaArray = Class(instanceMembers, staticMembers); export default MatreshkaArray;
import Class from '../class'; import Matreshka from '../matreshka'; import instanceMembers from './_prototype'; import matreshkaError from '../_helpers/matreshkaerror'; import initMK from '../_core/init'; import staticMembers from './_staticmembers'; instanceMembers.extends = Matreshka; instanceMembers.constructor = function MatreshkaArray(length) { if (!(this instanceof MatreshkaArray)) { throw matreshkaError('common:call_class'); } const def = initMK(this); const { itemMediator } = def; // repeat the same logic as for native Array if (arguments.length === 1 && typeof length === 'number') { this.length = length; } else { nofn.forEach(arguments, (arg, index) => { this[index] = itemMediator ? itemMediator(arg, index) : arg; }); this.length = arguments.length; } // return is used to make possible to chain super() calls return this; }; const MatreshkaArray = Class(instanceMembers, staticMembers); export default MatreshkaArray;
Call itemMediator in Array constructor
fix: Call itemMediator in Array constructor
JavaScript
mit
matreshkajs/matreshka,finom/matreshka,matreshkajs/matreshka,finom/matreshka
--- +++ @@ -12,14 +12,15 @@ throw matreshkaError('common:call_class'); } - initMK(this); + const def = initMK(this); + const { itemMediator } = def; // repeat the same logic as for native Array if (arguments.length === 1 && typeof length === 'number') { this.length = length; } else { nofn.forEach(arguments, (arg, index) => { - this[index] = arg; + this[index] = itemMediator ? itemMediator(arg, index) : arg; }); this.length = arguments.length;
a453568816c6bde8f9ca583fa9da5d6664d189e7
src/components/suggest/template.js
src/components/suggest/template.js
/** * Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017. */ import html from '../../templates/helpers'; const template = (context) => { return new Promise((resolve) => { context.api.getSuggestedSymptoms(context.data).then((suggestedSymptoms) => { resolve(html` <h5 class="card-title">Do you have any of the following symptoms?</h5> <div class="card-text"> <form> ${suggestedSymptoms.map(symptom => { return html` <div class="form-group"> <label class="custom-control custom-checkbox mb-2 mr-sm-2 mb-sm-0"> <input id="${symptom.id}" type="checkbox" class="input-symptom custom-control-input"> <span class="custom-control-indicator"></span> <span class="custom-control-description">${symptom.name}</span> </label> </div> `; })} </form> <p class="text-muted small"><i class="fa fa-info-circle"></i> This is a list of symptoms suggested by our AI, basing on the information gathered so far during the interview.</p> </div> `); }); }); }; export default template;
/** * Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017. */ import html from '../../templates/helpers'; const template = (context) => { return new Promise((resolve) => { context.api.getSuggestedSymptoms(context.data).then((suggestedSymptoms) => { if (!suggestedSymptoms.length) { resolve('<p><i class="fa fa-circle-o-notch fa-spin fa-fw"></i> I am thinking...</p>'); document.getElementById('next-step').click(); } resolve(html` <h5 class="card-title">Do you have any of the following symptoms?</h5> <div class="card-text"> <form> ${suggestedSymptoms.map(symptom => { return html` <div class="form-group"> <label class="custom-control custom-checkbox mb-2 mr-sm-2 mb-sm-0"> <input id="${symptom.id}" type="checkbox" class="input-symptom custom-control-input"> <span class="custom-control-indicator"></span> <span class="custom-control-description">${symptom.name}</span> </label> </div> `; })} </form> <p class="text-muted small"><i class="fa fa-info-circle"></i> This is a list of symptoms suggested by our AI, basing on the information gathered so far during the interview.</p> </div> `); }); }); }; export default template;
Handle empty response form /suggest
Handle empty response form /suggest
JavaScript
mit
infermedica/js-symptom-checker-example,infermedica/js-symptom-checker-example
--- +++ @@ -7,6 +7,10 @@ const template = (context) => { return new Promise((resolve) => { context.api.getSuggestedSymptoms(context.data).then((suggestedSymptoms) => { + if (!suggestedSymptoms.length) { + resolve('<p><i class="fa fa-circle-o-notch fa-spin fa-fw"></i> I am thinking...</p>'); + document.getElementById('next-step').click(); + } resolve(html` <h5 class="card-title">Do you have any of the following symptoms?</h5> <div class="card-text">
64e33618b2ffe993292568a747944471cca5d54e
examples/src/main/javascript/tor.js
examples/src/main/javascript/tor.js
// Example of how to connect to a Tor hidden service and use it as a peer. // See demo.js to learn how to invoke this program. var bcj = org.bitcoinj; var params = bcj.params.MainNetParams.get(); var context = new bcj.core.Context(params); bcj.utils.BriefLogFormatter.init(); var InetAddress = Java.type("java.net.InetAddress"); var InetSocketAddress = Java.type("java.net.InetSocketAddress"); // Hack around the fact that PeerAddress assumes nodes have IP addresses. Simple enough for now. var OnionAddress = Java.extend(Java.type("org.bitcoinj.core.PeerAddress"), { toSocketAddress: function() { return InetSocketAddress.createUnresolved("hhiv5pnxenvbf4am.onion", params.port); } }); var pg = bcj.core.PeerGroup.newWithTor(context, null, new com.subgraph.orchid.TorClient(), false); // c'tor is bogus here: the passed in InetAddress will be ignored. pg.addAddress(new OnionAddress(InetAddress.localHost, params.port)); pg.start(); pg.waitForPeers(1).get(); print("Connected to: " + pg.connectedPeers); for each (var peer in pg.connectedPeers) { print(peer.peerVersionMessage.subVer); peer.ping().get() } pg.stop();
// Example of how to connect to a Tor hidden service and use it as a peer. // See demo.js to learn how to invoke this program. var bcj = org.bitcoinj; var params = bcj.params.MainNetParams.get(); var context = new bcj.core.Context(params); bcj.utils.BriefLogFormatter.init(); var PeerAddress = Java.type("org.bitcoinj.core.PeerAddress"); var InetSocketAddress = Java.type("java.net.InetSocketAddress"); // The PeerAddress class can now handle InetSocketAddresses with hostnames if they are .onion. var OnionAddress = InetSocketAddress.createUnresolved("hhiv5pnxenvbf4am.onion", params.port); var pg = bcj.core.PeerGroup.newWithTor(context, null, new com.subgraph.orchid.TorClient(), false); pg.addAddress(new PeerAddress(OnionAddress)); pg.start(); pg.waitForPeers(1).get(); print("Connected to: " + pg.connectedPeers); for each (var peer in pg.connectedPeers) { print(peer.peerVersionMessage.subVer); peer.ping().get() } pg.stop();
Update javascript Tor example to reflect simplified handling of .onion addresses
Update javascript Tor example to reflect simplified handling of .onion addresses
JavaScript
apache-2.0
bitsquare/bitcoinj
--- +++ @@ -6,19 +6,15 @@ var context = new bcj.core.Context(params); bcj.utils.BriefLogFormatter.init(); -var InetAddress = Java.type("java.net.InetAddress"); +var PeerAddress = Java.type("org.bitcoinj.core.PeerAddress"); var InetSocketAddress = Java.type("java.net.InetSocketAddress"); -// Hack around the fact that PeerAddress assumes nodes have IP addresses. Simple enough for now. -var OnionAddress = Java.extend(Java.type("org.bitcoinj.core.PeerAddress"), { - toSocketAddress: function() { - return InetSocketAddress.createUnresolved("hhiv5pnxenvbf4am.onion", params.port); - } -}); +// The PeerAddress class can now handle InetSocketAddresses with hostnames if they are .onion. +var OnionAddress = InetSocketAddress.createUnresolved("hhiv5pnxenvbf4am.onion", params.port); var pg = bcj.core.PeerGroup.newWithTor(context, null, new com.subgraph.orchid.TorClient(), false); -// c'tor is bogus here: the passed in InetAddress will be ignored. -pg.addAddress(new OnionAddress(InetAddress.localHost, params.port)); + +pg.addAddress(new PeerAddress(OnionAddress)); pg.start(); pg.waitForPeers(1).get(); @@ -29,5 +25,4 @@ peer.ping().get() } - pg.stop();
658793601f1ce937724c8c45f52088b5054fdb79
plugins/auth.js
plugins/auth.js
var passport = require('passport'); var auth0 = require('../lib/services/auth0'); module.exports = { type: 'authentication', module: auth0, initialize: (app) => { passport.use(auth0.strategy); passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(user, done) { done(null, user); }); app.use(passport.initialize()); app.use(passport.session()); app.use(function(req, res, next) { res.locals.user = req.user; next(); }); }, registerRoutes: app => { app.get('/login', function(req, res) { res.render('login', {env: process.env}); }); app.get('/logout', function(req, res) { req.logout(); res.redirect('/'); }); app.get('/user', function (req, res) { res.render('user', {user: req.user}); }); app.get('/auth/callback', passport.authenticate('auth0', { failureRedirect: '/' }), function(req, res) { const serializedState = req.query.state; if(typeof(serializedState) === 'string') { const state = JSON.parse(Buffer.from(serializedState, 'base64')); res.redirect(state.returnPath); } else { res.redirect('/'); } }); } };
var passport = require('passport'); var auth0 = require('../lib/services/auth0'); module.exports = { type: 'authentication', module: auth0, initialize: (app) => { passport.use(auth0.strategy); passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(user, done) { done(null, user); }); app.use(passport.initialize()); app.use(passport.session()); app.use(function(req, res, next) { res.locals.user = req.user; next(); }); }, registerRoutes: app => { app.get('/login', function(req, res) { res.render('login', {env: process.env}); }); app.get('/logout', function(req, res) { req.logout(); res.redirect('/'); }); // Most user facing routes are danish, so let's keep it that way. app.get('/min-side', function (req, res) { res.render('profile', {user: req.user}); }); app.get('/auth/callback', passport.authenticate('auth0', { failureRedirect: '/' }), function(req, res) { const serializedState = req.query.state; if(typeof(serializedState) === 'string') { const state = JSON.parse(Buffer.from(serializedState, 'base64')); res.redirect(state.returnPath); } else { res.redirect('/'); } }); } };
Rename /user route to /min-side
Rename /user route to /min-side
JavaScript
mit
CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder
--- +++ @@ -33,8 +33,9 @@ res.redirect('/'); }); - app.get('/user', function (req, res) { - res.render('user', {user: req.user}); + // Most user facing routes are danish, so let's keep it that way. + app.get('/min-side', function (req, res) { + res.render('profile', {user: req.user}); }); app.get('/auth/callback', passport.authenticate('auth0', {
5abc3a92a3e5581965cae00d7d71705c553308c8
src/main/web/florence/js/functions/__init.js
src/main/web/florence/js/functions/__init.js
setupFlorence(); //forms field styling markup injection //$('select:not(.small)').wrap('<span class="selectbg"></span>'); //$('select.small').wrap('<span class="selectbg selectbg--small"></span>'); //$('.selectbg--small:eq(1)').addClass('selectbg--small--margin'); //$('.selectbg--small:eq(3)').addClass('float-right');
setupFlorence();
Remove commented code not used.
Remove commented code not used.
JavaScript
mit
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
--- +++ @@ -1,8 +1 @@ setupFlorence(); - - -//forms field styling markup injection -//$('select:not(.small)').wrap('<span class="selectbg"></span>'); -//$('select.small').wrap('<span class="selectbg selectbg--small"></span>'); -//$('.selectbg--small:eq(1)').addClass('selectbg--small--margin'); -//$('.selectbg--small:eq(3)').addClass('float-right');
27912a421479d2c4216169873e79a09267792f00
client/reducers/groupReducer.js
client/reducers/groupReducer.js
import { group, member, message } from '../actions/actionTypes'; const groupReducer = (state = {}, action = {}) => { switch (action.type) { case group.CREATE_SUCCESS: return { ...state, [action.group.id]: { members: [], messages: [] } }; case member.ADD_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], members: [ ...state[action.groupId].members, action.member ] } }; case member.LIST_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], members: action.list } }; case message.CREATE_SUCCESS: return { ...state, [action.message.groupId]: { messages: [...state[action.message.groupId].messages, action.message] } }; // return { // ...state, // [action.groupId]: { // ...state[action.groupId], // messages: [ // ...state[action.groupId].messages, // action.message // ] // } // }; case message.LIST_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], messages: action.list } }; default: return state; } }; export default groupReducer;
import { group, member, message } from '../actions/actionTypes'; const groupReducer = (state = {}, action = {}) => { switch (action.type) { case group.CREATE_SUCCESS: return { ...state, [action.group.id]: { members: [], messages: [] } }; case member.ADD_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], members: [ ...state[action.groupId].members, action.member ] } }; case member.LIST_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], members: action.list } }; case message.CREATE_SUCCESS: // return { ...state, // [action.message.groupId]: { // messages: [...state[action.message.groupId].messages, action.message] // } }; return { ...state, [action.message.groupId]: { ...state[action.message.groupId], messages: [ ...state[action.message.groupId].messages, action.message ] } }; case message.LIST_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], messages: action.list } }; default: return state; } }; export default groupReducer;
Edit logic for creating mesage success action
Edit logic for creating mesage success action
JavaScript
mit
3m3kalionel/PostIt,3m3kalionel/PostIt
--- +++ @@ -30,20 +30,20 @@ } }; case message.CREATE_SUCCESS: - return { ...state, + // return { ...state, + // [action.message.groupId]: { + // messages: [...state[action.message.groupId].messages, action.message] + // } }; + return { + ...state, [action.message.groupId]: { - messages: [...state[action.message.groupId].messages, action.message] - } }; - // return { - // ...state, - // [action.groupId]: { - // ...state[action.groupId], - // messages: [ - // ...state[action.groupId].messages, - // action.message - // ] - // } - // }; + ...state[action.message.groupId], + messages: [ + ...state[action.message.groupId].messages, + action.message + ] + } + }; case message.LIST_SUCCESS: return { ...state,
90dd885e4124b455a1c121f760552b601861354e
client/transitive-view/style.js
client/transitive-view/style.js
var convert = require('convert'); var parse = require('color-parser'); exports.segments = { stroke: function(display, segment) { if (!segment.focused) return; switch (segment.type) { case 'CAR': return '#888'; case 'WALK': return 'none'; case 'TRANSIT': var route = segment.patterns[0].route; var id = route.route_id.split(':'); return convert.routeToColor(route.route_type, id[0].toLowerCase(), id[1].toLowerCase(), route.route_color); } } }; exports.places = { stroke: 1 }; exports.places_icon = { x: -8, y: -8, width: 16, height: 16, 'xlink:href': function(display, data) { if (data.owner.getId() === 'from') return 'build/planner-app/transitive-view/start.svg'; if (data.owner.getId() === 'to') return 'build/planner-app/transitive-view/end.svg'; }, stroke: 1, visibility: 'visible' }; exports.multipoints_pattern = exports.multipoints_merged = exports.stops_pattern = exports.stops_merged = { r: function(display, data, index, utils) { return utils.pixels(display.zoom.scale(), 4, 6, 8); } };
var config = require('config'); var convert = require('convert'); var parse = require('color-parser'); exports.segments = { stroke: function(display, segment) { if (!segment.focused) return; switch (segment.type) { case 'CAR': return '#888'; case 'WALK': return 'none'; case 'TRANSIT': var route = segment.patterns[0].route; var id = route.route_id.split(':'); return convert.routeToColor(route.route_type, id[0].toLowerCase(), id[1].toLowerCase(), route.route_color); } } }; exports.places = { stroke: 1 }; exports.places_icon = { x: -8, y: -8, width: 16, height: 16, 'xlink:href': function(display, data) { if (data.owner.getId() === 'from') return config.s3_bucket() + '/build/planner-app/transitive-view/start.svg'; if (data.owner.getId() === 'to') return config.s3_bucket() + '/build/planner-app/transitive-view/end.svg'; }, stroke: 1, visibility: 'visible' }; exports.multipoints_pattern = exports.multipoints_merged = exports.stops_pattern = exports.stops_merged = { r: function(display, data, index, utils) { return utils.pixels(display.zoom.scale(), 4, 6, 8); } };
Prepend SVG icons with S3 bucket
Prepend SVG icons with S3 bucket
JavaScript
bsd-3-clause
amigocloud/modeify,miraculixx/modeify,amigocloud/modified-tripplanner,arunnair80/modeify-1,miraculixx/modeify,arunnair80/modeify-1,amigocloud/modified-tripplanner,arunnair80/modeify,arunnair80/modeify-1,miraculixx/modeify,amigocloud/modeify,amigocloud/modeify,arunnair80/modeify,arunnair80/modeify-1,tismart/modeify,arunnair80/modeify,tismart/modeify,amigocloud/modeify,amigocloud/modified-tripplanner,arunnair80/modeify,miraculixx/modeify,tismart/modeify,tismart/modeify,amigocloud/modified-tripplanner
--- +++ @@ -1,3 +1,4 @@ +var config = require('config'); var convert = require('convert'); var parse = require('color-parser'); @@ -28,8 +29,8 @@ width: 16, height: 16, 'xlink:href': function(display, data) { - if (data.owner.getId() === 'from') return 'build/planner-app/transitive-view/start.svg'; - if (data.owner.getId() === 'to') return 'build/planner-app/transitive-view/end.svg'; + if (data.owner.getId() === 'from') return config.s3_bucket() + '/build/planner-app/transitive-view/start.svg'; + if (data.owner.getId() === 'to') return config.s3_bucket() + '/build/planner-app/transitive-view/end.svg'; }, stroke: 1, visibility: 'visible'
fb4ce1399205e9f6299fdb6ccb2687a78f70a348
test/qunit/typeable_test.js
test/qunit/typeable_test.js
steal("src/synthetic.js", function (Syn) { module("synthetic/typeable"); var isTypeable = Syn.typeable.test; test("Inputs and textareas", function () { var input = document.createElement("input"); var textarea = document.createElement("textarea"); equal(isTypeable(input), true, "Input element is typeable."); equal(isTypeable(textarea), true, "Text area is typeable."); }); test("Normal divs", function () { var div = document.createElement("div"); equal(isTypeable(div), false, "Divs are not typeable."); }); test("Contenteditable div", function () { var div = document.createElement("div"); // True div.setAttribute("contenteditable", "true"); equal(isTypeable(div), true, "Divs with contenteditable true"); // Empty string div.setAttribute("contenteditable", ""); equal(isTypeable(div), true, "Divs with contenteditable as empty string."); }); test("User defined typeable function", function () { // We're going to define a typeable with a class of foo. Syn.typeable(function (node) { return node.className.split(" ") .indexOf("foo") !== -1; }); var div = document.createElement("div"); div.className = "foo"; equal(isTypeable(div), true, "Custom function works."); }); });
steal("src/synthetic.js", function (Syn) { module("synthetic/typeable"); var isTypeable = Syn.typeable.test; test("Inputs and textareas", function () { var input = document.createElement("input"); var textarea = document.createElement("textarea"); equal(isTypeable(input), true, "Input element is typeable."); equal(isTypeable(textarea), true, "Text area is typeable."); }); test("Normal divs", function () { var div = document.createElement("div"); equal(isTypeable(div), false, "Divs are not typeable."); }); test("Contenteditable div", function () { var div = document.createElement("div"); // True div.setAttribute("contenteditable", "true"); equal(isTypeable(div), true, "Divs with contenteditable true"); // Empty string div.setAttribute("contenteditable", ""); equal(isTypeable(div), true, "Divs with contenteditable as empty string."); }); test("User defined typeable function", function () { // We're going to define a typeable with a class of foo. Syn.typeable(function (node) { return node.className === "foo"; }); var div = document.createElement("div"); div.className = "foo"; equal(isTypeable(div), true, "Custom function works."); }); });
Make typeable test compatible with IE<=8
Make typeable test compatible with IE<=8 [].indexOf is not defined on IE<=8
JavaScript
mit
bitovi/syn,bitovi/syn
--- +++ @@ -32,8 +32,7 @@ test("User defined typeable function", function () { // We're going to define a typeable with a class of foo. Syn.typeable(function (node) { - return node.className.split(" ") - .indexOf("foo") !== -1; + return node.className === "foo"; }); var div = document.createElement("div");
7a46ecdf7a8494afb7c33dfb9de07dbd2b61d5e6
test/test-automatic-mode.js
test/test-automatic-mode.js
'use strict' require('../lib/peer-watch.js') const { setTimeout } = require('sdk/timers') const { prefs } = require('sdk/simple-prefs') const tabs = require('sdk/tabs') const gw = require('../lib/gateways.js') exports['test automatic mode disabling redirect when IPFS API is offline'] = function (assert, done) { const ipfsPath = 'ipfs/QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D/Makefile' prefs.apiPollInterval = 100 // faster test prefs.customApiPort = 59999 // change to something that will always fail prefs.useCustomGateway = true prefs.automatic = true setTimeout(function () { assert.equal(prefs.automatic, true, 'automatic mode should be enabled') assert.equal(prefs.useCustomGateway, false, 'redirect should be automatically disabled') assert.equal(gw.redirectEnabled, false, 'redirect should be automatically disabled') tabs.open({ url: 'https://ipfs.io/' + ipfsPath, onReady: function onReady (tab) { assert.equal(tab.url, 'https://ipfs.io/' + ipfsPath, 'expected no redirect') tab.close(done) } }) }, prefs.apiPollInterval + 500) } require('./prefs-util.js').isolateTestCases(exports) require('sdk/test').run(exports)
'use strict' require('../lib/peer-watch.js') const { env } = require('sdk/system/environment') const { setTimeout } = require('sdk/timers') const { prefs } = require('sdk/simple-prefs') const tabs = require('sdk/tabs') const gw = require('../lib/gateways.js') exports['test automatic mode disabling redirect when IPFS API is offline'] = function (assert, done) { const ipfsPath = 'ipfs/QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D/Makefile' const checkDelay = ('TRAVIS' in env && 'CI' in env) ? 5000 : 500 prefs.apiPollInterval = 100 // faster test prefs.customApiPort = 59999 // change to something that will always fail prefs.useCustomGateway = true prefs.automatic = true setTimeout(function () { assert.equal(prefs.automatic, true, 'automatic mode should be enabled') assert.equal(prefs.useCustomGateway, false, 'redirect should be automatically disabled') assert.equal(gw.redirectEnabled, false, 'redirect should be automatically disabled') tabs.open({ url: 'https://ipfs.io/' + ipfsPath, onReady: function onReady (tab) { assert.equal(tab.url, 'https://ipfs.io/' + ipfsPath, 'expected no redirect') tab.close(done) } }) }, prefs.apiPollInterval + checkDelay) } require('./prefs-util.js').isolateTestCases(exports) require('sdk/test').run(exports)
Increase test timeout when run in TravisCI
Increase test timeout when run in TravisCI - potential fix for https://travis-ci.org/lidel/ipfs-firefox-addon/jobs/109478424#L271
JavaScript
cc0-1.0
lidel/ipfs-firefox-addon,lidel/ipfs-firefox-addon,lidel/ipfs-firefox-addon
--- +++ @@ -2,6 +2,7 @@ require('../lib/peer-watch.js') +const { env } = require('sdk/system/environment') const { setTimeout } = require('sdk/timers') const { prefs } = require('sdk/simple-prefs') const tabs = require('sdk/tabs') @@ -9,6 +10,7 @@ exports['test automatic mode disabling redirect when IPFS API is offline'] = function (assert, done) { const ipfsPath = 'ipfs/QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D/Makefile' + const checkDelay = ('TRAVIS' in env && 'CI' in env) ? 5000 : 500 prefs.apiPollInterval = 100 // faster test prefs.customApiPort = 59999 // change to something that will always fail prefs.useCustomGateway = true @@ -25,7 +27,7 @@ tab.close(done) } }) - }, prefs.apiPollInterval + 500) + }, prefs.apiPollInterval + checkDelay) } require('./prefs-util.js').isolateTestCases(exports)
6e0b7f2873fb8ede6bfd8dbf29b30200330b2662
__mocks__/react-relay.js
__mocks__/react-relay.js
// Comes from https://github.com/facebook/relay/issues/161 // Should be used in tests as a replacement for `react-storybooks-relay-container` // var React = require.requireActual("react") const graphql = (strings, ...keys) => { const lastIndex = strings.length - 1 return ( strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], "") + strings[lastIndex] ) } module.exports = { graphql, commitMutation: jest.fn(), QueryRenderer: props => React.createElement("div", {}), createFragmentContainer: component => component, createPaginationContainer: component => component, createRefetchContainer: component => component, }
// Comes from https://github.com/facebook/relay/issues/161 // Should be used in tests as a replacement for `react-storybooks-relay-container` var React = require.requireActual("react") // This is a template string function, which returns the original string // It's based on https://github.com/lleaff/tagged-template-noop // Which is MIT licensed to lleaff const graphql = (strings, ...keys) => { const lastIndex = strings.length - 1 return ( strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], "") + strings[lastIndex] ) } module.exports = { graphql, commitMutation: jest.fn(), QueryRenderer: props => React.createElement("div", {}), createFragmentContainer: component => component, createPaginationContainer: component => component, createRefetchContainer: component => component, }
Document noop `graphql` tagged template
[mock] Document noop `graphql` tagged template [skip ci]
JavaScript
mit
artsy/reaction,artsy/reaction,artsy/reaction-force,artsy/reaction-force,artsy/reaction
--- +++ @@ -1,8 +1,11 @@ // Comes from https://github.com/facebook/relay/issues/161 // Should be used in tests as a replacement for `react-storybooks-relay-container` -// + var React = require.requireActual("react") +// This is a template string function, which returns the original string +// It's based on https://github.com/lleaff/tagged-template-noop +// Which is MIT licensed to lleaff const graphql = (strings, ...keys) => { const lastIndex = strings.length - 1 return (
52299ae65b41cdfae0d8a4b0fb69f19c94be3f8f
src/main/webapp/scripts/results.js
src/main/webapp/scripts/results.js
$().ready(loadContentSection); $("body").on('click', '.keyword', function() { $(this).addClass("active"); $(".base").hide(200); $("#real-body").addClass("focus"); }); $("body").on('click', ".close", function(event) { event.stopPropagation(); $(".extended").removeClass("extended"); $(this).parent().removeClass("active"); $(".base").show(200); $("#real-body").removeClass("focus"); }); $("body").on('click', ".active .item", function() { $(".item").off("click"); const url = $(this).attr("data-url"); window.location.href = url; }); $("body").on('click', '.level-name', function() { const isThisExtended = $(this).parent().hasClass("extended"); $(".extended").removeClass("extended"); if (!isThisExtended) { $(this).parent().addClass("extended"); } });
$().ready(loadContentSection); $("body").on('click', '.keyword', function() { $(this).addClass("active"); $(".base").hide(200); $("#real-body").addClass("focus"); }); $("body").on('click', ".close", function(event) { event.stopPropagation(); $(".extended").removeClass("extended"); $(this).parent().removeClass("active"); $(".base").show(200); $("#real-body").removeClass("focus"); }); $("body").on('click', ".active .item", function() { $(".item").off("click"); const url = $(this).attr("data-url"); window.location.href = url; }); $("body").on('click', '.level-name', function() { const isThisExtended = $(this).parent().hasClass("extended"); $(".extended").removeClass("extended"); if (!isThisExtended) { $(this).parent().addClass("extended"); } }); $("body").on('click', '#go-back', function() { $("#body").off("click"); window.location.href = '/'; });
Add event listener to back button
Add event listener to back button
JavaScript
apache-2.0
googleinterns/step36-2020,googleinterns/step36-2020,googleinterns/step36-2020
--- +++ @@ -27,3 +27,8 @@ $(this).parent().addClass("extended"); } }); + +$("body").on('click', '#go-back', function() { + $("#body").off("click"); + window.location.href = '/'; +});
3241e2d18bd58d84d253def70cd8db437411b702
src/webapp/js/controllers/FirstController.js
src/webapp/js/controllers/FirstController.js
(function () { 'use strict'; angular.module('j.point.me').controller('FirstController', ['$scope', '$firebase', '$firebaseAuth', '$window', function ($scope, $firebase, $firebaseAuth, $window) { var ref = new Firebase("https://jpointme.firebaseio.com/"); var auth = $firebaseAuth(ref); if (auth.$getAuth()) { $scope.username = auth.$getAuth().github.displayName; } else { $scope.username = "anonymous"; } $scope.authenticate = function (provider) { var auth = $firebaseAuth(ref); auth.$authWithOAuthPopup("github").then(function (authData) { console.log("Logged in as:", authData); $scope.username = authData.github.displayName; }).catch(function (error) { console.error("Authentication failed: ", error); }); }; $scope.logout = function () { ref.unauth(); $window.location.reload(); }; } ]); }());
(function () { 'use strict'; angular.module('j.point.me').controller('FirstController', ['$scope', '$firebase', '$firebaseAuth', '$window', function ($scope, $firebase, $firebaseAuth, $window) { var ref = new Firebase("https://jpointme.firebaseio.com/"); var auth = $firebaseAuth(ref); var authData = auth.$getAuth(); if (authData) { $scope.username = authData.github.displayName; $scope.userId = authData.auth.provider + '/' + authData.auth.uid; } else { $scope.username = "anonymous"; $scope.userId = ""; } $scope.authenticate = function (provider) { var auth = $firebaseAuth(ref); auth.$authWithOAuthPopup("github").then(function (authData) { console.log("Logged in as:", authData); $scope.username = authData.github.displayName; }).catch(function (error) { console.error("Authentication failed: ", error); }); }; $scope.logout = function () { ref.unauth(); $window.location.reload(); }; var users = $firebase(ref.child("users")); var userExists = false; users.$asArray() .$loaded() .then(function(data) { angular.forEach(data,function(user,index){ if (user.oAuthId === $scope.userId) { userExists = true; } }) }).then(function(data) { if (!userExists) { users.$push({name: $scope.username, oAuthId: $scope.userId}).then(function(newChildRef) { console.log('user with userId ' + $scope.userId + ' does not exist; adding'); }); } else { console.log('user with userId ' + $scope.userId + ' already exists; not adding.'); } }); } ]); }());
Write new users to database.
Write new users to database.
JavaScript
mit
bertjan/jpointme,bertjan/jpointme
--- +++ @@ -7,10 +7,13 @@ var ref = new Firebase("https://jpointme.firebaseio.com/"); var auth = $firebaseAuth(ref); - if (auth.$getAuth()) { - $scope.username = auth.$getAuth().github.displayName; + var authData = auth.$getAuth(); + if (authData) { + $scope.username = authData.github.displayName; + $scope.userId = authData.auth.provider + '/' + authData.auth.uid; } else { $scope.username = "anonymous"; + $scope.userId = ""; } $scope.authenticate = function (provider) { @@ -27,6 +30,30 @@ ref.unauth(); $window.location.reload(); }; + + + var users = $firebase(ref.child("users")); + var userExists = false; + + users.$asArray() + .$loaded() + .then(function(data) { + angular.forEach(data,function(user,index){ + if (user.oAuthId === $scope.userId) { + userExists = true; + } + }) + }).then(function(data) { + if (!userExists) { + users.$push({name: $scope.username, oAuthId: $scope.userId}).then(function(newChildRef) { + console.log('user with userId ' + $scope.userId + ' does not exist; adding'); + }); + } else { + console.log('user with userId ' + $scope.userId + ' already exists; not adding.'); + } + }); + + } ]); }());
925a1a772962f3b80c810f024c971eb49cc15d34
lib/vain.js
lib/vain.js
'use strict'; /***** * Vain * * A view-first templating engine for Node.js. *****/ var jsdom = require('jsdom'), $ = require('jquery')(jsdom.jsdom().createWindow()), snippetRegistry = {}; /** * Register a snippet in the snippet registry. **/ exports.registerSnippet = function(snippetName, snippetFn) { snippetRegistry[snippetName] = snippetFn; }; /** * Process the given markup. **/ exports.render = function(input, options, fn) { if ('function' === typeof options) { fn = options; options = undefined; } options = options || {}; var $template = $(input); $template.find("data-vain").each(function() { var snippetName = $(this).data('vain'); if ('function' === typeof snippetRegistry[snippetName]) { $(this).replaceWith(snippetRegistry[snippetName](this)); } }); return $("<div />").append($template).html(); }; /** * Process a given file. **/ exports.renderFile = function(path, options, fn) { // }; // Express support. exports.__express = exports.renderFile;
'use strict'; /***** * Vain * * A view-first templating engine for Node.js. *****/ var jsdom = require('jsdom'), $ = require('jquery')(jsdom.jsdom().createWindow()), snippetRegistry = {}; /** * Register a snippet in the snippet registry. **/ exports.registerSnippet = function(snippetName, snippetFn) { snippetRegistry[snippetName] = snippetFn; }; /** * Process the given markup. **/ exports.render = function(input, options, fn) { if ('function' === typeof options) { fn = options; options = undefined; } options = options || {}; var $template = $(input), snippetHandlers = $.merge(snippetRegistry, options.snippets || {}); $template.find("data-vain").each(function() { var snippetName = $(this).data('vain'); if ('function' === typeof snippetRegistry[snippetName]) { $(this).replaceWith(snippetRegistry[snippetName](this)); } }); return $("<div />").append($template).html(); }; /** * Process a given file. **/ exports.renderFile = function(path, options, fn) { // }; // Express support. exports.__express = exports.renderFile;
Add the ability to specify snippets on a per-invocation basis.
Add the ability to specify snippets on a per-invocation basis.
JavaScript
apache-2.0
farmdawgnation/vain
--- +++ @@ -27,7 +27,9 @@ options = options || {}; - var $template = $(input); + var $template = $(input), + snippetHandlers = $.merge(snippetRegistry, options.snippets || {}); + $template.find("data-vain").each(function() { var snippetName = $(this).data('vain');
02f37068864173e02e9ac4a38c8a94ae85a1ded5
src/www/js/i18n.js
src/www/js/i18n.js
'use strict'; define(function(require) { var i18next = require('ext/i18next'); var i18nextJquery = require('ext/jquery-i18next'); var i18nextXHRbackend = require('ext/i18next-xhr-backend'); i18next .use(i18nextXHRbackend) .init({ debug: false, lng: 'en', preload: ['en', 'es', 'gr'], lngs: ['en', 'es', 'gr'], fallbackLng: 'en', ns: [ 'index', 'map', 'footer', 'saved-records', 'common' ], defaultNS: 'index', fallbackNS: 'common', backend: { loadPath: 'locales/{{lng}}/{{ns}}.json' } }, function(err, t) { var userLng = localStorage.getItem('user-language'); i18nextJquery.init(i18next, $, { tName: 't', i18nName: 'i18n', handleName: 'localize', selectorAttr: 'data-i18n', targetAttr: 'data-i18n-target', optionsAttr: 'data-i18n-options', useOptionsAttr: false, parseDefaultValueFromContent: true }); $(document).on('pagecreate', function(event, ui) { $(event.target).localize(); }); i18next.changeLanguage(userLng); $(document).localize(); }); });
'use strict'; define(function(require) { var i18next = require('ext/i18next'); var i18nextJquery = require('ext/jquery-i18next'); var i18nextXHRbackend = require('ext/i18next-xhr-backend'); i18next .use(i18nextXHRbackend) .init({ debug: false, lng: 'en', preload: ['en', 'es', 'gr'], lngs: ['en', 'es', 'gr'], fallbackLng: 'en', ns: [ 'index', 'map', 'footer', 'project', 'saved-records', 'common' ], defaultNS: 'index', fallbackNS: 'common', backend: { loadPath: 'locales/{{lng}}/{{ns}}.json' } }, function(err, t) { var userLng = localStorage.getItem('user-language'); i18nextJquery.init(i18next, $, { tName: 't', i18nName: 'i18n', handleName: 'localize', selectorAttr: 'data-i18n', targetAttr: 'data-i18n-target', optionsAttr: 'data-i18n-options', useOptionsAttr: false, parseDefaultValueFromContent: true }); $(document).on('pagecreate', function(event, ui) { $(event.target).localize(); }); i18next.changeLanguage(userLng); $(document).localize(); }); });
Add a 'project' namespace for custom translations of each project
Add a 'project' namespace for custom translations of each project Add a generic namespace where the projects can store custom translations that don't override the preset namespaces of the core Issue edina/fieldtrip-cobweb-project#1
JavaScript
bsd-3-clause
edina/fieldtrip-open,edina/fieldtrip-open,edina/fieldtrip-open,edina/fieldtrip-open
--- +++ @@ -17,6 +17,7 @@ 'index', 'map', 'footer', + 'project', 'saved-records', 'common' ],
18eb89fb8f7d341009348cf91968965f5c9da691
assets/js/imageLoad.js
assets/js/imageLoad.js
//Loads images and then initializes Datatables $(window).load(function() { var tableTitle = $('.tableImage'); var imageTitle = $('.tableTitle a'); var i = 0; for (i; i < tableTitle.length; i++) { var imageLink = imageTitle[i].innerText.toLowerCase(); $('.tableImage')[i].innerHTML = "<a href='/" + imageLink + "/'" + "><img src='http://cdn.allghostthemes.com/assets/images/" + imageTitle[i].innerText + ".jpg' /></a>"; } });
//Loads images and then initializes Datatables $(window).load(function() { var tableTitle = $('.tableImage'); var imageTitle = $('.tableTitle a'); var i = 0; for (i; i < tableTitle.length; i++) { var imageLink = imageTitle[i].innerText.toLowerCase(); $('.tableImage')[i].innerHTML = "<a href='/" + imageLink + "/'" + "><img src='https://cdn.allghostthemes.com/assets/images/" + imageTitle[i].innerText + ".jpg' /></a>"; } });
Update Image Loader to HTTPS
Update Image Loader to HTTPS
JavaScript
mit
HowtoGhost/allghostthemes,HowtoGhost/allghostthemes
--- +++ @@ -7,6 +7,6 @@ for (i; i < tableTitle.length; i++) { var imageLink = imageTitle[i].innerText.toLowerCase(); - $('.tableImage')[i].innerHTML = "<a href='/" + imageLink + "/'" + "><img src='http://cdn.allghostthemes.com/assets/images/" + imageTitle[i].innerText + ".jpg' /></a>"; + $('.tableImage')[i].innerHTML = "<a href='/" + imageLink + "/'" + "><img src='https://cdn.allghostthemes.com/assets/images/" + imageTitle[i].innerText + ".jpg' /></a>"; } });
1043e155d585912f19199d525ae121484e95e0e4
src/normalizeStyle.js
src/normalizeStyle.js
import React from 'react' import { getDisplayName, wrapDisplayName, setDisplayName } from 'recompose' const fixLineHeight = (lineHeight, displayName) => { if (typeof lineHeight === 'string') { throw new Error( `The element \`${displayName}\` has a \`lineHeight\` set with a String. Use numbers instead.` ) } return global.navigator.product === 'ReactNative' ? lineHeight : `${lineHeight}px` } const fixStyle = (style, displayName) => ({ ...style, lineHeight: style.lineHeight ? fixLineHeight(style.lineHeight, displayName) : undefined, }) export default Target => setDisplayName(wrapDisplayName(Target, 'normalizeStyle'))(({ style, ...props }) => <Target style={style ? fixStyle(style, getDisplayName(Target)) : undefined} {...props} /> )
import React from 'react' import { getDisplayName, wrapDisplayName, setDisplayName } from 'recompose' const fixLineHeight = (lineHeight, displayName) => { if (typeof lineHeight === 'string') { throw new Error( `The element \`${displayName}\` has a \`lineHeight\` set with a String. Use numbers instead.` ) } return global.navigator && global.navigator.product === 'ReactNative' ? lineHeight : `${lineHeight}px` } const fixStyle = (style, displayName) => ({ ...style, lineHeight: style.lineHeight ? fixLineHeight(style.lineHeight, displayName) : undefined, }) export default Target => setDisplayName(wrapDisplayName(Target, 'normalizeStyle'))(({ style, ...props }) => <Target style={style ? fixStyle(style, getDisplayName(Target)) : undefined} {...props} /> )
Add additional guard for `global.navigator`
Add additional guard for `global.navigator`
JavaScript
mit
klarna/higher-order-components,klarna/higher-order-components
--- +++ @@ -8,7 +8,9 @@ ) } - return global.navigator.product === 'ReactNative' ? lineHeight : `${lineHeight}px` + return global.navigator && global.navigator.product === 'ReactNative' + ? lineHeight + : `${lineHeight}px` } const fixStyle = (style, displayName) => ({
5c340b295d7d368aa15d2c9f496a611989c587bb
js/app.js
js/app.js
(function(app) { 'use strict'; var Root = app.Root || require('./components/root.js'); var root = new Root(); root.init(); app.root = root; })(this.app || (this.app = {}));
(function(app) { 'use strict'; var Root = app.Root || require('./components/root.js'); var root = new Root(); root.init(); app._root = root; })(this.app || (this.app = {}));
Rename property for root element as private property
Rename property for root element as private property
JavaScript
mit
ionstage/loclock,ionstage/loclock
--- +++ @@ -6,5 +6,5 @@ var root = new Root(); root.init(); - app.root = root; + app._root = root; })(this.app || (this.app = {}));
057abacf5e0b2c1f47e2d6e00d3a9d8fbc880ac6
packages/shared/lib/api/reports.js
packages/shared/lib/api/reports.js
export const reportBug = (data) => ({ method: 'post', url: 'reports/bug', data }); export const reportCrash = (data) => ({ method: 'post', url: 'reports/bug', data }); // reportCrashSentryProxy unclear API-spec export const reportCSPViolation = (cspReport) => ({ method: 'post', url: 'reports/csp', data: { 'csp-report': cspReport } }); export const reportPishing = ({ MessageID, MIMEType, Body }) => ({ method: 'post', url: 'reports/pishing', data: { MessageID, MIMEType, Body } });
export const reportBug = (data, input) => ({ method: 'post', url: 'reports/bug', input, data }); export const reportCrash = (data) => ({ method: 'post', url: 'reports/bug', data }); // reportCrashSentryProxy unclear API-spec export const reportCSPViolation = (cspReport) => ({ method: 'post', url: 'reports/csp', data: { 'csp-report': cspReport } }); export const reportPishing = ({ MessageID, MIMEType, Body }) => ({ method: 'post', url: 'reports/pishing', data: { MessageID, MIMEType, Body } });
Add input as parameter to report bug
Add input as parameter to report bug
JavaScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
--- +++ @@ -1,6 +1,7 @@ -export const reportBug = (data) => ({ +export const reportBug = (data, input) => ({ method: 'post', url: 'reports/bug', + input, data });
69d502c43d1b623fb704761de9453e12da7eaafa
offClick.js
offClick.js
angular.module('offClick',[]) .directive('offClick', ['$document', function ($document) { function targetInFilter(target,filter){ if(!target || !filter) return false; var elms = angular.element(filter); var elmsLen = elms.length; for (var i = 0; i< elmsLen; ++i) if(elms[i].contains(target)) return true; return false; } return { restrict: 'A', scope: { offClick: '&', offClickIf: '&' }, link: function (scope, elm, attr) { if (attr.offClickIf) { scope.$watch(scope.offClickIf, function (newVal, oldVal) { if (newVal && !oldVal) { $document.on('click', handler); } else if(!newVal){ $document.off('click', handler); } } ); } else { $document.on('click', handler); } function handler(event) { var target = event.target || event.srcElement; if (!(elm[0].contains(target) || targetInFilter(target, attr.offClickFilter))) { scope.$apply(scope.offClick()); } } } }; }]);
angular.module('offClick',[]) .directive('offClick', ['$document', function ($document) { function targetInFilter(target,filter){ if(!target || !filter) return false; var elms = angular.element(filter); var elmsLen = elms.length; for (var i = 0; i< elmsLen; ++i) if(elms[i].contains(target)) return true; return false; } return { restrict: 'A', scope: { offClick: '&', offClickIf: '&' }, link: function (scope, elm, attr) { if (attr.offClickIf) { scope.$watch(scope.offClickIf, function (newVal, oldVal) { if (newVal && !oldVal) { $document.on('click', handler); } else if(!newVal){ $document.off('click', handler); } } ); } else { $document.on('click', handler); } scope.$on('$destroy', function() { $document.off('click', handler); }); function handler(event) { var target = event.target || event.srcElement; if (!(elm[0].contains(target) || targetInFilter(target, attr.offClickFilter))) { scope.$apply(scope.offClick()); } } } }; }]);
Remove click handler from document when scope is destroyed
Remove click handler from document when scope is destroyed
JavaScript
mit
trenthogan/angular-off-click,TheSharpieOne/angular-off-click,lmtm/angular-off-click
--- +++ @@ -31,6 +31,10 @@ $document.on('click', handler); } + scope.$on('$destroy', function() { + $document.off('click', handler); + }); + function handler(event) { var target = event.target || event.srcElement; if (!(elm[0].contains(target) || targetInFilter(target, attr.offClickFilter))) {
7eaf0e31a40d759d7a4b7bf5884a384e3d3dbc9b
src/reducers/index.js
src/reducers/index.js
import { combineReducers } from 'redux'; import fuelSavingsAppState from './fuelSavings'; import cmsAppState from './cms.js'; const rootReducer = combineReducers({ fuelSavingsAppState: fuelSavingsAppState, cmsAppState: cmsAppState }); export default rootReducer;
import { combineReducers } from 'redux'; import fuelSavingsAppState from './fuelSavings'; import cmsAppState from './cms.js'; const rootReducer = combineReducers({ fuelSavingsAppState, cmsAppState }); export default rootReducer;
Switch back to es6 object literal notation
Switch back to es6 object literal notation
JavaScript
mit
vandosant/fawn,vandosant/fawn
--- +++ @@ -3,8 +3,8 @@ import cmsAppState from './cms.js'; const rootReducer = combineReducers({ - fuelSavingsAppState: fuelSavingsAppState, - cmsAppState: cmsAppState + fuelSavingsAppState, + cmsAppState }); export default rootReducer;
45d04853df6e61dc601e57d4f9e2684cad58e710
script/postinstall.js
script/postinstall.js
var path = require('path') var cp = require('child_process') var script = path.join(__dirname, 'postinstall') if (process.platform.indexOf('win') === 0) { script += '.cmd' } else { script += '.sh' } var child = cp.exec(script, [], {stdio: ['pipe', 'pipe', 'pipe']}) child.stderr.pipe(process.stderr) child.stdout.pipe(process.stdout)
var path = require('path') var cp = require('child_process') var script = path.join(__dirname, 'postinstall') if (process.platform.indexOf('win') === 0) { script += '.cmd' } else { script += '.sh' } var child = cp.spawn(script, [], {stdio: ['pipe', 'pipe', 'pipe']}) child.stderr.pipe(process.stderr) child.stdout.pipe(process.stdout)
Fix build error on Node 7
Fix build error on Node 7
JavaScript
mit
bronson/apm,atom/apm,bronson/apm,atom/apm,atom/apm,atom/apm,bronson/apm,bronson/apm
--- +++ @@ -7,6 +7,6 @@ } else { script += '.sh' } -var child = cp.exec(script, [], {stdio: ['pipe', 'pipe', 'pipe']}) +var child = cp.spawn(script, [], {stdio: ['pipe', 'pipe', 'pipe']}) child.stderr.pipe(process.stderr) child.stdout.pipe(process.stdout)
5bda50aca253dced7089fd9eb98aff9dce37cb87
koans/AboutExpects.js
koans/AboutExpects.js
describe("About Expects", function() { //We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(false).toBeTruthy(); //This should be true }); //To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); //Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); //Sometimes you need to be really exact about what you "type". it("should assert equality with ===", function () { var expectedValue = FILL_ME_IN; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); //Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(FILL_ME_IN); }); });
describe("About Expects", function() { //We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(true).toBeTruthy(); //This should be true }); //To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = 2; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); //Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = 2; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); //Sometimes you need to be really exact about what you "type". it("should assert equality with ===", function () { var expectedValue = "2"; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); //Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(2); }); });
Change all expected variables to truthy values
Change all expected variables to truthy values
JavaScript
mit
garronmichael/javascript-koans,garronmichael/javascript-koans,garronmichael/javascript-koans
--- +++ @@ -2,12 +2,12 @@ //We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { - expect(false).toBeTruthy(); //This should be true + expect(true).toBeTruthy(); //This should be true }); //To understand reality, we must compare our expectations against reality. it("should expect equality", function () { - var expectedValue = FILL_ME_IN; + var expectedValue = 2; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); @@ -15,7 +15,7 @@ //Some ways of asserting equality are better than others. it("should assert equality a better way", function () { - var expectedValue = FILL_ME_IN; + var expectedValue = 2; var actualValue = 1 + 1; // toEqual() compares using common sense equality. @@ -24,7 +24,7 @@ //Sometimes you need to be really exact about what you "type". it("should assert equality with ===", function () { - var expectedValue = FILL_ME_IN; + var expectedValue = "2"; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. @@ -33,6 +33,6 @@ //Sometimes we will ask you to fill in the values. it("should have filled in values", function () { - expect(1 + 1).toEqual(FILL_ME_IN); + expect(1 + 1).toEqual(2); }); });
837f67b6dffe737f252d94a7a9d3d5c8bd5d899c
woff2.js
woff2.js
var supportsWoff2 = (function( win ){ if( !( "FontFace" in win ) ) { return false; } var f = new FontFace('t', 'url( "data:application/font-woff2;base64,d09GMgABAAAAAADcAAoAAAAAAggAAACWAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABk4ALAoUNAE2AiQDCAsGAAQgBSAHIBtvAcieB3aD8wURQ+TZazbRE9HvF5vde4KCYGhiCgq/NKPF0i6UIsZynbP+Xi9Ng+XLbNlmNz/xIBBqq61FIQRJhC/+QA/08PJQJ3sK5TZFMlWzC/iK5GUN40psgqvxwBjBOg6JUSJ7ewyKE2AAaXZrfUB4v+hze37ugJ9d+DeYqiDwVgCawviwVFGnuttkLqIMGivmDg" ) format( "woff2" )', {}); f.load()['catch'](function() {}); return f.status == 'loading' || f.status == 'loaded'; })( this );
var supportsWoff2 = (function( win ){ if( !( "FontFace" in win ) ) { return false; } var f = new FontFace('t', 'url( "data:application/font-woff2;base64,d09GMgABAAAAAADwAAoAAAAAAiQAAACoAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAALAogOAE2AiQDBgsGAAQgBSAHIBuDAciO1EZ3I/mL5/+5/rfPnTt9/9Qa8H4cUUZxaRbh36LiKJoVh61XGzw6ufkpoeZBW4KphwFYIJGHB4LAY4hby++gW+6N1EN94I49v86yCpUdYgqeZrOWN34CMQg2tAmthdli0eePIwAKNIIRS4AGZFzdX9lbBUAQlm//f262/61o8PlYO/D1/X4FrWFFgdCQD9DpGJSxmFyjOAGUU4P0qigcNb82GAAA" ) format( "woff2" )', {}); f.load()['catch'](function() {}); return f.status == 'loading' || f.status == 'loaded'; })( this );
Fix WOFF2 font so it passes OTS in Firefox
Fix WOFF2 font so it passes OTS in Firefox
JavaScript
mit
filamentgroup/woff2-feature-test,filamentgroup/woff2-feature-test
--- +++ @@ -1,10 +1,10 @@ var supportsWoff2 = (function( win ){ - if( !( "FontFace" in win ) ) { - return false; - } + if( !( "FontFace" in win ) ) { + return false; + } - var f = new FontFace('t', 'url( "data:application/font-woff2;base64,d09GMgABAAAAAADcAAoAAAAAAggAAACWAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABk4ALAoUNAE2AiQDCAsGAAQgBSAHIBtvAcieB3aD8wURQ+TZazbRE9HvF5vde4KCYGhiCgq/NKPF0i6UIsZynbP+Xi9Ng+XLbNlmNz/xIBBqq61FIQRJhC/+QA/08PJQJ3sK5TZFMlWzC/iK5GUN40psgqvxwBjBOg6JUSJ7ewyKE2AAaXZrfUB4v+hze37ugJ9d+DeYqiDwVgCawviwVFGnuttkLqIMGivmDg" ) format( "woff2" )', {}); - f.load()['catch'](function() {}); + var f = new FontFace('t', 'url( "data:application/font-woff2;base64,d09GMgABAAAAAADwAAoAAAAAAiQAAACoAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAALAogOAE2AiQDBgsGAAQgBSAHIBuDAciO1EZ3I/mL5/+5/rfPnTt9/9Qa8H4cUUZxaRbh36LiKJoVh61XGzw6ufkpoeZBW4KphwFYIJGHB4LAY4hby++gW+6N1EN94I49v86yCpUdYgqeZrOWN34CMQg2tAmthdli0eePIwAKNIIRS4AGZFzdX9lbBUAQlm//f262/61o8PlYO/D1/X4FrWFFgdCQD9DpGJSxmFyjOAGUU4P0qigcNb82GAAA" ) format( "woff2" )', {}); + f.load()['catch'](function() {}); - return f.status == 'loading' || f.status == 'loaded'; + return f.status == 'loading' || f.status == 'loaded'; })( this );
31db55474ac2fb49b3fb07065cd36bbdb606ee16
routes/index.js
routes/index.js
var express = require('express'); var router = express.Router(); var arduino = require('../lib/arduino'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Findmon - 2015 SBA IoT Hackathon' }); }); router.get('/arduino/display', function(req, res, next) { var message = req.param("message"); arduino.sendMessage(message, function(err, results) { res.render('arduinoRes', { title: 'Arduino Response', error: err, results: results }); }); }); module.exports = router;
var express = require('express'); var router = express.Router(); var arduino = require('../lib/arduino'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Findmon - 2015 SBA IoT Hackathon' }); }); router.get('/arduino/display', function(req, res, next) { var message = req.param("message"); arduino.sendMessage(message, function(err, results) { res.render('arduinoRes', { title: 'Arduino Response', error: err, results: results }); }); }); router.get('/arduino/location', function(req, res, next) { var lat = req.param('lat'); var lon = req.param('lon'); console.info('[NFC] lat: ' + lat + " | lon: " + lon); res.send(200); }); module.exports = router;
Add new REST API for getting the target location
Add new REST API for getting the target location - /arduino/location?lat=123&lon=456
JavaScript
mit
rambling/findmon-sba,rambling/findmon-sba,rambling/findmon-sba
--- +++ @@ -19,6 +19,13 @@ results: results }); }); +}); +router.get('/arduino/location', function(req, res, next) { + var lat = req.param('lat'); + var lon = req.param('lon'); + console.info('[NFC] lat: ' + lat + " | lon: " + lon); + res.send(200); }); + module.exports = router;
878e78af356d3067ccdac8bb2c4bd7c2b99bb885
src/config/bundleIdentifiers.js
src/config/bundleIdentifiers.js
// nS - No Space // lC - Lowercase export function bundleIdentifiers( currentAppName, newName, projectName, currentBundleID, newBundleID, newBundlePath ) { const nS_CurrentAppName = currentAppName.replace(/\s/g, ''); const nS_NewName = newName.replace(/\s/g, ''); const lC_Ns_CurrentBundleID = currentBundleID.toLowerCase(); const lC_Ns_NewBundleID = newBundleID.toLowerCase(); return [ { regex: currentBundleID, replacement: newBundleID, paths: [ './android/app/BUCK', './android/app/build.gradle', './android/app/src/main/AndroidManifest.xml', ], }, { regex: currentBundleID, replacement: newBundleID, paths: [`./ios/${nS_NewName}.xcodeproj/project.pbxproj`], }, { regex: lC_Ns_CurrentBundleID, replacement: lC_Ns_NewBundleID, paths: [`./ios/${nS_NewName}.xcodeproj/project.pbxproj`], }, { regex: currentBundleID, replacement: newBundleID, paths: [`${newBundlePath}/MainActivity.java`, `${newBundlePath}/MainApplication.java`], }, { regex: lC_Ns_CurrentBundleID, replacement: lC_Ns_NewBundleID, paths: [`${newBundlePath}/MainApplication.java`], }, { regex: nS_CurrentAppName, replacement: nS_NewName, paths: [`${newBundlePath}/MainActivity.java`], }, ]; }
// nS - No Space // lC - Lowercase export function bundleIdentifiers( currentAppName, newName, projectName, currentBundleID, newBundleID, newBundlePath ) { const nS_CurrentAppName = currentAppName.replace(/\s/g, ''); const nS_NewName = newName.replace(/\s/g, ''); const lC_Ns_CurrentBundleID = currentBundleID.toLowerCase(); const lC_Ns_NewBundleID = newBundleID.toLowerCase(); return [ { regex: currentBundleID, replacement: newBundleID, paths: [ './android/app/BUCK', './android/app/build.gradle', './android/app/src/main/AndroidManifest.xml', ], }, { regex: currentBundleID, replacement: newBundleID, paths: [`${newBundlePath}/MainActivity.java`, `${newBundlePath}/MainApplication.java`], }, { regex: lC_Ns_CurrentBundleID, replacement: lC_Ns_NewBundleID, paths: [`${newBundlePath}/MainApplication.java`], }, { regex: nS_CurrentAppName, replacement: nS_NewName, paths: [`${newBundlePath}/MainActivity.java`], }, ]; }
Remove ios files (use Xcode instead)
Remove ios files (use Xcode instead)
JavaScript
mit
JuneDomingo/react-native-rename
--- +++ @@ -27,16 +27,6 @@ { regex: currentBundleID, replacement: newBundleID, - paths: [`./ios/${nS_NewName}.xcodeproj/project.pbxproj`], - }, - { - regex: lC_Ns_CurrentBundleID, - replacement: lC_Ns_NewBundleID, - paths: [`./ios/${nS_NewName}.xcodeproj/project.pbxproj`], - }, - { - regex: currentBundleID, - replacement: newBundleID, paths: [`${newBundlePath}/MainActivity.java`, `${newBundlePath}/MainApplication.java`], }, {
7306b27f76c871fc6932b8cccfb2be600d062286
pecan.js
pecan.js
#!/usr/bin/env node var fs = require('fs'), url = require('url'), http = require('http'), prompt = require('prompt'), pecanApp = require('commander'), pecanInfo = require('./package.json'); pecanApp .version(pecanInfo.version) .command('init', 'Create new PyProcessing project') .action(function(){ console.log('Creating new PyProcessing project'); }) .parse(process.argv);
#!/usr/bin/env node var fs = require('fs'), url = require('url'), http = require('http'), prompt = require('prompt'), pecanApp = require('commander'), pecanInfo = require('./package.json'); // Setup Project pecanApp .version(pecanInfo.version) .command('init', 'Create new PyProcessing project'); // Run Project pecanApp .command('run', 'Run Pyprocessing file'); pecanApp.parse(process.argv);
Remove actions .action. Add run command.
Remove actions .action. Add run command.
JavaScript
apache-2.0
btcrooks/pecan
--- +++ @@ -7,10 +7,13 @@ pecanApp = require('commander'), pecanInfo = require('./package.json'); +// Setup Project pecanApp .version(pecanInfo.version) - .command('init', 'Create new PyProcessing project') - .action(function(){ - console.log('Creating new PyProcessing project'); - }) - .parse(process.argv); + .command('init', 'Create new PyProcessing project'); + +// Run Project +pecanApp + .command('run', 'Run Pyprocessing file'); + +pecanApp.parse(process.argv);
1c9039a0bc7fa585ed309cbc0ae73a29da93ca10
eloquent_js/chapter06/ch06_ex01.js
eloquent_js/chapter06/ch06_ex01.js
class Vec { constructor(x, y) { this.x = x; this.y = y; } plus(v) { return new Vec(this.x + v.x, this.y + v.y); } minus(v) { return new Vec(this.x - v.x, this.y - v.y); } get length() { return Math.sqrt(this.x**2 + this.y**2); } }
class Vec { constructor(x, y) { this.x = x; this.y = y; } plus(v) { return new Vec(this.x + v.x, this.y + v.y); } minus(v) { return new Vec(this.x - v.x, this.y - v.y); } get length() { return Math.sqrt(this.x**2 + this.y**2); } }
Add chapter 6, exercise 1
Add chapter 6, exercise 1
JavaScript
mit
bewuethr/ctci
--- +++ @@ -1,18 +1,18 @@ class Vec { - constructor(x, y) { - this.x = x; - this.y = y; - } + constructor(x, y) { + this.x = x; + this.y = y; + } - plus(v) { - return new Vec(this.x + v.x, this.y + v.y); - } + plus(v) { + return new Vec(this.x + v.x, this.y + v.y); + } - minus(v) { - return new Vec(this.x - v.x, this.y - v.y); - } + minus(v) { + return new Vec(this.x - v.x, this.y - v.y); + } - get length() { - return Math.sqrt(this.x**2 + this.y**2); - } + get length() { + return Math.sqrt(this.x**2 + this.y**2); + } }
bb3f26196e870007810f262a74cbe37b94f27bef
web/static/js/app.js
web/static/js/app.js
import {Socket} from "phoenix" window.Experiment = class Experiment { constructor(topic, token, update) { this.socket = new Socket("/socket") this.socket.connect() this.chan = this.socket.channel(topic, {token: token}) if (update != undefined) { this.onUpdate(update) } } send_data(data) { this.chan.push("client", {body: data}) } onUpdate(func) { this.chan.join().receive("ok", _ => { this.chan.push("fetch", {}) }) this.chan.on("update", payload => { func(payload.body) }) } onReceiveMessage(func) { this.chan.join().receive("ok", _ => { this.chan.push("fetch", {}) }) this.chan.on("message", payload => { func(payload.body) }) } }
import {Socket} from "phoenix" window.Experiment = class Experiment { constructor(topic, token, update) { this.socket = new Socket("/socket") this.socket.connect() this.chan = this.socket.channel(topic, {token: token}) if (update != undefined) { this.onUpdate(update) } } send_data(data) { this.chan.push("client", {body: data}) } onUpdate(func) { this.chan.join().receive("ok", _ => { this.chan.push("fetch", {}) }) this.chan.on("update", payload => { func(payload.body) }) } onReceiveMessage(func) { this.chan.join() this.chan.on("message", payload => { func(payload.body) }) } }
Remove fetch step from message-based experiment
Remove fetch step from message-based experiment
JavaScript
mit
xeejp/xee,xeejp/xee,xeejp/xee,xeejp/xee,xeejp/xee
--- +++ @@ -23,9 +23,7 @@ } onReceiveMessage(func) { - this.chan.join().receive("ok", _ => { - this.chan.push("fetch", {}) - }) + this.chan.join() this.chan.on("message", payload => { func(payload.body) })
1d413edc3969ad921af3bee1b0f22446458192f0
frontend/src/constants/database.js
frontend/src/constants/database.js
/** * This file specifies the database collection and field names. */ export const COLLECTION_TRIPS = 'trips'; export const TRIPS_TITLE = 'title'; export const TRIPS_DESCRIPTION = 'description'; export const TRIPS_DESTINATION = 'destination'; export const TRIPS_START_DATE = 'start_date'; export const TRIPS_END_DATE = 'end_date'; export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr'; export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr'; export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr'; export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp'; /** * NOTE: The following constant corresponds to the collaborator field in * {@link_RawTripData} and is not a field in a trip document. */ export const RAW_TRIP_COLLABS export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time'; export const ACTIVITIES_END_TIME = 'end_time'; export const ACTIVITIES_START_TZ = 'start_tz'; export const ACTIVITIES_END_TZ = 'end_tz'; export const ACTIVITIES_TITLE = 'title'; export const ACTIVITIES_DESCRIPTION = 'description'; export const ACTIVITIES_START_COUNTRY = 'start_country'; export const ACTIVITIES_END_COUNTRY = 'end_country';
/** * This file specifies the database collection and field names. */ export const COLLECTION_TRIPS = 'trips'; export const TRIPS_TITLE = 'title'; export const TRIPS_DESCRIPTION = 'description'; export const TRIPS_DESTINATION = 'destination'; export const TRIPS_START_DATE = 'start_date'; export const TRIPS_END_DATE = 'end_date'; export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr'; export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr'; export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr'; export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp'; /** * NOTE: The following constant corresponds to the collaborator field in * {@link_RawTripData} and is not a field in a trip document. */ export const RAW_TRIP_COLLABS = 'collaborator_email_arr'; export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time'; export const ACTIVITIES_END_TIME = 'end_time'; export const ACTIVITIES_START_TZ = 'start_tz'; export const ACTIVITIES_END_TZ = 'end_tz'; export const ACTIVITIES_TITLE = 'title'; export const ACTIVITIES_DESCRIPTION = 'description'; export const ACTIVITIES_START_COUNTRY = 'start_country'; export const ACTIVITIES_END_COUNTRY = 'end_country';
Update string for raw trip collab constant.
Update string for raw trip collab constant.
JavaScript
apache-2.0
googleinterns/SLURP,googleinterns/SLURP,googleinterns/SLURP
--- +++ @@ -15,7 +15,7 @@ * NOTE: The following constant corresponds to the collaborator field in * {@link_RawTripData} and is not a field in a trip document. */ -export const RAW_TRIP_COLLABS +export const RAW_TRIP_COLLABS = 'collaborator_email_arr'; export const COLLECTION_ACTIVITIES = 'activities'; export const ACTIVITIES_START_TIME = 'start_time';
251a3879743884b32fa7c75cd6d8e7bf1883d500
frontend/src/pages/AttackConfig.js
frontend/src/pages/AttackConfig.js
import React from 'react'; import ConfigForm from '../containers/ConfigForm'; export default class AttackConfig extends React.Component { constructor() { super(); this.state = { sourceip: '', victim_id: '' }; } componentWillMount() { if (this.props.location.state) { this.setState({ sourceip: this.props.location.state.sourceip, victim_id: this.props.location.state.victim_id}); } } render() { return( <div className='container'> <div className='row ghost formformat'> <div className='col-md-offset-3 col-md-6'> <ConfigForm sourceip={ this.state.sourceip } victim_id={ this.state.victim_id }/> </div> </div> </div> ); } }
import React from 'react'; import axios from 'axios'; import ConfigForm from '../containers/ConfigForm'; export default class AttackConfig extends React.Component { constructor() { super(); this.state = { sourceip: '', victim_id: '' }; } componentWillMount = () => { if (this.props.params.id) { this.setState({ victim_id: this.props.params.id }); axios.get('/breach/victim/' + this.props.params.id) .then(res => { this.setState({ sourceip: res.data.victim_ip }); }) .catch(error => { console.log(error); }); } } render() { console.log(this.state.sourceip); return( <div className='container'> <div className='row ghost formformat'> <div className='col-md-offset-3 col-md-6'> <ConfigForm sourceip={ this.state.sourceip } victim_id={ this.state.victim_id }/> </div> </div> </div> ); } }
Make GET /victim/<id> request to get the victimip
Make GET /victim/<id> request to get the victimip
JavaScript
mit
dimriou/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,dimriou/rupture,dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dionyziz/rupture
--- +++ @@ -1,4 +1,6 @@ import React from 'react'; +import axios from 'axios'; + import ConfigForm from '../containers/ConfigForm'; export default class AttackConfig extends React.Component { @@ -10,14 +12,21 @@ }; } - componentWillMount() { - if (this.props.location.state) { - this.setState({ sourceip: this.props.location.state.sourceip, - victim_id: this.props.location.state.victim_id}); + componentWillMount = () => { + if (this.props.params.id) { + this.setState({ victim_id: this.props.params.id }); + axios.get('/breach/victim/' + this.props.params.id) + .then(res => { + this.setState({ sourceip: res.data.victim_ip }); + }) + .catch(error => { + console.log(error); + }); } } render() { + console.log(this.state.sourceip); return( <div className='container'> <div className='row ghost formformat'>
969be31e021ad1941ff0f876c007efd3582fddfe
html5/dist/static/js/ps/interact.js
html5/dist/static/js/ps/interact.js
/** * Communicate back to the web app. */ var extensionRoot = (new File($.fileName)).parent + '/'; $.evalFile(extensionRoot + '/constants.js'); $.evalFile(extensionRoot + '/Json.js'); $.evalFile(extensionRoot + '/Saver.js'); function getSettingsPath() { return SP_SETTINGS_PATH; } function save(args) { var preset, s; preset = Json.eval(args[0]); s = new sp.Saver(); return Json.encode(s.save(preset)); } function serializeUi(args) { var file, collapsed; file = new File(SP_SETTINGS_PATH + 'ui.json'); collapsed = []; for (i in args[0]) collapsed.push(args[0][i]); if (file.open('w')) { file.writeln(Json.encode({ collapsed: collapsed })); } }
/** * Communicate back to the web app. */ var extensionRoot = (new File($.fileName)).parent + '/'; $.evalFile(extensionRoot + '/constants.js'); $.evalFile(extensionRoot + '/Json.js'); $.evalFile(extensionRoot + '/Saver.js'); function getSettingsPath() { return SP_SETTINGS_PATH; } function save(args) { var preset = Json.eval(args[0]) , s = new sp.Saver() ; return Json.encode(s.save(preset)); } function serializeUi(args) { var file = new File(SP_SETTINGS_PATH + 'ui.json') , collapsed = [] ; for (var i in args[0]) collapsed.push(args[0][i]); if (file.open('w')) { file.writeln(Json.encode({ collapsed: collapsed })); } }
Use npm style variable declarations.
Use npm style variable declarations.
JavaScript
mit
reimund/Save-Panel,reimund/Save-Panel,reimund/Save-Panel
--- +++ @@ -15,21 +15,19 @@ function save(args) { - var preset, s; - - preset = Json.eval(args[0]); - s = new sp.Saver(); + var preset = Json.eval(args[0]) + , s = new sp.Saver() + ; return Json.encode(s.save(preset)); } function serializeUi(args) { - var file, collapsed; + var file = new File(SP_SETTINGS_PATH + 'ui.json') + , collapsed = [] + ; - file = new File(SP_SETTINGS_PATH + 'ui.json'); - collapsed = []; - - for (i in args[0]) + for (var i in args[0]) collapsed.push(args[0][i]); if (file.open('w')) {
2c74d58a4d36b1cf35ad7c7a4f6ea38de83564f8
lib/argparser.js
lib/argparser.js
#!/usr/bin/env node const { ArgumentParser, Const } = require('argparse'); const { version } = require('../package.json'); const parser = new ArgumentParser({ version, addHelp: true, description: 'A simple npm package to generate gh-badges (shields.io) based on lighthouse performance.', }); parser.addArgument( ['-s', '--single-badge'], { action: 'storeFalse', help: 'Only output one single badge averaging the four lighthouse scores', }, ); parser.addArgument( ['-u', '--urls'], { action: 'store', required: true, nargs: Const.ONE_OR_MORE, help: 'the lighthouse badge(s) will contain the respective average score(s) of all the urls supplied, combined', }, ); module.exports = { parser, };
#!/usr/bin/env node const { ArgumentParser, Const } = require('argparse'); const { version } = require('../package.json'); const parser = new ArgumentParser({ version, addHelp: true, description: 'A simple npm package to generate gh-badges (shields.io) based on lighthouse performance.', }); parser.addArgument( ['-s', '--single-badge'], { action: 'storeFalse', help: 'Only output one single badge averaging the four lighthouse scores', }, ); let required_args = parser.addArgumentGroup({title: 'required arguments'}); required_args.addArgument( ['-u', '--urls'], { action: 'store', required: true, nargs: Const.ONE_OR_MORE, help: 'the lighthouse badge(s) will contain the respective average score(s) of all the urls supplied, combined', }, ); module.exports = { parser, };
Add section for required args in argparse
Add section for required args in argparse
JavaScript
mit
emazzotta/lighthouse-badges
--- +++ @@ -16,7 +16,8 @@ }, ); -parser.addArgument( +let required_args = parser.addArgumentGroup({title: 'required arguments'}); +required_args.addArgument( ['-u', '--urls'], { action: 'store', required: true, @@ -25,7 +26,6 @@ }, ); - module.exports = { parser, };
17db477c32955006c685bc70e663e230a8b44765
bin/pino-cloudwatch.js
bin/pino-cloudwatch.js
#!/usr/bin/env node var yargs = require('yargs'); var argv = yargs .usage('Sends pino logs to AWS CloudWatch Logs.\nUsage: node index.js | pino-cloudwatch [options]') .describe('aws_access_key_id', 'AWS Access Key ID') .describe('aws_secret_access_key', 'AWS Secret Access Key') .describe('aws_region', 'AWS Region') .describe('group', 'AWS CloudWatch log group name') .describe('prefix', 'AWS CloudWatch log stream name prefix') .describe('interval', 'The maxmimum interval (in ms) before flushing the log queue.') .demand('group') .default('interval', 1000) .wrap(140) .argv; require('../index')(argv);
#!/usr/bin/env node var yargs = require('yargs'); var pump = require('pump'); var split = require('split2'); var argv = yargs .usage('Sends pino logs to AWS CloudWatch Logs.\nUsage: node index.js | pino-cloudwatch [options]') .describe('aws_access_key_id', 'AWS Access Key ID') .describe('aws_secret_access_key', 'AWS Secret Access Key') .describe('aws_region', 'AWS Region') .describe('group', 'AWS CloudWatch log group name') .describe('prefix', 'AWS CloudWatch log stream name prefix') .describe('interval', 'The maxmimum interval (in ms) before flushing the log queue.') .demand('group') .default('interval', 1000) .wrap(140) .argv; pump(process.stdin, split(), require('../index')(argv));
Move piping from stdin to the cli
Move piping from stdin to the cli
JavaScript
mit
dbhowell/pino-cloudwatch
--- +++ @@ -1,5 +1,7 @@ #!/usr/bin/env node var yargs = require('yargs'); +var pump = require('pump'); +var split = require('split2'); var argv = yargs .usage('Sends pino logs to AWS CloudWatch Logs.\nUsage: node index.js | pino-cloudwatch [options]') @@ -14,4 +16,4 @@ .wrap(140) .argv; -require('../index')(argv); +pump(process.stdin, split(), require('../index')(argv));
767f796829702d79cb76ef5d9673d89d2d7cf107
examples/vanilla/webpack.config.js
examples/vanilla/webpack.config.js
'use strict'; module.exports = { entry: './src/index.ts', output: { filename: 'dist/index.js' }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader' } ] }, resolve: { extensions: [ '.ts', '.tsx', 'js' ] } };
'use strict'; module.exports = { entry: './src/index.ts', output: { filename: 'dist/index.js' }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader' } ] }, resolve: { extensions: [ '.ts', '.tsx', '.js' ] } };
Fix error in vanilla example
Fix error in vanilla example
JavaScript
mit
TypeStrong/ts-loader,TypeStrong/ts-loader,MortenHoustonLudvigsen/ts-loader,jbrantly/ts-loader,MortenHoustonLudvigsen/ts-loader,gsteacy/ts-loader,MortenHoustonLudvigsen/ts-loader,gsteacy/ts-loader,jbrantly/ts-loader,gsteacy/ts-loader,jbrantly/ts-loader
--- +++ @@ -12,6 +12,6 @@ ] }, resolve: { - extensions: [ '.ts', '.tsx', 'js' ] + extensions: [ '.ts', '.tsx', '.js' ] } };
9dc6b680d66b8352835b5808e2c12ac0abd20c77
app/assets/javascripts/meetings.js
app/assets/javascripts/meetings.js
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. $(document).ready(function() { // localize times $('.localize').each(function () { var element = $(this); element.html(moment(element.html()).format('LLL')); }); });
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. var ready = function() { // localize times $('.localize').each(function () { var element = $(this); element.html(moment(element.html()).format('LLL')); }); }; $(document).ready(ready); $(document).on('turbolinks:load', ready);
Fix dates sometimes not being localized on page load.
Fix dates sometimes not being localized on page load.
JavaScript
mit
robyparr/adjourn,robyparr/adjourn,robyparr/adjourn
--- +++ @@ -1,10 +1,13 @@ // Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. -$(document).ready(function() { +var ready = function() { // localize times $('.localize').each(function () { var element = $(this); element.html(moment(element.html()).format('LLL')); }); -}); +}; + +$(document).ready(ready); +$(document).on('turbolinks:load', ready);
47681a372c616cb0c3c4c76bc79dd21c6f847bb7
src/objects/player.js
src/objects/player.js
// import Platform from 'objects/platform'; import { ASSETS } from 'constants'; import Bullet from 'objects/bullet'; export default class Player extends Phaser.Sprite { constructor(game, x, y) { const { world } = game; super(game, x, y, ASSETS.PLAYER, 1); game.physics.p2.enable(this, true); this.body.setRectangle(20); this.body.static = true; game.debug.body(this); this.spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); this.bullet = new Bullet(game, x, y + 20); game.add.existing(this.bullet); } update() { if (this.spaceKey.isDown) { console.log('fire!') this.fireBullet(); } } fireBullet() { this.bullet.body.velocity.x = 200; } }
// import Platform from 'objects/platform'; import { ASSETS } from 'constants'; import Bullet from 'objects/bullet'; export default class Player extends Phaser.Sprite { constructor(game, x, y) { const { world } = game; super(game, x, y, ASSETS.PLAYER, 1); game.physics.p2.enable(this, true); this.body.setRectangle(20); this.body.static = true; game.debug.body(this); this.spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); this.bullet = new Bullet(game, x, y + 20); game.add.existing(this.bullet); } update() { if (this.spaceKey.isDown) { console.log('fire!') this.fireBullet(); } } fireBullet() { this.bullet.body.velocity.x = 500; // this.bullet.body.velocity.y = 200; } }
Increase bullet speed for testing
Increase bullet speed for testing
JavaScript
mit
oliverbenns/cga-jam,oliverbenns/cga-jam,oliverbenns/cga-jam
--- +++ @@ -28,7 +28,8 @@ } fireBullet() { - this.bullet.body.velocity.x = 200; + this.bullet.body.velocity.x = 500; + // this.bullet.body.velocity.y = 200; } }
4a8534ec77faeb3ac8135fac661b8034fdf0c7bb
src/main/web/js/app/external-link.js
src/main/web/js/app/external-link.js
// Using regex instead of simply using 'host' because it causes error with security on Government browsers (IE9 so far) function getHostname(url) { var m = url.match(/^http(s?):\/\/[^/]+/); return m ? m[0] : null; } function eachAnchor(anchors) { $(anchors).each(function() { var href = $(this).attr("href"); var hostname = getHostname(href); if (hostname) { if (hostname !== document.domain && hostname.indexOf('ons.gov.uk') == -1) { $(this).attr('target', '_blank'); } } }); } $(function() { eachAnchor('a[href^="http://"]:not([href*="loop11.com"]):not([href*="ons.gov.uk"])'); eachAnchor('a[href^="https://"]:not([href*="loop11.com"]):not([href*="ons.gov.uk"])'); eachAnchor('a[href*="nationalarchives.gov.uk"]'); });
// Using regex instead of simply using 'host' because it causes error with security on Government browsers (IE9 so far) function getHostname(url) { var m = url.match(/^http(s?):\/\/[^/]+/); return m ? m[0] : null; } function eachAnchor(anchors) { $(anchors).each(function() { var href = $(this).attr("href"); var hostname = getHostname(href); if (hostname) { if ((hostname !== document.domain && hostname.indexOf('ons.gov.uk') == -1) || (hostname.indexOf('visual.ons.gov.uk') != -1 )){ $(this).attr('target', '_blank'); } } }); } $(function() { eachAnchor('a[href^="http://"]:not([href*="loop11.com"]):not([href*="ons.gov.uk"])'); eachAnchor('a[href^="https://"]:not([href*="loop11.com"]):not([href*="ons.gov.uk"])'); eachAnchor('a[href*="nationalarchives.gov.uk"]'); eachAnchor('a[href*="visual.ons.gov.uk"]'); });
Add visual.ons to external link formatter (will enable event tracking for outbound clicks)
Add visual.ons to external link formatter (will enable event tracking for outbound clicks)
JavaScript
mit
ONSdigital/babbage,ONSdigital/babbage,ONSdigital/babbage,ONSdigital/babbage
--- +++ @@ -11,7 +11,7 @@ var hostname = getHostname(href); if (hostname) { - if (hostname !== document.domain && hostname.indexOf('ons.gov.uk') == -1) { + if ((hostname !== document.domain && hostname.indexOf('ons.gov.uk') == -1) || (hostname.indexOf('visual.ons.gov.uk') != -1 )){ $(this).attr('target', '_blank'); } } @@ -23,4 +23,5 @@ eachAnchor('a[href^="http://"]:not([href*="loop11.com"]):not([href*="ons.gov.uk"])'); eachAnchor('a[href^="https://"]:not([href*="loop11.com"]):not([href*="ons.gov.uk"])'); eachAnchor('a[href*="nationalarchives.gov.uk"]'); + eachAnchor('a[href*="visual.ons.gov.uk"]'); });
502e4687022985f00533d1c435e2f1b1ff4ab561
src/main/webapp/components/Header.js
src/main/webapp/components/Header.js
import * as React from "react"; import { Navigation } from "./Navigation"; /** * Main Navigation Component */ export const Header = () => { const TITLE = "LLVM Build View"; return ( <header> <Wrapper> <span>{TITLE}</span> </Wrapper> <Navigation/> </header> ); }
import * as React from "react"; import { Navigation } from "./Navigation"; /** * Main Navigation Component */ export const Header = () => { const TITLE = "LLVM Build View"; return ( <header> <Wrapper> <span className="title">{TITLE}</span> </Wrapper> <Navigation/> </header> ); }
Add classname to title component
Add classname to title component
JavaScript
apache-2.0
googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020
--- +++ @@ -10,7 +10,7 @@ return ( <header> <Wrapper> - <span>{TITLE}</span> + <span className="title">{TITLE}</span> </Wrapper> <Navigation/> </header>
5d49914f839331357ee9710b2bff36ea4d020d7d
app/initializers/ember-cli-uuid.js
app/initializers/ember-cli-uuid.js
import Ember from 'ember'; import uuid from 'ember-cli-uuid/utils/uuid-helpers'; export default { name: 'ember-cli-uuid', initialize: function () { console.log('uuid: ', uuid); DS.RESTAdapter.reopen({ generateIdForRecord: function () { return uuid(); } }); } };
import Ember from 'ember'; import uuid from 'ember-cli-uuid/utils/uuid-helpers'; export default { name: 'ember-cli-uuid', initialize: function () { console.log('Adapter'); DS.Adapter.reopen({ generateIdForRecord: function () { return uuid(); } }); } };
Expand the addon to all adapters
[Adapter] Expand the addon to all adapters
JavaScript
mit
thaume/ember-cli-uuid,thaume/ember-cli-uuid
--- +++ @@ -7,8 +7,8 @@ initialize: function () { - console.log('uuid: ', uuid); - DS.RESTAdapter.reopen({ + console.log('Adapter'); + DS.Adapter.reopen({ generateIdForRecord: function () { return uuid();
f4b2ec17526db8327841f413cc77ebf7593ed28b
polyfills/Event/detect.js
polyfills/Event/detect.js
(function(){ if(!'Event' in window) return false; if(typeof window.Event === 'function') return true; var result = true; try{ new Event('click'); }catch(e){ result = false; } return result; }())
(function(){ if(!'Event' in window) return false; if(typeof window.Event === 'function') return true; try{ new Event('click'); return true; }catch(e){ return false; } }());
Add missing semicolon, avoid var assignment
Add missing semicolon, avoid var assignment
JavaScript
mit
JakeChampion/polyfill-service,JakeChampion/polyfill-service,kdzwinel/polyfill-service,mcshaz/polyfill-service,jonathan-fielding/polyfill-service,jonathan-fielding/polyfill-service,kdzwinel/polyfill-service,kdzwinel/polyfill-service,jonathan-fielding/polyfill-service,mcshaz/polyfill-service,mcshaz/polyfill-service
--- +++ @@ -3,12 +3,10 @@ if(typeof window.Event === 'function') return true; - var result = true; try{ new Event('click'); + return true; }catch(e){ - result = false; + return false; } - - return result; -}()) +}());
1896e0afebba48e6f46be4921c834febace42306
app/models/virtualMachineSearch.js
app/models/virtualMachineSearch.js
var VirtualMachine = require('./virtualMachine'); //define a criteria for a virtual machines search //inherit of all property of a virtual machine module.exports = VirtualMachine.extend({ //Override the application validation, in order to not block the search. validation: {} });
var VirtualMachine = require('./virtualMachine'); /* Define a criteria for a virtual machines search inherit of all property of a virtual machine with the extend method which is inherit by the Backbone.Model */ module.exports = VirtualMachine.extend({ //Override the application validation. //If we have a required criteria in the search object it would be defined here. validation: {} });
Add the VirtualMachione model comment.
Add the VirtualMachione model comment.
JavaScript
mit
pierr/front-end-spa,pierr/front-end-spa,KleeGroup/front-end-spa,KleeGroup/front-end-spa
--- +++ @@ -1,8 +1,12 @@ var VirtualMachine = require('./virtualMachine'); -//define a criteria for a virtual machines search -//inherit of all property of a virtual machine +/* + Define a criteria for a virtual machines search + inherit of all property of a virtual machine with + the extend method which is inherit by the Backbone.Model +*/ module.exports = VirtualMachine.extend({ - //Override the application validation, in order to not block the search. + //Override the application validation. + //If we have a required criteria in the search object it would be defined here. validation: {} });
fb6169980efc8a0f3af5a63c017701e18070565e
test/utils/to-date-in-time-zone.js
test/utils/to-date-in-time-zone.js
'use strict'; var Database = require('dbjs') , defineDate = require('dbjs-ext/date-time/date'); module.exports = function (t, a) { var db = new Database() , toDateInTimeZone; defineDate(db); toDateInTimeZone = t(db); var mayanEndOfTheWorld = new Date(2012, 11, 21, 1, 1); a.deep(toDateInTimeZone(mayanEndOfTheWorld, 'America/Guatemala').valueOf(), new db.Date(2012, 11, 20).valueOf()); a.deep(toDateInTimeZone(mayanEndOfTheWorld, 'Europe/Poland').valueOf(), new db.Date(2012, 11, 21).valueOf()); };
'use strict'; var db = require('../../db') , defineDate = require('dbjs-ext/date-time/date'); module.exports = function (t, a) { defineDate(db); var mayanEndOfTheWorld = new Date(2012, 11, 21, 1, 1); a.deep(t(mayanEndOfTheWorld, 'America/Guatemala').valueOf(), new db.Date(2012, 11, 20).valueOf()); a.deep(t(mayanEndOfTheWorld, 'Europe/Poland').valueOf(), new db.Date(2012, 11, 21).valueOf()); };
Update test after recent changes
Update test after recent changes
JavaScript
mit
egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations
--- +++ @@ -1,19 +1,15 @@ 'use strict'; -var Database = require('dbjs') +var db = require('../../db') , defineDate = require('dbjs-ext/date-time/date'); module.exports = function (t, a) { - var db = new Database() - , toDateInTimeZone; - defineDate(db); - toDateInTimeZone = t(db); var mayanEndOfTheWorld = new Date(2012, 11, 21, 1, 1); - a.deep(toDateInTimeZone(mayanEndOfTheWorld, 'America/Guatemala').valueOf(), + a.deep(t(mayanEndOfTheWorld, 'America/Guatemala').valueOf(), new db.Date(2012, 11, 20).valueOf()); - a.deep(toDateInTimeZone(mayanEndOfTheWorld, 'Europe/Poland').valueOf(), + a.deep(t(mayanEndOfTheWorld, 'Europe/Poland').valueOf(), new db.Date(2012, 11, 21).valueOf()); };
d0e6353434fe7d47462c43a17a48723835e5a5ae
cbv/static/permalinks.js
cbv/static/permalinks.js
// Auto-expand the accordion and jump to the target if url contains a valid hash (function(doc){ "use strict"; $(function(){ var $section, hash = window.location.hash; if(hash){ $section = $(hash); if($section){ $(doc).one('hidden.bs.collapse', hash, function(){ $section.parent().find('h3').click(); }); $('html, body').animate({ scrollTop: $(hash).offset().top }, 500); } } }) })(document);
// Auto-expand the accordion and jump to the target if url contains a valid hash (function(doc){ "use strict"; // On DOM Load... $(function(){ var hash = window.location.hash; var headerHeight = $('.navbar').height(); var methods = $('.accordion-group .accordion-heading'); var methodCount = methods.length; // Sets-up an event handler that will expand and scroll to the desired // (hash) method. if(hash){ // We need to know that all the panes have (at least initially) // collapsed as a result of loading the page. Unfortunately, we // only get events for each collapsed item, so we count... $(doc).on('hidden.bs.collapse', function(evt) { var methodTop, $hdr = $(hash).parent('.accordion-group'); methodCount--; if(methodCount === 0){ // OK, they've /all/ collapsed, now we expand the one we're // interested in the scroll to it. // First, remove this very event handler $(doc).off('hidden.bs.collapse'); // Now wait just a beat more to allow the last collapse // animation to complete... setTimeout(function(){ // Open the desired method $hdr.find('h3').click(); // Take into account the fixed header and the margin methodTop = $hdr.offset().top - headerHeight - 8; // Scroll it into view $('html, body').animate({scrollTop: methodTop}, 250); }, 250); } }); } // Delegated event handler to prevent the collapse/expand function of // a method's header when clicking the Pilcrow (permalink) $('.accordion-group').on('click', '.permalink', function(evt){ evt.preventDefault(); evt.stopImmediatePropagation(); window.location = $(this).attr('href'); }); }) })(document);
Work around for lack of signal for collapsing of all methods
Work around for lack of signal for collapsing of all methods
JavaScript
bsd-2-clause
refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector,refreshoxford/django-cbv-inspector
--- +++ @@ -2,18 +2,48 @@ (function(doc){ "use strict"; + // On DOM Load... $(function(){ - var $section, hash = window.location.hash; + var hash = window.location.hash; + var headerHeight = $('.navbar').height(); + var methods = $('.accordion-group .accordion-heading'); + var methodCount = methods.length; + + // Sets-up an event handler that will expand and scroll to the desired + // (hash) method. if(hash){ - $section = $(hash); - if($section){ - $(doc).one('hidden.bs.collapse', hash, function(){ - $section.parent().find('h3').click(); - }); - $('html, body').animate({ - scrollTop: $(hash).offset().top - }, 500); - } + // We need to know that all the panes have (at least initially) + // collapsed as a result of loading the page. Unfortunately, we + // only get events for each collapsed item, so we count... + $(doc).on('hidden.bs.collapse', function(evt) { + var methodTop, $hdr = $(hash).parent('.accordion-group'); + methodCount--; + if(methodCount === 0){ + // OK, they've /all/ collapsed, now we expand the one we're + // interested in the scroll to it. + + // First, remove this very event handler + $(doc).off('hidden.bs.collapse'); + // Now wait just a beat more to allow the last collapse + // animation to complete... + setTimeout(function(){ + // Open the desired method + $hdr.find('h3').click(); + // Take into account the fixed header and the margin + methodTop = $hdr.offset().top - headerHeight - 8; + // Scroll it into view + $('html, body').animate({scrollTop: methodTop}, 250); + }, 250); + } + }); } + + // Delegated event handler to prevent the collapse/expand function of + // a method's header when clicking the Pilcrow (permalink) + $('.accordion-group').on('click', '.permalink', function(evt){ + evt.preventDefault(); + evt.stopImmediatePropagation(); + window.location = $(this).attr('href'); + }); }) })(document);
7e4244676bacc96b4726796784108c4a461b22ad
client/js/debug/level.js
client/js/debug/level.js
/* jshint devel: true */ 'use strict'; xss.debug.NS = 'DEBUG'; // Debug URL: debug.html?debug=level:0 xss.debug.levelIndex = location.search.match(/debug=level:([0-9]+)$/)[1]; if (xss.debug.levelIndex) { document.addEventListener('DOMContentLoaded', function() { window.setTimeout(function() { xss.levels.onload = xss.debug.level; }, 0); }); } xss.debug.level = function() { var game; xss.socket = {emit: xss.util.noop}; xss.menuSnake.destruct(); game = new xss.Game(0, xss.debug.levelIndex, ['']); game.start(); console.info(game.level.levelData); xss.event.on(xss.PUB_GAME_TICK, xss.debug.NS, function() { if (game.snakes[0].limbo) { console.log(game.snakes[0]); game.snakes[0].crash(); xss.event.off(xss.PUB_GAME_TICK, xss.debug.NS); } }); };
/* jshint devel: true */ 'use strict'; xss.debug.NS = 'DEBUG'; // Debug URL: debug.html?debug=level:0 xss.debug.debugLevelMatch = location.search.match(/debug=level:([0-9]+)$/); if (xss.debug.debugLevelMatch) { document.addEventListener('DOMContentLoaded', function() { window.setTimeout(function() { xss.levels.onload = xss.debug.level; }, 0); }); } xss.debug.level = function() { var game; xss.socket = {emit: xss.util.noop}; xss.menuSnake.destruct(); game = new xss.Game(0, xss.debug.debugLevelMatch, ['']); game.start(); console.info(game.level.levelData); xss.event.on(xss.PUB_GAME_TICK, xss.debug.NS, function() { if (game.snakes[0].limbo) { console.log(game.snakes[0]); game.snakes[0].crash(); xss.event.off(xss.PUB_GAME_TICK, xss.debug.NS); } }); };
Fix indexerr caused by debug page in non-debug mode
Fix indexerr caused by debug page in non-debug mode
JavaScript
mit
blaise-io/xssnake,blaise-io/xssnake
--- +++ @@ -4,8 +4,8 @@ xss.debug.NS = 'DEBUG'; // Debug URL: debug.html?debug=level:0 -xss.debug.levelIndex = location.search.match(/debug=level:([0-9]+)$/)[1]; -if (xss.debug.levelIndex) { +xss.debug.debugLevelMatch = location.search.match(/debug=level:([0-9]+)$/); +if (xss.debug.debugLevelMatch) { document.addEventListener('DOMContentLoaded', function() { window.setTimeout(function() { xss.levels.onload = xss.debug.level; @@ -19,7 +19,7 @@ xss.socket = {emit: xss.util.noop}; xss.menuSnake.destruct(); - game = new xss.Game(0, xss.debug.levelIndex, ['']); + game = new xss.Game(0, xss.debug.debugLevelMatch, ['']); game.start(); console.info(game.level.levelData);
7b2fd31edc314c695f5049130a1da4bdb3ce12a5
src/job.js
src/job.js
var util = require('util'); var _ = require('underscore'); var EventEmitter = require('events').EventEmitter; /** * @param {String} app * @param {String} env * @param {String} task * @param {Object.<String, String>} [taskVariables] * @constructor */ function Job(app, env, task, taskVariables) { this.app = app; this.env = env; this.task = task; this.taskVariables = taskVariables; this.data = {}; EventEmitter.call(this); } util.inherits(Job, EventEmitter); /** * @param {Object} jobData * @returns {Object} new merged Job's data */ Job.prototype.setData = function(jobData) { return _.extend(this.data, jobData); }; Job.prototype.toString = function() { var result = util.format('%s "%s" to "%s"', this.task, this.app, this.env); if (this.data.id) { result += ' id: ' + this.data.id; } return result; }; module.exports = Job;
var util = require('util'); var _ = require('underscore'); var EventEmitter = require('events').EventEmitter; var PulsarJob = require('../node_modules/pulsar-rest-api/lib/pulsar/job'); /** * @param {String} app * @param {String} env * @param {String} task * @param {Object.<String, String>} [taskVariables] * @constructor */ function Job(app, env, task, taskVariables) { this.app = app; this.env = env; this.task = task; this.taskVariables = taskVariables; this.data = {}; EventEmitter.call(this); } util.inherits(Job, EventEmitter); /** * @param {Object} jobData * @returns {Object} new merged Job's data */ Job.prototype.setData = function(jobData) { return _.extend(this.data, jobData); }; Job.prototype.isRunning = function() { return this.data.status == PulsarJob.STATUS.RUNNING; }; Job.prototype.toString = function() { var result = util.format('%s "%s" to "%s"', this.task, this.app, this.env); if (this.data.id) { result += ' id: ' + this.data.id; } return result; }; module.exports = Job;
Add isRunning method to Job
Add isRunning method to Job
JavaScript
mit
cargomedia/pulsar-rest-api-client-node,vogdb/pulsar-rest-api-client-node
--- +++ @@ -1,6 +1,7 @@ var util = require('util'); var _ = require('underscore'); var EventEmitter = require('events').EventEmitter; +var PulsarJob = require('../node_modules/pulsar-rest-api/lib/pulsar/job'); /** * @param {String} app @@ -29,6 +30,10 @@ return _.extend(this.data, jobData); }; +Job.prototype.isRunning = function() { + return this.data.status == PulsarJob.STATUS.RUNNING; +}; + Job.prototype.toString = function() { var result = util.format('%s "%s" to "%s"', this.task, this.app, this.env); if (this.data.id) {
aaaa280dd57278a3a2d4c316397105ff79418c68
lib/mock/duration.js
lib/mock/duration.js
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. module.exports = function(landscape) { let actions = new Map(); let tickCount = 0; let tickOnce = () => new Promise(function(resolve, reject) { tickCount += 1; let runAllActions = Promise.resolve(); for (let action of actions.get(tickCount) || []) runAllActions = new Promise(function(done) { runAllActions.then(function() { try { Promise.resolve( landscape[action.method].apply(landscape, action.args) ).then(done, reject); } catch(error) { reject(error); } }, reject); }); runAllActions.then(resolve, reject); }); return { "tick": n => new Promise(function(resolve, reject) { let allTicks = Promise.resolve(); if (typeof n === "undefined") n = 1; for (; n > 0; n -= 1) allTicks = allTicks.then(tickOnce, reject); allTicks.then(resolve, reject); }), "at": function(when, method) { if (!actions.has(when)) actions.set(when, []); actions.get(when).push({ "when": when, "method": method, "args": [...arguments].slice(2) }); } }; };
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. module.exports = function(landscape) { let actions = new Map(); let tickCount = 0; let tickOnce = () => new Promise(function(resolve, reject) { tickCount += 1; let runAllActions = Promise.resolve(); for (let action of actions.get(tickCount) || []) runAllActions = new Promise(function(done) { runAllActions.then(function() { try { Promise.resolve( landscape[action.method].apply(landscape, action.args) ).then(done, reject); } catch(error) { reject(error); } }, reject); }); runAllActions.then(resolve, reject); }); return { "tick": n => new Promise(function(resolve, reject) { let allTicks = Promise.resolve(); if (typeof n === "undefined") n = 1; for (; n > 0; n -= 1) allTicks = allTicks.then(tickOnce, reject); allTicks.then(resolve, reject); }), "at": function(when, method, ...args) { if (!actions.has(when)) actions.set(when, []); actions.get(when).push({ "when": when, "method": method, "args": args }); } }; };
Use rest parameters instead of arguments
:muscle: Use rest parameters instead of arguments
JavaScript
bsd-3-clause
daaang/awful-mess
--- +++ @@ -39,14 +39,14 @@ allTicks.then(resolve, reject); }), - "at": function(when, method) { + "at": function(when, method, ...args) { if (!actions.has(when)) actions.set(when, []); actions.get(when).push({ "when": when, "method": method, - "args": [...arguments].slice(2) + "args": args }); } };
c46eed27db65b4fa8495291a80ef4be56d344696
lib/src/data/load.js
lib/src/data/load.js
import {formatSize} from '../../../core/src/common/utils'; import log from '../../../core/src/common/log'; const BLOB_SIZE_LIMIT = 10 * 1024 * 1024; // 10 MB export function fetchURL(url) { log.info(`Fetching data from "${url}"`); return new Promise((resolve, reject) => { const request = new XMLHttpRequest; request.open('GET', url, true); request.responseType = 'arraybuffer'; request.onload = () => { if (request.status === 200) { resolve(request.response); } else if (request.status === 0) { reject(new Error('Unable to connect to the server')); } else { reject(new Error(`Unable to download file (${request.status} ${request.statusText})`)); } }; request.onerror = () => { reject(new Error('Unable to connect to the server')); }; request.send(); }); } export function readBlob(blob) { log.info(`Reading contents of ${formatSize(blob.size)} blob`); return new Promise((resolve, reject) => { if (blob.size > BLOB_SIZE_LIMIT) { reject(new Error(`Input is too large (${formatSize(blob.size)})`)); return; } const reader = new FileReader; reader.onload = event => { resolve(event.target.result); }; reader.onerror = event => { reject(new Error(event.target.error || 'Unknown error')); }; reader.readAsArrayBuffer(blob); }); }
import {formatSize} from '../../../core/src/common/utils'; import log from '../../../core/src/common/log'; const BLOB_SIZE_LIMIT = 10 * 1024 * 1024; // 10 MB export function fetchURL(url) { log.info(`Downloading data from "${url}"`); return new Promise((resolve, reject) => { const request = new XMLHttpRequest; request.open('GET', url, true); request.responseType = 'arraybuffer'; request.onload = () => { if (request.status === 200) { resolve(request.response); } else if (request.status === 0) { reject(new Error('Failed to connect to the server')); } else { reject(new Error(`Failed to download data (${request.status} ${request.statusText})`)); } }; request.onerror = () => { reject(new Error('Failed to connect to the server')); }; request.send(); }); } export function readBlob(blob) { log.info(`Reading contents of ${formatSize(blob.size)} blob`); return new Promise((resolve, reject) => { if (blob.size > BLOB_SIZE_LIMIT) { reject(new Error(`Input is too large (${formatSize(blob.size)})`)); return; } const reader = new FileReader; reader.onload = event => { resolve(event.target.result); }; reader.onerror = event => { reject(new Error(event.target.error || 'Unknown error')); }; reader.readAsArrayBuffer(blob); }); }
Unify error messages between lib and app
Unify error messages between lib and app
JavaScript
mit
jpikl/cfxnes,jpikl/cfxnes
--- +++ @@ -4,7 +4,7 @@ const BLOB_SIZE_LIMIT = 10 * 1024 * 1024; // 10 MB export function fetchURL(url) { - log.info(`Fetching data from "${url}"`); + log.info(`Downloading data from "${url}"`); return new Promise((resolve, reject) => { const request = new XMLHttpRequest; request.open('GET', url, true); @@ -13,13 +13,13 @@ if (request.status === 200) { resolve(request.response); } else if (request.status === 0) { - reject(new Error('Unable to connect to the server')); + reject(new Error('Failed to connect to the server')); } else { - reject(new Error(`Unable to download file (${request.status} ${request.statusText})`)); + reject(new Error(`Failed to download data (${request.status} ${request.statusText})`)); } }; request.onerror = () => { - reject(new Error('Unable to connect to the server')); + reject(new Error('Failed to connect to the server')); }; request.send(); });
6cdd42dba8b156d1892aa166177d2c49a542be14
lib/updateComment.js
lib/updateComment.js
const updateComment = (body, commentArr = []) => { body = body.map((obj, index, array) => { if (obj.type === 'Line' || obj.type === 'Block') { if (array[index + 1].type === 'Line' || array[index + 1].type === 'Block') { commentArr.push(obj) } else { commentArr.push(obj) array[index + 1].leadingComments = commentArr commentArr = [] } return undefined } return obj }).filter(stmt => stmt !== undefined) return body } /* Module Exports updateComment */ module.exports = updateComment
const updateComment = (body, commentArr = []) => { body = body.map((obj, index, array) => { if (obj.type === 'Line' || obj.type === 'Block') { commentArr.push(obj) if (array[index + 1] === undefined) { array[index - commentArr.length].trailingComments = commentArr return undefined } if (!(array[index + 1].type === 'Line' || array[index + 1].type === 'Block')) { array[index + 1].leadingComments = commentArr commentArr = [] } return undefined } return obj }).filter(stmt => stmt !== undefined) return body } /* Module Exports updateComment */ module.exports = updateComment
Add check for comments at the end of the file
Add check for comments at the end of the file
JavaScript
mit
cleanlang/clean,cleanlang/clean,cleanlang/clean
--- +++ @@ -1,10 +1,12 @@ const updateComment = (body, commentArr = []) => { body = body.map((obj, index, array) => { if (obj.type === 'Line' || obj.type === 'Block') { - if (array[index + 1].type === 'Line' || array[index + 1].type === 'Block') { - commentArr.push(obj) - } else { - commentArr.push(obj) + commentArr.push(obj) + if (array[index + 1] === undefined) { + array[index - commentArr.length].trailingComments = commentArr + return undefined + } + if (!(array[index + 1].type === 'Line' || array[index + 1].type === 'Block')) { array[index + 1].leadingComments = commentArr commentArr = [] }
f38a954ba98b2a71dda1ed34bcbfb2cc46232423
likeInstagramFeed.js
likeInstagramFeed.js
(function () { 'use strict'; window.scrollTo(0, document.body.scrollHeight); var likeElements = document.querySelectorAll(".coreSpriteHeartOpen"); var likeCount = 0; var nextTime = 1000; function doLike(i) { likeElements[i].click(); } for (var i = 0; i < likeElements.length; i++) { nextTime = Math.random() * (14000 - 4000) + 4000; console.log(nextTime); console.log("Like: " + likeCount); likeCount++; if (likeCount > 10) { console.log("too much liking !"); break; } else { setTimeout(doLike(i), nextTime); } } })();
(function () { 'use strict'; window.scrollTo(0, document.body.scrollHeight); var likeElements = document.querySelectorAll(".coreSpriteLikeHeartOpen"); var likeCount = 0; var nextTime = 1000; function doLike(photo) { photo.click(); } likeElements.forEach(photo => { nextTime = Math.random() * (14000 - 4000) + 4000; console.log(nextTime); console.log("Like: " + likeCount); likeCount++; if (likeCount > 5) { console.log("too much liking !"); return } else { setTimeout(doLike(photo), nextTime); } }); })();
Fix instagram script on feed
Fix instagram script on feed
JavaScript
apache-2.0
AxelMonroyX/botLikes
--- +++ @@ -1,25 +1,25 @@ (function () { 'use strict'; window.scrollTo(0, document.body.scrollHeight); - var likeElements = document.querySelectorAll(".coreSpriteHeartOpen"); + var likeElements = document.querySelectorAll(".coreSpriteLikeHeartOpen"); var likeCount = 0; var nextTime = 1000; - function doLike(i) { - likeElements[i].click(); + function doLike(photo) { + photo.click(); } - for (var i = 0; i < likeElements.length; i++) { + likeElements.forEach(photo => { nextTime = Math.random() * (14000 - 4000) + 4000; console.log(nextTime); console.log("Like: " + likeCount); likeCount++; - if (likeCount > 10) { + if (likeCount > 5) { console.log("too much liking !"); - break; + return } else { - setTimeout(doLike(i), nextTime); + setTimeout(doLike(photo), nextTime); } - } + }); })();
e9ef00a08454eb3d6109f3c3c51f1cd51cb726b5
lib/util/test.js
lib/util/test.js
var express = require('express'); exports.PROXY_ERROR_CODE_TO_HTTP_CODE_MAP = { 'NR-1000': 400, 'NR-1001': 400, 'NR-1002': 401, 'NR-2000': 400 }; exports.getTestHttpServer = function(port, ip, callback) { ip = ip || '127.0.0.1'; var server = express.createServer(); server.listen(port, ip, function(err) { callback(err, server); }); }; exports.setupErrorEchoHandlers = function(server) { function echoError(req, res) { var code; if (!req.headers.hasOwnProperty('x-rp-error-code')) { res.writeHead(404, {}); res.end(); return; } code = exports.PROXY_ERROR_CODE_TO_HTTP_CODE_MAP[req.headers['x-rp-error-code']]; res.writeHead(code, {}); res.end(req.headers['x-rp-error-message']); } server.get('*', echoError); server.post('*', echoError); server.put('*', echoError); };
var express = require('express'); exports.PROXY_ERROR_CODE_TO_HTTP_CODE_MAP = { 'NR-1000': 400, 'NR-1001': 400, 'NR-1002': 401, 'NR-2000': 400, 'NR-5000': 500 }; exports.getTestHttpServer = function(port, ip, callback) { ip = ip || '127.0.0.1'; var server = express.createServer(); server.listen(port, ip, function(err) { callback(err, server); }); }; exports.setupErrorEchoHandlers = function(server) { function echoError(req, res) { var code; if (!req.headers.hasOwnProperty('x-rp-error-code')) { res.writeHead(404, {}); res.end(); return; } code = exports.PROXY_ERROR_CODE_TO_HTTP_CODE_MAP[req.headers['x-rp-error-code']]; res.writeHead(code, {}); res.end(req.headers['x-rp-error-message']); } server.get('*', echoError); server.post('*', echoError); server.put('*', echoError); };
Add a status code mapping for NR-5000.
Add a status code mapping for NR-5000.
JavaScript
apache-2.0
racker/node-rproxy,racker/node-rproxy
--- +++ @@ -5,7 +5,9 @@ 'NR-1001': 400, 'NR-1002': 401, - 'NR-2000': 400 + 'NR-2000': 400, + + 'NR-5000': 500 }; exports.getTestHttpServer = function(port, ip, callback) {
287270fa3c7e221a42f5b3c9df86dbffde6ab044
client/lib/navigate.js
client/lib/navigate.js
navigate = function (hash) { window.location.replace(Meteor.absoluteUrl(null, { secure: true }) + hash); };
navigate = function (hash) { window.location.replace(Meteor.absoluteUrl() + hash); };
Remove extra option to absoluteUrl
Remove extra option to absoluteUrl force-ssl already sets this option by default
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
--- +++ @@ -1,3 +1,3 @@ navigate = function (hash) { - window.location.replace(Meteor.absoluteUrl(null, { secure: true }) + hash); + window.location.replace(Meteor.absoluteUrl() + hash); };
e6e8849a1f8b3ee60f7e595bd71cdc53194a307c
app/notes/notes-form/notes-form.controller.js
app/notes/notes-form/notes-form.controller.js
{ angular.module('meganote.notesForm') .controller('NotesFormController', NotesFormController); NotesFormController.$inject = ['$state', 'Flash', 'NotesService']; function NotesFormController($state, Flash, NotesService) { const vm = this; vm.note = NotesService.find($state.params.noteId); vm.clearForm = clearForm; vm.save = save; vm.destroy = destroy; ///////////////// function clearForm() { vm.note = { title: '', body_html: '' }; } function save() { if (vm.note._id) { NotesService.update(vm.note) .then( function(res) { vm.note = angular.copy(res.data.note); Flash.create('success', res.data.message); }, function() { Flash.create('danger', 'Oops! Something went wrong.'); }); } else { NotesService.create(vm.note) .then( function(res) { vm.note = res.data.note; Flash.create('success', res.data.message); $state.go('notes.form', { noteId: vm.note._id }); }, function() { Flash.create('danger', 'Oops! Something went wrong.'); }); } } function destroy() { NotesService.destroy(vm.note) .then(function() { vm.clearForm(); }); } } }
{ angular.module('meganote.notesForm') .controller('NotesFormController', NotesFormController); NotesFormController.$inject = ['$state', 'Flash', 'NotesService']; function NotesFormController($state, Flash, NotesService) { const vm = this; vm.note = NotesService.find($state.params.noteId); vm.clearForm = clearForm; vm.save = save; vm.destroy = destroy; ///////////////// function clearForm() { vm.note = { title: '', body_html: '' }; } function save() { if (vm.note._id) { NotesService.update(vm.note) .then( res => { vm.note = angular.copy(res.data.note); Flash.create('success', res.data.message); }, () => Flash.create('danger', 'Oops! Something went wrong.') ); } else { NotesService.create(vm.note) .then( res => { vm.note = res.data.note; Flash.create('success', res.data.message); $state.go('notes.form', { noteId: vm.note._id }); }, () => Flash.create('danger', 'Oops! Something went wrong.') ); } } function destroy() { NotesService.destroy(vm.note) .then( () => vm.clearForm() ); } } }
Use fat arrow syntax for callbacks.
Use fat arrow syntax for callbacks.
JavaScript
mit
xternbootcamp16/meganote,xternbootcamp16/meganote
--- +++ @@ -20,33 +20,31 @@ if (vm.note._id) { NotesService.update(vm.note) .then( - function(res) { + res => { vm.note = angular.copy(res.data.note); Flash.create('success', res.data.message); }, - function() { - Flash.create('danger', 'Oops! Something went wrong.'); - }); + () => Flash.create('danger', 'Oops! Something went wrong.') + ); } else { NotesService.create(vm.note) .then( - function(res) { + res => { vm.note = res.data.note; Flash.create('success', res.data.message); $state.go('notes.form', { noteId: vm.note._id }); }, - function() { - Flash.create('danger', 'Oops! Something went wrong.'); - }); + () => Flash.create('danger', 'Oops! Something went wrong.') + ); } } function destroy() { NotesService.destroy(vm.note) - .then(function() { - vm.clearForm(); - }); + .then( + () => vm.clearForm() + ); } } }
d3218561b7863cc7a7905624a7638709eee10292
templates/spec/App.js
templates/spec/App.js
'use strict'; describe('<%= classedName %>', function () { var <%= scriptAppName %>, component; beforeEach(function () { var container = document.createElement('div'); container.id = 'content'; document.body.appendChild(container); <%= scriptAppName %> = require('../../../src/scripts/components/<%= scriptAppName %>.jsx'); component = <%= scriptAppName %>(); }); it('should create a new instance of <%= scriptAppName %>', function () { expect(component).toBeDefined(); }); });
'use strict'; describe('<%= classedName %>', function () { var React = require('react/addons'); var <%= scriptAppName %>, component; beforeEach(function () { var container = document.createElement('div'); container.id = 'content'; document.body.appendChild(container); <%= scriptAppName %> = require('../../../src/scripts/components/<%= scriptAppName %>.js'); component = React.createElement(<%= scriptAppName %>); }); it('should create a new instance of <%= scriptAppName %>', function () { expect(component).toBeDefined(); }); });
Fix error and warning in test
Fix error and warning in test Fix `jsx` extension Fix warning "Something is calling a React component directly"
JavaScript
mit
andrewliebchen/generator-react-webpack,cmil/generator-react-webpack,ties/generator-react-reflux-webpack,cmil/generator-react-webpack,newtriks/generator-react-webpack,andrewliebchen/generator-react-webpack,mattludwigs/generator-react-redux-kit,adnasa/generator-react-webpack,akampjes/generator-react-webpack,react-webpack-generators/generator-react-webpack,justin3737/generator-react-webpack,yonatanmn/generator-react-webpack,rogeriochaves/generator-react-webpack,yonatanmn/generator-react-webpack,justin3737/generator-react-webpack,mjul/generator-react-webpack,mattludwigs/generator-react-redux-kit,adnasa/generator-react-webpack,rogeriochaves/generator-react-webpack,akampjes/generator-react-webpack,mjul/generator-react-webpack,ties/generator-react-reflux-webpack
--- +++ @@ -1,6 +1,7 @@ 'use strict'; describe('<%= classedName %>', function () { + var React = require('react/addons'); var <%= scriptAppName %>, component; beforeEach(function () { @@ -8,8 +9,8 @@ container.id = 'content'; document.body.appendChild(container); - <%= scriptAppName %> = require('../../../src/scripts/components/<%= scriptAppName %>.jsx'); - component = <%= scriptAppName %>(); + <%= scriptAppName %> = require('../../../src/scripts/components/<%= scriptAppName %>.js'); + component = React.createElement(<%= scriptAppName %>); }); it('should create a new instance of <%= scriptAppName %>', function () {
4d764b92798d254a70023f427c745beaa52e2d0b
src/app/layout/shell.directive.js
src/app/layout/shell.directive.js
export default function shellDirective() { return { templateUrl: 'app/layout/shell.html', restrict: 'EA', transclude: true, scope: true, controller: 'ShellController', controllerAs: 'vm' }; }
export default function shellDirective() { return { templateUrl: 'app/layout/shell.html', restrict: 'EA', transclude: true, scope: {}, controller: 'ShellController', controllerAs: 'vm' }; }
Change to correct isolate scope in shell
Change to correct isolate scope in shell
JavaScript
mit
tekerson/ng-bookmarks,tekerson/ng-bookmarks
--- +++ @@ -3,7 +3,7 @@ templateUrl: 'app/layout/shell.html', restrict: 'EA', transclude: true, - scope: true, + scope: {}, controller: 'ShellController', controllerAs: 'vm' };
0097ef31cbc2e6bae1e368aab277ebbfc5d8bda1
website/app/application/core/projects/project/processes/process-view-controller.js
website/app/application/core/projects/project/processes/process-view-controller.js
(function (module) { module.controller('projectViewProcess', projectViewProcess); projectViewProcess.$inject = ["$state", "process"]; function projectViewProcess($state, process) { var ctrl = this; ctrl.editProvenance = editProvenance; ctrl.process = process; function editProvenance() { $state.go('projects.project.processes.edit', {process_id: ctrl.process.id}); } } }(angular.module('materialscommons')));
(function (module) { module.controller('projectViewProcess', projectViewProcess); projectViewProcess.$inject = ["process"]; function projectViewProcess(process) { var ctrl = this; ctrl.process = process; } }(angular.module('materialscommons')));
Remove editProvenance and replace with ui-sref.
Remove editProvenance and replace with ui-sref.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
--- +++ @@ -1,14 +1,9 @@ (function (module) { module.controller('projectViewProcess', projectViewProcess); - projectViewProcess.$inject = ["$state", "process"]; + projectViewProcess.$inject = ["process"]; - function projectViewProcess($state, process) { + function projectViewProcess(process) { var ctrl = this; - ctrl.editProvenance = editProvenance; ctrl.process = process; - - function editProvenance() { - $state.go('projects.project.processes.edit', {process_id: ctrl.process.id}); - } } }(angular.module('materialscommons')));
3a31a49eda82c7eb1f41e64b60f4f5e98b2b2113
app/utils/websockets.js
app/utils/websockets.js
import WebSocketClient from 'websocket.js'; import config from '../config'; import createQueryString from './createQueryString'; import { User } from 'app/actions/ActionTypes'; export default function createWebSocketMiddleware() { let socket = null; return store => { const makeSocket = jwt => { if (socket || !jwt) return; const qs = createQueryString({ jwt }); socket = new WebSocketClient(`${config.wsServerUrl}/${qs}`); socket.onmessage = event => { const { type, payload, meta } = JSON.parse(event.data); store.dispatch({ type, payload, meta }); }; socket.onopen = () => { store.dispatch({ type: 'WS_CONNECTED' }); }; socket.onclose = () => { store.dispatch({ type: 'WS_CLOSED' }); }; socket.onerror = () => { store.dispatch({ type: 'WS_ERROR' }); }; }; return next => action => { if (action.type === 'REHYDRATED') { makeSocket(store.getState().auth.token); return next(action); } if (action.type === User.LOGIN.SUCCESS) { makeSocket(action.payload.token); return next(action); } if (action.type === User.LOGOUT) { if (socket) { socket.close(); } socket = null; return next(action); } return next(action); }; }; }
import WebSocketClient from 'websocket.js'; import config from '../config'; import createQueryString from './createQueryString'; import { addNotification } from 'app/actions/NotificationActions'; import { User } from 'app/actions/ActionTypes'; export default function createWebSocketMiddleware() { let socket = null; return store => { const makeSocket = jwt => { if (socket || !jwt) return; const qs = createQueryString({ jwt }); socket = new WebSocketClient(`${config.wsServerUrl}/${qs}`); socket.onmessage = event => { const { type, payload, meta } = JSON.parse(event.data); store.dispatch({ type, payload, meta }); if (meta.errorMessage) { store.dispatch(addNotification({ message: meta.errorMessage })); } }; socket.onopen = () => { store.dispatch({ type: 'WS_CONNECTED' }); }; socket.onclose = () => { store.dispatch({ type: 'WS_CLOSED' }); }; socket.onerror = () => { store.dispatch({ type: 'WS_ERROR' }); }; }; return next => action => { if (action.type === 'REHYDRATED') { makeSocket(store.getState().auth.token); return next(action); } if (action.type === User.LOGIN.SUCCESS) { makeSocket(action.payload.token); return next(action); } if (action.type === User.LOGOUT) { if (socket) { socket.close(); } socket = null; return next(action); } return next(action); }; }; }
Add errorMessage notifcation from backend
Add errorMessage notifcation from backend
JavaScript
mit
webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp
--- +++ @@ -1,6 +1,7 @@ import WebSocketClient from 'websocket.js'; import config from '../config'; import createQueryString from './createQueryString'; +import { addNotification } from 'app/actions/NotificationActions'; import { User } from 'app/actions/ActionTypes'; export default function createWebSocketMiddleware() { @@ -16,6 +17,9 @@ socket.onmessage = event => { const { type, payload, meta } = JSON.parse(event.data); store.dispatch({ type, payload, meta }); + if (meta.errorMessage) { + store.dispatch(addNotification({ message: meta.errorMessage })); + } }; socket.onopen = () => {
75c31652c76d58aef83a2cfd1cdbcd446abb2380
src/routes/Publication/index.js
src/routes/Publication/index.js
import Publication from 'common/modules/Publication/pages/Publication/Publication' import Organization from 'common/modules/Publication/pages/Organization/Organization' import PublishingDatasets from 'common/modules/Publication/pages/PublishingDatasets/PublishingDatasets' import OrganizationProducers from 'common/modules/Publication/pages/OrganizationProducers/OrganizationProducers' export default () => ({ path: 'publication', indexRoute: { component: Publication }, childRoutes: [ { path: ':organizationId', component: Organization }, { path: ':organizationId/datasets', component: PublishingDatasets }, { path: ':organizationId/producers', component: OrganizationProducers } ] })
export default () => ({ path: 'publication', indexRoute: { async getComponent(nextState, cb) { const Publication = await import( /* webpackChunkName: 'publication' */ 'common/modules/Publication/pages/Publication/Publication' ) cb(null, Publication.default) } }, childRoutes: [ { path: ':organizationId', async getComponent(nextState, cb) { const Organization = await import( /* webpackChunkName: 'publication' */ 'common/modules/Publication/pages/Organization/Organization' ) cb(null, Organization.default) } }, { path: ':organizationId/datasets', async getComponent(nextState, cb) { const PublishingDatasets = await import( /* webpackChunkName: 'publication' */ 'common/modules/Publication/pages/PublishingDatasets/PublishingDatasets' ) cb(null, PublishingDatasets.default) } }, { path: ':organizationId/producers', async getComponent(nextState, cb) { const OrganizationProducers = await import( /* webpackChunkName: 'publication' */ 'common/modules/Publication/pages/OrganizationProducers/OrganizationProducers' ) cb(null, OrganizationProducers.default) } } ] })
Split publication route out of the main bundle
Split publication route out of the main bundle Reduce the initial bundle sizes for more than 9KB gzipped.
JavaScript
mit
sgmap/inspire,sgmap/inspire
--- +++ @@ -1,27 +1,50 @@ -import Publication from 'common/modules/Publication/pages/Publication/Publication' -import Organization from 'common/modules/Publication/pages/Organization/Organization' -import PublishingDatasets from 'common/modules/Publication/pages/PublishingDatasets/PublishingDatasets' -import OrganizationProducers from 'common/modules/Publication/pages/OrganizationProducers/OrganizationProducers' - export default () => ({ path: 'publication', indexRoute: { - component: Publication + async getComponent(nextState, cb) { + const Publication = await import( + /* webpackChunkName: 'publication' */ + 'common/modules/Publication/pages/Publication/Publication' + ) + + cb(null, Publication.default) + } }, childRoutes: [ { path: ':organizationId', - component: Organization + async getComponent(nextState, cb) { + const Organization = await import( + /* webpackChunkName: 'publication' */ + 'common/modules/Publication/pages/Organization/Organization' + ) + + cb(null, Organization.default) + } }, { path: ':organizationId/datasets', - component: PublishingDatasets + async getComponent(nextState, cb) { + const PublishingDatasets = await import( + /* webpackChunkName: 'publication' */ + 'common/modules/Publication/pages/PublishingDatasets/PublishingDatasets' + ) + + cb(null, PublishingDatasets.default) + } }, { path: ':organizationId/producers', - component: OrganizationProducers + async getComponent(nextState, cb) { + const OrganizationProducers = await import( + /* webpackChunkName: 'publication' */ + 'common/modules/Publication/pages/OrganizationProducers/OrganizationProducers' + ) + + cb(null, OrganizationProducers.default) + } } ] })
dc67381059f21dc620a9286cd8ea18d4129d2833
lib/tap_i18next/tap_i18next_init.js
lib/tap_i18next/tap_i18next_init.js
TAPi18next.init({resStore: {}, fallbackLng: globals.fallback_language});
TAPi18next.init({resStore: {}, fallbackLng: globals.fallback_language, useCookie: false});
Disable TAPi18next cookie feature that caused anomalies
Disable TAPi18next cookie feature that caused anomalies
JavaScript
mit
TAPevents/tap-i18n,glyphing/tap-i18n,TAPevents/tap-i18n,phowat/tap-i18n,glyphing/tap-i18n,phowat/tap-i18n,glyphing/tap-i18n,TAPevents/tap-i18n,phowat/tap-i18n
--- +++ @@ -1 +1 @@ -TAPi18next.init({resStore: {}, fallbackLng: globals.fallback_language}); +TAPi18next.init({resStore: {}, fallbackLng: globals.fallback_language, useCookie: false});
8f42ebe887e9e823f03e2d0bc6f6105b87e2c113
test/client/client.js
test/client/client.js
var assert = require('chai').assert; var convert = require('../../browser'); var data = require('../data'); var formats = data.formats; var tests = data.tests; describe('client-side', function() { tests.forEach(function(test) { it(test.desc, function(done) { test.opts = {}; var result = convert(test.delta, formats, test.opts); assert.equal(result, test.expected); done(); }); }); it('throws an error for a delta with non-inserts', function() { assert.throws(function() { convert({ ops: [{ insert: 'abc' }, { retain: 3 }] }, formats); }, 'Cannot convert delta with non-insert operations'); }); });
var assert = require('chai').assert; var convert = require('../../browser'); var data = require('../data'); var formats = data.formats; var tests = data.tests; describe('client-side', function() { tests.forEach(function(test) { it(test.desc, function(done) { if (!test.hasOwnProperty('opts')) { test.opts = {}; } var result = convert(test.delta, formats, test.opts); assert.equal(result, test.expected); done(); }); }); it('throws an error for a delta with non-inserts', function() { assert.throws(function() { convert({ ops: [{ insert: 'abc' }, { retain: 3 }] }, formats); }, 'Cannot convert delta with non-insert operations'); }); });
Check for test opts in data blob
Check for test opts in data blob
JavaScript
mit
thomsbg/convert-rich-text,thomsbg/convert-rich-text
--- +++ @@ -8,7 +8,9 @@ describe('client-side', function() { tests.forEach(function(test) { it(test.desc, function(done) { - test.opts = {}; + if (!test.hasOwnProperty('opts')) { + test.opts = {}; + } var result = convert(test.delta, formats, test.opts); assert.equal(result, test.expected); done();
20baa7058024290bf0f376bb8454731894607bc8
src/components/LambdaBricksApp.js
src/components/LambdaBricksApp.js
import React, { Component, PropTypes } from 'react' import JoyRide from 'react-joyride' import Library from '../containers/Library' import Workspace from '../containers/Workspace' const styles = { display: 'flex' } export default class LambdaBricksApp extends Component { constructor() { super() this.state = { joyrideOverlay: true, joyrideType: 'continuous', ready: false, showStepsProgress: true, steps: [ { title: 'Library', text: 'Library description', selector: '#library', position: 'right' }, { title: 'Constants', text: 'Constants description', selector: '#constants', position: 'right' } ] } } componentDidMount() { this.setState({ ready: true }) } componentDidUpdate(prevProps, prevState) { if(!prevState.ready && this.state.ready) { this.refs.joyride.start(true) } } render() { const state = this.state return ( <div style={ styles }> <Library /> <Workspace /> <JoyRide ref="joyride" debug={ false } steps={ state.steps } type={ state.joyrideType } showSkipButton={ false } showStepsProgress={ state.showStepsProgress } showOverlay={ state.showOverlay } /> </div> ) } getChildContext() { return { locale: 'en' } } } LambdaBricksApp.childContextTypes = { locale: PropTypes.string.isRequired }
import React, { Component, PropTypes } from 'react' import Library from '../containers/Library' import Workspace from '../containers/Workspace' const styles = { display: 'flex' } export default class LambdaBricksApp extends Component { render() { return ( <div style={ styles }> <Library /> <Workspace /> </div> ) } getChildContext() { return { locale: 'en' } } } LambdaBricksApp.childContextTypes = { locale: PropTypes.string.isRequired }
Remove site tour from main app
Remove site tour from main app
JavaScript
agpl-3.0
lambdabricks/bricks-front-react
--- +++ @@ -1,5 +1,4 @@ import React, { Component, PropTypes } from 'react' -import JoyRide from 'react-joyride' import Library from '../containers/Library' import Workspace from '../containers/Workspace' @@ -9,59 +8,11 @@ } export default class LambdaBricksApp extends Component { - constructor() { - super() - - this.state = { - joyrideOverlay: true, - joyrideType: 'continuous', - ready: false, - showStepsProgress: true, - steps: [ - { - title: 'Library', - text: 'Library description', - selector: '#library', - position: 'right' - }, - { - title: 'Constants', - text: 'Constants description', - selector: '#constants', - position: 'right' - } - ] - } - } - - componentDidMount() { - this.setState({ - ready: true - }) - } - - componentDidUpdate(prevProps, prevState) { - if(!prevState.ready && this.state.ready) { - this.refs.joyride.start(true) - } - } - render() { - const state = this.state - return ( <div style={ styles }> <Library /> <Workspace /> - <JoyRide - ref="joyride" - debug={ false } - steps={ state.steps } - type={ state.joyrideType } - showSkipButton={ false } - showStepsProgress={ state.showStepsProgress } - showOverlay={ state.showOverlay } - /> </div> ) }
6b5e7506ed3c8b3c1a455adf88bbb29d655321a3
src/controllers/UserController.js
src/controllers/UserController.js
const { User } = require('./../models'); const getUser = (req, res) => { User.fetch({ facebook_id: req.query.facebook_id }) .then(fetchedUser => { res.status(200).json(fetchedUser); }) .catch(err => { console.err(err); }); }; const postUser = (req, res) => { const newUser = { facebook_id: req.body.facebook_id, first_name: req.body.first_name, last_name: req.body.last_name, display_name: req.body.display_name, gender: req.body.gender, photo_url: req.body.photo_url, }; User.save(newUser) .then(savedUser => { res.status(200).send(savedUser); }) .catch(err => { console.err(err); }); }; module.exports = { getUser, postUser, };
const { User } = require('./../models'); const getUser = (req, res) => { User.fetch({ facebook_id: req.query.facebook_id }) .then(results => results[0]) .then(fetchedUser => { if (fetchedUser) { res.status(200).json(fetchedUser); } else { res.sendStatus(404); } }) .catch(err => { console.error(err); res.status(500).json({ description: 'Gobble DB - User.fetch', error: err, }); }); }; const postUser = (req, res) => { const newUser = { facebook_id: req.body.facebook_id, first_name: req.body.first_name, last_name: req.body.last_name, display_name: req.body.display_name, gender: req.body.gender, photo_url: req.body.photo_url, }; User.save(newUser) .then(() => { // Not using mySQL response as of now console.log('New user success.'); User.fetch({ facebook_id: newUser.facebook_id }) .then(results => results[0]) .then(fetchedUser => { res.status(200).json(fetchedUser); }); }) .catch(err => { console.error(err); res.status(500).json({ description: 'Gobble DB - User.save', error: err, }); }); }; module.exports = { getUser, postUser, };
Add database interaction error handling
Add database interaction error handling
JavaScript
mit
gobble43/gobble-db
--- +++ @@ -2,11 +2,20 @@ const getUser = (req, res) => { User.fetch({ facebook_id: req.query.facebook_id }) + .then(results => results[0]) .then(fetchedUser => { - res.status(200).json(fetchedUser); + if (fetchedUser) { + res.status(200).json(fetchedUser); + } else { + res.sendStatus(404); + } }) .catch(err => { - console.err(err); + console.error(err); + res.status(500).json({ + description: 'Gobble DB - User.fetch', + error: err, + }); }); }; @@ -21,11 +30,21 @@ }; User.save(newUser) - .then(savedUser => { - res.status(200).send(savedUser); + .then(() => { + // Not using mySQL response as of now + console.log('New user success.'); + User.fetch({ facebook_id: newUser.facebook_id }) + .then(results => results[0]) + .then(fetchedUser => { + res.status(200).json(fetchedUser); + }); }) .catch(err => { - console.err(err); + console.error(err); + res.status(500).json({ + description: 'Gobble DB - User.save', + error: err, + }); }); };
c6d4ba9d67c3649fbfa071f29a383814f6b12524
setup.js
setup.js
var fs = require('fs'); function createDir(directory) { if (!fs.existsSync(directory)){ fs.mkdirSync(directory, 0766, function(err){ if(err) console.log(err); }); } } function createFile(filename, content) { if (!fs.exists(filename)) { fs.writeFile(filename, content, function(err){ if(err) console.log(err); }); } } function createDirs() { createDir('./saved-env'); createDir('./public/assets'); createDir('./public/assets/images'); createDir('./public/assets/images/screenshots'); createDir('./public/assets/images/screenshots/new'); createDir('./public/assets/images/screenshots/old'); createDir('./public/assets/images/screenshots/results'); } function createFiles() { createFile('executions.json', JSON.stringify({"log" : []})); } module.exports.directory = createDir; module.exports.file = createFile; module.exports.directories = createDirs; module.exports.files = createFiles;
var fs = require('fs'); function createDir(directory) { if (!fs.existsSync(directory)){ fs.mkdirSync(directory, 0766, function(err){ if(err) console.log(err); }); } } function createFile(filename, content) { if (!fs.existsSync(filename)) { fs.writeFile(filename, content, function(err){ if(err) console.log(err); }); } } function createDirs() { createDir('./saved-env'); createDir('./public/assets'); createDir('./public/assets/images'); createDir('./public/assets/images/screenshots'); createDir('./public/assets/images/screenshots/new'); createDir('./public/assets/images/screenshots/old'); createDir('./public/assets/images/screenshots/results'); if (fs.existsSync('./browser-list.json')) { var browsers = JSON.parse(fs.readFileSync('./browser-list.json')); var browser_list = browsers.browsers; for(i=0; i<browser_list.length; i++){ screensDir(browser_list[i]); } } } function createFiles() { createFile('./executions.json', JSON.stringify({"log" : []})); createFile('./browser-list.json', JSON.stringify({"browsers" : []})); } function screensDir(browser){ createDir('./public/assets/images/screenshots/new/' + browser); createDir('./public/assets/images/screenshots/old/' + browser); createDir('./public/assets/images/screenshots/results/' + browser); } module.exports.directory = createDir; module.exports.file = createFile; module.exports.directories = createDirs; module.exports.files = createFiles; module.exports.screensDir = screensDir;
Create per browser screenshot folder
Create per browser screenshot folder
JavaScript
mit
at1as/Website-Diff
--- +++ @@ -10,7 +10,7 @@ } function createFile(filename, content) { - if (!fs.exists(filename)) { + if (!fs.existsSync(filename)) { fs.writeFile(filename, content, function(err){ if(err) console.log(err); }); @@ -25,10 +25,24 @@ createDir('./public/assets/images/screenshots/new'); createDir('./public/assets/images/screenshots/old'); createDir('./public/assets/images/screenshots/results'); + if (fs.existsSync('./browser-list.json')) { + var browsers = JSON.parse(fs.readFileSync('./browser-list.json')); + var browser_list = browsers.browsers; + for(i=0; i<browser_list.length; i++){ + screensDir(browser_list[i]); + } + } } function createFiles() { - createFile('executions.json', JSON.stringify({"log" : []})); + createFile('./executions.json', JSON.stringify({"log" : []})); + createFile('./browser-list.json', JSON.stringify({"browsers" : []})); +} + +function screensDir(browser){ + createDir('./public/assets/images/screenshots/new/' + browser); + createDir('./public/assets/images/screenshots/old/' + browser); + createDir('./public/assets/images/screenshots/results/' + browser); } module.exports.directory = createDir; @@ -36,3 +50,5 @@ module.exports.directories = createDirs; module.exports.files = createFiles; + +module.exports.screensDir = screensDir;
5cfcfb77f47f6c7b981af4a70ded14023300fe5d
lib/di.js
lib/di.js
let Promise = require('bluebird'); let fnArgs = require('fn-args'); let dict = {}; module.exports = () => { let di = { value: (name, val) => { dict[name] = { type: 'value', x: val }; return di; }, factory: (name, fx) => { dict[name] = { type: 'factory', x: fx }; return di; }, invoke: (fx, context, hardcodedArgs) => { let args = fnArgs(fx); args = args.map((name) => { for (a in hardcodedArgs) { if (a === name) return hardcodedArgs[a]; } let d = dict[name]; if (!d) throw new Error(`Unknown dependency: '${name}'`); if (d.type === 'value') return d.x; else if (d.type === 'factory') return di.invoke(d.x, context, hardcodedArgs); else return undefined; }); return fx.apply(context, args); } }; return di; };
let Promise = require('bluebird'); let fnArgs = require('fn-args'); let dict = {}; module.exports = () => { let di = { value: (name, val) => { dict[name] = { type: 'value', x: val }; return di; }, factory: (name, fx) => { dict[name] = { type: 'factory', x: fx }; return di; }, invoke: (fx, context, hardcodedArgs) => { let args = fnArgs(fx); args = args.map((name) => { for (a in hardcodedArgs) { if (a === name) return hardcodedArgs[a]; } let d = dict[name]; if (!d) log.debug(`Unknown dependency: '${name}'`); if (d.type === 'value') return d.x; else if (d.type === 'factory') return di.invoke(d.x, context, hardcodedArgs); else return undefined; }); return fx.apply(context, args); } }; return di; };
Print debug message when there are unknown dependencies rather than throw
Print debug message when there are unknown dependencies rather than throw
JavaScript
mit
dhjohn0/express-yourself,dhjohn0/express-yourself
--- +++ @@ -29,7 +29,7 @@ let d = dict[name]; if (!d) - throw new Error(`Unknown dependency: '${name}'`); + log.debug(`Unknown dependency: '${name}'`); if (d.type === 'value') return d.x; else if (d.type === 'factory')
1476d59ac9030ef9c417de678c78771f5785d16c
lumber.js
lumber.js
#! /usr/bin/env node // __ _____ _____ _____ _____ _____ // | | | | | | __ | __| __ | // | |__| | | | | | __ -| __| -| // |_____|_____|_|_|_|_____|_____|__|__| const program = require('commander'); const packagejson = require('./package.json'); program .version(packagejson.version) .command('generate', 'generate your admin panel application based on your database schema') .command('update', 'update your models\'s definition according to your database schema') .command('deploy', 'deploy your admin panel application to production') .command('user', 'show your current logged user') .command('login', 'sign in to your Forest account') .command('logout', 'sign out of your Forest account') .parse(process.argv);
#! /usr/bin/env node // __ _____ _____ _____ _____ _____ // | | | | | | __ | __| __ | // | |__| | | | | | __ -| __| -| // |_____|_____|_|_|_|_____|_____|__|__| const program = require('commander'); const packagejson = require('./package.json'); program .version(packagejson.version) .command('generate <projectName>', 'generate your admin panel application based on your database schema') .command('update', 'update your models\'s definition according to your database schema') .command('deploy', 'deploy your admin panel application to production') .command('user', 'show your current logged user') .command('login', 'sign in to your Forest account') .command('logout', 'sign out of your Forest account') .parse(process.argv);
Add the <projectName> to the generate command's help
Add the <projectName> to the generate command's help
JavaScript
mit
ForestAdmin/lumber
--- +++ @@ -10,7 +10,7 @@ program .version(packagejson.version) - .command('generate', 'generate your admin panel application based on your database schema') + .command('generate <projectName>', 'generate your admin panel application based on your database schema') .command('update', 'update your models\'s definition according to your database schema') .command('deploy', 'deploy your admin panel application to production') .command('user', 'show your current logged user')
41aeec2d840fd530ff07440d0161baaf08098861
src/js/model/refugee-constants.js
src/js/model/refugee-constants.js
var moment = require('moment'); // note that month indices are zero-based module.exports.DATA_START_YEAR = 2012; module.exports.DATA_START_MONTH = 0; module.exports.DATA_END_YEAR = 2015; module.exports.DATA_END_MONTH = 10; module.exports.DATA_END_MOMENT = moment([ module.exports.DATA_END_YEAR, module.exports.DATA_END_MONTH]).endOf('month'); module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2016, 0, 6]); module.exports.SYRIA_REFUGEES_DATA_UPDATED_MOMENT = moment([2016, 0, 6]); module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN']; module.exports.labelShowBreakPoint = 992;
var moment = require('moment'); // NOTE: month indices are zero-based module.exports.DATA_START_YEAR = 2012; module.exports.DATA_START_MONTH = 0; module.exports.DATA_START_MOMENT = moment([ module.exports.DATA_START_YEAR, module.exports.DATA_START_MONTH]).startOf('month'); module.exports.DATA_END_YEAR = 2015; module.exports.DATA_END_MONTH = 10; module.exports.DATA_END_MOMENT = moment([ module.exports.DATA_END_YEAR, module.exports.DATA_END_MONTH]).endOf('month'); module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2016, 0, 6]); module.exports.SYRIA_REFUGEES_DATA_UPDATED_MOMENT = moment([2016, 0, 6]); module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN']; module.exports.labelShowBreakPoint = 992;
Add start data moment to RefugeeConstants
Add start data moment to RefugeeConstants
JavaScript
mit
lucified/lucify-asylum-countries,lucified/lucify-asylum-countries,lucified/lucify-asylum-countries,lucified/lucify-asylum-countries
--- +++ @@ -1,14 +1,16 @@ var moment = require('moment'); -// note that month indices are zero-based +// NOTE: month indices are zero-based module.exports.DATA_START_YEAR = 2012; module.exports.DATA_START_MONTH = 0; +module.exports.DATA_START_MOMENT = moment([ + module.exports.DATA_START_YEAR, + module.exports.DATA_START_MONTH]).startOf('month'); module.exports.DATA_END_YEAR = 2015; module.exports.DATA_END_MONTH = 10; - module.exports.DATA_END_MOMENT = moment([ module.exports.DATA_END_YEAR, module.exports.DATA_END_MONTH]).endOf('month');
a85d6fc088e1b875bdd306ff14dca86d74ea3d90
src/test/.eslintrc.js
src/test/.eslintrc.js
// @flow module.exports = { env: { jest: true, }, plugins: ['jest', 'testing-library', 'jest-formatting', 'jest-dom'], extends: [ 'plugin:jest/recommended', 'plugin:testing-library/react', 'plugin:jest-dom/recommended', ], rules: { 'react/jsx-no-bind': 0, // This rule isn't useful because use Flow. 'jest/valid-title': 0, // Adding more errors now 'testing-library/no-manual-cleanup': 'error', 'testing-library/no-wait-for-empty-callback': 'error', 'testing-library/no-wait-for-snapshot': 'error', 'testing-library/prefer-explicit-assert': 'error', 'testing-library/prefer-presence-queries': 'error', 'testing-library/prefer-wait-for': 'error', // Individual jest-formatting rules so that we format only test and describe blocks 'jest-formatting/padding-around-describe-blocks': 2, 'jest-formatting/padding-around-test-blocks': 2, }, };
// @flow module.exports = { env: { jest: true, }, plugins: ['jest', 'testing-library', 'jest-formatting', 'jest-dom'], extends: [ 'plugin:jest/recommended', 'plugin:testing-library/react', 'plugin:jest-dom/recommended', ], rules: { 'react/jsx-no-bind': 0, // This rule isn't useful because use Flow. 'jest/valid-title': 0, // Adding more errors now 'testing-library/no-manual-cleanup': 'error', 'testing-library/no-wait-for-snapshot': 'error', 'testing-library/prefer-explicit-assert': 'error', 'testing-library/prefer-presence-queries': 'error', 'testing-library/prefer-wait-for': 'error', // Disable some rules that are in the "recommended" part. // This is a purely stylistic rule 'testing-library/render-result-naming-convention': 'off', // This disallows using `container`, but this is still useful for us sometimes 'testing-library/no-container': 'off', // This disallows using direct Node properties (eg: firstChild), but we have // legitimate uses: 'testing-library/no-node-access': 'off', // Disable until https://github.com/testing-library/eslint-plugin-testing-library/issues/359 // is fixed. 'testing-library/await-async-query': 'off', // Individual jest-formatting rules so that we format only test and describe blocks 'jest-formatting/padding-around-describe-blocks': 2, 'jest-formatting/padding-around-test-blocks': 2, }, };
Disable some new rules that are too strict for us
Disable some new rules that are too strict for us
JavaScript
mpl-2.0
mstange/cleopatra,mstange/cleopatra
--- +++ @@ -16,11 +16,22 @@ // Adding more errors now 'testing-library/no-manual-cleanup': 'error', - 'testing-library/no-wait-for-empty-callback': 'error', 'testing-library/no-wait-for-snapshot': 'error', 'testing-library/prefer-explicit-assert': 'error', 'testing-library/prefer-presence-queries': 'error', 'testing-library/prefer-wait-for': 'error', + + // Disable some rules that are in the "recommended" part. + // This is a purely stylistic rule + 'testing-library/render-result-naming-convention': 'off', + // This disallows using `container`, but this is still useful for us sometimes + 'testing-library/no-container': 'off', + // This disallows using direct Node properties (eg: firstChild), but we have + // legitimate uses: + 'testing-library/no-node-access': 'off', + // Disable until https://github.com/testing-library/eslint-plugin-testing-library/issues/359 + // is fixed. + 'testing-library/await-async-query': 'off', // Individual jest-formatting rules so that we format only test and describe blocks 'jest-formatting/padding-around-describe-blocks': 2,
a2ce854b67d556b5d61500b0371ff049b78740d8
src/utils/firebase.js
src/utils/firebase.js
import Firebase from 'firebase'; import config from 'config'; export function firebaseInit() { // Authenticate with Firebase const ref = new Firebase(config.get('firebase.path')); ref.authWithCustomToken(config.get('firebase.apiKey'), (error) => { if (error) { console.error('Terminating startup due to bad Firebase ref'); process.exit(1); } // Conveniently access the root ref Firebase.root = ref; }); }
import Firebase from 'firebase'; import config from 'config'; export function firebaseInit() { // Authenticate with Firebase const ref = new Firebase(config.get('firebase.path')); ref.authWithCustomToken(config.get('firebase.apiKey'), (error) => { if (error) { console.error('Terminating startup due to bad Firebase ref'); process.exit(1); } // Conveniently access the root ref Firebase.root = ref; }); } export function once(type, child) { return new Promise((resolve, reject) => { Firebase.root.child(child).once(type, (snapshot) => { resolve(snapshot.val()); }, (err) => { reject(err); }); }); }
Add Firebase once promise wrapper to facilitate async/await
Add Firebase once promise wrapper to facilitate async/await
JavaScript
mit
apazzolini/andreazzolini.com,apazzolini/andreazzolini.com
--- +++ @@ -14,3 +14,13 @@ Firebase.root = ref; }); } + +export function once(type, child) { + return new Promise((resolve, reject) => { + Firebase.root.child(child).once(type, (snapshot) => { + resolve(snapshot.val()); + }, (err) => { + reject(err); + }); + }); +}
5bc1a9c802d74c7a5bfa31c5543f87b5d6df7c94
src/waterfallError.js
src/waterfallError.js
export default class WaterfallError extends Error { get results() { return this._results; } set results(results) { if (this._results == null) { this._results = results; } return this; } constructor(...args) { super(...args); this.name = 'WaterfallError'; this._results = null; } };
module.exports = function WaterfallError(message, results) { Error.captureStackTrace(this, this.constructor); this.name = this.constructor.name; this.message = message; this.results = results; }; require('util').inherits(module.exports, Error);
Fix WaterfallError to properly extend Error
Fix WaterfallError to properly extend Error
JavaScript
mit
jgornick/asyncp
--- +++ @@ -1,20 +1,8 @@ -export default class WaterfallError extends Error { - get results() { - return this._results; - } +module.exports = function WaterfallError(message, results) { + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.message = message; + this.results = results; +}; - set results(results) { - if (this._results == null) { - this._results = results; - } - - return this; - } - - constructor(...args) { - super(...args); - - this.name = 'WaterfallError'; - this._results = null; - } -}; +require('util').inherits(module.exports, Error);
2fdd2802ef12e1e0fe339f36fc95d14b7128fe9f
src/scenes/AppRoot/presenter.js
src/scenes/AppRoot/presenter.js
/* * Application root * */ import React from 'react'; const AppRoot = props => { return ( <div className="application"> </div> ); }; export default AppRoot;
/* * Application root * */ import React from 'react'; import imgSrc from './images/redux.png'; const AppRoot = props => { return ( <div className="application"> Example component <div className="application__logo"> <img src={imgSrc} alt=""/> </div> </div> ); }; export default AppRoot;
Add image to example component
Add image to example component
JavaScript
mit
dashukin/react-redux-template,dashukin/react-redux-template
--- +++ @@ -3,11 +3,15 @@ * */ import React from 'react'; +import imgSrc from './images/redux.png'; const AppRoot = props => { return ( <div className="application"> - + Example component + <div className="application__logo"> + <img src={imgSrc} alt=""/> + </div> </div> ); };
58e66a7a78480e754336b7de24fa83b6a249eaa8
view/js/scripts.js
view/js/scripts.js
num=0; function createDiv(fil) { obj=fil.form; tab = document.createElement('div'); tab.id = 'calendario'; tab.style.padding = "1px"; tab.style.border = "1px solid red"; tab.style.background = "blue"; obj.appendChild(tab); }
$(document).ready(function(){ function exampleJQuery() { $("p").click(function(){ $(".classTest").hide(); }); } }); function createDiv(contentDiv,className) { var div = document.createElement('div'); div.className = className; var content = document.getElementById('content'); div.innerHTML = "<p>"+contentDiv+"</p>"; content.appendChild(div); }
Add function to create dynamic divs
Add function to create dynamic divs
JavaScript
bsd-3-clause
LuciaPerez/PUWI,LuciaPerez/PUWI,LuciaPerez/PUWI
--- +++ @@ -1,12 +1,20 @@ +$(document).ready(function(){ + function exampleJQuery() + { + $("p").click(function(){ + $(".classTest").hide(); + }); + } +}); -num=0; -function createDiv(fil) { - obj=fil.form; - tab = document.createElement('div'); - tab.id = 'calendario'; - tab.style.padding = "1px"; - tab.style.border = "1px solid red"; - tab.style.background = "blue"; - obj.appendChild(tab); -} + function createDiv(contentDiv,className) { + var div = document.createElement('div'); + div.className = className; + var content = document.getElementById('content'); + div.innerHTML = "<p>"+contentDiv+"</p>"; + content.appendChild(div); + } + + +
b1cfd2280111c2056e8504522bdcbe29a6269be8
client/helpers/handlebars.js
client/helpers/handlebars.js
/** * Simple pluralizer */ Handlebars.registerHelper('pluralize', function(n, thing) { if (n === 1) { return '1 ' + thing; } else { return n + ' ' + thing + 's'; } }); /** * Turn titles into CSS classes * * Remove puncuation * Spaces to undescores * Lowercase text */ Handlebars.registerHelper('lowerSpacesToDashes', function(input) { if (input) { return input.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()@\+\?><\[\]\+]/g, '').replace(/\s+/g, '-').toLowerCase(); } }); /** * Strip HTML from a string * * This is obviously imperfect, but I trust the data source...me. */ Handlebars.registerHelper('brToSpace', function(input) { if (input) { return input.replace(/<br ?\/?>/g, " ") } });
/** * Simple pluralizer */ Handlebars.registerHelper('pluralize', function(n, thing) { if (n === 1) { return '1 ' + thing; } else { return n + ' ' + thing + 's'; } }); /** * Turn titles into CSS classes * * Remove puncuation * Spaces to undescores * Lowercase text */ Handlebars.registerHelper('lowerSpacesToDashes', function(input) { if (input) { return input.replace(/[\.,'-\/#!$%\^&\*;:{}=\-_`~()@\+\?><\[\]\+]/g, '').replace(/\s+/g, '-').toLowerCase(); } }); /** * Strip HTML from a string * * This is obviously imperfect, but I trust the data source...me. */ Handlebars.registerHelper('brToSpace', function(input) { if (input) { return input.replace(/<br ?\/?>/g, " ") } });
Remove curly quotes as well
Remove curly quotes as well I have a few of these in titles and they were showing up in CSS clases.
JavaScript
mit
scimusmn/sd-waw,scimusmn/sd-waw
--- +++ @@ -18,7 +18,7 @@ */ Handlebars.registerHelper('lowerSpacesToDashes', function(input) { if (input) { - return input.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()@\+\?><\[\]\+]/g, '').replace(/\s+/g, '-').toLowerCase(); + return input.replace(/[\.,'-\/#!$%\^&\*;:{}=\-_`~()@\+\?><\[\]\+]/g, '').replace(/\s+/g, '-').toLowerCase(); } });
c6357f71e8e6cec97f9217579c5bee480388b807
client/src/lib/clientAuth.js
client/src/lib/clientAuth.js
module.exports = (router) => { // router is props.history from a component served by react router let cookies = {}; for (let cookie of document.cookie.split(';')) { let c = cookie.trim().split('='); cookies[c[0]] = c[1]; } if (!(cookies.fridgrSesh && cookies.fridgrSesh.userId && cookies.fridgrSesh.houseId)) { router.push('/login'); } };
import {parse} from 'cookie'; module.exports = (router) => { // router is props.history from a component served by react router let cookies = parse(document.cookie); if (!(cookies.fridgrSesh && cookies.fridgrSesh.userId && cookies.fridgrSesh.houseId)) { router.push('/login'); } };
Refactor auth to use npm cookie parse
Refactor auth to use npm cookie parse
JavaScript
mit
SentinelsOfMagic/SentinelsOfMagic
--- +++ @@ -1,10 +1,7 @@ +import {parse} from 'cookie'; module.exports = (router) => { // router is props.history from a component served by react router - let cookies = {}; - for (let cookie of document.cookie.split(';')) { - let c = cookie.trim().split('='); - cookies[c[0]] = c[1]; - } + let cookies = parse(document.cookie); if (!(cookies.fridgrSesh && cookies.fridgrSesh.userId && cookies.fridgrSesh.houseId)) { router.push('/login');
39c902c39ad446e8549ec253647d77fae1f27cc3
app/templates/Gruntfile.js
app/templates/Gruntfile.js
/*! * Generator-Gnar Gruntfile * http://gnarmedia.com * @author Adam Murphy */ // Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %> 'use strict'; /** * Grunt module */ module.exports = function (grunt) { /** * Generator-Gnar Grunt config */ grunt.initConfig({ ]); };
/*! * Generator-Gnar Gruntfile * http://gnarmedia.com * @author Adam Murphy */ // Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %> 'use strict'; /** * Grunt module */ module.exports = function (grunt) { /** * Generator-Gnar Grunt config */ grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), /** * Set project info */ project: { src: 'src', dist: 'dist', assets: '<%= project.dist %>/assets', css: [ '<%= project.src %>/scss/style.scss' ], js: [ '<%= project.src %>/js/*.js' ] } ]); };
Add pkg json and project variables
Add pkg json and project variables
JavaScript
mit
gnarmedia/gnenerator-gnar
--- +++ @@ -17,6 +17,23 @@ * Generator-Gnar Grunt config */ grunt.initConfig({ + + pkg: grunt.file.readJSON('package.json'), + + /** + * Set project info + */ + project: { + src: 'src', + dist: 'dist', + assets: '<%= project.dist %>/assets', + css: [ + '<%= project.src %>/scss/style.scss' + ], + js: [ + '<%= project.src %>/js/*.js' + ] + } ]); };
16c1e7f7fd59789d20ebe4d00675e8ebcd356dab
web/js/reducers.js
web/js/reducers.js
// Copyright © 2015-2017 Esko Luontola // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 /* @flow */ import combineReducers from "redux/es/combineReducers"; import type {ApiState} from "./apiReducer"; import api from "./apiReducer"; import type {ConfigState} from "./configReducer"; import config from "./configReducer"; import {reducer as form} from "redux-form"; export type State = { api: ApiState, config: ConfigState, form: any } export default combineReducers({ api, config, form, });
// Copyright © 2015-2017 Esko Luontola // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 /* @flow */ import combineReducers from "redux/lib/combineReducers"; import type {ApiState} from "./apiReducer"; import api from "./apiReducer"; import type {ConfigState} from "./configReducer"; import config from "./configReducer"; import {reducer as form} from "redux-form"; export type State = { api: ApiState, config: ConfigState, form: any } export default combineReducers({ api, config, form, });
Fix "SyntaxError: Unexpected token import" when running mocha tests
Fix "SyntaxError: Unexpected token import" when running mocha tests
JavaScript
apache-2.0
orfjackal/territory-bro,orfjackal/territory-bro,orfjackal/territory-bro
--- +++ @@ -4,7 +4,7 @@ /* @flow */ -import combineReducers from "redux/es/combineReducers"; +import combineReducers from "redux/lib/combineReducers"; import type {ApiState} from "./apiReducer"; import api from "./apiReducer"; import type {ConfigState} from "./configReducer";
4f9c18ad8c3c2a974c7bd812a9e211b589fd4bbd
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { build: ['Gruntfile.js', 'src/**/*.js'] }, watch: { scripts: { files: 'src/**/*.js', tasks: ['jshint'] } }, copy: { build: { files: [ { expand: true, src: 'node_modules/knockout/build/output/knockout-latest.js', dest: 'dist/js/', flatten: true, rename: function (dest, src) { return dest + 'knockout.js'; } } ] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-copy'); // Default task(s). grunt.registerTask('default', ['jshint']); };
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { build: ['Gruntfile.js', 'src/**/*.js'] }, watch: { scripts: { files: 'src/**/*.js', tasks: ['jshint'] } }, copy: { build: { files: [ { expand: true, src: 'node_modules/knockout/build/output/knockout-latest.js', dest: 'dist/js/', flatten: true, rename: function (dest, src) { return dest + 'knockout.js'; } } ] } }, htmlmin: { build: { options: { removeComments: true, collapseWhitespace: true }, files: { 'dist/index.html': 'src/index.html' } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-htmlmin'); // Default task(s). grunt.registerTask('default', ['jshint']); };
Add htmlmin task to gruntfile
Add htmlmin task to gruntfile
JavaScript
mit
byanofsky/playa-vista-neighborhood,byanofsky/playa-vista-neighborhood,byanofsky/playa-vista-neighborhood
--- +++ @@ -26,12 +26,24 @@ } ] } + }, + htmlmin: { + build: { + options: { + removeComments: true, + collapseWhitespace: true + }, + files: { + 'dist/index.html': 'src/index.html' + } + } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-copy'); + grunt.loadNpmTasks('grunt-contrib-htmlmin'); // Default task(s). grunt.registerTask('default', ['jshint']);
e409839be5d1173fb8203da3eec8b21c8f93e0d8
Gruntfile.js
Gruntfile.js
module.exports = function (grunt) { var standaloneFiles = [ 'bower_components/sockjs-client/dist/sockjs.min.js', 'bower_components/stomp-websocket/lib/stomp.min.js', 'src/ng-stomp.js' ] grunt.initConfig({ fileExists: { scripts: standaloneFiles }, uglify: { main: { options: { preserveComments: 'some' }, files: { 'dist/ng-stomp.min.js': ['src/ng-stomp.js'], 'dist/ng-stomp.standalone.min.js': standaloneFiles } } }, standard: { options: { format: true }, app: { src: ['ng-stomp.js'] } } }) grunt.loadNpmTasks('grunt-file-exists') grunt.loadNpmTasks('grunt-contrib-uglify') grunt.loadNpmTasks('grunt-standard') grunt.registerTask('default', ['standard', 'fileExists', 'uglify']) }
module.exports = function (grunt) { var standaloneFiles = [ 'bower_components/sockjs-client/dist/sockjs.min.js', 'bower_components/stomp-websocket/lib/stomp.min.js', 'src/ng-stomp.js' ] grunt.initConfig({ fileExists: { scripts: standaloneFiles }, uglify: { main: { options: { preserveComments: 'some' }, files: { 'dist/ng-stomp.min.js': ['src/ng-stomp.js'], 'dist/ng-stomp.standalone.min.js': standaloneFiles } } } }) grunt.loadNpmTasks('grunt-file-exists') grunt.loadNpmTasks('grunt-contrib-uglify') grunt.registerTask('default', ['fileExists', 'uglify']) }
Disable StandardJS in Grunt to fix builds
Disable StandardJS in Grunt to fix builds
JavaScript
mit
beevelop/ng-stomp
--- +++ @@ -19,19 +19,10 @@ 'dist/ng-stomp.standalone.min.js': standaloneFiles } } - }, - standard: { - options: { - format: true - }, - app: { - src: ['ng-stomp.js'] - } } }) grunt.loadNpmTasks('grunt-file-exists') grunt.loadNpmTasks('grunt-contrib-uglify') - grunt.loadNpmTasks('grunt-standard') - grunt.registerTask('default', ['standard', 'fileExists', 'uglify']) + grunt.registerTask('default', ['fileExists', 'uglify']) }
467e1990ab2d63ae5816a8e2fa0408fbf4f23153
Gruntfile.js
Gruntfile.js
/* * grunt-contrib-watch * http://gruntjs.com/ * * Copyright (c) 2013 "Cowboy" Ben Alman, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/**/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, watch: { all: { files: ['<%= jshint.all %>'], tasks: ['jshint', 'nodeunit'], }, }, nodeunit: { tests: ['test/tasks/*_test.js'] } }); // Dynamic alias task to nodeunit. Run individual tests with: grunt test:events grunt.registerTask('test', function(file) { grunt.config('nodeunit.tests', String(grunt.config('nodeunit.tests')).replace('*', file || '*')); grunt.task.run('nodeunit'); }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-contrib-internal'); grunt.registerTask('default', ['jshint', 'nodeunit', 'build-contrib']); };
/* * grunt-contrib-watch * http://gruntjs.com/ * * Copyright (c) 2013 "Cowboy" Ben Alman, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/**/*.js', '<%= nodeunit.tests %>', ], options: { jshintrc: '.jshintrc', }, }, watch: { all: { files: ['<%= jshint.all %>'], tasks: ['jshint', 'nodeunit'], }, }, nodeunit: { tests: ['test/tasks/*_test.js'], }, }); // Dynamic alias task to nodeunit. Run individual tests with: grunt test:events grunt.registerTask('test', function(file) { grunt.config('nodeunit.tests', String(grunt.config('nodeunit.tests')).replace('*', file || '*')); grunt.task.run('nodeunit'); }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-contrib-internal'); grunt.registerTask('default', ['jshint', 'nodeunit', 'build-contrib']); };
Add trailing commas (to secretly nudge travis-ci)
Add trailing commas (to secretly nudge travis-ci)
JavaScript
mit
chemoish/grunt-contrib-watch,AlexJeng/grunt-contrib-watch,testcodefresh/grunt-contrib-watch,gruntjs/grunt-contrib-watch,Rebzie/grunt-contrib-watch,JimRobs/grunt-chokidar,whisklabs/grunt-contrib-watch,yuhualingfeng/grunt-contrib-watch,Ariel-Isaacm/grunt-contrib-watch,mobify/grunt-contrib-watch,eddiemonge/grunt-contrib-watch
--- +++ @@ -14,11 +14,11 @@ all: [ 'Gruntfile.js', 'tasks/**/*.js', - '<%= nodeunit.tests %>' + '<%= nodeunit.tests %>', ], options: { - jshintrc: '.jshintrc' - } + jshintrc: '.jshintrc', + }, }, watch: { all: { @@ -27,8 +27,8 @@ }, }, nodeunit: { - tests: ['test/tasks/*_test.js'] - } + tests: ['test/tasks/*_test.js'], + }, }); // Dynamic alias task to nodeunit. Run individual tests with: grunt test:events
fb3ab9e1f1f32bdbd40c8bce56a3818a0c311cfe
spec/api-desktop-capturer-spec.js
spec/api-desktop-capturer-spec.js
var assert, desktopCapturer; assert = require('assert'); desktopCapturer = require('electron').desktopCapturer; describe('desktopCapturer', function() { return it('should return a non-empty array of sources', function(done) { return desktopCapturer.getSources({ types: ['window', 'screen'] }, function(error, sources) { assert.equal(error, null); assert.notEqual(sources.length, 0); return done(); }); }); });
const assert = require('assert'); const desktopCapturer = require('electron').desktopCapturer; describe('desktopCapturer', function() { it('should return a non-empty array of sources', function(done) { desktopCapturer.getSources({ types: ['window', 'screen'] }, function(error, sources) { assert.equal(error, null); assert.notEqual(sources.length, 0); done(); }); }); });
Use const and remove extra returns
Use const and remove extra returns
JavaScript
mit
deed02392/electron,bbondy/electron,astoilkov/electron,jhen0409/electron,brenca/electron,shiftkey/electron,posix4e/electron,dongjoon-hyun/electron,gabriel/electron,renaesop/electron,rreimann/electron,Floato/electron,wan-qy/electron,shiftkey/electron,bpasero/electron,joaomoreno/atom-shell,stevekinney/electron,aichingm/electron,noikiy/electron,thomsonreuters/electron,posix4e/electron,rreimann/electron,biblerule/UMCTelnetHub,posix4e/electron,rajatsingla28/electron,rajatsingla28/electron,Floato/electron,tonyganch/electron,noikiy/electron,astoilkov/electron,wan-qy/electron,seanchas116/electron,ankitaggarwal011/electron,Evercoder/electron,Floato/electron,ankitaggarwal011/electron,leethomas/electron,kcrt/electron,posix4e/electron,tinydew4/electron,stevekinney/electron,gabriel/electron,felixrieseberg/electron,joaomoreno/atom-shell,biblerule/UMCTelnetHub,tonyganch/electron,rreimann/electron,twolfson/electron,noikiy/electron,wan-qy/electron,aliib/electron,MaxWhere/electron,aichingm/electron,jhen0409/electron,dongjoon-hyun/electron,bpasero/electron,gabriel/electron,bpasero/electron,aichingm/electron,noikiy/electron,gerhardberger/electron,MaxWhere/electron,Gerhut/electron,twolfson/electron,brave/electron,biblerule/UMCTelnetHub,wan-qy/electron,tinydew4/electron,ankitaggarwal011/electron,thingsinjars/electron,seanchas116/electron,voidbridge/electron,ankitaggarwal011/electron,renaesop/electron,minggo/electron,brave/electron,renaesop/electron,tinydew4/electron,deed02392/electron,leethomas/electron,Gerhut/electron,brenca/electron,twolfson/electron,renaesop/electron,joaomoreno/atom-shell,Floato/electron,preco21/electron,pombredanne/electron,voidbridge/electron,gerhardberger/electron,thomsonreuters/electron,MaxWhere/electron,posix4e/electron,rajatsingla28/electron,preco21/electron,thingsinjars/electron,twolfson/electron,simongregory/electron,simongregory/electron,MaxWhere/electron,joaomoreno/atom-shell,brave/electron,gabriel/electron,astoilkov/electron,pombredanne/electron,Evercoder/electron,simongregory/electron,bpasero/electron,aliib/electron,thomsonreuters/electron,minggo/electron,tonyganch/electron,leethomas/electron,Evercoder/electron,the-ress/electron,Evercoder/electron,gabriel/electron,felixrieseberg/electron,rreimann/electron,brave/muon,kcrt/electron,Gerhut/electron,electron/electron,bbondy/electron,the-ress/electron,bpasero/electron,leethomas/electron,brave/electron,twolfson/electron,felixrieseberg/electron,aliib/electron,gerhardberger/electron,the-ress/electron,tonyganch/electron,kcrt/electron,kokdemo/electron,jhen0409/electron,aliib/electron,miniak/electron,kcrt/electron,rreimann/electron,thompsonemerson/electron,tonyganch/electron,brenca/electron,felixrieseberg/electron,rreimann/electron,minggo/electron,evgenyzinoviev/electron,Evercoder/electron,posix4e/electron,stevekinney/electron,evgenyzinoviev/electron,wan-qy/electron,gerhardberger/electron,bbondy/electron,simongregory/electron,astoilkov/electron,the-ress/electron,brenca/electron,shiftkey/electron,Floato/electron,rajatsingla28/electron,MaxWhere/electron,deed02392/electron,thompsonemerson/electron,preco21/electron,bpasero/electron,voidbridge/electron,Gerhut/electron,electron/electron,pombredanne/electron,brave/muon,brenca/electron,rajatsingla28/electron,jhen0409/electron,voidbridge/electron,electron/electron,aichingm/electron,electron/electron,stevekinney/electron,evgenyzinoviev/electron,gerhardberger/electron,miniak/electron,deed02392/electron,tinydew4/electron,gerhardberger/electron,felixrieseberg/electron,joaomoreno/atom-shell,kokdemo/electron,aliib/electron,miniak/electron,seanchas116/electron,shiftkey/electron,simongregory/electron,electron/electron,minggo/electron,miniak/electron,tinydew4/electron,preco21/electron,the-ress/electron,bbondy/electron,deed02392/electron,jhen0409/electron,shiftkey/electron,brave/muon,kokdemo/electron,seanchas116/electron,thingsinjars/electron,gabriel/electron,bbondy/electron,aliib/electron,kcrt/electron,renaesop/electron,pombredanne/electron,thompsonemerson/electron,Gerhut/electron,aichingm/electron,astoilkov/electron,voidbridge/electron,tinydew4/electron,dongjoon-hyun/electron,noikiy/electron,voidbridge/electron,leethomas/electron,jhen0409/electron,biblerule/UMCTelnetHub,the-ress/electron,brave/electron,noikiy/electron,aichingm/electron,Gerhut/electron,thompsonemerson/electron,seanchas116/electron,thompsonemerson/electron,stevekinney/electron,wan-qy/electron,bbondy/electron,brave/muon,biblerule/UMCTelnetHub,astoilkov/electron,brave/muon,ankitaggarwal011/electron,kokdemo/electron,shiftkey/electron,bpasero/electron,preco21/electron,felixrieseberg/electron,thingsinjars/electron,brave/muon,evgenyzinoviev/electron,brenca/electron,twolfson/electron,kcrt/electron,tonyganch/electron,thomsonreuters/electron,dongjoon-hyun/electron,Floato/electron,seanchas116/electron,stevekinney/electron,pombredanne/electron,MaxWhere/electron,thomsonreuters/electron,rajatsingla28/electron,thingsinjars/electron,Evercoder/electron,leethomas/electron,dongjoon-hyun/electron,gerhardberger/electron,ankitaggarwal011/electron,kokdemo/electron,minggo/electron,evgenyzinoviev/electron,kokdemo/electron,miniak/electron,deed02392/electron,evgenyzinoviev/electron,simongregory/electron,dongjoon-hyun/electron,electron/electron,preco21/electron,the-ress/electron,joaomoreno/atom-shell,minggo/electron,thingsinjars/electron,pombredanne/electron,biblerule/UMCTelnetHub,renaesop/electron,thomsonreuters/electron,electron/electron,thompsonemerson/electron,brave/electron,miniak/electron
--- +++ @@ -1,17 +1,14 @@ -var assert, desktopCapturer; - -assert = require('assert'); - -desktopCapturer = require('electron').desktopCapturer; +const assert = require('assert'); +const desktopCapturer = require('electron').desktopCapturer; describe('desktopCapturer', function() { - return it('should return a non-empty array of sources', function(done) { - return desktopCapturer.getSources({ + it('should return a non-empty array of sources', function(done) { + desktopCapturer.getSources({ types: ['window', 'screen'] }, function(error, sources) { assert.equal(error, null); assert.notEqual(sources.length, 0); - return done(); + done(); }); }); });
133394c011364a252a706b59b4f3f369922169e3
src/ui/components/ColorPicker/index.js
src/ui/components/ColorPicker/index.js
const ColorPicker = require("./components/ColorPicker"); module.exports = ColorPicker;
const ColorPicker = require("./components/ColorPicker"); /* ColorPicker is modified version of https://github.com/adhbh/react-color-selector */ module.exports = ColorPicker;
Add link to color picker original project
Add link to color picker original project
JavaScript
apache-2.0
FrantisekGazo/PCA-Viewer,FrantisekGazo/PCA-Viewer
--- +++ @@ -1,4 +1,4 @@ const ColorPicker = require("./components/ColorPicker"); - +/* ColorPicker is modified version of https://github.com/adhbh/react-color-selector */ module.exports = ColorPicker;
8c73221a2ecf53c4e72d43fd3b2e0421dbb342f3
test/lint.prettify.js
test/lint.prettify.js
// modules var assert = require('assert') var _ = require('underscore') var fs = require('fs'); var S = require('string'); var passmarked = require('passmarked'); var pluginFunc = require('../lib/rules/lint/prettify'); describe('lint', function(){ describe('#prettify', function(){ // handle the settings it('Should return a error if the message passed was undefined', function(done){ // handle the stream pluginFunc(undefined, function(err, content){ // check for a error if(!err) assert.fail('Was expecting a error for the undefined content'); // done done(); }); }); // handle the settings it('Should return a error if the message passed was null', function(done){ // handle the stream pluginFunc(null, function(err, content){ // check for a error if(!err) assert.fail('Was expecting a error for the null content'); // done done(); }); }); // handle the settings it('Should return a pretified version from our passed in CSS', function(done){ // handle the stream pluginFunc('.text{color:black;}', function(err, content){ // check for a error if(err) assert.fail(err); // check if not empty if(S(content).isEmpty() == true) assert.fail('Prettified content was blank') // should match a cleaned version if(content != `.text { color: black; }`) assert.fail('Did not clean the content correctly.'); // done done(); }); }); }); });
// modules var assert = require('assert') var _ = require('underscore') var fs = require('fs'); var S = require('string'); var passmarked = require('passmarked'); var pluginFunc = require('../lib/rules/lint/prettify'); describe('lint', function(){ describe('#prettify', function(){ // handle the settings it('Should return a error if the message passed was undefined', function(done){ // handle the stream pluginFunc(undefined, function(err, content){ // check for a error if(!err) assert.fail('Was expecting a error for the undefined content'); // done done(); }); }); // handle the settings it('Should return a error if the message passed was null', function(done){ // handle the stream pluginFunc(null, function(err, content){ // check for a error if(!err) assert.fail('Was expecting a error for the null content'); // done done(); }); }); // handle the settings it('Should return a pretified version from our passed in CSS', function(done){ // handle the stream pluginFunc('.text{color:black;}', function(err, content){ // check for a error if(err) assert.fail(err); // check if not empty if(S(content).isEmpty() == true) assert.fail('Prettified content was blank') // should match a cleaned version if(content.replace(/\s+/gi, '') != '.text{color: black;}'.replace(/\s+/gi, '')) assert.fail('Did not clean the content correctly.'); // done done(); }); }); }); });
Update to not use newer ES6 function so we can support Node 0.12
Update to not use newer ES6 function so we can support Node 0.12
JavaScript
apache-2.0
passmarked/css
--- +++ @@ -56,10 +56,7 @@ assert.fail('Prettified content was blank') // should match a cleaned version - if(content != `.text -{ - color: black; -}`) + if(content.replace(/\s+/gi, '') != '.text{color: black;}'.replace(/\s+/gi, '')) assert.fail('Did not clean the content correctly.'); // done
97597e00b5f2a105a201dd283a07986bd073f9ce
templates/jqplugin.js
templates/jqplugin.js
/** * <%= name %> * * Makes bla bla. * * @version 0.0.0 * @requires jQuery * @author <%= authorName %> * @copyright <%= (new Date).getFullYear() %> <%= authorName %>, <%= authorUrl %> * @license MIT */ /*jshint browser:true, jquery:true, white:false, smarttabs:true, eqeqeq:true, immed:true, latedef:false, newcap:true, undef:true */ /*global define:false*/ ;(function(factory) { // Try to register as an anonymous AMD module if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { factory(jQuery); } }(function($) { 'use strict'; $.fn.<%= method %> = function(options) { options = $.extend({}, $.fn.<%= method %>.defaults, options); return this.each(function() { // var elem = $(this); new <%= cls %>($(this), options); }); }; $.fn.<%= method %>.defaults = { }; function <%= cls %>(container, options) { this.container = container; this.options = options; this.init(); } <%= cls %>.prototype = { init: function() { /* Magic begins here */ } }; }));
/** * <%= name %> * * Makes bla bla. * * @version 0.0.0 * @requires jQuery * @author <%= authorName %> * @copyright <%= (new Date).getFullYear() %> <%= authorName %>, <%= authorUrl %> * @license MIT */ /*global define:false*/ ;(function(factory) { // Try to register as an anonymous AMD module if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { factory(jQuery); } }(function($) { 'use strict'; $.fn.<%= method %> = function(options) { options = $.extend({}, $.fn.<%= method %>.defaults, options); return this.each(function() { // var elem = $(this); new <%= cls %>($(this), options); }); }; $.fn.<%= method %>.defaults = { }; function <%= cls %>(container, options) { this.container = container; this.options = options; this.init(); } <%= cls %>.prototype = { init: function() { /* Magic begins here */ } }; }));
Fix code style, remove JSHint comment.
jQuery: Fix code style, remove JSHint comment.
JavaScript
mit
tamiadev/generator-tamia,tamiadev/generator-tamia,tamiadev/generator-tamia
--- +++ @@ -10,13 +10,12 @@ * @license MIT */ -/*jshint browser:true, jquery:true, white:false, smarttabs:true, eqeqeq:true, - immed:true, latedef:false, newcap:true, undef:true */ /*global define:false*/ ;(function(factory) { // Try to register as an anonymous AMD module if (typeof define === 'function' && define.amd) { define(['jquery'], factory); - } else { + } + else { factory(jQuery); } }(function($) {
6b74a6d656fe61f7730d4b8994d2f53c5d9211ac
src/views/datagrid.js
src/views/datagrid.js
define(['backbone', 'handlebars', 'views/row', 'text!../../../src/templates/datagrid.hbs'], function(Backbone, Handlebars, Row, datagridTemplate) { var Datagrid = Backbone.View.extend({ initialize: function() { this.collection.on('reset', this.render, this); this._prepareColumns(); }, render: function() { var template = Handlebars.compile(datagridTemplate); var html = template({ columns: this.columns }); this.$el.html(html); this.collection.forEach(this.renderRow, this); return this; }, renderRow: function(model) { var row = new Row({model: model, columns: this.columns}); this.$('tbody').append(row.render(this.columns).el); }, _prepareColumns: function() { this.columns = []; var model = this.collection.first(); for (var p in model.toJSON()) { this.columns.push({ name: p.charAt(0).toUpperCase() + p.substr(1), property: p }); } } }); return Datagrid; });
define(['backbone', 'handlebars', 'views/row', 'text!../../../src/templates/datagrid.hbs'], function(Backbone, Handlebars, Row, datagridTemplate) { var Datagrid = Backbone.View.extend({ initialize: function() { this.collection.on('reset', this.render, this); this._prepareColumns(); }, render: function() { var template = Handlebars.compile(datagridTemplate); var html = template({ columns: this.columns }); this.$el.html(html); this.collection.forEach(this.renderRow, this); return this; }, renderRow: function(model) { var row = new Row({model: model, columns: this.columns}); this.$('tbody').append(row.render(this.columns).el); }, sort: function(column) { this.collection.comparator = function(model) { return model.get(column.property); }; this.collection.sort(); }, _prepareColumns: function() { this.columns = []; var model = this.collection.first(); for (var p in model.toJSON()) { this.columns.push({ name: p.charAt(0).toUpperCase() + p.substr(1), property: p }); } } }); return Datagrid; });
Add a sort function which is not bind on any event for now.
Add a sort function which is not bind on any event for now.
JavaScript
mit
loicfrering/backbone.datagrid
--- +++ @@ -23,6 +23,13 @@ this.$('tbody').append(row.render(this.columns).el); }, + sort: function(column) { + this.collection.comparator = function(model) { + return model.get(column.property); + }; + this.collection.sort(); + }, + _prepareColumns: function() { this.columns = []; var model = this.collection.first();
1b3957d61e8f99a78aa640bd7b8861d3e591c09d
javascripts/directory/directory.js
javascripts/directory/directory.js
BustinBash.Directory.View = function() {} BustinBash.Directory.View.prototype = { hideAndShowDOM: function(data) { $(data.Hide).hide(); $(data.Show).show(); this.clearDom(); }, clearDom: function() { $('#directory-template li').hide(); }, appendCurrentFolder: function(data) { $('.current-folder').text(data) } } BustinBash.Directory.Controller = function(view) { this.view = view; } BustinBash.Directory.Controller.prototype = { init: function() { this.bindListeners(); }, bindListeners: function() { $(document).on('changeLevel', function(event, data) { this.data = data; this.clickLevel(this.data) }.bind(this)); $(document).on('success', function() { if(this.data.ID <= 12 ){ this.checkLevel(this.data) } }.bind(this)); }, checkLevel: function(data) { this.view.hideAndShowDOM(data); }, clickLevel: function(data){ $(document).on('clickLevel', function(event, data){ this.view.hideAndShowDOM(data); }.bind(this)) } }
BustinBash.Directory.View = function() {} BustinBash.Directory.View.prototype = { hideAndShowDOM: function(data) { if(data != undefined){ $(data.Hide).hide(); $(data.Show).show(); this.clearDom(); } }, clearDom: function() { $('#directory-template li').hide(); }, appendCurrentFolder: function(data) { $('.current-folder').text(data) } } BustinBash.Directory.Controller = function(view) { this.view = view; } BustinBash.Directory.Controller.prototype = { init: function() { this.bindListeners(); }, bindListeners: function() { $(document).on('changeLevel', function(event, data) { this.data = data; this.clickLevel(this.data) }.bind(this)); $(document).on('success', function() { if(this.data.ID <= 12 ){ this.checkLevel(this.data) } }.bind(this)); }, checkLevel: function(data) { this.view.hideAndShowDOM(data); }, clickLevel: function(data){ $(document).on('clickLevel', function(event, data){ this.view.hideAndShowDOM(data); }.bind(this)) } }
Fix a bug while clicking the first button to show the lesson
Fix a bug while clicking the first button to show the lesson
JavaScript
mit
BustinBash/bustinbash.github.io,BustinBash/BustinBash
--- +++ @@ -3,9 +3,11 @@ BustinBash.Directory.View.prototype = { hideAndShowDOM: function(data) { - $(data.Hide).hide(); - $(data.Show).show(); - this.clearDom(); + if(data != undefined){ + $(data.Hide).hide(); + $(data.Show).show(); + this.clearDom(); + } }, clearDom: function() {
003fda3f99e3453c997b20eb79f7d6a1ef3461ba
jsapp/controllers/level-01.ctrl.js
jsapp/controllers/level-01.ctrl.js
/** * @fileOverview Level 01 controller. */ var Vector = require('../vector/main.vector'); /** * Level 01 controller. * * @constructor */ var Level01 = module.exports = function () { this.vector = new Vector(); }; /** * Initialize Level 01. * */ Level01.prototype.init = function() { this.vector.makeLine(50,200, 500, 200); this.vector.update(); };
/** * @fileOverview Level 01 controller. */ var Vector = require('../vector/main.vector'); var Level = require('../level/level.base'); /** * Level 01 controller. * * @constructor */ var Level01 = module.exports = function () { }; /** * Initialize Level 01. * */ Level01.prototype.init = function() { this.vector = new Vector(); this.level = new Level(this.vector); this.level.makeLine(50,200, 500, 200); this.vector.update(); };
Adjust new API on controller
Adjust new API on controller
JavaScript
mpl-2.0
skgtech/stepstepjump
--- +++ @@ -3,6 +3,7 @@ */ var Vector = require('../vector/main.vector'); +var Level = require('../level/level.base'); /** * Level 01 controller. @@ -10,7 +11,6 @@ * @constructor */ var Level01 = module.exports = function () { - this.vector = new Vector(); }; /** @@ -18,7 +18,12 @@ * */ Level01.prototype.init = function() { - this.vector.makeLine(50,200, 500, 200); + + this.vector = new Vector(); + + this.level = new Level(this.vector); + + this.level.makeLine(50,200, 500, 200); this.vector.update(); };
467657ff4c0fcd52f2c8d83ef99c0a927c635ef6
tests.js
tests.js
const rules = require('./index').rules; const RuleTester = require('eslint').RuleTester; const ruleTester = new RuleTester(); ruleTester.run('no-only-tests', rules['no-only-tests'], { valid: [ {code: 'describe("Some describe block", function() {});'}, {code: 'it("Some assertion", function() {});'}, {code: 'xit.only("Some assertion", function() {});'}, {code: 'xdescribe.only("Some describe block", function() {});'}, {code: 'xcontext.only("A context block", function() {});'}, {code: 'xtape.only("A tape block", function() {});'}, {code: 'xtest.only("A test block", function() {});'}, {code: 'other.only("An other block", function() {});'} ], invalid: [{ code: 'describe.only("Some describe block", function() {});', errors: [{message: 'describe.only not permitted'}] }, { code: 'it.only("Some assertion", function() {});', errors: [{message: 'it.only not permitted'}] }, { code: 'context.only("Some context", function() {});', errors: [{message: 'context.only not permitted'}] }, { code: 'test.only("Some test", function() {});', errors: [{message: 'test.only not permitted'}] }, { code: 'tape.only("A tape", function() {});', errors: [{message: 'tape.only not permitted'}] }] }); console.log('Tests completed successfully');
const rules = require('./index').rules; const RuleTester = require('eslint').RuleTester; const ruleTester = new RuleTester(); ruleTester.run('no-only-tests', rules['no-only-tests'], { valid: [ 'describe("Some describe block", function() {});', 'it("Some assertion", function() {});', 'xit.only("Some assertion", function() {});', 'xdescribe.only("Some describe block", function() {});', 'xcontext.only("A context block", function() {});', 'xtape.only("A tape block", function() {});', 'xtest.only("A test block", function() {});', 'other.only("An other block", function() {});', 'var args = {only: "test"}', ], invalid: [{ code: 'describe.only("Some describe block", function() {});', errors: [{message: 'describe.only not permitted'}] }, { code: 'it.only("Some assertion", function() {});', errors: [{message: 'it.only not permitted'}] }, { code: 'context.only("Some context", function() {});', errors: [{message: 'context.only not permitted'}] }, { code: 'test.only("Some test", function() {});', errors: [{message: 'test.only not permitted'}] }, { code: 'tape.only("A tape", function() {});', errors: [{message: 'tape.only not permitted'}] }] }); console.log('Tests completed successfully');
Add failing test for 'only' object keys
Add failing test for 'only' object keys
JavaScript
mit
levibuzolic/eslint-plugin-no-only-tests
--- +++ @@ -4,14 +4,15 @@ ruleTester.run('no-only-tests', rules['no-only-tests'], { valid: [ - {code: 'describe("Some describe block", function() {});'}, - {code: 'it("Some assertion", function() {});'}, - {code: 'xit.only("Some assertion", function() {});'}, - {code: 'xdescribe.only("Some describe block", function() {});'}, - {code: 'xcontext.only("A context block", function() {});'}, - {code: 'xtape.only("A tape block", function() {});'}, - {code: 'xtest.only("A test block", function() {});'}, - {code: 'other.only("An other block", function() {});'} + 'describe("Some describe block", function() {});', + 'it("Some assertion", function() {});', + 'xit.only("Some assertion", function() {});', + 'xdescribe.only("Some describe block", function() {});', + 'xcontext.only("A context block", function() {});', + 'xtape.only("A tape block", function() {});', + 'xtest.only("A test block", function() {});', + 'other.only("An other block", function() {});', + 'var args = {only: "test"}', ], invalid: [{
4b40b408e65c290bc8ad744900679b18c09d8a2f
src/server/protocols/http/start.js
src/server/protocols/http/start.js
'use strict'; const http = require('http'); const { host, port } = require('../../../config'); const { addStopFunctions } = require('./stop'); // Start HTTP server const startServer = function ({ serverState: { handleRequest, handleListening, processLog }, }) { const server = http.createServer(function requestHandler(req, res) { handleRequest({ req, res }); }); addStopFunctions(server); server.protocolName = 'HTTP'; server.listen(port, host, function listeningHandler() { handleListening({ protocol: 'HTTP', host, port }); }); handleClientError({ server, log: processLog }); const promise = new Promise((resolve, reject) => { server.on('listening', () => resolve(server)); server.on('error', () => reject()); }); return promise; }; // Report TCP client errors const handleClientError = function ({ server, log }) { server.on('clientError', async (error, socket) => { const message = 'Client TCP socket error'; await log.process({ value: error, message }); socket.end(''); }); }; module.exports = { HTTP: { startServer, }, };
'use strict'; const http = require('http'); const { host, port } = require('../../../config'); const { addStopFunctions } = require('./stop'); // Start HTTP server const startServer = function ({ serverState: { handleRequest, handleListening, processLog }, }) { const server = http.createServer(function requestHandler(req, res) { handleRequest({ req, res }); }); addStopFunctions(server); server.protocolName = 'HTTP'; server.listen(port, host, function listeningHandler() { const { address: usedHost, port: usedPort } = server.address(); handleListening({ protocol: 'HTTP', host: usedHost, port: usedPort }); }); handleClientError({ server, log: processLog }); const promise = new Promise((resolve, reject) => { server.on('listening', () => resolve(server)); server.on('error', error => reject(error)); }); return promise; }; // Report TCP client errors const handleClientError = function ({ server, log }) { server.on('clientError', async (error, socket) => { const message = 'Client TCP socket error'; await log.process({ value: error, message }); socket.end(''); }); }; module.exports = { HTTP: { startServer, }, };
Fix missing server error information
Fix missing server error information
JavaScript
apache-2.0
autoserver-org/autoserver,autoserver-org/autoserver
--- +++ @@ -19,14 +19,15 @@ server.protocolName = 'HTTP'; server.listen(port, host, function listeningHandler() { - handleListening({ protocol: 'HTTP', host, port }); + const { address: usedHost, port: usedPort } = server.address(); + handleListening({ protocol: 'HTTP', host: usedHost, port: usedPort }); }); handleClientError({ server, log: processLog }); const promise = new Promise((resolve, reject) => { server.on('listening', () => resolve(server)); - server.on('error', () => reject()); + server.on('error', error => reject(error)); }); return promise;
3d9320f3b8b309067cab67ff1d5fe291485b7708
src/parsers/guides/guide-group.js
src/parsers/guides/guide-group.js
import {GroupMark} from '../marks/marktypes'; export default function(role, style, name, dataRef, interactive, encode, marks) { return { type: GroupMark, name: name, role: role, style: style, from: dataRef, interactive: interactive || false, encode: encode, marks: marks }; }
import {GroupMark} from '../marks/marktypes'; export default function(role, style, name, dataRef, interactive, encode, marks, layout) { return { type: GroupMark, name: name, role: role, style: style, from: dataRef, interactive: interactive || false, encode: encode, marks: marks, layout: layout }; }
Update guide group util to include layout option.
Update guide group util to include layout option.
JavaScript
bsd-3-clause
vega/vega-parser
--- +++ @@ -1,6 +1,6 @@ import {GroupMark} from '../marks/marktypes'; -export default function(role, style, name, dataRef, interactive, encode, marks) { +export default function(role, style, name, dataRef, interactive, encode, marks, layout) { return { type: GroupMark, name: name, @@ -9,6 +9,7 @@ from: dataRef, interactive: interactive || false, encode: encode, - marks: marks + marks: marks, + layout: layout }; }