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 |
|---|---|---|---|---|---|---|---|---|---|---|
eb85db3ed1dbd7f30ebc0a67777951c37dfe766e | app/adapters/gist-file.js | app/adapters/gist-file.js | import ApplicationAdapter from './application';
export default ApplicationAdapter.extend({
generateIdForRecord: function(store, type, inputProperties) {
return inputProperties.filePath.replace(/\//gi, '.');
}
}); | import ApplicationAdapter from './application';
export default ApplicationAdapter.extend({
seq: 0,
generateIdForRecord: function(store, type, inputProperties) {
return inputProperties.filePath.replace(/\//gi, '.') + "." + this.incrementProperty('seq');
}
});
| Fix issue cannot create two files of the same type | Fix issue cannot create two files of the same type
| JavaScript | mit | pangratz/ember-twiddle,pangratz/ember-twiddle,vikram7/ember-twiddle,Gaurav0/ember-twiddle,ember-cli/ember-twiddle,knownasilya/ember-twiddle,knownasilya/ember-twiddle,Gaurav0/ember-twiddle,vikram7/ember-twiddle,knownasilya/ember-twiddle,vikram7/ember-twiddle,pangratz/ember-twiddle,Gaurav0/ember-twiddle,ember-cli/ember-twiddle,ember-cli/ember-twiddle | ---
+++
@@ -1,7 +1,9 @@
import ApplicationAdapter from './application';
export default ApplicationAdapter.extend({
+ seq: 0,
+
generateIdForRecord: function(store, type, inputProperties) {
- return inputProperties.filePath.replace(/\//gi, '.');
+ return inputProperties.filePath.replace(/\//gi, '.') + "." + this.incrementProperty('seq');
}
}); |
0e149f3fe042b6c2aaed0ff8d97116624f148951 | server/game/cards/02.3-ItFC/ChasingTheSun.js | server/game/cards/02.3-ItFC/ChasingTheSun.js | const _ = require('underscore');
const DrawCard = require('../../drawcard.js');
const { Locations, CardTypes, EventNames } = require('../../Constants');
class ChasingTheSun extends DrawCard {
setupCardAbilities() {
this.action({
title: 'Move the conflict to another eligible province',
condition: context => context.player.isAttackingPlayer(),
cannotBeMirrored: true,
effect: 'move the conflict to a different province',
handler: context => this.game.promptForSelect(context.player, {
context: context,
cardType: CardTypes.Province,
location: Locations.Provinces,
cardCondition: (card, context) => !card.isConflictProvince() && (card.location !== Locations.StrongholdProvince ||
_.size(this.game.provinceCards.filter(card => card.isBroken && card.controller === context.player.opponent)) > 2),
onSelect: (player, card) => {
this.game.addMessage('{0} moves the conflict to {1}', player, card);
card.inConflict = true;
this.game.currentConflict.conflictProvince.inConflict = false;
this.game.currentConflict.conflictProvince = card;
if(card.facedown) {
card.facedown = false;
this.game.raiseEvent(EventNames.OnCardRevealed, { context: context, card: card });
}
return true;
}
})
});
}
}
ChasingTheSun.id = 'chasing-the-sun';
module.exports = ChasingTheSun;
| const _ = require('underscore');
const DrawCard = require('../../drawcard.js');
const { Locations, CardTypes, EventNames } = require('../../Constants');
class ChasingTheSun extends DrawCard {
setupCardAbilities() {
this.action({
title: 'Move the conflict to another eligible province',
condition: context => context.player.isAttackingPlayer(),
cannotBeMirrored: true,
effect: 'move the conflict to a different province',
handler: context => this.game.promptForSelect(context.player, {
context: context,
cardType: CardTypes.Province,
location: Locations.Provinces,
cardCondition: (card, context) => !card.isConflictProvince() && card.canBeAttacked() && (card.location !== Locations.StrongholdProvince ||
_.size(this.game.provinceCards.filter(card => card.isBroken && card.controller === context.player.opponent)) > 2),
onSelect: (player, card) => {
this.game.addMessage('{0} moves the conflict to {1}', player, card);
card.inConflict = true;
this.game.currentConflict.conflictProvince.inConflict = false;
this.game.currentConflict.conflictProvince = card;
if(card.facedown) {
card.facedown = false;
this.game.raiseEvent(EventNames.OnCardRevealed, { context: context, card: card });
}
return true;
}
})
});
}
}
ChasingTheSun.id = 'chasing-the-sun';
module.exports = ChasingTheSun;
| Add canBeAttacked condition to Chasing the Sun | Add canBeAttacked condition to Chasing the Sun
| JavaScript | mit | gryffon/ringteki,jeremylarner/ringteki,gryffon/ringteki,jeremylarner/ringteki,gryffon/ringteki,jeremylarner/ringteki | ---
+++
@@ -13,7 +13,7 @@
context: context,
cardType: CardTypes.Province,
location: Locations.Provinces,
- cardCondition: (card, context) => !card.isConflictProvince() && (card.location !== Locations.StrongholdProvince ||
+ cardCondition: (card, context) => !card.isConflictProvince() && card.canBeAttacked() && (card.location !== Locations.StrongholdProvince ||
_.size(this.game.provinceCards.filter(card => card.isBroken && card.controller === context.player.opponent)) > 2),
onSelect: (player, card) => {
this.game.addMessage('{0} moves the conflict to {1}', player, card); |
511d83a1612d0c348045bb0511bbd6ecc6cb01a7 | jenkins/seedDatabase.js | jenkins/seedDatabase.js | var system = require('system');
var url = encodeURI(system.args[1]);
var page = require('webpage').create();
page.open(url, function(status) {
console.log("Status: " + status);
phantom.exit();
});
| var system = require('system');
console.log(system.args[1]);
var url = encodeURI(system.args[1]);
console.log(url);
var page = require('webpage').create();
page.open(url, function(status) {
console.log("Status: " + status);
phantom.exit();
});
| Include debugging in seed database script | Include debugging in seed database script
| JavaScript | apache-2.0 | ecohealthalliance/infrastructure,ecohealthalliance/infrastructure,ecohealthalliance/infrastructure,ecohealthalliance/infrastructure | ---
+++
@@ -1,5 +1,7 @@
var system = require('system');
+console.log(system.args[1]);
var url = encodeURI(system.args[1]);
+console.log(url);
var page = require('webpage').create();
|
3fbbec30b1bfd3f635becb3496481a187f29b7e3 | index.ios.js | index.ios.js | /**
* @providesModule RNShare
* @flow
*/
'use strict';
var NativeRNShare = require('react-native').NativeModules.RNShare;
var invariant = require('invariant');
/**
* High-level docs for the RNShare iOS API can be written here.
*/
var RNShare = {
test: function() {
NativeRNShare.test();
},
open: function(options) {
NativeRNShare.open(options);
}
};
module.exports = RNShare;
| /**
* @providesModule RNShare
* @flow
*/
'use strict';
var NativeRNShare = require('NativeModules').RNShare;
var invariant = require('invariant');
/**
* High-level docs for the RNShare iOS API can be written here.
*/
var RNShare = {
test: function() {
NativeRNShare.test();
},
open: function(options) {
NativeRNShare.open(options);
}
};
module.exports = RNShare;
| Revert "updateRN 0.14.0 new native module Api" | Revert "updateRN 0.14.0 new native module Api"
| JavaScript | mit | EstebanFuentealba/react-native-share,EstebanFuentealba/react-native-share,EstebanFuentealba/react-native-share,EstebanFuentealba/react-native-share | ---
+++
@@ -4,7 +4,7 @@
*/
'use strict';
-var NativeRNShare = require('react-native').NativeModules.RNShare;
+var NativeRNShare = require('NativeModules').RNShare;
var invariant = require('invariant');
/** |
5211ee14bd569729d8c5193a1684e495f649f16a | generators/app/templates/task/dev.js | generators/app/templates/task/dev.js | import gulp from 'gulp';
import browserSync from 'browser-sync';
const bs = browserSync.get('dev');
gulp.task('connect:dev', ['styles'], (done) => {
bs.init({
notify: false,
port: 9000,
open: false,
server: {
baseDir: ['.tmp', 'app']
}
}, done);
});
gulp.task('watch:dev', ['connect:dev'], function () {
gulp.watch([
'app/index.html',
'app/scripts/**/*',
'app/images/**/*',
'app/config.js'
]).on('change', bs.reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
});
gulp.task('serve:dev', ['connect:dev', 'watch:dev']);
| import gulp from 'gulp';
import browserSync from 'browser-sync';
const bs = browserSync.get('dev');
gulp.task('connect:dev', ['styles'], (done) => {
bs.init({
notify: false,
port: 9000,
open: false,
server: {
baseDir: ['.tmp', 'app']
}
}, done);
});
gulp.task('watch:dev', ['connect:dev'], function () {
gulp.watch([
'app/index.html',
'app/scripts/**/*',
'app/images/**/*',
'app/jspm-config.js'
]).on('change', bs.reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
});
gulp.task('serve:dev', ['connect:dev', 'watch:dev']);
| Fix wrong jspm config path | Fix wrong jspm config path
| JavaScript | mit | silvenon/generator-wbp,silvenon/generator-wbp | ---
+++
@@ -19,7 +19,7 @@
'app/index.html',
'app/scripts/**/*',
'app/images/**/*',
- 'app/config.js'
+ 'app/jspm-config.js'
]).on('change', bs.reload);
gulp.watch('app/styles/**/*.scss', ['styles']); |
612a144c611549b6ceef9f59e2df0eb246d881d0 | concat-svg/concat-svg.js | concat-svg/concat-svg.js | #!/usr/bin/env node
var fs = require('fs');
var cheerio = require('cheerio');
var path = require('path');
var cheerioOptions = {xmlMode: true};
var files = process.argv.slice(2);
function read(file) {
var content = fs.readFileSync(file, 'utf8');
return cheerio.load(content, cheerioOptions);
}
function transmogrify($, name) {
// output with cleaned up icon name
var node = $('#Icon').attr('id', name);
// print icon svg
console.log($.xml(node));
}
function path2IconName(file) {
parts = path.basename(file).split('_');
// remove ic_
parts.shift();
// remove _24px.svg
parts.pop();
return parts.join('-');
}
files.forEach(function(file) {
var name = path2IconName(file);
var $ = read(file);
transmogrify($, name);
});
| #!/usr/bin/env node
var fs = require('fs');
var cheerio = require('cheerio');
var path = require('path');
var cheerioOptions = {xmlMode: true};
var files = process.argv.slice(2);
function read(file) {
var content = fs.readFileSync(file, 'utf8');
return cheerio.load(content, cheerioOptions);
}
function transmogrify($, name) {
// output with cleaned up icon name
var node = $('#Icon').attr('id', name);
// remove spacer rectangles
node.find('rect[fill],rect[style*="fill"]').remove();
// remove empty groups
var innerHTML = $.xml(node.find('*').filter(':not(g)'));
node.html(innerHTML);
// print icon svg
console.log($.xml(node));
}
function path2IconName(file) {
parts = path.basename(file).split('_');
// remove ic_
parts.shift();
// remove _24px.svg
parts.pop();
return parts.join('-');
}
files.forEach(function(file) {
var name = path2IconName(file);
var $ = read(file);
transmogrify($, name);
});
| Remove spacer rectangles and flatten groups in source SVG files | Remove spacer rectangles and flatten groups in source SVG files
Saves 30K on the iconsets!
| JavaScript | bsd-3-clause | jorgecasar/tools,imrehorvath/tools,Polymer/tools,Polymer/tools,imrehorvath/tools,Polymer/tools,jorgecasar/tools,Polymer/tools | ---
+++
@@ -15,6 +15,11 @@
function transmogrify($, name) {
// output with cleaned up icon name
var node = $('#Icon').attr('id', name);
+ // remove spacer rectangles
+ node.find('rect[fill],rect[style*="fill"]').remove();
+ // remove empty groups
+ var innerHTML = $.xml(node.find('*').filter(':not(g)'));
+ node.html(innerHTML);
// print icon svg
console.log($.xml(node));
} |
5bcd4d2b709128e9e908812279280d3e4fca5eca | app/app.js | app/app.js | "use strict";
// Declare app level module which depends on views, and components
angular.module("myApp", [
"ngRoute",
"myApp.view1",
"myApp.view2",
"myApp.version",
"ui.bootstrap"
]).
config(["$routeProvider", function($routeProvider) {
$routeProvider.otherwise({redirectTo: "/view1"});
}]);
| "use strict";
// Declare app level module which depends on views, and components
angular.module("myApp", [
"ngRoute",
"myApp.view1",
"myApp.view2",
"myApp.version"
]).
config(["$routeProvider", function($routeProvider) {
$routeProvider.otherwise({redirectTo: "/view1"});
}]);
| Fix integration test by removing bootstrap module | Fix integration test by removing bootstrap module | JavaScript | mit | mikar/cmis-browser,mikar/cmis-browser | ---
+++
@@ -5,8 +5,7 @@
"ngRoute",
"myApp.view1",
"myApp.view2",
- "myApp.version",
- "ui.bootstrap"
+ "myApp.version"
]).
config(["$routeProvider", function($routeProvider) {
$routeProvider.otherwise({redirectTo: "/view1"}); |
d6807bb4f28e0b8bc3cf990ce629edfe186dfa80 | js/events.js | js/events.js | function Events()
{
var listeners = {}
$.extend(this, {
on: function(type, cb)
{
if (!$.isArray(listeners[type]))
listeners[type] = []
if (listeners[type].indexOf(cb) < 0)
listeners[type].push(cb)
},
once: function(type, cb)
{
this.on(type, function observer()
{
this.off(type, observer)
cb.apply(this, arguments)
})
},
emit: function(type)
{
if (!$.isArray(listeners[type]))
listeners[type] = []
var args = Array.prototype.slice.call(arguments, 1)
var cbs = listeners[type].slice()
while (cbs.length > 0)
{
cbs.shift().apply(this, args)
}
},
off: function(type, cb)
{
if (cb == undefined)
throw new Error("You cannot remove all listeners on an event")
if (!$.isFunction(cb))
throw new Error("You must pass a listener to Event.off")
var index = listeners[type].indexOf(cb)
if (index != undefined && index >= 0)
{
listeners[type].splice(index, 1);
}
},
})
}
| function Events()
{
var listeners = {}
$.extend(this, {
on: function(type, cb)
{
if (!$.isArray(listeners[type]))
listeners[type] = []
if (listeners[type].indexOf(cb) < 0)
listeners[type].push(cb)
},
once: function(type, cb)
{
this.on(type, function observer()
{
this.off(type, observer)
cb.apply(this, arguments)
})
},
emit: function(type)
{
var result = []
if (!$.isArray(listeners[type]))
listeners[type] = []
var args = Array.prototype.slice.call(arguments, 1)
var cbs = listeners[type].slice()
while (cbs.length > 0)
{
result.push(cbs.shift().apply(this, args))
}
return result
},
off: function(type, cb)
{
if (cb == undefined)
throw new Error("You cannot remove all listeners on an event")
if (!$.isFunction(cb))
throw new Error("You must pass a listener to Event.off")
var index = listeners[type].indexOf(cb)
if (index != undefined && index >= 0)
{
listeners[type].splice(index, 1);
}
},
})
}
| Make emit able to return an array of values | Make emit able to return an array of values
| JavaScript | artistic-2.0 | atrodo/fission_engine,atrodo/fission_engine | ---
+++
@@ -20,6 +20,8 @@
},
emit: function(type)
{
+ var result = []
+
if (!$.isArray(listeners[type]))
listeners[type] = []
@@ -27,8 +29,10 @@
var cbs = listeners[type].slice()
while (cbs.length > 0)
{
- cbs.shift().apply(this, args)
+ result.push(cbs.shift().apply(this, args))
}
+
+ return result
},
off: function(type, cb)
{ |
65eff470cfe7e52ec3c778290dc0c20d046ee23a | src/Disp/buildingTiles/toggleBuildingLock.js | src/Disp/buildingTiles/toggleBuildingLock.js | /**
* This function toggle the locked state of a building
* @param {number} index Index of the row to change
*/
export default function toggleBuildingLock(index) {
if (l(`productLock${index}`).innerHTML === 'Lock') {
Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.push(
index.toString(),
);
l(`row${index}`).style.pointerEvents = 'none';
l(`row${index}`).style.opacity = '0.4';
l(`productLock${index}`).innerHTML = 'Unlock';
l(`productLock${index}`).style.pointerEvents = 'auto';
} else {
Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames =
Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.filter(
(value) => value !== index.toString(),
);
l(`productLock${index}`).innerHTML = 'Lock';
l(`row${index}`).style.pointerEvents = 'auto';
l(`row${index}`).style.opacity = '1';
}
}
| /**
* This function toggle the locked state of a building
* @param {number} index Index of the row to change
*/
export default function toggleBuildingLock(index) {
if (l(`productLock${index}`).innerHTML === 'Lock') {
// Add to storing array
Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.push(
index.toString(),
);
// Update styles
l(`row${index}`).style.pointerEvents = 'none';
l(`row${index}`).style.opacity = '0.4';
l(`productLock${index}`).innerHTML = 'Unlock';
l(`productLock${index}`).style.pointerEvents = 'auto';
} else {
// Remove from storing array
if (
Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.includes(
index.toString(),
)
) {
Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames =
Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.filter(
(value) => value !== index.toString(),
);
}
// Update styles
l(`productLock${index}`).innerHTML = 'Lock';
l(`row${index}`).style.pointerEvents = 'auto';
l(`row${index}`).style.opacity = '1';
}
}
| Fix bug with storing locked buildings | Fix bug with storing locked buildings
| JavaScript | mit | Aktanusa/CookieMonster,Aktanusa/CookieMonster | ---
+++
@@ -4,18 +4,30 @@
*/
export default function toggleBuildingLock(index) {
if (l(`productLock${index}`).innerHTML === 'Lock') {
+ // Add to storing array
Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.push(
index.toString(),
);
+
+ // Update styles
l(`row${index}`).style.pointerEvents = 'none';
l(`row${index}`).style.opacity = '0.4';
l(`productLock${index}`).innerHTML = 'Unlock';
l(`productLock${index}`).style.pointerEvents = 'auto';
} else {
- Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames =
- Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.filter(
- (value) => value !== index.toString(),
- );
+ // Remove from storing array
+ if (
+ Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.includes(
+ index.toString(),
+ )
+ ) {
+ Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames =
+ Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.lockedMinigames.filter(
+ (value) => value !== index.toString(),
+ );
+ }
+
+ // Update styles
l(`productLock${index}`).innerHTML = 'Lock';
l(`row${index}`).style.pointerEvents = 'auto';
l(`row${index}`).style.opacity = '1'; |
3bb25ff6053f6ea0ce124a7fdfa804f15631ede9 | grunt/config/copy.js | grunt/config/copy.js | module.exports = {
docs: {
files: [
{
src: ['css/**/*'],
dest: 'docs/public/'
},
{
src: ['img/**/*'],
dest: 'docs/public/'
}
]
}
}; | module.exports = {
docs: {
files: [
{
src: ['css/**/*'],
dest: 'docs/public/'
},
{
src: ['img/**/*'],
dest: 'docs/public/'
},
{
src: ['js/**/*'],
dest: 'docs/public/'
}
]
}
}; | Copy the JS to the docs dir | Copy the JS to the docs dir
| JavaScript | agpl-3.0 | FiviumAustralia/OpenEyes,FiviumAustralia/OpenEyes,FiviumAustralia/OpenEyes,FiviumAustralia/OpenEyes,FiviumAustralia/OpenEyes | ---
+++
@@ -8,6 +8,10 @@
{
src: ['img/**/*'],
dest: 'docs/public/'
+ },
+ {
+ src: ['js/**/*'],
+ dest: 'docs/public/'
}
]
} |
ff4679095d924160e1ee69a1b1051bf846689dac | config/passportConfig.js | config/passportConfig.js | /*
* This file contains all of the Passport configuration that will
* be used through the application for Facebook authentication.
*/
var FacebookStrategy = require('passport-facebook').Strategy;
var keys = require('./keys');
var model = require('../models/index');
module.exports = function(app, passport) {
app.use(passport.initialize());
app.use(passport.session());
passport.use(new FacebookStrategy({
clientID : keys.facebook.APP_ID,
clientSecret : keys.facebook.SECRET,
callbackURL : 'http://localhost:3000/auth/facebook/callback'
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function() {
model['User'].findOne({ where: { facebookId: profile.id }}, {})
.then(function(result) {
if (!result) {
model['User'].create({ facebookId: profile.id, v2AccessToken: accessToken });
}
})
});
})
);
} | /*
* This file contains all of the Passport configuration that will
* be used through the application for Facebook authentication.
*/
var FacebookStrategy = require('passport-facebook').Strategy;
var keys = require('./keys');
var model = require('../models/index');
module.exports = function(app, passport) {
app.use(passport.initialize());
app.use(passport.session());
// Serializes the user for the session based on their ID
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// Deserializes the user based on their ID
passport.deserializeUser(function(id, done) {
model.User.find({ where: { id: id }})
.then(function(user) {
done(null, user);
})
.catch(function(err) {
done(err, null);
});
});
// Setup for the Facebook authentication strategy
passport.use(new FacebookStrategy({
clientID : keys.facebook.APP_ID,
clientSecret : keys.facebook.SECRET,
callbackURL : keys.facebook.CALLBACK
},
function(accessToken, refreshToken, profile, done) {
// Performs verification asynchronously
process.nextTick(function() {
// Queries the database to see if the user is already stored there
model.User.find({ where: { facebookId: profile.id }}, {})
.then(function(user) {
// If the user is not stored in the database, then store the user there
if (user === null) {
model.User.create({ facebookId: profile.id, v2AccessToken: accessToken })
.then(function(user) {
done(null, user);
})
.catch(function(err) {
done(err, null);
});
}
else {
// If the user has a new access token, then update the token in the database
if (user.v2AccessToken !== accessToken) {
user.updateAttributes({ v2AccessToken: accessToken })
.then(function() {
done(null, user);
});
}
else {
done(null, user);
}
}
})
.catch(function(err) {
done(err, null)
});
});
}
));
} | Add sessions and more robust Facebook auth. | Add sessions and more robust Facebook auth.
| JavaScript | mit | kurtbradd/facebook-music-recommender,kurtbradd/facebook-music-recommender,kurtbradd/facebook-music-recommender,kurtbradd/facebook-music-recommender | ---
+++
@@ -12,23 +12,68 @@
app.use(passport.initialize());
app.use(passport.session());
+ // Serializes the user for the session based on their ID
+ passport.serializeUser(function(user, done) {
+ done(null, user.id);
+ });
+
+ // Deserializes the user based on their ID
+ passport.deserializeUser(function(id, done) {
+ model.User.find({ where: { id: id }})
+ .then(function(user) {
+ done(null, user);
+ })
+ .catch(function(err) {
+ done(err, null);
+ });
+ });
+
+ // Setup for the Facebook authentication strategy
passport.use(new FacebookStrategy({
clientID : keys.facebook.APP_ID,
clientSecret : keys.facebook.SECRET,
- callbackURL : 'http://localhost:3000/auth/facebook/callback'
+ callbackURL : keys.facebook.CALLBACK
},
function(accessToken, refreshToken, profile, done) {
+
+ // Performs verification asynchronously
process.nextTick(function() {
- model['User'].findOne({ where: { facebookId: profile.id }}, {})
- .then(function(result) {
- if (!result) {
- model['User'].create({ facebookId: profile.id, v2AccessToken: accessToken });
+ // Queries the database to see if the user is already stored there
+ model.User.find({ where: { facebookId: profile.id }}, {})
+
+ .then(function(user) {
+ // If the user is not stored in the database, then store the user there
+ if (user === null) {
+ model.User.create({ facebookId: profile.id, v2AccessToken: accessToken })
+ .then(function(user) {
+ done(null, user);
+ })
+ .catch(function(err) {
+ done(err, null);
+ });
+ }
+
+ else {
+ // If the user has a new access token, then update the token in the database
+ if (user.v2AccessToken !== accessToken) {
+ user.updateAttributes({ v2AccessToken: accessToken })
+ .then(function() {
+ done(null, user);
+ });
+ }
+ else {
+ done(null, user);
+ }
}
})
- });
- })
- );
+ .catch(function(err) {
+ done(err, null)
+ });
+
+ });
+ }
+ ));
} |
90fb58a96ea37dfe6c9e08e2248b833e60038093 | bin/cmd.js | bin/cmd.js | #!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var argv = require('yargs')
.alias('s', 'silent')
.describe('s', 'print empty string instead of erroring out')
.argv
var pkg = path.join(process.cwd(), 'package.json')
var field = argv._[0] || 'name'
fs.readFile(pkg, 'utf8', function(err, data) {
if (err) {
if (argv.s)
process.stdout.write('')
else
throw new Error(err)
} else {
try {
var p = JSON.parse(data)
process.stdout.write(p[field]||'')
} catch (e) {
if (argv.s)
process.stdout.write('')
else
throw new Error(e)
}
}
}) | #!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var argv = require('yargs')
.boolean('s')
.alias('s', 'silent')
.describe('s', 'print empty string instead of erroring out')
.argv
var pkg = path.join(process.cwd(), 'package.json')
var field = argv._[0] || 'name'
fs.readFile(pkg, 'utf8', function(err, data) {
if (err) {
if (argv.s)
process.stdout.write('')
else
throw new Error(err)
} else {
try {
var p = JSON.parse(data)
process.stdout.write(p[field]||'')
} catch (e) {
if (argv.s)
process.stdout.write('')
else
throw new Error(e)
}
}
})
| Use -s option before or after argument | Use -s option before or after argument
| JavaScript | mit | mattdesl/package-field | ---
+++
@@ -3,6 +3,7 @@
var fs = require('fs')
var path = require('path')
var argv = require('yargs')
+ .boolean('s')
.alias('s', 'silent')
.describe('s', 'print empty string instead of erroring out')
.argv |
bc72cb413b3ebc308027ea9fb7191455a6005071 | bin/guh.js | bin/guh.js | #!/usr/bin/env node
"use strict";
const aliases = {
h: "help",
"-h": "help",
"/h": "help",
v: "version",
"-v": "version",
n: "new",
b: "build"
};
let command = process.argv[2] || "help";
if (aliases[command]) {
command = aliases[command];
}
try {
require(`./guh-${ command }`);
} catch(e) {
if (e.code === "MODULE_NOT_FOUND") {
console.log(`"${ command }" isn't a valid guh command. Try "guh help"`);
process.exit(-1);
} else {
throw e;
}
} | #!/usr/bin/env node
"use strict";
const aliases = {
h: "help",
"-h": "help",
"/h": "help",
v: "version",
"-v": "version",
n: "new",
b: "build"
};
let command = process.argv[2] || "help";
if (aliases[command]) {
command = aliases[command];
}
try {
require(`./guh-${ command }`);
} catch(e) {
if (e.code === "MODULE_NOT_FOUND") {
if (process.argv.includes("--debug")) {
throw e;
} else {
console.log(`"${ command }" isn't a valid guh command. Try "guh help"`);
process.exit(-1);
}
} else {
throw e;
}
} | Add --debug flag to command line to allow easier reporting | Add --debug flag to command line to allow easier reporting
| JavaScript | mit | LPGhatguy/guh,LPGhatguy/basis | ---
+++
@@ -21,9 +21,12 @@
require(`./guh-${ command }`);
} catch(e) {
if (e.code === "MODULE_NOT_FOUND") {
- console.log(`"${ command }" isn't a valid guh command. Try "guh help"`);
-
- process.exit(-1);
+ if (process.argv.includes("--debug")) {
+ throw e;
+ } else {
+ console.log(`"${ command }" isn't a valid guh command. Try "guh help"`);
+ process.exit(-1);
+ }
} else {
throw e;
} |
ce3b4d7c61fde7c4918205df77f7f009c2eb461c | Welcomer/index.js | Welcomer/index.js | /*Tell users to read the rules,
with a direct link to the channel,
when they join.*/
var info = console.log.bind(console, "[Welcomer]");
var message = [
"Welcome to the server!",
"We have rules that we'd like you to follow, so make sure to check out the <#155309620540342272> channel.",
"We hope you enjoy your stay!"
];
function Welcomer(client, serverID) {
client.on('any', function handleWelcomerEvent(event) {
return (event.t === 'GUILD_MEMBER_ADD' && event.d.guild_id === serverID) ?
(setTimeout( welcome, 3000, client, event.d.user.id ), true) :
false;
});
}
module.exports = Welcomer;
function welcome(client, userID) {
client.sendMessage({
to: userID,
message: message.join("\n")
}, function(err, res) {
if (err) return info(JSON.stringify(err));
});
} | /*Tell users to read the rules,
with a direct link to the channel,
when they join.*/
var info = console.log.bind(console, "[Welcomer]");
var message = [
"Welcome to the server!",
"We have rules that we'd like you to follow, so make sure to check out the <#155309620540342272> channel.",
"We hope you enjoy your stay!"
].join("\n");
function Welcomer(client, serverID) {
client.on('any', function handleWelcomerEvent(event) {
return (event.t === 'GUILD_MEMBER_ADD' && event.d.guild_id === serverID) ?
(setTimeout( welcome, 3000, client, event.d.user.id ), true) :
false;
});
}
function welcome(client, userID) {
client.sendMessage({
to: userID,
message: message
}, function(err, res) {
if (!err) return
info(err.message);
info(err.stack);
});
}
module.exports = Welcomer;
| Join the welcome message on script init | Join the welcome message on script init
| JavaScript | mit | izy521/Sera-PCMR | ---
+++
@@ -7,7 +7,7 @@
"Welcome to the server!",
"We have rules that we'd like you to follow, so make sure to check out the <#155309620540342272> channel.",
"We hope you enjoy your stay!"
-];
+].join("\n");
function Welcomer(client, serverID) {
client.on('any', function handleWelcomerEvent(event) {
@@ -17,13 +17,15 @@
});
}
-module.exports = Welcomer;
-
function welcome(client, userID) {
client.sendMessage({
to: userID,
- message: message.join("\n")
+ message: message
}, function(err, res) {
- if (err) return info(JSON.stringify(err));
+ if (!err) return
+ info(err.message);
+ info(err.stack);
});
}
+
+module.exports = Welcomer; |
271c7b629d84c0fbe4fe0003cb49e07c8d8b5cf5 | generators/app/templates/gulp-tasks/build/composer.js | generators/app/templates/gulp-tasks/build/composer.js | const childProcess = require('child_process');
const path = require('path');
const setup = require('setup/setup');
function exec(command) {
const run = childProcess.exec;
return new Promise((resolve, reject) => {
run(command, (error, stdout, stderr) => {
if (error) {
return reject(stderr);
}
return resolve(stdout);
});
});
}
module.exports = function(taskDone) {
const assets = setup.assets;
const execOpts = setup.plugins.exec;
const vendorDir = path.join(assets.build, setup.root, assets.vendor);
const cmd = 'composer';
const cmdConfig = [cmd, 'config', 'vendor-dir', vendorDir].join(' ');
const cmdInstall = [cmd, 'install']
.concat(setup.isOnline ? ['--no-dev', '-o'] : ['--dev']).join(' ');
const cmdUnset = [cmd, 'config', '--unset', 'vendor-dir'].join(' ');
exec(cmdConfig, execOpts)
.then(() => exec(cmdInstall, execOpts))
.then(() => exec(cmdUnset, execOpts))
.catch(taskDone);
};
| const childProcess = require('child_process');
const path = require('path');
const setup = require('setup/setup');
function exec(command) {
const run = childProcess.exec;
return new Promise((resolve, reject) => {
run(command, (error, stdout, stderr) => {
if (error) {
return reject(stderr);
}
return resolve(stdout);
});
});
}
module.exports = function(taskDone) {
const assets = setup.assets;
const execOpts = setup.plugins.exec;
const vendorDir = path.join(assets.build, setup.root, assets.vendor);
const cmd = 'composer';
const cmdConfig = [cmd, 'config', 'vendor-dir', vendorDir].join(' ');
const cmdInstall = [cmd, 'install']
.concat(setup.isOnline ? ['--no-dev', '-o'] : ['--dev']).join(' ');
const cmdUnset = [cmd, 'config', '--unset', 'vendor-dir'].join(' ');
exec(cmdConfig, execOpts)
.then(() => exec(cmdInstall, execOpts))
.then(() => exec(cmdUnset, execOpts))
.then(taskDone)
.catch(taskDone);
};
| Fix task not complete error | Fix task not complete error
| JavaScript | mit | ethancfchen/generator-nodena-api-php | ---
+++
@@ -31,5 +31,6 @@
exec(cmdConfig, execOpts)
.then(() => exec(cmdInstall, execOpts))
.then(() => exec(cmdUnset, execOpts))
+ .then(taskDone)
.catch(taskDone);
}; |
100021f87e4401d94a034f15b917efb6d68b60e9 | packages/truffle-debugger/lib/web3/adapter.js | packages/truffle-debugger/lib/web3/adapter.js | import debugModule from "debug";
const debug = debugModule("debugger:web3:adapter");
import Web3 from "web3";
export default class Web3Adapter {
constructor(provider) {
this.web3 = new Web3(provider);
}
async getTrace(txHash) {
return new Promise((accept, reject) => {
this.web3.currentProvider.send(
{
jsonrpc: "2.0",
method: "debug_traceTransaction",
params: [txHash, {}],
id: new Date().getTime()
},
(err, result) => {
if (err) return reject(err);
if (result.error) return reject(new Error(result.error.message));
debug("result: %o", result);
accept(result.result.structLogs);
}
);
});
}
async getTransaction(txHash) {
return await this.web3.eth.getTransaction(txHash);
}
async getReceipt(txHash) {
return await this.web3.eth.getTransactionReceipt(txHash);
}
async getBlock(blockNumberOrHash) {
return await this.web3.eth.getBlock(blockNumberOrHash);
}
/**
* getDeployedCode - get the deployed code for an address from the client
* @param {String} address
* @return {String} deployedBinary
*/
async getDeployedCode(address) {
debug("getting deployed code for %s", address);
return await this.web3.eth.getCode(address);
}
}
| import debugModule from "debug";
const debug = debugModule("debugger:web3:adapter");
import Web3 from "web3";
import { promisify } from "util";
export default class Web3Adapter {
constructor(provider) {
this.web3 = new Web3(provider);
}
async getTrace(txHash) {
let result = await promisify(this.web3.currentProvider.send)(
//send *only* uses callbacks, so we use promsifiy to make things more
//readable
{
jsonrpc: "2.0",
method: "debug_traceTransaction",
params: [txHash, {}],
id: new Date().getTime()
}
);
if (result.error) {
throw new Error(result.error.message);
} else {
return result.result.structLogs;
}
}
async getTransaction(txHash) {
return await this.web3.eth.getTransaction(txHash);
}
async getReceipt(txHash) {
return await this.web3.eth.getTransactionReceipt(txHash);
}
async getBlock(blockNumberOrHash) {
return await this.web3.eth.getBlock(blockNumberOrHash);
}
/**
* getDeployedCode - get the deployed code for an address from the client
* @param {String} address
* @return {String} deployedBinary
*/
async getDeployedCode(address) {
debug("getting deployed code for %s", address);
return await this.web3.eth.getCode(address);
}
}
| Rewrite getTrace with util.promisify for readability | Rewrite getTrace with util.promisify for readability
| JavaScript | mit | ConsenSys/truffle | ---
+++
@@ -2,6 +2,7 @@
const debug = debugModule("debugger:web3:adapter");
import Web3 from "web3";
+import { promisify } from "util";
export default class Web3Adapter {
constructor(provider) {
@@ -9,22 +10,21 @@
}
async getTrace(txHash) {
- return new Promise((accept, reject) => {
- this.web3.currentProvider.send(
- {
- jsonrpc: "2.0",
- method: "debug_traceTransaction",
- params: [txHash, {}],
- id: new Date().getTime()
- },
- (err, result) => {
- if (err) return reject(err);
- if (result.error) return reject(new Error(result.error.message));
- debug("result: %o", result);
- accept(result.result.structLogs);
- }
- );
- });
+ let result = await promisify(this.web3.currentProvider.send)(
+ //send *only* uses callbacks, so we use promsifiy to make things more
+ //readable
+ {
+ jsonrpc: "2.0",
+ method: "debug_traceTransaction",
+ params: [txHash, {}],
+ id: new Date().getTime()
+ }
+ );
+ if (result.error) {
+ throw new Error(result.error.message);
+ } else {
+ return result.result.structLogs;
+ }
}
async getTransaction(txHash) { |
63dbcbe2fa8a1ca0fb1dbc1e4df928f11e52f45e | js/getData.js | js/getData.js | window.onload = initializeData()
var ref = new Firebase("https://cepatsembuh.firebaseio.com");
var no_antri = new Firebase(ref + '/no_antrian');
function initializeData() {
var right_now = document.getElementById("right_now");
var date = new Date();
right_now.textContent = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
var right_now_text_content = right_now.textContent;
}
ref.on("value", function(snapshot) {
var no_antri = document.getElementById("no_antri");
var no_antrian = snapshot.val();
no_antri.textContent = no_antrian;
var no_antrian_text_content = no_antri.textContent;
})
| window.onload = initializeData()
var ref = new Firebase("https://cepatsembuh.firebaseio.com");
var no_antri = new Firebase(ref + '/no_antrian');
function initializeData() {
var right_now = $('#right_now');
var date = new Date();
right_now.textContent = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
var right_now_text_content = right_now.textContent;
}
ref.on("value", function(snapshot) {
var no_antri = $('#no_antri');
var no_antrian = snapshot.val();
no_antri.textContent = no_antrian;
var no_antrian_text_content = no_antri.textContent;
})
| Use jQuery to get elements | Use jQuery to get elements
| JavaScript | mit | mercysmart/cepatsembuh-iqbal,mercysmart/cepatsembuh-iqbal | ---
+++
@@ -3,14 +3,14 @@
var no_antri = new Firebase(ref + '/no_antrian');
function initializeData() {
- var right_now = document.getElementById("right_now");
+ var right_now = $('#right_now');
var date = new Date();
right_now.textContent = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
var right_now_text_content = right_now.textContent;
}
ref.on("value", function(snapshot) {
- var no_antri = document.getElementById("no_antri");
+ var no_antri = $('#no_antri');
var no_antrian = snapshot.val();
no_antri.textContent = no_antrian;
var no_antrian_text_content = no_antri.textContent; |
43d17915450f11cb928cbba68a7c08f7b1f31c87 | src/TimeSelect.js | src/TimeSelect.js | import React from 'react'
import PropTypes from 'prop-types'
import NativeSelect from '@material-ui/core/NativeSelect'
class TimeSelect extends React.Component {
render = () => {
const topRight = { position: 'absolute', right: '0px', top: '0px' }
// Inspired by: https://material-ui.com/components/selects/#native-select
return (
<NativeSelect style={topRight} value={'now'}>
<option value={'now'}>Now</option>
<option value={'tomorrow'}>Tomorrow</option>
</NativeSelect>
)
}
}
TimeSelect.propTypes = {
onSelect: PropTypes.func.isRequired
}
export default TimeSelect
| import React from 'react'
import PropTypes from 'prop-types'
import NativeSelect from '@material-ui/core/NativeSelect'
class TimeSelect extends React.Component {
constructor (props) {
super(props)
this.state = {
value: 'now'
}
}
render = () => {
const topRight = { position: 'absolute', right: '0px', top: '0px' }
// Inspired by: https://material-ui.com/components/selects/#native-select
return (
<NativeSelect style={topRight} value={this.state.value} onChange={this.onChange}>
<option value={'now'}>Now</option>
<option value={'tomorrow'}>Tomorrow</option>
</NativeSelect>
)
}
onChange = event => {
this.setState({ value: event.target.value })
// FIXME: Report to this.props.onSelect!
}
}
TimeSelect.propTypes = {
onSelect: PropTypes.func.isRequired
}
export default TimeSelect
| Switch dropdown value on selections | Switch dropdown value on selections
| JavaScript | mit | walles/weatherclock,walles/weatherclock,walles/weatherclock,walles/weatherclock | ---
+++
@@ -4,16 +4,30 @@
import NativeSelect from '@material-ui/core/NativeSelect'
class TimeSelect extends React.Component {
+ constructor (props) {
+ super(props)
+
+ this.state = {
+ value: 'now'
+ }
+ }
+
render = () => {
const topRight = { position: 'absolute', right: '0px', top: '0px' }
// Inspired by: https://material-ui.com/components/selects/#native-select
return (
- <NativeSelect style={topRight} value={'now'}>
+ <NativeSelect style={topRight} value={this.state.value} onChange={this.onChange}>
<option value={'now'}>Now</option>
<option value={'tomorrow'}>Tomorrow</option>
</NativeSelect>
)
+ }
+
+ onChange = event => {
+ this.setState({ value: event.target.value })
+
+ // FIXME: Report to this.props.onSelect!
}
}
|
5f6fec6b2548f2151291bb4d7876939c0271c5d6 | karma.conf.js | karma.conf.js | var fs = require('fs')
module.exports = function(config) {
config.set({
browserify: {
debug: true,
extensions: ['.ts'],
plugin: [['tsify', JSON.parse(fs.readFileSync('./tsconfig.json', 'utf8')).compilerOptions]],
transform: ['brfs'],
},
browsers: ['Firefox'],
concurrency: 1,
files: [
'spec/**/*.spec.ts'
],
frameworks: ['jasmine', 'browserify'],
preprocessors: {
'spec/**/*.spec.ts': ['browserify'],
}
})
}
| var fs = require('fs')
module.exports = function(config) {
config.set({
browserify: {
debug: true,
extensions: ['.ts'],
plugin: [['tsify', JSON.parse(fs.readFileSync('./tsconfig.json', 'utf8')).compilerOptions]],
transform: ['brfs'],
},
browsers: ['Firefox'],
concurrency: 1,
files: [
'spec/**/*.spec.ts'
],
frameworks: ['jasmine', 'browserify'],
mime: {
'text/x-typescript': ['ts','tsx']
},
preprocessors: {
'spec/**/*.spec.ts': ['browserify'],
}
})
}
| Set mime type for ts files explicitly. | Set mime type for ts files explicitly.
Set mime type to ensure that Chrome interprets Typescript
files correctly when debugging unit tests.
| JavaScript | mit | mapillary/mapillary-js,mapillary/mapillary-js | ---
+++
@@ -14,6 +14,9 @@
'spec/**/*.spec.ts'
],
frameworks: ['jasmine', 'browserify'],
+ mime: {
+ 'text/x-typescript': ['ts','tsx']
+ },
preprocessors: {
'spec/**/*.spec.ts': ['browserify'],
} |
0d306907d1f2de812504af43fbaa360e070d720a | karma.conf.js | karma.conf.js | module.exports = function(config) {
config.set({
frameworks: ['mocha', 'chai'],
files: ['test/**/*.js', 'xterm-terminal.js'],
reporters: ['progress'],
port: 9876, // karma web server port
colors: true,
logLevel: config.LOG_INFO,
browsers: ['ChromeHeadless'],
autoWatch: false,
concurrency: Infinity,
customContextFile: 'test/context.html'
});
};
| module.exports = function(config) {
config.set({
frameworks: ['mocha', 'chai'],
files: ['test/**/*.js', 'node_modules/xterm/dist/xterm.js', 'xterm-terminal.js'],
reporters: ['progress'],
port: 9876, // karma web server port
colors: true,
logLevel: config.LOG_INFO,
browsers: ['ChromeHeadless'],
autoWatch: false,
concurrency: Infinity,
customContextFile: 'test/context.html'
});
};
| Add xterm.js to included files | Add xterm.js to included files | JavaScript | mit | parisk/xterm-terminal,parisk/xterm-terminal | ---
+++
@@ -1,7 +1,7 @@
module.exports = function(config) {
config.set({
frameworks: ['mocha', 'chai'],
- files: ['test/**/*.js', 'xterm-terminal.js'],
+ files: ['test/**/*.js', 'node_modules/xterm/dist/xterm.js', 'xterm-terminal.js'],
reporters: ['progress'],
port: 9876, // karma web server port
colors: true, |
fba020f9b26f4f8f8beefc925f219c5211174ea4 | www/last_photo_taken.js | www/last_photo_taken.js | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var LastPhotoTaken = {
getLastPhoto: function(max, startTime, endTime, onSuccess, onFailure){
cordova.exec(onSuccess, onFailure, "LastPhotoTaken", "getLastPhoto", [max, startTime, endTime]);
}
};
module.exports = LastPhotoTaken;
| /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var LastPhotoTaken = {
getLastPhoto: function(max, startTime, endTime, scanStartTime, onSuccess, onFailure){
cordova.exec(onSuccess, onFailure, "LastPhotoTaken", "getLastPhoto", [max, startTime, endTime, scanStartTime]);
}
};
module.exports = LastPhotoTaken;
| Update js interface to allow more params | Update js interface to allow more params
| JavaScript | apache-2.0 | xlongtang/cordova-last-photo-taken,xlongtang/cordova-last-photo-taken | ---
+++
@@ -18,8 +18,8 @@
*/
var LastPhotoTaken = {
- getLastPhoto: function(max, startTime, endTime, onSuccess, onFailure){
- cordova.exec(onSuccess, onFailure, "LastPhotoTaken", "getLastPhoto", [max, startTime, endTime]);
+ getLastPhoto: function(max, startTime, endTime, scanStartTime, onSuccess, onFailure){
+ cordova.exec(onSuccess, onFailure, "LastPhotoTaken", "getLastPhoto", [max, startTime, endTime, scanStartTime]);
}
};
|
6424996e2bd5f6ba06443c8efc4f3ae13f7b2186 | app/js/views/edit_profile_modal.js | app/js/views/edit_profile_modal.js | define(["application"], function(App) {
App.EditProfileModalView = Ember.View.extend({
actions: {
save: function () {
var person = this.get('controller.person')
, personData = this.get('controller.personData')
, newProperties = personData.getProperties([
'name', 'title', 'bio', 'website', 'github', 'twitter'
]);
/* Hide modal. */
this.$('#edit_profile_modal').modal('hide');
$.ajax({
url: App.API_BASE_URL + '/profile',
type: 'put',
data: {
person: {
}
}
});
/* Save profile changes. */
person.setProperties(newProperties);
}
},
templateName: 'views/edit_profile_modal'
});
}); | define(["application"], function(App) {
App.EditProfileModalView = Ember.View.extend({
actions: {
save: function () {
var person = this.get('controller.person')
, personData = this.get('controller.personData')
, newProperties = personData.getProperties([
'name', 'title', 'bio', 'website', 'github', 'twitter'
]);
/* Hide modal. */
this.$('#edit_profile_modal').modal('hide');
$.ajax({
url: App.API_BASE_URL + '/profile',
type: 'put',
data: {
person: personData.getProperties('name', 'title', 'twitter', 'github', 'website', 'bio')
}
});
/* Save profile changes. */
person.setProperties(newProperties);
}
},
templateName: 'views/edit_profile_modal'
});
});
| Send person data in the request. | Send person data in the request.
| JavaScript | mit | mhs/t2-people,mhs/t2-people,mhs/t2-people | ---
+++
@@ -15,9 +15,7 @@
url: App.API_BASE_URL + '/profile',
type: 'put',
data: {
- person: {
-
- }
+ person: personData.getProperties('name', 'title', 'twitter', 'github', 'website', 'bio')
}
});
|
908cee1e2d7a13863ff6b4dc0501f56e65eed958 | lib/index.js | lib/index.js | /**
server
The backbone of the server module. In development, this runs proxied through
BrowserSync server.
@param {Object} options Options passed on to "globals"
@param {Function} next Called when server successfully initialized
**/
var reorg = require("reorg");
module.exports = reorg(function(options, next) {
// Globals
require("./globals")(options);
var server = global.shipp.framework(),
middleware = require("./middleware"),
Utils = require("./utils");
[
// User-defined middleware
middleware("beforeAll"),
// Common middleware: logging, favicons, cookie parsing, sessions and body parsing
require("./common")(),
// User-defined middleware
middleware("beforeRoutes"),
// Static and compiled routes
require("./routes")(),
// Data-server
require("./data-server")(),
// User-defined middleware
middleware("afterRoutes")
].forEach(function(library) {
Utils.useMiddleware(server, library);
});
// Error handling: please see errors middleware for explanation of structure
require("./errors")(server, middleware("errorHandler"));
// Find open port and set up graceful shutdown
require("./lifecycle")(server, next);
}, "object", ["function", function() {}]);
| /**
server
The backbone of the server module. In development, this runs proxied through
BrowserSync server.
@param {Object} options Options passed on to "globals"
@param {Function} next Called when server successfully initialized
**/
var reorg = require("reorg");
module.exports = reorg(function(options, next) {
// Globals
require("./globals")(options);
var server = global.shipp.framework({ strict: true }),
middleware = require("./middleware"),
Utils = require("./utils");
[
// User-defined middleware
middleware("beforeAll"),
// Common middleware: logging, favicons, cookie parsing, sessions and body parsing
require("./common")(),
// User-defined middleware
middleware("beforeRoutes"),
// Static and compiled routes
require("./routes")(),
// Data-server
require("./data-server")(),
// User-defined middleware
middleware("afterRoutes")
].forEach(function(library) {
Utils.useMiddleware(server, library);
});
// Error handling: please see errors middleware for explanation of structure
require("./errors")(server, middleware("errorHandler"));
// Find open port and set up graceful shutdown
require("./lifecycle")(server, next);
}, "object", ["function", function() {}]);
| Enforce strict routing (handled in compiler) | Enforce strict routing (handled in compiler)
| JavaScript | apache-2.0 | shippjs/shipp-server,shippjs/shipp-server | ---
+++
@@ -17,7 +17,7 @@
// Globals
require("./globals")(options);
- var server = global.shipp.framework(),
+ var server = global.shipp.framework({ strict: true }),
middleware = require("./middleware"),
Utils = require("./utils");
|
498ca98b2fad6e15fa2d65cd7fb461861158e839 | packages/bottom-tabs/src/views/ResourceSavingScene.js | packages/bottom-tabs/src/views/ResourceSavingScene.js | /* @flow */
import * as React from 'react';
import { Platform, StyleSheet, View } from 'react-native';
import { Screen, screensEnabled } from 'react-native-screens';
type Props = {
isVisible: boolean,
children: React.Node,
style?: any,
};
const FAR_FAR_AWAY = 3000; // this should be big enough to move the whole view out of its container
export default class ResourceSavingScene extends React.Component<Props> {
render() {
if (screensEnabled()) {
const { isVisible, ...rest } = this.props;
return <Screen active={isVisible ? 1 : 0} {...rest} />;
}
const { isVisible, children, style, ...rest } = this.props;
return (
<View
style={[styles.container, style]}
collapsable={false}
removeClippedSubviews={
// On iOS, set removeClippedSubviews to true only when not focused
// This is an workaround for a bug where the clipped view never re-appears
Platform.OS === 'ios' ? !isVisible : true
}
pointerEvents={isVisible ? 'auto' : 'none'}
{...rest}
>
<View style={isVisible ? styles.attached : styles.detached}>
{children}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
overflow: 'hidden',
},
attached: {
flex: 1,
},
detached: {
flex: 1,
top: FAR_FAR_AWAY,
},
});
| /* @flow */
import * as React from 'react';
import { Platform, StyleSheet, View } from 'react-native';
import { Screen, screensEnabled } from 'react-native-screens';
type Props = {
isVisible: boolean,
children: React.Node,
style?: any,
};
const FAR_FAR_AWAY = 3000; // this should be big enough to move the whole view out of its container
export default class ResourceSavingScene extends React.Component<Props> {
render() {
if (screensEnabled && screensEnabled()) {
const { isVisible, ...rest } = this.props;
return <Screen active={isVisible ? 1 : 0} {...rest} />;
}
const { isVisible, children, style, ...rest } = this.props;
return (
<View
style={[styles.container, style]}
collapsable={false}
removeClippedSubviews={
// On iOS, set removeClippedSubviews to true only when not focused
// This is an workaround for a bug where the clipped view never re-appears
Platform.OS === 'ios' ? !isVisible : true
}
pointerEvents={isVisible ? 'auto' : 'none'}
{...rest}
>
<View style={isVisible ? styles.attached : styles.detached}>
{children}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
overflow: 'hidden',
},
attached: {
flex: 1,
},
detached: {
flex: 1,
top: FAR_FAR_AWAY,
},
});
| Handle case where screensEnabled isn't available (in Snack) | Handle case where screensEnabled isn't available (in Snack)
| JavaScript | bsd-2-clause | react-community/react-navigation,react-community/react-navigation,react-community/react-navigation | ---
+++
@@ -14,7 +14,7 @@
export default class ResourceSavingScene extends React.Component<Props> {
render() {
- if (screensEnabled()) {
+ if (screensEnabled && screensEnabled()) {
const { isVisible, ...rest } = this.props;
return <Screen active={isVisible ? 1 : 0} {...rest} />;
} |
400f41f87ae4d06db3d3c4e2b59dee40f4d06d0a | src/apps/support/middleware.js | src/apps/support/middleware.js | const { isEmpty, pickBy } = require('lodash')
const logger = require('../../../config/logger')
const { createZenDeskMessage, postToZenDesk } = require('./services')
async function postFeedback (req, res, next) {
const { title, feedbackType, email } = req.body
const messages = pickBy({
title: !title && 'Your feedback needs a title',
feedbackType: !feedbackType && 'You need to choose between raising a problem and leaving feedback',
email: (email && !email.match(/.*@.*\..*/)) && 'A valid email address is required',
})
res.locals.formErrors = Object.assign({}, res.locals.formErrors, {
messages,
})
const hasErrors = !isEmpty(res.locals.formErrors.messages) || res.locals.formErrors.summary
if (hasErrors) {
return next()
}
const ticket = createZenDeskMessage(req.body)
try {
const response = await postToZenDesk(ticket)
// TODO: Look into improving confirmation page https://www.gov.uk/service-manual/design/confirmation-pages
req.flash('success', `Created new report, reference number ${response.data.ticket.id}`)
res.redirect('/support/thank-you')
} catch (error) {
logger.error(error)
res.locals.formErrors = {
summary: error.message,
}
next()
}
}
module.exports = {
postFeedback,
}
| const { isEmpty, pickBy } = require('lodash')
const logger = require('../../../config/logger')
const { createZenDeskMessage, postToZenDesk } = require('./services')
async function postFeedback (req, res, next) {
const { title, feedbackType, email } = req.body
const messages = pickBy({
title: !title && 'Your feedback needs a title',
feedbackType: !feedbackType && 'You need to choose between raising a problem and leaving feedback',
email: (!email.match(/.*@.*\..*/)) && 'A valid email address is required',
})
res.locals.formErrors = Object.assign({}, res.locals.formErrors, {
messages,
})
const hasErrors = !isEmpty(res.locals.formErrors.messages) || res.locals.formErrors.summary
if (hasErrors) {
return next()
}
const ticket = createZenDeskMessage(req.body)
try {
const response = await postToZenDesk(ticket)
// TODO: Look into improving confirmation page https://www.gov.uk/service-manual/design/confirmation-pages
req.flash('success', `Created new report, reference number ${response.data.ticket.id}`)
res.redirect('/support/thank-you')
} catch (error) {
logger.error(error)
res.locals.formErrors = {
summary: error.message,
}
next()
}
}
module.exports = {
postFeedback,
}
| Set email address as optional to show optional label | Set email address as optional to show optional label
| JavaScript | mit | uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend | ---
+++
@@ -9,7 +9,7 @@
const messages = pickBy({
title: !title && 'Your feedback needs a title',
feedbackType: !feedbackType && 'You need to choose between raising a problem and leaving feedback',
- email: (email && !email.match(/.*@.*\..*/)) && 'A valid email address is required',
+ email: (!email.match(/.*@.*\..*/)) && 'A valid email address is required',
})
res.locals.formErrors = Object.assign({}, res.locals.formErrors, { |
2d7da7b416b460aaa646e6662a622990bda1a07b | src/components/services/ConfigService.js | src/components/services/ConfigService.js | (function() {
'use strict';
angular.module('civic.services')
.constant('ConfigService', {
serverUrl: 'http://localhost:3000/',
mainMenuItems: [
{
label: 'Collaborate',
state: 'collaborate'
},
{
label: 'Help',
state: 'help'
},
{
label: 'Contact',
state: 'contact'
}
]
}
);
})();
| (function() {
'use strict';
angular.module('civic.services')
.constant('ConfigService', {
serverUrl: 'http://localhost:3000/',
mainMenuItems: [
{
label: 'Collaborate',
state: 'collaborate'
},
{
label: 'Help',
state: 'help'
},
{
label: 'FAQ',
state: 'faq'
}
]
}
);
})();
| Replace the Contact page with the FAQ page | Replace the Contact page with the FAQ page
| JavaScript | mit | yanyangfeng/civic-client,yanyangfeng/civic-client,genome/civic-client,genome/civic-client | ---
+++
@@ -13,8 +13,8 @@
state: 'help'
},
{
- label: 'Contact',
- state: 'contact'
+ label: 'FAQ',
+ state: 'faq'
}
]
} |
54cb3847e205dff54c4f3490a15e659f81b0bb5a | app/javascript/messages.js | app/javascript/messages.js | /* global angular */
const MESSAGE_TIMEOUTS = {message: 7000, success: 6000, error: 14000};
angular.module('dappChess').controller('MessagesCtrl', function ($scope) {
$scope.messages = [];
$scope.$on('message', function(event, message, type = message, topic = null) {
let id = Math.random();
if(topic) {
$scope.messages = $scope.messages.filter(function(message) {
if(topic === message.topic) {
return false;
}
return true;
});
}
if(type === 'success' || type === 'error') {
setTimeout(function() {
$scope.messages = $scope.messages.filter(function(message) {
if(id === message.id) {
return false;
}
return true;
});
$scope.$apply();
}, MESSAGE_TIMEOUTS[type]);
}
$scope.messages.push({
id: id,
message: message,
type: type,
topic: topic
});
});
});
| /* global angular */
const MESSAGE_TIMEOUTS = {message: 7000, success: 6000, error: 14000};
angular.module('dappChess').controller('MessagesCtrl', function ($scope, $timeout) {
$scope.messages = [];
$scope.$on('message', function(event, message, type = message, topic = null) {
let id = Math.random();
if(topic) {
$scope.messages = $scope.messages.filter(function(message) {
if(topic === message.topic) {
return false;
}
return true;
});
}
if(type === 'success' || type === 'error') {
$timeout(function() {
$scope.messages = $scope.messages.filter(function(message) {
if(id === message.id) {
return false;
}
return true;
});
}, MESSAGE_TIMEOUTS[type]);
}
$scope.messages.push({
id: id,
message: message,
type: type,
topic: topic
});
});
});
| Use $timeout instead of setTimeout for better compatibility | Use $timeout instead of setTimeout for better compatibility | JavaScript | mit | ise-ethereum/on-chain-chess,ise-ethereum/on-chain-chess | ---
+++
@@ -1,7 +1,7 @@
/* global angular */
const MESSAGE_TIMEOUTS = {message: 7000, success: 6000, error: 14000};
-angular.module('dappChess').controller('MessagesCtrl', function ($scope) {
+angular.module('dappChess').controller('MessagesCtrl', function ($scope, $timeout) {
$scope.messages = [];
$scope.$on('message', function(event, message, type = message, topic = null) {
@@ -16,14 +16,13 @@
});
}
if(type === 'success' || type === 'error') {
- setTimeout(function() {
+ $timeout(function() {
$scope.messages = $scope.messages.filter(function(message) {
if(id === message.id) {
return false;
}
return true;
});
- $scope.$apply();
}, MESSAGE_TIMEOUTS[type]);
}
|
b752f54661aa11ea235ed6c092a2b41188685e68 | src/beat.js | src/beat.js | (function() {
var Beat = function ( dance, freq, threshold, decay, onBeat, offBeat ) {
this.dance = dance;
this.freq = freq;
this.threshold = threshold;
this.decay = decay;
this.onBeat = onBeat;
this.offBeat = offBeat;
this.isOn = false;
this.currentThreshold = threshold;
var _this = this;
this.dance.bind( 'update', function() {
if ( !_this.isOn ) { return; }
var magnitude = _this.dance.spectrum()[ _this.freq ];
if ( magnitude >= _this.currentThreshold &&
magnitude >= _this.threshold ) {
_this.currentThreshold = magnitude;
onBeat.call( _this.dance, magnitude );
} else {
offBeat.call( _this.dance, magnitude );
_this.currentThreshold -= _this.decay;
}
});
};
Beat.prototype = {
on : function () { this.isOn = true; },
off : function () { this.isOn = false; }
};
window.Dance.Beat = Beat;
})();
| (function() {
var Beat = function ( dance, frequency, threshold, decay, onBeat, offBeat ) {
this.dance = dance;
this.frequency = frequency;
this.threshold = threshold;
this.decay = decay;
this.onBeat = onBeat;
this.offBeat = offBeat;
this.isOn = false;
this.currentThreshold = threshold;
var _this = this;
this.dance.bind( 'update', function() {
if ( !_this.isOn ) { return; }
var magnitude = _this.dance.spectrum()[ _this.frequency ];
if ( magnitude >= _this.currentThreshold &&
magnitude >= _this.threshold ) {
_this.currentThreshold = magnitude;
onBeat.call( _this.dance, magnitude );
} else {
offBeat.call( _this.dance, magnitude );
_this.currentThreshold -= _this.decay;
}
});
};
Beat.prototype = {
on : function () { this.isOn = true; },
off : function () { this.isOn = false; }
};
window.Dance.Beat = Beat;
})();
| Change Beat's instance property 'freq' to 'frequency' for more natural get/setting | Change Beat's instance property 'freq' to 'frequency' for more natural get/setting
| JavaScript | mit | modulexcite/dancer.js,kyroskoh/dancer.js,ngokevin/dancer.js,jsantell/dancer.js,kyroskoh/dancer.js,ngokevin/dancer.js,modulexcite/dancer.js,hoboman313/dancer.js,hoboman313/dancer.js,suryasingh/dancer.js,suryasingh/dancer.js | ---
+++
@@ -1,7 +1,7 @@
(function() {
- var Beat = function ( dance, freq, threshold, decay, onBeat, offBeat ) {
+ var Beat = function ( dance, frequency, threshold, decay, onBeat, offBeat ) {
this.dance = dance;
- this.freq = freq;
+ this.frequency = frequency;
this.threshold = threshold;
this.decay = decay;
this.onBeat = onBeat;
@@ -12,7 +12,7 @@
var _this = this;
this.dance.bind( 'update', function() {
if ( !_this.isOn ) { return; }
- var magnitude = _this.dance.spectrum()[ _this.freq ];
+ var magnitude = _this.dance.spectrum()[ _this.frequency ];
if ( magnitude >= _this.currentThreshold &&
magnitude >= _this.threshold ) {
_this.currentThreshold = magnitude; |
989bd29938fe860ea862fe914254d1373a6422da | app/mirage/route-handlers/index.js | app/mirage/route-handlers/index.js | import getDailyRiderships from './get-daily-riderships';
import getRoute from './get-route';
import getRoutes from './get-routes';
import getServiceHourRiderships from './get-service-hour-riderships';
import getSystemTrends from './get-system-trends';
export {getDailyRiderships as getDailyRiderships};
export {getServiceHourRiderships as getServiceHourRiderships};
export {getRoute as getRoute};
export {getRoutes as getRoutes};
export {getSystemTrends as getSystemTrends};
| import getDailyRiderships from './get-daily-riderships';
import getHighRidership from './get-high-ridership';
import getRoute from './get-route';
import getRoutes from './get-routes';
import getRouteLabels from './get-route-labels';
import getServiceHourRiderships from './get-service-hour-riderships';
import getSystemTrends from './get-system-trends';
export {getDailyRiderships as getDailyRiderships};
export {getHighRidership as getHighRidership};
export {getRoute as getRoute};
export {getRoutes as getRoutes};
export {getRouteLabels as getRouteLabels};
export {getServiceHourRiderships as getServiceHourRiderships};
export {getSystemTrends as getSystemTrends};
| Add new Mirage route handlers. | Add new Mirage route handlers.
| JavaScript | mit | jga/capmetrics-web,jga/capmetrics-web | ---
+++
@@ -1,12 +1,15 @@
import getDailyRiderships from './get-daily-riderships';
+import getHighRidership from './get-high-ridership';
import getRoute from './get-route';
import getRoutes from './get-routes';
+import getRouteLabels from './get-route-labels';
import getServiceHourRiderships from './get-service-hour-riderships';
import getSystemTrends from './get-system-trends';
export {getDailyRiderships as getDailyRiderships};
-export {getServiceHourRiderships as getServiceHourRiderships};
+export {getHighRidership as getHighRidership};
export {getRoute as getRoute};
export {getRoutes as getRoutes};
+export {getRouteLabels as getRouteLabels};
+export {getServiceHourRiderships as getServiceHourRiderships};
export {getSystemTrends as getSystemTrends};
- |
ecca67b6eb571673adca35cf952b5e3bcaa01832 | gulp/handlebars.js | gulp/handlebars.js | import path from 'path';
import _ from 'lodash';
import minimatch from "minimatch";
let allFiles = {}
module.exports.helpers = {
equal(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlebars Helper equal needs 2 parameters");
if( lvalue!=rvalue ) {
return options.inverse(this);
} else {
return options.fn(this);
}
},
eachFile() {
let args = Array.slice(arguments);
let options = _.last(args)
let globs = args.slice(0, args.length-1);
let result = "";
_.each(allFiles, (f,p) => {
let matches = _.any(globs, g => minimatch(p,g));
if (!matches) return
result += options.fn({path: p, file: f});
});
return result;
},
sidebarSubMenu(title, options) {
return `
<li class="pageNavList__subList">
<span class="pageNavList__title">${title}</span>
<ul>
${options.fn(this)}
</ul>
</li>
`;
},
}
module.exports.setFileList = function(files) {
allFiles = files
}
| import path from 'path';
import _ from 'lodash';
import minimatch from "minimatch";
let allFiles = {}
module.exports.helpers = {
equal(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlebars Helper equal needs 2 parameters");
if( lvalue!=rvalue ) {
return options.inverse(this);
} else {
return options.fn(this);
}
},
eachFile() {
let args = Array.slice(arguments);
let options = _.last(args)
let globs = args.slice(0, args.length-1);
let result = "";
_.each(allFiles, (f,p) => {
let matches = _.any(globs, g => minimatch(p,g));
if (!matches) return
let ctx = _.extend({}, this, {path: p, file: f})
result += options.fn(ctx);
});
return result;
},
sidebarSubMenu(title, options) {
return `
<li class="pageNavList__subList">
<span class="pageNavList__title">${title}</span>
<ul>
${options.fn(this)}
</ul>
</li>
`;
},
}
module.exports.setFileList = function(files) {
allFiles = files
}
| Fix context loss for eachFile helper | Fix context loss for eachFile helper
| JavaScript | apache-2.0 | stellar/developers,stellar/developers | ---
+++
@@ -26,7 +26,9 @@
let matches = _.any(globs, g => minimatch(p,g));
if (!matches) return
- result += options.fn({path: p, file: f});
+ let ctx = _.extend({}, this, {path: p, file: f})
+
+ result += options.fn(ctx);
});
return result; |
2d61e31acdc66a57107ef4198f9641f0b18b2d13 | packages/truffle-core/lib/services/analytics/index.js | packages/truffle-core/lib/services/analytics/index.js | const analytics = {
send: function(eventObject) {
let analyticsPath;
const path = require("path");
if (typeof BUNDLE_ANALYTICS_FILENAME != "undefined") {
analyticsPath = path.join(__dirname, BUNDLE_ANALYTICS_FILENAME);
} else {
analyticsPath = path.join(__dirname, "main.js");
}
const cp = require("child_process");
const child = cp.fork(analyticsPath, { silent: true });
child.send(eventObject);
}
};
module.exports = analytics;
| const analytics = {
send: function(eventObject) {
let analyticsPath;
const path = require("path");
if (typeof BUNDLE_ANALYTICS_FILENAME !== "undefined") {
analyticsPath = path.join(__dirname, BUNDLE_ANALYTICS_FILENAME);
} else {
analyticsPath = path.join(__dirname, "main.js");
}
const cp = require("child_process");
const child = cp.fork(analyticsPath, { silent: true });
child.send(eventObject);
}
};
module.exports = analytics;
| Convert Non-strict to strict equality checking Convert non-strict equality checking, using `==`, to the strict version, using `===`. | Convert Non-strict to strict equality checking
Convert non-strict equality checking, using `==`, to the strict version, using `===`. | JavaScript | mit | ConsenSys/truffle | ---
+++
@@ -2,7 +2,7 @@
send: function(eventObject) {
let analyticsPath;
const path = require("path");
- if (typeof BUNDLE_ANALYTICS_FILENAME != "undefined") {
+ if (typeof BUNDLE_ANALYTICS_FILENAME !== "undefined") {
analyticsPath = path.join(__dirname, BUNDLE_ANALYTICS_FILENAME);
} else {
analyticsPath = path.join(__dirname, "main.js"); |
c01901bb1c95c5b96560d53dd4e2cf46b6b95207 | simpleshelfmobile/_attachments/code/router.js | simpleshelfmobile/_attachments/code/router.js | "use strict";
/**
* Handle all routes.
*/
define([
"underscore",
"backbone",
"app"
], function(_, Backbone, app) {
// Define the application router.
var Router = Backbone.Router.extend({
routes: {
"": "index",
"login": "login"
},
/**
* Index route (default)
*/
index: function() {
this._log("/ route.");
this._changeScreen(app.views.frontPageView);
},
login: function() {
this._log("/login");
// TODO
},
_log: function() {
console.log("[router]", _.toArray(arguments).join(" "));
}
});
return Router;
});
| "use strict";
/**
* Handle all routes.
*/
define([
"underscore",
"backbone",
"app"
], function(_, Backbone, app) {
// Define the application router.
var Router = Backbone.Router.extend({
routes: {
"": "index",
"login": "login"
},
/**
* Index route (default)
*/
index: function() {
this._log("/ route.");
// this._changeScreen(app.views.frontPageView);
},
login: function() {
this._log("/login");
this._changeScreen(app.views.loginPageView);
},
main: function() {
this._log("/main");
// TODO
},
/**
* Change the current screen.
* Instantiates the view if not already in DOM.
*/
_changeScreen: function(view, options) {
if (!view.isInDOM) {
console.info("[router]", "Rendering " + view.getName());
// Render view & get handle to object.
view.render();
// Call post-render actions.
if (view.postRender) {
view.postRender();
}
// Initialize the jqm page widget for this new element.
view.$el.page({});
view.$el.trigger('create');
}
// Change to this view.
$.mobile.pageContainer.pagecontainer("change", view.$el, options);
},
_log: function() {
console.log("[router]", _.toArray(arguments).join(" "));
}
});
return Router;
});
| Add main route, change screen helper | Add main route, change screen helper
| JavaScript | agpl-3.0 | tephyr/simpleshelf,tephyr/simpleshelf,tephyr/simpleshelf,tephyr/simpleshelf | ---
+++
@@ -20,12 +20,38 @@
*/
index: function() {
this._log("/ route.");
- this._changeScreen(app.views.frontPageView);
+ // this._changeScreen(app.views.frontPageView);
},
login: function() {
this._log("/login");
+ this._changeScreen(app.views.loginPageView);
+ },
+
+ main: function() {
+ this._log("/main");
// TODO
+ },
+
+ /**
+ * Change the current screen.
+ * Instantiates the view if not already in DOM.
+ */
+ _changeScreen: function(view, options) {
+ if (!view.isInDOM) {
+ console.info("[router]", "Rendering " + view.getName());
+ // Render view & get handle to object.
+ view.render();
+ // Call post-render actions.
+ if (view.postRender) {
+ view.postRender();
+ }
+ // Initialize the jqm page widget for this new element.
+ view.$el.page({});
+ view.$el.trigger('create');
+ }
+ // Change to this view.
+ $.mobile.pageContainer.pagecontainer("change", view.$el, options);
},
_log: function() { |
cfaa1420009e4525aa74f7374c04adb0d29721b4 | src/v2/components/UI/Layouts/BlankLayout/components/BaseStyles/index.js | src/v2/components/UI/Layouts/BlankLayout/components/BaseStyles/index.js | import { createGlobalStyle } from 'styled-components'
export default createGlobalStyle`
body {
margin: 0;
padding: 0;
-webkit-font-smoothing: antialiased;
font-family: ${props => props.theme.fonts.sans};
background-color: ${props => props.theme.colors.background};
}
a {
text-decoration: none;
color: inherit;
cursor: pointer;
}
a:focus {
outline: none;
}
a:focus-visible {
outline: 1px solid ${({ theme }) => theme.colors.state.premium};
}
@media not all and (min-resolution:.001dpcm){
@supports (-webkit-appearance:none) {
a:focus {
outline: 0;
}
}
}
`
| import { createGlobalStyle } from 'styled-components'
export default createGlobalStyle`
body {
margin: 0;
padding: 0;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-family: ${props => props.theme.fonts.sans};
background-color: ${props => props.theme.colors.background};
}
a {
text-decoration: none;
color: inherit;
cursor: pointer;
}
a:focus {
outline: none;
}
a:focus-visible {
outline: 1px solid ${({ theme }) => theme.colors.state.premium};
}
@media not all and (min-resolution:.001dpcm){
@supports (-webkit-appearance:none) {
a:focus {
outline: 0;
}
}
}
`
| Add font smoothing for firefox | Add font smoothing for firefox
| JavaScript | mit | aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell | ---
+++
@@ -5,6 +5,7 @@
margin: 0;
padding: 0;
-webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
font-family: ${props => props.theme.fonts.sans};
background-color: ${props => props.theme.colors.background};
} |
c40a5137dd0236ff6a9ad4ebfda4071381f3fd9a | src/app/services/messaging.js | src/app/services/messaging.js | import socketCluster from 'socketcluster-client';
import socketOptions from '../constants/socketOptions';
let socket;
let channel;
export function subscribe(subscriber, options) {
if (socket) socket.disconnect();
socket = socketCluster.connect({
...socketOptions,
...options
});
socket.emit('login', {}, (err, channelName) => {
if (err) { console.error(err); return; }
channel = socket.subscribe(channelName);
channel.watch(subscriber);
});
}
export function dispatchRemotely(action) {
socket.emit('respond', { type: 'DISPATCH', action });
}
| import socketCluster from 'socketcluster-client';
import socketOptions from '../constants/socketOptions';
let socket;
let channel;
export function subscribe(subscriber, options = socketOptions) {
if (socket) socket.disconnect();
socket = socketCluster.connect(options);
socket.emit('login', {}, (err, channelName) => {
if (err) { console.error(err); return; }
channel = socket.subscribe(channelName);
channel.watch(subscriber);
});
}
export function dispatchRemotely(action) {
socket.emit('respond', { type: 'DISPATCH', action });
}
| Use default options from socketcluster when not specified | Use default options from socketcluster when not specified
| JavaScript | mit | zalmoxisus/remotedev-app,zalmoxisus/remotedev-app | ---
+++
@@ -4,12 +4,9 @@
let socket;
let channel;
-export function subscribe(subscriber, options) {
+export function subscribe(subscriber, options = socketOptions) {
if (socket) socket.disconnect();
- socket = socketCluster.connect({
- ...socketOptions,
- ...options
- });
+ socket = socketCluster.connect(options);
socket.emit('login', {}, (err, channelName) => {
if (err) { console.error(err); return; } |
dbc6e45a1b2c8de616f1d28646c388951125d241 | src/defaultPropTypes.js | src/defaultPropTypes.js | import { PropTypes } from 'react';
export default {
message: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element
]).isRequired,
action: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.string
]),
onClick: PropTypes.func,
style: PropTypes.bool,
actionStyle: PropTypes.object,
barStyle: PropTypes.object,
activeBarStyle: PropTypes.object,
dismissAfter: PropTypes.number,
onDismiss: PropTypes.func,
className: PropTypes.string,
activeClassName: PropTypes.string.isRequired,
isActive: PropTypes.bool,
title: PropTypes.string
};
| import { PropTypes } from 'react';
export default {
message: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element
]).isRequired,
action: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.string,
PropTypes.node
]),
onClick: PropTypes.func,
style: PropTypes.bool,
actionStyle: PropTypes.object,
barStyle: PropTypes.object,
activeBarStyle: PropTypes.object,
dismissAfter: PropTypes.number,
onDismiss: PropTypes.func,
className: PropTypes.string,
activeClassName: PropTypes.string.isRequired,
isActive: PropTypes.bool,
title: PropTypes.string
};
| Change proptypes for action to allow node | Change proptypes for action to allow node
* Changed proptypes for action in order to remove the proptypes warning when passing a node.
* Changed action proptype to accept node
| JavaScript | mit | pburtchaell/react-notification | ---
+++
@@ -7,7 +7,8 @@
]).isRequired,
action: PropTypes.oneOfType([
PropTypes.bool,
- PropTypes.string
+ PropTypes.string,
+ PropTypes.node
]),
onClick: PropTypes.func,
style: PropTypes.bool, |
92a92cdbf9a25aa4afa6b5d7983ec5d4c9738747 | gevents.js | gevents.js | 'use strict';
var request = require('request');
var opts = parseOptions(process.argv[2]);
request(opts, function (err, res, body) {
if (err) throw new Error(err);
var format = '[%s]: %s %s %s %s';
for (var i = 0; i < body.length; i++) {
/*
* TODO return something like this as JSON
* for caller consumption (useful for servers).
*/
console.log(format
, body[i].created_at
, body[i].type
, body[i].actor.login
, body[i].repo.name);
}
});
/*
* Verify param is present, and just return it.
* TODO
* Check for multiple params, and check validity
* as well as presence.
*/
function parseParams(params) {
if (! params) {
console.log('Usage: nodejs gevents.js <user-name>');
process.exit(0);
}
return params;
}
function parseOptions(opts) {
// org or users, resource, query topic
var who = '/users'
, where = '/' + opts
, what = '/events'
var options = {
uri: 'https://api.github.com'
+ who
+ where
+ what,
json: true,
method: 'GET',
headers: {
'User-Agent': 'nodejs script'
}
}
return options;
}
| 'use strict';
var request = require('request');
var opts = parseOptions(process.argv[2]);
request(opts, function (err, res, body) {
if (err) throw new Error(err);
var format = '[%s]: %s %s %s';
for (var i = 0; i < body.length; i++) {
/*
* TODO return something like this as JSON
* for caller consumption (useful for servers).
*/
console.log(format
, body[i].created_at
, body[i].type
, body[i].actor.login
, body[i].repo.name);
}
});
/*
* Verify param is present, and just return it.
* TODO
* Check for multiple params, and check validity
* as well as presence.
*/
function parseParams(params) {
if (! params) {
console.log('Usage: nodejs gevents.js <user-name>');
process.exit(0);
}
return params;
}
function parseOptions(opts) {
// org or users, resource, query topic
var who = '/users'
, where = '/' + opts
, what = '/events'
var options = {
uri: 'https://api.github.com'
+ who
+ where
+ what,
json: true,
method: 'GET',
headers: {
'User-Agent': 'nodejs script'
}
}
return options;
}
| Remove superfluous string from format variable | Remove superfluous string from format variable
| JavaScript | mit | jm-janzen/scripts,jm-janzen/scripts,jm-janzen/scripts | ---
+++
@@ -7,7 +7,7 @@
request(opts, function (err, res, body) {
if (err) throw new Error(err);
- var format = '[%s]: %s %s %s %s';
+ var format = '[%s]: %s %s %s';
for (var i = 0; i < body.length; i++) {
/* |
fbda3cfcb96e7cb8b5535fcb8985b942b7f0606d | javascript/DependentDynamicListDropdownField.js | javascript/DependentDynamicListDropdownField.js | (function($){
$.entwine('ss', function($){
$('select.dependentdynamiclistdropdown').entwine({
onmatch : function(){
var self = $(this),
dependentOn = $('select[name=' + self.data('dependenton') + ']');
if(!dependentOn.length){
return;
}
if(dependentOn.val()){
self.updateOptions(dependentOn.val());
if(self.data('initialvalue')){
self.val(self.data('initialvalue'));
}
}
dependentOn.bind('change', function(){
self.updateOptions(dependentOn.val());
});
},
updateOptions : function(listName, value){
var self = $(this),
lists = self.data('listoptions'),
list = lists[listName];
if(typeof list == "object"){
self.empty();
for (var k in list) {
var sel = '';
if (k == value) {
sel = ' selected="selected"';
}
self.append('<option val="' + k + '"' + sel + '>' + k + '</option>');
}
}
self.trigger('liszt:updated');
}
});
});
})(jQuery); | (function($){
$.entwine('ss', function($){
$('select.dependentdynamiclistdropdown').entwine({
onmatch : function(){
var self = $(this),
dependentOn = $('select[name=' + self.data('dependenton') + ']');
if(!dependentOn.length){
return;
}
if(dependentOn.val()){
self.updateOptions(dependentOn.val());
if(self.data('initialvalue')){
self.change(function(){
var data = $(this).val();
});
self.val(self.data('initialvalue')).trigger('change');
if(self.chosen != undefined) {
self.trigger("liszt:updated");
self.trigger("chosen:updated");
}
}
}
dependentOn.bind('change', function(){
self.updateOptions(dependentOn.val());
});
},
updateOptions : function(listName, value){
var self = $(this),
lists = self.data('listoptions'),
list = lists[listName];
if(typeof list == "object"){
self.empty();
for (var k in list) {
var sel = '';
if (k == value) {
sel = ' selected="selected"';
}
self.append('<option val="' + k + '"' + sel + '>' + k + '</option>');
}
}
if(self.chosen != undefined) {
self.trigger('liszt:updated');
self.trigger("chosen:updated");
}
}
});
});
})(jQuery); | FIX (field js): correctly refresh chosen fields if dependent field already has value | FIX (field js): correctly refresh chosen fields if dependent field already has value
| JavaScript | bsd-3-clause | sheadawson/silverstripe-dynamiclists,sheadawson/silverstripe-dynamiclists | ---
+++
@@ -13,7 +13,16 @@
if(dependentOn.val()){
self.updateOptions(dependentOn.val());
if(self.data('initialvalue')){
- self.val(self.data('initialvalue'));
+ self.change(function(){
+ var data = $(this).val();
+ });
+
+ self.val(self.data('initialvalue')).trigger('change');
+
+ if(self.chosen != undefined) {
+ self.trigger("liszt:updated");
+ self.trigger("chosen:updated");
+ }
}
}
@@ -37,7 +46,10 @@
self.append('<option val="' + k + '"' + sel + '>' + k + '</option>');
}
}
- self.trigger('liszt:updated');
+ if(self.chosen != undefined) {
+ self.trigger('liszt:updated');
+ self.trigger("chosen:updated");
+ }
}
}); |
c79d4fee907c01e8a1acb8d33fbac5be67493f9f | app/components/game-nav.js | app/components/game-nav.js | import * as React from 'react'
import {Octicon as OcticonClass} from './octicon'
import {Link} from 'react-router'
let Octicon = React.createFactory(OcticonClass);
let GameNavbar = React.createClass({
render() {
return React.createElement('ul', {id: 'game-nav', className: 'menu'},
React.createElement('li', {key: 'board'},
React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'board'}}, Octicon({icon: 'globe'}
))),
React.createElement('li', {key: 'chat'},
React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'chat'}}, Octicon({icon: 'comment-discussion'}
))),
React.createElement('li', {key: 'history'},
React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'history'}}, Octicon({icon: 'clock'}
))),
React.createElement('li', {key: 'info'},
React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'info'}}, Octicon({icon: 'gear'}
)))
)
},
})
export default GameNavbar
| import * as React from 'react'
import {State} from 'react-router'
import {Octicon as OcticonClass} from './octicon'
import {Link as LinkClass} from 'react-router'
let Link = React.createFactory(LinkClass);
let Octicon = React.createFactory(OcticonClass);
let GameNavbar = React.createClass({
mixins: [State],
render() {
return React.createElement('ul', {id: 'game-nav', className: 'menu'},
React.createElement('li', null,
Link({to: 'game', params: this.getParams(), query: {section: 'board'}}, Octicon({icon: 'globe'}
))),
React.createElement('li', null,
Link({to: 'game', params: this.getParams(), query: {section: 'chat'}}, Octicon({icon: 'comment-discussion'}
))),
React.createElement('li', null,
Link({to: 'game', params: this.getParams(), query: {section: 'history'}}, Octicon({icon: 'clock'}
))),
React.createElement('li', null,
Link({to: 'game', params: this.getParams(), query: {section: 'info'}}, Octicon({icon: 'gear'}
)))
)
},
})
export default GameNavbar
| Use the RouterState mixin in GameNav | Use the RouterState mixin in GameNav
| JavaScript | mit | hawkrives/svg-diplomacy,hawkrives/svg-diplomacy,hawkrives/svg-diplomacy,hawkrives/svg-diplomacy | ---
+++
@@ -1,23 +1,26 @@
import * as React from 'react'
+import {State} from 'react-router'
import {Octicon as OcticonClass} from './octicon'
-import {Link} from 'react-router'
+import {Link as LinkClass} from 'react-router'
+let Link = React.createFactory(LinkClass);
let Octicon = React.createFactory(OcticonClass);
let GameNavbar = React.createClass({
+ mixins: [State],
render() {
return React.createElement('ul', {id: 'game-nav', className: 'menu'},
- React.createElement('li', {key: 'board'},
- React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'board'}}, Octicon({icon: 'globe'}
+ React.createElement('li', null,
+ Link({to: 'game', params: this.getParams(), query: {section: 'board'}}, Octicon({icon: 'globe'}
))),
- React.createElement('li', {key: 'chat'},
- React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'chat'}}, Octicon({icon: 'comment-discussion'}
+ React.createElement('li', null,
+ Link({to: 'game', params: this.getParams(), query: {section: 'chat'}}, Octicon({icon: 'comment-discussion'}
))),
- React.createElement('li', {key: 'history'},
- React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'history'}}, Octicon({icon: 'clock'}
+ React.createElement('li', null,
+ Link({to: 'game', params: this.getParams(), query: {section: 'history'}}, Octicon({icon: 'clock'}
))),
- React.createElement('li', {key: 'info'},
- React.createElement(Link, {to: 'game', params: {gameId: this.props.params.gameId}, query: {section: 'info'}}, Octicon({icon: 'gear'}
+ React.createElement('li', null,
+ Link({to: 'game', params: this.getParams(), query: {section: 'info'}}, Octicon({icon: 'gear'}
)))
)
}, |
e8d94d83d8f78d5407aca3f3609b68b375ffb667 | app/Gruntfile.js | app/Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
babel: {
options: {
sourceMap: true,
presets: ['es2015', 'react']
},
dist: {
files: [
{
expand: true,
cwd: 'ui/js',
src: ['*.js'],
ext: '.js',
dest: 'ui/'
}
]
}
},
watch: {
scripts: {
files: ['**/*.jsx'],
tasks: ['babel'],
options: {
spawn: false,
},
},
}
});
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('load-grunt-tasks');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['babel']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
babel: {
options: {
sourceMap: true,
presets: ['es2015', 'react']
},
dist: {
files: [
{
expand: true,
cwd: 'ui/js',
src: ['*.js', '*.jsx'],
ext: '.js',
dest: 'ui/'
}
]
}
},
watch: {
scripts: {
files: ['**/*.jsx'],
tasks: ['babel'],
options: {
spawn: false,
},
},
}
});
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('load-grunt-tasks');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['babel']);
};
| Update grunt setup to compile JSX properly | Update grunt setup to compile JSX properly
| JavaScript | mit | muffinista/before-dawn,muffinista/before-dawn,muffinista/before-dawn | ---
+++
@@ -11,7 +11,7 @@
{
expand: true,
cwd: 'ui/js',
- src: ['*.js'],
+ src: ['*.js', '*.jsx'],
ext: '.js',
dest: 'ui/'
} |
79924bfd5429029b7ab7943bbbd9ac67182bb0e0 | src/core/touch.js | src/core/touch.js | /**
* Flag indicating if the client supports touch events.
*
* @returns {Boolean} <em>true</em> if have touch support
* @preserve
*/
sn.hasTouchSupport = (function() {
if ( !(global && global.document) ) {
return false;
}
if ( 'createTouch' in global.document ) { // True on the iPhone
return true;
}
try {
var event = global.document.createEvent('TouchEvent');
return !!event.initTouchEvent;
} catch( error ) {
return false;
}
}());
| /**
* Flag indicating if the client supports touch events.
*
* @returns {Boolean} <em>true</em> if have touch support
* @preserve
*/
sn.hasTouchSupport = (function() {
if ( !(global && global.document) ) {
return false;
}
if ( 'createTouch' in global.document ) { // True on the iPhone
return true;
}
try {
var event = global.document.createEvent('TouchEvent');
return !!event.initTouchEvent;
} catch( error ) {
return false;
}
}());
/**
* Names to use for user-interaction events.
*
* <p>On non-touch devices these equate to <em>mousedown</em>,
* <em>mouseup</em>, etc. On touch-enabled devices these equate to
* <em>touchstart</em>, <em>touchend</em>, etc.</p>
*
* @retunrs {Object} Mapping of start, move, end, cancel keys to associated event names.
* @preserve
*/
sn.tapEventNames = (function() {
return (sn.hasTouchSupport ? {
start: "touchstart",
move: "touchmove",
end: "touchend",
cancel: "touchcancel",
click: "touchstart",
dblclick: "touchstart"
} : {
start: "mousedown",
move: "mousemove",
end: "mouseup",
cancel: "touchcancel",
click: "click",
dblclick: "dblclick"
});
}());
/**
* Get the first user-interaction x,y coordinates relative to a given container element.
*
* @param {Node} container - A DOM container node to get the relative coordinates for.
* @returns {Array} An array like <code>[x, y]</code> or <code>undefined</code> if not known.
* @preserve
*/
sn.tapCoordinates = function(container) {
var coordinates;
if ( sn.hasTouchSupport ) {
coordinates = d3.touches(container);
return (coordinates && coordinates.length > 0 ? coordinates[0] : undefined);
}
return d3.mouse(container);
};
| Add missing tapEventNames and tapCoordinates properties. | Add missing tapEventNames and tapCoordinates properties.
| JavaScript | apache-2.0 | SolarNetwork/solarnetwork-d3,SolarNetwork/solarnetwork-d3 | ---
+++
@@ -18,3 +18,47 @@
return false;
}
}());
+
+/**
+ * Names to use for user-interaction events.
+ *
+ * <p>On non-touch devices these equate to <em>mousedown</em>,
+ * <em>mouseup</em>, etc. On touch-enabled devices these equate to
+ * <em>touchstart</em>, <em>touchend</em>, etc.</p>
+ *
+ * @retunrs {Object} Mapping of start, move, end, cancel keys to associated event names.
+ * @preserve
+ */
+sn.tapEventNames = (function() {
+ return (sn.hasTouchSupport ? {
+ start: "touchstart",
+ move: "touchmove",
+ end: "touchend",
+ cancel: "touchcancel",
+ click: "touchstart",
+ dblclick: "touchstart"
+ } : {
+ start: "mousedown",
+ move: "mousemove",
+ end: "mouseup",
+ cancel: "touchcancel",
+ click: "click",
+ dblclick: "dblclick"
+ });
+}());
+
+/**
+ * Get the first user-interaction x,y coordinates relative to a given container element.
+ *
+ * @param {Node} container - A DOM container node to get the relative coordinates for.
+ * @returns {Array} An array like <code>[x, y]</code> or <code>undefined</code> if not known.
+ * @preserve
+ */
+sn.tapCoordinates = function(container) {
+ var coordinates;
+ if ( sn.hasTouchSupport ) {
+ coordinates = d3.touches(container);
+ return (coordinates && coordinates.length > 0 ? coordinates[0] : undefined);
+ }
+ return d3.mouse(container);
+}; |
c4fbfd51a6281efa61bfa0cff69ee9d6f3c152a6 | lib/client.js | lib/client.js | var Promise = require('es6-promise').Promise;
module.exports = {
init: function(url) {
createIframe(url)
.then(sendHandshake);
}
};
function createIframe(url) {
var iframe = document.createElement('iframe');
iframe.src = url;
var iframeLoaded = new Promise(function(resolve, reject) {
onIframeLoad(iframe, resolve.bind(null, iframe));
});
document.body.appendChild(iframe);
return iframeLoaded;
}
function onIframeLoad(iframe, callback) {
if (iframe.attachEvent){
iframe.attachEvent('onload', callback);
} else {
iframe.addEventListener('load', callback, false);
}
}
function sendHandshake(iframe) {
send(iframe, 'handshake');
}
function send(iframe, data) {
iframe.contentWindow.postMessage(data);
}
| var Promise = require('es6-promise').Promise;
module.exports = {
init: function(url) {
createIframe(url)
.then(sendHandshake)
.then(undefined, errorHandler);
}
};
function createIframe(url) {
var iframe = document.createElement('iframe');
iframe.src = url;
var iframeLoaded = new Promise(function(resolve, reject) {
try {
onIframeLoad(iframe, resolve.bind(null, iframe));
} catch (ex) {
reject(ex);
}
});
document.body.appendChild(iframe);
return iframeLoaded;
}
function onIframeLoad(iframe, callback) {
if (iframe.attachEvent){
iframe.attachEvent('onload', callback);
} else {
iframe.addEventListener('load', callback, false);
}
}
function sendHandshake(iframe) {
send(iframe, 'handshake');
}
function send(iframe, data) {
iframe.contentWindow.postMessage(data);
}
function errorHandler(error) {
console.error(error.toString());
console.error(error.stack);
}
| Add simple error handling during iframe creation. | Add simple error handling during iframe creation.
| JavaScript | mit | igoratron/iframe-api | ---
+++
@@ -3,7 +3,8 @@
module.exports = {
init: function(url) {
createIframe(url)
- .then(sendHandshake);
+ .then(sendHandshake)
+ .then(undefined, errorHandler);
}
};
@@ -12,7 +13,11 @@
iframe.src = url;
var iframeLoaded = new Promise(function(resolve, reject) {
- onIframeLoad(iframe, resolve.bind(null, iframe));
+ try {
+ onIframeLoad(iframe, resolve.bind(null, iframe));
+ } catch (ex) {
+ reject(ex);
+ }
});
document.body.appendChild(iframe);
@@ -35,3 +40,8 @@
function send(iframe, data) {
iframe.contentWindow.postMessage(data);
}
+
+function errorHandler(error) {
+ console.error(error.toString());
+ console.error(error.stack);
+} |
d31252d2335c1f4a66a27e068fc32c87ed2b52e2 | app/feed/model.js | app/feed/model.js | import Ember from 'ember';
import DS from 'ember-data';
import _ from 'npm:lodash';
var Feed = DS.Model.extend({
onestop_id: Ember.computed.alias('id'),
operators: DS.hasMany('operator', { async: true }),
url: DS.attr('string'),
feed_format: DS.attr('string'),
license_name: DS.attr('string'),
license_url: DS.attr('string'),
license_use_without_attribution: DS.attr('string'),
license_create_derived_product: DS.attr('string'),
license_redistribute: DS.attr('string'),
last_sha1: DS.attr('string'),
last_fetched_at: DS.attr('string'),
last_imported_at: DS.attr('string'),
created_at: DS.attr('date'),
updated_at: DS.attr('date'),
geometry: DS.attr(),
tags: DS.attr(),
addOperator: function(operator) {
this.get('operators').createRecord({
id: operator.onestop_id,
name: operator.name,
website: operator.website,
onestop_id: operator.onestop_id,
timezone: operator.timezone
})
}
});
export default Feed;
| import Ember from 'ember';
import DS from 'ember-data';
import _ from 'npm:lodash';
var Feed = DS.Model.extend({
onestop_id: Ember.computed.alias('id'),
operators: DS.hasMany('operator', { async: true }),
url: DS.attr('string'),
feed_format: DS.attr('string'),
license_name: DS.attr('string'),
license_url: DS.attr('string'),
license_use_without_attribution: DS.attr('string'),
license_create_derived_product: DS.attr('string'),
license_redistribute: DS.attr('string'),
last_sha1: DS.attr('string'),
last_fetched_at: DS.attr('string'),
last_imported_at: DS.attr('string'),
created_at: DS.attr('date'),
updated_at: DS.attr('date'),
geometry: DS.attr(),
tags: DS.attr(),
addOperator: function(operator) {
this.get('operators').createRecord({
id: operator.onestop_id,
name: operator.name,
website: operator.website,
timezone: operator.timezone,
geometry: operator.geometry,
tags: operator.tags
})
}
});
export default Feed;
| Add timezone/geometry/tags to new Operators from Feed | Add timezone/geometry/tags to new Operators from Feed
| JavaScript | mit | transitland/feed-registry,transitland/feed-registry | ---
+++
@@ -24,8 +24,9 @@
id: operator.onestop_id,
name: operator.name,
website: operator.website,
- onestop_id: operator.onestop_id,
- timezone: operator.timezone
+ timezone: operator.timezone,
+ geometry: operator.geometry,
+ tags: operator.tags
})
}
}); |
7382b2af070e4b3210bd378242483058ce5f98f0 | lib/utils.js | lib/utils.js | module.exports.extend = function(constructor, parent) {
constructor.prototype = Object.create(parent.prototype);
constructor.prototype.constructor = constructor;
};
var utils = {};
utils.extend = function(constructor, parent) {
constructor.prototype = Object.create(parent.prototype);
constructor.prototype.constructor = constructor;
};
utils.toRadians = function(degrees) {
return degrees * Math.PI / 180;
};
utils.toDegrees = function(radians) {
return radians * 180 / Math.PI;
};
utils.options = function(options, object) {
options = options || {};
if (options.value !== undefined) {
throw new TypeError('Could not create options object.');
}
options.value = function (name, value) {
if (options[name] === undefined) {
if (object) {
object[name] = value;
}
return value;
}
if (object) {
object[name] = options[name];
}
return options[name];
};
return options;
};
module.exports.Utils = utils; | module.exports.extend = function(constructor, parent) {
constructor.prototype = Object.create(parent.prototype);
constructor.prototype.constructor = constructor;
};
var utils = {};
utils.extend = function(constructor, parent) {
constructor.prototype = Object.create(parent.prototype);
constructor.prototype.constructor = constructor;
};
utils.toRadians = function(degrees) {
return degrees * Math.PI / 180;
};
utils.toDegrees = function(radians) {
return radians * 180 / Math.PI;
};
utils.options = function(options, object) {
if (typeof options !== 'object') {
options = {};
}
if (options.value !== undefined) {
throw new TypeError('Could not create options object.');
}
options.value = function (name, value) {
if (options[name] === undefined) {
if (object) {
object[name] = value;
}
return value;
}
if (object) {
object[name] = options[name];
}
return options[name];
};
return options;
};
module.exports.Utils = utils; | Make sure options is an object. | Make sure options is an object.
| JavaScript | mit | jnsmalm/jsplay,jnsmalm/jsplay | ---
+++
@@ -19,7 +19,9 @@
};
utils.options = function(options, object) {
- options = options || {};
+ if (typeof options !== 'object') {
+ options = {};
+ }
if (options.value !== undefined) {
throw new TypeError('Could not create options object.');
} |
6631e9734e40a90df936cf0778bbe3c407878f1e | src/fetch/auth.js | src/fetch/auth.js | export function signUp(name, email, password) {
return fetch('/api/user', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ name, email, password })
})
.then(response => response);
}
export function authenticate(email, password) {
return fetch('/api/authenticate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'WWW-Authenticate': 'Bearer'
},
body: JSON.stringify({ email, password })
})
.then(response => response);
}
| export function signUp(name, email, password) {
return fetch('/api/users', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ name, email, password })
})
.then(response => response);
}
export function authenticate(email, password) {
return fetch('/api/authenticate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'WWW-Authenticate': 'Bearer'
},
body: JSON.stringify({ email, password })
})
.then(response => response);
}
| Use plurals in API resource URIs | Use plurals in API resource URIs
| JavaScript | mit | orouvinen/mytype-frontend,orouvinen/mytype-frontend | ---
+++
@@ -1,5 +1,5 @@
export function signUp(name, email, password) {
- return fetch('/api/user', {
+ return fetch('/api/users', {
method: 'POST',
headers: {
'Accept': 'application/json', |
9f45ec003be871fc1f79264eb2936638baba76d8 | infernoshoutmod.user.js | infernoshoutmod.user.js | // ==UserScript==
// @name InfernoShoutMod Dev
// @namespace http://rune-server.org/
// @include *.rune-server.org/forum.php
// @include *.rune-server.org/infernoshout.php?do=detach
// @version 1
// ==/UserScript==
var scriptNode = document.createElement("script");
scriptNode.setAttribute("type", "text/javascript");
scriptNode.setAttribute("src", "http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.min.js");
scriptNode.setAttribute("data-main", "http://nikkii.us/sbmod/loader.js");
scriptNode.setAttribute("async", true);
document.getElementsByTagName("head")[0].appendChild(scriptNode); | // ==UserScript==
// @name InfernoShoutMod Dev
// @namespace http://rune-server.org/
// @include *.rune-server.org/forum.php
// @include *.rune-server.org/infernoshout.php?do=detach
// @version 1.1
// ==/UserScript==
var scriptNode = document.createElement("script");
scriptNode.setAttribute("type", "text/javascript");
scriptNode.setAttribute("src", "https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.min.js");
scriptNode.setAttribute("data-main", "https://nikkii.us/sbmod/loader.js");
scriptNode.setAttribute("async", true);
document.getElementsByTagName("head")[0].appendChild(scriptNode);
| Update the loader to use SSL | Update the loader to use SSL
Update the loader to use SSL | JavaScript | isc | nikkiii/infernoshoutmod,nikkiii/infernoshoutmod | ---
+++
@@ -3,12 +3,12 @@
// @namespace http://rune-server.org/
// @include *.rune-server.org/forum.php
// @include *.rune-server.org/infernoshout.php?do=detach
-// @version 1
+// @version 1.1
// ==/UserScript==
var scriptNode = document.createElement("script");
scriptNode.setAttribute("type", "text/javascript");
-scriptNode.setAttribute("src", "http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.min.js");
-scriptNode.setAttribute("data-main", "http://nikkii.us/sbmod/loader.js");
+scriptNode.setAttribute("src", "https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.min.js");
+scriptNode.setAttribute("data-main", "https://nikkii.us/sbmod/loader.js");
scriptNode.setAttribute("async", true);
document.getElementsByTagName("head")[0].appendChild(scriptNode); |
1ca4cbf376d39c152cb6b2680f777985bd03cea3 | input/utils/fieldset.js | input/utils/fieldset.js | 'use strict';
var Db = require('../');
module.exports = Db;
require('./row');
Db.prototype.set('toDOMFieldset', function (document/*, options*/) {
var options = Object(arguments[1]), names, container, rows, body;
if (options.names != null) names = options.names;
else names = this.getPropertyNames(options.tag);
rows = Array.prototype.map.call(names, function (name) {
var rel = this['_' + name];
return (rel.ns === this.db.Base) ? null : rel;
}, this).filter(Boolean).sort(function (relA, relB) {
return relA.order - relB.order;
}).map(function (rel) {
return rel.toDOMInputRow(document, options.control);
});
if (!rows.length) return null;
container = document.createElement('fieldset');
container.setAttribute('class', 'dbjs');
body = container.appendChild(document.createElement('table'))
.appendChild(document.createElement('tbody'));
rows.forEach(body.appendChild, body);
return container;
});
| 'use strict';
var Db = require('../');
module.exports = Db;
require('./row');
Db.prototype.set('toDOMFieldset', function (document/*, options*/) {
var options = Object(arguments[1]), names, container, rows, body;
if (options.names != null) names = options.names;
else names = this.getPropertyNames(options.tag);
rows = Array.prototype.map.call(names, function (name) {
var rel = this['_' + name];
return (rel.ns === this.db.Base) ? null : rel;
}, this).filter(Boolean).sort(function (relA, relB) {
return relA.order - relB.order;
}).map(function (rel) {
var controlOpts;
if (options.control) controlOpts = this.plainCopy(options.control);
if (options.controls && options.controls[rel.name]) {
controlOpts = this.plainExtend(Object(controlOpts),
options.controls[rel.name]);
}
return rel.toDOMInputRow(document, controlOpts);
}, this.db);
if (!rows.length) return null;
container = document.createElement('fieldset');
container.setAttribute('class', 'dbjs');
body = container.appendChild(document.createElement('table'))
.appendChild(document.createElement('tbody'));
rows.forEach(body.appendChild, body);
return container;
});
| Support custom options for each field | Support custom options for each field
| JavaScript | mit | medikoo/dbjs-dom | ---
+++
@@ -18,8 +18,14 @@
}, this).filter(Boolean).sort(function (relA, relB) {
return relA.order - relB.order;
}).map(function (rel) {
- return rel.toDOMInputRow(document, options.control);
- });
+ var controlOpts;
+ if (options.control) controlOpts = this.plainCopy(options.control);
+ if (options.controls && options.controls[rel.name]) {
+ controlOpts = this.plainExtend(Object(controlOpts),
+ options.controls[rel.name]);
+ }
+ return rel.toDOMInputRow(document, controlOpts);
+ }, this.db);
if (!rows.length) return null;
|
2c5954d3964bbab33cb381037604d37db7bf4f6b | gatsby-node.js | gatsby-node.js | const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
module.exports.onCreateWebpackConfig = ({ actions, stage }, { logo, icons = {}, title, background }) => {
if (stage === 'develop-html' || stage === 'build-html') {
const prefix = __PATH_PREFIX__ ? __PATH_PREFIX__ : '';
actions.setWebpackConfig({
plugins: [
new FaviconsWebpackPlugin({
logo: logo || './src/favicon.png',
title,
background: background || '#fff',
inject: false,
emitStats: true,
statsFilename: '.iconstats.json',
publicPath: prefix,
icons: {
android: true,
appleIcon: true,
appleStartup: true,
coast: false,
favicons: true,
firefox: true,
opengraph: false,
twitter: false,
yandex: false,
windows: false,
...icons,
},
}),
],
});
}
};
| const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
module.exports.onCreateWebpackConfig = ({ actions, stage, getConfig }, { logo, icons = {}, title, background }) => {
if (stage === 'develop-html' || stage === 'build-html') {
actions.setWebpackConfig({
plugins: [
new FaviconsWebpackPlugin({
logo: logo || './src/favicon.png',
title,
background: background || '#fff',
inject: false,
emitStats: true,
statsFilename: '.iconstats.json',
publicPath: getConfig().output.publicPath,
icons: {
android: true,
appleIcon: true,
appleStartup: true,
coast: false,
favicons: true,
firefox: true,
opengraph: false,
twitter: false,
yandex: false,
windows: false,
...icons,
},
}),
],
});
}
};
| Use webpack config to set publicPath | Use webpack config to set publicPath
| JavaScript | mit | Creatiwity/gatsby-plugin-favicon | ---
+++
@@ -1,9 +1,7 @@
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
-module.exports.onCreateWebpackConfig = ({ actions, stage }, { logo, icons = {}, title, background }) => {
+module.exports.onCreateWebpackConfig = ({ actions, stage, getConfig }, { logo, icons = {}, title, background }) => {
if (stage === 'develop-html' || stage === 'build-html') {
- const prefix = __PATH_PREFIX__ ? __PATH_PREFIX__ : '';
-
actions.setWebpackConfig({
plugins: [
new FaviconsWebpackPlugin({
@@ -13,7 +11,7 @@
inject: false,
emitStats: true,
statsFilename: '.iconstats.json',
- publicPath: prefix,
+ publicPath: getConfig().output.publicPath,
icons: {
android: true,
appleIcon: true, |
d4bad6943f16db6d651725dd39df7974549cf245 | js/injector.js | js/injector.js | /////////////////////////////////
// Dropbox injection functions //
/////////////////////////////////
Dropbox.appKey = "8oj6dw6o6urk6wn";
function addDropboxScriptTag() {
$("head").append('<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="8oj6dw6o6urk6wn"></script>');
}
function addDropboxButton() {
var options = {
success: function () {
console.log("File saved to Dropbox");
},
error: function (errorMessage) {
console.log(errorMessage);
}
};
var temp = "https://mycourses.rit.edu/d2l/le/content/" +
"585427" +
"/topics/files/download/" +
"3815682" +
"/DirectFileTopicDownload";
var button = Dropbox.createSaveButton(temp, getFileName(), options);
$("div[class^=d2l_1] > div.d2l-left").append(button);
} | /////////////////////////////////
// Dropbox injection functions //
/////////////////////////////////
Dropbox.appKey = "8oj6dw6o6urk6wn";
function addDropboxScriptTag() {
$("head").append('<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="8oj6dw6o6urk6wn"></script>');
}
function addDropboxButton() {
var options = {
success: function () {
console.log("File saved to Dropbox");
},
error: function (errorMessage) {
console.log(errorMessage);
}
};
var button = Dropbox.createSaveButton(getDownloadLink(), getFileName(), options);
$("div[class^=d2l_1] > div.d2l-left").append(button);
} | Remove temp download link format that doesn't work | Remove temp download link format that doesn't work
| JavaScript | mit | Speenah/rit-mycourses-file-downloader | ---
+++
@@ -17,11 +17,7 @@
console.log(errorMessage);
}
};
- var temp = "https://mycourses.rit.edu/d2l/le/content/" +
- "585427" +
- "/topics/files/download/" +
- "3815682" +
- "/DirectFileTopicDownload";
- var button = Dropbox.createSaveButton(temp, getFileName(), options);
+
+ var button = Dropbox.createSaveButton(getDownloadLink(), getFileName(), options);
$("div[class^=d2l_1] > div.d2l-left").append(button);
} |
ee7d89a16ccea59a675a7ba1afbf5707a4521f3b | src/kata.js | src/kata.js | const rawPathToEs6KataLink = (path) => {
return `http://tddbin.com/#?kata=es6/language/${path}`;
};
export default class Kata {
static fromRawItem(rawItem) {
let kata = new Kata();
kata.initializePropertiesFromRawItem(rawItem);
kata.url = rawPathToEs6KataLink(rawItem.path);
kata.id = parseInt(kata.id);
return kata;
}
initializePropertiesFromRawItem(rawItem) {
const allRawKeys = Object.keys(rawItem);
allRawKeys.forEach(key => this[key] = rawItem[key]);
}
} | const rawPathToEs6KataLink = (path) => {
return `http://tddbin.com/#?kata=es6/language/${path}`;
};
export default class Kata {
static fromRawItem(rawItem) {
let kata = new Kata();
kata.initializePropertiesFromRawItem(rawItem);
kata.url = rawPathToEs6KataLink(rawItem.path);
kata.id = Number.parseInt(kata.id);
return kata;
}
initializePropertiesFromRawItem(rawItem) {
const allRawKeys = Object.keys(rawItem);
allRawKeys.forEach(key => this[key] = rawItem[key]);
}
}
| Use the ES6 parseInt, which is in the Number namespace now. | Use the ES6 parseInt, which is in the Number namespace now.
| JavaScript | mit | tddbin/es6katas.org | ---
+++
@@ -8,7 +8,7 @@
let kata = new Kata();
kata.initializePropertiesFromRawItem(rawItem);
kata.url = rawPathToEs6KataLink(rawItem.path);
- kata.id = parseInt(kata.id);
+ kata.id = Number.parseInt(kata.id);
return kata;
}
|
694ae32b7f74402bddd4d14e8f2b492776e6c66b | assets/js/profile-index.js | assets/js/profile-index.js | ---
---
$(document).ready(function() {
'use strict';
// Navbar
// =======================================================
const header = $('.header');
const navbar = $('.navbar-profile');
const range = 64; // Height of navbar
$(window).on('scroll', function() {
let scrollTop = $(this).scrollTop();
let height = header.outerHeight();
let offset = height / 2;
let calc = 1 - (scrollTop - offset + range) / range;
header.css({ 'opacity': calc });
if (calc > '1') {
header.css({ 'opacity': 1 });
navbar.addClass('affix-top');
navbar.removeClass('affix');
} else if ( calc < '0' ) {
header.css({ 'opacity': 0 });
navbar.addClass('affix');
navbar.removeClass('affix-top');
}
});
// Materialize components
// =======================================================
window.onload = function() {
$('.tooltipped:not(.v-tooltipped)').tooltip(); // :not ensures Vue handles relevant initiation for Vue-controlled elements
$('.collapsible').collapsible({
'accordion': false,
});
};
});
| ---
---
$(document).ready(function() {
'use strict';
// Navbar
// =======================================================
const header = $('.header');
const navbar = $('.navbar-profile');
const range = 64; // Height of navbar
$(window).on('scroll', function() {
let scrollTop = $(this).scrollTop();
let height = header.outerHeight();
let offset = height / 2;
let calc = 1 - (scrollTop - offset + range) / range;
header.css({ 'opacity': calc });
if (calc > '1') {
header.css({ 'opacity': 1 });
navbar.addClass('affix-top');
navbar.removeClass('affix');
} else if ( calc < '0' ) {
header.css({ 'opacity': 0 });
navbar.addClass('affix');
navbar.removeClass('affix-top');
}
});
// Materialize components
// =======================================================
window.onload = function() {
$('.sidenav').sidenav();
$('.tooltipped:not(.v-tooltipped)').tooltip(); // :not ensures Vue handles relevant initiation for Vue-controlled elements
$('.collapsible').collapsible({
'accordion': false,
});
};
});
| Fix sidenav on full-index page | Fix sidenav on full-index page
| JavaScript | mit | grantmakers/profiles,grantmakers/profiles,grantmakers/profiles | ---
+++
@@ -31,6 +31,7 @@
// Materialize components
// =======================================================
window.onload = function() {
+ $('.sidenav').sidenav();
$('.tooltipped:not(.v-tooltipped)').tooltip(); // :not ensures Vue handles relevant initiation for Vue-controlled elements
$('.collapsible').collapsible({
'accordion': false, |
503fc48217ebb38e8d69d858a7e51aa953929225 | tests/integration/_testHelpers/setupTeardown.js | tests/integration/_testHelpers/setupTeardown.js | let serverless
export async function setup(options) {
const { servicePath } = options
if (RUN_TEST_AGAINST_AWS) {
return
}
// require lazy, AWS tests will execute faster
const { default: Serverless } = await import('serverless')
const { argv } = process
// just areally hacky way to pass options
process.argv = [
'', // '/bin/node',
'', // '/serverless-offline/node_modules/.bin/serverless',
'offline',
'start',
'--webpack-no-watch',
]
serverless = new Serverless({ servicePath })
await serverless.init()
await serverless.run()
// set to original
process.argv = argv
}
export async function teardown() {
if (RUN_TEST_AGAINST_AWS) {
return
}
const { plugins } = serverless.pluginManager
const serverlessOffline = plugins.find(
(item) => item.constructor.name === 'ServerlessOffline',
)
const serverlessWebpack = plugins.find(
(item) => item.constructor.name === 'ServerlessWebpack',
)
if (serverlessWebpack) {
await serverlessWebpack.cleanup()
}
await serverlessOffline.end(true)
}
| const { node } = require('execa')
const { resolve } = require('path')
let serverlessProcess
const serverlessPath = resolve(
__dirname,
'../../../node_modules/serverless/bin/serverless',
)
export async function setup(options) {
const { servicePath } = options
if (RUN_TEST_AGAINST_AWS) {
return
}
serverlessProcess = node(serverlessPath, ['offline', 'start'], {
cwd: servicePath,
})
await new Promise((res) => {
serverlessProcess.stdout.on('data', (data) => {
if (String(data).includes('[HTTP] server ready')) {
res()
}
})
})
}
export async function teardown() {
if (RUN_TEST_AGAINST_AWS) {
return
}
serverlessProcess.cancel()
await serverlessProcess
}
| Rewrite plugin instantiation for integration tests | Rewrite plugin instantiation for integration tests
| JavaScript | mit | dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline | ---
+++
@@ -1,4 +1,12 @@
-let serverless
+const { node } = require('execa')
+const { resolve } = require('path')
+
+let serverlessProcess
+
+const serverlessPath = resolve(
+ __dirname,
+ '../../../node_modules/serverless/bin/serverless',
+)
export async function setup(options) {
const { servicePath } = options
@@ -7,27 +15,17 @@
return
}
- // require lazy, AWS tests will execute faster
- const { default: Serverless } = await import('serverless')
+ serverlessProcess = node(serverlessPath, ['offline', 'start'], {
+ cwd: servicePath,
+ })
- const { argv } = process
-
- // just areally hacky way to pass options
- process.argv = [
- '', // '/bin/node',
- '', // '/serverless-offline/node_modules/.bin/serverless',
- 'offline',
- 'start',
- '--webpack-no-watch',
- ]
-
- serverless = new Serverless({ servicePath })
-
- await serverless.init()
- await serverless.run()
-
- // set to original
- process.argv = argv
+ await new Promise((res) => {
+ serverlessProcess.stdout.on('data', (data) => {
+ if (String(data).includes('[HTTP] server ready')) {
+ res()
+ }
+ })
+ })
}
export async function teardown() {
@@ -35,19 +33,7 @@
return
}
- const { plugins } = serverless.pluginManager
+ serverlessProcess.cancel()
- const serverlessOffline = plugins.find(
- (item) => item.constructor.name === 'ServerlessOffline',
- )
-
- const serverlessWebpack = plugins.find(
- (item) => item.constructor.name === 'ServerlessWebpack',
- )
-
- if (serverlessWebpack) {
- await serverlessWebpack.cleanup()
- }
-
- await serverlessOffline.end(true)
+ await serverlessProcess
} |
23438dd73bce70df44dde2874113ce8961505acd | src/main.js | src/main.js | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-native-router-flux';
import setup from './store/setup';
import scenes from './scenes';
global.isDebuggingInChrome = __DEV__ && !!window.navigator.userAgent;
function bootstrap() {
// Setup any services here... e.g. Parse, Facebook SDK etc
class Root extends Component {
constructor() {
super();
this.state = {
isLoading: true,
store: null,
};
}
componentWillMount() {
setup(store => {
this.setState({
isLoading: false,
store,
});
});
}
render() {
if (this.state.isLoading) {
// TODO Render splash screen whilst store is bootstrapping
return null;
}
return (
<Provider store={this.state.store}>
<Router scenes={scenes} />
</Provider>
);
}
}
return Root;
}
export default bootstrap();
| import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-native-router-flux';
import setup from './store/setup';
import scenes from './scenes';
global.isDebuggingInChrome = __DEV__ && !!window.navigator.userAgent;
function bootstrap() {
// Setup any services here... e.g. Parse, Facebook SDK etc
class Root extends Component {
constructor() {
super();
this.state = {
isLoading: true,
store: null,
};
}
componentDidMount() {
setup(store => {
this.setState({
isLoading: false,
store,
});
});
}
render() {
if (this.state.isLoading) {
// TODO Render splash screen whilst store is bootstrapping
return null;
}
return (
<Provider store={this.state.store}>
<Router scenes={scenes} />
</Provider>
);
}
}
return Root;
}
export default bootstrap();
| Use componentDidMount over willMount in boostrap | Use componentDidMount over willMount in boostrap
| JavaScript | mit | teamfa/react-native-starter-app,teamfa/react-native-starter-app,teamfa/react-native-starter-app | ---
+++
@@ -19,7 +19,7 @@
};
}
- componentWillMount() {
+ componentDidMount() {
setup(store => {
this.setState({
isLoading: false, |
a57f7e9e4e64740c5207d691c5cfb4d62df9381a | app.js | app.js | require('dotenv').config();
var path = require('path');
var express = require('express');
var passport = require('passport');
var authRouter = require('./routes/auth');
// Create a new Express application.
var app = express();
require('./boot/auth')();
// Configure view engine to render EJS templates.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());
// Define routes.
app.get('/',
function(req, res) {
res.render('home', { user: req.user });
});
app.use('/', authRouter);
app.get('/profile',
require('connect-ensure-login').ensureLoggedIn(),
function(req, res){
res.render('profile', { user: req.user });
});
module.exports = app;
| require('dotenv').config();
var express = require('express');
var passport = require('passport');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var authRouter = require('./routes/auth');
var app = express();
require('./boot/auth')();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// session setup
//
// This sequence of middleware is necessary for login sessions. The first
// middleware loads session data and makes it available at `req.session`. The
// next lines initialize Passport and authenticate the request based on session
// data. If session data contains an authenticated user, the user is set at
// `req.user`.
app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
// Define routes.
app.get('/',
function(req, res) {
res.render('home', { user: req.user });
});
app.use('/', authRouter);
app.get('/profile',
require('connect-ensure-login').ensureLoggedIn(),
function(req, res){
res.render('profile', { user: req.user });
});
module.exports = app;
| Use middleware as generated by express-generator. | Use middleware as generated by express-generator.
| JavaScript | unlicense | passport/express-4.x-facebook-example,passport/express-4.x-facebook-example | ---
+++
@@ -1,31 +1,34 @@
require('dotenv').config();
-var path = require('path');
var express = require('express');
var passport = require('passport');
+var path = require('path');
+var cookieParser = require('cookie-parser');
+var logger = require('morgan');
var authRouter = require('./routes/auth');
-
-// Create a new Express application.
var app = express();
require('./boot/auth')();
-// Configure view engine to render EJS templates.
-app.set('views', __dirname + '/views');
+// view engine setup
+app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
-// Use application-level middleware for common functionality, including
-// logging, parsing, and session handling.
-app.use(require('morgan')('combined'));
+app.use(logger('dev'));
+app.use(express.json());
+app.use(express.urlencoded({ extended: false }));
+app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
-app.use(require('cookie-parser')());
-app.use(require('body-parser').urlencoded({ extended: true }));
-app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
-
-// Initialize Passport and restore authentication state, if any, from the
-// session.
+// session setup
+//
+// This sequence of middleware is necessary for login sessions. The first
+// middleware loads session data and makes it available at `req.session`. The
+// next lines initialize Passport and authenticate the request based on session
+// data. If session data contains an authenticated user, the user is set at
+// `req.user`.
+app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
|
bf6bf26788ca5b1aa9af01fa647aca883766af0f | server/sessions/sessionsController.js | server/sessions/sessionsController.js | var helpers = require( '../config/helpers' );
var Session = require( './sessions' );
module.exports = {
getAllSessions: function( reqw, res, next ) {
Session.findAll()
.then( function( sessions ) {
response.send( sessions );
})
},
addSession: function( req, res, next ) {
var sessionName = request.body.sessionName;
Session.create( {
sessionName: sessionName
} ).then( function() {
response.status = 201;
response.end();
} )
},
getSessionByName: function( req, res, next ) {
var sessionName = request.params.sessionName;
Session.findOne( { where: { sessionName: sessionName } } )
.then( function( session ) {
response.json( session );
}, function( err ) {
helpers.errorHandler( err, request, response, next );
});
}
};
| var helpers = require( '../config/helpers' );
var Session = require( './sessions' );
module.exports = {
getAllSessions: function( reqw, res, next ) {
Session.findAll()
.then( function( sessions ) {
res.send( sessions );
})
},
addSession: function( req, res, next ) {
var sessionName = req.body.sessionName;
Session.create( {
sessionName: sessionName
} ).then( function() {
res.status = 201;
res.end();
} )
},
getSessionByName: function( req, res, next ) {
var sessionName = req.params.sessionName;
Session.findOne( { where: { sessionName: sessionName } } )
.then( function( session ) {
res.json( session );
}, function( err ) {
helpers.errorHandler( err, req, res, next );
});
}
};
| Refactor to use shorthand req res | Refactor to use shorthand req res
| JavaScript | mpl-2.0 | RubiginousChanticleer/rubiginouschanticleer,CantillatingZygote/rubiginouschanticleer,CantillatingZygote/rubiginouschanticleer,RubiginousChanticleer/rubiginouschanticleer | ---
+++
@@ -6,29 +6,29 @@
getAllSessions: function( reqw, res, next ) {
Session.findAll()
.then( function( sessions ) {
- response.send( sessions );
+ res.send( sessions );
})
},
addSession: function( req, res, next ) {
- var sessionName = request.body.sessionName;
+ var sessionName = req.body.sessionName;
Session.create( {
sessionName: sessionName
} ).then( function() {
- response.status = 201;
- response.end();
+ res.status = 201;
+ res.end();
} )
},
getSessionByName: function( req, res, next ) {
- var sessionName = request.params.sessionName;
+ var sessionName = req.params.sessionName;
Session.findOne( { where: { sessionName: sessionName } } )
.then( function( session ) {
- response.json( session );
+ res.json( session );
}, function( err ) {
- helpers.errorHandler( err, request, response, next );
+ helpers.errorHandler( err, req, res, next );
});
}
|
f90e02e8e62807d1b22698ec57fcb08281e33834 | lib/command/utils.js | lib/command/utils.js | 'use strict';
let fileExists = require('../utils').fileExists;
let output = require("../output");
let fs = require('fs');
let path = require('path');
let colors = require('colors');
module.exports.getTestRoot = function (currentPath) {
let testsPath = path.join(process.cwd(), currentPath || '.');
if (!currentPath) {
output.print(`Test root is assumed to be ${colors.yellow.bold(testsPath)}`);
} else {
output.print(`Using test root ${colors.bold(testsPath)}`);
}
return testsPath;
};
module.exports.getConfig = function (testsPath) {
let configFile = path.join(testsPath, 'codecept.json');
if (!fileExists(configFile)) {
output.error(`Can not load config from ${configFile}\nCodeceptJS is not initialized in this dir. Execute 'codeceptjs init' to start`);
process.exit(1);
}
let config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
if (!config.include) config.include = {};
if (!config.helpers) config.helpers = {};
return config;
};
| 'use strict';
let fileExists = require('../utils').fileExists;
let output = require("../output");
let fs = require('fs');
let path = require('path');
let colors = require('colors');
module.exports.getTestRoot = function (currentPath) {
let testsPath = path.resolve(currentPath || '.');
if (!currentPath) {
output.print(`Test root is assumed to be ${colors.yellow.bold(testsPath)}`);
} else {
output.print(`Using test root ${colors.bold(testsPath)}`);
}
return testsPath;
};
module.exports.getConfig = function (testsPath) {
let configFile = path.join(testsPath, 'codecept.json');
if (!fileExists(configFile)) {
output.error(`Can not load config from ${configFile}\nCodeceptJS is not initialized in this dir. Execute 'codeceptjs init' to start`);
process.exit(1);
}
let config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
if (!config.include) config.include = {};
if (!config.helpers) config.helpers = {};
return config;
};
| Fix path resolution on the command line to support absolute paths | Fix path resolution on the command line to support absolute paths
Before the change, I could not `codecept run /my/absolute/path`.
`path.join` would always stick the current working directory in front.
More proper path resolution is also simpler, as `path.resolve` will stick
the current working directory if the path is not already absolute. | JavaScript | mit | Codeception/CodeceptJS,Codeception/CodeceptJS,Codeception/CodeceptJS,Shullaca1/Teste-do-CdB,williammizuta/CodeceptJS,williammizuta/CodeceptJS,Nighthawk14/CodeceptJS,Nighthawk14/CodeceptJS,Shullaca1/Teste-do-CdB,williammizuta/CodeceptJS,Shullaca1/Teste-do-CdB | ---
+++
@@ -6,7 +6,7 @@
let colors = require('colors');
module.exports.getTestRoot = function (currentPath) {
- let testsPath = path.join(process.cwd(), currentPath || '.');
+ let testsPath = path.resolve(currentPath || '.');
if (!currentPath) {
output.print(`Test root is assumed to be ${colors.yellow.bold(testsPath)}`); |
7e38fce931f119035c611825a4c923a59b5a43f9 | lib/flash-message.js | lib/flash-message.js | App.FlashMessage = Ember.Object.extend({
type: 'notice',
dismissable: true,
message: null,
isNotice: function(){
return this.get('type') == 'notice';
}.property('type'),
isWarning: function(){
return this.get('type') == 'warning';
}.property('type'),
isAlert: function(){
return this.get('type') == 'alert';
}.property('type'),
isInfo: function(){
return this.get('type') == 'info';
}.property('type')
});
| App.FlashMessage = Ember.Object.extend({
type: 'notice',
message: null,
dismissable: true,
isInfo: Ember.computed.equal('type', 'info'),
isAlert: Ember.computed.equal('type', 'alert'),
isNotice: Ember.computed.equal('type', 'notice'),
isWarning: Ember.computed.equal('type', 'warning')
});
| Use computed properties instead of manually checking equality | Use computed properties instead of manually checking equality
| JavaScript | mit | aackerman/ember-flash-queue | ---
+++
@@ -1,21 +1,9 @@
App.FlashMessage = Ember.Object.extend({
- type: 'notice',
+ type: 'notice',
+ message: null,
dismissable: true,
- message: null,
-
- isNotice: function(){
- return this.get('type') == 'notice';
- }.property('type'),
-
- isWarning: function(){
- return this.get('type') == 'warning';
- }.property('type'),
-
- isAlert: function(){
- return this.get('type') == 'alert';
- }.property('type'),
-
- isInfo: function(){
- return this.get('type') == 'info';
- }.property('type')
+ isInfo: Ember.computed.equal('type', 'info'),
+ isAlert: Ember.computed.equal('type', 'alert'),
+ isNotice: Ember.computed.equal('type', 'notice'),
+ isWarning: Ember.computed.equal('type', 'warning')
}); |
3e5afa07ed9d94a1c607c0dff8355c157d6cded1 | karma-unit.conf.js | karma-unit.conf.js | module.exports = function(config) {
config.set({
basePath: '',
files: [
'vendor/angular/angular.js',
'vendor/angular-animate/angular-animate.js',
'vendor/angular-mocks/angular-mocks.js',
'dist/*.template.js',
'src/**/*.js'
],
exclude: [
],
frameworks: ['jasmine'],
browsers: ['Chrome'],
preprocessors: {},
reporters: ['dots'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false
});
};
| module.exports = function(config) {
config.set({
basePath: '',
files: [
'vendor/angular/angular.js',
'vendor/angular-animate/angular-animate.js',
'vendor/angular-mocks/angular-mocks.js',
'vendor/angular-progress-arc/angular-progress-arc.js',
'dist/*.template.js',
'src/**/*.module.js',
'src/**/!(*module).js'
],
exclude: [
],
frameworks: ['jasmine'],
browsers: ['Chrome'],
preprocessors: {},
reporters: ['dots'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false
});
};
| Make sure `module` files are loaded first. | chore(karma): Make sure `module` files are loaded first.
| JavaScript | mit | sebald/ed,mps-gmbh/ed,sebald/ed,mps-gmbh/ed,mps-gmbh/ed,sebald/ed | ---
+++
@@ -7,8 +7,10 @@
'vendor/angular/angular.js',
'vendor/angular-animate/angular-animate.js',
'vendor/angular-mocks/angular-mocks.js',
+ 'vendor/angular-progress-arc/angular-progress-arc.js',
'dist/*.template.js',
- 'src/**/*.js'
+ 'src/**/*.module.js',
+ 'src/**/!(*module).js'
],
exclude: [
], |
db90a78b8cc5fc0f30e2ae88ff58165ea8714d4f | lib/number.js | lib/number.js | 'use strict';
function hasTypeNumber(numberToCheck) {
return typeof numberToCheck === 'number';
}
module.exports = {
isNumeric: function isNumeric(numberToCheck) {
if(!hasTypeNumber(numberToCheck)) {
return false;
}
return (numberToCheck - parseFloat(numberToCheck) + 1) >= 0;
},
isInt: function isInt(numberToCheck) {
if(!hasTypeNumber(numberToCheck)) {
return false;
}
return parseInt(numberToCheck) === numberToCheck;
},
isFloat: function isInt(numberToCheck) {
if(!hasTypeNumber(numberToCheck) || isNaN(numberToCheck)) {
return false;
}
return !module.exports.isInt(numberToCheck);
}
};
| 'use strict';
function hasTypeNumber(numberToCheck) {
return typeof numberToCheck === 'number';
}
module.exports = {
isNumeric: function isNumeric(numberToCheck) {
if(!hasTypeNumber(numberToCheck) || isNaN(numberToCheck)) {
return false;
}
return (numberToCheck - parseFloat(numberToCheck) + 1) >= 0;
},
isInt: function isInt(numberToCheck) {
if(!hasTypeNumber(numberToCheck) || isNaN(numberToCheck)) {
return false;
}
return parseInt(numberToCheck) === numberToCheck;
},
isFloat: function isInt(numberToCheck) {
if(!hasTypeNumber(numberToCheck) || isNaN(numberToCheck)) {
return false;
}
return !module.exports.isInt(numberToCheck);
}
};
| Add additional isNaN check for check methods. | Add additional isNaN check for check methods.
| JavaScript | mit | lxanders/belt | ---
+++
@@ -7,7 +7,7 @@
module.exports = {
isNumeric: function isNumeric(numberToCheck) {
- if(!hasTypeNumber(numberToCheck)) {
+ if(!hasTypeNumber(numberToCheck) || isNaN(numberToCheck)) {
return false;
}
@@ -15,7 +15,7 @@
},
isInt: function isInt(numberToCheck) {
- if(!hasTypeNumber(numberToCheck)) {
+ if(!hasTypeNumber(numberToCheck) || isNaN(numberToCheck)) {
return false;
}
|
8ce1c294cfc87ba18d743cf14801843cc112a0b4 | app/actions/item-actions.js | app/actions/item-actions.js | import AppDispatcher from '../dispatchers/app-dispatcher';
import {products} from '../lib/sprintly-client';
let ItemActions = {
addItem(productId, data) {
let product = products.get(productId);
if (!product) {
throw new Error('Missing product: %s', productId);
}
data.product = product.toJSON();
let item = product.createItem(data, { silent: true });
return item.save().then(function() {
let col = product.getItemsByStatus(item.status);
if (col) {
col.add(item);
}
});
}
};
export default ItemActions;
| import AppDispatcher from '../dispatchers/app-dispatcher';
import {products} from '../lib/sprintly-client';
import Promise from 'bluebird';
let ItemActions = {
addItem(productId, data) {
let product = products.get(productId);
if (!product) {
throw new Error('Missing product: %s', productId);
}
data.product = product.toJSON();
let item = product.createItem(data, { silent: true });
let saved = item.save();
if (saved) {
return saved.then(function() {
let col = product.getItemsByStatus(item.status);
if (col) {
col.add(item);
}
});
} else {
return new Promise(function(resolve) {
resolve(item)
});
}
}
};
export default ItemActions;
| Return a promise from a failed item save | Return a promise from a failed item save | JavaScript | isc | jeffreymoya/sprintly-kanban,whitebird08/sprintly-kanban,sprintly/sprintly-kanban,pipermerriam/sprintly-kanban,florapdx/sprintly-kanban,florapdx/sprintly-kanban,sprintly/sprintly-kanban,datachand/sprintly-kanban,whitebird08/sprintly-kanban,datachand/sprintly-kanban,pipermerriam/sprintly-kanban,jeffreymoya/sprintly-kanban | ---
+++
@@ -1,5 +1,6 @@
import AppDispatcher from '../dispatchers/app-dispatcher';
import {products} from '../lib/sprintly-client';
+import Promise from 'bluebird';
let ItemActions = {
addItem(productId, data) {
@@ -10,15 +11,24 @@
}
data.product = product.toJSON();
+ let item = product.createItem(data, { silent: true });
+ let saved = item.save();
- let item = product.createItem(data, { silent: true });
- return item.save().then(function() {
- let col = product.getItemsByStatus(item.status);
- if (col) {
- col.add(item);
- }
- });
+ if (saved) {
+ return saved.then(function() {
+ let col = product.getItemsByStatus(item.status);
+ if (col) {
+ col.add(item);
+ }
+ });
+ } else {
+ return new Promise(function(resolve) {
+ resolve(item)
+ });
+ }
}
};
export default ItemActions;
+
+ |
b53c220b892f41d431487ab4ad7ff3c7ef92de21 | src/panels/EmptyDetailPanel.js | src/panels/EmptyDetailPanel.js | /**
* Empty panel which is shown when no data object is selected.
* @class
*/
export default class EmptyDetailPanel {
constructor(rootElement, rb) {
this.rootElement = rootElement;
this.rb = rb;
}
render() {
let panel = $('#rbro_detail_panel');
$('#rbro_detail_panel').append(`<div id="rbro_empty_detail_panel" class="rbroEmptyDetailPanel rbroHidden">
<div class="rbroLogo"></div>
</div>`);
}
destroy() {
}
show(data) {
$('#rbro_empty_detail_panel').removeClass('rbroHidden');
}
hide() {
$('#rbro_empty_detail_panel').addClass('rbroHidden');
}
notifyEvent(obj, operation) {
}
updateErrors() {
}
}
| /**
* Empty panel which is shown when no data object is selected.
* @class
*/
export default class EmptyDetailPanel {
constructor(rootElement, rb) {
this.rootElement = rootElement;
this.rb = rb;
}
render() {
let panel = $('#rbro_detail_panel');
$('#rbro_detail_panel').append(`<div id="rbro_empty_detail_panel" class="rbroEmptyDetailPanel rbroHidden">
<div class="rbroLogo"></div>
</div>`);
}
destroy() {
}
show(data) {
$('#rbro_empty_detail_panel').removeClass('rbroHidden');
}
hide() {
$('#rbro_empty_detail_panel').addClass('rbroHidden');
}
isKeyEventDisabled() {
return false;
}
notifyEvent(obj, operation) {
}
updateErrors() {
}
}
| Add missing method for empty panel | Add missing method for empty panel
| JavaScript | agpl-3.0 | jobsta/reportbro-designer | ---
+++
@@ -26,6 +26,10 @@
$('#rbro_empty_detail_panel').addClass('rbroHidden');
}
+ isKeyEventDisabled() {
+ return false;
+ }
+
notifyEvent(obj, operation) {
}
|
6946908ae19972853902e2e0aaf01f35b18731b8 | src/prefabs/datatype_number.js | src/prefabs/datatype_number.js | var BigNumber = require("bignumber.js");
class ErlNumber {
constructor(value) {
this.value = new BigNumber(value);
}
toString() {
return this.value.toString();
}
static isErlNumber(erlnum) {
return erlnum instanceof ErlNumber;
}
static cloneNumber(erlnum) {
return new ErlNumber(erlnum.toString());
}
isUnbound() {
return false;
}
match(value) {
if (!this.value.equals(value)) {
return undefined;
}
return value;
}
}
exports.ErlNumber = ErlNumber;
| var BigNumber = require("bignumber.js");
// Constructor
function ErlNumber(value) {
this.value = new BigNumber(value);
}
// Static Methods
ErlNumber.isErlNumber = function(erlnum) {
return erlnum instanceof ErlNumber;
}
ErlNumber.cloneNumber = function(erlnum) {
return new ErlNumber(erlnum.toString());
}
// Prototype Methods
ErlNumber.prototype.toString = function() {
return this.value.toString();
}
ErlNumber.prototype.isUnbound = function() {
return false;
}
ErlNumber.prototype.match = function(value) {
if (!this.value.equals(value)) {
return undefined;
}
return value;
}
exports.ErlNumber = ErlNumber;
| Change format of ErlNumber class | Change format of ErlNumber class
| JavaScript | mit | Vereis/jarlang,Vereis/jarlang | ---
+++
@@ -1,32 +1,37 @@
var BigNumber = require("bignumber.js");
-class ErlNumber {
- constructor(value) {
- this.value = new BigNumber(value);
- }
- toString() {
- return this.value.toString();
- }
-
- static isErlNumber(erlnum) {
- return erlnum instanceof ErlNumber;
- }
-
- static cloneNumber(erlnum) {
- return new ErlNumber(erlnum.toString());
- }
-
- isUnbound() {
- return false;
- }
-
- match(value) {
- if (!this.value.equals(value)) {
- return undefined;
- }
- return value;
- }
+// Constructor
+function ErlNumber(value) {
+ this.value = new BigNumber(value);
}
+
+// Static Methods
+ErlNumber.isErlNumber = function(erlnum) {
+ return erlnum instanceof ErlNumber;
+}
+
+ErlNumber.cloneNumber = function(erlnum) {
+ return new ErlNumber(erlnum.toString());
+}
+
+
+// Prototype Methods
+ErlNumber.prototype.toString = function() {
+ return this.value.toString();
+}
+
+ErlNumber.prototype.isUnbound = function() {
+ return false;
+}
+
+ErlNumber.prototype.match = function(value) {
+ if (!this.value.equals(value)) {
+ return undefined;
+ }
+ return value;
+}
+
+
exports.ErlNumber = ErlNumber; |
96e350cb21377ca65d0c05ae63f37416fa0b0f65 | models/student.model.js | models/student.model.js | const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const studentSchema = new Schema({
fname: String,
lname: String,
csub_id: Number,
gender: String,
created_at: Date,
evaluations: [
{
wais: {
vc: Number,
pri: Number,
wmi: Number,
ps: Number,
fsiq: Number,
gai: Number,
final_score: Number,
}
},
{
micro_cog: {
gcf: Number,
gcp: Number,
ips: Number,
attn: Number,
reas: Number,
mem: Number,
spat: Number,
final_score: Number,
}
},
{
wiat: {
lc: Number,
oe: Number,
rc: Number,
wr: Number,
pd: Number,
orf: Number,
sc: Number,
ec: Number,
sp: Number,
mps: Number,
no: Number,
mfa: Number,
mfs: Number,
mfm: Number,
final_score: Number,
}
}
]
});
const Student = mongoose.model('Student', studentSchema);
module.exports = Student;
| const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const studentSchema = new Schema({
fname: String,
lname: String,
csub_id: Number,
gender: String,
created_at: Date,
evaluations: {
wais: {
vc: Number,
pri: Number,
wmi: Number,
ps: Number,
fsiq: Number,
gai: Number,
final_score: Number,
},
micro_cog: {
gcf: Number,
gcp: Number,
ips: Number,
attn: Number,
reas: Number,
mem: Number,
spat: Number,
final_score: Number,
},
wiat: {
lc: Number,
oe: Number,
rc: Number,
wr: Number,
pd: Number,
orf: Number,
sc: Number,
ec: Number,
sp: Number,
mps: Number,
no: Number,
mfa: Number,
mfs: Number,
mfm: Number,
final_score: Number,
},
}
});
const Student = mongoose.model('Student', studentSchema);
module.exports = Student;
| Use key/val data structure for evaluations | Use key/val data structure for evaluations
| JavaScript | mit | corykitchens/gaus,corykitchens/gaus | ---
+++
@@ -7,50 +7,44 @@
csub_id: Number,
gender: String,
created_at: Date,
- evaluations: [
- {
- wais: {
- vc: Number,
- pri: Number,
- wmi: Number,
- ps: Number,
- fsiq: Number,
- gai: Number,
- final_score: Number,
- }
+ evaluations: {
+ wais: {
+ vc: Number,
+ pri: Number,
+ wmi: Number,
+ ps: Number,
+ fsiq: Number,
+ gai: Number,
+ final_score: Number,
},
- {
- micro_cog: {
- gcf: Number,
- gcp: Number,
- ips: Number,
- attn: Number,
- reas: Number,
- mem: Number,
- spat: Number,
- final_score: Number,
- }
+ micro_cog: {
+ gcf: Number,
+ gcp: Number,
+ ips: Number,
+ attn: Number,
+ reas: Number,
+ mem: Number,
+ spat: Number,
+ final_score: Number,
},
- {
- wiat: {
- lc: Number,
- oe: Number,
- rc: Number,
- wr: Number,
- pd: Number,
- orf: Number,
- sc: Number,
- ec: Number,
- sp: Number,
- mps: Number,
- no: Number,
- mfa: Number,
- mfs: Number,
- mfm: Number,
- final_score: Number,
- }
- }
- ]
+ wiat: {
+ lc: Number,
+ oe: Number,
+ rc: Number,
+ wr: Number,
+ pd: Number,
+ orf: Number,
+ sc: Number,
+ ec: Number,
+ sp: Number,
+ mps: Number,
+ no: Number,
+ mfa: Number,
+ mfs: Number,
+ mfm: Number,
+ final_score: Number,
+ },
+ }
});
const Student = mongoose.model('Student', studentSchema); |
f3cc961adfdaacfa43b2bc6349a389679f14740e | modules/chaos-monkey.js | modules/chaos-monkey.js | 'use strict';
/**
* Stubby Chaos Money Demo Module
*/
var StubbyChaosMonkey = function() {
/* min is inclusive, and max is exclusive */
var getRandomArbitrary = function(min, max) {
return Math.random() * (max - min) + min;
};
var getRandomHTTPStatus = function() {
return getRandomArbitrary(100, 600);
};
this.register = function(handler) {
// Request is empty on route setup.
handler.on('setup', this.onRequestSetup, this);
// Called before a request and response are matched
handler.on('routesetup', this.onRouteSetup, this);
// Called after a request and response are matched
handler.on('request', this.onRequestExecute, this);
};
this.onRouteSetup = function(request, stub) {
if (!stub.internal.options.chaos) {
return;
}
if (stub.response.status !== 43) {
throw new Error('Response status needs to be `43` for a valid chaos response');
}
};
this.onRequestSetup = function() {
// console.log('[requestsetup] ', request, stub);
};
this.onRequestExecute = function(request, stub) {
if (stub.internal.options.chaos) {
stub.response.status = getRandomHTTPStatus();
}
};
};
if (typeof module === 'undefined') {
window.StubbyChaosMonkey = StubbyChaosMonkey;
} else {
module.exports = StubbyChaosMonkey;
}
| 'use strict';
/**
* Stubby Chaos Money Demo Module
*/
var StubbyChaosMonkey = function() {
/* min is inclusive, and max is exclusive */
var getRandomArbitrary = function(min, max) {
return Math.random() * (max - min) + min;
};
var getRandomHTTPStatus = function() {
return getRandomArbitrary(100, 600);
};
this.register = function(handler) {
// Called before a request and response are matched
handler.on('routesetup', this.onRouteSetup, this);
// Called after a request and response are matched
handler.on('request', this.onRequestExecute, this);
};
this.onRouteSetup = function(request, stub) {
if (!stub.internal.options.chaos) {
return;
}
if (stub.response.status !== 43) {
throw new Error('Response status needs to be `43` for a valid chaos response');
}
};
this.onRequestExecute = function(request, stub) {
if (stub.internal.options.chaos) {
stub.response.status = getRandomHTTPStatus();
}
};
};
if (typeof module === 'undefined') {
window.StubbyChaosMonkey = StubbyChaosMonkey;
} else {
module.exports = StubbyChaosMonkey;
}
| Remove empty event handler in chaos monkey | Remove empty event handler in chaos monkey
| JavaScript | mit | gocardless/stubby,gocardless/stubby,gocardless/stubby | ---
+++
@@ -16,9 +16,6 @@
};
this.register = function(handler) {
- // Request is empty on route setup.
- handler.on('setup', this.onRequestSetup, this);
-
// Called before a request and response are matched
handler.on('routesetup', this.onRouteSetup, this);
@@ -35,10 +32,6 @@
}
};
- this.onRequestSetup = function() {
- // console.log('[requestsetup] ', request, stub);
- };
-
this.onRequestExecute = function(request, stub) {
if (stub.internal.options.chaos) {
stub.response.status = getRandomHTTPStatus(); |
046b30842e00b37d8b30c899b7af06b76a7b4434 | encryption.js | encryption.js | var crypto = require('crypto');
var iv = new Buffer("");
function createCryptor(key) {
key = new Buffer(key);
return function encrypt(data) {
var cipher = crypto.createCipheriv("bf-ecb", key, iv);
try {
return Buffer.concat([
cipher.update(data),
cipher.final()
]);
} catch (e) {
return null;
}
}
}
function createDecryptor(key) {
key = new Buffer(key);
return function decrypt(data) {
var cipher = crypto.createDecipheriv("bf-ecb", key, iv);
try {
return Buffer.concat([
cipher.update(data),
cipher.final()
]);
} catch (e) {
return null;
}
}
}
exports.decrypt = function(password, ciphered) {
var blowfish = createDecryptor(password);
var buff = blowfish(new Buffer(ciphered, "hex"));
return buff;
};
exports.encrypt = function(password, plain) {
var blowfish = createCryptor(password);
var buff = blowfish(plain);
return buff;
};
| var crypto = require('crypto');
var iv = new Buffer("");
var PADDING_LENGTH = 16;
var PADDING = Array(PADDING_LENGTH).join("\0");
function createCryptor(key) {
key = new Buffer(key);
return function encrypt(data) {
var cipher = crypto.createCipheriv("bf-ecb", key, iv);
cipher.setAutoPadding(false);
var padLength = PADDING_LENGTH - (data.length % PADDING_LENGTH);
try {
return Buffer.concat([
cipher.update(data + PADDING.substr(0, padLength)),
cipher.final()
]);
} catch (e) {
return null;
}
}
}
function createDecryptor(key) {
key = new Buffer(key);
return function decrypt(data) {
var cipher = crypto.createDecipheriv("bf-ecb", key, iv);
cipher.setAutoPadding(false);
try {
return Buffer.concat([
cipher.update(data),
cipher.final()
]);
} catch (e) {
return null;
}
}
}
exports.decrypt = function(password, ciphered) {
var blowfish = createDecryptor(password);
var buff = blowfish(new Buffer(ciphered, "hex"));
return buff;
};
exports.encrypt = function(password, plain) {
var blowfish = createCryptor(password);
var buff = blowfish(plain);
return buff;
};
| Fix null padding issues to pass tests | Fix null padding issues to pass tests
| JavaScript | mit | dlom/anesidora | ---
+++
@@ -1,13 +1,18 @@
var crypto = require('crypto');
var iv = new Buffer("");
+
+var PADDING_LENGTH = 16;
+var PADDING = Array(PADDING_LENGTH).join("\0");
function createCryptor(key) {
key = new Buffer(key);
return function encrypt(data) {
var cipher = crypto.createCipheriv("bf-ecb", key, iv);
+ cipher.setAutoPadding(false);
+ var padLength = PADDING_LENGTH - (data.length % PADDING_LENGTH);
try {
return Buffer.concat([
- cipher.update(data),
+ cipher.update(data + PADDING.substr(0, padLength)),
cipher.final()
]);
} catch (e) {
@@ -20,6 +25,7 @@
key = new Buffer(key);
return function decrypt(data) {
var cipher = crypto.createDecipheriv("bf-ecb", key, iv);
+ cipher.setAutoPadding(false);
try {
return Buffer.concat([
cipher.update(data),
@@ -42,6 +48,6 @@
exports.encrypt = function(password, plain) {
var blowfish = createCryptor(password);
var buff = blowfish(plain);
-
+
return buff;
}; |
364541ae389891a27d7e1b2a87c9e37e25f50bae | src/store/reducers/captures.js | src/store/reducers/captures.js | function faceCaptures(state = [], action) {
switch (action.type) {
case 'FACE_CAPTURE':
return [action.data, ...state]
default:
return state
}
}
function documentCaptures(state = [], action) {
switch (action.type) {
case 'DOCUMENT_CAPTURE':
return [action.data, ...state]
default:
return state
}
}
module.exports = {
faceCaptures,
documentCaptures
}
| function faceCaptures(state = [], action) {
switch (action.type) {
case 'FACE_CAPTURE':
return [action.payload, ...state]
default:
return state
}
}
function documentCaptures(state = [], action) {
switch (action.type) {
case 'DOCUMENT_CAPTURE':
return [action.payload, ...state]
default:
return state
}
}
module.exports = {
faceCaptures,
documentCaptures
}
| Rename action data to payload | Rename action data to payload
| JavaScript | mit | onfido/onfido-sdk-core | ---
+++
@@ -1,7 +1,7 @@
function faceCaptures(state = [], action) {
switch (action.type) {
case 'FACE_CAPTURE':
- return [action.data, ...state]
+ return [action.payload, ...state]
default:
return state
}
@@ -10,7 +10,7 @@
function documentCaptures(state = [], action) {
switch (action.type) {
case 'DOCUMENT_CAPTURE':
- return [action.data, ...state]
+ return [action.payload, ...state]
default:
return state
} |
25158df23cfefb8c770da68393e8229a3b5ee39f | src/renderers/NotAnimatedContextMenu.js | src/renderers/NotAnimatedContextMenu.js | import React from 'react';
import { View } from 'react-native';
import { computePosition, styles } from './ContextMenu';
/**
Simplified version of ContextMenu without animation.
*/
export default class NotAnimatedContextMenu extends React.Component {
render() {
const { style, children, layouts, ...other } = this.props;
const position = computePosition(layouts);
return (
<View {...other} style={[styles.options, style, position]}>
{children}
</View>
);
}
}
| import React from 'react';
import { I18nManager, View } from 'react-native';
import { computePosition, styles } from './ContextMenu';
/**
Simplified version of ContextMenu without animation.
*/
export default class NotAnimatedContextMenu extends React.Component {
render() {
const { style, children, layouts, ...other } = this.props;
const position = computePosition(layouts, I18nManager.isRTL);
return (
<View {...other} style={[styles.options, style, position]}>
{children}
</View>
);
}
}
| Add RTL for not animated menu | Add RTL for not animated menu
| JavaScript | isc | instea/react-native-popup-menu | ---
+++
@@ -1,5 +1,5 @@
import React from 'react';
-import { View } from 'react-native';
+import { I18nManager, View } from 'react-native';
import { computePosition, styles } from './ContextMenu';
@@ -10,7 +10,7 @@
render() {
const { style, children, layouts, ...other } = this.props;
- const position = computePosition(layouts);
+ const position = computePosition(layouts, I18nManager.isRTL);
return (
<View {...other} style={[styles.options, style, position]}>
{children} |
1de65779516311c98f38f9c77bb13cab2716e5f6 | .eslintrc.js | .eslintrc.js | module.exports = {
extends: [
'onelint'
],
plugins: ['import'],
rules: {
'import/no-extraneous-dependencies': [
'error', {
devDependencies: [ '**/test/**/*.js' ],
optionalDependencies: false,
peerDependencies: false
}
]
}
};
| module.exports = {
extends: [
'onelint'
],
plugins: ['import'],
rules: {
'import/no-extraneous-dependencies': [
'error', {
devDependencies: [ '**/test/**/*.js', '**/bootstrap-unexpected-markdown.js' ],
optionalDependencies: false,
peerDependencies: false
}
]
}
};
| Allow use of 'require' in the docs bootstrap | Allow use of 'require' in the docs bootstrap
| JavaScript | mit | alexjeffburke/unexpected,unexpectedjs/unexpected,alexjeffburke/unexpected | ---
+++
@@ -6,7 +6,7 @@
rules: {
'import/no-extraneous-dependencies': [
'error', {
- devDependencies: [ '**/test/**/*.js' ],
+ devDependencies: [ '**/test/**/*.js', '**/bootstrap-unexpected-markdown.js' ],
optionalDependencies: false,
peerDependencies: false
} |
f771deccadd644e2f79ff975fcb594c3639265c7 | src/templates/post-template.js | src/templates/post-template.js | import React from 'react'
import Helmet from 'react-helmet'
import { graphql } from 'gatsby'
import Layout from '../components/Layout'
import PostTemplateDetails from '../components/PostTemplateDetails'
class PostTemplate extends React.Component {
render() {
const { title, subtitle } = this.props.data.site.siteMetadata
const post = this.props.data.markdownRemark
const { title: postTitle, description: postDescription } = post.frontmatter
const description = postDescription !== null ? postDescription : subtitle
return (
<Layout>
<div>
<Helmet>
<title>{`${postTitle} - ${title}`}</title>
<meta name="description" content={description} />
</Helmet>
<PostTemplateDetails {...this.props} />
</div>
</Layout>
)
}
}
export default PostTemplate
export const pageQuery = graphql`
query PostBySlug($slug: String!) {
site {
siteMetadata {
title
subtitle
copyright
author {
name
twitter
}
url
}
}
markdownRemark(fields: { slug: { eq: $slug } }) {
id
html
excerpt
fields {
tagSlugs
}
frontmatter {
title
tags
date
}
}
}
`
| import React from 'react'
import Helmet from 'react-helmet'
import { graphql } from 'gatsby'
import Layout from '../components/Layout'
import PostTemplateDetails from '../components/PostTemplateDetails'
class PostTemplate extends React.Component {
render() {
const { title, subtitle } = this.props.data.site.siteMetadata
const post = this.props.data.markdownRemark
const { title: postTitle, description: postDescription } = post.frontmatter
const description = postDescription !== null ? postDescription : subtitle
return (
<Layout>
<div>
<Helmet>
<title>{`${postTitle} - ${title}`}</title>
<meta name="description" content={description} />
</Helmet>
<PostTemplateDetails {...this.props} />
</div>
</Layout>
)
}
}
export default PostTemplate
export const pageQuery = graphql`
query PostBySlug($slug: String!) {
site {
siteMetadata {
title
subtitle
copyright
author {
name
email
twitter
github
linkedin
}
url
}
}
markdownRemark(fields: { slug: { eq: $slug } }) {
id
html
excerpt
fields {
tagSlugs
}
frontmatter {
title
tags
date
}
}
}
`
| Fix social links at the bottom of posts | Fix social links at the bottom of posts
| JavaScript | mit | schneidmaster/schneid.io,schneidmaster/schneid.io | ---
+++
@@ -36,7 +36,10 @@
copyright
author {
name
+ email
twitter
+ github
+ linkedin
}
url
} |
e5a2221ec332ba1f3cd2fc8888770bdf31e9b851 | element.js | element.js | var walk = require('dom-walk')
var FormData = require('./index.js')
module.exports = getFormData
function buildElems(rootElem) {
var hash = {}
if (rootElem.name) {
hash[rootElem.name] = rootElem
return hash
}
walk(rootElem, function (child) {
if (child.name) {
hash[child.name] = child
}
})
return hash
}
function getFormData(rootElem) {
var elements = buildElems(rootElem)
return FormData(elements)
}
| var walk = require('dom-walk')
var FormData = require('./index.js')
module.exports = getFormData
function buildElems(rootElem) {
var hash = {}
if (rootElem.name) {
hash[rootElem.name] = rootElem
}
walk(rootElem, function (child) {
if (child.name) {
hash[child.name] = child
}
})
return hash
}
function getFormData(rootElem) {
var elements = buildElems(rootElem)
return FormData(elements)
}
| Remove return early from buildElems | Remove return early from buildElems
| JavaScript | mit | Raynos/form-data-set | ---
+++
@@ -8,9 +8,8 @@
var hash = {}
if (rootElem.name) {
hash[rootElem.name] = rootElem
- return hash
}
-
+
walk(rootElem, function (child) {
if (child.name) {
hash[child.name] = child |
4061d46dcfb7c33b22e8f1c50c76b507f596dd7a | app/models/booking_model.js | app/models/booking_model.js | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Objectid = mongoose.Schema.Types.ObjectId;
var BookingSchema = new Schema({
room: Objectid,
start_time: Date,
end_time: Date,
title: String,
member: String,
_owner_id: Objectid
});
BookingSchema.set("_perms", {
admin: "crud",
owner: "crud",
user: "cr",
});
module.exports = mongoose.model('Booking', BookingSchema); | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Objectid = mongoose.Schema.Types.ObjectId;
var BookingSchema = new Schema({
room: Objectid,
start_time: Date,
end_time: Date,
title: String,
member: String,
cost: Number,
_owner_id: Objectid
});
BookingSchema.set("_perms", {
admin: "crud",
owner: "crud",
user: "cr",
});
BookingSchema.post("save", function(transaction) { //Keep our running total up to date
try {
var Reserve = require("./reserve_model");
var reserve = Reserve({
user_id: transaction._owner_id,
description: "Booking",
amount: transaction.cost * -1,
cred_type: "space",
source_type: "booking",
source_id: transaction._id
});
reserve.save();
} catch(err) {
console.log("Error", err);
// throw(err);
}
});
BookingSchema.post("remove", function(transaction) { //Keep our running total up to date
console.log("Going to remove reserve");
console.log(transaction);
try {
var Reserve = require("./reserve_model");
Reserve.findOne({
source_type: "booking",
source_id: transaction._id
}, function(err, item) {
if (err) {
console.log("Error", err);
return;
}
if (!item) {
console.log("Could not find Reserve");
return;
}
item.remove();
});
} catch(err) {
console.log("Error", err);
// throw(err);
}
});
module.exports = mongoose.model('Booking', BookingSchema); | Handle Reserve from Booking Model | Handle Reserve from Booking Model
| JavaScript | mit | 10layer/jexpress,j-norwood-young/jexpress,j-norwood-young/jexpress,10layer/jexpress,j-norwood-young/jexpress | ---
+++
@@ -9,6 +9,7 @@
end_time: Date,
title: String,
member: String,
+ cost: Number,
_owner_id: Objectid
});
@@ -18,4 +19,47 @@
user: "cr",
});
+BookingSchema.post("save", function(transaction) { //Keep our running total up to date
+ try {
+ var Reserve = require("./reserve_model");
+ var reserve = Reserve({
+ user_id: transaction._owner_id,
+ description: "Booking",
+ amount: transaction.cost * -1,
+ cred_type: "space",
+ source_type: "booking",
+ source_id: transaction._id
+ });
+ reserve.save();
+ } catch(err) {
+ console.log("Error", err);
+ // throw(err);
+ }
+});
+
+BookingSchema.post("remove", function(transaction) { //Keep our running total up to date
+ console.log("Going to remove reserve");
+ console.log(transaction);
+ try {
+ var Reserve = require("./reserve_model");
+ Reserve.findOne({
+ source_type: "booking",
+ source_id: transaction._id
+ }, function(err, item) {
+ if (err) {
+ console.log("Error", err);
+ return;
+ }
+ if (!item) {
+ console.log("Could not find Reserve");
+ return;
+ }
+ item.remove();
+ });
+ } catch(err) {
+ console.log("Error", err);
+ // throw(err);
+ }
+});
+
module.exports = mongoose.model('Booking', BookingSchema); |
e34eb8ad630540f45f74c3a22e91595e6403e26c | src/reducers/author.js | src/reducers/author.js | 'use strict'
import * as types from '../constants/action-types'
import { REQUEST_PAGE_START_FROM } from '../constants/author-page'
import get from 'lodash/get'
import isArray from 'lodash/isArray'
import merge from 'lodash/merge'
import uniq from 'lodash/uniq'
const _ = {
get,
isArray,
merge,
uniq
}
const initialStates = {
isFetching: false
}
export const author = (state = initialStates, action = {}) => {
switch (action.type) {
case types.FETCH_AUTHOR_COLLECTION_REQUEST:
return Object.assign({}, state, {
isFetching: true
})
case types.FETCH_AUTHOR_COLLECTION_SUCCESS:
const {
authorId,
response,
currentPage,
totalResults,
totalPages,
receivedAt } = action
const previousCollectionIdList = _.get(state, [ authorId, 'collectIndexList' ], [])
const saveToState = {
isFetching: false,
[authorId]: {
collectIndexList: _.uniq(previousCollectionIdList.concat(_.get(response, 'result', []))),
currentPage,
totalResults,
receivedAt,
isFinish: (currentPage - REQUEST_PAGE_START_FROM + 1 >= totalPages)
}
}
return _.merge({}, state, saveToState)
case types.FETCH_AUTHOR_COLLECTION_FAILURE:
return Object.assign({}, state, {
isFetching: false,
error: action.error
})
default:
return state
}
}
| 'use strict'
import * as types from '../constants/action-types'
import { REQUEST_PAGE_START_FROM } from '../constants/author-page'
import get from 'lodash/get'
import isArray from 'lodash/isArray'
import uniq from 'lodash/uniq'
const _ = {
get,
isArray,
uniq
}
const initialStates = {
isFetching: false
}
export const author = (state = initialStates, action = {}) => {
switch (action.type) {
case types.FETCH_AUTHOR_COLLECTION_REQUEST:
return Object.assign({}, state, {
isFetching: true
})
case types.FETCH_AUTHOR_COLLECTION_SUCCESS:
const {
authorId,
response,
currentPage,
totalResults,
totalPages,
receivedAt } = action
const previousCollectionIdList = _.get(state, [ authorId, 'collectIndexList' ], [])
const saveToState = {
isFetching: false,
[authorId]: {
collectIndexList: _.uniq(previousCollectionIdList.concat(_.get(response, 'result', []))),
currentPage,
totalResults,
receivedAt,
isFinish: (currentPage - REQUEST_PAGE_START_FROM + 1 >= totalPages)
}
}
return Object.assign({}, state, saveToState)
case types.FETCH_AUTHOR_COLLECTION_FAILURE:
return Object.assign({}, state, {
isFetching: false,
error: action.error
})
default:
return state
}
}
| Use assign instead of merge | Use assign instead of merge
| JavaScript | agpl-3.0 | hanyulo/twreporter-react,garfieldduck/twreporter-react,nickhsine/twreporter-react,garfieldduck/twreporter-react,hanyulo/twreporter-react,twreporter/twreporter-react | ---
+++
@@ -5,13 +5,11 @@
import get from 'lodash/get'
import isArray from 'lodash/isArray'
-import merge from 'lodash/merge'
import uniq from 'lodash/uniq'
const _ = {
get,
isArray,
- merge,
uniq
}
@@ -44,7 +42,7 @@
isFinish: (currentPage - REQUEST_PAGE_START_FROM + 1 >= totalPages)
}
}
- return _.merge({}, state, saveToState)
+ return Object.assign({}, state, saveToState)
case types.FETCH_AUTHOR_COLLECTION_FAILURE:
return Object.assign({}, state, {
isFetching: false, |
a107b97aca1d6346811f4fba3bd2cc0dcded2dff | lib/helpers.js | lib/helpers.js | o_.capitaliseFirstLetter = function(string){
return string.charAt(0).toUpperCase() + string.slice(1);
};
o_.lowerFirstLetter = function(string){
if(!string) return;
return string.charAt(0).toLowerCase() + string.slice(1);
};
o_.sanitizeObject = function(object){
if(Meteor.isServer){
var sanitizedObject = {};
_.each(_.pairs(object), function(lonelyArray){
sanitizedObject[lonelyArray[0]] = sanitizeHtml(lonelyArray[1], {allowedTags: [], allowedAttributes: {}});
});
return sanitizedObject
}
};
o_.sanitizeArray = function(array){
if(Meteor.isServer){
var sanitizedArray = [];
_.each(array, function(string){
sanitizedArray.push(sanitizeHtml(string, {allowedTags: [], allowedAttributes: {}}));
});
return sanitizedArray;
}
};
o_.sanitizeString = function(string){
if(Meteor.isServer){
return sanitizeHtml(string, {allowedTags: [], allowedAttributes: {}});
}
} | o_.capitaliseFirstLetter = function(string){
return string.charAt(0).toUpperCase() + string.slice(1);
};
o_.lowerFirstLetter = function(string){
if(!string) return;
return string.charAt(0).toLowerCase() + string.slice(1);
};
o_.sanitizeObject = function(object){
if(Meteor.isServer){
var sanitizedObject = {};
_.each(_.pairs(object), function(lonelyArray){
if(sanitizedObject[0] === "summary"){
sanitizedObject[lonelyArray[0]] = sanitizeHtml(lonelyArray[1],
{allowedTags: ["a"], allowedAttributes: {"a": ["href"]}});
} else {
sanitizedObject[lonelyArray[0]] = sanitizeHtml(lonelyArray[1], {allowedTags: [], allowedAttributes: {}});
}
});
return sanitizedObject
}
};
o_.sanitizeArray = function(array){
if(Meteor.isServer){
var sanitizedArray = [];
_.each(array, function(string){
sanitizedArray.push(sanitizeHtml(string, {allowedTags: [], allowedAttributes: {}}));
});
return sanitizedArray;
}
};
o_.sanitizeString = function(string){
if(Meteor.isServer){
return sanitizeHtml(string, {allowedTags: [], allowedAttributes: {}});
}
} | Allow <a>-tags for policyAreas.summary and policies.summary | Allow <a>-tags for policyAreas.summary and policies.summary
| JavaScript | mit | carlbror/political-works,carlbror/political-works | ---
+++
@@ -11,7 +11,12 @@
if(Meteor.isServer){
var sanitizedObject = {};
_.each(_.pairs(object), function(lonelyArray){
- sanitizedObject[lonelyArray[0]] = sanitizeHtml(lonelyArray[1], {allowedTags: [], allowedAttributes: {}});
+ if(sanitizedObject[0] === "summary"){
+ sanitizedObject[lonelyArray[0]] = sanitizeHtml(lonelyArray[1],
+ {allowedTags: ["a"], allowedAttributes: {"a": ["href"]}});
+ } else {
+ sanitizedObject[lonelyArray[0]] = sanitizeHtml(lonelyArray[1], {allowedTags: [], allowedAttributes: {}});
+ }
});
return sanitizedObject |
a894ec199d6335794110b6b54d5b63583bc80da7 | lib/boilerUtils.js | lib/boilerUtils.js | /* boilerUtils
* This object holds functions that assist Boilerplate
*/
var boilerUtils = {}
boilerUtils.renderAction = function renderAction (action) {
return {
'string': altboiler.getTemplate,
'function': action
}[typeof action](action)
},
boilerUtils.getBoilerTemplateData = function getTemplateData (includes, content, options) {
return {
script: Assets.getText('assets/loader.js'),
styles: Assets.getText('assets/styles.css'),
content: content,
head: '"' + encodeURIComponent(includes['head'].join('\n')) + '"',
body: '"' + encodeURIComponent(includes['body'].join('\n')) + '"',
jsIncludes: EJSON.stringify(includes['js']),
onLoadHooks: '[' + boilerUtils.parseOnLoadHooks(options.onLoad).join(',') + ']',
meteorRuntimeConfig: EJSON.stringify(__meteor_runtime_config__ || {})
}
},
/* boilerUtils.parseOnLoadHooks(hooksArr)
* `hooksArr` - An array of hooks to parse
* Maps through the array;
* simply executing and returning `toString`
*/
boilerUtils.parseOnLoadHooks = function parseOnLoadHooks (hooksArr) {
return _.invoke(hooksArr, 'toString')
}
altboilerScope = altboilerScope || {}
altboilerScope._boilerUtils = boilerUtils | /* boilerUtils
* This object holds functions that assist Boilerplate
*/
var boilerUtils = {}
boilerUtils.renderAction = function renderAction (action) {
return {
'string': altboiler.getTemplate,
'function': action
}[typeof action](action)
},
boilerUtils.getBoilerTemplateData = function getTemplateData (includes, content, onLoadHooks) {
return {
script: Assets.getText('assets/loader.js'),
styles: Assets.getText('assets/styles.css'),
content: content,
head: '"' + encodeURIComponent(includes['head'].join('\n')) + '"',
body: '"' + encodeURIComponent(includes['body'].join('\n')) + '"',
jsIncludes: EJSON.stringify(includes['js']),
onLoadHooks: '[' + boilerUtils.parseOnLoadHooks(onLoadHooks).join(',') + ']',
meteorRuntimeConfig: EJSON.stringify(__meteor_runtime_config__ || {})
}
},
/* boilerUtils.parseOnLoadHooks(hooksArr)
* `hooksArr` - An array of hooks to parse
* Maps through the array;
* simply executing and returning `toString`
*/
boilerUtils.parseOnLoadHooks = function parseOnLoadHooks (hooksArr) {
return _.invoke(hooksArr, 'toString')
}
altboilerScope = altboilerScope || {}
altboilerScope._boilerUtils = boilerUtils | Fix a small bug related to onLoadHooks | Fix a small bug related to onLoadHooks
| JavaScript | mit | Kriegslustig/meteor-altboiler,Kriegslustig/meteor-altboiler | ---
+++
@@ -11,7 +11,7 @@
}[typeof action](action)
},
-boilerUtils.getBoilerTemplateData = function getTemplateData (includes, content, options) {
+boilerUtils.getBoilerTemplateData = function getTemplateData (includes, content, onLoadHooks) {
return {
script: Assets.getText('assets/loader.js'),
styles: Assets.getText('assets/styles.css'),
@@ -19,7 +19,7 @@
head: '"' + encodeURIComponent(includes['head'].join('\n')) + '"',
body: '"' + encodeURIComponent(includes['body'].join('\n')) + '"',
jsIncludes: EJSON.stringify(includes['js']),
- onLoadHooks: '[' + boilerUtils.parseOnLoadHooks(options.onLoad).join(',') + ']',
+ onLoadHooks: '[' + boilerUtils.parseOnLoadHooks(onLoadHooks).join(',') + ']',
meteorRuntimeConfig: EJSON.stringify(__meteor_runtime_config__ || {})
}
}, |
fddc78d8eff0e21b790cdb85a17f3c7406cd6f76 | lib/dust_driver.js | lib/dust_driver.js | 'use strict'
const fs = require('fs')
const { resolve } = require('url')
const escapeHTML = require('escape-html')
module.exports = createDustRenderer
function createDustRenderer () {
const dust = require('dustjs-linkedin')
dust.config.cache = false
dust.helpers.component = component
dust.onLoad = onLoad
return function render (name, opts = {}) {
return new Promise((resolve, reject) => {
dust.render(name, opts, (err, content) => {
if (err) return reject(err)
resolve(content)
})
})
}
function component (chunk, context, bodies, params) {
const props = params
const name = props.name
const tagName = props.tagName || 'div'
delete props.name
delete props.tagName
chunk.write(
`<${tagName} \
data-component='${name}' \
data-props='${escapeHTML(JSON.stringify(props))}'></${tagName}>`
)
}
function onLoad (templateName, opts, callback) {
fs.readFile(templateName + '.html', 'utf8', (err, src) => {
if (err) return callback(err)
let compiled
try {
compiled = dust.compile(src, templateName)
} catch (err) { return callback(err) }
callback(null, dust.loadSource(compiled))
})
}
}
| 'use strict'
const fs = require('fs')
const escapeHTML = require('escape-html')
module.exports = createDustRenderer
function createDustRenderer () {
const dust = require('dustjs-linkedin')
dust.config.cache = false
dust.helpers.component = component
dust.onLoad = onLoad
return function render (name, opts = {}) {
return new Promise((resolve, reject) => {
dust.render(name, opts, (err, content) => {
if (err) return reject(err)
resolve(content)
})
})
}
function component (chunk, context, bodies, params) {
const props = params
const name = props.name
const tagName = props.tagName || 'div'
delete props.name
delete props.tagName
chunk.write(
`<${tagName} \
data-component='${name}' \
data-props='${escapeHTML(JSON.stringify(props))}'>`
)
if (bodies.block) chunk.render(bodies.block, context)
chunk.write(`</${tagName}>`)
}
function onLoad (templateName, opts, callback) {
fs.readFile(templateName + '.html', 'utf8', (err, src) => {
if (err) return callback(err)
let compiled
try {
compiled = dust.compile(src, templateName)
} catch (err) { return callback(err) }
callback(null, dust.loadSource(compiled))
})
}
}
| Fix dust driver to include innerHTML | Fix dust driver to include innerHTML
| JavaScript | mit | domachine/penguin,domachine/penguin | ---
+++
@@ -1,7 +1,6 @@
'use strict'
const fs = require('fs')
-const { resolve } = require('url')
const escapeHTML = require('escape-html')
module.exports = createDustRenderer
@@ -29,8 +28,10 @@
chunk.write(
`<${tagName} \
data-component='${name}' \
-data-props='${escapeHTML(JSON.stringify(props))}'></${tagName}>`
+data-props='${escapeHTML(JSON.stringify(props))}'>`
)
+ if (bodies.block) chunk.render(bodies.block, context)
+ chunk.write(`</${tagName}>`)
}
function onLoad (templateName, opts, callback) { |
39a044493e57dabd6eb04d390fe12dc9d8033576 | src/Filters/HTML/CSSInlining/inlined-css-retriever.js | src/Filters/HTML/CSSInlining/inlined-css-retriever.js | phast.stylesLoading = 0;
var resourceLoader = new phast.ResourceLoader.make(phast.config.serviceUrl);
phast.forEachSelectedElement('style[data-phast-params]', function (style) {
phast.stylesLoading++;
retrieveFromBundler(style.getAttribute('data-phast-params'), function (css) {
style.textContent = css;
style.removeAttribute('data-phast-params');
}, phast.once(function () {
phast.stylesLoading--;
if (phast.stylesLoading === 0 && phast.onStylesLoaded) {
phast.onStylesLoaded();
}
}));
});
function retrieveFromBundler(textParams, done, always) {
var params = phast.ResourceLoader.RequestParams.fromString(textParams);
var request = resourceLoader.get(params);
request.onsuccess = done;
request.onend = always;
}
| phast.stylesLoading = 0;
var resourceLoader = new phast.ResourceLoader.make(phast.config.serviceUrl);
phast.forEachSelectedElement('style[data-phast-params]', function (style) {
phast.stylesLoading++;
retrieveFromBundler(style.getAttribute('data-phast-params'), function (css) {
style.textContent = css;
style.removeAttribute('data-phast-params');
}, phast.once(function () {
phast.stylesLoading--;
if (phast.stylesLoading === 0 && phast.onStylesLoaded) {
phast.onStylesLoaded();
}
}));
});
function retrieveFromBundler(textParams, done, always) {
var params = phast.ResourceLoader.RequestParams.fromString(textParams);
resourceLoader.get(params)
.then(done)
.finally(always);
}
| Make css loader work with promises | Make css loader work with promises
| JavaScript | agpl-3.0 | kiboit/phast,kiboit/phast,kiboit/phast | ---
+++
@@ -17,7 +17,7 @@
function retrieveFromBundler(textParams, done, always) {
var params = phast.ResourceLoader.RequestParams.fromString(textParams);
- var request = resourceLoader.get(params);
- request.onsuccess = done;
- request.onend = always;
+ resourceLoader.get(params)
+ .then(done)
+ .finally(always);
} |
b6045a736c4bcaaa3b6999cbc318b6033acc5d4b | src/lib/reports-request.js | src/lib/reports-request.js | 'use strict';
const baseUrl = 'http://www.spc.noaa.gov/climo/data/nglsr/data/rpts/';
const Promise = require('bluebird');
const request = Promise.promisifyAll(require('request'));
const co = require('co');
module.exports = function reportsRequest(date) {
date = date.replace(/\d{2}(\d{2})-(\d{2})-(\d{2})/, '$1$2$3');
return co(function* spcRequest() {
let response = yield request.getAsync(`${baseUrl}${date}.log`);
return Promise.resolve(response.body);
}).catch(function errorHandler(err) {
throw(err);
});
}; | 'use strict';
const baseUrl = 'http://www.spc.noaa.gov/climo/data/nglsr/data/rpts/';
const Promise = require('bluebird');
const request = Promise.promisifyAll(require('request'));
const co = require('co');
module.exports = function reportsRequest(date) {
date = date.replace(/\d{2}(\d{2})-(\d{2})-(\d{2})/, '$1$2$3');
return co(function* spcRequest() {
let response = yield request.getAsync(`${baseUrl}${date}.log`);
return Promise.resolve(response);
}).catch(function errorHandler(err) {
throw(err);
});
}; | Return the response object, rather than body | Return the response object, rather than body
| JavaScript | isc | jcharrell/node-spc-storm-reports | ---
+++
@@ -10,7 +10,7 @@
return co(function* spcRequest() {
let response = yield request.getAsync(`${baseUrl}${date}.log`);
- return Promise.resolve(response.body);
+ return Promise.resolve(response);
}).catch(function errorHandler(err) {
throw(err);
}); |
60ba23f69ee6e7997f58c303fe3d9fbb34d01f62 | fsr-logger.js | fsr-logger.js | var
moment = require('moment'),
sprintf = require('sprintf'),
fsr = require('file-stream-rotator');
function create_logger (streamConfig) {
streamConfig = streamConfig || {
filename: './log/activity.log',
frequency: 'daily',
verbose: false
};
var stream = fsr.getStream(streamConfig);
return function(msg) {
stream.write(sprintf("%s %s\n", moment().toISOString(), msg));
};
}
module.exports = create_logger;
module.exports.fileStreamRotator = fsr; | var
moment = require('moment'),
sprintf = require('sprintf'),
fsr = require('file-stream-rotator');
function create_simple_config(name, frequency, verbosity) {
var config = {}
config.filename = name || './log/activity.log';
config.frequency = frequency || 'daily';
config.verbose = verbosity || false;
}
function create_logger (streamConfig) {
if(!streamConfig) {
streamConfig = create_simple_config();
} else if(typeof streamConfig == 'string') {
streamConfig = create_simple_config(streamConfig);
}
var stream = fsr.getStream(streamConfig);
return function(msg) {
stream.write(sprintf("%s %s\n", moment().toISOString(), msg));
};
}
module.exports = create_logger;
module.exports.fileStreamRotator = fsr; | Make sure we can easily create new daily logs | Make sure we can easily create new daily logs
| JavaScript | mit | jasonlotito/fsr-logger | ---
+++
@@ -3,13 +3,20 @@
sprintf = require('sprintf'),
fsr = require('file-stream-rotator');
+function create_simple_config(name, frequency, verbosity) {
+ var config = {}
+ config.filename = name || './log/activity.log';
+ config.frequency = frequency || 'daily';
+ config.verbose = verbosity || false;
+}
+
function create_logger (streamConfig) {
- streamConfig = streamConfig || {
- filename: './log/activity.log',
- frequency: 'daily',
- verbose: false
- };
+ if(!streamConfig) {
+ streamConfig = create_simple_config();
+ } else if(typeof streamConfig == 'string') {
+ streamConfig = create_simple_config(streamConfig);
+ }
var stream = fsr.getStream(streamConfig);
|
26fcc3c6876a1ce783892bece78245609ce6d5d0 | app/routes/post_login.js | app/routes/post_login.js | import Ember from 'ember';
import preloadDataMixin from '../mixins/preload_data';
export default Ember.Route.extend(preloadDataMixin, {
cordova: Ember.inject.service(),
beforeModel() {
Ember.run(() => this.controllerFor('application').send('logMeIn'));
return this.preloadData().catch(error => {
if (error.status === 0) {
this.transitionTo("offline");
} else {
throw error;
}
}).finally(() => this.get("cordova").appLoad());
},
afterModel() {
if (this.get("session.isAdminApp")) {
this.loadStaticData().catch(error => {
if (error.status === 0) {
this.transitionTo("offline");
} else {
throw error;
}
});
}
// After everthying has been loaded, redirect user to requested url
var attemptedTransition = this.controllerFor('login').get('attemptedTransition');
if (attemptedTransition) {
attemptedTransition.retry();
this.set('attemptedTransition', null);
} else {
var currentUser = this.get('session.currentUser');
if (this.get('session.isAdminApp')) {
var myOffers = this.store.peekAll('offer').filterBy('reviewedBy.id', currentUser.get('id'));
if (myOffers.get('length') > 0) {
this.transitionTo('my_list');
} else {
this.transitionTo('offers');
}
} else {
this.transitionTo('/offers');
}
}
}
});
| import Ember from 'ember';
import preloadDataMixin from '../mixins/preload_data';
export default Ember.Route.extend(preloadDataMixin, {
cordova: Ember.inject.service(),
beforeModel() {
Ember.run(() => this.controllerFor('application').send('logMeIn'));
return this.preloadData().catch(error => {
if (error.status === 0) {
this.transitionTo("offline");
} else {
throw error;
}
}).finally(() => this.get("cordova").appLoad());
},
afterModel() {
if (this.get("session.isAdminApp")) {
this.loadStaticData().catch(error => {
if (error.status === 0) {
this.transitionTo("offline");
} else {
throw error;
}
});
}
// After everthying has been loaded, redirect user to requested url
var attemptedTransition = this.controllerFor('login').get('attemptedTransition');
if (attemptedTransition) {
attemptedTransition.retry();
this.set('attemptedTransition', null);
} else {
var currentUser = this.get('session.currentUser');
if (this.get('session.isAdminApp')) {
this.transitionTo('dashboard');
} else {
this.transitionTo('/offers');
}
}
}
});
| Revert "Revert "GCW- 2473- Replace Admin Offers UI with Dashboard and Search Filters"" | Revert "Revert "GCW- 2473- Replace Admin Offers UI with Dashboard and Search Filters""
| JavaScript | mit | crossroads/shared.goodcity,crossroads/shared.goodcity | ---
+++
@@ -35,12 +35,7 @@
} else {
var currentUser = this.get('session.currentUser');
if (this.get('session.isAdminApp')) {
- var myOffers = this.store.peekAll('offer').filterBy('reviewedBy.id', currentUser.get('id'));
- if (myOffers.get('length') > 0) {
- this.transitionTo('my_list');
- } else {
- this.transitionTo('offers');
- }
+ this.transitionTo('dashboard');
} else {
this.transitionTo('/offers');
} |
0b79ce4530ac5b3a98883e06ba1bf0e2434aa598 | js/myscript.js | js/myscript.js | // window.checkAdLoad = function(){
// var checkAdLoadfunction = function(){
// var msg = "Ad unit is not present";
// if($("._teraAdContainer")){
// console.log("Ad unit is present")
// msg = "Ad unit is present";
// }
// return msg;
// }
// checkAdLoadfunction()
// console.log(checkAdLoadfunction);
// var validateAd = new CustomEvent("trackAdLoad", { "detail": checkAdLoadfunction});
// window.dispatchEvent(validateAd);
// }
t$(document).ready(function(){
console.log("Checking the AdInstances.");
var checkAdLoadfunction = function(){
if(t$("._teraAdContainer")){
console.log("Ad unit is present");
t$('._teraAdContainer').mouseover(function(){
t$(this).focus();
console.log('Hoverred mouseover tera ad unit')
});
}
}
checkAdLoadfunction();
});
| // window.checkAdLoad = function(){
// var checkAdLoadfunction = function(){
// var msg = "Ad unit is not present";
// if($("._teraAdContainer")){
// console.log("Ad unit is present")
// msg = "Ad unit is present";
// }
// return msg;
// }
// checkAdLoadfunction()
// console.log(checkAdLoadfunction);
// var validateAd = new CustomEvent("trackAdLoad", { "detail": checkAdLoadfunction});
// window.dispatchEvent(validateAd);
// }
t$(document).ready(function(){
console.log("Checking the AdInstances.");
var checkAdLoadfunction = function(){
if(t$("._abmMainAdContainer")){
console.log("Ad unit is present");
t$('._teraAdContainer').mouseover(function(){
t$(this).find('._abmAdContainer').text("Mouse over tera ad unit")
console.log('Hoverred mouse over tera ad unit')
});
}
}
checkAdLoadfunction();
});
| Add changes to the js file | Add changes to the js file
| JavaScript | mit | hoverr/hoverr.github.io,hoverr/hoverr.github.io | ---
+++
@@ -16,11 +16,11 @@
t$(document).ready(function(){
console.log("Checking the AdInstances.");
var checkAdLoadfunction = function(){
- if(t$("._teraAdContainer")){
+ if(t$("._abmMainAdContainer")){
console.log("Ad unit is present");
t$('._teraAdContainer').mouseover(function(){
- t$(this).focus();
- console.log('Hoverred mouseover tera ad unit')
+ t$(this).find('._abmAdContainer').text("Mouse over tera ad unit")
+ console.log('Hoverred mouse over tera ad unit')
});
}
} |
19288160ef71d34f48a424eaea3055cc0cc14c93 | app/actions/asyncActions.js | app/actions/asyncActions.js | import AsyncQueue from '../utils/asyncQueueStructures';
let asyncQueue = new AsyncQueue();
const endAsync = () => ({ type: 'ASYNC_INACTIVE' });
const startAsync = () => ({ type: 'ASYNC_ACTIVE' });
const callAsync = (dispatchFn, newState) => (dispatch, getState) => {
if (!asyncQueue.size) {
asyncQueue.listenForEnd(dispatch.bind(null, endAsync()));
}
asyncQueue.add(dispatchFn, getState().async.delay, newState);
dispatch(startAsync());
};
const setDelay = (newDelay) => {
return {
type: 'SET_DELAY',
newDelay
};
};
export default {
callAsync,
endAsync,
setDelay,
startAsync
};
| import AsyncQueue from '../utils/asyncQueueStructures';
let asyncQueue = new AsyncQueue();
const endAsync = () => ({ type: 'ASYNC_INACTIVE' });
const startAsync = () => ({ type: 'ASYNC_ACTIVE' });
const callAsync = (dispatchFn, ...args) => (dispatch, getState) => {
if (!asyncQueue.size) {
asyncQueue.listenForEnd(dispatch.bind(null, endAsync()));
}
asyncQueue.add(dispatchFn, getState().async.delay, ...args);
dispatch(startAsync());
};
const setDelay = (newDelay) => {
return {
type: 'SET_DELAY',
newDelay
};
};
export default {
callAsync,
endAsync,
setDelay,
startAsync
};
| Allow multiple arguments for async actions | Allow multiple arguments for async actions
| JavaScript | mit | ivtpz/brancher,ivtpz/brancher | ---
+++
@@ -6,11 +6,11 @@
const startAsync = () => ({ type: 'ASYNC_ACTIVE' });
-const callAsync = (dispatchFn, newState) => (dispatch, getState) => {
+const callAsync = (dispatchFn, ...args) => (dispatch, getState) => {
if (!asyncQueue.size) {
asyncQueue.listenForEnd(dispatch.bind(null, endAsync()));
}
- asyncQueue.add(dispatchFn, getState().async.delay, newState);
+ asyncQueue.add(dispatchFn, getState().async.delay, ...args);
dispatch(startAsync());
};
|
b328d6d95f5642afba8b6ee80b3351a3bf71a0af | better-stacks.js | better-stacks.js | try { require('source-map-support-2/register') } catch (_) {}
// Async stacks.
try { require('trace') } catch (_) {}
// Removes node_modules and internal modules.
try {
var sep = require('path').sep
var path = __dirname + sep + 'node_modules' + sep
require('stack-chain').filter.attach(function (_, frames) {
var filtered = frames.filter(function (frame) {
var name = frame && frame.getFileName()
return (
// has a filename
name &&
// contains a separator (no internal modules)
name.indexOf(sep) !== -1 &&
// does not start with the current path followed by node_modules.
name.lastIndexOf(path, 0) !== 0
)
})
// depd (used amongst other by express requires at least 3 frames
// in the stack.
return filtered.length > 2
? filtered
: frames
})
} catch (_) {}
| Error.stackTraceLimit = 100
try { require('source-map-support-2/register') } catch (_) {}
// Async stacks.
try { require('trace') } catch (_) {}
// Removes node_modules and internal modules.
try {
var sep = require('path').sep
var path = __dirname + sep + 'node_modules' + sep
require('stack-chain').filter.attach(function (_, frames) {
var filtered = frames.filter(function (frame) {
var name = frame && frame.getFileName()
return (
// has a filename
name &&
// contains a separator (no internal modules)
name.indexOf(sep) !== -1 &&
// does not start with the current path followed by node_modules.
name.lastIndexOf(path, 0) !== 0
)
})
// depd (used amongst other by express requires at least 3 frames
// in the stack.
return filtered.length > 2
? filtered
: frames
})
} catch (_) {}
| Augment stack traces limit to 100. | Augment stack traces limit to 100.
| JavaScript | agpl-3.0 | vatesfr/xo-web,lmcro/xo-web,vatesfr/xo-web,lmcro/xo-web,lmcro/xo-web | ---
+++
@@ -1,3 +1,5 @@
+Error.stackTraceLimit = 100
+
try { require('source-map-support-2/register') } catch (_) {}
// Async stacks. |
4e5f184a89eaa1d58361e178bf7a26e23d9c36fb | src/resource/RefraxMutableResource.js | src/resource/RefraxMutableResource.js | /**
* Copyright (c) 2015-present, Joshua Hollenbeck
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const RefraxResourceBase = require('RefraxResourceBase');
const RefraxSchemaNodeAccessor = require('RefraxSchemaNodeAccessor');
const RefraxConstants = require('RefraxConstants');
const invokeDescriptor = require('invokeDescriptor');
const ACTION_CREATE = RefraxConstants.action.create;
const ACTION_UPDATE = RefraxConstants.action.update;
const ACTION_DELETE = RefraxConstants.action.delete;
/**
* RefraxMutableResource is a public facing interface class to querying a Schema Node.
*/
class RefraxMutableResource extends RefraxResourceBase {
static from(accessor, ...args) {
return new RefraxMutableResource(accessor, ...args);
}
constructor(accessor, ...args) {
if (!(accessor instanceof RefraxSchemaNodeAccessor)) {
throw new TypeError(
'RefraxMutableResource - Expected accessor of type RefraxSchemaNodeAccessor ' +
'but found `' + typeof(accessor) + '`'
);
}
super(accessor, ...args);
}
create(data) {
return invokeDescriptor(this._generateDescriptor(ACTION_CREATE, data));
}
destroy(data) {
return invokeDescriptor(this._generateDescriptor(ACTION_DELETE, data));
}
update(data) {
return invokeDescriptor(this._generateDescriptor(ACTION_UPDATE, data));
}
}
export default RefraxMutableResource;
| /**
* Copyright (c) 2015-present, Joshua Hollenbeck
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const RefraxResourceBase = require('RefraxResourceBase');
const RefraxSchemaNodeAccessor = require('RefraxSchemaNodeAccessor');
const RefraxConstants = require('RefraxConstants');
const invokeDescriptor = require('invokeDescriptor');
const ACTION_CREATE = RefraxConstants.action.create;
const ACTION_UPDATE = RefraxConstants.action.update;
const ACTION_DELETE = RefraxConstants.action.delete;
/**
* RefraxMutableResource is a public facing interface class to querying a Schema Node.
*/
class RefraxMutableResource extends RefraxResourceBase {
static from(accessor, ...args) {
return new RefraxMutableResource(accessor, ...args);
}
constructor(accessor, ...args) {
if (!(accessor instanceof RefraxSchemaNodeAccessor)) {
throw new TypeError(
'RefraxMutableResource - Expected accessor of type RefraxSchemaNodeAccessor ' +
'but found `' + typeof(accessor) + '`'
);
}
super(accessor, ...args);
}
create(...data) {
return invokeDescriptor(this._generateDescriptor(ACTION_CREATE, data));
}
destroy(...data) {
return invokeDescriptor(this._generateDescriptor(ACTION_DELETE, data));
}
update(...data) {
return invokeDescriptor(this._generateDescriptor(ACTION_UPDATE, data));
}
}
export default RefraxMutableResource;
| Update mutable methods for arguments passing | Update mutable methods for arguments passing
| JavaScript | bsd-3-clause | netarc/refrax,netarc/refrax | ---
+++
@@ -33,15 +33,15 @@
super(accessor, ...args);
}
- create(data) {
+ create(...data) {
return invokeDescriptor(this._generateDescriptor(ACTION_CREATE, data));
}
- destroy(data) {
+ destroy(...data) {
return invokeDescriptor(this._generateDescriptor(ACTION_DELETE, data));
}
- update(data) {
+ update(...data) {
return invokeDescriptor(this._generateDescriptor(ACTION_UPDATE, data));
}
} |
c2091a31f778f4a3ca0894833bb4ca07a599ca81 | lib/to_tree.js | lib/to_tree.js | "use strict";
/**
* to_tree(source[, root = null]) -> array
* - source (array): array of sections
* - root (mongodb.BSONPure.ObjectID|String): id of common root for result first level.
*
* Build sections tree (nested) from flat sorted array.
**/
module.exports = function (source, root) {
var result = [];
var nodes = {};
source.forEach(function (node) {
node.child_list = [];
nodes[node._id.toString()] = node;
});
root = !!root ? root.toString() : null;
// set children links for all nodes
// and collect root children to result array
source.forEach(function (node) {
node.parent = !!node.parent ? node.parent.toString() : null;
if (node.parent === root) {
result.push(node);
}
else {
if (node.parent !== null) {
nodes[node.parent].child_list.push(node);
}
}
});
return result;
};
| "use strict";
/**
* to_tree(source[, root = null]) -> array
* - source (array): array of sections
* - root (mongodb.BSONPure.ObjectID|String): id of common root for result first level.
*
* Build sections tree (nested) from flat sorted array.
**/
module.exports = function (source, root) {
var result = [];
var nodes = {};
source.forEach(function (node) {
node.child_list = [];
nodes[node._id.toString()] = node;
});
root = !!root ? root.toString() : null;
// set children links for all nodes
// and collect root children to result array
source.forEach(function (node) {
node.parent = !!node.parent ? node.parent.toString() : null;
if (node.parent === root) {
result.push(node);
} else if (node.parent !== null) {
// Add child node if parent node actually exists.
// It may not if we deal with nested forum sections where visible
// section is a descendant of invisible section.
if (nodes[node.parent]) {
nodes[node.parent].child_list.push(node);
}
}
});
return result;
};
| Fix fatal error when visible section is a descendant of invisible one. | Fix fatal error when visible section is a descendant of invisible one.
| JavaScript | mit | nodeca/nodeca.forum | ---
+++
@@ -25,9 +25,12 @@
if (node.parent === root) {
result.push(node);
- }
- else {
- if (node.parent !== null) {
+
+ } else if (node.parent !== null) {
+ // Add child node if parent node actually exists.
+ // It may not if we deal with nested forum sections where visible
+ // section is a descendant of invisible section.
+ if (nodes[node.parent]) {
nodes[node.parent].child_list.push(node);
}
} |
7000f6dfd23da27fdb4c6b73a03a672f04abf271 | jest_config/setup.js | jest_config/setup.js | import Vue from 'vue';
import Vuetify from 'vuetify';
Vue.use(Vuetify);
const csrf = global.document.createElement('input');
csrf.name = 'csrfmiddlewaretoken';
csrf.value = 'csrfmiddlewaretoken';
global.document.body.append(csrf);
global.document.body.setAttribute('data-app', true);
global.window.Urls = new Proxy(
{},
{
get(obj, prop) {
return () => prop;
},
}
);
| import Vue from 'vue';
import Vuetify from 'vuetify';
import icons from 'shared/vuetify/icons';
Vue.use(Vuetify, {
icons: icons(),
});
const csrf = global.document.createElement('input');
csrf.name = 'csrfmiddlewaretoken';
csrf.value = 'csrfmiddlewaretoken';
global.document.body.append(csrf);
global.document.body.setAttribute('data-app', true);
global.window.Urls = new Proxy(
{},
{
get(obj, prop) {
return () => prop;
},
}
);
| Fix missing globally registered <Icon> in tests | Fix missing globally registered <Icon> in tests
| JavaScript | mit | DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation | ---
+++
@@ -1,7 +1,10 @@
import Vue from 'vue';
import Vuetify from 'vuetify';
+import icons from 'shared/vuetify/icons';
-Vue.use(Vuetify);
+Vue.use(Vuetify, {
+ icons: icons(),
+});
const csrf = global.document.createElement('input');
csrf.name = 'csrfmiddlewaretoken'; |
4d5177898b73b95b304a39c2934201aefdc4ef26 | jest.config.js | jest.config.js | module.exports = {
name: 'Unit test',
testMatch: ['**/packages/**/__tests__/?(*.)+(spec|test).js'],
transform: {},
};
| module.exports = {
name: 'Unit test',
testMatch: ['<rootDir>/packages/**/__tests__/?(*.)+(spec|test).js'],
modulePathIgnorePatterns: ['.cache'],
transform: {},
};
| Fix jest hast map issue with .cache folder in examples | Fix jest hast map issue with .cache folder in examples
Signed-off-by: Alexandre Bodin <70f0c7aa1e44ecfca5832512bee3743e3471816f@gmail.com>
| JavaScript | mit | wistityhq/strapi,wistityhq/strapi | ---
+++
@@ -1,5 +1,6 @@
module.exports = {
name: 'Unit test',
- testMatch: ['**/packages/**/__tests__/?(*.)+(spec|test).js'],
+ testMatch: ['<rootDir>/packages/**/__tests__/?(*.)+(spec|test).js'],
+ modulePathIgnorePatterns: ['.cache'],
transform: {},
}; |
0476ef142043c2cbb7bb74dc4994d18f5ab4376e | src/services/config/config.service.js | src/services/config/config.service.js | 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
scale: {useRawDomain: false},
mark: {
tickThickness: 2
}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
},
mark: {
tickThickness: 2
}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
| 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
scale: {useRawDomain: false}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
| Revert "Make tick thicker to facilitate hovering" | Revert "Make tick thicker to facilitate hovering"
This reverts commit a90e6f1f92888e0904bd50d67993ab23ccec1a38.
| JavaScript | bsd-3-clause | vega/vega-lite-ui,uwdata/vega-lite-ui,vega/vega-lite-ui,uwdata/vega-lite-ui,uwdata/vega-lite-ui,vega/vega-lite-ui | ---
+++
@@ -29,10 +29,7 @@
height: 150
}
},
- scale: {useRawDomain: false},
- mark: {
- tickThickness: 2
- }
+ scale: {useRawDomain: false}
};
};
@@ -43,9 +40,6 @@
width: 150,
height: 150
}
- },
- mark: {
- tickThickness: 2
}
};
}; |
2e59b255d81ab6bf6eb3a2431cd78d3a5f265144 | js/gittip/upgrade.js | js/gittip/upgrade.js | Gittip.upgrade = {};
Gittip.upgrade.init = function () {
var userAgent = navigator.userAgent.toLowerCase();
var browser = (userAgent.indexOf('msie') != -1) ? parseInt(userAgent.split('msie')[1]) : -1;
if(browser != -1 && browser < 9) {
var message = '' +
'<div id="upgrade_browser">' +
' <div class="container">' +
'This browser isn\'t supported by GitTip.com. ' +
'We encourage You to upgrade or change browser. ' +
'<a href="http://browsehappy.com">Learn more</a>' +
' </div>' +
'</div>';
$("body").prepend(message);
}
};
$(document).ready(Gittip.upgrade.init); | Gittip.upgrade = {};
Gittip.upgrade.init = function () {
var userAgent = navigator.userAgent.toLowerCase();
var browser = (userAgent.indexOf('msie') != -1) ? parseInt(userAgent.split('msie')[1], 10) : -1;
if(browser != -1 && browser < 9) {
var message = '' +
'<div id="upgrade_browser">' +
' <div class="container">' +
'This browser isn\'t supported by GitTip.com. ' +
'We encourage You to upgrade or change browser. ' +
'<a href="http://browsehappy.com">Learn more</a>' +
' </div>' +
'</div>';
$("body").prepend(message);
}
};
$(document).ready(Gittip.upgrade.init);
| Add radix to a parseInt() | Add radix to a parseInt()
| JavaScript | mit | mccolgst/www.gittip.com,gratipay/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,studio666/gratipay.com,gratipay/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,eXcomm/gratipay.com,studio666/gratipay.com,studio666/gratipay.com,gratipay/gratipay.com | ---
+++
@@ -3,7 +3,7 @@
Gittip.upgrade.init = function () {
var userAgent = navigator.userAgent.toLowerCase();
- var browser = (userAgent.indexOf('msie') != -1) ? parseInt(userAgent.split('msie')[1]) : -1;
+ var browser = (userAgent.indexOf('msie') != -1) ? parseInt(userAgent.split('msie')[1], 10) : -1;
if(browser != -1 && browser < 9) {
var message = '' + |
fa8fa16839f3ff5185fe74c83b75aacc9023155c | js/cookies.js | js/cookies.js | // https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
console.log('Any cookies yet? ' + document.cookie);
console.log('Setting a cookie...');
document.cookie = 'something=somethingelse';
console.log('OK set one: ' + document.cookie);
| // https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
$(document).on('ready', function() {
allCookies = document.cookie;
if (allCookies === '') {
$('hi').append('Welcome for the first time!');
document.cookie = 'something=somethingelse';
} else {
$('hi').append('Welcome back!');
}
})
| Change messaging based on cookie | Change messaging based on cookie
| JavaScript | mit | oldhill/oldhill.github.io,oldhill/oldhill.github.io | ---
+++
@@ -1,9 +1,15 @@
// https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
-console.log('Any cookies yet? ' + document.cookie);
-console.log('Setting a cookie...');
+$(document).on('ready', function() {
-document.cookie = 'something=somethingelse';
+ allCookies = document.cookie;
-console.log('OK set one: ' + document.cookie);
+ if (allCookies === '') {
+ $('hi').append('Welcome for the first time!');
+ document.cookie = 'something=somethingelse';
+ } else {
+ $('hi').append('Welcome back!');
+ }
+
+}) |
ef4f7975c56c9c7adcaa213e99e394c035f1dd71 | js/includes.js | js/includes.js | $(function() {
$.get("includes/header.html", function(data) {
$('body').prepend(data);
});
$("#footer").load("includes/footer.html");
}) | $(function() {
$.get("includes/header.html", function(data) {
$('body').prepend(data);
$('.dropdown-item[href="' + window.location.pathname.split('/').pop() + '"]').addClass('active');
});
$("#footer").load("includes/footer.html");
}) | Add active class to current page in drop down | Add active class to current page in drop down
| JavaScript | mit | Skramdhanie/softwarecareers,Skramdhanie/softwarecareers,Skramdhanie/softwarecareers | ---
+++
@@ -1,6 +1,9 @@
$(function() {
$.get("includes/header.html", function(data) {
$('body').prepend(data);
+ $('.dropdown-item[href="' + window.location.pathname.split('/').pop() + '"]').addClass('active');
});
$("#footer").load("includes/footer.html");
+
+
}) |
a89cef0ab9d51aeffb5c016cb56539fac275171e | src/store/auth.js | src/store/auth.js | /* eslint-disable no-param-reassign */
import Vue from 'vue';
export default {
namespaced: true,
state: {
username: null,
},
mutations: {
setUsername(state, username) {
state.username = username;
},
},
actions: {
status({ commit }) {
return Vue.http.get('api/session').then(
(response) => {
commit('setUsername', (response.body && response.body.username) ? response.body.username : null);
return response.status;
},
(response) => {
commit('setUsername', null);
return response.status;
},
);
},
login({ commit }, { username, password }) {
return Vue.http.post('api/session', { username, password }).then(
(response) => {
commit('setUsername', response.username);
return true;
},
() => false,
);
},
logout({ commit }) {
return Vue.http.delete('api/session').then(
() => {
commit('setUsername', null);
return true;
},
() => false,
);
},
},
};
| /* eslint-disable no-param-reassign */
import Vue from 'vue';
export default {
namespaced: true,
state: {
username: null,
},
mutations: {
setUsername(state, username) {
state.username = username;
},
},
actions: {
status({ commit }) {
return Vue.http.get('api/session').then(
(response) => {
commit('setUsername', (response.body && response.body.username) ? response.body.username : null);
return response.status;
},
(response) => {
commit('setUsername', null);
return response.status;
},
);
},
login({ commit }, { username, password }) {
return Vue.http.post('api/session', { username, password }).then(
(response) => {
commit('setUsername', response.body.username);
return true;
},
() => false,
);
},
logout({ commit }) {
return Vue.http.delete('api/session').then(
() => {
commit('setUsername', null);
return true;
},
() => false,
);
},
},
};
| Fix missing username in initial login session | Fix missing username in initial login session
| JavaScript | mit | contao/package-manager | ---
+++
@@ -35,7 +35,7 @@
login({ commit }, { username, password }) {
return Vue.http.post('api/session', { username, password }).then(
(response) => {
- commit('setUsername', response.username);
+ commit('setUsername', response.body.username);
return true;
}, |
2ba30de598892d4c5667d26f3ca4f94652c849c2 | js/main.js | js/main.js | require.config({
paths: {
"knockout": "ext/knockout-2.1.0",
"jquery": "ext/jquery-1.7.2.min",
"text": "ext/text",
"codemirror": "ext/CodeMirror",
"bootstrap": "ext/bootstrap.min"
},
shim: {
"bootstrap": ["jquery"]
}
});
require(["knockout", "app", "jquery", "bootstrap", "utilities", "stringTemplateEngine", "text", "codemirror"], function(ko, App, $) {
var vm = new App();
//simple client-side routing - update hash when current section is changed
vm.currentSection.subscribe(function(newValue) {
location.hash = newValue.name;
});
var updateSection = function() {
vm.updateSection(location.hash.substr(1));
};
//respond to hashchange event
window.onhashchange = updateSection;
//initialize
updateSection();
//block alt navigation
$(document).keydown(function(event) {
if (event.altKey && (event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40)) {
return false;
}
});
window.alert = function(text) {
$("#alert .modal-body").html("<p>" + text + "</p>").parent().modal();
};
ko.applyBindings(vm);
});
| require.config({
paths: {
"knockout": "ext/knockout-2.1.0",
"jquery": "ext/jquery-1.7.2.min",
"text": "ext/text",
"codemirror": "ext/codemirror",
"bootstrap": "ext/bootstrap.min"
},
shim: {
"bootstrap": ["jquery"]
}
});
require(["knockout", "app", "jquery", "bootstrap", "utilities", "stringTemplateEngine", "text", "codemirror"], function(ko, App, $) {
var vm = new App();
//simple client-side routing - update hash when current section is changed
vm.currentSection.subscribe(function(newValue) {
location.hash = newValue.name;
});
var updateSection = function() {
vm.updateSection(location.hash.substr(1));
};
//respond to hashchange event
window.onhashchange = updateSection;
//initialize
updateSection();
//block alt navigation
$(document).keydown(function(event) {
if (event.altKey && (event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40)) {
return false;
}
});
window.alert = function(text) {
$("#alert .modal-body").html("<p>" + text + "</p>").parent().modal();
};
ko.applyBindings(vm);
});
| Update case on CodeMirror require in case web server is case sensitive (like gh-pages) | Update case on CodeMirror require in case web server is case sensitive (like gh-pages)
| JavaScript | mit | rniemeyer/SamplePresentation,rniemeyer/SamplePresentation | ---
+++
@@ -3,7 +3,7 @@
"knockout": "ext/knockout-2.1.0",
"jquery": "ext/jquery-1.7.2.min",
"text": "ext/text",
- "codemirror": "ext/CodeMirror",
+ "codemirror": "ext/codemirror",
"bootstrap": "ext/bootstrap.min"
},
shim: { |
1ac7400520c35c47b27c311fad3a15887f8cb2d5 | athenicpaste/application.js | athenicpaste/application.js | 'use strict';
let express = require('express');
let router = require('./router.js');
let createDatabaseManager = require('./models/dbManager.js');
let ClientError = require('./errors.js').ClientError;
const dbUrl = 'mongodb://localhost:27017/athenicpaste';
function logErrors(err, request, response, next) {
console.error(err.stack);
next();
}
function handleClientError(err, request, response, next) {
if (err instanceof ClientError) {
response.status(err.statusCode).send(err.message);
} else {
next();
}
}
function createApplication() {
return createDatabaseManager(dbUrl).then(function(dbManager) {
let app = express();
app.use(function(request, response, next) {
request.db = dbManager;
next();
});
app.use(router);
app.use(logErrors);
app.use(handleClientError);
return app;
});
}
exports.createApplication = createApplication;
| 'use strict';
let express = require('express');
let router = require('./router.js');
let createDatabaseManager = require('./models/dbManager.js');
let ClientError = require('./errors.js').ClientError;
const dbUrl = 'mongodb://localhost:27017/athenicpaste';
function createApplication() {
return createDatabaseManager(dbUrl).then(function(dbManager) {
let app = express();
app.use(function(request, response, next) {
request.db = dbManager;
next();
});
app.use(router);
app.use(function logErrors(err, request, response, next) {
console.error(err.stack);
next(err);
});
app.use(function handleClientError(err, request, response, next) {
if (err instanceof ClientError) {
response.status(err.statusCode).send(err.message);
} else {
next(err);
}
});
return app;
});
}
exports.createApplication = createApplication;
| Fix error propagation in middleware | Fix error propagation in middleware
| JavaScript | bsd-3-clause | cdunklau/athenicpaste | ---
+++
@@ -8,21 +8,6 @@
const dbUrl = 'mongodb://localhost:27017/athenicpaste';
-
-
-function logErrors(err, request, response, next) {
- console.error(err.stack);
- next();
-}
-
-
-function handleClientError(err, request, response, next) {
- if (err instanceof ClientError) {
- response.status(err.statusCode).send(err.message);
- } else {
- next();
- }
-}
function createApplication() {
@@ -36,8 +21,17 @@
app.use(router);
- app.use(logErrors);
- app.use(handleClientError);
+ app.use(function logErrors(err, request, response, next) {
+ console.error(err.stack);
+ next(err);
+ });
+ app.use(function handleClientError(err, request, response, next) {
+ if (err instanceof ClientError) {
+ response.status(err.statusCode).send(err.message);
+ } else {
+ next(err);
+ }
+ });
return app;
});
} |
33d33c639ee78ff0877127b9c03fc9f842f83440 | lib/reporters/tap.js | lib/reporters/tap.js |
/**
* Module dependencies.
*/
var Base = require('./base')
, cursor = Base.cursor
, color = Base.color;
/**
* Expose `TAP`.
*/
exports = module.exports = TAP;
/**
* Initialize a new `TAP` reporter.
*
* @param {Runner} runner
* @api public
*/
function TAP(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, total = runner.total
, n = 1;
runner.on('start', function(){
console.log('%d..%d', 1, total);
});
runner.on('test end', function(){
++n;
});
runner.on('pass', function(test){
console.log('ok %d %s', n, test.fullTitle());
});
runner.on('fail', function(test, err){
console.log('not ok %d %s', n, test.fullTitle());
console.log(err.stack.replace(/^/gm, ' '));
});
} |
/**
* Module dependencies.
*/
var Base = require('./base')
, cursor = Base.cursor
, color = Base.color;
/**
* Expose `TAP`.
*/
exports = module.exports = TAP;
/**
* Initialize a new `TAP` reporter.
*
* @param {Runner} runner
* @api public
*/
function TAP(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, total = runner.total
, n = 1;
runner.on('start', function(){
console.log('%d..%d', 1, total);
});
runner.on('test end', function(){
++n;
});
runner.on('pass', function(test){
console.log('ok %d %s', n, title(test));
});
runner.on('fail', function(test, err){
console.log('not ok %d %s', n, title(test));
console.log(err.stack.replace(/^/gm, ' '));
});
}
/**
* Return a TAP-safe title of `test`
*
* @param {Object} test
* @return {String}
* @api private
*/
function title(test) {
return test.fullTitle().replace(/#/g, '');
}
| Remove hasmark from TAP titles. | Remove hasmark from TAP titles.
| JavaScript | mit | nexdrew/mocha,tinganho/mocha,kevinburke/mocha,jbnicolai/mocha,duncanbeevers/mocha,outsideris/mocha,ajaykodali/mocha,GabrielNicolasAvellaneda/mocha,rstacruz/mocha,antoval/mocha,jbnicolai/mocha,geometrybase/mocha,pandeysoni/mocha,igwejk/mocha,adamgruber/mocha,GerHobbelt/mocha,tswaters/mocha,adamgruber/mocha,TimothyGu/mocha,papandreou/mocha,ilkkao/co-mocha,joshski/mocha,GranitB/mocha,Hacker0x01/mocha,Hacker0x01/mocha,IveWong/mocha,Phoenixmatrix/mocha,santiagoaguiar/mocha,tinganho/mocha,verkkokauppacom/mocha,beatfactor/mocha,gaye/mocha,pandeysoni/mocha,luxe-eng/valet-express.mocha,npmcomponent/visionmedia-mocha,DeNA/mocha,Hacker0x01/mocha,rstacruz/mocha,ELLIOTTCABLE/mocha,rstacruz/mocha,gaye/mocha,JohnnyEstilles/mocha,mysterycommand/mocha,sul4bh/mocha,santiagoaguiar/mocha,kolodny/mocha,TimothyGu/mocha,michaelBenin/mocha,jkresner/mocha,mbovel/mocha,Shyp/mocha,verkkokauppacom/mocha,jjoos/mocha,cleberar38/mocha,benvinegar/mocha,airportyh/mocha,beni55/mocha,mochajs/mocha,boneskull/mocha,beatfactor/mocha,imsobear/mocha,nightwatchjs/mocha-nightwatch,mponizil/mocha,beatfactor/mocha,node-rookie/mocha,jasonkarns/mocha,cleberar38/mocha,villesau/mocha,mtscout6/mocha,luxe-eng/valet-express.mocha,KevinTCoughlin/mocha,kyroskoh/mocha,benvinegar/mocha,aaroncrows/mocha,jkresner/mocha,ilkkao/co-mocha,hashcube/mocha,hackreactor/mocha,glenjamin/mocha,GabrielNicolasAvellaneda/mocha,phated/mocha,kolodny/mocha,menelaos/mocha-solarized,KevinTCoughlin/mocha,ELLIOTTCABLE/mocha,boneskull/mocha,antoval/mocha,kyroskoh/mocha,rlugojr/mocha,Khan/mocha,igwejk/mocha,ajaykodali/mocha,youprofit/mocha,DeNA/mocha,jkresner/mocha,charlie77/mocha,Shyp/mocha,boneskull/mocha,ianwremmel/mocha,mochajs/mocha,diydyq/mocha,phated/mocha,kevinburke/mocha,villesau/mocha,upfrontIO/mocha,irnc/mocha,kolodny/mocha,upfrontIO/mocha,tswaters/mocha,nightwatchjs/mocha-nightwatch,GranitB/mocha,netei/mocha,Khan/mocha,mponizil/mocha,joshski/mocha,ELLIOTTCABLE/mocha,wltsmrz/mocha,netei/mocha,hackreactor/mocha,node-rookie/mocha,ryanshawty/mocha,geometrybase/mocha,Khan/mocha,outsideris/mocha,wltsmrz/mocha,jbnicolai/mocha,tinganho/mocha,a8m/mocha,IveWong/mocha,KevinTCoughlin/mocha,aaroncrows/mocha,ilkkao/co-mocha,domenic/mocha,mochajs/mocha,pumpupapp/mocha,moander/mocha,menelaos/mocha-solarized,moander/mocha,wltsmrz/mocha,kevinburke/mocha,GerHobbelt/mocha,Shyp/mocha,diydyq/mocha,gaye/mocha,a8m/mocha,sul4bh/mocha,rlugojr/mocha,ryanshawty/mocha,hoverduck/mocha,adamgruber/mocha,mponizil/mocha,GabrielNicolasAvellaneda/mocha,villesau/mocha,hashcube/mocha,GranitB/mocha,luxe-eng/valet-express.mocha,tswaters/mocha,mysterycommand/mocha,duncanbeevers/mocha,mbovel/mocha,moander/mocha,woodyrew/mocha,pandeysoni/mocha,mysterycommand/mocha,jjoos/mocha,phated/mocha,irnc/mocha,menelaos/mocha-solarized,netei/mocha,GerHobbelt/mocha,upfrontIO/mocha,ianwremmel/mocha,charlie77/mocha,imsobear/mocha,pumpupapp/mocha,hashcube/mocha,pumpupapp/mocha,youprofit/mocha,sergeydt/mocha,ryanshawty/mocha,rlugojr/mocha,cleberar38/mocha,joshski/mocha,diydyq/mocha,ianwremmel/mocha,node-rookie/mocha,ajaykodali/mocha,nexdrew/mocha,hoverduck/mocha,santiagoaguiar/mocha,aaroncrows/mocha,airportyh/mocha,jasonkarns/mocha,verkkokauppacom/mocha,domenic/mocha,papandreou/mocha,jjoos/mocha,a8m/mocha,woodyrew/mocha,hoverduck/mocha,Phoenixmatrix/mocha,charlie77/mocha,DeNA/mocha,sergeydt/mocha,apkiernan/mocha,glenjamin/mocha,hoverduck/mocha,geometrybase/mocha,imsobear/mocha,michaelBenin/mocha,IveWong/mocha,JohnnyEstilles/mocha,youprofit/mocha,nightwatchjs/mocha-nightwatch,Phoenixmatrix/mocha,apkiernan/mocha,beni55/mocha,kyroskoh/mocha,nexdrew/mocha,jasonkarns/mocha,apkiernan/mocha,benvinegar/mocha,woodyrew/mocha,beni55/mocha,mbovel/mocha,JohnnyEstilles/mocha,irnc/mocha,npmcomponent/visionmedia-mocha,antoval/mocha,sul4bh/mocha | ---
+++
@@ -37,11 +37,23 @@
});
runner.on('pass', function(test){
- console.log('ok %d %s', n, test.fullTitle());
+ console.log('ok %d %s', n, title(test));
});
runner.on('fail', function(test, err){
- console.log('not ok %d %s', n, test.fullTitle());
+ console.log('not ok %d %s', n, title(test));
console.log(err.stack.replace(/^/gm, ' '));
});
}
+
+/**
+ * Return a TAP-safe title of `test`
+ *
+ * @param {Object} test
+ * @return {String}
+ * @api private
+ */
+
+function title(test) {
+ return test.fullTitle().replace(/#/g, '');
+} |
1f88eb60f6f12d0b01f3902ca22cd6964eac7e72 | karma.conf.js | karma.conf.js | module.exports = function (karma) {
let configuration = {
basePath: '.',
frameworks: ['mocha'],
files: [
{ pattern: 'node_modules/chai/chai.js', include: true },
'src/*.js',
'spec/*.js'
],
reporters: ['spec'],
browsers: ['Chrome'],
singleRun: true,
client: {
mocha: {
reporter: 'html'
}
}
};
if (karma.tdd) {
configuration = Object.assign(configuration, {
browsers: ['Chrome'],
reporters: ['dots'],
singleRun: false,
autoWatch: true
});
}
karma.set(configuration);
} | module.exports = function (karma) {
let configuration = {
basePath: '.',
frameworks: ['mocha'],
files: [
{ pattern: 'node_modules/chai/chai.js', include: true },
'src/*.js',
'spec/*.js'
],
reporters: ['spec'],
browsers: ['ChromeHeadless'],
singleRun: true,
client: {
mocha: {
reporter: 'html'
}
}
};
if (karma.tdd) {
configuration = Object.assign(configuration, {
browsers: ['Chrome'],
reporters: ['dots'],
singleRun: false,
autoWatch: true
});
}
karma.set(configuration);
} | Use headless Chrome in non-tdd mode | Use headless Chrome in non-tdd mode
| JavaScript | mit | antivanov/sniffr | ---
+++
@@ -8,7 +8,7 @@
'spec/*.js'
],
reporters: ['spec'],
- browsers: ['Chrome'],
+ browsers: ['ChromeHeadless'],
singleRun: true,
client: {
mocha: { |
5448e753590a58ac4fc2340a4cfb0798a54e494b | lib/sms.js | lib/sms.js | 'use strict';
module.exports =
{
base_name : 'sms',
action_name : 'sms/{id}',
send: function() {
return this.action(...arguments);
},
getResponses: function(/* dynamic */) {
var params = this.parseBaseParams(arguments);
return this.quiubas.network.get( [ this.action_name + '/responses', { 'id': params.id } ], params.params, params.success, params.error );
},
};
| 'use strict';
module.exports =
{
base_name : 'sms',
action_name : 'sms/{id}',
send: function() {
return this.action.apply(this, arguments);
},
getResponses: function(/* dynamic */) {
var params = this.parseBaseParams(arguments);
return this.quiubas.network.get( [ this.action_name + '/responses', { 'id': params.id } ], params.params, params.success, params.error );
},
};
| Add Node <5 support by removing spread operator | Add Node <5 support by removing spread operator | JavaScript | mit | quiubas/quiubas-node | ---
+++
@@ -6,7 +6,7 @@
action_name : 'sms/{id}',
send: function() {
- return this.action(...arguments);
+ return this.action.apply(this, arguments);
},
getResponses: function(/* dynamic */) { |
087fe83fd227c9700ca4dc0e9248103406617937 | eloquent_js/chapter03/ch03_ex01.js | eloquent_js/chapter03/ch03_ex01.js | function min(a, b) {
return a < b ? a : b;
}
console.log(min(0, 10));
console.log(min(0, -10));
| function min(a, b) {
return a < b ? a : b;
}
| Add chapter 3, exercise 1 | Add chapter 3, exercise 1
| JavaScript | mit | bewuethr/ctci | ---
+++
@@ -1,6 +1,3 @@
function min(a, b) {
- return a < b ? a : b;
+ return a < b ? a : b;
}
-
-console.log(min(0, 10));
-console.log(min(0, -10)); |
e3c4841a8552ea180ccfd9c241b6a3bf7382f200 | test/fixtures/common/_sites.js | test/fixtures/common/_sites.js | var background= __dirname+'/../background';
var map= {
localhost: background
,'127.0.0.1': background
}
exports= module.exports= {
lookup: function() {
return map[this.host.name]
}
,paths: [background]
}
| var background= __dirname+'/../background';
var sample= __dirname+'/../sample.com';
var map= {
localhost: background
,'127.0.0.1': background
,'sample.com': sample
}
exports= module.exports= {
lookup: function() {
return map[this.host.name]
}
,paths: [background,sample]
}
| Add sample.com site. Rerouting allows testing site routing, so here's a site. | Add sample.com site. Rerouting allows testing site routing, so here's a site.
| JavaScript | mit | randymized/malifi | ---
+++
@@ -1,12 +1,14 @@
var background= __dirname+'/../background';
+var sample= __dirname+'/../sample.com';
var map= {
localhost: background
,'127.0.0.1': background
+ ,'sample.com': sample
}
exports= module.exports= {
lookup: function() {
return map[this.host.name]
}
- ,paths: [background]
+ ,paths: [background,sample]
} |
13d00833dfe4386847599ab1e827eebc9030f120 | client/src/App.js | client/src/App.js | import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import Receipt from './Receipt';
import ReceiptsList from './ReceiptsList';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends Component {
render() {
return (
<div className="app container">
<Switch>
<Route path='/' component={ReceiptsList} />
<Route path='/receipt/:year/:month' component={Receipt} />
</Switch>
</div>
);
}
}
export default App;
| import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import Receipt from './Receipt';
import ReceiptsList from './ReceiptsList';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends Component {
render() {
return (
<div className="app container">
<Switch>
<Route path='/' exact component={ReceiptsList} />
<Route path='/receipt/:year/:month' component={Receipt} />
</Switch>
</div>
);
}
}
export default App;
| Fix an issue with matching route | Fix an issue with matching route
| JavaScript | mit | Ramp-Receipts/Ramp,Ramp-Receipts/Ramp | ---
+++
@@ -11,7 +11,7 @@
return (
<div className="app container">
<Switch>
- <Route path='/' component={ReceiptsList} />
+ <Route path='/' exact component={ReceiptsList} />
<Route path='/receipt/:year/:month' component={Receipt} />
</Switch>
</div> |
1f2dac22c64a768aac02f2b9a1246dfcb9e9d75a | lib/policies/rate-limit/rate-limit.js | lib/policies/rate-limit/rate-limit.js | const RateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
const logger = require('../../logger').policy;
module.exports = (params) => {
if (params.rateLimitBy) {
params.keyGenerator = (req) => {
try {
return req.egContext.evaluateAsTemplateString(params.rateLimitBy);
} catch (err) {
logger.error('Failed to generate rate-limit key with config: %s; %s', params.rateLimitBy, err.message);
}
};
}
return new RateLimit(Object.assign(params, {
store: new RedisStore({
client: require('../../db')
})
}));
};
| const RateLimit = require('express-rate-limit');
const RedisStore = require('rate-limit-redis');
const logger = require('../../logger').policy;
module.exports = (params) => {
if (params.rateLimitBy) {
params.keyGenerator = (req) => {
try {
return req.egContext.evaluateAsTemplateString(params.rateLimitBy);
} catch (err) {
logger.error('Failed to generate rate-limit key with config: %s; %s', params.rateLimitBy, err.message);
}
};
}
return new RateLimit(Object.assign(params, {
store: new RedisStore({
client: require('../../db'),
expiry: params.windowMs / 1000
})
}));
};
| Update rate limit policy to set redis expiry inline with windowMs | Update rate limit policy to set redis expiry inline with windowMs
| JavaScript | apache-2.0 | ExpressGateway/express-gateway | ---
+++
@@ -14,7 +14,8 @@
}
return new RateLimit(Object.assign(params, {
store: new RedisStore({
- client: require('../../db')
+ client: require('../../db'),
+ expiry: params.windowMs / 1000
})
}));
}; |
c43f5346480d1f92f95ee495d31dd61940d453d7 | lib/xregexp.js | lib/xregexp.js | const xRegExp = require('xregexp');
/**
* Wrapper for xRegExp to work around
* https://github.com/slevithan/xregexp/issues/130
*/
module.exports = (regexp, flags) => {
if (!flags || !flags.includes('x')) {
// We aren't using the 'x' flag, so we don't need to remove comments and
// whitespace as a workaround for
// https://github.com/slevithan/xregexp/issues/130
return xRegExp(regexp, flags);
}
const lines = regexp.split('\n');
return xRegExp(
lines.map((line) => line.replace(/\s+#.+/, ' ')).join('\n'),
flags
);
};
| const originalXRegExp = require('xregexp');
/**
* Wrapper for xRegExp to work around
* https://github.com/slevithan/xregexp/issues/130
*/
function xRegExp(regexp, flags) {
if (!flags || !flags.includes('x')) {
// We aren't using the 'x' flag, so we don't need to remove comments and
// whitespace as a workaround for
// https://github.com/slevithan/xregexp/issues/130
return originalXRegExp(regexp, flags);
}
const lines = regexp.split('\n');
return originalXRegExp(
lines.map((line) => line.replace(/\s+#.+/, ' ')).join('\n'),
flags
);
}
xRegExp.exec = originalXRegExp.exec;
module.exports = xRegExp;
| Add exec() to xRegExp wrapper | Add exec() to xRegExp wrapper
xRegExp includes an exec() method that we are using, but we hadn't
included it on our wrapper, so it was failing.
| JavaScript | mit | trotzig/import-js,trotzig/import-js,trotzig/import-js,Galooshi/import-js | ---
+++
@@ -1,20 +1,24 @@
-const xRegExp = require('xregexp');
+const originalXRegExp = require('xregexp');
/**
* Wrapper for xRegExp to work around
* https://github.com/slevithan/xregexp/issues/130
*/
-module.exports = (regexp, flags) => {
+function xRegExp(regexp, flags) {
if (!flags || !flags.includes('x')) {
// We aren't using the 'x' flag, so we don't need to remove comments and
// whitespace as a workaround for
// https://github.com/slevithan/xregexp/issues/130
- return xRegExp(regexp, flags);
+ return originalXRegExp(regexp, flags);
}
const lines = regexp.split('\n');
- return xRegExp(
+ return originalXRegExp(
lines.map((line) => line.replace(/\s+#.+/, ' ')).join('\n'),
flags
);
-};
+}
+
+xRegExp.exec = originalXRegExp.exec;
+
+module.exports = xRegExp; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.