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
02b3bb70674d192b864f1c15f542af125a1655ef
public/js/main.js
public/js/main.js
$(document).ready(function () { $(".carousel-inner-download").cycle({ fx:'scrollVert', pager: '.pager', timeout: 4000, speed: 500, // pause: 1, }); $(".c1-right").on("click", function(e) { var activeImage = $(".c1-image-shown"); var nextImage = activeImage.next(); if(nextImage.length == 0) { nextImage = $(".slider-inner img").first(); }; activeImage.removeClass("c1-image-shown").addClass("c1-image-hidden").css("z-index",-10);; nextImage.addClass("c1-image-shown").removeClass("c1-image-hidden").css("z-index",20); $(".slider-inner img").not([activeImage, nextImage]).css("z-index",1); }); $(".c1-left").on("click", function(e){ var activeImage = $(".c1-image-shown"); var nextImage = activeImage.prev(); if(nextImage.length == 0) { nextImage = $('.slider-inner img').last(); } activeImage.removeClass("c1-image-shown").addClass("c1-image-hidden").css("z-index", -10); nextImage.addClass("c1-image-shown").removeClass("c1-image-hidden").css("z-index", 20); $('.slider-inner img').not([activeImage, nextImage]).css("z-index", 1); }) });
$(document).ready(function () { $(".carousel-inner-download").cycle({ fx:'scrollVert', pager: '.pager', timeout: 4000, speed: 1000, // pause: 1, }); $(".c1-right").on("click", function(e) { var activeImage = $(".c1-image-shown"); var nextImage = activeImage.next(); if(nextImage.length == 0) { nextImage = $(".slider-inner img").first(); }; activeImage.removeClass("c1-image-shown").addClass("c1-image-hidden").css("z-index",-10);; nextImage.addClass("c1-image-shown").removeClass("c1-image-hidden").css("z-index",20); $(".slider-inner img").not([activeImage, nextImage]).css("z-index",1); }); $(".c1-left").on("click", function(e){ var activeImage = $(".c1-image-shown"); var nextImage = activeImage.prev(); if(nextImage.length == 0) { nextImage = $('.slider-inner img').last(); } activeImage.removeClass("c1-image-shown").addClass("c1-image-hidden").css("z-index", -10); nextImage.addClass("c1-image-shown").removeClass("c1-image-hidden").css("z-index", 20); $('.slider-inner img').not([activeImage, nextImage]).css("z-index", 1); }) });
Add slow down carousel speed
Add slow down carousel speed
JavaScript
mit
ZachKGordon/project_week_one,ZachKGordon/project_week_one
--- +++ @@ -4,7 +4,7 @@ fx:'scrollVert', pager: '.pager', timeout: 4000, - speed: 500, + speed: 1000, // pause: 1, });
031a0774e1995ca132120617131b5582bdf67b07
lib/handlers/documents/index.js
lib/handlers/documents/index.js
"use strict"; var restify = require('restify'); var async = require('async'); var Anyfetch = require('anyfetch'); module.exports.get = function get(req, res, next) { if(!req.query.context) { return next(new restify.ConflictError("Missing query parameter")); } async.waterfall([ function getDocuments(cb) { var params = { search: req.query.context, render_templates: true, sort: "-modificationDate", strict: true, fields: "data", }; if(req.query.limit) { params.limit = req.query.limit; } var anyfetchClient = new Anyfetch(req.accessToken.token); anyfetchClient.getDocuments(params, cb); }, function remapDocuments(documentsRes, cb) { res.set("Cache-Control", "max-age=3600"); res.send(200, documentsRes.body.data.map(function mapDocuments(document) { return { documentId: document.id, typeId: document.document_type.id, providerId: document.provider.client ? document.provider.client.id : null, date: document.modification_date, snippet: document.rendered_snippet, title: document.rendered_title }; })); cb(); } ], next); };
"use strict"; var restify = require('restify'); var async = require('async'); var Anyfetch = require('anyfetch'); module.exports.get = function get(req, res, next) { if(!req.query.context) { return next(new restify.ConflictError("Missing query parameter")); } async.waterfall([ function getDocuments(cb) { var params = { search: req.query.context, render_templates: true, sort: "-modificationDate", strict: true, fields: "data", }; if(req.query.limit) { params.limit = req.query.limit; } var anyfetchClient = new Anyfetch(req.accessToken.token); anyfetchClient.getDocuments(params, cb); }, function remapDocuments(documentsRes, cb) { res.set("Cache-Control", "max-age=3600"); res.send(200, documentsRes.body.data.map(function mapDocuments(document) { return { documentId: document.id, typeId: document.document_type.id, providerId: document.provider.client ? document.provider.client.id : "", date: document.modification_date, snippet: document.rendered_snippet, title: document.rendered_title }; })); cb(); } ], next); };
Handle null case for client id
Handle null case for client id
JavaScript
mit
AnyFetch/companion-server
--- +++ @@ -32,7 +32,7 @@ return { documentId: document.id, typeId: document.document_type.id, - providerId: document.provider.client ? document.provider.client.id : null, + providerId: document.provider.client ? document.provider.client.id : "", date: document.modification_date, snippet: document.rendered_snippet, title: document.rendered_title
7001a99ac6e7341b900472cb72eb92385765bf6d
contactmps/static/javascript/embed.js
contactmps/static/javascript/embed.js
if (document.location.hostname == "localhost") { var baseurl = ""; } else { var baseurl = "https://noconfidencevote.openup.org.za"; } var initContactMPsPymParent = function() { var pymParent = new pym.Parent('contactmps-embed-parent', baseurl + '/campaign/newsmedia/', {}); }; var agent = navigator.userAgent.toLowerCase(); if (agent.includes("mobile") && agent.includes("android")) { // addEventListener only available in later chrome versions window.addEventListener("load",function(){ window.addEventListener('error', function(e) { ga('send', 'event', 'JavaScript Error Parent', e.filename + ': ' + e.lineno, e.message); }); }); // Don't initialise pymParent! we iframe it ourselves! document.write('<div id="contactmps-embed-parent" style="height: 2500px; background: url(\'/static/images/background.svg\'); background-repeat: no-repeat"><iframe src="' + baseurl + '/campaign/newsmedia/" width="100%" scrolling="no" marginheight="0" frameborder="0" height="2500px" style="height: 2500px">Loading...</iframe></div>'); } else { document.write('<div id="contactmps-embed-parent"></div>'); document.write('<script type="text/javascript" src="' + baseurl + '/static/javascript/pym.v1.min.js" crossorigin="anonymous" async defer onload="initContactMPsPymParent()"></script>'); }
if (document.location.hostname == "localhost") { var baseurl = ""; } else { var baseurl = "https://noconfidencevote.openup.org.za"; } var initContactMPsPymParent = function() { var pymParent = new pym.Parent('contactmps-embed-parent', baseurl + '/campaign/newsmedia/', {}); }; var agent = navigator.userAgent.toLowerCase(); if (agent.includes("mobile") && agent.includes("android")) { // addEventListener only available in later chrome versions window.addEventListener("load",function(){ window.addEventListener('error', function(e) { ga('send', 'event', 'JavaScript Error Parent', e.filename + ': ' + e.lineno, e.message); }); }); // Don't initialise pymParent! we iframe it ourselves! document.write('<div id="contactmps-embed-parent" style="height: 2500px; background: url(https://noconfidencevote.openup.org.za/static/images/background.svg); background-repeat: no-repeat"><iframe src="' + baseurl + '/campaign/newsmedia/" width="100%" scrolling="no" marginheight="0" frameborder="0" height="2500px" style="height: 2500px">Loading...</iframe></div>'); } else { document.write('<div id="contactmps-embed-parent"></div>'); document.write('<script type="text/javascript" src="' + baseurl + '/static/javascript/pym.v1.min.js" crossorigin="anonymous" async defer onload="initContactMPsPymParent()"></script>'); }
Fix background - abs url for injected code
Fix background - abs url for injected code
JavaScript
mit
OpenUpSA/contact-mps,OpenUpSA/contact-mps,OpenUpSA/contact-mps,OpenUpSA/contact-mps
--- +++ @@ -17,7 +17,7 @@ }); }); // Don't initialise pymParent! we iframe it ourselves! - document.write('<div id="contactmps-embed-parent" style="height: 2500px; background: url(\'/static/images/background.svg\'); background-repeat: no-repeat"><iframe src="' + baseurl + '/campaign/newsmedia/" width="100%" scrolling="no" marginheight="0" frameborder="0" height="2500px" style="height: 2500px">Loading...</iframe></div>'); + document.write('<div id="contactmps-embed-parent" style="height: 2500px; background: url(https://noconfidencevote.openup.org.za/static/images/background.svg); background-repeat: no-repeat"><iframe src="' + baseurl + '/campaign/newsmedia/" width="100%" scrolling="no" marginheight="0" frameborder="0" height="2500px" style="height: 2500px">Loading...</iframe></div>'); } else { document.write('<div id="contactmps-embed-parent"></div>'); document.write('<script type="text/javascript" src="' + baseurl + '/static/javascript/pym.v1.min.js" crossorigin="anonymous" async defer onload="initContactMPsPymParent()"></script>');
740fe7c68a3dc0c66621ac83b04df579d7e0b180
pages/about.js
pages/about.js
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>About Us</h1> <p>We are a team of undergraduate students dedicated to using software to address sustainability challenges.</p> <p>We are a project-focused organization. We also hold programming workshops and guest lectures. Revert sample</p> </div> ); } }
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { Component } from 'react'; export default class extends Component { render() { return ( <div> <h1>About Us</h1> <p>We are a team of undergraduate students dedicated to using software to address sustainability challenges.</p> <p>We are a project-focused organization. We also hold programming workshops and guest lectures.</p> </div> ); } }
Revert "Added revert test line"
Revert "Added revert test line" This reverts commit 493c18f25d20e16f044d7ec489f836f72151e3bb.
JavaScript
mit
Princeton-SSI/organization-website
--- +++ @@ -13,7 +13,7 @@ <div> <h1>About Us</h1> <p>We are a team of undergraduate students dedicated to using software to address sustainability challenges.</p> - <p>We are a project-focused organization. We also hold programming workshops and guest lectures. Revert sample</p> + <p>We are a project-focused organization. We also hold programming workshops and guest lectures.</p> </div> ); }
dd0fc15d814acf458ce1e2e53859552c8ebe19da
server/routers/cars-router.js
server/routers/cars-router.js
var express = require('express'), router = express.Router(), carsData = require('../data/data-cars'), carsController = require('../controllers/cars-controller')(carsData), passport = require('passport'); // TODO: Add more routes. router .get('/:id', carsController.getCarById) .post('/delete', passport.authenticate('bearer', { session: false }), carsController.removeCar); module.exports = function (app) { app.use('/api/cars', router); };
var express = require('express'), router = express.Router(), carsData = require('../data/data-cars'), carsController = require('../controllers/cars-controller')(carsData), passport = require('passport'); // TODO: Add more routes. router .get('/all', carsController.getAllCars) .get('/:id', carsController.getCarById) .post('/:id/buy', carsController.buyCar) .post('/delete', passport.authenticate('bearer', { session: false }), carsController.removeCar); module.exports = function (app) { app.use('/shop/cars', router); };
Add routing for getting cars and buying car.
Add routing for getting cars and buying car.
JavaScript
mit
TA-2016-NodeJs-Team2/Telerik-Racer,TA-2016-NodeJs-Team2/Telerik-Racer
--- +++ @@ -6,11 +6,13 @@ // TODO: Add more routes. router + .get('/all', carsController.getAllCars) .get('/:id', carsController.getCarById) + .post('/:id/buy', carsController.buyCar) .post('/delete', passport.authenticate('bearer', { session: false }), carsController.removeCar); module.exports = function (app) { - app.use('/api/cars', router); + app.use('/shop/cars', router); };
217dac82baeb840fc9f6c0e65962cd1b817b7f10
client/templates/bets/create.js
client/templates/bets/create.js
var createBetNotification = function(bet){ var bet = Bets.findOne({ _id: bet }); BetNotifications.insert({ toNotify: bet.bettors[1], betBy: bet.bettors[0], bet: bet._id }); } Template.createBetForm.events({ "submit .create-bet" : function(event){ event.preventDefault(); var title = event.target.betTitle.value; wager = event.target.betWager.value; user = Meteor.user() username = user.username defender = event.target.defender.value; Meteor.call("createBet", username, defender, title, wager) Router.go('/bets') } });
var createBetNotification = function(bet){ var bet = Bets.findOne({ _id: bet }); BetNotifications.insert({ toNotify: bet.bettors[1], betBy: bet.bettors[0], bet: bet._id }); } Template.createBetForm.events({ "submit .create-bet" : function(event){ event.preventDefault(); var title = event.target.betTitle.value, wager = event.target.betWager.value, user = Meteor.user(), username = user.username, defender = event.target.defender.value; Meteor.call("createBet", username, defender, title, wager) Router.go('/bets') } });
Fix spacing in multiline variables
Fix spacing in multiline variables
JavaScript
mit
nmmascia/webet,nmmascia/webet
--- +++ @@ -10,12 +10,12 @@ Template.createBetForm.events({ "submit .create-bet" : function(event){ + event.preventDefault(); - event.preventDefault(); - var title = event.target.betTitle.value; - wager = event.target.betWager.value; - user = Meteor.user() - username = user.username + var title = event.target.betTitle.value, + wager = event.target.betWager.value, + user = Meteor.user(), + username = user.username, defender = event.target.defender.value; Meteor.call("createBet", username, defender, title, wager)
94468916921501961db178a80f93439f686bf830
config.js
config.js
module.exports = { auth : { github: { appId: 'edfc013fd01cf9d52a31', appSecret: 'a9ebb79267b7d968f10e9004724a9d9ac817a8ee', callbackURL : 'http://akrasia.ujo.guru:7173/auth/github/callback', username : "Zeukkari" }, local : { subnets : [ "192.168.1.0/24", "127.0.0.1/32" ] } }, /* * Device bridge * * Trigger on/off commands from remotes */ bridge : { 5 : { "script" : "bin/alarm.sh" }, 8 : { "script" : "bin/alarm.sh" }, 7 : { "script" : "bin/pdu.sh" }, 8 : { "bridgeTo" : 7 }, 6 : { "bridgeTo" : 4 } } };
var process = require('process'); module.exports = { auth : { local : { subnets : [ "192.168.1.0/24", "127.0.0.1/32" ] }, github : { /* * FIXME: Authentication mechanism is improperly implemented. * * - Username checkup seems a little strange * - appSecret should remain secret! */ appId: 'edfc013fd01cf9d52a31', appSecret: process.env.TELLDUS_APP_SECRET, callbackURL : 'http://akrasia.ujo.guru:7173/auth/github/callback', username : "Zeukkari" } }, /* * Device bridge * * Trigger on/off commands from remotes */ bridge : { 5 : { "script" : "bin/alarm.sh" }, 8 : { "script" : "bin/alarm.sh" }, 7 : { "script" : "bin/pdu.sh" }, 6 : { "bridgeTo" : 4 } } }
Read app secret from environment
Read app secret from environment
JavaScript
apache-2.0
Zeukkari/node-telldusserver,Zeukkari/node-telldusserver
--- +++ @@ -1,13 +1,21 @@ +var process = require('process'); + module.exports = { auth : { - github: { - appId: 'edfc013fd01cf9d52a31', - appSecret: 'a9ebb79267b7d968f10e9004724a9d9ac817a8ee', - callbackURL : 'http://akrasia.ujo.guru:7173/auth/github/callback', - username : "Zeukkari" - }, local : { subnets : [ "192.168.1.0/24", "127.0.0.1/32" ] + }, + github : { + /* + * FIXME: Authentication mechanism is improperly implemented. + * + * - Username checkup seems a little strange + * - appSecret should remain secret! + */ + appId: 'edfc013fd01cf9d52a31', + appSecret: process.env.TELLDUS_APP_SECRET, + callbackURL : 'http://akrasia.ujo.guru:7173/auth/github/callback', + username : "Zeukkari" } }, /* @@ -19,7 +27,6 @@ 5 : { "script" : "bin/alarm.sh" }, 8 : { "script" : "bin/alarm.sh" }, 7 : { "script" : "bin/pdu.sh" }, - 8 : { "bridgeTo" : 7 }, 6 : { "bridgeTo" : 4 } } -}; +}
eeb4f53559cecab3c01b3d62c69eaf1a599c3f0e
config/models.js
config/models.js
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#!/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // connection: 'localDiskDb', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ // migrate: 'alter' };
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#!/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // connection: 'localDiskDb', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'alter' };
Set sails.js migration property to 'alter'
Set sails.js migration property to 'alter' We want Sails.js to try to perform migration automatically
JavaScript
agpl-3.0
romain-ortega/nanocloud,Nanocloud/nanocloud,Gentux/nanocloud,Leblantoine/nanocloud,corentindrouet/nanocloud,romain-ortega/nanocloud,corentindrouet/nanocloud,corentindrouet/nanocloud,Nanocloud/nanocloud,Gentux/nanocloud,corentindrouet/nanocloud,Nanocloud/nanocloud,dynamiccast/nanocloud,Gentux/nanocloud,dynamiccast/nanocloud,dynamiccast/nanocloud,Gentux/nanocloud,corentindrouet/nanocloud,romain-ortega/nanocloud,Gentux/nanocloud,romain-ortega/nanocloud,Nanocloud/nanocloud,Nanocloud/nanocloud,Leblantoine/nanocloud,Nanocloud/nanocloud,corentindrouet/nanocloud,corentindrouet/nanocloud,Gentux/nanocloud,dynamiccast/nanocloud,Leblantoine/nanocloud,romain-ortega/nanocloud,Nanocloud/nanocloud,romain-ortega/nanocloud,Leblantoine/nanocloud,Gentux/nanocloud,Leblantoine/nanocloud,romain-ortega/nanocloud,corentindrouet/nanocloud,Leblantoine/nanocloud,Gentux/nanocloud,dynamiccast/nanocloud,romain-ortega/nanocloud,Nanocloud/nanocloud,Leblantoine/nanocloud,Leblantoine/nanocloud,dynamiccast/nanocloud
--- +++ @@ -27,6 +27,6 @@ * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ - // migrate: 'alter' + migrate: 'alter' };
4c2f94d399f37f39bd9cb4d4fad8b0cce35f2231
data/assets.js
data/assets.js
module.exports = [ { id: 'Hairstyles', required: false, sortOrder: 1 }, { id: 'Beards', required: false, sortOrder: 4 }, { id: 'Body', required: true, sortOrder: 0 }, { id: 'Glasses', required: false, sortOrder: 2 }, { id: 'Scarfes', required: false, sortOrder: 3 }, { id: 'Shirts', required: false, sortOrder: 1 }, { id: 'Tie', required: false, sortOrder: 2 }, { id: 'Eyes', required: true, sortOrder: 1, subColors: true }, { id: 'Jackets', required: false, sortOrder: 1 }, { id: 'Mouths', required: true, sortOrder: 1 } ];
module.exports = [ { id: 'Hairstyles', required: false, sortOrder: 1 }, { id: 'Beards', required: false, sortOrder: 5 }, { id: 'Body', required: true, sortOrder: 0 }, { id: 'Glasses', required: false, sortOrder: 2 }, { id: 'Scarfes', required: false, sortOrder: 4 }, { id: 'Shirts', required: false, sortOrder: 1 }, { id: 'Tie', required: false, sortOrder: 2 }, { id: 'Eyes', required: true, sortOrder: 1, subColors: true }, { id: 'Jackets', required: false, sortOrder: 3 }, { id: 'Mouths', required: true, sortOrder: 1 } ];
Update sort order in order to fix tie to be under jackets
Update sort order in order to fix tie to be under jackets
JavaScript
mit
g8extended/Character-Generator,g8extended/Character-Generator
--- +++ @@ -7,7 +7,7 @@ { id: 'Beards', required: false, - sortOrder: 4 + sortOrder: 5 }, { id: 'Body', @@ -22,7 +22,7 @@ { id: 'Scarfes', required: false, - sortOrder: 3 + sortOrder: 4 }, { id: 'Shirts', @@ -43,7 +43,7 @@ { id: 'Jackets', required: false, - sortOrder: 1 + sortOrder: 3 }, { id: 'Mouths',
33f0d928fa52c7bab202017d31bbed5be43bb57f
data/search-data.js
data/search-data.js
module.exports = function (models) { const { Photo, User } = models; return { searchPhotos(pattern) { let regex = new RegExp(pattern, 'i'); return new Promise((resolve, reject) => { Photo.find({ $or: [{ 'title': regex }, { 'description': regex }] }, (err, photos) => { if (err) { reject(err); } resolve(photos); }) }); }, searchUsers(pattern) { let regex = new RegExp(pattern, 'i'); return new Promise((resolve, reject) => { User.find({ $or: [{ 'username': regex }, { 'description': regex }, { 'name': regex }] }, (err, users) => { if (err) { reject(err); } resolve(users); }) }); }, searchTags(tag) { return new Promise((resolve, reject) => { let regex = new RegExp(tag, 'i'); Photo.find({ $or: [{ 'tags': regex }] }, (err, photos) => { if (err) { reject(err); } resolve(photos); }) }); }, }; };
module.exports = function (models) { const { Photo, User } = models; return { searchPhotos(pattern) { let regex = new RegExp(pattern, 'i'); return new Promise((resolve, reject) => { Photo.find({ $or: [{ 'title': regex }, { 'description': regex }] }, (err, photos) => { if (err) { reject(err); } resolve(photos); }) }); }, searchUsers(pattern) { let regex = new RegExp(pattern, 'i'); return new Promise((resolve, reject) => { User.find({ $or: [{ 'username': regex }, { 'description': regex }, { 'name': regex }] }, (err, users) => { if (err) { reject(err); } resolve(users); }) }); }, searchTags(tag) { return new Promise((resolve, reject) => { Photo.find({ $or: [{ 'tags': tag }] }, (err, photos) => { if (err) { reject(err); } resolve(photos); }) }); }, }; };
Tag searching now really works!
Tag searching now really works!
JavaScript
mit
Bird-Shamaness/MuchPixels,Bird-Shamaness/MuchPixels
--- +++ @@ -51,11 +51,10 @@ }, searchTags(tag) { return new Promise((resolve, reject) => { - let regex = new RegExp(tag, 'i'); Photo.find({ $or: [{ - 'tags': regex + 'tags': tag }] }, (err, photos) => {
dfaea825bc63b9930a3ed2ae4e170771981f9c0a
app.js
app.js
var RtmClient = require('@slack/client').RtmClient; var RTM_CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS.RTM; var RTM_EVENTS = require('@slack/client').RTM_EVENTS; var Conversation = require('watson-developer-cloud/conversation/v1') var conversation = new Conversation({ username: process.env.CONVERSATION_USERNAME || '', password: process.env.CONVERSATION_PASSWORD || '', version_date: Conversation.VERSION_DATE_2017_02_03 }); var workspace_id = process.env.CONVERSATION_WORKSPACE_ID || '' var bot_token = process.env.SLACK_BOT_TOKEN || ''; var rtm = new RtmClient(bot_token); rtm.start(); var responseObj = { context: {} } rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) { if (!responseObj.context.user) { responseObj.context.user = message.user } conversation.message({ input: {text: message.text}, context: responseObj.context, workspace_id: workspace_id }, function(err, response) { if (err) { console.log(err) } else { console.log(JSON.stringify(response, null, 2)) responseObj = response rtm.sendMessage(response.output.text[0], message.channel); } }) }); rtm.start();
var RtmClient = require('@slack/client').RtmClient; var RTM_CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS.RTM; var RTM_EVENTS = require('@slack/client').RTM_EVENTS; var Conversation = require('watson-developer-cloud/conversation/v1') var conversation = new Conversation({ username: process.env.CONVERSATION_USERNAME || '', password: process.env.CONVERSATION_PASSWORD || '', version_date: Conversation.VERSION_DATE_2017_02_03 }); var workspace_id = process.env.CONVERSATION_WORKSPACE_ID || '' var bot_token = process.env.SLACK_BOT_TOKEN || ''; var rtm = new RtmClient(bot_token); rtm.start(); var responseObj = { context: {} } rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) { responseObj.context.user = message.user conversation.message({ input: {text: message.text}, context: responseObj.context, workspace_id: workspace_id }, function(err, response) { if (err) { console.log(err) } else { console.log(JSON.stringify(response, null, 2)) responseObj = response rtm.sendMessage(response.output.text[0], message.channel); } }) }); rtm.start();
Fix history message user issue
Fix history message user issue
JavaScript
mit
SinisterBlade/slackbot
--- +++ @@ -17,9 +17,7 @@ context: {} } rtm.on(RTM_EVENTS.MESSAGE, function handleRtmMessage(message) { - if (!responseObj.context.user) { - responseObj.context.user = message.user - } + responseObj.context.user = message.user conversation.message({ input: {text: message.text}, context: responseObj.context,
1348dbf2b3dc6150ed1939da81a630943eafe99c
lib/octobat-moss-service.js
lib/octobat-moss-service.js
'use strict'; var rest = require('restler-q'); var q = require('q'); module.exports = function(options) { return q.fcall(function() { if (!options) { throw new Error("options required"); } var supplier = options.supplier; var customer = options.customer; if (!supplier || !customer) { throw new Error("options expects supplier and country"); } if (!supplier.country || !supplier.vatNumber) { throw new Error("options.supplier expects country and vatNumber"); } if (!customer.country) { throw new Error("options.customer expects country"); } return rest.postJson('http://vatmoss.octobat.com/vat.json', { supplier: { country: supplier.country, vat_number: supplier.vatNumber }, customer: { country: customer.country, vat_number: customer.vatNumber || "" } }); }); };
'use strict'; var rest = require('restler-q'); var q = require('q'); module.exports = function(options) { return q.fcall(function() { if (!options) { throw new Error("options required"); } var supplier = options.supplier; var customer = options.customer; if (!supplier || !customer) { throw new Error("options expects supplier and country"); } if (!supplier.country || !supplier.vatNumber) { throw new Error("options.supplier expects country and vatNumber"); } if (!customer.country) { throw new Error("options.customer expects country"); } var eservice, transactionType; if(customer.vatNumber) { transactionType = "B2B"; } else { transactionType = "B2C"; eservice = options.eservice === undefined ? true : options.eservice; } return rest.postJson('http://vatmoss.octobat.com/vat.json', { supplier: { country: supplier.country, vat_number: supplier.vatNumber || undefined }, customer: { country: customer.country, vat_number: customer.vatNumber || undefined }, transaction: { type: transactionType, eservice: eservice } }); }); };
Handle change to octobat service api.
Handle change to octobat service api.
JavaScript
mit
gitterHQ/vat-calculator
--- +++ @@ -24,14 +24,26 @@ throw new Error("options.customer expects country"); } + var eservice, transactionType; + if(customer.vatNumber) { + transactionType = "B2B"; + } else { + transactionType = "B2C"; + eservice = options.eservice === undefined ? true : options.eservice; + } + return rest.postJson('http://vatmoss.octobat.com/vat.json', { supplier: { country: supplier.country, - vat_number: supplier.vatNumber + vat_number: supplier.vatNumber || undefined }, customer: { country: customer.country, - vat_number: customer.vatNumber || "" + vat_number: customer.vatNumber || undefined + }, + transaction: { + type: transactionType, + eservice: eservice } });
f60c3ffc40204c6c92581b96584a176d88fc21ec
lib/transport/demo/index.js
lib/transport/demo/index.js
"use babel"; import github from './github'; import git from './git'; export default { github, git, make: function ({git, github}) { let dup = Object.create(this); if (git) { let g = Object.create(this.git); Object.keys(git).forEach((k) => { g[k] = git[k]; }); dup.git = g; } if (github) { let gh = Object.create(this.github); Object.keys(github).forEach((k) => { gh[k] = github[k]; }); dup.github = gh; } return dup; } };
"use babel"; import github from './github'; import git from './git'; function validStub(name, real, stub) { if (real === undefined) { throw new Error(`Attempt to stub nonexistent property: ${name}`); } if (typeof real !== typeof stub) { throw new Error(`Attempt to stub ${name} (${typeof real}) with ${typeof stub}`); } if (typeof real === 'function' && real.length !== stub.length) { throw new Error(`Argument length mismatch for ${name}: ${real.length} expected, got ${stub.length}`); } } export default { github, git, make: function ({git, github}) { let dup = Object.create(this); if (git) { let g = Object.create(this.git); Object.keys(git).forEach((k) => { validStub(k, this.git[k], git[k]); g[k] = git[k]; }); dup.git = g; } if (github) { let gh = Object.create(this.github); Object.keys(github).forEach((k) => { validStub(k, this.github[k], github[k]); gh[k] = github[k]; }); dup.github = gh; } return dup; } };
Validate stubs before permitting them.
Validate stubs before permitting them.
JavaScript
mit
smashwilson/pull-request
--- +++ @@ -2,6 +2,20 @@ import github from './github'; import git from './git'; + +function validStub(name, real, stub) { + if (real === undefined) { + throw new Error(`Attempt to stub nonexistent property: ${name}`); + } + + if (typeof real !== typeof stub) { + throw new Error(`Attempt to stub ${name} (${typeof real}) with ${typeof stub}`); + } + + if (typeof real === 'function' && real.length !== stub.length) { + throw new Error(`Argument length mismatch for ${name}: ${real.length} expected, got ${stub.length}`); + } +} export default { github, @@ -14,6 +28,8 @@ let g = Object.create(this.git); Object.keys(git).forEach((k) => { + validStub(k, this.git[k], git[k]); + g[k] = git[k]; }); @@ -24,6 +40,8 @@ let gh = Object.create(this.github); Object.keys(github).forEach((k) => { + validStub(k, this.github[k], github[k]); + gh[k] = github[k]; });
d27e66c219a2b0f175ea392ca41b074f25fdd4ef
source/moon-container-init.js
source/moon-container-init.js
(function (enyo, scope) { enyo.kind({ name: 'moon.ContainerInitializer', components: [ {kind: 'moon.Drawers', drawers: [{}], components: [ {kind: 'moon.Panels', pattern: 'activity', components: [ {components: [ {kind: 'moon.TooltipDecorator', components: [{kind: 'moon.Button'},{kind: 'moon.Tooltip'}]}, {kind: 'moon.ToggleButton'}, {kind: 'moon.ToggleItem'}, {kind: 'moon.FormCheckbox'}, {kind: 'moon.Image'}, {kind: 'moon.SelectableItem'}, {kind: 'moon.ProgressBar'}, {kind: 'moon.Slider'}, {kind: 'moon.Spinner'}, {kind: 'moon.BodyText'}, {kind: 'moon.LabeledTextItem'}, {kind: 'moon.ImageItem'}, {kind: 'moon.Divider'}, {kind: 'moon.ContextualPopupDecorator', components: [ {kind: 'moon.ContextualPopupButton'}, {kind: 'moon.ContextualPopup', components: [{}]} ]} ]} ]} ]} ] }); window.moon = window.moon || {}; moon.initContainer = function () { var initializer = new moon.ContainerInitializer(); initializer.renderInto(document.body); initializer.destroy(); }; })(enyo, this);
(function (enyo, scope) { enyo.kind({ name: 'moon.ContainerInitializer', components: [ {kind: 'moon.Drawers', drawers: [{}], components: [ {kind: 'moon.Panels', pattern: 'activity', components: [ {components: [ {kind: 'moon.TooltipDecorator', components: [{kind: 'moon.Button'},{kind: 'moon.Tooltip'}]}, {kind: 'moon.ToggleButton'}, {kind: 'moon.ToggleItem'}, {kind: 'moon.FormCheckbox'}, {kind: 'moon.Image'}, {kind: 'moon.SelectableItem'}, {kind: 'moon.ProgressBar'}, {kind: 'moon.Spinner'}, {kind: 'moon.BodyText'}, {kind: 'moon.LabeledTextItem'}, {kind: 'moon.ImageItem'}, {kind: 'moon.Divider'}, {kind: 'moon.ContextualPopupDecorator', components: [ {kind: 'moon.ContextualPopupButton'}, {kind: 'moon.ContextualPopup', components: [{}]} ]} ]} ]} ]} ] }); window.moon = window.moon || {}; moon.initContainer = function () { var initializer = new moon.ContainerInitializer(); initializer.renderInto(document.body); initializer.destroy(); }; })(enyo, this);
Remove moon.Slider from set of pre-[initialized, rendered, destroyed] controls.
ENYO-373: Remove moon.Slider from set of pre-[initialized, rendered, destroyed] controls. Enyo-DCO-1.1-Signed-off-by: Aaron Tam <aaron.tam@lge.com>
JavaScript
apache-2.0
mcanthony/moonstone,mcanthony/moonstone,mcanthony/moonstone,enyojs/moonstone
--- +++ @@ -12,7 +12,6 @@ {kind: 'moon.Image'}, {kind: 'moon.SelectableItem'}, {kind: 'moon.ProgressBar'}, - {kind: 'moon.Slider'}, {kind: 'moon.Spinner'}, {kind: 'moon.BodyText'}, {kind: 'moon.LabeledTextItem'},
120371b68002767acad1310860cbfaecef5dfd7d
server/routes/schema-info.js
server/routes/schema-info.js
require('../typedefs'); const router = require('express').Router(); const mustHaveConnectionAccess = require('../middleware/must-have-connection-access.js'); const ConnectionClient = require('../lib/connection-client'); const wrap = require('../lib/wrap'); /** * @param {Req} req * @param {Res} res */ async function getSchemaInfo(req, res) { const { models, user } = req; const { connectionId } = req.params; const reload = req.query.reload === 'true'; const conn = await models.connections.findOneById(connectionId); if (!conn) { return res.utils.notFound(); } const connectionClient = new ConnectionClient(conn, user); const schemaCacheId = connectionClient.getSchemaCacheId(); let schemaInfo = await models.schemaInfo.getSchemaInfo(schemaCacheId); if (schemaInfo && !reload) { return res.utils.data(schemaInfo); } schemaInfo = await connectionClient.getSchema(); if (Object.keys(schemaInfo).length) { await models.schemaInfo.saveSchemaInfo(schemaCacheId, schemaInfo); } return res.utils.data(schemaInfo); } router.get( '/api/schema-info/:connectionId', mustHaveConnectionAccess, wrap(getSchemaInfo) ); module.exports = router;
require('../typedefs'); const router = require('express').Router(); const mustHaveConnectionAccess = require('../middleware/must-have-connection-access.js'); const ConnectionClient = require('../lib/connection-client'); const wrap = require('../lib/wrap'); /** * @param {Req} req * @param {Res} res */ async function getSchemaInfo(req, res) { const { models, user } = req; const { connectionId } = req.params; const reload = req.query.reload === 'true'; const conn = await models.connections.findOneById(connectionId); if (!conn) { return res.utils.notFound(); } const connectionClient = new ConnectionClient(conn, user); const schemaCacheId = connectionClient.getSchemaCacheId(); let schemaInfo = await models.schemaInfo.getSchemaInfo(schemaCacheId); if (schemaInfo && !reload) { return res.utils.data(schemaInfo); } try { schemaInfo = await connectionClient.getSchema(); } catch (error) { // Assumption is that error is due to user configuration // letting it bubble up results in 500, but it should be 400 return res.utils.error(error); } if (Object.keys(schemaInfo).length) { await models.schemaInfo.saveSchemaInfo(schemaCacheId, schemaInfo); } return res.utils.data(schemaInfo); } router.get( '/api/schema-info/:connectionId', mustHaveConnectionAccess, wrap(getSchemaInfo) ); module.exports = router;
Send schema info error as 400
Send schema info error as 400 This assume schema info failure is due to user input, not application code. This could be that the server is unavailable however. Regardless it is something to be expected as opposed to an internal server error
JavaScript
mit
rickbergfalk/sqlpad,rickbergfalk/sqlpad,rickbergfalk/sqlpad
--- +++ @@ -28,7 +28,14 @@ return res.utils.data(schemaInfo); } - schemaInfo = await connectionClient.getSchema(); + try { + schemaInfo = await connectionClient.getSchema(); + } catch (error) { + // Assumption is that error is due to user configuration + // letting it bubble up results in 500, but it should be 400 + return res.utils.error(error); + } + if (Object.keys(schemaInfo).length) { await models.schemaInfo.saveSchemaInfo(schemaCacheId, schemaInfo); }
3869efee28f86209ba9bb692d9f70c63f1b3bc8c
share/spice/youtube/spice.js
share/spice/youtube/spice.js
function ddg_spice_youtube(api_result) { "use strict"; DDG.require("/js/nryt.js", { success: function() { window.iqyt = 2; ddgyt.nryt(api_result); } }); }
function ddg_spice_youtube(api_result) { "use strict"; DDG.load("/js/nryt.js", { success: function() { window.iqyt = 2; ddgyt.nryt(api_result); } }); }
Use DDG.load instead of DDG.require on the YouTube plugin.
Use DDG.load instead of DDG.require on the YouTube plugin. - DDG.require was renamed to DDG.load.
JavaScript
apache-2.0
digit4lfa1l/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,stennie/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,deserted/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,levaly/zeroclickinfo-spice,ppant/zeroclickinfo-spice,lerna/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,mayo/zeroclickinfo-spice,deserted/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,deserted/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,soleo/zeroclickinfo-spice,levaly/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,lerna/zeroclickinfo-spice,P71/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,sevki/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,lerna/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,soleo/zeroclickinfo-spice,imwally/zeroclickinfo-spice,echosa/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,imwally/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,soleo/zeroclickinfo-spice,ppant/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,stennie/zeroclickinfo-spice,imwally/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,stennie/zeroclickinfo-spice,soleo/zeroclickinfo-spice,ppant/zeroclickinfo-spice,lerna/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,sevki/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,soleo/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,levaly/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,echosa/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,sevki/zeroclickinfo-spice,deserted/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,lernae/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,loganom/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,levaly/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,P71/zeroclickinfo-spice,imwally/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,lernae/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,deserted/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,levaly/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,lernae/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,mayo/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,loganom/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,mayo/zeroclickinfo-spice,P71/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,imwally/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,stennie/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,loganom/zeroclickinfo-spice,echosa/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,lernae/zeroclickinfo-spice,levaly/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,sevki/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,echosa/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,lernae/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,P71/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,ppant/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,soleo/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,lernae/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,lerna/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,loganom/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,deserted/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,mayo/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,jyounker/zeroclickinfo-spice
--- +++ @@ -1,6 +1,6 @@ function ddg_spice_youtube(api_result) { "use strict"; - DDG.require("/js/nryt.js", { + DDG.load("/js/nryt.js", { success: function() { window.iqyt = 2; ddgyt.nryt(api_result);
1ee9edda855c8570fe016fd4abb1cf6857a0396a
lib/util/badgeVault.js
lib/util/badgeVault.js
'use strict'; const Promise = require('bluebird'); const readFile = Promise.promisify(require('fs').readFile); const stat = Promise.promisify(require('fs').stat); const cache = {}; const badgesDir = `${__dirname}/../../badges`; function info(score, options) { const isUnknown = typeof score !== 'number'; options = Object.assign({ format: 'svg', style: 'flat', revision: 1 }, options); const percentage = !isUnknown ? Math.round(score * 100) : null; const value = !isUnknown ? `${percentage}%` : 'unknown'; const file = `${isUnknown ? 'unknown' : percentage}/${isUnknown ? 'unknown' : percentage}-${options.style}.${options.format}`; return { id: `${file}.rev${options.revision}`, value, filePath: `${badgesDir}/${file}`, isUnknown, }; } function get(score, options) { options = Object.assign({ format: 'svg', style: 'flat' }, options); const badgeInfo = info(score, options); if (cache[badgeInfo.id]) { return cache[badgeInfo.id]; } const promise = cache[badgeInfo.id] = Promise.props(Object.assign(badgeInfo, { buffer: readFile(badgeInfo.filePath), stats: stat(badgeInfo.filePath), })); promise.catch(() => { /* istanbul ignore next */ delete cache[badgeInfo.id]; }); return promise; } module.exports.get = get; module.exports.info = info;
'use strict'; const Promise = require('bluebird'); const readFile = Promise.promisify(require('fs').readFile); const stat = Promise.promisify(require('fs').stat); const cache = {}; const badgesDir = `${__dirname}/../../badges`; function info(score, options) { const isUnknown = typeof score !== 'number'; options = Object.assign({ format: 'svg', style: 'flat', revision: 0 }, options); const percentage = !isUnknown ? Math.round(score * 100) : null; const value = !isUnknown ? `${percentage}%` : 'unknown'; const file = `${isUnknown ? 'unknown' : percentage}/${isUnknown ? 'unknown' : percentage}-${options.style}.${options.format}`; return { id: `${file}.rev${options.revision}`, value, filePath: `${badgesDir}/${file}`, isUnknown, }; } function get(score, options) { options = Object.assign({ format: 'svg', style: 'flat' }, options); const badgeInfo = info(score, options); if (cache[badgeInfo.id]) { return cache[badgeInfo.id]; } const promise = cache[badgeInfo.id] = Promise.props(Object.assign(badgeInfo, { buffer: readFile(badgeInfo.filePath), stats: stat(badgeInfo.filePath), })); promise.catch(() => { /* istanbul ignore next */ delete cache[badgeInfo.id]; }); return promise; } module.exports.get = get; module.exports.info = info;
Change rev option to 0.
Change rev option to 0.
JavaScript
mit
npms-io/npms-badges
--- +++ @@ -10,7 +10,7 @@ function info(score, options) { const isUnknown = typeof score !== 'number'; - options = Object.assign({ format: 'svg', style: 'flat', revision: 1 }, options); + options = Object.assign({ format: 'svg', style: 'flat', revision: 0 }, options); const percentage = !isUnknown ? Math.round(score * 100) : null; const value = !isUnknown ? `${percentage}%` : 'unknown';
184d6265997ef8fd114e0a605a1a2b279c150543
game/game-state-managers/instructionsState.js
game/game-state-managers/instructionsState.js
var instructionsState = { create: function () { _setBackgroundImage('instructions'); battleStateButton = new MenuButton(528, 175, "mainMenuButtons", "mapSelectState", "battleGround", "map", "army1", "army2", "battleButton", 0, 0, 1, 0); campaignStateButton = new MenuButton(528, 275, "mainMenuButtons", "mapSelectState", "campaign", "map", "army1", "army2", "battleButton", 2, 2, 3, 2); } }; function _setBackgroundImage(imgKey) { var logo = game.add.image(0, 0, imgKey); logo.width = game.width; logo.height = game.height; };
var instructionsState = { create: function () { _setBackgroundImage('instructions'); battleStateButton = new MenuButton(175, 500, "mainMenuButtons", "mapSelectState", "battleGround", "map", "army1", "army2", "battleButton", 0, 0, 1, 0); campaignStateButton = new MenuButton(450, 500, "mainMenuButtons", "mapSelectState", "campaign", "map", "army1", "army2", "battleButton", 2, 2, 3, 2); } }; function _setBackgroundImage(imgKey) { var logo = game.add.image(0, 0, imgKey); logo.width = game.width; logo.height = game.height; };
Adjust buttons on instructions page
Adjust buttons on instructions page
JavaScript
mit
JohnP42/Fantasy-Wars,JohnP42/Fantasy-Wars
--- +++ @@ -2,8 +2,8 @@ create: function () { _setBackgroundImage('instructions'); - battleStateButton = new MenuButton(528, 175, "mainMenuButtons", "mapSelectState", "battleGround", "map", "army1", "army2", "battleButton", 0, 0, 1, 0); - campaignStateButton = new MenuButton(528, 275, "mainMenuButtons", "mapSelectState", "campaign", "map", "army1", "army2", "battleButton", 2, 2, 3, 2); + battleStateButton = new MenuButton(175, 500, "mainMenuButtons", "mapSelectState", "battleGround", "map", "army1", "army2", "battleButton", 0, 0, 1, 0); + campaignStateButton = new MenuButton(450, 500, "mainMenuButtons", "mapSelectState", "campaign", "map", "army1", "army2", "battleButton", 2, 2, 3, 2); } };
d92515ee55752ab9054441ac2dc2ae7f2dd7fc07
source/nestedSortableCtrl.js
source/nestedSortableCtrl.js
(function () { 'use strict'; angular.module('ui.nestedSortable') .controller('NestedSortableController', ['$scope', '$attrs', 'nestedSortableConfig', function ($scope, $attrs, nestedSortableConfig) { $scope.sortableElement = null; $scope.sortableModelValue = null; $scope.callbacks = null; $scope.items = []; $scope.initSortable = function(element) { $scope.sortableElement = element; }; $scope.insertSortableItem = function(index, itemModelData, itemScope) { $scope.sortableModelValue.splice(index, 0, itemModelData); $scope.$apply(); }; $scope.initSubItemElement = function(subElement) { subElement.parentScope = $scope; }; $scope.parentItemScope = function() { return $scope.sortableElement.parentItemScope; }; } ]); })();
(function () { 'use strict'; angular.module('ui.nestedSortable') .controller('NestedSortableController', ['$scope', 'nestedSortableConfig', function ($scope, nestedSortableConfig) { $scope.sortableElement = null; $scope.sortableModelValue = null; $scope.callbacks = null; $scope.items = []; $scope.initSortable = function(element) { $scope.sortableElement = element; }; $scope.insertSortableItem = function(index, itemModelData) { console.log($scope.sortableModelValue); $scope.sortableModelValue.splice(index, 0, itemModelData); $scope.$apply(); }; $scope.initSubItemElement = function(subElement) { subElement.parentScope = $scope; }; $scope.parentItemScope = function() { return $scope.sortableElement.parentItemScope; }; } ]); })();
Remove unexisting $attrs provider + unused itemScope parameter
Remove unexisting $attrs provider + unused itemScope parameter
JavaScript
mit
joaocc/angular-ui-tree,TommyM/angular-ui-tree,akshath4u/akkutest,kotmatpockuh/angular-ui-tree,robertdamoc/angular-ui-tree,faceleg/angular-ui-tree,Movideo/angular-ui-tree,fmoliveira/angular-ui-tree,foglerek/angular-ui-tree,BlakeBrown/angular-ui-tree,albi34/angular-ui-tree,zachlysobey/angular-ui-tree,asciicode/angular-ui-tree,TommyM/angular-ui-tree,gamejolt/angular-ui-tree,fgleilsonf/angular-ui-tree,geraldpereira/angular-ui-tree,brandonaaskov/angular-ui-tree,kzganesan/angular-ui-tree,domio/angular-ui-tree,geraldpereira/angular-ui-tree,domio/angular-ui-tree,a-elnajjar/angular-ui-tree,resiliencesw/angular-ui-tree,gamejolt/angular-ui-tree,codeice/angular-ui-tree,midhunsudhakar/test,ajitsonlion/angular-ui-tree,Movideo/angular-ui-tree,Alexn555/angular-ui-tree,multiarc/angular-ui-tree,Rademade/angular-ui-tree,farindra/angular-ui-tree,kotmatpockuh/angular-ui-tree,angular-ui-tree/angular-ui-tree,Vela/angular-ui-tree,multiarc/angular-ui-tree,Vela/angular-ui-tree,a-elnajjar/angular-ui-tree,TonyNguyen101/angular-ui-tree,kzganesan/angular-ui-tree
--- +++ @@ -3,8 +3,8 @@ angular.module('ui.nestedSortable') - .controller('NestedSortableController', ['$scope', '$attrs', 'nestedSortableConfig', - function ($scope, $attrs, nestedSortableConfig) { + .controller('NestedSortableController', ['$scope', 'nestedSortableConfig', + function ($scope, nestedSortableConfig) { $scope.sortableElement = null; $scope.sortableModelValue = null; $scope.callbacks = null; @@ -14,7 +14,8 @@ $scope.sortableElement = element; }; - $scope.insertSortableItem = function(index, itemModelData, itemScope) { + $scope.insertSortableItem = function(index, itemModelData) { + console.log($scope.sortableModelValue); $scope.sortableModelValue.splice(index, 0, itemModelData); $scope.$apply(); };
3d95a7876e938cc9dc7ade149a3b7e4b460f854a
web/src/constants/stocks.js
web/src/constants/stocks.js
const stockIndexRegex = /^([^/]+)\/([^/]+)$/; export const STOCK_INDICES = (process.env.STOCK_INDICES || '') .split(',') .map(code => code.match(stockIndexRegex)) .filter(code => code) .reduce((last, [, code, name]) => ({ ...last, [code]: name }), {}); export const DO_STOCKS_LIST = process.env.SKIP_STOCKS_LIST !== 'true'; export const FAKE_STOCK_PRICES = process.env.FAKE_STOCK_PRICES === 'true'; export const STOCKS_GRAPH_RESOLUTION = 50; export const STOCK_PRICES_DELAY = FAKE_STOCK_PRICES ? 5000 : 10000; // investment rate of return (assumed, per annum) export const FUTURE_INVESTMENT_RATE = 0.1;
const stockIndexRegex = /^([^/]+)\/([^/]+)$/; export const STOCK_INDICES = (process.env.STOCK_INDICES || '') .split(',') .map(code => code.match(stockIndexRegex)) .filter(code => code) .reduce((last, [, code, name]) => ({ ...last, [code]: name }), {}); export const DO_STOCKS_LIST = process.env.DO_STOCKS_LIST !== 'false'; export const FAKE_STOCK_PRICES = process.env.FAKE_STOCK_PRICES === 'true'; export const STOCKS_GRAPH_RESOLUTION = 50; export const STOCK_PRICES_DELAY = FAKE_STOCK_PRICES ? 5000 : 10000; // investment rate of return (assumed, per annum) export const FUTURE_INVESTMENT_RATE = 0.1;
Fix reference to DO_STOCKS_LIST environment variable
Fix reference to DO_STOCKS_LIST environment variable
JavaScript
mit
felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget
--- +++ @@ -9,7 +9,7 @@ [code]: name }), {}); -export const DO_STOCKS_LIST = process.env.SKIP_STOCKS_LIST !== 'true'; +export const DO_STOCKS_LIST = process.env.DO_STOCKS_LIST !== 'false'; export const FAKE_STOCK_PRICES = process.env.FAKE_STOCK_PRICES === 'true'; export const STOCKS_GRAPH_RESOLUTION = 50; export const STOCK_PRICES_DELAY = FAKE_STOCK_PRICES
07ceb4095f62f37ba36b401f8834706f9aeb712a
app.js
app.js
/*jslint node: true*/ "use strict"; var site = require("./lib/scraper").site; site. getRecipeUrls(). then(function (recipeUrls) { return site.getRecipe(recipeUrls[0]); }). then(function (recipe) { console.log(JSON.stringify(recipe)); });
/*jslint node: true*/ "use strict"; var site = require("./lib/scraper").site; site. getRecipeUrls(). then(function (recipeUrls) { return site.getRecipe(recipeUrls[0]); }). then(function (recipe) { console.log(JSON.stringify(recipe)); }). done();
Make sure to call done to end the promise chain
Make sure to call done to end the promise chain
JavaScript
mit
Koekelas/dagelijkse-kost,Koekelas/dagelijkse-kost
--- +++ @@ -11,4 +11,5 @@ }). then(function (recipe) { console.log(JSON.stringify(recipe)); - }); + }). + done();
d859978c912d6a49ca1d87f012647eccdd7378d9
app.js
app.js
const Server = require('./server.heroku.js') const port = (process.env.PORT || 8080) const app = Server.app() /*if (process.env.NODE_ENV !== 'production') { const webpack = require('webpack') const webpackDevMiddleware = require('webpack-dev-middleware') const webpackHotMiddleware = require('webpack-hot-middleware') const config = require('./webpack.dev.config.js') const compiler = webpack(config) app.use(webpackHotMiddleware(compiler)) app.use(webpackDevMiddleware(compiler, { publicPath: config.output.staticPath })) }*/ app.listen(port) console.log('Listening at http://localhost:', port)
const Server = require('./server.heroku.js') const port = (process.env.PORT || 8080) const app = Server.app() if (process.env.NODE_ENV !== 'production') { const webpack = require('webpack') const WebpackDevServer = require('webpack-dev-server'); const config = require('./webpack.config.js') new WebpackDevServer(webpack(config), { publicPath: config.output.publicPath, hot: true, historyApiFallback: true }).listen(port, 'localhost', function(err, res) { if (err) { return console.log(err); } console.log('Listening at http://localhost:', port) }) } else { app.listen(port) console.log('Listening at http://localhost:', port) }
Consolidate dev and prod server initialization
Consolidate dev and prod server initialization
JavaScript
mit
kngroo/Kngr,kngroo/Kngr
--- +++ @@ -2,18 +2,23 @@ const port = (process.env.PORT || 8080) const app = Server.app() -/*if (process.env.NODE_ENV !== 'production') { +if (process.env.NODE_ENV !== 'production') { const webpack = require('webpack') - const webpackDevMiddleware = require('webpack-dev-middleware') - const webpackHotMiddleware = require('webpack-hot-middleware') - const config = require('./webpack.dev.config.js') - const compiler = webpack(config) + const WebpackDevServer = require('webpack-dev-server'); + const config = require('./webpack.config.js') - app.use(webpackHotMiddleware(compiler)) - app.use(webpackDevMiddleware(compiler, { - publicPath: config.output.staticPath - })) -}*/ + new WebpackDevServer(webpack(config), { + publicPath: config.output.publicPath, + hot: true, + historyApiFallback: true + }).listen(port, 'localhost', function(err, res) { + if (err) { + return console.log(err); + } + console.log('Listening at http://localhost:', port) + }) +} else { + app.listen(port) + console.log('Listening at http://localhost:', port) +} -app.listen(port) -console.log('Listening at http://localhost:', port)
2a6d614b453c545bce4c8a8b0ef9d7548554c74b
app.js
app.js
var config = require('./config'); var express = require('express'); var bodyParser = require('body-parser'); var winston = require('winston'); winston.add(winston.transports.File, { filename: 'info.log', level: 'info' }); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { level: 'info' }); var statusHandler = require('./routes/status'); var telegramHandler = require('./routes/telegram'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/status', statusHandler); app.post('/telegramBot', telegramHandler); var server = app.listen(config.SERVER_PORT, function () { var host = server.address().address; var port = server.address().port; winston.info('server listening at http://%s:%s', host, port); });
var config = require('./config'); var express = require('express'); var bodyParser = require('body-parser'); var winston = require('winston'); winston.add(winston.transports.File, { filename: 'info.log', level: 'info' }); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { level: 'info' }); var statusHandler = require('./routes/status'); var logHandler = require('./routes/log'); var telegramHandler = require('./routes/telegram'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/status', statusHandler); app.post('/telegramBot', telegramHandler); app.use(express.static()); var server = app.listen(config.SERVER_PORT, function () { var host = server.address().address; var port = server.address().port; winston.info('server listening at http://%s:%s', host, port); });
Test serving static log file.
Test serving static log file.
JavaScript
mit
membersheep/4bot
--- +++ @@ -7,7 +7,7 @@ winston.add(winston.transports.Console, { level: 'info' }); var statusHandler = require('./routes/status'); - +var logHandler = require('./routes/log'); var telegramHandler = require('./routes/telegram'); var app = express(); @@ -17,6 +17,7 @@ app.get('/status', statusHandler); app.post('/telegramBot', telegramHandler); +app.use(express.static()); var server = app.listen(config.SERVER_PORT, function () { var host = server.address().address;
d927134ca685dcdadfafbea6a732cb95120399ff
app.js
app.js
const discord = require('discord.js'); const fs = require('fs'); const yaml = require('js-yaml'); const client = new discord.Client({ fetchAllMembers: true, messageCacheMaxSize: 100000 }); if (fs.existsSync('./config.yml')) { var config = yaml.safeLoad(fs.readFileSync('./config.yml', 'utf8')); } else { throw new Error("config.yml does not exist! Check README.md for a config template.") } client.on('ready', () => { console.log('Ready event emitted.'); }); client.login(config.token);
const discord = require('discord.js'); const fs = require('fs'); const yaml = require('js-yaml'); const client = new discord.Client({ fetchAllMembers: true, messageCacheMaxSize: 100000 }); if (fs.existsSync('./config.yml')) { var config = yaml.safeLoad(fs.readFileSync('./config.yml', 'utf8')); } else { throw new Error("config.yml does not exist! Check README.md for a config template.") } client.on('ready', () => { console.log('Ready event emitted.'); }); client.on('debug', console.log); client.on('error', console.error); client.on('warn', console.warn); client.on('disconnect', console.warn); client.login(config.token);
Add some basic error logging
Add some basic error logging
JavaScript
mit
IanMurray/AnnuBot
--- +++ @@ -17,4 +17,9 @@ console.log('Ready event emitted.'); }); +client.on('debug', console.log); +client.on('error', console.error); +client.on('warn', console.warn); +client.on('disconnect', console.warn); + client.login(config.token);
75534b5dca41c6e5a36b34094ce50d72a23a3889
app.js
app.js
var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); var path = require('path'); var game = require('./game.js'); server.listen(3000, function() { console.log("listening on port 3000"); }); app.set('views', path.join(__dirname, 'templates')); app.set('view engine', 'jade'); app.get('/', function(req, res) { var state0 = game.getInitialState() res.render('index', state0); })
var express = require('express'); var http = require('http'); var socketIO = require('socket.io'); var path = require('path'); var game = require('./game.js'); var app = express(); var server = http.Server(app); var io = socketIO(server); app.set('views', path.join(__dirname, 'templates')); app.set('view engine', 'jade'); app.get('/', function(req, res) { var state0 = game.getInitialState() res.render('index', state0); }) server.listen(3000, function() { console.log("listening on port 3000"); });
Rename imports to get access to express
Rename imports to get access to express
JavaScript
mit
vakila/net-set,vakila/net-set
--- +++ @@ -1,12 +1,12 @@ -var app = require('express')(); -var server = require('http').Server(app); -var io = require('socket.io')(server); +var express = require('express'); +var http = require('http'); +var socketIO = require('socket.io'); var path = require('path'); var game = require('./game.js'); -server.listen(3000, function() { - console.log("listening on port 3000"); -}); +var app = express(); +var server = http.Server(app); +var io = socketIO(server); app.set('views', path.join(__dirname, 'templates')); app.set('view engine', 'jade'); @@ -15,3 +15,7 @@ var state0 = game.getInitialState() res.render('index', state0); }) + +server.listen(3000, function() { + console.log("listening on port 3000"); +});
cc41abb3c8ea389bdf526c3fcafbc83b5b2a1785
cli.js
cli.js
#!/usr/bin/env node 'use strict'; var meow = require('meow'); var w3counter = require('./'); var cli = meow({ help: [ 'Usage', ' $ w3counter <type>', '', 'Example', ' $ w3counter browser', ' $ w3counter country', ' $ w3counter os', ' $ w3counter res' ].join('\n') }); if (!cli.input.length) { console.error([ 'Provide a type', '', 'Example', ' $ w3counter browser', ' $ w3counter country', ' $ w3counter os', ' $ w3counter res' ].join('\n')); process.exit(1); } w3counter(cli.input, function (err, types) { if (err) { console.error(err.message); process.exit(1); } types.forEach(function (type, i) { i = i + 1; console.log(i + '. ' + type.item); }); });
#!/usr/bin/env node 'use strict'; var meow = require('meow'); var w3counter = require('./'); var cli = meow({ help: [ 'Usage', ' $ w3counter <type>', '', 'Example', ' $ w3counter browser', ' $ w3counter country', ' $ w3counter os', ' $ w3counter res' ].join('\n') }); if (!cli.input.length) { console.error([ 'Provide a type', '', 'Example', ' $ w3counter browser', ' $ w3counter country', ' $ w3counter os', ' $ w3counter res' ].join('\n')); process.exit(1); } w3counter(cli.input, function (err, types) { if (err) { console.error(err.message); process.exit(1); } types.forEach(function (type, i) { i = i + 1; console.log(i + '. ' + type.item + ' (' + type.percent + ')'); }); });
Add percentage to CLI output
Add percentage to CLI output
JavaScript
mit
kevva/w3counter
--- +++ @@ -39,6 +39,6 @@ types.forEach(function (type, i) { i = i + 1; - console.log(i + '. ' + type.item); + console.log(i + '. ' + type.item + ' (' + type.percent + ')'); }); });
b5351acc81211a1f57362ed02283e8215a7feca3
src/components/posts_show.js
src/components/posts_show.js
import React from 'react'; import connect from 'react-redux'; import { fetchPost } from '../actions'; class PostsShow extends React.Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } render() { return ( <div> Posts Show </div> ) } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(null, { fetchPost })(PostsShow);
import React from 'react'; import connect from 'react-redux'; import { fetchPost } from '../actions'; class PostsShow extends React.Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } render() { const { post } = this.props; return ( <div> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ) } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(null, { fetchPost })(PostsShow);
Add basic markup of single post
Add basic markup of single post
JavaScript
mit
monsteronfire/redux-learning-blog,monsteronfire/redux-learning-blog
--- +++ @@ -9,9 +9,13 @@ } render() { + const { post } = this.props; + return ( <div> - Posts Show + <h3>{post.title}</h3> + <h6>Categories: {post.categories}</h6> + <p>{post.content}</p> </div> ) }
6d4640854d6842b3c283cea18efd4a5f008d5121
packages/core/module.js
packages/core/module.js
/** * @copyright 2016-2019, Miles Johnson * @license https://opensource.org/licenses/MIT */ // Our index re-exports TypeScript types, which Babel is unable to detect and omit. // Because of this, Webpack and other bundlers attempt to import values that do not exist. // To mitigate this issue, we need this module specific index file that manually exports. import Interweave from './esm/Interweave'; import Markup from './esm/Markup'; import Filter from './esm/Filter'; import Matcher from './esm/Matcher'; export { Markup, Filter, Matcher }; export default Interweave;
/** * @copyright 2016-2019, Miles Johnson * @license https://opensource.org/licenses/MIT */ // Our index re-exports TypeScript types, which Babel is unable to detect and omit. // Because of this, Webpack and other bundlers attempt to import values that do not exist. // To mitigate this issue, we need this module specific index file that manually exports. import Interweave from './esm/Interweave'; import Markup from './esm/Markup'; import Filter from './esm/Filter'; import Matcher from './esm/Matcher'; import Element from './esm/Element'; import Parser from './esm/Parser'; export { Markup, Filter, Matcher, Element, Parser }; export default Interweave;
Add Element and Parser to esm index.
Add Element and Parser to esm index.
JavaScript
mit
milesj/interweave,milesj/interweave,milesj/interweave
--- +++ @@ -11,7 +11,9 @@ import Markup from './esm/Markup'; import Filter from './esm/Filter'; import Matcher from './esm/Matcher'; +import Element from './esm/Element'; +import Parser from './esm/Parser'; -export { Markup, Filter, Matcher }; +export { Markup, Filter, Matcher, Element, Parser }; export default Interweave;
e3726db6f132c4c170c892da74a542f9967bc1ff
server/migrations/20180201131052-create-shares.js
server/migrations/20180201131052-create-shares.js
'use strict' var Sequelize = require('sequelize') var tableName = 'Shares' var schema = { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, sharer: { type: Sequelize.INTEGER, allowNull: false }, sharee: { type: Sequelize.INTEGER, allowNull: false } } module.exports = { up: async function (queryInterface, Sequelize) { if (queryInterface.sequelize.options.dialect !== 'postgres') return await queryInterface.createTable(tableName, schema) }, down: async function (queryInterface, Sequelize) { if (queryInterface.sequelize.options.dialect !== 'postgres') return await queryInterface.dropTable(tableName) } }
'use strict' var Sequelize = require('sequelize') var tableName = 'Shares' var schema = { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, sharer: { type: Sequelize.INTEGER, allowNull: false }, sharee: { type: Sequelize.INTEGER, allowNull: false } } module.exports = { up: async function (queryInterface, Sequelize) { await queryInterface.createTable(tableName, schema) }, down: async function (queryInterface, Sequelize) { await queryInterface.dropTable(tableName) } }
Enable shares migration for all databases
Enable shares migration for all databases
JavaScript
agpl-3.0
BspbOrg/smartbirds-server,BspbOrg/smartbirds-server,BspbOrg/smartbirds-server
--- +++ @@ -22,12 +22,10 @@ module.exports = { up: async function (queryInterface, Sequelize) { - if (queryInterface.sequelize.options.dialect !== 'postgres') return await queryInterface.createTable(tableName, schema) }, down: async function (queryInterface, Sequelize) { - if (queryInterface.sequelize.options.dialect !== 'postgres') return await queryInterface.dropTable(tableName) } }
0cb7904353a5b900e026d22df28a0357acad58b0
server/services/signup/hooks/getSignupAndEvent.js
server/services/signup/hooks/getSignupAndEvent.js
const config = require('../../../../config/ilmomasiina.config'); // eslint-disable-line const md5 = require('md5'); module.exports = () => (hook) => { const models = hook.app.get('models'); const id = hook.id; const editToken = hook.params.query.editToken; if (editToken !== md5(`${`${hook.id}`}${config.editTokenSalt}`)) { throw new Error('Invalid editToken'); } return models.signup .findOne({ where: { id, }, }) .then(signup => models.quota .findOne({ where: { id: signup.quotaId, }, }) .then(quota => models.event .findOne({ where: { id: quota.eventId, }, }) .then((event) => { hook.result = { signup, event, }; return hook; }), ), ); };
const _ = require('lodash'); const config = require('../../../../config/ilmomasiina.config'); // eslint-disable-line const md5 = require('md5'); module.exports = () => (hook) => { const models = hook.app.get('models'); const id = hook.id; const editToken = hook.params.query.editToken; const fields = []; const userAnswers = []; if (editToken !== md5(`${`${hook.id}`}${config.editTokenSalt}`)) { throw new Error('Invalid editToken'); } return models.answer .findAll({ where: { signupId: id } }) .then(answers => answers.map(answer => userAnswers.push(answer.dataValues))) .then(() => models.signup .findOne({ where: { id, }, }) .then(signup => { if (signup === null) { // Event not found with id, probably deleted hook.result = { signup, event: null, }; return hook; } return models.quota .findOne({ where: { id: signup.quotaId, }, }) .then(quota => models.event .findOne({ where: { id: quota.eventId, }, }) .then((event) => event.getQuestions().then((questions) => { questions.map((question) => { const answer = _.find(userAnswers, { questionId: question.id }); if (answer) { fields.push({ ...question.dataValues, answer: answer.answer, answerId: answer.id, }); } }); hook.result = { signup: { ...signup.dataValues, answers: fields }, event, }; return hook; }), ), ); }), ); };
Add necessary data to server response and improve error handling
Add necessary data to server response and improve error handling
JavaScript
mit
athenekilta/ilmomasiina,athenekilta/ilmomasiina
--- +++ @@ -1,3 +1,4 @@ +const _ = require('lodash'); const config = require('../../../../config/ilmomasiina.config'); // eslint-disable-line const md5 = require('md5'); @@ -5,38 +6,64 @@ const models = hook.app.get('models'); const id = hook.id; const editToken = hook.params.query.editToken; + const fields = []; + const userAnswers = []; if (editToken !== md5(`${`${hook.id}`}${config.editTokenSalt}`)) { throw new Error('Invalid editToken'); } - return models.signup - .findOne({ - where: { - id, - }, - }) - .then(signup => - models.quota - .findOne({ - where: { - id: signup.quotaId, - }, - }) - .then(quota => - models.event - .findOne({ - where: { - id: quota.eventId, - }, - }) - .then((event) => { - hook.result = { - signup, - event, - }; - return hook; - }), - ), + return models.answer + .findAll({ where: { signupId: id } }) + .then(answers => answers.map(answer => userAnswers.push(answer.dataValues))) + .then(() => models.signup + .findOne({ + where: { + id, + }, + }) + .then(signup => { + if (signup === null) { // Event not found with id, probably deleted + hook.result = { + signup, + event: null, + }; + return hook; + } + return models.quota + .findOne({ + where: { + id: signup.quotaId, + }, + }) + .then(quota => + models.event + .findOne({ + where: { + id: quota.eventId, + }, + }) + .then((event) => + event.getQuestions().then((questions) => { + questions.map((question) => { + const answer = _.find(userAnswers, { questionId: question.id }); + + if (answer) { + fields.push({ + ...question.dataValues, + answer: answer.answer, + answerId: answer.id, + }); + } + }); + hook.result = { + signup: { ...signup.dataValues, answers: fields }, + event, + }; + return hook; + }), + ), + ); + }), ); };
d0768e1473108f14abeb9d2d29fdbceae87caf94
playground/parseMson.js
playground/parseMson.js
import protagonist from 'protagonist'; export default function parseMson(mson, cb) { protagonist.parse(mson.trim(), (err, parseResult) => { let dataStructureElements; if (err) { return cb(err); } dataStructureElements = parseResult.content[0].content; dataStructureElements = dataStructureElements.map((element) => { if (element.content && element.content[0] && element.content[0].content) { return element.content[0].content[0]; } return null; }); return cb(null, dataStructureElements); }); }
import protagonist from 'protagonist'; export default function parseMson(mson, cb) { protagonist.parse(mson.trim(), (err, parseResult) => { let dataStructureElements; if (err) { return cb(err); } dataStructureElements = parseResult.content[0].content[0].content; dataStructureElements = dataStructureElements.map((element) => element.content[0] ); return cb(null, dataStructureElements); }); }
Send a list of all data structure elements.
Send a list of all data structure elements.
JavaScript
mit
apiaryio/attributes-kit,apiaryio/attributes-kit,apiaryio/attributes-kit
--- +++ @@ -8,14 +8,12 @@ return cb(err); } - dataStructureElements = parseResult.content[0].content; - dataStructureElements = dataStructureElements.map((element) => { - if (element.content && element.content[0] && element.content[0].content) { - return element.content[0].content[0]; - } - return null; - }); + dataStructureElements = parseResult.content[0].content[0].content; + + dataStructureElements = dataStructureElements.map((element) => + element.content[0] + ); return cb(null, dataStructureElements); });
58d6977d32d96b19bbf76d51f5612313b29fdc4a
src/plugins/plugin-shim.js
src/plugins/plugin-shim.js
/** * Add shim config for configuring the dependencies and exports for * older, traditional "browser globals" scripts that do not use define() * to declare the dependencies and set a module value. */ (function(seajs, global) { // seajs.config({ // shim: { // "jquery": { // src: "lib/jquery.js", // exports: "jQuery" or function // }, // "jquery.easing": { // src: "lib/jquery.easing.js", // deps: ["jquery"] // } // }) seajs.on("config", onConfig) onConfig(seajs.config.data) function onConfig(data) { if (!data) return var shim = data.shim for (var id in shim) { (function(item) { // Set dependencies item.deps && define(item.src, item.deps) // Define the proxy cmd module define(id, [item.src], function() { var exports = item.exports return typeof exports === "function" ? exports() : typeof exports === "string" ? global[exports] : exports }) })(shim[id]) } } })(seajs, this);
/** * Add shim config for configuring the dependencies and exports for * older, traditional "browser globals" scripts that do not use define() * to declare the dependencies and set a module value. */ (function(seajs, global) { // seajs.config({ // shim: { // "jquery": { // src: "lib/jquery.js", // exports: "jQuery" or function // }, // "jquery.easing": { // src: "lib/jquery.easing.js", // deps: ["jquery"] // } // }) seajs.on("config", onConfig) onConfig(seajs.config.data) function onConfig(data) { if (!data) return var shim = data.shim for (var id in shim) { (function(item) { // Set dependencies item.deps && define(item.src, item.deps) // Define the proxy cmd module define(id, [item.src], function() { var exports = item.exports return typeof exports === "function" ? exports() : typeof exports === "string" ? global[exports] : exports }) })(shim[id]) } } })(seajs, typeof global === "undefined" ? this : global);
Fix a bug in Node.js
Fix a bug in Node.js
JavaScript
mit
LzhElite/seajs,Lyfme/seajs,seajs/seajs,miusuncle/seajs,imcys/seajs,tonny-zhang/seajs,miusuncle/seajs,lianggaolin/seajs,eleanors/SeaJS,evilemon/seajs,wenber/seajs,eleanors/SeaJS,treejames/seajs,coolyhx/seajs,MrZhengliang/seajs,JeffLi1993/seajs,uestcNaldo/seajs,Gatsbyy/seajs,liupeng110112/seajs,Lyfme/seajs,kuier/seajs,MrZhengliang/seajs,PUSEN/seajs,kaijiemo/seajs,judastree/seajs,tonny-zhang/seajs,evilemon/seajs,zaoli/seajs,baiduoduo/seajs,moccen/seajs,kaijiemo/seajs,zaoli/seajs,sheldonzf/seajs,angelLYK/seajs,baiduoduo/seajs,coolyhx/seajs,ysxlinux/seajs,longze/seajs,kaijiemo/seajs,imcys/seajs,moccen/seajs,treejames/seajs,coolyhx/seajs,lianggaolin/seajs,121595113/seajs,JeffLi1993/seajs,tonny-zhang/seajs,zwh6611/seajs,yern/seajs,seajs/seajs,AlvinWei1024/seajs,lovelykobe/seajs,FrankElean/SeaJS,FrankElean/SeaJS,jishichang/seajs,hbdrawn/seajs,MrZhengliang/seajs,zwh6611/seajs,treejames/seajs,Lyfme/seajs,kuier/seajs,chinakids/seajs,121595113/seajs,lovelykobe/seajs,twoubt/seajs,liupeng110112/seajs,longze/seajs,wenber/seajs,chinakids/seajs,mosoft521/seajs,yern/seajs,sheldonzf/seajs,FrankElean/SeaJS,JeffLi1993/seajs,13693100472/seajs,lovelykobe/seajs,longze/seajs,zaoli/seajs,uestcNaldo/seajs,judastree/seajs,Gatsbyy/seajs,zwh6611/seajs,twoubt/seajs,PUSEN/seajs,yuhualingfeng/seajs,sheldonzf/seajs,lee-my/seajs,jishichang/seajs,eleanors/SeaJS,PUSEN/seajs,twoubt/seajs,moccen/seajs,ysxlinux/seajs,hbdrawn/seajs,AlvinWei1024/seajs,LzhElite/seajs,wenber/seajs,jishichang/seajs,AlvinWei1024/seajs,LzhElite/seajs,angelLYK/seajs,uestcNaldo/seajs,lee-my/seajs,miusuncle/seajs,yern/seajs,baiduoduo/seajs,judastree/seajs,angelLYK/seajs,lee-my/seajs,Gatsbyy/seajs,ysxlinux/seajs,lianggaolin/seajs,imcys/seajs,yuhualingfeng/seajs,evilemon/seajs,13693100472/seajs,liupeng110112/seajs,kuier/seajs,mosoft521/seajs,yuhualingfeng/seajs,seajs/seajs,mosoft521/seajs
--- +++ @@ -42,5 +42,5 @@ } } -})(seajs, this); +})(seajs, typeof global === "undefined" ? this : global);
c8aefb887e233ad064db33ba87fe6b83a7b67338
test/grunt-accessibility_test.js
test/grunt-accessibility_test.js
'use strict'; var grunt = require('grunt'); exports.accessibilityTests = { matchReports: function(test) { var actual; var expected; test.expect(2); actual = grunt.file.read('reports/txt/test.txt'); expected = grunt.file.read('test/expected/txt/test.txt'); test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); actual = grunt.file.read('reports/json/test.json'); expected = grunt.file.read('test/expected/json/test.json'); test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); // actual = grunt.file.read('reports/csv/test.csv'); // expected = grunt.file.read('test/expected/csv/test.csv'); // test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); test.done(); } };
'use strict'; var grunt = require('grunt'); function readFile(file) { var contents = grunt.file.read(file); if (process.platform === 'win32') { contents = contents.replace(/\r\n/g, '\n'); } return contents; } exports.accessibilityTests = { matchReports: function(test) { var actual; var expected; test.expect(2); actual = readFile('reports/txt/test.txt'); expected = readFile('test/expected/txt/test.txt'); test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); actual = readFile('reports/json/test.json'); expected = readFile('test/expected/json/test.json'); test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); // actual = readFile('reports/csv/test.csv'); // expected = readFile('test/expected/csv/test.csv'); // test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); test.done(); } };
Fix tests on Windows with autocrlf on.
Fix tests on Windows with autocrlf on.
JavaScript
mit
yargalot/grunt-accessibility,yargalot/grunt-accessibility
--- +++ @@ -1,6 +1,16 @@ 'use strict'; var grunt = require('grunt'); + +function readFile(file) { + var contents = grunt.file.read(file); + + if (process.platform === 'win32') { + contents = contents.replace(/\r\n/g, '\n'); + } + + return contents; +} exports.accessibilityTests = { matchReports: function(test) { @@ -10,16 +20,16 @@ test.expect(2); - actual = grunt.file.read('reports/txt/test.txt'); - expected = grunt.file.read('test/expected/txt/test.txt'); + actual = readFile('reports/txt/test.txt'); + expected = readFile('test/expected/txt/test.txt'); test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); - actual = grunt.file.read('reports/json/test.json'); - expected = grunt.file.read('test/expected/json/test.json'); + actual = readFile('reports/json/test.json'); + expected = readFile('test/expected/json/test.json'); test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); - // actual = grunt.file.read('reports/csv/test.csv'); - // expected = grunt.file.read('test/expected/csv/test.csv'); + // actual = readFile('reports/csv/test.csv'); + // expected = readFile('test/expected/csv/test.csv'); // test.equal(actual, expected, 'Should produce a default report without DOM element for a test file'); test.done();
8341dad7f0ca21d296253c8668f99d9c27b9f175
app/models/virtualMachines.js
app/models/virtualMachines.js
/*global Backbone*/ var URL = require('./URL'); var VirtualMachine = require('./virtualMachine'); //define a collection of virtual machines module.exports = Backbone.Collection.extend({ model: VirtualMachine, url: URL.virtualMachine });
/*global Backbone*/ //Dependencies. var URL = require('./URL'); var VirtualMachine = require('./virtualMachine'); //define a collection of virtual machines module.exports = Backbone.Collection.extend({ //A collection only need a model property in order to _Type_ each element of the collection. model: VirtualMachine, //The url will be use in order to do all the [CRUD](http://en.wikipedia.org/wiki/Create,_read,_update_and_delete) // operations on the model with the REST api. All operations will only exchange json between client and server.s url: URL.virtualMachine });
Add the comments on the Virtual machine collection.
Add the comments on the Virtual machine collection.
JavaScript
mit
KleeGroup/front-end-spa,pierr/front-end-spa,pierr/front-end-spa,KleeGroup/front-end-spa
--- +++ @@ -1,9 +1,13 @@ /*global Backbone*/ +//Dependencies. var URL = require('./URL'); var VirtualMachine = require('./virtualMachine'); //define a collection of virtual machines module.exports = Backbone.Collection.extend({ + //A collection only need a model property in order to _Type_ each element of the collection. model: VirtualMachine, + //The url will be use in order to do all the [CRUD](http://en.wikipedia.org/wiki/Create,_read,_update_and_delete) + // operations on the model with the REST api. All operations will only exchange json between client and server.s url: URL.virtualMachine });
63743241a188b427c061bea2dc4572a208567daa
troposphere/static/js/components/modals/instance/launch/components/AdvancedOptionsFooter.react.js
troposphere/static/js/components/modals/instance/launch/components/AdvancedOptionsFooter.react.js
import React from 'react'; export default React.createClass({ render: function() { let saveOptionsDisabled = this.props.saveOptionsDisabled ? "disabled" : ""; return ( <div className="modal-footer"> <button type="button" disabled={this.props.saveOptionsDisabled} className="btn btn-primary pull-right" onClick={this.props.onSaveAdvanced} > Save Advanced Options </button> <button type="button" className="btn btn-default pull-right" style={{marginRight:"10px"}} onClick={this.props.cancel} > Cancel Advanced Options </button> </div> ) } });
import React from 'react'; import Button from 'components/common/ui/Button.react'; export default React.createClass({ render: function() { let saveOptionsDisabled = this.props.saveOptionsDisabled ? "disabled" : ""; return ( <div className="modal-footer"> <Button style={{float:"right"}} isDisabled={this.props.saveOptionsDisabled} buttonType="default" title="Continue to Launch" onTouch={this.props.onSaveAdvanced} /> <Button tooltip={{ title: "Warning, any changes to Advanced Options will be lost", placement: "top" }} style={{ marginRight:"10px", float:"right" }} icon="refresh" buttonType="link" title="Restore Advaced Options" onTouch={this.props.onClearAdvanced} /> </div> ) } });
Refactor to use new button and add tooltip message
Refactor to use new button and add tooltip message
JavaScript
apache-2.0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
--- +++ @@ -1,24 +1,33 @@ import React from 'react'; +import Button from 'components/common/ui/Button.react'; export default React.createClass({ + render: function() { let saveOptionsDisabled = this.props.saveOptionsDisabled ? "disabled" : ""; return ( <div className="modal-footer"> - <button type="button" - disabled={this.props.saveOptionsDisabled} - className="btn btn-primary pull-right" - onClick={this.props.onSaveAdvanced} - > - Save Advanced Options - </button> - <button type="button" - className="btn btn-default pull-right" - style={{marginRight:"10px"}} - onClick={this.props.cancel} - > - Cancel Advanced Options - </button> + <Button + style={{float:"right"}} + isDisabled={this.props.saveOptionsDisabled} + buttonType="default" + title="Continue to Launch" + onTouch={this.props.onSaveAdvanced} + /> + <Button + tooltip={{ + title: "Warning, any changes to Advanced Options will be lost", + placement: "top" + }} + style={{ + marginRight:"10px", + float:"right" + }} + icon="refresh" + buttonType="link" + title="Restore Advaced Options" + onTouch={this.props.onClearAdvanced} + /> </div> ) }
4d11031607c718fb0ede81562c36b0e6cf50af13
src/reducers/aboutReducer.js
src/reducers/aboutReducer.js
import * as actions from '../constants/actionTypes'; export default function(state = {}, action) { switch(action.type) { case actions.ABOUT_FETCH: return Object.assign(...state, action.payload.data); default: return state; } }
import * as actions from '../constants/actionTypes'; import initialState from './initialState'; export default function(state = initialState.about, action) { switch(action.type) { case actions.ABOUT_FETCH: return Object.assign(...state, action.payload.data); default: return state; } }
Update about reducer to use initial state
Update about reducer to use initial state
JavaScript
mit
veryaustin/veryaustin-2017-frontend,veryaustin/veryaustin-2017-frontend
--- +++ @@ -1,6 +1,7 @@ import * as actions from '../constants/actionTypes'; +import initialState from './initialState'; -export default function(state = {}, action) { +export default function(state = initialState.about, action) { switch(action.type) { case actions.ABOUT_FETCH: return Object.assign(...state, action.payload.data);
679ce7c3942f7b6d150653ba3a8e9cfda3af1b99
extensions/tools/targets/myCreeps.js
extensions/tools/targets/myCreeps.js
'use strict'; var all = false; var cache = {}; function getCache(room) { if (all === false) { all = []; for (var i in Game.creeps) { if (!Game.creeps.spawning) { if (cache[Game.creeps[i].room] === undefined) { cache[Game.creeps[i].room] = [Game.creeps[i]]; } else { cache[Game.creeps[i].room].push(Game.creeps[i]); } } all.push(Game.creeps[i]); } } if (room === undefined) { return all; } if (cache[room] === undefined) { return []; } return cache[room]; } function get(room, options) { if (options === undefined) { options = {}; } return getCache(room); } function filter(creep, options) { options = options || {}; return { filter: function(obj) { if (!(obj instanceof Creep)) { return false; } if (obj.my !== true) { return false; } if (options.spawningOnly === true) { return creep.spawning === true; } if (options.spawning !== true) { return creep.spawning === false; } return true; } }; } module.exports = { get: get, filter: filter };
'use strict'; var all = false; var cache = {}; function getCache(room) { if (all === false) { all = []; for (var i in Game.creeps) { if (!Game.creeps.spawning) { if (cache[Game.creeps[i].room.name] === undefined) { cache[Game.creeps[i].room.name] = [Game.creeps[i]]; } else { cache[Game.creeps[i].room.name].push(Game.creeps[i]); } } all.push(Game.creeps[i]); } } if (room === undefined) { return all; } if (room instanceof Room) { room = room.name; } if (cache[room] === undefined) { return []; } return cache[room]; } function get(room, options) { if (options === undefined) { options = {}; } return getCache(room); } function filter(creep, options) { options = options || {}; return { filter: function(obj) { if (!(obj instanceof Creep)) { return false; } if (obj.my !== true) { return false; } if (options.spawningOnly === true) { return creep.spawning === true; } if (options.spawning !== true) { return creep.spawning === false; } return true; } }; } module.exports = { get: get, filter: filter };
Use room name as string, instead as object for key value
Use room name as string, instead as object for key value
JavaScript
mit
avdg/screeps
--- +++ @@ -8,10 +8,10 @@ all = []; for (var i in Game.creeps) { if (!Game.creeps.spawning) { - if (cache[Game.creeps[i].room] === undefined) { - cache[Game.creeps[i].room] = [Game.creeps[i]]; + if (cache[Game.creeps[i].room.name] === undefined) { + cache[Game.creeps[i].room.name] = [Game.creeps[i]]; } else { - cache[Game.creeps[i].room].push(Game.creeps[i]); + cache[Game.creeps[i].room.name].push(Game.creeps[i]); } } all.push(Game.creeps[i]); @@ -20,6 +20,10 @@ if (room === undefined) { return all; + } + + if (room instanceof Room) { + room = room.name; } if (cache[room] === undefined) {
7cf0a253819661c84e593d4a8dade96d1f4f253c
ghost/admin/controllers/forgotten.js
ghost/admin/controllers/forgotten.js
/* jshint unused: false */ import ajax from 'ghost/utils/ajax'; import ValidationEngine from 'ghost/mixins/validation-engine'; var ForgottenController = Ember.Controller.extend(ValidationEngine, { email: '', submitting: false, // ValidationEngine settings validationType: 'forgotten', actions: { submit: function () { var self = this, data = self.getProperties('email'); this.toggleProperty('submitting'); this.validate({ format: false }).then(function () { ajax({ url: self.get('ghostPaths.url').api('authentication', 'passwordreset'), type: 'POST', data: { passwordreset: [{ email: data.email }] } }).then(function (resp) { self.toggleProperty('submitting'); self.notifications.showSuccess('Please check your email for instructions.'); self.transitionToRoute('signin'); }).catch(function (resp) { self.toggleProperty('submitting'); self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.'); }); }).catch(function (errors) { self.toggleProperty('submitting'); self.notifications.showErrors(errors); }); } } }); export default ForgottenController;
/* jshint unused: false */ import ajax from 'ghost/utils/ajax'; import ValidationEngine from 'ghost/mixins/validation-engine'; var ForgottenController = Ember.Controller.extend(ValidationEngine, { email: '', submitting: false, // ValidationEngine settings validationType: 'forgotten', actions: { submit: function () { var self = this, data = self.getProperties('email'); this.toggleProperty('submitting'); this.validate({ format: false }).then(function () { ajax({ url: self.get('ghostPaths.url').api('authentication', 'passwordreset'), type: 'POST', data: { passwordreset: [{ email: data.email }] } }).then(function (resp) { self.toggleProperty('submitting'); self.notifications.showSuccess('Please check your email for instructions.'); self.transitionToRoute('signin'); }).catch(function (resp) { self.toggleProperty('submitting'); self.notifications.closePassive(); self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.'); }); }).catch(function (errors) { self.toggleProperty('submitting'); self.notifications.closePassive(); self.notifications.showErrors(errors); }); } } }); export default ForgottenController;
Stop validation error notification stack
Stop validation error notification stack closes #3383 - Calls closePassive() if a new validation error is thrown to display only the latest validation error
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
--- +++ @@ -30,10 +30,12 @@ self.transitionToRoute('signin'); }).catch(function (resp) { self.toggleProperty('submitting'); + self.notifications.closePassive(); self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.'); }); }).catch(function (errors) { self.toggleProperty('submitting'); + self.notifications.closePassive(); self.notifications.showErrors(errors); }); }
4d491cc111a7084cae7069b26f597e7993acafa4
web/app/themes/theme/assets/ng/events/directives/preview.directive.js
web/app/themes/theme/assets/ng/events/directives/preview.directive.js
angular .module('events.preview.directive', ['ui.router']) .directive('eventPreview', function () { return { restrict: 'E', replace: true, template: '<div class="event-preview__item">'+ '<div class="event-preview__image-overlay event-preview__image-overlay--gradient"></div>' + '<div class="event-preview__image-overlay event-preview__image-overlay--solid"></div>' + '<div class="event-preview__content">'+ '<span class="event-preview__year">{{ year }}</span>' + '<h2 class="event-preview__title o-heading c-heading--event-preview">{{ title }}</h2>' + '</div>'+ '</div>', scope: { image: '@', title: '@', year: '@', slug: '@' }, link: function (scope, element, attr) { element.css('background-image', 'url('+attr.image+')'); } }; });
angular .module('events.preview.directive', ['ui.router']) .directive('eventPreview', function () { return { restrict: 'E', replace: true, template: '<div class="event-preview__item">'+ '<div class="event-preview__image-overlay event-preview__image-overlay--gradient"></div>' + '<div class="event-preview__image-overlay event-preview__image-overlay--solid"></div>' + '<div class="event-preview__content">'+ '<span class="event-preview__year">{{ year }}</span>' + '<h2 class="event-preview__title o-heading c-heading--event-preview">{{ title }}</h2>' + '</div>'+ '</div>', scope: { image: '@', title: '@', year: '@', slug: '@' }, link: function (scope, element, attr) { var imgArr = attr.image.split('.'); imgArr[imgArr.length-2] += '-250x250'; var previewImgPath = imgArr.join('.'); element.css('background-image', 'url('+ previewImgPath +')'); } }; });
Fix the preview image size
Fix the preview image size
JavaScript
mit
rslnk/reimagine-belonging,rslnk/reimagine-belonging,rslnk/reimagine-belonging
--- +++ @@ -19,7 +19,12 @@ slug: '@' }, link: function (scope, element, attr) { - element.css('background-image', 'url('+attr.image+')'); + var imgArr = attr.image.split('.'); + imgArr[imgArr.length-2] += '-250x250'; + var previewImgPath = imgArr.join('.'); + + element.css('background-image', 'url('+ previewImgPath +')'); + } }; });
01b7581484ef5ec3e020a4da099e6407b5744a76
assets/js/modules/analytics/common/account-create/create-account-field.js
assets/js/modules/analytics/common/account-create/create-account-field.js
/** * CreateAccountField component. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ /** * Internal dependencies */ import { Input, TextField, } from '../../../../material-components'; import classnames from 'classnames'; export default function CreateAccountField( { hasError, value, setValue, name, label, } ) { if ( 'undefined' === typeof value ) { return null; } return ( <TextField className={ classnames( 'mdc-text-field', { 'mdc-text-field--error': hasError } ) } label={ label } name={ name } onChange={ ( e ) => { setValue( e.target.value, name ); } } outlined required > <Input name={ name } value={ value } /> </TextField> ); }
/** * CreateAccountField component. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ /** * Internal dependencies */ import { Input, TextField, } from '../../../../material-components'; import classnames from 'classnames'; export default function CreateAccountField( { hasError, value, setValue, name, label, } ) { if ( 'undefined' === typeof value ) { return null; } return ( <TextField className={ classnames( 'mdc-text-field', { 'mdc-text-field--error': hasError } ) } label={ label } name={ name } onChange={ ( event ) => { setValue( event.target.value, name ); } } outlined required > <Input name={ name } value={ value } /> </TextField> ); }
Change event parameter name from `e` to `event`.
Change event parameter name from `e` to `event`.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -44,8 +44,8 @@ ) } label={ label } name={ name } - onChange={ ( e ) => { - setValue( e.target.value, name ); + onChange={ ( event ) => { + setValue( event.target.value, name ); } } outlined required
630f21ebededd3ab940137187925c47af789f2c6
realtime/index.js
realtime/index.js
const io = require('socket.io'), winston = require('winston'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, {'timestamp': true}); const PORT = 3031; winston.info('Rupture real-time service starting'); winston.info('Listening on port ' + PORT); var socket = io.listen(PORT); socket.on('connection', function(client) { winston.info('New connection from client ' + client.id); client.on('get-work', function() { winston.info('get-work from client ' + client.id); client.emit('do-work', { url: 'https://facebook.com/?breach-test', amount: 1000, timeout: 0 }); }); client.on('work-completed', function({work, success, host}) { winston.info('Client indicates work completed: ', work, success, host); }); client.on('disconnect', function() { winston.info('Client ' + client.id + ' disconnected'); }); });
const io = require('socket.io'), winston = require('winston'), http = require('http'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, {'timestamp': true}); const PORT = 3031; winston.info('Rupture real-time service starting'); winston.info('Listening on port ' + PORT); var socket = io.listen(PORT); const options = { host: 'localhost', port: '8000' }; socket.on('connection', function(client) { winston.info('New connection from client ' + client.id); client.on('get-work', function() { winston.info('get-work from client ' + client.id); var getWorkOptions = options; getWorkOptions['path'] = '/breach/get_work'; http.request(getWorkOptions, function(response) { var res = ''; response.on('data', function(chunk) { res += chunk; }); response.on('end', function() { winston.info('Got (get-work) response from backend: ' + res); }); }).end(); client.emit('do-work', { url: 'https://facebook.com/?breach-test', amount: 1000, timeout: 0 }); }); client.on('work-completed', function({work, success, host}) { winston.info('Client indicates work completed: ', work, success, host); }); client.on('disconnect', function() { winston.info('Client ' + client.id + ' disconnected'); }); });
Add get-work request from realtime to backend
Add get-work request from realtime to backend
JavaScript
mit
esarafianou/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dionyziz/rupture,dimkarakostas/rupture
--- +++ @@ -1,5 +1,6 @@ const io = require('socket.io'), - winston = require('winston'); + winston = require('winston'), + http = require('http'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, {'timestamp': true}); @@ -11,11 +12,29 @@ var socket = io.listen(PORT); +const options = { + host: 'localhost', + port: '8000' +}; + socket.on('connection', function(client) { winston.info('New connection from client ' + client.id); client.on('get-work', function() { winston.info('get-work from client ' + client.id); + + var getWorkOptions = options; + getWorkOptions['path'] = '/breach/get_work'; + http.request(getWorkOptions, function(response) { + var res = ''; + response.on('data', function(chunk) { + res += chunk; + }); + response.on('end', function() { + winston.info('Got (get-work) response from backend: ' + res); + }); + }).end(); + client.emit('do-work', { url: 'https://facebook.com/?breach-test', amount: 1000,
7b9419174ef72b0ff19dd60657272d894d5fd165
games/common/js/submit_score.js
games/common/js/submit_score.js
function submit_score(score) { auth_data = get_auth_data() submit_data = auth_data + "&" + score call_api("set_score", submit_data) } function get_auth_data() { hash = window.location.hash return hash.substring(1, hash.indexOf("&")) } function call_api(name, data) { request = new XMLHttpRequest() request.open("POST", "https://cgb.ohbah.com:4343/cgbapi/" + name) request.send(window.location.hash) }
function submit_score(score) { auth_data = get_auth_data() submit_data = auth_data + "&" + score call_api("set_score", submit_data) } function get_auth_data() { hash = window.location.hash auth_data = hash.substring(1) additionalDataStart = auth_data.indexOf("&") if (additionalDataStart > 0) { auth_data = auth_data.substring(0, additionalDataStart) } return auth_data } function call_api(name, data) { request = new XMLHttpRequest() request.open("POST", "https://cgb.ohbah.com:4343/cgbapi/" + name) request.send(window.location.hash) }
Fix get_auth_data when no additional data on hash
Fix get_auth_data when no additional data on hash
JavaScript
apache-2.0
alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games
--- +++ @@ -6,7 +6,12 @@ function get_auth_data() { hash = window.location.hash - return hash.substring(1, hash.indexOf("&")) + auth_data = hash.substring(1) + additionalDataStart = auth_data.indexOf("&") + if (additionalDataStart > 0) { + auth_data = auth_data.substring(0, additionalDataStart) + } + return auth_data } function call_api(name, data) {
e743fab34e49352d902d8b027252bf013e039b40
snippet.js
snippet.js
(function (instanceName) { var i, s, z, w = window, d = document, q = 'script', f = ['config', 'track', 'identify', 'push', 'call'], c = function () { var self = this; self._e = []; for (i = 0; i < f.length; i++) { (function (f) { self[f] = function () { // need to do this so params get called properly self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; // check if instance of tracker exists w._w[instanceName] = w[instanceName] = w[instanceName] || new c(); // insert tracker script s = d.createElement(q); s.async = 1; s.src = '//static.woopra.com/js/wpt.js?v=3.0.2'; z = d.getElementsByTagName(q)[0]; z.parentNode.insertBefore(s, z); })('woopra');
(function (instanceName) { var i, s, z, w = window, d = document, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function () { var self = this; self._e = []; for (i = 0; i < f.length; i++) { (function (f) { self[f] = function () { // need to do this so params get called properly self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; // check if instance of tracker exists w._w[instanceName] = w[instanceName] = w[instanceName] || new c(); // insert tracker script s = d.createElement(q); s.async = 1; s.src = '//static.woopra.com/js/wpt.min.js?v=3.0.3'; z = d.getElementsByTagName(q)[0]; z.parentNode.insertBefore(s, z); })('woopra');
Add 'visit' to tracker stub
Add 'visit' to tracker stub
JavaScript
mit
Woopra/js-client-tracker,Woopra/js-client-tracker
--- +++ @@ -5,7 +5,7 @@ w = window, d = document, q = 'script', - f = ['config', 'track', 'identify', 'push', 'call'], + f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function () { var self = this; self._e = []; @@ -26,7 +26,7 @@ // insert tracker script s = d.createElement(q); s.async = 1; - s.src = '//static.woopra.com/js/wpt.js?v=3.0.2'; + s.src = '//static.woopra.com/js/wpt.min.js?v=3.0.3'; z = d.getElementsByTagName(q)[0]; z.parentNode.insertBefore(s, z); })('woopra');
1194543426bba9f5620423f53920a0eaf96e1601
client/mobilizations/paths.js
client/mobilizations/paths.js
import DefaultConfigServer from '~server/config' export const mobilizations = () => '/' export const mobilization = (mobilization, domain = DefaultConfigServer.appDomain) => { if (domain && domain.indexOf('staging') !== -1) { return `http://${mobilization.slug}.${domain}` } return mobilization.custom_domain ? `http://${mobilization.custom_domain}` : `http://${mobilization.slug}.${domain}` } export const mobilizationLaunch = id => `/mobilizations/${id}/launch` export const newMobilization = () => '/mobilizations/new' export const editMobilization = id => `/mobilizations/${id}/edit` export const basicsMobilization = id => `/mobilizations/${id}/basics` export const cityMobilization = id => `/mobilizations/${id}/city` export const cityNewMobilization = id => `/mobilizations/${id}/cityNew` export const sharingMobilization = id => `/mobilizations/${id}/sharing` export const analyticsMobilization = id => `/mobilizations/${id}/analytics` export const customDomainMobilization = id => `/mobilizations/${id}/customDomain`
import DefaultConfigServer from '~server/config' export const mobilizations = () => '/mobilizations' export const mobilization = (mobilization, domain = DefaultConfigServer.appDomain) => { if (domain && domain.indexOf('staging') !== -1) { return `http://${mobilization.slug}.${domain}` } return mobilization.custom_domain ? `http://${mobilization.custom_domain}` : `http://${mobilization.slug}.${domain}` } export const mobilizationLaunch = id => `/mobilizations/${id}/launch` export const newMobilization = () => '/mobilizations/new' export const editMobilization = id => `/mobilizations/${id}/edit` export const basicsMobilization = id => `/mobilizations/${id}/basics` export const cityMobilization = id => `/mobilizations/${id}/city` export const cityNewMobilization = id => `/mobilizations/${id}/cityNew` export const sharingMobilization = id => `/mobilizations/${id}/sharing` export const analyticsMobilization = id => `/mobilizations/${id}/analytics` export const customDomainMobilization = id => `/mobilizations/${id}/customDomain`
Change mobilization root path to /mobilizations
Change mobilization root path to /mobilizations
JavaScript
agpl-3.0
nossas/bonde-client,nossas/bonde-client,nossas/bonde-client
--- +++ @@ -1,6 +1,6 @@ import DefaultConfigServer from '~server/config' -export const mobilizations = () => '/' +export const mobilizations = () => '/mobilizations' export const mobilization = (mobilization, domain = DefaultConfigServer.appDomain) => { if (domain && domain.indexOf('staging') !== -1) { return `http://${mobilization.slug}.${domain}`
d9d6e8e84f038a08d4bdbf33256f7cf8f9d23cd0
src/app.js
src/app.js
(function (window) { 'use strict'; var hearingTest = HearingTest; var hearing = hearingTest.init(); var app = new Vue({ el: '#hearing-test-app', data: { frequency: 1000 }, methods: { changeFrequency: function() { hearing.sound.frequency.value = this.frequency; } } }); }(window));
(function (window) { 'use strict'; var hearingTest = HearingTest; var hearing = hearingTest.init(); var app = new Vue({ el: '#hearing-test-app', data: { isPlaySound: false, frequency: 1000 }, methods: { changeFrequency: function() { hearing.sound.frequency.value = this.frequency; } } }); }(window));
Add a play sound flag
Add a play sound flag
JavaScript
mit
kubosho/hearing-test-app
--- +++ @@ -7,6 +7,7 @@ var app = new Vue({ el: '#hearing-test-app', data: { + isPlaySound: false, frequency: 1000 }, methods: {
aaa8f64c4ce06e67dc078cb417e085499fb4504d
scripts/views/quizz-view.js
scripts/views/quizz-view.js
var QuizzListView = Backbone.View.extend({ el: '#app', templateHandlebars: Handlebars.compile( $('#play-template-handlebars').html() ), remove: function() { this.$el.empty(); return this; }, initialize: function() { console.log('Initialize in quizz view'); this.myQuizzCollection = new QuizzCollection(); var self = this; this.myQuizzCollection.fetch({ success: function(data) { self.render(); }, error: function(error) { console.log('Error while fetching quizz: ', error); } }); }, render: function() { this.$el.html( this.templateHandlebars(this.myQuizzCollection.toJSON()) ); } });
var QuizzListView = Backbone.View.extend({ el: '#app', templateHandlebars: Handlebars.compile( $('#play-template-handlebars').html() ), remove: function() { this.$el.empty(); return this; }, shuffleArray: function (o){ for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; }, initialize: function() { console.log('Initialize in quizz view'); this.myQuizzCollection = new QuizzCollection(); var self = this; this.myQuizzCollection.fetch({ success: function(data) { // Shuffle the data and store it self.quizzList = self.shuffleArray(self.myQuizzCollection.toJSON()); self.render(); }, error: function(error) { console.log('Error while fetching quizz: ', error); } }); }, render: function() { this.$el.html( this.templateHandlebars(this.quizzList) ); } });
Add random on quizz list
Add random on quizz list
JavaScript
mit
KillianKemps/MovieQuizz,KillianKemps/MovieQuizz
--- +++ @@ -11,6 +11,11 @@ return this; }, + shuffleArray: function (o){ + for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); + return o; + }, + initialize: function() { console.log('Initialize in quizz view'); this.myQuizzCollection = new QuizzCollection(); @@ -19,17 +24,20 @@ this.myQuizzCollection.fetch({ success: function(data) { + // Shuffle the data and store it + self.quizzList = self.shuffleArray(self.myQuizzCollection.toJSON()); self.render(); }, error: function(error) { console.log('Error while fetching quizz: ', error); } }); + }, render: function() { this.$el.html( - this.templateHandlebars(this.myQuizzCollection.toJSON()) + this.templateHandlebars(this.quizzList) ); } });
11f7957362867684b2e30c70944f3496fc6f99b6
renderer/index.js
renderer/index.js
require('./patches/gherkin') require('./keyboard/bindings') const electron = require('electron') const Cucumber = require('cucumber') const Options = require('../cli/options') const Output = require('./output') const output = new Output() const options = new Options(electron.remote.process.argv) process.on('unhandledRejection', function(reason) { output.write(reason.message + "\n" + reason.stack) exitWithCode(3) }) function exitWithCode(code) { if (options.electronDebug) return electron.remote.getGlobal('console').log("EXITING WITH CODE", code) electron.remote.process.exit(code) } try { const argv = options.cucumberArgv const cwd = process.cwd() const stdout = new Output() new Cucumber.Cli({ argv, cwd, stdout }).run() .then(pass => exitWithCode(pass ? 0 : 1)) } catch (err) { log(err.stack) exitWithCode(2) }
require('./patches/gherkin') require('./keyboard/bindings') const electron = require('electron') const Cucumber = require('cucumber') const Options = require('../cli/options') const Output = require('./output') const output = new Output() const options = new Options(electron.remote.process.argv) process.on('unhandledRejection', function(reason) { output.write(reason.message + "\n" + reason.stack) exitWithCode(3) }) function exitWithCode(code) { if (options.electronDebug) return electron.remote.process.exit(code) } try { const argv = options.cucumberArgv const cwd = process.cwd() const stdout = new Output() new Cucumber.Cli({ argv, cwd, stdout }).run() .then(pass => exitWithCode(pass ? 0 : 1)) } catch (err) { log(err.stack) exitWithCode(2) }
Remove console.log about exit code
Remove console.log about exit code
JavaScript
mit
cucumber/cucumber-electron,featurist/cucumber-electron,featurist/cucumber-electron,cucumber/cucumber-electron,cucumber/cucumber-electron,cucumber/cucumber-electron
--- +++ @@ -17,7 +17,6 @@ function exitWithCode(code) { if (options.electronDebug) return - electron.remote.getGlobal('console').log("EXITING WITH CODE", code) electron.remote.process.exit(code) }
6a8cd955389226e749afd36b85641cc08ac54023
feelings/client/lib/router.js
feelings/client/lib/router.js
Router.route('/', function () { this.layout("layout") this.render('feelings'); });
Router.route('/', function () { this.layout("layout") this.render('feelings'); }, {name: 'feelings'}); Router.route('/results', function () { this.layout("layout") this.render('results'); }, {name: 'results'});
Add results route; name routes
Add results route; name routes
JavaScript
agpl-3.0
GeriLife/feelings,GeriLife/feelings
--- +++ @@ -1,4 +1,9 @@ Router.route('/', function () { this.layout("layout") this.render('feelings'); -}); +}, {name: 'feelings'}); + +Router.route('/results', function () { + this.layout("layout") + this.render('results'); +}, {name: 'results'});
f8c11d94e363d8d3c8d571723a85b4087cfbe6fd
src/map.js
src/map.js
function ObjectMap(){ this._obj = {}; } let p = ObjectMap.prototype; p.set = function( key, val ){ this._obj[ key ] = val; }; p.delete = function( key ){ this._obj[ key ] = null; }; p.has = function( key ){ return this._obj[ key ] != null; }; p.get = function( key ){ return this._obj[ key ]; }; // TODO use the stdlib Map in future... // module.exports = typeof Map !== 'undefined' ? Map : ObjectMap; module.exports = ObjectMap;
class ObjectMap { constructor(){ this._obj = {}; } set( key, val ){ this._obj[ key ] = val; return this; } delete( key ){ this._obj[ key ] = undefined; return this; } clear(){ this._obj = {}; } has( key ){ return this._obj[ key ] !== undefined; } get( key ){ return this._obj[ key ]; } } // TODO use the stdlib Map in future... // module.exports = typeof Map !== 'undefined' ? Map : ObjectMap; module.exports = ObjectMap;
Use class syntax for `Map`
Use class syntax for `Map`
JavaScript
mit
cytoscape/cytoscape.js,cytoscape/cytoscape.js
--- +++ @@ -1,24 +1,32 @@ -function ObjectMap(){ - this._obj = {}; +class ObjectMap { + constructor(){ + this._obj = {}; + } + + set( key, val ){ + this._obj[ key ] = val; + + return this; + } + + delete( key ){ + this._obj[ key ] = undefined; + + return this; + } + + clear(){ + this._obj = {}; + } + + has( key ){ + return this._obj[ key ] !== undefined; + } + + get( key ){ + return this._obj[ key ]; + } } - -let p = ObjectMap.prototype; - -p.set = function( key, val ){ - this._obj[ key ] = val; -}; - -p.delete = function( key ){ - this._obj[ key ] = null; -}; - -p.has = function( key ){ - return this._obj[ key ] != null; -}; - -p.get = function( key ){ - return this._obj[ key ]; -}; // TODO use the stdlib Map in future... // module.exports = typeof Map !== 'undefined' ? Map : ObjectMap;
77e82bf90581e98a95ba5c1f58cf1cbb67e8bdc6
app/config/auth.js
app/config/auth.js
module.exports = { settings: { domain: 'your-domain.auth0.com', clientID: 'your-client-id', clientSecret: 'your-client-secret' }, allow: function(user) { return true; }, };
module.exports = { settings: { domain: 'your-domain.auth0.com', clientID: 'your-client-id', clientSecret: 'your-client-secret' }, allow: function() { return false; }, };
Set default for allow method to be false
Set default for allow method to be false
JavaScript
mit
spleenboy/pallium-cms,spleenboy/pallium-cms
--- +++ @@ -4,7 +4,7 @@ clientID: 'your-client-id', clientSecret: 'your-client-secret' }, - allow: function(user) { - return true; + allow: function() { + return false; }, };
e9b59975ca5b1f3584a3fa0f828e015205be28be
app/controllers.js
app/controllers.js
'use strict'; /* Controllers */ var recordControllers = angular.module('myApp.recordControllers', []); recordControllers.controller('recordCtrl', ['$scope', '$http', '_', function($scope, $http, _) { // Initialize $scope.distance = '25m'; $scope.style = '自由形'; $scope.submit = function() { let config = { params: {} }; if ($scope.name && $scope.name.length > 0) { config.params.name = $scope.name; } if ($scope.distance != '指定なし') { config.params.distance = $scope.distance; } if ($scope.style != '指定なし') { config.params.style = $scope.style; } if ($scope.name) { $http.get('http://localhost:3000/db', config) .success(function(data) { data = _.uniq(data).sort(function(a, b) { if (a.year && b.year && a.year !== b.year) { return a.year - b.year; } else if (a.month && b.month && a.month !== b.month) { return a.month - b.month; } else if (a.day && b.day && a.day !== b.day) { return a.day - b.day; } return 0; }); $scope.records = data; }); } }; } ]);
'use strict'; /* Controllers */ var recordControllers = angular.module('myApp.recordControllers', []); recordControllers.controller('recordCtrl', ['$scope', '$http', '_', function($scope, $http, _) { // Initialize $scope.distance = '25m'; $scope.style = '自由形'; $scope.submit = function() { let config = { params: {} }; if ($scope.name && $scope.name.length > 0) { config.params.name = $scope.name; } if ($scope.distance != '指定なし') { config.params.distance = $scope.distance; } if ($scope.style != '指定なし') { config.params.style = $scope.style; } if ($scope.name) { $http.get('/db', config) .success(function(data) { data = _.uniq(data).sort(function(a, b) { if (a.year && b.year && a.year !== b.year) { return a.year - b.year; } else if (a.month && b.month && a.month !== b.month) { return a.month - b.month; } else if (a.day && b.day && a.day !== b.day) { return a.day - b.day; } return 0; }); $scope.records = data; }); } }; } ]);
Use relative path for db REST API access
Use relative path for db REST API access
JavaScript
mit
chopstickexe/swimtrack,chopstickexe/swimtrack
--- +++ @@ -23,7 +23,7 @@ config.params.style = $scope.style; } if ($scope.name) { - $http.get('http://localhost:3000/db', config) + $http.get('/db', config) .success(function(data) { data = _.uniq(data).sort(function(a, b) { if (a.year && b.year && a.year !== b.year) {
b3cb93f4b798e08841d9681cf06a783bab62de41
examples/main-page/main.js
examples/main-page/main.js
window.onload = function() { d3.json("../examples/data/gitstats.json", function(data) { data.forEach(function(d) { d.date = new Date(d.date); d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name; }); var dataset = {data: data, metadata: {}}; var commitSVG = d3.select("#intro-chart"); sizeSVG(commitSVG); commitChart(commitSVG, dataset); var scatterFullSVG = d3.select("#scatter-full"); sizeSVG(scatterFullSVG); scatterFull(scatterFullSVG, dataset); var lineSVG = d3.select("#line-chart"); sizeSVG(lineSVG); lineChart(lineSVG, dataset); }); } function sizeSVG(svg) { var width = svg.node().clientWidth; var height = Math.min(width*.75, 600); svg.attr("height", height); }
window.onload = function() { d3.json("examples/data/gitstats.json", function(data) { data.forEach(function(d) { d.date = new Date(d.date); d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name; }); var dataset = {data: data, metadata: {}}; var commitSVG = d3.select("#intro-chart"); sizeSVG(commitSVG); commitChart(commitSVG, dataset); var scatterFullSVG = d3.select("#scatter-full"); sizeSVG(scatterFullSVG); scatterFull(scatterFullSVG, dataset); var lineSVG = d3.select("#line-chart"); sizeSVG(lineSVG); lineChart(lineSVG, dataset); }); } function sizeSVG(svg) { var width = svg.node().clientWidth; var height = Math.min(width*.75, 600); svg.attr("height", height); }
Fix it gau! oh godgp
Fix it gau! oh godgp
JavaScript
mit
palantir/plottable,gdseller/plottable,jacqt/plottable,danmane/plottable,RobertoMalatesta/plottable,RobertoMalatesta/plottable,iobeam/plottable,gdseller/plottable,iobeam/plottable,NextTuesday/plottable,palantir/plottable,softwords/plottable,palantir/plottable,danmane/plottable,RobertoMalatesta/plottable,NextTuesday/plottable,jacqt/plottable,softwords/plottable,alyssaq/plottable,gdseller/plottable,alyssaq/plottable,danmane/plottable,onaio/plottable,jacqt/plottable,iobeam/plottable,alyssaq/plottable,onaio/plottable,onaio/plottable,softwords/plottable,NextTuesday/plottable,palantir/plottable
--- +++ @@ -1,5 +1,5 @@ window.onload = function() { - d3.json("../examples/data/gitstats.json", function(data) { + d3.json("examples/data/gitstats.json", function(data) { data.forEach(function(d) { d.date = new Date(d.date); d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name;
36e6a4eabfe79f7e0df25621e4380ad49697aba7
external-ab-neuter/main.js
external-ab-neuter/main.js
'use strict'; const release_type = process.config.target_defaults.default_configuration; const ab_neuter = require(`./build/${release_type}/ab_neuter`); module.exports = neuter; function neuter(obj) { ab_neuter.neuter(ArrayBuffer.isView(obj) ? obj.buffer : obj); }
'use strict'; const ab_neuter = require('./build/Release/ab_neuter'); module.exports = neuter; function neuter(obj) { ab_neuter.neuter(ArrayBuffer.isView(obj) ? obj.buffer : obj); }
Support Release only to simplify webpack
Support Release only to simplify webpack
JavaScript
mit
silklabs/silk,silklabs/silk,silklabs/silk,silklabs/silk,silklabs/silk,silklabs/silk
--- +++ @@ -1,7 +1,6 @@ 'use strict'; -const release_type = process.config.target_defaults.default_configuration; -const ab_neuter = require(`./build/${release_type}/ab_neuter`); +const ab_neuter = require('./build/Release/ab_neuter'); module.exports = neuter;
18ebe527e06ffb04d22da5491d7dde5b40943a1c
packages/truffle-core/lib/testing/deployed.js
packages/truffle-core/lib/testing/deployed.js
// Using web3 for its sha function... var Web3 = require("web3"); var Deployed = { makeSolidityDeployedAddressesLibrary: function(mapping) { var self = this; var source = ""; source += "pragma solidity ^0.4.6; \n\n library DeployedAddresses {" + "\n"; Object.keys(mapping).forEach(function(name) { var address = mapping[name]; var body = "throw;"; if (address) { address = self.toChecksumAddress(address); body = "return " + address + ";"; } source += " function " + name + "() returns (address) { " + body + " }" source += "\n"; }); source += "}"; return source; }, // Pulled from ethereumjs-util, but I don't want all its dependencies at the moment. toChecksumAddress: function (address) { var web3 = new Web3(); address = address.toLowerCase().replace("0x", ""); var hash = web3.sha3(address).replace("0x", ""); var ret = '0x' for (var i = 0; i < address.length; i++) { if (parseInt(hash[i], 16) >= 8) { ret += address[i].toUpperCase() } else { ret += address[i] } } return ret } }; module.exports = Deployed;
// Using web3 for its sha function... var Web3 = require("web3"); var Deployed = { makeSolidityDeployedAddressesLibrary: function(mapping) { var self = this; var source = ""; source += "pragma solidity ^0.4.6; \n\n library DeployedAddresses {" + "\n"; Object.keys(mapping).forEach(function(name) { var address = mapping[name]; var body = "revert();"; if (address) { address = self.toChecksumAddress(address); body = "return " + address + ";"; } source += " function " + name + "() returns (address) { " + body + " }" source += "\n"; }); source += "}"; return source; }, // Pulled from ethereumjs-util, but I don't want all its dependencies at the moment. toChecksumAddress: function (address) { var web3 = new Web3(); address = address.toLowerCase().replace("0x", ""); var hash = web3.sha3(address).replace("0x", ""); var ret = '0x' for (var i = 0; i < address.length; i++) { if (parseInt(hash[i], 16) >= 8) { ret += address[i].toUpperCase() } else { ret += address[i] } } return ret } }; module.exports = Deployed;
Use revert() instead of throw
Use revert() instead of throw
JavaScript
mit
ConsenSys/truffle
--- +++ @@ -12,7 +12,7 @@ Object.keys(mapping).forEach(function(name) { var address = mapping[name]; - var body = "throw;"; + var body = "revert();"; if (address) { address = self.toChecksumAddress(address);
658ba7209b07bb763e6e93592bfefdde9c9ce78a
server/src/app.js
server/src/app.js
const express = require('express') const bodyParser = require('body-parser') const cors = require('cors') const morgan = require('morgan') const app = express() // Seting up middleware app.use(morgan('combined')) app.use(bodyParser.json()) app.use(cors()) app.get('/', (req, res) => { res.send('Hello world') }) app.get('/status', (req, res) => { res.send({ message: 'Hello world' }) }) app.listen(process.env.PORT || 8081, () => { console.log('Server started at http://127.0.0.1:8081') });
const express = require('express') const bodyParser = require('body-parser') const cors = require('cors') const morgan = require('morgan') const app = express() // Seting up middleware app.use(morgan('combined')) app.use(bodyParser.json()) app.use(cors()) app.get('/', (req, res) => { res.send('Hello world') }) app.get('/status', (req, res) => { res.send({ message: 'Hello world' }) }) app.post('/register', (req, res) => { console.log(req.body); res.send({ message: `User ${req.body.email}! was registered!` }) }) app.listen(process.env.PORT || 8081, () => { console.log('Server started at http://127.0.0.1:8081') });
Test post register response with Postman
Test post register response with Postman
JavaScript
mit
rahman541/tab-tracker,rahman541/tab-tracker
--- +++ @@ -19,6 +19,13 @@ }) }) +app.post('/register', (req, res) => { + console.log(req.body); + res.send({ + message: `User ${req.body.email}! was registered!` + }) +}) + app.listen(process.env.PORT || 8081, () => { console.log('Server started at http://127.0.0.1:8081') });
76c112da2263ea398e5da129e1f9663f727d031e
ember-cli-build.js
ember-cli-build.js
'use strict'; const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); const Project = require('ember-cli/lib/models/project'); module.exports = function(defaults) { let project = Project.closestSync(process.cwd()); project.pkg['ember-addon'].paths = ['sandbox']; defaults.project = project; var app = new EmberAddon(defaults, { project, svgJar: { sourceDirs: [ 'public', 'tests/dummy/public' ] }, 'ember-cli-addon-docs': { projects: { sandbox: { tree: 'sandbox' } } } }); return app.toTree(); };
'use strict'; const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); const Project = require('ember-cli/lib/models/project'); module.exports = function(defaults) { let project = Project.closestSync(process.cwd()); project.pkg['ember-addon'].paths = ['sandbox']; defaults.project = project; var app = new EmberAddon(defaults, { project, vendorFiles: { 'jquery.js': null, 'app-shims.js': null }, svgJar: { sourceDirs: [ 'public', 'tests/dummy/public' ] }, 'ember-cli-addon-docs': { projects: { sandbox: { tree: 'sandbox' } } } }); return app.toTree(); };
Stop including jquery and shims in the output
Stop including jquery and shims in the output
JavaScript
mit
ember-learn/ember-cli-addon-docs,ember-learn/ember-cli-addon-docs,ember-learn/ember-cli-addon-docs
--- +++ @@ -12,6 +12,7 @@ var app = new EmberAddon(defaults, { project, + vendorFiles: { 'jquery.js': null, 'app-shims.js': null }, svgJar: { sourceDirs: [ 'public',
14d9151ba1d0376b1ba9a86761c0aaf9e02d37f6
ember-cli-build.js
ember-cli-build.js
'use strict'; const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { let app = new EmberAddon(defaults, { // Import _all_ Froala Editor files // for the "dummy" app 'ember-froala-editor': { plugins : [ 'align','char_counter','colors','emoticons','entities','font_family','font_size', 'line_breaker','link','lists','paragraph_format','special_characters','table','url' ], languages: false, themes : true }, // Use Bootswatch in the "dummy" app // to resemble the Froala Editor Website 'ember-cli-bootswatch': { theme: 'materia', importJS: ['util','collapse'] } }); /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
'use strict'; const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { let app = new EmberAddon(defaults, { 'ember-froala-editor': { plugins : [ 'align','char_counter','colors','emoticons','entities','font_family','font_size', 'line_breaker','link','lists','paragraph_format','special_characters','table','url' ], languages: false, themes : true }, // Use Bootswatch in the "dummy" app // to resemble the Froala Editor Website 'ember-cli-bootswatch': { theme: 'materia', importJS: ['util','collapse'] } }); /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
Remove comment about importing all plugins
Remove comment about importing all plugins No longer the case
JavaScript
mit
Panman8201/ember-froala-editor,Panman8201/ember-froala-editor,froala/ember-froala-editor,froala/ember-froala-editor
--- +++ @@ -5,8 +5,6 @@ module.exports = function(defaults) { let app = new EmberAddon(defaults, { - // Import _all_ Froala Editor files - // for the "dummy" app 'ember-froala-editor': { plugins : [ 'align','char_counter','colors','emoticons','entities','font_family','font_size',
0f5d2e7a73abf567750489748058a75cb6a4989b
ember-cli-build.js
ember-cli-build.js
/* eslint-env node */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { var app = new EmberAddon(defaults, { // Add options here }); /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
/* eslint-env node */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { var app = new EmberAddon(defaults, { sourcemaps: { enabled: false, extensions: ['js'], } }); /* This build file specifies the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree(); };
Disable source map in dev
Disable source map in dev
JavaScript
mit
masonwan/ember-render-validate,masonwan/ember-render-validate
--- +++ @@ -3,7 +3,10 @@ module.exports = function(defaults) { var app = new EmberAddon(defaults, { - // Add options here + sourcemaps: { + enabled: false, + extensions: ['js'], + } }); /*
e91126a3233e719eedba767dbcc656750ac0f523
app/src/upgrade.js
app/src/upgrade.js
var path = require('path'); var fs = require('fs-extra'); function upgradeNeeded(config, callback) { var oldSyncDir = syncDirWrong(config); var needsUpgrade = oldSyncDir; callback(needsUpgrade); //return oldSyncDir; } function syncDirWrong(config) { for (var r in config.roots) { var oldDir = path.join(r, '.sync'); //console.log('Checking for old dir: ' + oldDir); if (fs.existsSync(oldDir)) { return true; } } return false; } module.exports = upgradeNeeded;
var path = require('path'); var fs = require('fs-extra'); function upgradeNeeded(config, callback) { var oldSyncDir = syncDirWrong(config); var needsUpgrade = oldSyncDir; callback(needsUpgrade); //return oldSyncDir; } function syncDirWrong(config) { for (var r in config.roots) { var oldDir = path.join(r, '.sync'); //console.log('Checking for old dir: ' + oldDir); if (fs.existsSync(oldDir)) { console.log('Please remove ' + oldDir + ' and re-run with "--resync"'); return true; } } return false; } module.exports = upgradeNeeded;
Add help for upgrading to latest version.
Add help for upgrading to latest version.
JavaScript
mit
dynamicdan/filesync,dynamicdan/sn-filesync,Echo3ToEcho7/filesync
--- +++ @@ -16,6 +16,7 @@ var oldDir = path.join(r, '.sync'); //console.log('Checking for old dir: ' + oldDir); if (fs.existsSync(oldDir)) { + console.log('Please remove ' + oldDir + ' and re-run with "--resync"'); return true; } }
90ab18f216757cb67af21d2b28d1da3cf4e8b1b4
source/components/SiteHeader.js
source/components/SiteHeader.js
import React from 'react' import { Link } from 'react-router-dom' import Facebook from '../components/Facebook' import SearchBox from '../components/SearchBox' const SiteHeader = ({ user }) => ( <header className="site-header"> <div className="logo icon-axis"> <Link to="/"><b>Axis</b>RPG</Link> </div> <SearchBox /> <Facebook user={user} /> </header> ) SiteHeader.displayName = 'Header' export default SiteHeader
import React from 'react' import { Link } from 'react-router-dom' import Facebook from '../components/Facebook' import SearchBox from '../components/SearchBox' const SiteHeader = ({ user }) => ( <header className="site-header"> <Link className="logo icon-axis" to="/"> <span className="name"><b>Axis</b>RPG</span> </Link> <SearchBox /> <Facebook user={user} /> </header> ) SiteHeader.displayName = 'Header' export default SiteHeader
Add Axis icon to the clickable area of logo
Add Axis icon to the clickable area of logo
JavaScript
mit
TroyAlford/axis-wiki,TroyAlford/axis-wiki
--- +++ @@ -5,9 +5,9 @@ const SiteHeader = ({ user }) => ( <header className="site-header"> - <div className="logo icon-axis"> - <Link to="/"><b>Axis</b>RPG</Link> - </div> + <Link className="logo icon-axis" to="/"> + <span className="name"><b>Axis</b>RPG</span> + </Link> <SearchBox /> <Facebook user={user} /> </header>
5a26dfebaf9bf2a9604df92f6dd029c43ab9bddc
troposphere/static/js/components/modals/instance_launch/ProjectOption.react.js
troposphere/static/js/components/modals/instance_launch/ProjectOption.react.js
/** @jsx React.DOM */ define( [ 'react', 'backbone' ], function (React, Backbone) { return React.createClass({ propTypes: { project: React.PropTypes.instanceOf(Backbone.Model).isRequired }, render: function () { var projectName = this.props.project.get('name'); if(projectName === "Default") projectName = "Do not add to a project"; return ( <option value={this.props.project.id}> {projectName} </option> ); } }); });
/** @jsx React.DOM */ define( [ 'react', 'backbone' ], function (React, Backbone) { return React.createClass({ propTypes: { project: React.PropTypes.instanceOf(Backbone.Model).isRequired }, render: function () { var project = this.props.project; return ( <option value={project.id}> {project.get('name')} </option> ); } }); });
Remove alternate statement for Default project
Remove alternate statement for Default project
JavaScript
apache-2.0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
--- +++ @@ -14,11 +14,11 @@ }, render: function () { - var projectName = this.props.project.get('name'); - if(projectName === "Default") projectName = "Do not add to a project"; + var project = this.props.project; + return ( - <option value={this.props.project.id}> - {projectName} + <option value={project.id}> + {project.get('name')} </option> ); }
1ea825202a2b67d05e6be5f9fc1cf3009f263764
server/server.js
server/server.js
const express = require('express'); const mongoose = require('mongoose'); const app = express(); mongoose.connect('mongodb://localhost/speechdoctor'); require('./config/middleware')(app, express); require('./config/routes.js')(app); const port = process.env.PORT || 8080; app.listen(port); console.log('Listening on port ', port); module.exports = app;
const express = require('express'); const mongoose = require('mongoose'); const app = express(); mongoose.connect('mongodb://localhost/speechdoctor'); require('./config/middleware')(app, express); require('./config/routes.js')(app); const port = process.env.PORT || 80; app.listen(port); console.log('Listening on port ', port); module.exports = app;
Change port number from 8080 to 80 for deployment
Change port number from 8080 to 80 for deployment
JavaScript
mit
nonchalantkettle/SpeechDoctor,nonchalantkettle/SpeechDoctor,alexxisroxxanne/SpeechDoctor,alexxisroxxanne/SpeechDoctor
--- +++ @@ -8,7 +8,7 @@ require('./config/middleware')(app, express); require('./config/routes.js')(app); -const port = process.env.PORT || 8080; +const port = process.env.PORT || 80; app.listen(port);
30a571553b09a4e221445f9f0292fd9da449c3ce
app/assets/javascripts/student_profile/provided_by_educator_dropdown.js
app/assets/javascripts/student_profile/provided_by_educator_dropdown.js
(function() { window.shared || (window.shared = {}); var dom = window.shared.ReactHelpers.dom; var ProvidedByEducatorDropdown = window.shared.ProvidedByEducatorDropdown = React.createClass({ displayName: 'ProvidedByEducatorDropdown', propTypes: { educatorsForServicesDropdown: React.PropTypes.array.isRequired, onChange: React.PropTypes.func.isRequired, }, render: function () { return dom.input({ className: 'ProvidedByEducatorDropdown', onChange: this.props.onChange, style: { marginTop: 2, fontSize: 14, padding: 4, width: '50%' } }); }, componentDidMount: function() { $(ReactDOM.findDOMNode(this)).autocomplete({ source: this.props.educatorsForServicesDropdown }); }, componentWillUnmount: function() { $(ReactDOM.findDOMNode(this)).autocomplete('destroy'); } }); })();
(function() { window.shared || (window.shared = {}); var dom = window.shared.ReactHelpers.dom; var ProvidedByEducatorDropdown = window.shared.ProvidedByEducatorDropdown = React.createClass({ displayName: 'ProvidedByEducatorDropdown', propTypes: { educatorsForServicesDropdown: React.PropTypes.array.isRequired, onChange: React.PropTypes.func.isRequired, }, render: function () { return dom.input({ className: 'ProvidedByEducatorDropdown', onChange: this.props.onChange, placeholder: 'Last Name, First Name...', style: { marginTop: 2, fontSize: 14, padding: 4, width: '50%' } }); }, componentDidMount: function() { $(ReactDOM.findDOMNode(this)).autocomplete({ source: this.props.educatorsForServicesDropdown }); }, componentWillUnmount: function() { $(ReactDOM.findDOMNode(this)).autocomplete('destroy'); } }); })();
Add placeholder text and suggest Last Name, First Name
Add placeholder text and suggest Last Name, First Name
JavaScript
mit
studentinsights/studentinsights,jhilde/studentinsights,jhilde/studentinsights,jhilde/studentinsights,jhilde/studentinsights,studentinsights/studentinsights,erose/studentinsights,erose/studentinsights,studentinsights/studentinsights,studentinsights/studentinsights,erose/studentinsights,erose/studentinsights
--- +++ @@ -14,6 +14,7 @@ return dom.input({ className: 'ProvidedByEducatorDropdown', onChange: this.props.onChange, + placeholder: 'Last Name, First Name...', style: { marginTop: 2, fontSize: 14,
9b00021f5bf69a6d76e26543a527802319d6cdd3
grunt-tasks/grunt-babel.js
grunt-tasks/grunt-babel.js
module.exports = function gruntBabel(grunt) { grunt.config('babel', { options: { sourceMap: false, modules: 'amd', moduleIds: true, moduleRoot: 'crm', sourceRoot: 'src', blacklist: [ 'strict', ], }, dist: { files: [{ expand: true, cwd: 'src', src: ['**/*.js'], dest: 'src-out', }], }, }); grunt.loadNpmTasks('grunt-babel'); };
module.exports = function gruntBabel(grunt) { grunt.config('babel', { options: { sourceMaps: 'inline', modules: 'amd', moduleIds: true, moduleRoot: 'crm', sourceRoot: 'src', blacklist: [ 'strict', ], }, dist: { files: [{ expand: true, cwd: 'src', src: ['**/*.js'], dest: 'src-out', }], }, }); grunt.loadNpmTasks('grunt-babel'); };
Enable inline sourcemaps for better ES6 debugging.
Enable inline sourcemaps for better ES6 debugging.
JavaScript
apache-2.0
Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix
--- +++ @@ -1,7 +1,7 @@ module.exports = function gruntBabel(grunt) { grunt.config('babel', { options: { - sourceMap: false, + sourceMaps: 'inline', modules: 'amd', moduleIds: true, moduleRoot: 'crm',
8f220780ef56b5b3c010c3368e83a86452ef3042
assets/js/index.js
assets/js/index.js
function ready(fn) { if (document.readyState != 'loading'){ fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } function previousElementSibling( elem ) { do { elem = elem.previousSibling; } while ( elem && elem.nodeType !== 1 ); return elem; } function pullPullQuotes(){ var pullquotes = document.getElementsByClassName('pullquote'); for (var i = 0; i < pullquotes.length; i++) { var el = pullquotes[i]; for (var i = 0; i < 10; i++){ if (el.parentNode.nodeName == "P"){ var parentParagraph = el.parentNode; break; } } if (previousElementSibling(parentParagraph).nodeName == "P"){ parentParagraph = previousElementSibling(parentParagraph); } var newEl = el.cloneNode(true); newEl.classList.add('pullquote--pulled'); newEl.classList.remove('pullquote'); parentParagraph.insertBefore(newEl, parentParagraph.firstChild); } } ready(pullPullQuotes());
function previousElementSibling( elem ) { do { elem = elem.previousSibling; } while ( elem && elem.nodeType !== 1 ); return elem; } function pullPullQuotes(){ var pullquotes = document.getElementsByClassName('pullquote'); for (var i = 0; i < pullquotes.length; i++) { var el = pullquotes[i]; for (var i = 0; i < 10; i++){ if (el.parentNode.nodeName == "P"){ var parentParagraph = el.parentNode; break; } } if (previousElementSibling(parentParagraph).nodeName == "P"){ parentParagraph = previousElementSibling(parentParagraph); } var newEl = el.cloneNode(true); newEl.classList.add('pullquote--pulled'); newEl.classList.remove('pullquote'); parentParagraph.insertBefore(newEl, parentParagraph.firstChild); } } document.addEventListener('DOMContentLoaded', pullPullQuotes());
Simplify js ready function (and make it work…)
Simplify js ready function (and make it work…)
JavaScript
mit
curiositry/mnml-ghost-theme,omphalosskeptic/mnml-ghost-theme,omphalosskeptic/mnml-ghost-theme
--- +++ @@ -1,11 +1,3 @@ -function ready(fn) { - if (document.readyState != 'loading'){ - fn(); - } else { - document.addEventListener('DOMContentLoaded', fn); - } -} - function previousElementSibling( elem ) { do { elem = elem.previousSibling; @@ -33,11 +25,8 @@ } } -ready(pullPullQuotes()); +document.addEventListener('DOMContentLoaded', pullPullQuotes()); - - -
623da4bb405c483555eb97857be9b675437230bb
src/Store.js
src/Store.js
import Reflux from 'reflux'; import Actions from './Actions'; import Handlers from './Handlers'; export default class Store extends Reflux.Store { constructor() { super(); this.state = { retrievingLocation: false, fetchingData: false, radius: process.env.REACT_APP_DEFAULT_RADIUS, address: null, latitude: null, longitude: null, restaurant: null, excludedCategories: [] }; this.handlers = new Handlers(); this.listenables = [Actions]; } onGetCurrentLocation() { this.handlers.getCurrentLocation(this); } onSetCurrentLocation(latitude, longitude) { this.handlers.setCurrentLocation(this, latitude, longitude); } onGetCurrentAddress() { this.handlers.getCurrentAddress(this); } onSetCurrentAddress(address) { this.handlers.setCurrentAddress(this, address); } onSelectRestaurant() { this.handlers.selectRestaurant(this); } onGetRestaurant(id) { this.handlers.getRestaurant(this, id); } onGetDirections() { this.handlers.getDirections(this); } onSetDirectionsLink() { this.handlers.setDirectionsLink(this); } onReduceSearchRadius() { this.handlers.reduceSearchRadius(this); } onExcludeCurrentCategory() { this.handlers.excludeCurrentCategory(this); } }
import Reflux from 'reflux'; import Actions from './Actions'; import Handlers from './Handlers'; export default class Store extends Reflux.Store { constructor() { super(); this.state = { retrievingLocation: false, fetchingData: false, radius: process.env.REACT_APP_DEFAULT_RADIUS, address: null, latitude: null, longitude: null, restaurant: null }; this.handlers = new Handlers(); this.listenables = [Actions]; } onGetCurrentLocation() { this.handlers.getCurrentLocation(this); } onSetCurrentLocation(latitude, longitude) { this.handlers.setCurrentLocation(this, latitude, longitude); } onGetCurrentAddress() { this.handlers.getCurrentAddress(this); } onSetCurrentAddress(address) { this.handlers.setCurrentAddress(this, address); } onSelectRestaurant() { this.handlers.selectRestaurant(this); } onGetRestaurant(id) { this.handlers.getRestaurant(this, id); } onGetDirections() { this.handlers.getDirections(this); } onSetDirectionsLink() { this.handlers.setDirectionsLink(this); } onReduceSearchRadius() { this.handlers.reduceSearchRadius(this); } onExcludeCurrentCategory() { this.handlers.excludeCurrentCategory(this); } }
Remove useless var in store
Remove useless var in store
JavaScript
mit
mdcarter/lunchfinder.io,mdcarter/lunchfinder.io
--- +++ @@ -12,8 +12,7 @@ address: null, latitude: null, longitude: null, - restaurant: null, - excludedCategories: [] + restaurant: null }; this.handlers = new Handlers();
73e797b3b9765455d66cdc7ee9edb67d2e321689
BookShelf.Mobile/views/BookAdd.js
BookShelf.Mobile/views/BookAdd.js
BookShelf.BookAdd = function(params) { return $.extend(BookShelf.BookForm(params), { resetBook: function() { this.book.title(""); this.book.author(""); }, save: function() { BookShelf.db.books.add(this.getBook()); BookShelf.app.back(); }, cancel: function() { BookShelf.app.back(); }, viewShowing: function() { this.resetBook(); } }); return viewModel; };
BookShelf.BookAdd = function(params) { return $.extend(BookShelf.BookForm(params), { resetBook: function() { this.book.title(""); this.book.author(""); this.book.status(params.status); this.book.startDate(new Date()); this.book.finishDate(new Date()); }, save: function() { BookShelf.db.books.add(this.getBook()); BookShelf.app.back(); }, cancel: function() { BookShelf.app.back(); }, viewShowing: function() { this.resetBook(); } }); return viewModel; };
Reset book status and start/finish dates on add form
Views: Reset book status and start/finish dates on add form
JavaScript
mit
tabalinas/BookShelf,tabalinas/BookShelf
--- +++ @@ -5,6 +5,9 @@ resetBook: function() { this.book.title(""); this.book.author(""); + this.book.status(params.status); + this.book.startDate(new Date()); + this.book.finishDate(new Date()); }, save: function() {
7361ad915b14e267ac9848cc3c88f37fd3404849
server/scoring.js
server/scoring.js
// TODO: should the baseScore be stored, and updated at vote time? // This interface should change and become more OO, this'll do for now var Scoring = { // re-run the scoring algorithm on a single object updateObject: function(object) { if(isNaN(object.score)){ object.score=0; } // just count the number of votes for now var baseScore = object.votes; // now multiply by 'age' exponentiated // FIXME: timezones <-- set by server or is getTime() ok? var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000); object.score = baseScore * Math.pow(ageInHours + 2, -0.1375); }, // rerun all the scoring -- TODO: should we check to see if the score has // changed before saving? updateScores: function() { Posts.find().forEach(function(post) { Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); }); Comments.find().forEach(function(comment) { Scoring.updateObject(comment); Comments.update(comment._id, {$set: {score: comment.score}}); }); } } Meteor.Cron = new Cron(); Meteor.Cron.addJob(1, function() { Scoring.updateScores(); })
// TODO: should the baseScore be stored, and updated at vote time? // This interface should change and become more OO, this'll do for now var Scoring = { // re-run the scoring algorithm on a single object updateObject: function(object) { if(isNaN(object.score)){ object.score=0; } // just count the number of votes for now var baseScore = object.votes; // now multiply by 'age' exponentiated // FIXME: timezones <-- set by server or is getTime() ok? var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000); object.score = baseScore * Math.pow(ageInHours + 2, -0.1375); }, // rerun all the scoring -- TODO: should we check to see if the score has // changed before saving? updateScores: function() { Posts.find().forEach(function(post) { Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); }); Comments.find().forEach(function(comment) { Scoring.updateObject(comment); Comments.update(comment._id, {$set: {score: comment.score}}); }); } } // tick every second Meteor.Cron = new Cron(1000); // update scores every 10 seconds Meteor.Cron.addJob(10, function() { Scoring.updateScores(); })
Change to updating every 10s
Change to updating every 10s
JavaScript
mit
IQ2022/Telescope,basehaar/sumocollect,jparyani/Telescope,GeoffAbbott/dfl,STANAPO/Telescope,gzingraf/GreenLight-Pix,Daz2345/dhPulse,sethbonnie/StartupNews,eruwinu/presto,jkuruzovich/projecthunt,TribeMedia/Screenings,Leeibrah/telescope,jonmc12/heypsycho,dima7b/stewardsof,cydoval/Telescope,aichane/digigov,liamdarmody/telescope_app,silky/GitXiv,neynah/Telescope,wangleihd/Telescope,wduntak/tibetalk,SachaG/Gamba,jbschaff/StartupNews,WeAreWakanda/telescope,SachaG/swpsub,jbschaff/StartupNews,em0ney/Telescope,xamfoo/change-route-in-iron-router,yourcelf/Telescope,basemm911/questionsociety,ourcities/conectacao,lewisnyman/Telescope,SSOCIETY/webpages,MallorcaJS/discuss.mallorcajs.com,ibrahimcesar/Screenings,geverit4/Telescope,higgsj/phunt,Tobi2705/telescopedeploy,McBainCO/telescope-apto-news,seanpat09/crebuzz,lambtron/goodwillhunt.org,huaiyudavid/rentech,opendataforgood/dataforgood_restyling,parkeasz/Telescope,julienlapointe/telescope-nova-social-news,Air2air/Telescope,TelescopeJS/CrunchHunt,TribeMedia/Telescope,zandboxapp/zandbox,Discordius/Telescope,Discordius/Telescope,xamfoo/Telescope,crozzfire/hacky,tommytwoeyes/Telescope,tylermalin/Screenings,wojingdaile/Telescope,Bloc/Telescope,nishanbose/Telescope,edjv711/presto,TodoTemplates/Telescope,lewisnyman/Telescope,msavin/Telescope,HelloMeets/HelloMakers,arbfay/Telescope,ryeskelton/Telescope,SwarnaKishore/TechTrendz,dima7b/stewardsof,arbfay/Telescope,nickmke/decibel,flyghtdeck/beta,flyghtdeck/beta,SachaG/fundandexit,mrn3/ldsdiscuss,SachaG/Zensroom,nickmke/decibel,tonyoconnell/nootropics,liamdarmody/telescope_app,tylermalin/Screenings,automenta/sernyl,baptistemac/Telescope,MeteorKorea/MeteorJS_KR,SachaG/fundandexit,sabon/great-balls-of-fire,nikhilno1/Telescope,pombredanne/Telescope,dominictracey/Telescope,veerjainATgmail/Telescope,guillaumj/Telescope,HelloMeets/HelloMakers,faaez/Telescope,Tobi2705/Telescope,veerjainATgmail/Telescope,MeteorHudsonValley/Telescope,jrmedia/oilgas,wangleihd/Telescope,dima7b/stewardsof,xamfoo/change-route-in-iron-router,mavidser/Telescope,Heyho-letsgo/frenchmeteor,covernal/Telescope,Code-for-Miami/miami-graph-telescope,zires/Telescope,julienlapointe/telescope-nova-social-news,Air2air/Telescope,aozora/Telescope,cmrberry/startup-stories,LocalFoodSupply/CrunchHunt,bshenk/projectIterate,mr1azl/Telescope,saadullahkhan/giteor,Discordius/Lesswrong2,cydoval/Telescope,ahmadassaf/Telescope,iraasta/quickformtest,arbfay/Telescope,enginbodur/TelescopeLatest,elamotte/indieshunt,samim23/GitXiv,Scalingo/Telescope,meteorclub/crater.io,nwabdou85/tagsira,AdmitHub/Telescope,niranjans/Indostartups,STANAPO/Telescope,elamotte/indieshunt,Daz2345/Telescope,rafaecheve/startupstudygroup,Alekzanther/LawScope,sethbonnie/StartupNews,hoihei/Telescope,caglarsayin/Telescope,baptistemac/Telescope,wunderkraut/WunderShare,meteorclub/crater.io,metstrike/Telescope,Bloc/Telescope,rtluu/immersive,delgermurun/Telescope,SachaG/Gamba,danieltynerbryan/ProductNews,geoclicks/Telescope,theartsnetwork/artytrends,sophearak/Telescope,kakedis/Telescope,Code-for-Miami/miami-graph-telescope,tupeloTS/grittynashville,lpatmo/cb-links,LuisHerranz/Telescope,Erwyn/Test-deploy-telescope,jamesrhymer/iwishcitiescould,tupeloTS/grittynashville,almogdesign/Telescope,almogdesign/Telescope,nwabdou85/tagsira_,jparyani/Telescope,braskinfvr/storytellers,ryangum/telescope,manriquef/Vulcan,tupeloTS/grittynashville,edjv711/presto,geoclicks/Telescope,geverit4/Telescope,jbschaff/StartupNews,nishanbose/Telescope,nathanmelenbrink/theRecord,rselk/telescope,alertdelta/asxbase,codebuddiesdotorg/cb-v2,nwabdou85/tagsira,haribabuthilakar/fh,evilhei/itForum,adhikariaman01/Telescope,GitYong/Telescope,bengott/Telescope,aichane/digigov,TelescopeJS/Screenings,LuisHerranz/Telescope,SachaG/Zensroom,jonmc12/heypsycho,guillaumj/Telescope,bharatjilledumudi/StockX,aykutyaman/Telescope,zarkem/ironhacks,iraasta/quickformtest,SachaG/Gamba,Code-for-Miami/miami-graph-telescope,simbird/Test,Discordius/Telescope,thinkxl/telescope-theme-mono,maxtor3569/Telescope,geverit4/Telescope,Eynaliyev/Screenings,automenta/sernyl,tonyoconnell/nootropics,azukiapp/Telescope,mr1azl/Telescope,edjv711/presto,GeoffAbbott/easyLife,KarimHmaissi/Codehunt,wunderkraut/WunderShare,nhlennox/gbjobs,maxtor3569/Telescope,wilsonpeng8/growthintensive,netham91/Telescope,KarimHmaissi/Codehunt,jeehag/linkupp,NYUMusEdLab/fork-cb,Daz2345/Telescope,mavidser/Telescope,IQ2022/Telescope,bshenk/projectIterate,tommytwoeyes/Telescope,covernal/Telescope,weld-co/weld-telescope,sungwoncho/Telescope,julienlapointe/telescope-nova-social-news,okaysee/snackr,manriquef/Vulcan,lpatmo/cb2,tylermalin/Screenings,sdeveloper/Telescope,johndpark/Telescope,Healdb/Telescope,eruwinu/presto,msavin/Telescope,Daz2345/dhPulse,tupeloTS/telescopety,geoclicks/Telescope,TodoTemplates/Telescope,tepk/Telescope,MeteorHudsonValley/Telescope,georules/iwishcitiescould,Discordius/Lesswrong2,xamfoo/change-route-in-iron-router,cydoval/Telescope,huaiyudavid/rentech,azukiapp/Telescope,Leeibrah/telescope,JstnEdr/Telescope,braskinfvr/storytellers,tupeloTS/telescopety,faaez/Telescope,Eynaliyev/Screenings,lpatmo/cb-links,innesm4/strictly44,cloudunicorn/fundandexit,dominictracey/Telescope,aykutyaman/Telescope,wende/quickformtest,youprofit/Telescope,filkuzmanovski/Telescope,almeidamarcell/AplicativoDoDia,capensisma/Asteroid,basemm911/questionsociety,parkeasz/Telescope,IanWhalen/Telescope,rizakaynak/Telescope,veerjainATgmail/Telescope,wduntak/tibetalk,kakedis/Telescope,empirical-org/codex-quill,gzingraf/GreenLight-Pix,georules/iwishcitiescould,datracka/dataforgood,bengott/Telescope,SachaG/swpsub,wrichman/tuleboxapp,meurio/conectacao,sabon/great-balls-of-fire,yourcelf/Telescope,asm-products/discourse,SSOCIETY/webpages,Accentax/betanyheter,em0ney/Telescope,theartsnetwork/artytrends,NodeJSBarenko/Telescope,evilhei/itForum,maxtor3569/Telescope,xamfoo/Telescope,bharatjilledumudi/StockX,meteorhacks/Telescope,adhikariaman01/Telescope,msavin/Telescope,guillaumj/Telescope,TodoTemplates/Telescope,johndpark/Telescope,wende/quickformtest,arunoda/Telescope,JstnEdr/Telescope,sdeveloper/Telescope,StEight/Telescope,acidsound/Telescope,SachaG/bjjbot,youprofit/Telescope,sethbonnie/StartupNews,crozzfire/hacky,rizakaynak/Telescope,kakedis/Telescope,johndpark/Telescope,covernal/Telescope,sharakarasic/telescope-coderdojola,jamesrhymer/iwishcitiescould,Daz2345/dhPulse,pombredanne/Telescope,lpatmo/cb,codebuddiesdotorg/cb-v2,nathanmelenbrink/theRecord,gkovacs/Telescope,UCSC-MedBook/MedBook-Telescope2,MeteorHudsonValley/Telescope,bharatjilledumudi/india-shop,meurio/conectacao,mandym-webdev/suggestanapp,sungwoncho/Telescope,samim23/GitXiv,wduntak/tibetalk,TribeMedia/Telescope,Leeibrah/telescope,mavidser/Telescope,jonmc12/heypsycho,gzingraf/GreenLight-Pix,lpatmo/cb2,parkeasz/Telescope,Alekzanther/LawScope,jrmedia/oilgas,nhlennox/gbjobs,danieltynerbryan/ProductNews,sabon/great-balls-of-fire,TribeMedia/Screenings,decent10/Telescope,SachaG/fundandexit,NodeJSBarenko/Telescope,fr0zen/viajavaga,sharakarasic/telescope-coderdojola,victorleungtw/AskMe,robertoscaccia/Crafteria-webapp,ibrahimcesar/Screenings,faaez/Telescope,danieltynerbryan/ProductNews,AdmitHub/Telescope,mr1azl/Telescope,weld-co/weld-telescope,samim23/GitXiv,acidsound/Telescope,yourcelf/Telescope,UCSC-MedBook/MedBook-Telescope3,VulcanJS/Vulcan,sungwoncho/Telescope,jamesrhymer/iwishcitiescould,queso/Telescope,hudat/Behaviorally,StEight/Telescope,simbird/Test,almogdesign/Telescope,GeoffAbbott/easyLife,WeAreWakanda/telescope,Alekzanther/LawScope,ryeskelton/Telescope,Scalingo/Telescope,TelescopeJS/Meta,dominictracey/Telescope,UCSC-MedBook/MedBook-Telescope3,mandym-webdev/digitalnomadnews,PaulAsjes/snackr,JackAdams/meteorpad-index,nikhilno1/Telescope,cdinnison/NPnews,nhlennox/gbjobs,sing1ee/Telescope,jkuruzovich/projecthunt,SachaG/bjjbot,pombredanne/Telescope,automenta/sernyl,aozora/Telescope,lambtron/goodwillhunt.org,Discordius/Telescope,sophearak/Telescope,basehaar/sumocollect,lpatmo/cb-links,wende/quickformtest,innesm4/strictly44,Scalingo/Telescope,TelescopeJS/Screenings,jrmedia/oilgas,georules/iwishcitiescould,lewisnyman/Telescope,ibrahimcesar/Screenings,bharatjilledumudi/StockX,UCSC-MedBook/MedBook-Telescope3,Heyho-letsgo/frenchmeteor,codebuddiesdotorg/cb-v2,caglarsayin/Telescope,mandym-webdev/suggestanapp,ryeskelton/Telescope,youprofit/Telescope,zires/Telescope,simbird/Test,WeAreWakanda/telescope,sdeveloper/Telescope,SachaG/Zensroom,gkovacs/Telescope,HelloMeets/HelloMakers,GeoffAbbott/dfl,TribeMedia/Screenings,basemm911/questionsociety,caglarsayin/Telescope,enginbodur/TelescopeLatest,sabon/teleport-troubleshoot,NodeJSBarenko/Telescope,nishanbose/Telescope,mandym-webdev/digitalnomadnews,Discordius/Lesswrong2,vazco/Telescope,rizakaynak/Telescope,SSOCIETY/webpages,lpatmo/cb2,tepk/Telescope,Air2air/Telescope,Daz2345/Telescope,iraasta/quickformtest,wooplaza/wpmob,delgermurun/Telescope,vazco/Telescope,ourcities/conectacao,zires/Telescope,SwarnaKishore/TechTrendz,aykutyaman/Telescope,rtluu/immersive,bharatjilledumudi/india-shop,bharatjilledumudi/india-shop,tart2000/Telescope,LuisHerranz/Telescope,sing1ee/Telescope,zarkem/ironhacks,tupeloTS/telescopety,meteorhacks/Telescope,VulcanJS/Vulcan,TelescopeJS/Screenings,metstrike/Telescope,nathanmelenbrink/theRecord,huaiyudavid/rentech,tommytwoeyes/Telescope,wojingdaile/Telescope,enginbodur/TelescopeLatest,acidsound/Telescope,TelescopeJS/CrunchHunt,silky/GitXiv,nwabdou85/tagsira_,em0ney/Telescope,bshenk/projectIterate,Eynaliyev/Screenings,neynah/Telescope,guilherme22/forum,lpatmo/sibp,capensisma/Asteroid,queso/Telescope,metstrike/Telescope,IQ2022/Telescope,JstnEdr/Telescope,tepk/Telescope,haribabuthilakar/fh,StEight/Telescope,delgermurun/Telescope,queso/Telescope,Discordius/Lesswrong2,theartsnetwork/artytrends,PaulAsjes/snackr,fr0zen/viajavaga,cloudunicorn/fundandexit,hoihei/Telescope,Healdb/Telescope,SachaG/bjjbot,UCSC-MedBook/MedBook-Telescope2,sing1ee/Telescope,GitYong/Telescope,STANAPO/Telescope,silky/GitXiv,wooplaza/wpmob,zarkem/ironhacks,filkuzmanovski/Telescope,SachaG/swpsub,aozora/Telescope,wunderkraut/WunderShare,adhikariaman01/Telescope,cloudunicorn/fundandexit,cmrberry/startup-stories,sophearak/Telescope,NYUMusEdLab/fork-cb,TribeMedia/Telescope,Healdb/Telescope,tart2000/Telescope,evilhei/itForum,hoihei/Telescope,capensisma/Asteroid,eruwinu/presto,rafaecheve/startupstudygroup,ahmadassaf/Telescope,manriquef/Vulcan,azukiapp/Telescope,wangleihd/Telescope,ahmadassaf/Telescope,bengott/Telescope,rtluu/immersive,chemceem/telescopeapp,LocalFoodSupply/CrunchHunt,lpatmo/cb,aichane/digigov
--- +++ @@ -34,7 +34,9 @@ } } -Meteor.Cron = new Cron(); -Meteor.Cron.addJob(1, function() { +// tick every second +Meteor.Cron = new Cron(1000); +// update scores every 10 seconds +Meteor.Cron.addJob(10, function() { Scoring.updateScores(); })
b114afe32fdcbedc20af613e940bf8196b069b47
src/index.js
src/index.js
import React, { Component } from 'react'; import ReactDom from 'react-dom'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/search_bar'; import VideoList from './components/video_list'; // const API_KEY = 'PLACE_YOUR_API_KEY_HERE'; class App extends Component { constructor (props) { super(props); this.state = { videos: [] }; YTSearch({key: API_KEY, term: 'dragonball super'}, (videos) => { console.log(videos); this.setState({ videos }); }); } render () { return ( <div> <SearchBar /> <VideoList videos={this.state.videos} /> </div> ); } } ReactDom.render(<App />, document.querySelector('.container'));
import React, { Component } from 'react'; import ReactDom from 'react-dom'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/search_bar'; import VideoList from './components/video_list'; import VideoDetail from './components/video_detail'; // const API_KEY = 'PLACE_YOUR_API_KEY_HERE'; class App extends Component { constructor (props) { super(props); this.state = { videos: [] }; YTSearch({key: API_KEY, term: 'dragonball super'}, (videos) => { console.log(videos); this.setState({ videos }); }); } render () { return ( <div> <SearchBar /> <VideoDetail video={this.state.videos[0]} /> <VideoList videos={this.state.videos} /> </div> ); } } ReactDom.render(<App />, document.querySelector('.container'));
Add the video detail component.
Add the video detail component.
JavaScript
mit
JosephLeon/redux-simple-starter-tutorial,JosephLeon/redux-simple-starter-tutorial
--- +++ @@ -3,6 +3,7 @@ import YTSearch from 'youtube-api-search'; import SearchBar from './components/search_bar'; import VideoList from './components/video_list'; +import VideoDetail from './components/video_detail'; // const API_KEY = 'PLACE_YOUR_API_KEY_HERE'; class App extends Component { @@ -21,6 +22,7 @@ return ( <div> <SearchBar /> + <VideoDetail video={this.state.videos[0]} /> <VideoList videos={this.state.videos} /> </div> );
911f44c4a6ffc730060687e589cbf63d0a7be4fc
src/index.js
src/index.js
import { setItemsActionCreator as setItems } from './setItems' import { rangeToActionCreator as rangeTo } from './rangeTo' import { removeActionCreator as remove } from './remove' import { removeAllActionCreator as removeAll } from './removeAll' import { replaceActionCreator as replace } from './replace' import { toggleActionCreator as toggle } from './toggle' import * as actionTypes from './actionTypes' import reducer from './reducer' import * as selectors from './selectors' import _bindToSelection from './bindToSelection' const actions = { setItems, rangeTo, remove, removeAll, replace, toggle, } const bindToSelection = _bindToSelection(actions, selectors) export { actionTypes, reducer, selectors, bindToSelection, }
import { setItemsActionCreator as setItems } from './setItems' import { rangeToActionCreator as rangeTo } from './rangeTo' import { removeActionCreator as remove } from './remove' import { removeAllActionCreator as removeAll } from './removeAll' import { replaceActionCreator as replace } from './replace' import { toggleActionCreator as toggle } from './toggle' import * as actionTypes from './actionTypes' import reducer from './reducer' import * as selectors from './selectors' import _bindToSelection from './bindToSelection' const actions = { setItems, rangeTo, remove, removeAll, replace, toggle, } const bindToSelection = _bindToSelection(actions, selectors) export { actionTypes, reducer, bindToSelection, }
Remove code of old API
Remove code of old API - bound `actions` and `selectors` will be provided by `bindToSelection`
JavaScript
mit
actano/yourchoice-redux
--- +++ @@ -23,6 +23,5 @@ export { actionTypes, reducer, - selectors, bindToSelection, }
6254538340e9e0390f03fa810f5c06404e36e48f
src/index.js
src/index.js
// We load the Safari fix before document-register-element because DRE // overrides attachShadow() and calls back the one it finds on HTMLElement. import './fix/safari'; import 'document-register-element'; import '@webcomponents/shadydom'; import '@webcomponents/shadycss';
// We load the Safari fix before document-register-element because DRE // overrides attachShadow() and calls back the one it finds on HTMLElement. import './fix/safari'; import 'document-register-element/build/document-register-element'; import '@webcomponents/shadydom'; import '@webcomponents/shadycss';
Fix to import the browser version of document-register-element.
fix: Fix to import the browser version of document-register-element. #26
JavaScript
mit
skatejs/web-components
--- +++ @@ -1,6 +1,6 @@ // We load the Safari fix before document-register-element because DRE // overrides attachShadow() and calls back the one it finds on HTMLElement. import './fix/safari'; -import 'document-register-element'; +import 'document-register-element/build/document-register-element'; import '@webcomponents/shadydom'; import '@webcomponents/shadycss';
35f06cce46eef1d1dadd3c7b512dd2378d1ea9d5
src/jokes.js
src/jokes.js
define(['lib/def', 'handler'], function(Def, Handler) { var Jokes = Def.type(Handler, function(source) { this.constructor.__super__.call(this); this.def_prop('source', source); }); Jokes.def_method(function next() { return this.source.next(); }); Jokes.def_method(function match(msg) { return /[tT]ell a joke/.test(msg); }); Jokes.def_method(function on_message(msg, cont) { return this.match(msg.text) ? msg.reply(this.next(), cont) : cont(); }); return Jokes; });
define(['lib/def', 'handler'], function(Def, Handler) { var Jokes = Def.type(Handler, function(source) { this.constructor.__super__.call(this); this.def_prop('source', source); }); Jokes.def_method(function next() { return this.source.next(); }); Jokes.def_method(function match(msg) { return /[tT]ell a joke/.test(msg); }); Jokes.def_method(function on_message(msg, cont) { return this.match(msg.text) ? msg.reply(this.next(), cont) : cont(msg); }); return Jokes; });
Fix bug where Jokes.on_message did not pass on non-matching messages.
Fix bug where Jokes.on_message did not pass on non-matching messages.
JavaScript
mit
bassettmb/slack-bot-dev
--- +++ @@ -14,7 +14,7 @@ }); Jokes.def_method(function on_message(msg, cont) { - return this.match(msg.text) ? msg.reply(this.next(), cont) : cont(); + return this.match(msg.text) ? msg.reply(this.next(), cont) : cont(msg); }); return Jokes;
74a4b20404fc506fef118a6553e171c0967f5f40
src/preload.js
src/preload.js
'use strict'; console.log('Loading preload script'); const { ipcRenderer } = require('electron'); const OldNotification = Notification; Notification = function(title, options) { const notificationSettings = ipcRenderer.sendSync('get-notification-settings', { title, body: options.body, isDirect: !options.silent, }); if (notificationSettings.ignoreNotification) { return {}; } else { return new OldNotification(title, { body: options.body, icon: options.icon, silent: !notificationSettings.playSound, }); } }; Notification.prototype = OldNotification.prototype; Notification.permission = OldNotification.permission; Notification.requestPermission = OldNotification.requestPermission;
'use strict'; console.log('Loading preload script'); const { ipcRenderer } = require('electron'); const OldNotification = Notification; Notification = function(title, options) { const notificationSettings = ipcRenderer.sendSync('get-notification-settings', { title, body: options.body, isDirect: !options.silent, }); if (notificationSettings.ignoreNotification) { return { close: function() {} }; } else { return new OldNotification(title, { body: options.body, icon: options.icon, silent: !notificationSettings.playSound, }); } }; Notification.prototype = OldNotification.prototype; Notification.permission = OldNotification.permission; Notification.requestPermission = OldNotification.requestPermission;
Add empty close funciton to silence error
Add empty close funciton to silence error
JavaScript
mit
Faithlife/FaithlifeMessages
--- +++ @@ -13,7 +13,7 @@ }); if (notificationSettings.ignoreNotification) { - return {}; + return { close: function() {} }; } else { return new OldNotification(title, { body: options.body,
7510b80e8b5aa5c34b91825a29eb9443bf6387fa
src/components/VmDisks/utils.js
src/components/VmDisks/utils.js
import { locale as appLocale } from '../../intl' function localeCompare (a, b, locale = appLocale) { return a.localeCompare(b, locale, { numeric: true }) } /* * Sort an Immutable List of Maps (set of disks) for display on the VmDisks list. * Bootable drives sort first, then sorted number aware alphabetically. */ export function sortDisksForDisplay (disks, locale = appLocale) { return disks.sort((a, b) => { const aBoot = a.get('bootable') const bBoot = b.get('bootable') return aBoot && !bBoot ? -1 : !aBoot && bBoot ? 1 : localeCompare(a.get('name'), b.get('name'), locale) }) }
import { locale as appLocale } from '../../intl' function localeCompare (a, b, locale = appLocale) { return a.localeCompare(b, locale, { numeric: true }) } /* * Sort an Immutable List of Maps (set of disks) for display on the VmDisks list. * Bootable drives sort first, then sorted number aware alphabetically. */ export function sortDisksForDisplay (disks, locale = appLocale) { return disks.sort((a, b) => { const aBoot = a.get('bootable') const bBoot = b.get('bootable') return (aBoot && !bBoot) ? -1 : ( (!aBoot && bBoot) ? 1 : localeCompare(a.get('name'), b.get('name'), locale) ) }) }
Improve readability of ternary operator
Improve readability of ternary operator
JavaScript
apache-2.0
mareklibra/userportal,oVirt/ovirt-web-ui,mareklibra/userportal,oVirt/ovirt-web-ui,mareklibra/userportal,oVirt/ovirt-web-ui,mareklibra/userportal
--- +++ @@ -14,8 +14,8 @@ const aBoot = a.get('bootable') const bBoot = b.get('bootable') - return aBoot && !bBoot ? -1 - : !aBoot && bBoot ? 1 - : localeCompare(a.get('name'), b.get('name'), locale) + return (aBoot && !bBoot) ? -1 : ( + (!aBoot && bBoot) ? 1 : localeCompare(a.get('name'), b.get('name'), locale) + ) }) }
8bad7a944039d5b374bf963c97c3428c05eb7980
jenkins-show-advanced.user.js
jenkins-show-advanced.user.js
/* Copyright 2015 Ops For Developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // ==UserScript== // @name Jenkins Show Advanced // @namespace http://opsfordevelopers.com/jenkins/userscripts // @description Automatically shows the configuration hidden beneath the "Advanced..." buttons in Jenkins jobs // @match https://*/jenkins/* // @match http://*/jenkins/* // @require https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js // @run-at document-end // @version 1.0 // @grant none // ==/UserScript== function showAdvancedTables () { // hide the "Advanced..." buttons and show the advanced tables jQuery("div.advancedLink").hide(); jQuery("table.advancedBody").show(); // give to the advanced tables the full width and remove the adjacent td tags jQuery("table.advancedBody").parent("td").attr("colspan", 4); jQuery("table.advancedBody").parentsUntil("tbody").children("td:empty").remove(); } jQuery(document).ready(function(){ jQuery.noConflict(); showAdvancedTables(); });
/* Copyright 2015 Ops For Developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // ==UserScript== // @name Jenkins Show Advanced // @namespace http://opsfordevelopers.com/jenkins/userscripts // @description Automatically shows the configuration hidden beneath the "Advanced..." buttons in Jenkins jobs // @match */job/*/configure // @require https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js // @run-at document-end // @version 1.0 // @grant none // ==/UserScript== function showAdvancedTables () { // hide the "Advanced..." buttons and show the advanced tables jQuery("div.advancedLink").hide(); jQuery("table.advancedBody").show(); // give to the advanced tables the full width and remove the adjacent td tags jQuery("table.advancedBody").parent("td").attr("colspan", 4); jQuery("table.advancedBody").parentsUntil("tbody").children("td:empty").remove(); } jQuery(document).ready(function(){ jQuery.noConflict(); showAdvancedTables(); });
Change the @match metadata to the */job/*/configure pattern to be as generic as possible
Change the @match metadata to the */job/*/configure pattern to be as generic as possible
JavaScript
apache-2.0
opsfordevelopers/jenkins-show-advanced
--- +++ @@ -17,8 +17,7 @@ // @name Jenkins Show Advanced // @namespace http://opsfordevelopers.com/jenkins/userscripts // @description Automatically shows the configuration hidden beneath the "Advanced..." buttons in Jenkins jobs -// @match https://*/jenkins/* -// @match http://*/jenkins/* +// @match */job/*/configure // @require https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js // @run-at document-end // @version 1.0
23b1947d2b1aec2325178c8d426167c74e414e74
jsbeautifierSettingsTweaks.js
jsbeautifierSettingsTweaks.js
/*! jsbeautifierSettingsTweaks.js v0.1.1 by ryanpcmcquen */ (function () { 'use strict'; window.addEventListener('load', function () { // set any vars you want to change here var jslintCheckbox = document.getElementById('jslint-happy'); var tabSize = document.getElementById('tabsize'); // set your values for those vars here tabSize.value = 2; jslintCheckbox.checked = true; }); }());
/*! jsbeautifierSettingsTweaks.js v0.2.0 by ryanpcmcquen */ window.addEventListener('load', function () { 'use strict'; // Set any vars you want to change here: var jslintCheckbox = document.getElementById('jslint-happy'); var tabSize = document.getElementById('tabsize'); var wrapLength = document.getElementById('wrap-line-length'); // Set your values for those vars here: tabSize.value = 2; jslintCheckbox.checked = true; wrapLength.value = 80; });
Add 80 character wrap length.
Add 80 character wrap length.
JavaScript
mpl-2.0
ryanpcmcquen/jsbeautifierSettingsTweaks.js
--- +++ @@ -1,16 +1,13 @@ -/*! jsbeautifierSettingsTweaks.js v0.1.1 by ryanpcmcquen */ -(function () { +/*! jsbeautifierSettingsTweaks.js v0.2.0 by ryanpcmcquen */ +window.addEventListener('load', function () { + 'use strict'; + // Set any vars you want to change here: + var jslintCheckbox = document.getElementById('jslint-happy'); + var tabSize = document.getElementById('tabsize'); + var wrapLength = document.getElementById('wrap-line-length'); - 'use strict'; - - window.addEventListener('load', function () { - // set any vars you want to change here - var jslintCheckbox = document.getElementById('jslint-happy'); - var tabSize = document.getElementById('tabsize'); - - // set your values for those vars here - tabSize.value = 2; - jslintCheckbox.checked = true; - }); - -}()); + // Set your values for those vars here: + tabSize.value = 2; + jslintCheckbox.checked = true; + wrapLength.value = 80; +});
f439ac809210f9dbfaf176bdff00569f7dcc4fa6
source/helpers.js
source/helpers.js
/** * Truncate a string to the given length. * * @param string The string to truncate. * @param length The length to truncate by. * * @returns {string} */ export const truncateString = (string, length) => { return string.slice(0, length) + '...'; }; export const formatRant = (rant) => { return { color: '#f99a66', author_name: rant.user_username, image_url: rant.attached_image.url, title: truncateString(rant.text, 100), title_link: `https://devrant.io/rants/${rant.id}?ref=devrant-bot`, author_link: `https://devrant.io/users/${rant.user_username}?ref=devrant-bot`, fields: [ { short: true, title: 'Score', value: rant.score }, { short: true, title: 'Comments', value: rant.num_comments } ] }; };
/** * Truncate a string to the given length. * * @param string The string to truncate. * @param length The length to truncate by. * * @returns {string} */ export const truncateString = (string, length) => { return string.slice(0, length) + '...'; }; export const formatRant = (rant) => { return { color: '#f99a66', author_name: rant.user_username, image_url: rant.attached_image.url, title: truncateString(rant.text, 100), title_link: `https://www.devrant.io/rants/${rant.id}?ref=devrant-bot`, author_link: `https://www.devrant.io/users/${rant.user_username}?ref=devrant-bot`, fields: [ { short: true, title: 'Score', value: rant.score }, { short: true, title: 'Comments', value: rant.num_comments } ] }; };
Change link URLs to avoid redirect
Change link URLs to avoid redirect
JavaScript
mit
nblackburn/devrant-bot
--- +++ @@ -17,8 +17,8 @@ author_name: rant.user_username, image_url: rant.attached_image.url, title: truncateString(rant.text, 100), - title_link: `https://devrant.io/rants/${rant.id}?ref=devrant-bot`, - author_link: `https://devrant.io/users/${rant.user_username}?ref=devrant-bot`, + title_link: `https://www.devrant.io/rants/${rant.id}?ref=devrant-bot`, + author_link: `https://www.devrant.io/users/${rant.user_username}?ref=devrant-bot`, fields: [ { short: true,
8a77f3189ac621c3530c006500f8b5e89a365585
src/app/logger.js
src/app/logger.js
/* global DEBUG */ /* eslint-disable no-console */ import { argv } from "nwjs/argv"; import Logger from "utils/Logger"; const { logDebug, logError } = new Logger( "Application" ); const onError = async ( type, err, debug ) => { if ( DEBUG ) { console.error( type, err, debug ); } try { await logError( type ? `${type}: ${err}` : err, debug ); } catch ( e ) {} }; process.on( "uncaughtException", e => onError( "uncaughtException", e ) ); window.addEventListener( "unhandledrejection", e => onError( e.type, e.reason, e.promise ) ); window.addEventListener( "error", e => onError( "error", e ) ); // don't log parameters when running a dev build via grunt if ( DEBUG ) { console.debug( argv ); } else { logDebug( "Parameters", argv ); }
/* global DEBUG */ /* eslint-disable no-console */ import Ember from "ember"; import { argv } from "nwjs/argv"; import Logger from "utils/Logger"; const { logDebug, logError } = new Logger( "Application" ); const onError = async ( type, err, debug ) => { if ( DEBUG ) { console.error( type, err, debug ); } try { await logError( type ? `${type}: ${err}` : err, debug ); } catch ( e ) {} }; process.on( "uncaughtException", e => onError( "uncaughtException", e ) ); window.addEventListener( "unhandledrejection", e => onError( e.type, e.reason, e.promise ) ); window.addEventListener( "error", e => onError( "error", e.error ) ); Ember.onerror = e => e && e.name !== "Adapter Error" ? onError( "Ember error", e ) : null; // don't log parameters when running a dev build via grunt if ( DEBUG ) { console.debug( argv ); } else { logDebug( "Parameters", argv ); }
Fix ErrorEvent logging + add Ember error listener
Fix ErrorEvent logging + add Ember error listener
JavaScript
mit
streamlink/streamlink-twitch-gui,streamlink/streamlink-twitch-gui,chhe/livestreamer-twitch-gui,streamlink/streamlink-twitch-gui,chhe/livestreamer-twitch-gui,chhe/livestreamer-twitch-gui
--- +++ @@ -1,5 +1,6 @@ /* global DEBUG */ /* eslint-disable no-console */ +import Ember from "ember"; import { argv } from "nwjs/argv"; import Logger from "utils/Logger"; @@ -19,7 +20,8 @@ process.on( "uncaughtException", e => onError( "uncaughtException", e ) ); window.addEventListener( "unhandledrejection", e => onError( e.type, e.reason, e.promise ) ); -window.addEventListener( "error", e => onError( "error", e ) ); +window.addEventListener( "error", e => onError( "error", e.error ) ); +Ember.onerror = e => e && e.name !== "Adapter Error" ? onError( "Ember error", e ) : null; // don't log parameters when running a dev build via grunt if ( DEBUG ) {
fa3bc8b524f281d8bae728aa556cba6bc45c0566
src/webroot/js/quickSearch.js
src/webroot/js/quickSearch.js
//autocomplete for organism search $("#search_organism").autocomplete({ position: { my: "right top", at: "right bottom" }, source: function (request, response) { var $search = request.term; $.ajax({ url: WebRoot.concat("/ajax/listing/Organisms"), data: {term: request.term, limit: 500, search: $search}, dataType: "json", success: function (data) { response(data); } }); }, minLength: 3 }); $("#search_organism").data("ui-autocomplete")._renderItem = function (ul, item) { var li = $("<li>") .append("<a href='"+WebRoot+"/details/byId/"+item.organism_id+"' class='fancybox' data-fancybox-type='ajax'><span style='display:inline-block; width: 100%; font-style: italic;'>" + item.scientific_name + "</span><span style='color: #338C8C'>" + item.rank + "</span></a>") .appendTo(ul); return li; };
//autocomplete for organism search $("#search_organism").autocomplete({ position: { my: "right top", at: "right bottom" }, source: function (request, response) { var $search = request.term; $.ajax({ url: WebRoot.concat("/ajax/listing/Organisms"), data: {term: request.term, limit: 500, search: $search}, dataType: "json", success: function (data) { response(data); } }); }, minLength: 3 }); $("#search_organism").data("ui-autocomplete")._renderItem = function (ul, item) { var li = $("<li>") .append("<a href='"+WebRoot+"/details/byId/"+item.organism_id+"' class='fancybox' data-fancybox-type='ajax'><span style='display:inline-block; width: 100%; font-style: italic;'>" + item.scientific_name + "</span><span style='color: #338C8C'>" + item.rank + "</span></a>") .appendTo(ul); return li; }; $("#btn_search_organism").click(function(){ $searchTerm = $("#search_organism").val(); $.ajax({ url: WebRoot.concat("/ajax/listing/Organisms"), data: {limit: 500, search: $searchTerm}, dataType: "json", success: function (data) { console.log(data);e } }); });
Add onclick function for button. The function is called after submitting the search. It gets the value of the search field and get the data objects via ajax
Add onclick function for button. The function is called after submitting the search. It gets the value of the search field and get the data objects via ajax
JavaScript
mit
molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec
--- +++ @@ -25,3 +25,16 @@ }; +$("#btn_search_organism").click(function(){ + $searchTerm = $("#search_organism").val(); + $.ajax({ + url: WebRoot.concat("/ajax/listing/Organisms"), + data: {limit: 500, search: $searchTerm}, + dataType: "json", + success: function (data) { + console.log(data);e + } + }); +}); + +
fded4d32e273e3d2183005c803bcecc68fa616e0
spec/main-spec.js
spec/main-spec.js
'use strict' describe('StreamPromise', function() { const StreamPromise = require('../') const FS = require('fs') it('works', function() { waitsForPromise(function() { return StreamPromise.create(FS.createReadStream(`${__dirname}/fixtures/something.txt`)) .then(function(contents) { expect(contents).toBe(`Something\n`) }) }) }) it('limits by bytes', function() { waitsForPromise(function() { let Threw = false return StreamPromise.create(FS.createReadStream(`${__dirname}/fixtures/something.txt`), 1) .catch(function() { Threw = true }) .then(function() { expect(Threw).toBe(true) }) }) }) })
'use strict' describe('StreamPromise', function() { const StreamPromise = require('../') const FS = require('fs') it('works', function() { waitsForPromise(function() { return StreamPromise.create(FS.createReadStream(`${__dirname}/fixtures/something.txt`)) .then(function(contents) { expect(contents).toBe(`Something\n`) }) }) }) it('limits by bytes', function() { waitsForPromise(function() { let Threw = false return StreamPromise.create(FS.createReadStream(`${__dirname}/fixtures/something.txt`), 1) .catch(function() { Threw = true }) .then(function() { expect(Threw).toBe(true) }) }) }) it('rejects promise on stream error', function() { waitsForPromise(function() { let Threw = false return StreamPromise.create(FS.createReadStream(`/etc/some-non-existing-file`)) .catch(function(e) { Threw = true }) .then(function() { expect(Threw).toBe(true) }) }) }) })
Add specs for rejecting promise on stream error
:new: Add specs for rejecting promise on stream error
JavaScript
mit
steelbrain/stream-promise
--- +++ @@ -22,4 +22,16 @@ }) }) }) + it('rejects promise on stream error', function() { + waitsForPromise(function() { + let Threw = false + return StreamPromise.create(FS.createReadStream(`/etc/some-non-existing-file`)) + .catch(function(e) { + Threw = true + }) + .then(function() { + expect(Threw).toBe(true) + }) + }) + }) })
13ddf46c44933bcc21a37fa626e723729d7768c2
src/engine/scene/text/enable.js
src/engine/scene/text/enable.js
// Dependencies import 'engine/scene/sprites/enable'; // Loader middleware import bitmap_font_parser from './bitmap_font_parser'; import { loader_use_procs } from 'engine/registry'; loader_use_procs.push(bitmap_font_parser); // Renderer // Class export { default as BitmapText } from './BitmapText'; export { default as Text } from './Text';
// Dependencies import 'engine/scene/sprites/enable'; // Loader middleware import bitmap_font_parser from './bitmap_font_parser'; import { loader_use_procs } from 'engine/registry'; loader_use_procs.push(bitmap_font_parser); // Register to global node class map import { node_class_map } from 'engine/registry'; import Text from './Text'; import BitmapText from './BitmapText'; node_class_map['Text'] = Text; node_class_map['BitmapText'] = BitmapText;
Add Text and BitmapText to node class map
Add Text and BitmapText to node class map
JavaScript
mit
pixelpicosean/voltar,pixelpicosean/voltar
--- +++ @@ -6,8 +6,11 @@ import { loader_use_procs } from 'engine/registry'; loader_use_procs.push(bitmap_font_parser); -// Renderer +// Register to global node class map +import { node_class_map } from 'engine/registry'; -// Class -export { default as BitmapText } from './BitmapText'; -export { default as Text } from './Text'; +import Text from './Text'; +import BitmapText from './BitmapText'; + +node_class_map['Text'] = Text; +node_class_map['BitmapText'] = BitmapText;
4da6eb8cee0e4463bd7436da58c1caf352ae6c31
test-loader.js
test-loader.js
/* globals requirejs, require */ QUnit.config.urlConfig.push({ id: 'nojshint', label: 'Disable JSHint'}); // TODO: load based on params for (var moduleName in requirejs.entries) { var shouldLoad; if (moduleName.match(/-test$/)) { shouldLoad = true; } if (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/)) { shouldLoad = true; } if (shouldLoad) { require(moduleName); } } if (QUnit.notifications) { QUnit.notifications({ icons: { passed: '/assets/passed.png', failed: '/assets/failed.png' } }); }
/* globals requirejs, require */ QUnit.config.urlConfig.push({ id: 'nojshint', label: 'Disable JSHint'}); // TODO: load based on params for (var moduleName in requirejs.entries) { var shouldLoad; if (moduleName.match(/[-_]test$/)) { shouldLoad = true; } if (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/)) { shouldLoad = true; } if (shouldLoad) { require(moduleName); } } if (QUnit.notifications) { QUnit.notifications({ icons: { passed: '/assets/passed.png', failed: '/assets/failed.png' } }); }
Allow tests to be underscored.
Allow tests to be underscored. This is to support legacy projects that are still using underscored names (looking at you backburner).
JavaScript
mit
ember-cli/ember-cli-test-loader
--- +++ @@ -6,7 +6,7 @@ for (var moduleName in requirejs.entries) { var shouldLoad; - if (moduleName.match(/-test$/)) { shouldLoad = true; } + if (moduleName.match(/[-_]test$/)) { shouldLoad = true; } if (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/)) { shouldLoad = true; } if (shouldLoad) { require(moduleName); }
97aeed066aee1b166e7c635755f275bf58eb530c
ngrinder-controller/src/main/resources/ngrinder_home_template/process_and_thread_policy.js
ngrinder-controller/src/main/resources/ngrinder_home_template/process_and_thread_policy.js
function getProcessCount(total) { if (total < 2) { return 1; } if (total > 80) { return parseInt(total / 30); } return 2; } function getThreadCount(total) { if (total < 2) { return 1; } if (total > 80) { return parseInt(total / (parseInt(total / 30))); } return parseInt(total / 2 + 0.5); }
function getProcessCount(total) { if (total < 2) { return 1; } var processCount = 2; if (total > 80) { processCount = parseInt(total / 40) + 1; } if (processCount > 20) { processCount = 20; } return processCount; } function getThreadCount(total) { var processCount = getProcessCount(total); return parseInt(total / processCount); }
Modify process and thread calc to support vuser more than 600.
[NGRINDER-495] Modify process and thread calc to support vuser more than 600.
JavaScript
apache-2.0
bwahn/ngrinder,nanpa83/ngrinder,bwahn/ngrinder,SRCB-CloudPart/ngrinder,chengaomin/ngrinder,ropik/ngrinder,songeunwoo/ngrinder,chengaomin/ngrinder,SRCB-CloudPart/ngrinder,ropik/ngrinder,GwonGisoo/ngrinder,songeunwoo/ngrinder,bwahn/ngrinder,SRCB-CloudPart/ngrinder,ropik/ngrinder,SRCB-CloudPart/ngrinder,songeunwoo/ngrinder,nanpa83/ngrinder,GwonGisoo/ngrinder,songeunwoo/ngrinder,naver/ngrinder,naver/ngrinder,chengaomin/ngrinder,songeunwoo/ngrinder,GwonGisoo/ngrinder,naver/ngrinder,ropik/ngrinder,bwahn/ngrinder,GwonGisoo/ngrinder,chengaomin/ngrinder,SRCB-CloudPart/ngrinder,nanpa83/ngrinder,naver/ngrinder,nanpa83/ngrinder,GwonGisoo/ngrinder,bwahn/ngrinder,chengaomin/ngrinder,naver/ngrinder,nanpa83/ngrinder
--- +++ @@ -2,18 +2,20 @@ if (total < 2) { return 1; } + + var processCount = 2; + if (total > 80) { - return parseInt(total / 30); + processCount = parseInt(total / 40) + 1; } - return 2; + + if (processCount > 20) { + processCount = 20; + } + return processCount; } function getThreadCount(total) { - if (total < 2) { - return 1; - } - if (total > 80) { - return parseInt(total / (parseInt(total / 30))); - } - return parseInt(total / 2 + 0.5); + var processCount = getProcessCount(total); + return parseInt(total / processCount); }
ad8527e1d63d99f14f956b69a3a52e018b4b3058
src/js/single/committee/edit.js
src/js/single/committee/edit.js
$(function () { 'use strict'; var $coordinator_select = $('#coordinator_id'); var $group_select = $('#group_id'); $coordinator_select.select2(); $group_select.select2(); function set_group_users() { var group_id = $group_select.val(); $.get('/api/group/users/' + group_id, {}, function (data) { $coordinator_select.empty(); _(data.users).forEach(function (user) { var $option = $('<option></option>'); $option.val(user.val); $option.text(user.label); $coordinator_select.append($option); }); }); } $group_select.change(function () { set_group_users(); }); });
$(function () { 'use strict'; var $coordinator_select = $('#coordinator_id'); var $group_select = $('#group_id'); function set_group_users() { var group_id = $group_select.val(); $.get('/api/group/users/' + group_id, {}, function (data) { $coordinator_select.empty(); _(data.users).forEach(function (user) { var $option = $('<option></option>'); $option.val(user.val); $option.text(user.label); $coordinator_select.append($option); }); }); } $group_select.change(function () { set_group_users(); }); });
Remove select2 again, because that sucked
Remove select2 again, because that sucked
JavaScript
mit
viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct
--- +++ @@ -3,9 +3,6 @@ var $coordinator_select = $('#coordinator_id'); var $group_select = $('#group_id'); - - $coordinator_select.select2(); - $group_select.select2(); function set_group_users() { var group_id = $group_select.val();
3124a0955dbedcd57b78858a5c7af9f197bb3d68
src/orm-tests.js
src/orm-tests.js
/* eslint-disable no-unused-expressions */ import { expect } from 'chai'; export default function orm (people, _ids, errors) { describe('Feathers ORM Specific Tests', () => { it('wraps an ORM error in a feathers error', () => { return people.create({}).catch(error => expect(error instanceof errors.FeathersError).to.be.ok ); }); }); }
/* eslint-disable no-unused-expressions */ import { expect } from 'chai'; export default function orm (people, errors, idProp = 'id') { describe('Feathers ORM Common Tests', () => { it('wraps an ORM error in a feathers error', () => { return people.create({}).catch(error => { expect(error instanceof errors.FeathersError).to.be.ok }); }); describe('Raw/Lean Queries', () => { const _ids = {}; const _data = {}; beforeEach(() => people.create({ name: 'Doug', age: 32 }).then(data => { _data.Doug = data; _ids.Doug = data[idProp]; }) ); afterEach(() => people.remove(_ids.Doug).catch(() => {}) ); function noPOJO() { // The prototype objects are huge and cause node to hang // when the reporter tries to log the errors to the console. throw new Error('The expected result was not a POJO.'); } it('returns POJOs for find()', () => { return people.find({}).then(results => expect(Object.getPrototypeOf(results[0])).to.equal(Object.prototype) ).catch(noPOJO); }); it('returns a POJO for get()', () => { return people.get(_ids.Doug).then(result => expect(Object.getPrototypeOf(result)).to.equal(Object.prototype) ).catch(noPOJO); }); it('returns a POJO for create()', () => { return people.create({name: 'Sarah', age: 30}).then(result => expect(Object.getPrototypeOf(result)).to.equal(Object.prototype) ).catch(noPOJO); }); it('returns POJOs for bulk create()', () => { return people.create([{name: 'Sarah', age: 30}]).then(result => expect(Object.getPrototypeOf(result[0])).to.equal(Object.prototype) ).catch(noPOJO); }); it('returns a POJO for patch()', () => { return people.patch(_ids.Doug, {name: 'Sarah'}).then(result => expect(Object.getPrototypeOf(result)).to.equal(Object.prototype) ).catch(noPOJO); }); it('returns a POJO for update()', () => { return people.update(_ids.Doug, Object.assign(_data.Doug, {name: 'Sarah'})).then(result => expect(Object.getPrototypeOf(result)).to.equal(Object.prototype) ).catch(noPOJO); }); }); }); }
Update ORM tests to ensure plain objects are returned
Update ORM tests to ensure plain objects are returned
JavaScript
mit
feathersjs/feathers-service-tests
--- +++ @@ -2,12 +2,73 @@ import { expect } from 'chai'; -export default function orm (people, _ids, errors) { - describe('Feathers ORM Specific Tests', () => { +export default function orm (people, errors, idProp = 'id') { + describe('Feathers ORM Common Tests', () => { it('wraps an ORM error in a feathers error', () => { - return people.create({}).catch(error => + return people.create({}).catch(error => { expect(error instanceof errors.FeathersError).to.be.ok + }); + }); + + describe('Raw/Lean Queries', () => { + const _ids = {}; + const _data = {}; + + beforeEach(() => + people.create({ + name: 'Doug', + age: 32 + }).then(data => { + _data.Doug = data; + _ids.Doug = data[idProp]; + }) ); + + afterEach(() => + people.remove(_ids.Doug).catch(() => {}) + ); + + function noPOJO() { + // The prototype objects are huge and cause node to hang + // when the reporter tries to log the errors to the console. + throw new Error('The expected result was not a POJO.'); + } + + it('returns POJOs for find()', () => { + return people.find({}).then(results => + expect(Object.getPrototypeOf(results[0])).to.equal(Object.prototype) + ).catch(noPOJO); + }); + + it('returns a POJO for get()', () => { + return people.get(_ids.Doug).then(result => + expect(Object.getPrototypeOf(result)).to.equal(Object.prototype) + ).catch(noPOJO); + }); + + it('returns a POJO for create()', () => { + return people.create({name: 'Sarah', age: 30}).then(result => + expect(Object.getPrototypeOf(result)).to.equal(Object.prototype) + ).catch(noPOJO); + }); + + it('returns POJOs for bulk create()', () => { + return people.create([{name: 'Sarah', age: 30}]).then(result => + expect(Object.getPrototypeOf(result[0])).to.equal(Object.prototype) + ).catch(noPOJO); + }); + + it('returns a POJO for patch()', () => { + return people.patch(_ids.Doug, {name: 'Sarah'}).then(result => + expect(Object.getPrototypeOf(result)).to.equal(Object.prototype) + ).catch(noPOJO); + }); + + it('returns a POJO for update()', () => { + return people.update(_ids.Doug, Object.assign(_data.Doug, {name: 'Sarah'})).then(result => + expect(Object.getPrototypeOf(result)).to.equal(Object.prototype) + ).catch(noPOJO); + }); }); }); }
848ee33109b35c83ac846a91d106e9268d1336d4
test/app.spec.js
test/app.spec.js
import { expect } from 'chai'; describe('smoke test', () => { it('run a test', () => { expect(true).to.equal(true); }); });
import { expect } from 'chai'; describe('smoke test', () => { it('run a test', () => { expect(true).to.equal(false); }); });
Make the fail the test to demo CircleCI
CSRA-000: Make the fail the test to demo CircleCI
JavaScript
mit
noms-digital-studio/csra-app,noms-digital-studio/csra-app,noms-digital-studio/csra-app
--- +++ @@ -2,6 +2,6 @@ describe('smoke test', () => { it('run a test', () => { - expect(true).to.equal(true); + expect(true).to.equal(false); }); });
eb3311239dac49183579a91ad99d9f1e6733e0bc
test/fixtures.js
test/fixtures.js
'use strict' const packageJson = require('../package') const channelHeader = `Node.js-${process.version}-SDK-v${packageJson.version}` module.exports = { reqWithBody: { reqheaders: { 'X-App-Id': 'node-sdk-test-id', 'X-App-Token': 'node-sdk-test-secret', 'X-Voucherify-Channel': channelHeader, 'accept': 'application/json', 'content-type': 'application/json' } }, reqWithoutBody: { reqheaders: { 'X-App-Id': 'node-sdk-test-id', 'X-App-Token': 'node-sdk-test-secret', 'X-Voucherify-Channel': channelHeader, 'accept': 'application/json' } } }
'use strict' // FIXME leaving var to satisfy tests for node v0.10 and v0.12 var packageJson = require('../package') var channelHeader = `Node.js-${process.version}-SDK-v${packageJson.version}` module.exports = { reqWithBody: { reqheaders: { 'X-App-Id': 'node-sdk-test-id', 'X-App-Token': 'node-sdk-test-secret', 'X-Voucherify-Channel': channelHeader, 'accept': 'application/json', 'content-type': 'application/json' } }, reqWithoutBody: { reqheaders: { 'X-App-Id': 'node-sdk-test-id', 'X-App-Token': 'node-sdk-test-secret', 'X-Voucherify-Channel': channelHeader, 'accept': 'application/json' } } }
Use var to satisfy tests for prehistoric nodejs versions
Use var to satisfy tests for prehistoric nodejs versions
JavaScript
mit
voucherifyio/voucherify-nodejs-sdk,rspective/voucherify-nodejs-sdk
--- +++ @@ -1,7 +1,8 @@ 'use strict' -const packageJson = require('../package') -const channelHeader = `Node.js-${process.version}-SDK-v${packageJson.version}` +// FIXME leaving var to satisfy tests for node v0.10 and v0.12 +var packageJson = require('../package') +var channelHeader = `Node.js-${process.version}-SDK-v${packageJson.version}` module.exports = { reqWithBody: {
d9d8003d5a91f8849b6d63e78c95a384f4643ef6
bin/execbin.js
bin/execbin.js
#!/usr/bin/env node var Janeway = require('../lib/init.js'), libpath = require('path'), main_file; // Get the wanted file to require main_file = libpath.resolve(process.cwd(), process.argv[2]); // Remove janeway from the arguments array process.argv.splice(1, 1); // Start initializing janeway Janeway.start(function started(err) { if (err) { console.error('Could not start Janeway: ' + err); } try { Janeway.print('info', ['Requiring main file', JSON.stringify(process.argv[1])]); require(main_file); } catch (err) { console.log('Error requiring main file: ' + err); } });
#!/usr/bin/env node var Janeway = require('../lib/init.js'), libpath = require('path'), main_file; // Get the wanted file to require if (process.argv[2]) { main_file = libpath.resolve(process.cwd(), process.argv[2]); } // Remove janeway from the arguments array process.argv.splice(1, 1); // Start initializing janeway Janeway.start(function started(err) { if (err) { console.error('Could not start Janeway: ' + err); } try { if (main_file) { Janeway.print('info', ['Requiring main file', JSON.stringify(process.argv[1])]); require(main_file); } } catch (err) { console.log('Error requiring main file: ' + err); } });
Allow lauching without specifying main_file
Allow lauching without specifying main_file
JavaScript
mit
skerit/janeway
--- +++ @@ -4,7 +4,9 @@ main_file; // Get the wanted file to require -main_file = libpath.resolve(process.cwd(), process.argv[2]); +if (process.argv[2]) { + main_file = libpath.resolve(process.cwd(), process.argv[2]); +} // Remove janeway from the arguments array process.argv.splice(1, 1); @@ -17,8 +19,10 @@ } try { - Janeway.print('info', ['Requiring main file', JSON.stringify(process.argv[1])]); - require(main_file); + if (main_file) { + Janeway.print('info', ['Requiring main file', JSON.stringify(process.argv[1])]); + require(main_file); + } } catch (err) { console.log('Error requiring main file: ' + err); }
df476029bd49caf6de34eeee05ef3af83649173b
bin/m3u-export.js
bin/m3u-export.js
#!/usr/bin/env node var LineReader = require('line-by-line'), minimist = require('minimist'), exec = require('exec'), path = require('path'), fs = require('fs'); var filenames = minimist(process.argv.slice(2))._; filenames.forEach(function (filename) { if (!fs.existsSync(filename)) { console.log(filename + ' does not exist or cannot be read, skipping.'); return; } var reader = new LineReader(filename), lines = []; reader.on('error', function (err) { throw err; }); reader.on('line', function (line) { var outputLine = line; // Not EXIF data if (line.indexOf('#') !== 0) { var filename = path.basename(line); // @todo Properly escape spaces exec('cp "' + line + '" "./' + filename + '"', function (err, out, code) { if (err) throw err; }); // Update line with new path [same directory] outputLine = filename; } lines.push(outputLine); }); reader.on('end', function () { fs.writeFileSync(filename, lines.join('\r')); console.log('Exported ' + filename); }); });
#!/usr/bin/env node var LineReader = require('line-by-line'), minimist = require('minimist'), exec = require('exec'), path = require('path'), fs = require('fs'), // Get all the arguments that don't have an option associated with them filenames = minimist(process.argv.slice(2))._; filenames.forEach(function (filename) { if (!fs.existsSync(filename)) { console.log(filename + ' does not exist or cannot be read, skipping.'); return; } var reader = new LineReader(filename), lines = []; reader.on('error', function (err) { throw err; }); reader.on('line', function (line) { var outputLine = line; // Not EXIF data // @todo Is this *really* going to do? if (line.indexOf('#') !== 0) { var musicFilename = path.basename(line); // @todo Properly escape spaces exec('cp "' + line + '" "./' + musicFilename + '"', function (err, out, code) { if (err) throw err; }); // Update line with new path [same directory] outputLine = musicFilename; } lines.push(outputLine); }); reader.on('end', function () { // Write a file to the local directory — this may not be the same directory as the original m3u, but it will be // where the music files have been copied to, so they need to be in the same place for the new m3u to work fs.writeFileSync(path.basename(filename), lines.join('\r')); console.log('Exported ' + filename); }); });
Write output m3u to local directory Regardless of whether source m3u is in local dir or not
Write output m3u to local directory Regardless of whether source m3u is in local dir or not
JavaScript
mit
rowanoulton/m3u-export
--- +++ @@ -4,9 +4,9 @@ minimist = require('minimist'), exec = require('exec'), path = require('path'), - fs = require('fs'); - -var filenames = minimist(process.argv.slice(2))._; + fs = require('fs'), + // Get all the arguments that don't have an option associated with them + filenames = minimist(process.argv.slice(2))._; filenames.forEach(function (filename) { if (!fs.existsSync(filename)) { @@ -25,23 +25,26 @@ var outputLine = line; // Not EXIF data + // @todo Is this *really* going to do? if (line.indexOf('#') !== 0) { - var filename = path.basename(line); + var musicFilename = path.basename(line); // @todo Properly escape spaces - exec('cp "' + line + '" "./' + filename + '"', function (err, out, code) { + exec('cp "' + line + '" "./' + musicFilename + '"', function (err, out, code) { if (err) throw err; }); // Update line with new path [same directory] - outputLine = filename; + outputLine = musicFilename; } lines.push(outputLine); }); reader.on('end', function () { - fs.writeFileSync(filename, lines.join('\r')); + // Write a file to the local directory — this may not be the same directory as the original m3u, but it will be + // where the music files have been copied to, so they need to be in the same place for the new m3u to work + fs.writeFileSync(path.basename(filename), lines.join('\r')); console.log('Exported ' + filename); }); });
dcc87fda6efccbc88a74ef556c1a5a5868500cf2
lib/resource/client/Company.js
lib/resource/client/Company.js
'use strict'; //var P = require('bluebird'); var Resource = require('../Resource'); function Company(primus) { Resource.call(this, primus, 'Company'); this._cache = { // contains Promises all: null }; } require('inherits')(Company, Resource); module.exports = Company; Company.prototype.all = function() { this._cache.all = this._cache.all || this.rpc('all'); return this._cache.all; }; Company.prototype.updateCompany = function(id, values) { // todo update cache return this.rpc('updateCompany', id, values); };
'use strict'; //var P = require('bluebird'); var Resource = require('../Resource'); function Company(primus) { Resource.call(this, primus, 'Company'); this._cache = { // contains Promises all: null }; } require('inherits')(Company, Resource); module.exports = Company; Company.prototype.all = function() { this._cache.all = this._cache.all || this.rpc('all'); return this._cache.all; }; Company.prototype.updateCompany = function(id, values) { // todo update cache var p = this.rpc('updateCompany', id, values); // The caller of updateCompany does not have to wait for this stuff: p.then(function(rpcReturn) { if (!this._cache.all || !this._cache.all.isFulfilled()) { return; } var keys = Object.keys(values); this._cache.all.value().forEach(function(item) { if (item._id !== id) { return; } keys.forEach(function(key) { item[key] = values[key]; }); }); }); return p; };
Update cache after an edit
Update cache after an edit
JavaScript
agpl-3.0
dealport/dealport
--- +++ @@ -26,5 +26,33 @@ { // todo update cache - return this.rpc('updateCompany', id, values); + var p = this.rpc('updateCompany', id, values); + + // The caller of updateCompany does not have to wait for this stuff: + p.then(function(rpcReturn) + { + if (!this._cache.all || + !this._cache.all.isFulfilled()) + { + return; + } + + var keys = Object.keys(values); + + this._cache.all.value().forEach(function(item) + { + if (item._id !== id) + { + return; + } + + keys.forEach(function(key) + { + item[key] = values[key]; + }); + }); + + }); + + return p; };
016209fd667a21ac2c9800c29efd3e2be4bae872
Gulpfile.js
Gulpfile.js
var gulp = require('gulp'); gulp.task('test', function () { require('./'); var mocha = require('gulp-mocha'); return gulp.src('test/**/*.es6', { read: false }) .pipe(mocha({ bail: true })); }); gulp.task('watch', ['default'], function () { gulp.watch([ 'index.js', 'lib/**/*.es6', 'test/**/*.es6' ], ['default']); }); gulp.task('default', ['test']);
var gulp = require('gulp'); gulp.task('test', function () { require('babel/register')({ // All the subsequent files required by node with the extension of `.es6` // will be transformed to ES5 extensions: ['.es6'] }); var mocha = require('gulp-mocha'); return gulp.src('test/**/*.es6', { read: false }) .pipe(mocha({ bail: true })); }); gulp.task('watch', ['default'], function () { gulp.watch([ 'index.js', 'lib/**/*.es6', 'test/**/*.es6' ], ['default']); }); gulp.task('default', ['test']);
Enable Babel properly while testing
Enable Babel properly while testing
JavaScript
mit
OEvgeny/postcss-assets,borodean/postcss-assets,justinanastos/postcss-assets,assetsjs/postcss-assets,glebmachine/postcss-assets
--- +++ @@ -1,7 +1,11 @@ var gulp = require('gulp'); gulp.task('test', function () { - require('./'); + require('babel/register')({ + // All the subsequent files required by node with the extension of `.es6` + // will be transformed to ES5 + extensions: ['.es6'] + }); var mocha = require('gulp-mocha'); return gulp.src('test/**/*.es6', { read: false
a3c2fdadd697e0bcdece46a8d6ecf1affa5c572d
lib/core/src/server/config.js
lib/core/src/server/config.js
import path from 'path'; import loadPresets from './presets'; import serverRequire from './serverRequire'; function customPreset({ configDir }) { return serverRequire(path.resolve(configDir, 'presets')) || []; } function getWebpackConfig(options, presets) { const babelOptions = presets.extendBabel({}, options); const entries = { iframe: presets.extendPreview([], options), manager: presets.extendManager([], options), }; return presets.extendWebpack({}, { ...options, babelOptions, entries }); } export default options => { const { corePresets = [], frameworkPresets = [], ...restOptions } = options; const presetsConfig = [ ...corePresets, require.resolve('./core-preset-babel-cache.js'), ...frameworkPresets, ...customPreset(options), require.resolve('./core-preset-webpack-custom.js'), ]; const presets = loadPresets(presetsConfig); return getWebpackConfig(restOptions, presets); };
import path from 'path'; import { logger } from '@storybook/node-logger'; import loadPresets from './presets'; import serverRequire from './serverRequire'; function customPreset({ configDir }) { const presets = serverRequire(path.resolve(configDir, 'presets')); if (presets) { logger.warn( '"Custom presets" is an experimental and undocumented feature that will be changed or deprecated soon. Use it on your own risk.' ); return presets; } return []; } function getWebpackConfig(options, presets) { const babelOptions = presets.extendBabel({}, options); const entries = { iframe: presets.extendPreview([], options), manager: presets.extendManager([], options), }; return presets.extendWebpack({}, { ...options, babelOptions, entries }); } export default options => { const { corePresets = [], frameworkPresets = [], ...restOptions } = options; const presetsConfig = [ ...corePresets, require.resolve('./core-preset-babel-cache.js'), ...frameworkPresets, ...customPreset(options), require.resolve('./core-preset-webpack-custom.js'), ]; const presets = loadPresets(presetsConfig); return getWebpackConfig(restOptions, presets); };
Add warning about custom presets
Add warning about custom presets
JavaScript
mit
storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook
--- +++ @@ -1,9 +1,20 @@ import path from 'path'; +import { logger } from '@storybook/node-logger'; import loadPresets from './presets'; import serverRequire from './serverRequire'; function customPreset({ configDir }) { - return serverRequire(path.resolve(configDir, 'presets')) || []; + const presets = serverRequire(path.resolve(configDir, 'presets')); + + if (presets) { + logger.warn( + '"Custom presets" is an experimental and undocumented feature that will be changed or deprecated soon. Use it on your own risk.' + ); + + return presets; + } + + return []; } function getWebpackConfig(options, presets) {
e939cdd71013934a26e477288d22e0240bd8bb7f
src/server/entrypoint-render.js
src/server/entrypoint-render.js
import prerender from './prerender' // This is a wrapper to handle a single isomorphic render inside a child process function startRender(context) { prerender(context).then((result) => { process.send(result, null, {}, () => { process.exit(0) }) }).catch(() => { process.exit(1) }) } process.on('message', startRender)
import prerender from './prerender' import { updateStrings as updateTimeAgoStrings } from './../lib/time_ago_in_words' updateTimeAgoStrings({ about: '' }) // This is a wrapper to handle a single isomorphic render inside a child process function startRender(context) { prerender(context).then((result) => { process.send(result, null, {}, () => { process.exit(0) }) }).catch(() => { process.exit(1) }) } process.on('message', startRender)
Add time ago in words to the server render
Add time ago in words to the server render
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
--- +++ @@ -1,4 +1,7 @@ import prerender from './prerender' +import { updateStrings as updateTimeAgoStrings } from './../lib/time_ago_in_words' + +updateTimeAgoStrings({ about: '' }) // This is a wrapper to handle a single isomorphic render inside a child process
5871c8b7077eaeaf04049135142d7e34f6130e30
lib/flatten.js
lib/flatten.js
/* Copyright (c) 2014, Ryuichi Okumura. All rights reserved. Code licensed under the BSD License: https://github.com/okuryu/package-json-flatten/blob/master/LICENSE.md */ "use strict"; /* Based on order of the NPM official package.json reference. https://www.npmjs.org/doc/package.json.html */ var priorityKeys = [ "name", "version", "description", "keywords", "homepage", "bugs", "license", "author", "contributors", "files", "main", "bin", "man", "directories", "repository", "scripts", "config", "dependencies", "devDependencies", "bundledDependencies", "optionalDependencies", "engines", "engineStrict", "os", "cpu", "preferGlobal", "private", "publishConfig" ]; export default function (inputData) { var flattenData = {}, formerKey; priorityKeys.forEach(function (key) { if (inputData.hasOwnProperty(key)) { flattenData[key] = inputData[key]; delete inputData[key]; } }); for (formerKey in inputData) { if (inputData.hasOwnProperty(formerKey)) { flattenData[formerKey] = inputData[formerKey]; } } return flattenData; }
/* Copyright (c) 2014, Ryuichi Okumura. All rights reserved. Code licensed under the BSD License: https://github.com/okuryu/package-json-flatten/blob/master/LICENSE.md */ "use strict"; /* Based on order of the NPM official package.json reference. https://www.npmjs.org/doc/package.json.html */ var priorityKeys = [ "name", "version", "description", "keywords", "homepage", "bugs", "license", "author", "contributors", "files", "main", "bin", "man", "directories", "repository", "scripts", "config", "dependencies", "devDependencies", "bundledDependencies", "optionalDependencies", "engines", "engineStrict", "os", "cpu", "preferGlobal", "private", "publishConfig" ]; export default function (inputData) { var flattenData = {}, formerKey; priorityKeys.forEach(function (key) { if (inputData.hasOwnProperty(key)) { flattenData[key] = inputData[key]; delete inputData[key]; } }); for (formerKey in inputData) { flattenData[formerKey] = inputData[formerKey]; } return flattenData; }
Move out checking by using hasOwnProperty()
Move out checking by using hasOwnProperty()
JavaScript
bsd-3-clause
okuryu/package-json-flatten
--- +++ @@ -52,9 +52,7 @@ }); for (formerKey in inputData) { - if (inputData.hasOwnProperty(formerKey)) { - flattenData[formerKey] = inputData[formerKey]; - } + flattenData[formerKey] = inputData[formerKey]; } return flattenData;
4ab6a6db8542d018ca1068808f83daa5f09bc3dc
src/client/es6/routers.js
src/client/es6/routers.js
export default function CartRouters($stateProvider, $urlRouterProvider) { }
function CartRouters($stateProvider, $urlRouterProvider) { } CartRouters.$inject = ['$stateProvider', '$urlRouterProvider']; export default CartRouters;
Use injector to do angular config function.
Use injector to do angular config function.
JavaScript
mit
agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart
--- +++ @@ -1,3 +1,6 @@ -export default function CartRouters($stateProvider, $urlRouterProvider) { +function CartRouters($stateProvider, $urlRouterProvider) { +} -} +CartRouters.$inject = ['$stateProvider', '$urlRouterProvider']; + +export default CartRouters;
62e3f095c37976d67d28a16056b188ac643124a4
static/js/main.js
static/js/main.js
(function($) { "use strict"; var apiUrl = "http://redjohn.herokuapp.com/api/tweets"; function addScoresToSuspects(response) { _.each(response.results, function(mentions, suspect) { $("#" + suspect).find(".mentions").text(mentions); }); } function addTotal(response) { $("#tweet-count").text(response.results); } $.ajax({ url: apiUrl + "suspects/count", type: "GET", dataType: "jsonp", success: addScoresToSuspects }); $.ajax({ url: apiUrl + "count", type: "GET", dataType: "jsonp", success: addTotal }); })(jQuery);
(function($) { "use strict"; var apiUrl = "http://redjohn.herokuapp.com/api/tweets/"; function addScoresToSuspects(response) { _.each(response.results, function(mentions, suspect) { $("#" + suspect).find(".mentions").text(mentions); }); } function addTotal(response) { $("#tweet-count").text(response.results); } $.ajax({ url: apiUrl + "suspects/count", type: "GET", dataType: "jsonp", success: addScoresToSuspects }); $.ajax({ url: apiUrl + "count", type: "GET", dataType: "jsonp", success: addTotal }); })(jQuery);
Add a trailing slash to the base API URL
Add a trailing slash to the base API URL
JavaScript
mit
AnSavvides/redjohn,AnSavvides/redjohn
--- +++ @@ -2,7 +2,7 @@ "use strict"; - var apiUrl = "http://redjohn.herokuapp.com/api/tweets"; + var apiUrl = "http://redjohn.herokuapp.com/api/tweets/"; function addScoresToSuspects(response) { _.each(response.results, function(mentions, suspect) {
4593b652c4791c7b30cacd9b60fe90fad0d1aa98
lib/renderers/JsonRenderer.js
lib/renderers/JsonRenderer.js
function JsonRenderer() { this._nrLogs = 0; } JsonRenderer.prototype.end = function (data) { if (this._nrLogs) { process.stderr.write(']\n'); } if (data) { process.stdout.write(this._stringify(data) + '\n'); } }; JsonRenderer.prototype.error = function (err) { err.id = err.code || 'error'; err.level = 'error'; this.log(err); this.end(); }; JsonRenderer.prototype.log = function (log) { if (!this._nrLogs) { process.stderr.write('['); } else { process.stderr.write(', '); } process.stderr.write(this._stringify(log)); this._nrLogs++; }; JsonRenderer.prototype.updateAvailable = function () {}; // ------------------------- JsonRenderer.prototype._stringify = function (log) { // To json var str = JSON.stringify(log, null, ' '); // Remove colors in case some log has colors.. str = str.replace(/\x1B\[\d+m/g, ''); return str; }; module.exports = JsonRenderer;
function JsonRenderer() { this._nrLogs = 0; } JsonRenderer.prototype.end = function (data) { if (this._nrLogs) { process.stderr.write(']\n'); } if (data) { process.stdout.write(this._stringify(data) + '\n'); } }; JsonRenderer.prototype.error = function (err) { var message = err.message; err.id = err.code || 'error'; err.level = 'error'; err.data = err.data || {}; // Need to set message again because it is // not enumerable in some cases delete err.message; err.message = message; this.log(err); this.end(); }; JsonRenderer.prototype.log = function (log) { if (!this._nrLogs) { process.stderr.write('['); } else { process.stderr.write(', '); } process.stderr.write(this._stringify(log)); this._nrLogs++; }; JsonRenderer.prototype.updateAvailable = function () {}; // ------------------------- JsonRenderer.prototype._stringify = function (log) { // To json var str = JSON.stringify(log, null, ' '); // Remove colors in case some log has colors.. str = str.replace(/\x1B\[\d+m/g, ''); return str; }; module.exports = JsonRenderer;
Fix log of errors not rendering the error message/data in the JSON renderer.
Fix log of errors not rendering the error message/data in the JSON renderer.
JavaScript
mit
mattpugh/bower,haolee1990/bower,Teino1978-Corp/bower,unilynx/bower,lukemelia/bower,angeliaz/bower,Jeremy017/bower,Teino1978-Corp/Teino1978-Corp-bower,jvkops/bower,pjump/bower,rajzshkr/bower,pwang2/bower,bower/bower,return02/bower,fernandomoraes/bower,wenyanw/bower,sanyueyu/bower,rlugojr/bower,supriyantomaftuh/bower,grigorkh/bower,kevinjdinicola/hg-bower,magnetech/bower,thinkxl/bower,XCage15/bower,jisaacks/bower,Blackbaud-EricSlater/bower,insanehong/bower,M4gn4tor/bower,akaash-nigam/bower,pertrai1/bower,xfstudio/bower,DevVersion/bower,vladikoff/bower,adriaanthomas/bower,cnbin/bower,amilaonbitlab/bower,msbit/bower,PimsJay01/bower,dreamauya/bower,yinhe007/bower,gronke/bower,twalpole/bower,yuhualingfeng/bower,JFrogDev/bower-art,watilde/bower,DrRataplan/bower,buildsample/bower,prometheansacrifice/bower,krahman/bower,skinzer/bower,Connectlegendary/bower,ThiagoGarciaAlves/bower,Jinkwon/naver-bower-cli,jodytate/bower,kodypeterson/bower,Backbase/bower,liorhson/bower,kruppel/bower,omurbilgili/bower,hyperweb2/upt,gorcz/bower,fewspider/bower,mex/bower,cgvarela/bower,TooHTooH/bower
--- +++ @@ -13,8 +13,16 @@ }; JsonRenderer.prototype.error = function (err) { + var message = err.message; + err.id = err.code || 'error'; err.level = 'error'; + err.data = err.data || {}; + + // Need to set message again because it is + // not enumerable in some cases + delete err.message; + err.message = message; this.log(err); this.end();
d03a772f541090e8d9165314371cb222702d435d
test/queue/with_delay_test.js
test/queue/with_delay_test.js
'use strict'; require('../helpers'); const assert = require('assert'); const Ironium = require('../..'); describe('Queue with delay', function() { const captureQueue = Ironium.queue('capture'); // Capture processed jobs here. const processed = []; before(function() { captureQueue.eachJob(function(job) { processed.push(job); return Promise.resolve(); }); }); before(function() { return captureQueue.delayJob('delayed', '2s'); }); before(Ironium.runOnce); it('should not process immediately', function() { assert.equal(processed.length, 0); }); describe('after short delay', function() { before(function(done) { setTimeout(done, 1500); }); before(Ironium.runOnce); it('should not process job', function() { assert.equal(processed.length, 0); }); }); describe('after sufficient delay', function() { before(function(done) { setTimeout(done, 1000); }); before(Ironium.runOnce); it('should process job', function() { assert.equal(processed.length, 1); assert.equal(processed[0], 'delayed'); }); }); });
'use strict'; require('../helpers'); const assert = require('assert'); const Ironium = require('../..'); const ms = require('ms'); const TimeKeeper = require('timekeeper'); describe('Queue with delay', function() { const captureQueue = Ironium.queue('capture'); // Capture processed jobs here. const processed = []; before(function() { captureQueue.eachJob(function(job) { processed.push(job); return Promise.resolve(); }); }); before(function() { return captureQueue.delayJob('delayed', '2m'); }); before(Ironium.runOnce); it('should not process immediately', function() { assert.equal(processed.length, 0); }); describe('after 1 minute', function() { before(function() { TimeKeeper.travel(Date.now() + ms('1m')); }); before(Ironium.runOnce); it('should not process job', function() { assert.equal(processed.length, 0); }); }); describe('after 2 minutes', function() { before(function() { TimeKeeper.travel(Date.now() + ms('2m')); }); before(Ironium.runOnce); it('should process job', function() { assert.equal(processed.length, 1); assert.equal(processed[0], 'delayed'); }); }); });
Update delayJob test to use TimeKeeper
Update delayJob test to use TimeKeeper
JavaScript
mit
assaf/ironium
--- +++ @@ -1,7 +1,9 @@ 'use strict'; require('../helpers'); -const assert = require('assert'); -const Ironium = require('../..'); +const assert = require('assert'); +const Ironium = require('../..'); +const ms = require('ms'); +const TimeKeeper = require('timekeeper'); describe('Queue with delay', function() { @@ -19,18 +21,20 @@ }); before(function() { - return captureQueue.delayJob('delayed', '2s'); + return captureQueue.delayJob('delayed', '2m'); }); + before(Ironium.runOnce); it('should not process immediately', function() { assert.equal(processed.length, 0); }); - describe('after short delay', function() { - before(function(done) { - setTimeout(done, 1500); + describe('after 1 minute', function() { + before(function() { + TimeKeeper.travel(Date.now() + ms('1m')); }); + before(Ironium.runOnce); it('should not process job', function() { @@ -38,10 +42,11 @@ }); }); - describe('after sufficient delay', function() { - before(function(done) { - setTimeout(done, 1000); + describe('after 2 minutes', function() { + before(function() { + TimeKeeper.travel(Date.now() + ms('2m')); }); + before(Ironium.runOnce); it('should process job', function() {
775bf364fc17512bd16827526bd7745352c015a6
src/js/models/model-timeline-base.js
src/js/models/model-timeline-base.js
YUI.add("model-timeline-base", function(Y) { "use strict"; var models = Y.namespace("Falco.Models"), TimelineBase; TimelineBase = Y.Base.create("timeline", Y.Model, [], { initializer : function(config) { var tweets; config || (config = {}); tweets = new models.Tweets({ items : config.tweets || [] }); this.set("tweets", tweets); this._handles = [ tweets.after([ "more", "add" ], this._tweetAdd, this) ]; this.publish("tweets", { preventable : false }); }, destructor : function() { new Y.EventTarget(this._handles).detach(); this._handles = null; this.get("tweets").destroy(); }, // Override .toJSON() to make sure tweets are included toJSON : function() { var json = TimelineBase.superclass.toJSON.apply(this); json.tweets = json.tweets.toJSON(); return json; }, _tweetAdd : function(e) { var count = 1; // Don't notify for tweets from cache if(e.cached) { return; } if(e.parsed || e.models) { count = (e.parsed || e.models).length; } this.fire("tweets", { count : count }); } }); models.TimelineBase = TimelineBase; }, "@VERSION@", { requires : [ // YUI "base-build", "model", // Models "model-list-tweets" ] });
YUI.add("model-timeline-base", function(Y) { "use strict"; var models = Y.namespace("Falco.Models"), TimelineBase; TimelineBase = Y.Base.create("timeline", Y.Model, [], { initializer : function(config) { var tweets; if(!config) { config = {}; } tweets = new models.Tweets({ items : config.tweets || [] }); this.set("tweets", tweets); this._handles = [ tweets.after([ "more", "add" ], this._tweetAdd, this) ]; this.publish("tweets", { preventable : false }); }, destructor : function() { new Y.EventTarget(this._handles).detach(); this._handles = null; this.get("tweets").destroy(); }, // Override .toJSON() to make sure tweets are included toJSON : function() { var json = TimelineBase.superclass.toJSON.apply(this); json.tweets = json.tweets.toJSON(); return json; }, _tweetAdd : function(e) { // Don't notify for tweets from cache // TODO: is this ever hit? if(e.cached) { debugger; return; } this.fire("tweets", { count : e.model ? 1 : (e.parsed || e.models).length }); } }); models.TimelineBase = TimelineBase; }, "@VERSION@", { requires : [ // YUI "base-build", "model", // Models "model-list-tweets" ] });
Clean up how timelines respond to tweets
Clean up how timelines respond to tweets
JavaScript
mit
tivac/falco,tivac/falco
--- +++ @@ -9,7 +9,9 @@ initializer : function(config) { var tweets; - config || (config = {}); + if(!config) { + config = {}; + } tweets = new models.Tweets({ items : config.tweets || [] @@ -42,19 +44,16 @@ }, _tweetAdd : function(e) { - var count = 1; - // Don't notify for tweets from cache + // TODO: is this ever hit? if(e.cached) { + debugger; + return; } - if(e.parsed || e.models) { - count = (e.parsed || e.models).length; - } - this.fire("tweets", { - count : count + count : e.model ? 1 : (e.parsed || e.models).length }); } });
bfc7ae42c589838f6ae04b3d2e944d585e8382bb
www/app/app.js
www/app/app.js
'use strict'; /* * Angular Seed - v0.1 * https://github.com/rachellcarbone/angular-seed/ * Copyright (c) 2015 Rachel L Carbone; Licensed MIT */ // Include modules, and run application. angular.module('theApp', [ 'ui.bootstrap', 'ui.bootstrap.showErrors', 'datatables', 'datatables.bootstrap', 'ngCookies', 'ngMessages', 'angular-md5', 'api.v1', 'rcDirectives', 'rcCart', 'app.config', 'app.router', 'app.run', 'app.run.dev', 'app.filters', 'app.services' ]);
'use strict'; /* * Angular Seed - v0.1 * https://github.com/rachellcarbone/angular-seed/ * Copyright (c) 2015 Rachel L Carbone; Licensed MIT */ // Include modules, and run application. angular.module('theApp', [ 'ui.bootstrap', 'ui.bootstrap.showErrors', 'datatables', 'datatables.bootstrap', 'ngCookies', 'ngMessages', 'ngFileUpload', 'ngImgCrop', 'angular-md5', 'api.v1', 'rcDirectives', 'rcCart', 'app.config', 'app.router', 'app.run', 'app.run.dev', 'app.filters', 'app.services' ]);
Include new libraries in the project.
Include new libraries in the project.
JavaScript
mit
rachellcarbone/angular-seed,rachellcarbone/angular-seed,rachellcarbone/angular-seed
--- +++ @@ -14,6 +14,8 @@ 'datatables.bootstrap', 'ngCookies', 'ngMessages', + 'ngFileUpload', + 'ngImgCrop', 'angular-md5', 'api.v1', 'rcDirectives',