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 |
|---|---|---|---|---|---|---|---|---|---|---|
039bda9c3ffb82749732ef1109c869c3a733d003 | posts/index.js | posts/index.js | module.exports = [
{
"title": "BibleJS NPM Module"
, "slug": "bible-js"
, "publishedAt": "25-05-2014"
, "content": "bible-js.md"
}
, {
"title": "Testing Code Highlight"
, "slug": "testing-code-highlight"
, "publishedAt": "18-05-2014"
, "content": "testing-code-highlight.md"
}
, {
"title": "Hello World"
, "slug": "hello-world"
, "publishedAt": "15-05-2014"
, "content": "hello-world.md"
}
];
| module.exports = [
{
"title": "BibleJS NPM Module"
, "slug": "bible-js"
, "publishedAt": "25-05-2014"
, "path": "bible-js.md"
}
, {
"title": "Testing Code Highlight"
, "slug": "testing-code-highlight"
, "publishedAt": "18-05-2014"
, "path": "testing-code-highlight.md"
}
, {
"title": "Hello World"
, "slug": "hello-world"
, "publishedAt": "15-05-2014"
, "path": "hello-world.md"
}
];
| Save name of md file in path field | Save name of md file in path field
| JavaScript | mit | IonicaBizau/ionicabizau.net,IonicaBizau/ionicabizau.net | ---
+++
@@ -3,18 +3,18 @@
"title": "BibleJS NPM Module"
, "slug": "bible-js"
, "publishedAt": "25-05-2014"
- , "content": "bible-js.md"
+ , "path": "bible-js.md"
}
, {
"title": "Testing Code Highlight"
, "slug": "testing-code-highlight"
, "publishedAt": "18-05-2014"
- , "content": "testing-code-highlight.md"
+ , "path": "testing-code-highlight.md"
}
, {
"title": "Hello World"
, "slug": "hello-world"
, "publishedAt": "15-05-2014"
- , "content": "hello-world.md"
+ , "path": "hello-world.md"
}
]; |
60679fa6c82d5b858d9323bfeff41612c6b8b7b3 | lib/parser.js | lib/parser.js | var sax = require('sax')
var parser = {}
parser.stream = function () {
return sax.createStream({
trim: true,
normalize: true,
lowercase: true
})
}
parser.capture = function (stream) {
return new Promise(function (resolve, reject) {
var frames = [{}]
stream.on('opentagstart', (node) => frames.push({}))
stream.on('attribute', (node) => frames[frames.length - 1][node.name] = node.value)
stream.on('text', (text) => text.trim().length && (frames[frames.length - 1] = text.trim()))
stream.on('closetag', (name) => frames[frames.length - 2][name] = []
.concat(frames[frames.length - 2][name] || [])
.concat(frames.pop()))
stream.on('end', () => resolve(frames.pop()))
})
}
module.exports = parser
| var sax = require('sax')
var parser = {}
parser.stream = function () {
return sax.createStream({
trim: true,
normalize: true,
lowercase: true
})
}
parser.capture = function (stream) {
return new Promise(function (resolve, reject) {
var frames = [{}]
stream.on('opentagstart', (node) => frames.push({}))
stream.on('attribute', (node) => frames[frames.length - 1][node.name] = node.value)
stream.on('text', (text) => text.trim().length && (frames[frames.length - 1] = text.trim()))
stream.on('closetag', (name) => frames[frames.length - 2][name] = []
.concat(frames[frames.length - 2][name] || [])
.concat(frames.pop()))
stream.on('end', () => resolve(frames.pop()))
stream.on('error', reject)
})
}
module.exports = parser
| Throw an error if the XML is invalid. | Throw an error if the XML is invalid.
| JavaScript | mpl-2.0 | Schoonology/boardgamegeek | ---
+++
@@ -20,6 +20,7 @@
.concat(frames[frames.length - 2][name] || [])
.concat(frames.pop()))
stream.on('end', () => resolve(frames.pop()))
+ stream.on('error', reject)
})
}
|
902bf0c2a79c6967ad339adee867893e86763663 | lib/runner.js | lib/runner.js | var util = require("util");
var thunkify = require("thunkify");
var spawn = require("child_process").spawn;
var debug = require("debug")("offload:runner");
var runner = function(cmd, args, body, cb){
debug("preping job");
var envCopy = util._extend({}, process.env);
envCopy.OFFLOAD_WORKSPACE = this.workspace;
var opts = {
stdio: 'pipe',
cwd: process.cwd(),
env: envCopy
};
var jobProcess = spawn(cmd, args, opts);
debug("sending data to cmd");
//handle if body is undefined
jobProcess.stdin.write(body);
jobProcess.stdin.end();
var result = null;
jobProcess.stdout.on("data", function(data){
debug("new data received - buffer");
if (result === null) {
result = data;
}
else{
result = Buffer.concat([result, data]);
}
});
var error = "";
jobProcess.stderr.on("data", function(data){
debug("new error or warning recived");
error += data.toString();
});
jobProcess.on("exit", function(code){
if (code != 0) {
debug("job done with error");
cb({cmd:cmd, args:args});
}
else{
cb(null, result);
debug("job done");
}
});
}
module.exports = thunkify(runner);
| var util = require("util");
var thunkify = require("thunkify");
var spawn = require("child_process").spawn;
var debug = require("debug")("offload:runner");
var runner = function(cmd, args, body, cb){
debug("preping job");
var envCopy = util._extend({}, process.env);
envCopy.OFFLOAD_WORKSPACE = this.workspace;
var opts = {
stdio: 'pipe',
cwd: process.cwd(),
env: envCopy
};
var jobProcess = spawn(cmd, args, opts);
debug("sending data to cmd");
//handle if body is undefined
jobProcess.stdin.write(body);
jobProcess.stdin.end();
var result = null;
jobProcess.stdout.on("data", function(data){
debug("new data received - buffer");
if (result === null) {
result = data;
}
else{
result = Buffer.concat([result, data]);
}
});
var error = "";
jobProcess.stderr.on("data", function(data){
debug("new error or warning recived");
error += data.toString();
});
jobProcess.on("exit", function(code){
if (code != 0) {
debug("job done with error");
cb({cmd:cmd, args:args, error:error});
}
else{
cb(null, result);
debug("job done");
}
});
}
module.exports = thunkify(runner);
| Send back stderr for command-line jobs | Send back stderr for command-line jobs
| JavaScript | mit | socialtables/offload | ---
+++
@@ -45,7 +45,7 @@
jobProcess.on("exit", function(code){
if (code != 0) {
debug("job done with error");
- cb({cmd:cmd, args:args});
+ cb({cmd:cmd, args:args, error:error});
}
else{
cb(null, result); |
b58c49d85de57f7def4917f0df99fec2391f2114 | app/sentry.js | app/sentry.js | var Raven = require('raven-js');
Raven
.config('https://fde1d4c9741e4ef3a3416e4e88b61392@sentry.data.gouv.fr/17', {
ignoreUrls: [
/^file:\/\//i
]
})
.addPlugin(require('raven-js/plugins/angular'), window.angular)
.install();
| var Raven = require('raven-js');
Raven
.config('https://fde1d4c9741e4ef3a3416e4e88b61392@sentry.data.gouv.fr/17', {
whitelistUrls: [
/mes-aides\.gouv\.fr/
],
ignoreUrls: [
/^file:\/\//i
]
})
.addPlugin(require('raven-js/plugins/angular'), window.angular)
.install();
| Add production domain to whitelistUrls. | Add production domain to whitelistUrls.
| JavaScript | agpl-3.0 | sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui | ---
+++
@@ -2,6 +2,9 @@
Raven
.config('https://fde1d4c9741e4ef3a3416e4e88b61392@sentry.data.gouv.fr/17', {
+ whitelistUrls: [
+ /mes-aides\.gouv\.fr/
+ ],
ignoreUrls: [
/^file:\/\//i
] |
66ca45a0a094507eb319ba594c9a4030128dc776 | index.js | index.js | var GraphemeBreaker = require('grapheme-breaker');
var assign = require('object-assign');
/**
* Extracts a section of a string and returns a new string.
*/
function slice(str, beginSlice, endSlice) {
return GraphemeBreaker.break(str)
.slice(beginSlice, endSlice)
.join('');
}
/**
* Truncates string if it’s longer than the given maximum string length. The last characters of the truncated string are
* replaced with the omission string which defaults to "…".
* Similar to https://lodash.com/docs#trunc but doesn't have the separator option yet.
*/
function truncate(str, options) {
options = assign({
length: 24,
omission: '...'
}, options);
if (GraphemeBreaker.countBreaks(str) <= options.length) {
return str;
}
var length = options.length - options.omission.length;
return slice(str, 0, length) + options.omission;
}
exports.slice = slice;
exports.truncate = truncate;
| var GraphemeBreaker = require('grapheme-breaker');
var assign = require('object-assign');
/**
* Extracts a section of a string and returns a new string.
*/
function slice(str, beginSlice, endSlice) {
return GraphemeBreaker.break(str)
.slice(beginSlice, endSlice)
.join('');
}
/**
* Truncates string if it’s longer than the given maximum string length. The last characters of the truncated string are
* replaced with the omission string which defaults to "…".
* Similar to https://lodash.com/docs#trunc but doesn't have the separator option yet.
*/
function truncate(str, options) {
options = assign({
length: 24,
omission: '...'
}, options);
if (GraphemeBreaker.countBreaks(str) <= options.length) {
return str;
}
var length = options.length - options.omission.length;
if (length < 0) {
length = 0;
}
return slice(str, 0, length) + options.omission;
}
exports.slice = slice;
exports.truncate = truncate;
| Fix truncate incorrectly handling length < omission.length | Fix truncate incorrectly handling length < omission.length
| JavaScript | mit | Lokiedu/grapheme-utils | ---
+++
@@ -27,6 +27,10 @@
var length = options.length - options.omission.length;
+ if (length < 0) {
+ length = 0;
+ }
+
return slice(str, 0, length) + options.omission;
}
|
64ffd76107741f8894faf91f3de1d2fc54682bbf | index.js | index.js | var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/dist'));
// views is directory for all template files
// app.set('views', __dirname + '/views');
// app.set('view engine', 'ejs');
app.get('/', function(request, response) {
response.render('dist');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
| var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/dist'));
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
| Trim out old demo code | Trim out old demo code
| JavaScript | mit | RobEasthope/lazarus,RobEasthope/lazarus | ---
+++
@@ -5,14 +5,6 @@
app.use(express.static(__dirname + '/dist'));
-// views is directory for all template files
-// app.set('views', __dirname + '/views');
-// app.set('view engine', 'ejs');
-
-app.get('/', function(request, response) {
- response.render('dist');
-});
-
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
}); |
2e045cd85f4e1ce600eeecd378c51184a8d60776 | schema/me/update_collector_profile.js | schema/me/update_collector_profile.js | import gravity from '../../lib/loaders/gravity';
import { CollectorProfileType } from './collector_profile';
import {
GraphQLBoolean,
} from 'graphql';
export default {
type: CollectorProfileType,
decription: 'Updating a collector profile (loyalty applicant status).',
args: {
loyalty_applicant: {
type: GraphQLBoolean,
},
professional_buyer: {
type: GraphQLBoolean,
},
},
resolve: (root, {
loyalty_applicant,
professional_buyer,
}, request, { rootValue: { accessToken } }) => {
if (!accessToken) return null;
return gravity.with(accessToken, {
method: 'POST',
})('me/collector_profile', { loyalty_applicant, professional_buyer });
},
};
| import gravity from '../../lib/loaders/gravity';
import { CollectorProfileType } from './collector_profile';
import {
GraphQLBoolean,
} from 'graphql';
export default {
type: CollectorProfileType,
decription: 'Updating a collector profile (loyalty applicant status).',
args: {
loyalty_applicant: {
type: GraphQLBoolean,
},
professional_buyer: {
type: GraphQLBoolean,
},
},
resolve: (root, {
loyalty_applicant,
professional_buyer,
}, request, { rootValue: { accessToken } }) => {
if (!accessToken) return null;
return gravity.with(accessToken, {
method: 'PUT',
})('me/collector_profile', { loyalty_applicant, professional_buyer });
},
};
| Switch to PUT over POST | Switch to PUT over POST
| JavaScript | mit | mzikherman/metaphysics-1,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1,broskoski/metaphysics,craigspaeth/metaphysics,craigspaeth/metaphysics,artsy/metaphysics,artsy/metaphysics,mzikherman/metaphysics-1 | ---
+++
@@ -21,7 +21,7 @@
}, request, { rootValue: { accessToken } }) => {
if (!accessToken) return null;
return gravity.with(accessToken, {
- method: 'POST',
+ method: 'PUT',
})('me/collector_profile', { loyalty_applicant, professional_buyer });
},
}; |
c9f287a5f683a53eed3b18646f29b047c410ea4f | src/updater/updaters/MerchandisesUpdater.js | src/updater/updaters/MerchandisesUpdater.js | const Updater = require('./Updater');
const SplatNet = require('../splatnet');
const { getOriginalGear } = require('../../js/splatoon');
class MerchandisesUpdater extends Updater {
constructor() {
super({
name: 'Merchandises',
filename: 'merchandises.json',
request: (splatnet) => splatnet.getMerchandises(),
rootKeys: ['merchandises'],
imagePaths: [
'$..gear.image',
'$..gear.brand.image',
'$..gear.brand.frequent_skill.image',
'$..skill.image',
],
});
}
processData(data) {
for (let merchandise of data.merchandises)
merchandise.original_gear = getOriginalGear(merchandise.gear);
return data;
}
}
module.exports = MerchandisesUpdater;
| const Updater = require('./Updater');
const SplatNet = require('../splatnet');
const { getOriginalGear } = require('../../js/splatoon');
class MerchandisesUpdater extends Updater {
constructor() {
super({
name: 'Merchandises',
filename: 'merchandises.json',
request: (splatnet) => splatnet.getMerchandises(),
rootKeys: ['merchandises'],
imagePaths: [
'$..gear.image',
'$..gear.brand.image',
'$..gear.brand.frequent_skill.image',
'$..skill.image',
],
});
}
processData(data) {
for (let merchandise of data.merchandises) {
let originalGear = getOriginalGear(merchandise.gear);
// We don't need the brand data since it should match the SplatNet gear's brand
if (originalGear)
delete originalGear.brand
merchandise.original_gear = originalGear;
}
return data;
}
}
module.exports = MerchandisesUpdater;
| Remove original_gear brand data from merchandises.json | Remove original_gear brand data from merchandises.json
This is a bit redundant and doesn't really add anything we don't already have. | JavaScript | mit | misenhower/splatoon2.ink,misenhower/splatoon2.ink,misenhower/splatoon2.ink | ---
+++
@@ -19,8 +19,15 @@
}
processData(data) {
- for (let merchandise of data.merchandises)
- merchandise.original_gear = getOriginalGear(merchandise.gear);
+ for (let merchandise of data.merchandises) {
+ let originalGear = getOriginalGear(merchandise.gear);
+
+ // We don't need the brand data since it should match the SplatNet gear's brand
+ if (originalGear)
+ delete originalGear.brand
+
+ merchandise.original_gear = originalGear;
+ }
return data;
} |
269ccb8878f11531b71df3dbb1d990317b2a275b | server.js | server.js | var express = require('express');
var port = process.env.PORT || 3333;
var app = express();
app.use(express.static(__dirname + '/dev/patterns'));
app.get('/', function (req, res) {
res.sendFile('index.html');
});
app.listen(port);
| var express = require('express');
var port = process.env.PORT || 3333;
var app = express();
// Controlling shutdown of nodemon
// https://github.com/remy/nodemon#controlling-shutdown-of-your-script
process.once('SIGUSR2', function () {
process.kill(process.pid, 'SIGUSR2');
});
app.use(express.static(__dirname + '/dev/patterns'));
app.get('/', function (req, res) {
res.sendFile('index.html');
});
app.listen(port);
| Add process killer for controlling shutdown of nodemon When manually starting and stopping `npm run dev` script, which includes nodemon, the nodemon process doesn't always exit cleanly. This code (I think) controls the shutdown process so that there's always a clean exit | Add process killer for controlling shutdown of nodemon
When manually starting and stopping `npm run dev` script, which includes
nodemon, the nodemon process doesn't always exit cleanly.
This code (I think) controls the shutdown process so that there's always
a clean exit
| JavaScript | apache-2.0 | carbon-design-system/carbon-components,carbon-design-system/carbon-components,carbon-design-system/carbon-components | ---
+++
@@ -1,6 +1,13 @@
var express = require('express');
var port = process.env.PORT || 3333;
var app = express();
+
+
+// Controlling shutdown of nodemon
+// https://github.com/remy/nodemon#controlling-shutdown-of-your-script
+process.once('SIGUSR2', function () {
+ process.kill(process.pid, 'SIGUSR2');
+});
app.use(express.static(__dirname + '/dev/patterns'));
|
c5e1d62e88221c0780c04683b8f66a01a4008f75 | server.js | server.js | 'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000
var slapp = Slapp({
// Beep Boop sets the SLACK_VERIFY_TOKEN env var
verify_token: process.env.SLACK_VERIFY_TOKEN,
convo_store: ConvoStore(),
context: Context()
})
//*********************************************
// Setup different handlers for messages
//*********************************************
// response to the user typing "help"
slapp.message('^([0-9-]{9,12})$', (msg) => {
msg.say('https://teamleader.zoom.us/j/' + msg.replace('-', ''))
})
// attach Slapp to express server
var server = slapp.attachToExpress(express())
// start http server
server.listen(port, (err) => {
if (err) {
return console.error(err)
}
console.log(`Listening on port ${port}`)
})
| 'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000
var slapp = Slapp({
// Beep Boop sets the SLACK_VERIFY_TOKEN env var
verify_token: process.env.SLACK_VERIFY_TOKEN,
convo_store: ConvoStore(),
context: Context()
})
//*********************************************
// Setup different handlers for messages
//*********************************************
slapp.message('3020791579', (msg) => {
msg.say('https://teamleader.zoom.us/j/' + msg.replace('-', ''))
})
// response to the user typing "help"
slapp.message('^([0-9-]{9,12})$', (msg) => {
msg.say('https://teamleader.zoom.us/j/' + msg.replace('-', ''))
})
// attach Slapp to express server
var server = slapp.attachToExpress(express())
// start http server
server.listen(port, (err) => {
if (err) {
return console.error(err)
}
console.log(`Listening on port ${port}`)
})
| Test of regex is the issue | Test of regex is the issue | JavaScript | mit | andreascreten/zoom-links | ---
+++
@@ -19,6 +19,11 @@
// Setup different handlers for messages
//*********************************************
+slapp.message('3020791579', (msg) => {
+ msg.say('https://teamleader.zoom.us/j/' + msg.replace('-', ''))
+})
+
+
// response to the user typing "help"
slapp.message('^([0-9-]{9,12})$', (msg) => {
msg.say('https://teamleader.zoom.us/j/' + msg.replace('-', '')) |
bb0e24071e545d06b62d1028f53bfa0a0850361d | index.js | index.js | 'use strict';
var isSvg = require('is-svg');
var SVGO = require('svgo');
var through = require('through2');
module.exports = function (opts) {
opts = opts || {};
return through.ctor({objectMode: true}, function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
if (!isSvg(file.contents)) {
cb(null, file);
return;
}
try {
var svgo = new SVGO({
multipass: opts.multipass || false,
plugins: opts.plugins || []
});
svgo.optimize(file.contents.toString('utf8'), function (res) {
if (res.data && res.data.length) {
res.data = res.data.replace(/&(?!amp;)/g, '&');
}
res.data = new Buffer(res.data);
if (res.data.length < file.contents.length) {
file.contents = res.data;
}
cb(null, file);
});
} catch (err) {
cb(err);
}
});
};
| 'use strict';
var isSvg = require('is-svg');
var SVGO = require('svgo');
var through = require('through2');
module.exports = function (opts) {
opts = opts || {};
return through.ctor({objectMode: true}, function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
if (!isSvg(file.contents)) {
cb(null, file);
return;
}
try {
var svgo = new SVGO({
multipass: opts.multipass || false,
plugins: opts.plugins || []
});
svgo.optimize(file.contents.toString('utf8'), function (res) {
if (!res.data) {
cb(null, file);
}
if (res.data && res.data.length) {
res.data = res.data.replace(/&(?!amp;)/g, '&');
}
res.data = new Buffer(res.data);
if (res.data.length < file.contents.length) {
file.contents = res.data;
}
cb(null, file);
});
} catch (err) {
cb(err);
}
});
};
| Return the original file if SVGO fails | Return the original file if SVGO fails
| JavaScript | mit | imagemin/imagemin-svgo | ---
+++
@@ -30,6 +30,10 @@
});
svgo.optimize(file.contents.toString('utf8'), function (res) {
+ if (!res.data) {
+ cb(null, file);
+ }
+
if (res.data && res.data.length) {
res.data = res.data.replace(/&(?!amp;)/g, '&');
} |
b22c3e01fb12c170f651f92758241ddf1499990b | index.js | index.js | module.exports = asString
module.exports.add = append
function asString(fonts) {
var href = getHref(fonts)
return '<link href="' + href + '" rel="stylesheet" type="text/css">'
}
function asElement(fonts) {
var href = getHref(fonts)
var link = document.createElement('link')
link.setAttribute('href', href)
link.setAttribute('rel', 'stylesheet')
link.setAttribute('type', 'text/css')
return link
}
function getHref(fonts) {
var family = Object.keys(fonts).map(function(name) {
var details = fonts[name]
name = name.replace(/\s+/, '+')
return typeof details === 'boolean'
? name
: name + ':' + makeArray(details).join(',')
}).join('|')
return 'http://fonts.googleapis.com/css?family=' + family
}
function append(fonts) {
var link = asElement(fonts)
document.head.appendChild(link)
return link
}
function makeArray(arr) {
return Array.isArray(arr) ? arr : [arr]
}
| module.exports = asString
module.exports.add = append
function asString(fonts) {
var href = getHref(fonts)
return '<link href="' + href + '" rel="stylesheet" type="text/css">'
}
function asElement(fonts) {
var href = getHref(fonts)
var link = document.createElement('link')
link.setAttribute('href', href)
link.setAttribute('rel', 'stylesheet')
link.setAttribute('type', 'text/css')
return link
}
function getHref(fonts) {
var family = Object.keys(fonts).map(function(name) {
var details = fonts[name]
name = name.replace(/\s+/, '+')
return typeof details === 'boolean'
? name
: name + ':' + makeArray(details).join(',')
}).join('|')
return '//fonts.googleapis.com/css?family=' + family
}
function append(fonts) {
var link = asElement(fonts)
document.head.appendChild(link)
return link
}
function makeArray(arr) {
return Array.isArray(arr) ? arr : [arr]
}
| Use a protocol relative URL so the package can be used other HTTPS as well | Use a protocol relative URL so the package can be used other HTTPS as well | JavaScript | mit | hughsk/google-fonts,hughsk/google-fonts | ---
+++
@@ -24,7 +24,7 @@
: name + ':' + makeArray(details).join(',')
}).join('|')
- return 'http://fonts.googleapis.com/css?family=' + family
+ return '//fonts.googleapis.com/css?family=' + family
}
function append(fonts) { |
e81cde0e9247ef9b52e50bada6eb2cc0e804ddf4 | src/systems/simulation/handle-collisions.js | src/systems/simulation/handle-collisions.js | "use strict";
var onEntityDelete = require("splat-ecs/lib/systems/box-collider").onEntityDelete;
function getCamera(entities) {
return entities[1];
}
module.exports = function(ecs, data) { // eslint-disable-line no-unused-vars
ecs.addEach(function(entity, elapsed) { // eslint-disable-line no-unused-vars
if (entity.collisions.length === 0) {
return;
}
entity.collisions.forEach(function(id) {
var other = data.entities.entities[id];
if (other.sticky) {
return;
}
data.canvas.width += 50;
data.canvas.height += 50;
other.match = {
id: entity.id,
offsetX: other.position.x - entity.position.x,
offsetY: other.position.y - entity.position.y
};
other.sticky = true;
other.velocity = { x: 0, y: 0 };
onEntityDelete(other, data);
});
var camera = getCamera(data.entities.entities);
camera.size.width = data.canvas.width;
camera.size.height = data.canvas.height;
}, ["sticky"]);
};
| "use strict";
var onEntityDelete = require("splat-ecs/lib/systems/box-collider").onEntityDelete;
function getCamera(entities) {
return entities[1];
}
module.exports = function(ecs, data) { // eslint-disable-line no-unused-vars
ecs.addEach(function(entity, elapsed) { // eslint-disable-line no-unused-vars
if (entity.collisions.length === 0) {
return;
}
var player = data.entities.entities[0];
entity.collisions.forEach(function(id) {
var other = data.entities.entities[id];
if (other.sticky) {
return;
}
data.canvas.width += 50;
data.canvas.height += 50;
other.match = {
id: player.id,
offsetX: other.position.x - player.position.x,
offsetY: other.position.y - player.position.y
};
other.sticky = true;
other.velocity = { x: 0, y: 0 };
onEntityDelete(other, data);
});
var camera = getCamera(data.entities.entities);
camera.size.width = data.canvas.width;
camera.size.height = data.canvas.height;
}, ["sticky"]);
};
| Attach to player, not other things | Attach to player, not other things
| JavaScript | mit | TwoScoopGames/Cluster-Junk,TwoScoopGames/Cluster-Junk,TwoScoopGames/Cluster-Junk | ---
+++
@@ -11,6 +11,7 @@
if (entity.collisions.length === 0) {
return;
}
+ var player = data.entities.entities[0];
entity.collisions.forEach(function(id) {
var other = data.entities.entities[id];
if (other.sticky) {
@@ -21,9 +22,9 @@
data.canvas.height += 50;
other.match = {
- id: entity.id,
- offsetX: other.position.x - entity.position.x,
- offsetY: other.position.y - entity.position.y
+ id: player.id,
+ offsetX: other.position.x - player.position.x,
+ offsetY: other.position.y - player.position.y
};
other.sticky = true;
other.velocity = { x: 0, y: 0 }; |
c46bdbc1225dc1883c71cb6c32363573d7beab28 | server.js | server.js | var express = require('express')
var expressApp = express()
var path = require('path')
var pickerApp = require('./src/bootstrap')
var registerRoutes = require('./src/routes')
var port = 8080
// Open up the static files
expressApp.use(express.static('dist'))
// Serve index.html
expressApp.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
})
// Register API routes
registerRoutes(expressApp, pickerApp)
// Listen
expressApp.listen(port, function (err) {
if (err) {
console.error(err)
return
}
var uri = 'http://localhost:' + port
console.log('Listening at ' + port + '...\n')
})
| var express = require('express')
var expressApp = express()
var path = require('path')
var pickerApp = require('./src/bootstrap')
var registerRoutes = require('./src/routes')
var port = 8080
// Open up the static files
expressApp.use(express.static(path.join(__dirname + '/dist')))
// Serve index.html
expressApp.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
})
// Register API routes
registerRoutes(expressApp, pickerApp)
// Listen
expressApp.listen(port, function (err) {
if (err) {
console.error(err)
return
}
var uri = 'http://localhost:' + port
console.log('Listening at ' + port + '...\n')
})
| Use absolute path for serving static files | Use absolute path for serving static files
| JavaScript | mit | cvalarida/name-picker,cvalarida/name-picker | ---
+++
@@ -7,7 +7,7 @@
var port = 8080
// Open up the static files
-expressApp.use(express.static('dist'))
+expressApp.use(express.static(path.join(__dirname + '/dist')))
// Serve index.html
expressApp.get('/', function(req, res) { |
266d52354571e3f341996e1fa1c74c490f290a75 | src/transformers/importExportDeclaration.js | src/transformers/importExportDeclaration.js | import replacePath from "../helpers/replacePath";
export default function (t, path, state, {toMatch, toRemove, toReplace}) {
const pathIsImportDeclaration = path.isImportDeclaration();
const pathToMatch = path.get("source"),
pathToRemove = pathIsImportDeclaration && !path.node.specifiers.length && path,
pathToReplace = pathIsImportDeclaration && path.node.specifiers.length && path;
if(pathToMatch.node) {
replacePath(t, {
pathToMatch,
pathToRemove,
// TODO replacement functionality
pathToReplace,
toMatch, toRemove, toReplace
}, state);
}
} | import replacePath from "../helpers/replacePath";
const replaceImport = (t, replacementObj, pathToReplace) => {
const props = [];
let firstDeclaration, firstIdentifier;
for(let specifier of pathToReplace.node.specifiers) {
if(t.isImportNamespaceSpecifier(specifier)) {
firstDeclaration = t.variableDeclarator(firstIdentifier = specifier.local, replacementObj);
} else {
const isDefaultSpecifier = t.isImportDefaultSpecifier(specifier);
const imported = isDefaultSpecifier ? t.Identifier("default") : specifier.imported;
const local = specifier.local;
const shorthand = !isDefaultSpecifier && imported.start === local.start && imported.end === local.end;
const objectProp = t.objectProperty(
imported,
specifier.local, false, shorthand
);
props.push(objectProp);
}
}
const declarations =
firstDeclaration ?
props.length ?
[firstDeclaration, t.variableDeclarator(t.objectPattern(props, null), firstIdentifier)] : [firstDeclaration] :
props.length ?
[t.variableDeclarator(t.objectPattern(props), replacementObj)] : [];
const variableDeclaration = t.variableDeclaration("const", declarations);
pathToReplace.replaceWith(variableDeclaration);
};
export default function (t, path, state, {toMatch, toRemove, toReplace}) {
const pathIsImportDeclaration = path.isImportDeclaration();
const pathToMatch = path.get("source"),
pathToRemove = pathIsImportDeclaration && !path.node.specifiers.length && path,
pathToReplace = pathIsImportDeclaration && path.node.specifiers.length && path;
if(pathToMatch.node) {
replacePath(t, {
pathToMatch,
pathToRemove,
pathToReplace,
toMatch, toRemove, toReplace,
replaceFn: replaceImport
}, state);
}
} | Allow to replace named imports with objects per property | feat(transformers): Allow to replace named imports with objects per property
| JavaScript | mit | Velenir/babel-plugin-import-redirect | ---
+++
@@ -1,4 +1,38 @@
import replacePath from "../helpers/replacePath";
+
+const replaceImport = (t, replacementObj, pathToReplace) => {
+ const props = [];
+ let firstDeclaration, firstIdentifier;
+
+ for(let specifier of pathToReplace.node.specifiers) {
+ if(t.isImportNamespaceSpecifier(specifier)) {
+ firstDeclaration = t.variableDeclarator(firstIdentifier = specifier.local, replacementObj);
+ } else {
+ const isDefaultSpecifier = t.isImportDefaultSpecifier(specifier);
+
+ const imported = isDefaultSpecifier ? t.Identifier("default") : specifier.imported;
+ const local = specifier.local;
+
+ const shorthand = !isDefaultSpecifier && imported.start === local.start && imported.end === local.end;
+ const objectProp = t.objectProperty(
+ imported,
+ specifier.local, false, shorthand
+ );
+ props.push(objectProp);
+ }
+ }
+
+ const declarations =
+ firstDeclaration ?
+ props.length ?
+ [firstDeclaration, t.variableDeclarator(t.objectPattern(props, null), firstIdentifier)] : [firstDeclaration] :
+ props.length ?
+ [t.variableDeclarator(t.objectPattern(props), replacementObj)] : [];
+
+ const variableDeclaration = t.variableDeclaration("const", declarations);
+
+ pathToReplace.replaceWith(variableDeclaration);
+};
export default function (t, path, state, {toMatch, toRemove, toReplace}) {
const pathIsImportDeclaration = path.isImportDeclaration();
@@ -10,9 +44,9 @@
replacePath(t, {
pathToMatch,
pathToRemove,
- // TODO replacement functionality
pathToReplace,
- toMatch, toRemove, toReplace
+ toMatch, toRemove, toReplace,
+ replaceFn: replaceImport
}, state);
}
} |
0662a23ca1b5b9ac8fd09cd3b94fcf79ccbe37d3 | server/frontend/components/Landing.js | server/frontend/components/Landing.js | import React, { PropTypes, Component } from 'react';
import d3 from 'd3';
//import * as parcoords from './lib/d3.parcoords.js';
import Parallel from './Parallel.js';
export default class Landing extends Component {
constructor() {
super();
this.state = {data: []}
}
// componentDidMount() {
// d3.csv('nutrients.csv', function(error, data) {
// if (error) console.log(error);
// this.setState({data: data});
// console.log('in Landing: ', data.length);
// }.bind(this));
// }
render() {
return (
<div>
<div>Landing Test</div>
<Parallel data={this.state.data} />
</div>
);
}
}
| import React, { PropTypes, Component } from 'react';
import d3 from 'd3';
//import * as parcoords from './lib/d3.parcoords.js';
import Parallel from './Parallel.js';
export default class Landing extends Component {
constructor() {
super();
this.state = {data: []}
}
// componentDidMount() {
// d3.csv('nutrients.csv', function(error, data) {
// if (error) console.log(error);
// this.setState({data: data});
// console.log('in Landing: ', data.length);
// }.bind(this));
// }
render() {
return (
<div>
<Parallel data={this.state.data} />
</div>
);
}
}
| Clean up test text from landing page | Clean up test text from landing page
| JavaScript | mit | benjaminhoffman/Encompass,benjaminhoffman/Encompass,benjaminhoffman/Encompass | ---
+++
@@ -23,7 +23,6 @@
render() {
return (
<div>
- <div>Landing Test</div>
<Parallel data={this.state.data} />
</div>
); |
d80648f8854a168d33eec16bbac453ebbf0b4820 | lib/jsdom/living/aborting/AbortSignal-impl.js | lib/jsdom/living/aborting/AbortSignal-impl.js | "use strict";
const { setupForSimpleEventAccessors } = require("../helpers/create-event-accessor");
const EventTargetImpl = require("../events/EventTarget-impl").implementation;
const Event = require("../generated/Event");
class AbortSignalImpl extends EventTargetImpl {
constructor(args, privateData) {
super();
// make event firing possible
this._ownerDocument = privateData.window.document;
this.aborted = false;
this.abortAlgorithms = new Set();
}
_signalAbort() {
if (this.aborted) {
return;
}
this.aborted = true;
for (const algorithm of this.abortAlgorithms) {
algorithm();
}
this.abortAlgorithms.clear();
this._dispatch(Event.createImpl(["abort"]), false);
}
_addAlgorithm(algorithm) {
if (this.aborted) {
return;
}
this.abortAlgorithms.add(algorithm);
}
_removeAlgorithm(algorithm) {
this.abortAlgorithms.delete(algorithm);
}
}
setupForSimpleEventAccessors(AbortSignalImpl.prototype, ["abort"]);
module.exports = {
implementation: AbortSignalImpl
};
| "use strict";
const { setupForSimpleEventAccessors } = require("../helpers/create-event-accessor");
const EventTargetImpl = require("../events/EventTarget-impl").implementation;
const Event = require("../generated/Event");
class AbortSignalImpl extends EventTargetImpl {
constructor(args, privateData) {
super();
// make event firing possible
this._ownerDocument = privateData.window.document;
this.aborted = false;
this.abortAlgorithms = new Set();
}
_signalAbort() {
if (this.aborted) {
return;
}
this.aborted = true;
for (const algorithm of this.abortAlgorithms) {
algorithm();
}
this.abortAlgorithms.clear();
this._dispatch(Event.createImpl(
[
"abort",
{ bubbles: false, cancelable: false }
],
{ isTrusted: true }
));
}
_addAlgorithm(algorithm) {
if (this.aborted) {
return;
}
this.abortAlgorithms.add(algorithm);
}
_removeAlgorithm(algorithm) {
this.abortAlgorithms.delete(algorithm);
}
}
setupForSimpleEventAccessors(AbortSignalImpl.prototype, ["abort"]);
module.exports = {
implementation: AbortSignalImpl
};
| Set abort event isTrusted to true | Set abort event isTrusted to true
| JavaScript | mit | mzgol/jsdom,mzgol/jsdom,mzgol/jsdom,tmpvar/jsdom,tmpvar/jsdom | ---
+++
@@ -26,7 +26,14 @@
algorithm();
}
this.abortAlgorithms.clear();
- this._dispatch(Event.createImpl(["abort"]), false);
+
+ this._dispatch(Event.createImpl(
+ [
+ "abort",
+ { bubbles: false, cancelable: false }
+ ],
+ { isTrusted: true }
+ ));
}
_addAlgorithm(algorithm) { |
0e54f763654fc79af4005e49dae810c1478fe128 | server.js | server.js | var express = require('express');
var childProcess = require('child_process');
var middleware = require('./config/initializers/middleware.js');
var router = require('./config/routes.js');
var host = process.env.HOST;
var port = process.env.PORT || 4000;
var app = express();
middleware.configure(app);
router.route(app);
host ? app.listen(port, host) : app.listen(port);
setTimeout(function(){
var outgoingPaymentsMonitor = childProcess.spawn("node", ["workers/outgoing_ripple_payments.js"]);
outgoingPaymentsMonitor.stdout.on('data', function(data) {
console.log(data.toString());
});
outgoingPaymentsMonitor.stderr.on('data', function(data) {
console.log(data.toString());
});
},10000);
console.log('Serving HTTP on', (host || 'localhost')+":"+port);
| var express = require('express');
var childProcess = require('child_process');
var middleware = require('./config/initializers/middleware.js');
var router = require('./config/routes.js');
var host = process.env.HOST;
var port = process.env.PORT || 4000;
var app = express();
middleware.configure(app);
router.route(app);
host ? app.listen(port, host) : app.listen(port);
var incomingPaymentsMonitor = childProcess.spawn("node", ["workers/listener.js"]);
incomingPaymentsMonitor.stdout.on('data', function(data){
console.log(data.toString());
});
incomingPaymentsMonitor.stderr.on('data', function(data){
console.log(data.toString());
});
setTimeout(function(){
var outgoingPaymentsMonitor = childProcess.spawn("node", ["workers/outgoing_ripple_payments.js"]);
outgoingPaymentsMonitor.stdout.on('data', function(data) {
console.log(data.toString());
});
outgoingPaymentsMonitor.stderr.on('data', function(data) {
console.log(data.toString());
});
},10000);
console.log('Serving HTTP on', (host || 'localhost')+":"+port);
| Add child process for payments monitor | [FEATURE] Add child process for payments monitor
| JavaScript | isc | zealord/gatewayd,crazyquark/gatewayd,Parkjeahwan/awegeeks,whotooktwarden/gatewayd,xdv/gatewayd,crazyquark/gatewayd,Parkjeahwan/awegeeks,whotooktwarden/gatewayd,zealord/gatewayd,xdv/gatewayd | ---
+++
@@ -10,6 +10,15 @@
router.route(app);
host ? app.listen(port, host) : app.listen(port);
+
+var incomingPaymentsMonitor = childProcess.spawn("node", ["workers/listener.js"]);
+incomingPaymentsMonitor.stdout.on('data', function(data){
+ console.log(data.toString());
+});
+
+incomingPaymentsMonitor.stderr.on('data', function(data){
+ console.log(data.toString());
+});
setTimeout(function(){
var outgoingPaymentsMonitor = childProcess.spawn("node", ["workers/outgoing_ripple_payments.js"]); |
d05d48d6ab8a4fc29412f74247a028ff3921e215 | index.js | index.js | 'use strict';
var PluginError = require('plugin-error'),
through = require('through2'),
inlineCss = require('inline-css');
module.exports = function (opt) {
return through.obj(function (file, enc, cb) {
var self = this,
_opt = JSON.parse(JSON.stringify(opt || {}));
// 'url' option is required
// set it automatically if not provided
if (!_opt.url) {
_opt.url = 'file://' + file.path;
}
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new PluginError('gulp-inline-css', 'Streaming not supported'));
return;
}
inlineCss(file.contents, _opt)
.then(function (html) {
file.contents = new Buffer(String(html));
self.push(file);
return cb();
})
.catch(function (err) {
if (err) {
self.emit('error', new PluginError('gulp-inline-css', err));
}
});
});
};
| 'use strict';
var PluginError = require('plugin-error'),
through = require('through2'),
inlineCss = require('inline-css');
module.exports = function (opt) {
return through.obj(function (file, enc, cb) {
var self = this,
_opt = JSON.parse(JSON.stringify(opt || {}));
// 'url' option is required
// set it automatically if not provided
if (!_opt.url) {
_opt.url = 'file://' + file.path;
}
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new PluginError('gulp-inline-css', 'Streaming not supported'));
return;
}
inlineCss(String(file.contents), _opt)
.then(function (html) {
file.contents = new Buffer(html);
self.push(file);
return cb();
})
.catch(function (err) {
if (err) {
self.emit('error', new PluginError('gulp-inline-css', err));
}
});
});
};
| Convert file to string before sending downstream. | Convert file to string before sending downstream.
| JavaScript | mit | jonkemp/gulp-inline-css,jonkemp/gulp-inline-css | ---
+++
@@ -25,9 +25,9 @@
return;
}
- inlineCss(file.contents, _opt)
+ inlineCss(String(file.contents), _opt)
.then(function (html) {
- file.contents = new Buffer(String(html));
+ file.contents = new Buffer(html);
self.push(file);
|
a1939530519f310e7e4e957b9360ac125ace618a | index.js | index.js | var Batcher = require('byte-stream')
var manualMergeStream = require('manual-merge-stream')
var diff2daff = require('diff2daff')
module.exports = function (diffStream, opts, merge) {
if (!opts) {
opts = {}
}
var limit = (opts.limit || 20) * 2
var batchStream = Batcher(limit)
var vizFn = opts.vizFn || diff2daff
var mergeStream
if (merge) mergeStream = manualMergeStream(vizFn, merge)
else mergeStream = manualMergeStream(vizFn)
return diffStream.pipe(batchStream).pipe(mergeStream)
} | var Batcher = require('byte-stream')
var manualMergeStream = require('manual-merge-stream')
var diff2daff = require('diff2daff')
module.exports = function (diffStream, opts, merge) {
if (!opts) {
opts = {}
}
var limit = (opts.limit || 20) * 2
var batchStream = Batcher(limit)
var opts = {
vizFn: opts.vizFn || diff2daff,
merge: merge
}
return diffStream.pipe(batchStream).pipe(manualMergeStream(opts))
} | Use new manual-merge-stream vizFn opts | Use new manual-merge-stream vizFn opts
| JavaScript | bsd-2-clause | karissa/knead,finnp/knead | ---
+++
@@ -8,11 +8,10 @@
}
var limit = (opts.limit || 20) * 2
var batchStream = Batcher(limit)
- var vizFn = opts.vizFn || diff2daff
+ var opts = {
+ vizFn: opts.vizFn || diff2daff,
+ merge: merge
+ }
- var mergeStream
- if (merge) mergeStream = manualMergeStream(vizFn, merge)
- else mergeStream = manualMergeStream(vizFn)
-
- return diffStream.pipe(batchStream).pipe(mergeStream)
+ return diffStream.pipe(batchStream).pipe(manualMergeStream(opts))
} |
14c2d99e593603f4cd49a1b152f30dbc19ac9cf5 | index.js | index.js | /* eslint-env node */
'use strict';
const htmlTags = require('html-tags');
const diff = require('lodash/difference');
const compileCSS = require('broccoli-postcss');
const removeableElements = () => {
const whitelistedTags = ['html', 'body'];
const removeableTags = diff(htmlTags, whitelistedTags);
const { getItemSync } = process.emberAddonStateBucket;
const htmlElementsInApp = getItemSync('ember-dom-inventory:htmlElements') || [];
return diff(
removeableTags,
htmlElementsInApp
);
};
module.exports = {
name: 'ember-tachyons-sweeper',
postprocessTree(type, tree) {
const selectorBlacklist = removeableElements();
return compileCSS(tree, {
plugins: [
{
module: require('postcss-discard-comments'),
options: {
removeAll: true
},
},
{
module: require('postcss-strip-selectors'),
options: {
selectors: selectorBlacklist,
},
},
{
module: require('postcss-discard-empty'),
options: {},
}
]
});
},
};
| /* eslint-env node */
'use strict';
const htmlTags = require('html-tags');
const diff = require('lodash/difference');
const merge = require('lodash/merge');
const compileCSS = require('broccoli-postcss');
const removeableElements = () => {
const whitelistedTags = ['html', 'body'];
const removeableTags = diff(htmlTags, whitelistedTags);
const { getItemSync } = process.emberAddonStateBucket;
const htmlElementsInApp = getItemSync('ember-dom-inventory:htmlElements') || [];
return diff(
removeableTags,
htmlElementsInApp
);
};
const removeableClasses = () => {
const { getItemSync } = process.emberAddonStateBucket;
const cssClassesInApp = getItemSync('ember-dom-inventory:htmlClasses') || [];
if (cssClassesInApp.length) {
const klasses = cssClassesInApp.join('|');
const regex = new RegExp(`^\\.(?!(${klasses})$).*`)
return [regex];
}
const regexMatchingAllClasses = new RegExp(/^\..*$/);
return [regexMatchingAllClasses];
};
module.exports = {
name: 'ember-tachyons-sweeper',
postprocessTree(type, tree) {
const selectorBlacklist = removeableElements();
const regexenBlacklist = removeableClasses();
return compileCSS(tree, {
plugins: [
{
module: require('postcss-discard-comments'),
options: {
removeAll: true
},
},
{
module: require('postcss-strip-selectors'),
options: {
selectors: selectorBlacklist,
regexen: regexenBlacklist,
},
},
{
module: require('postcss-discard-empty'),
options: {},
}
]
});
},
};
| Remove classes that are not present in application | Remove classes that are not present in application
| JavaScript | mit | fauxton/ember-tachyons-sweeper,fauxton/ember-tachyons-sweeper | ---
+++
@@ -2,6 +2,7 @@
'use strict';
const htmlTags = require('html-tags');
const diff = require('lodash/difference');
+const merge = require('lodash/merge');
const compileCSS = require('broccoli-postcss');
const removeableElements = () => {
@@ -18,12 +19,27 @@
);
};
+const removeableClasses = () => {
+ const { getItemSync } = process.emberAddonStateBucket;
+ const cssClassesInApp = getItemSync('ember-dom-inventory:htmlClasses') || [];
+
+ if (cssClassesInApp.length) {
+ const klasses = cssClassesInApp.join('|');
+ const regex = new RegExp(`^\\.(?!(${klasses})$).*`)
+ return [regex];
+ }
+
+ const regexMatchingAllClasses = new RegExp(/^\..*$/);
+ return [regexMatchingAllClasses];
+};
+
module.exports = {
name: 'ember-tachyons-sweeper',
postprocessTree(type, tree) {
const selectorBlacklist = removeableElements();
+ const regexenBlacklist = removeableClasses();
return compileCSS(tree, {
plugins: [
@@ -37,6 +53,7 @@
module: require('postcss-strip-selectors'),
options: {
selectors: selectorBlacklist,
+ regexen: regexenBlacklist,
},
},
{ |
3ab481b770d2aeb7aba08a73733043210cb6fb99 | index.js | index.js | #!/usr/bin/env node
console.log("Starting bert. Type 'exit' when you're done.")
// TODO: run file watcher
// TODO: add command line option to specify logs location
let logDir = resolveHome('~/.bert/');
// create the log directory if it doesn't already exist
createDirectory(logDir);
// start `script`
var spawn = require('child_process').spawn;
// we won't intercept the output to avoid causing user disruption
spawn('script', ['-F', logDir + generateNewLogName()], { stdio: 'inherit' });
// generate new log to avoid name conflicts
function generateNewLogName() {
// TODO: check directory and add increment for each new session
return 'log';
}
function createDirectory(dir) {
const fs = require('fs');
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
}
// resolve ~ as the user's home directory
function resolveHome(filepath) {
const path = require('path');
if (filepath[0] === '~') {
return path.join(process.env.HOME, filepath.slice(1));
}
return filepath;
}
| #!/usr/bin/env node
console.log("Starting bert. Type 'exit' when you're done.")
// TODO: run file watcher
// TODO: add command line option to specify logs location
let logDir = resolveHome('~/.bert/');
// create the log directory if it doesn't already exist
createDirectory(logDir);
// start `script`
var spawn = require('child_process').spawn;
// we won't intercept the output to avoid causing user disruption
spawn('script', ['-q', '-F', logDir + generateNewLogName()], { stdio: 'inherit' });
// generate new log to avoid name conflicts
function generateNewLogName() {
// TODO: check directory and add increment for each new session
return 'log';
}
function createDirectory(dir) {
const fs = require('fs');
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
}
// resolve ~ as the user's home directory
function resolveHome(filepath) {
const path = require('path');
if (filepath[0] === '~') {
return path.join(process.env.HOME, filepath.slice(1));
}
return filepath;
}
| Disable script start and end messages | Disable script start and end messages
| JavaScript | mit | oliveroneill/bert | ---
+++
@@ -11,7 +11,7 @@
// start `script`
var spawn = require('child_process').spawn;
// we won't intercept the output to avoid causing user disruption
-spawn('script', ['-F', logDir + generateNewLogName()], { stdio: 'inherit' });
+spawn('script', ['-q', '-F', logDir + generateNewLogName()], { stdio: 'inherit' });
// generate new log to avoid name conflicts
function generateNewLogName() { |
781a59f0ae255040bebd4d3ea54de70b812c049f | express/models/rule_parser.js | express/models/rule_parser.js | // L-System Rule Parser
function RuleParser(str) {
this.str = str;
this.rules = {};
this.parse = function() {
var c, d;
var env = 0;
var rule_str;
var variable;
for (var i = 0; i < this.str.length; i++) {
c = this.str[i];
if (i > 0) {
d = this.str[i-1];
} else {
d = null;
}
if (c == '(') {
env = 1;
rule_str = "";
} else if (c.search(/[A-Z]/) == 0 && env == 1) {
variable = c;
} else if (c == '>' && d == '-') {
env = 2;
} else if ((c.search(/[A-Z]/) == 0 || c.search(/[\+-\[\]]/) == 0)
&& env == 2) {
rule_str += c;
} else if (c == ')') {
this.rules[variable] = rule_str;
env = 0;
}
}
return this.rules;
}
}
module.exports = RuleParser;
| // L-System Rule Parser
function RuleParser(str) {
this.str = str;
this.rules = {};
this.parse = function() {
var c, d;
var env = 0;
var rule_str;
var variable;
for (var i = 0; i < this.str.length; i++) {
c = this.str[i];
if (i > 0) {
d = this.str[i-1];
} else {
d = null;
}
if (c == '(') {
env = 1;
rule_str = "";
} else if ((c.search(/[A-Z]/) == 0 || c.search(/[\+\-\[\]]/) == 0)
&& env == 1) {
variable = c;
} else if (c == '>' && d == '-') {
env = 2;
} else if ((c.search(/[A-Z]/) == 0 || c.search(/[\+-\[\]]/) == 0)
&& env == 2) {
rule_str += c;
} else if (c == ')') {
this.rules[variable] = rule_str;
env = 0;
}
}
return this.rules;
}
}
module.exports = RuleParser;
| Allow control char as rule "variable" | Allow control char as rule "variable"
| JavaScript | bsd-3-clause | dwjackson/html_fractals | ---
+++
@@ -20,7 +20,8 @@
if (c == '(') {
env = 1;
rule_str = "";
- } else if (c.search(/[A-Z]/) == 0 && env == 1) {
+ } else if ((c.search(/[A-Z]/) == 0 || c.search(/[\+\-\[\]]/) == 0)
+ && env == 1) {
variable = c;
} else if (c == '>' && d == '-') {
env = 2; |
a3238411dc7bde812d20ee6385f3be8e2eefd548 | index.js | index.js | 'use strict';
var React = require('react');
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var Range = React.createClass({
displayName: 'Range',
propTypes: {
onChange: React.PropTypes.func,
onMouseMove: React.PropTypes.func
},
getDefaultProps: function() {
return {
type: 'range'
};
},
onRangeChange: function(e) {
if (this.props.onMouseMove) this.props.onMouseMove(e);
if (e.buttons !== 1) return;
if (this.props.onChange) this.props.onChange(e);
},
onRangeKeyDown: function(e) {
if (this.props.onMouseMove) this.props.onMouseMove(e);
if (this.props.onChange) this.props.onChange(e);
},
componentWillReceiveProps: function(props) {
React.findDOMNode(this).value = props.value;
},
render: function() {
var props = _extends({}, this.props, {
defaultValue: this.props.value,
onMouseMove: this.onRangeChange,
onKeyDown: this.onRangeKeyDown,
onChange: function() {}
});
delete props.value;
return React.createElement(
'input',
props
);
}
});
module.exports = Range;
| 'use strict';
var React = require('react');
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var Range = React.createClass({
displayName: 'Range',
propTypes: {
onChange: React.PropTypes.func,
onMouseMove: React.PropTypes.func
},
getDefaultProps: function() {
return {
type: 'range'
};
},
onRangeChange: function(e) {
if (this.props.onMouseMove) this.props.onMouseMove(e);
if (e.buttons !== 1) return;
if (this.props.onChange) this.props.onChange(e);
},
onRangeKeyDown: function(e) {
if (this.props.onKeyDown) this.props.onKeyDown(e);
if (this.props.onChange) this.props.onChange(e);
},
componentWillReceiveProps: function(props) {
React.findDOMNode(this).value = props.value;
},
render: function() {
var props = _extends({}, this.props, {
defaultValue: this.props.value,
onMouseMove: this.onRangeChange,
onKeyDown: this.onRangeKeyDown,
onChange: function() {}
});
delete props.value;
return React.createElement(
'input',
props
);
}
});
module.exports = Range;
| Check if user passes in their own keyDown function | Check if user passes in their own keyDown function
| JavaScript | isc | mapbox/react-range | ---
+++
@@ -20,7 +20,7 @@
if (this.props.onChange) this.props.onChange(e);
},
onRangeKeyDown: function(e) {
- if (this.props.onMouseMove) this.props.onMouseMove(e);
+ if (this.props.onKeyDown) this.props.onKeyDown(e);
if (this.props.onChange) this.props.onChange(e);
},
componentWillReceiveProps: function(props) { |
468570966eb500348066665bc29177c218b663d3 | tests/unit/odata/execute-odata-CRUD-test.js | tests/unit/odata/execute-odata-CRUD-test.js | import Ember from 'ember';
import { module, test } from 'qunit';
import ODataAdapter from 'ember-flexberry-data/adapters/odata';
import startApp from '../../helpers/start-app';
import config from '../../../../dummy/config/environment';
export default function executeTest(testName, callback) {
if (config.APP.testODataService) {
const randKey = Math.floor(Math.random() * 9999);
const baseUrl = 'http://rtc-web:8081/odatatmp/ember' + randKey;
const app = startApp();
const store = app.__container__.lookup('service:store');
const adapter = ODataAdapter.create();
Ember.set(adapter, 'host', baseUrl);
store.reopen({
adapterFor() {
return adapter;
}
});
module('OData | CRUD');
test(testName, (assert) => callback(store, assert));
}
}
| import Ember from 'ember';
import { module, test } from 'qunit';
import ODataAdapter from 'ember-flexberry-data/adapters/odata';
import startApp from '../../helpers/start-app';
import config from '../../../../dummy/config/environment';
export default function executeTest(testName, callback) {
if (config.APP.testODataService) {
const randKey = Math.floor(Math.random() * 9999);
const baseUrl = 'http://rtc-web:8081/odatatmp/ember' + randKey;
const app = startApp();
const store = app.__container__.lookup('service:store');
const adapter = ODataAdapter.create(app.__container__.ownerInjection());
Ember.set(adapter, 'host', baseUrl);
store.get('onlineStore').reopen({
adapterFor() {
return adapter;
}
});
module('OData | CRUD');
test(testName, (assert) => callback(store, assert));
}
}
| Fix execute-odata helper base-store now default | Fix execute-odata helper base-store now default
| JavaScript | mit | Flexberry/ember-flexberry-projections,Flexberry/ember-flexberry-data,Flexberry/ember-flexberry-data,Flexberry/ember-flexberry-data,Flexberry/ember-flexberry-projections | ---
+++
@@ -13,10 +13,10 @@
const app = startApp();
const store = app.__container__.lookup('service:store');
- const adapter = ODataAdapter.create();
+ const adapter = ODataAdapter.create(app.__container__.ownerInjection());
Ember.set(adapter, 'host', baseUrl);
- store.reopen({
+ store.get('onlineStore').reopen({
adapterFor() {
return adapter;
} |
b62e6b8b50dd8f7c45bab95b1986c73a14ff27f0 | server.js | server.js | // Import modules
var connect = require('connect');
var http = require('http');
var serveStatic = require('serve-static');
// Create middleware functions, from nodeJS, to set up server
var app = connect();
app.use(serveStatic('./dist'));
app.use(serveStatic('./'));
// Start server
console.log('Starting webserver on http://localhost:8080/');
http.createServer(app).listen(8080);
| // Import modules
var connect = require('connect');
var http = require('http');
var serveStatic = require('serve-static');
var fs = require('fs');
var url = require('url');
// Create middleware functions, from nodeJS, to set up server
var app = connect();
app.use(serveStatic('./dist'));
app.use(serveStatic('./'));
// Map all the expected SPA (Single Page App.) URLs to the root index.html
app.use(function (req, res, next) {
var reqUri = url.parse(req.url);
// Brainstorming correct regex to cover all valid URLs in the SPA.
// var regex = /^\/[0-9]+/
// var regex_views = /^\/(choose-video|watch-video|save-notes)$/
// var regex_views_with_search = /^\/(choose-video(\/\w+)*|watch-video|save-notes)$/
// var regex_youtube = /^http://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)([\w\-]+)(&(amp;)?[\w\?=]*)?$/
// regex = regex;
// if (regex.test(requestURI.pathname)) {
if (/^\/[0-9]+/.test(reqUri.pathname)) {
fs.readFile('./dist/index.html', { encoding: 'utf8' }, function (err, data) {
if (err) {
throw err;
}
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', data.length);
res.write(data, 'utf8', function (err) {
if (err) {
throw err;
}
res.end();
});
});
} else {
next();
}
});
// Start server
console.log('Starting webserver on http://localhost:8080/');
http.createServer(app).listen(8080);
| Add lines for another app.use() for coveringall expected URLs to be used in the SPA (Single Page App). Tried to come up with a regex to replace the basic regex on line 23. Function was written by Chad Killingsworth as an in-class example, in the msu-calendar project. | Add lines for another app.use() for coveringall expected URLs to be used in the SPA (Single Page App). Tried to come up with a regex to replace the basic regex on line 23. Function was written by Chad Killingsworth as an in-class example, in the msu-calendar project.
I learned how the first block of statements are related to nodeJS; the parameter inside of require() is used to tell what parts of nodeJS can be used in this file. That's about as detailed of a solution I could find today.
| JavaScript | mit | NBumgardner/YouTube-Notes,NBumgardner/YouTube-Notes | ---
+++
@@ -2,12 +2,44 @@
var connect = require('connect');
var http = require('http');
var serveStatic = require('serve-static');
+var fs = require('fs');
+var url = require('url');
// Create middleware functions, from nodeJS, to set up server
var app = connect();
app.use(serveStatic('./dist'));
app.use(serveStatic('./'));
+// Map all the expected SPA (Single Page App.) URLs to the root index.html
+app.use(function (req, res, next) {
+ var reqUri = url.parse(req.url);
+ // Brainstorming correct regex to cover all valid URLs in the SPA.
+ // var regex = /^\/[0-9]+/
+ // var regex_views = /^\/(choose-video|watch-video|save-notes)$/
+ // var regex_views_with_search = /^\/(choose-video(\/\w+)*|watch-video|save-notes)$/
+ // var regex_youtube = /^http://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)([\w\-]+)(&(amp;)?[\w\?=]*)?$/
+ // regex = regex;
+ // if (regex.test(requestURI.pathname)) {
+ if (/^\/[0-9]+/.test(reqUri.pathname)) {
+ fs.readFile('./dist/index.html', { encoding: 'utf8' }, function (err, data) {
+ if (err) {
+ throw err;
+ }
+ res.statusCode = 200;
+ res.setHeader('Content-Type', 'text/html');
+ res.setHeader('Content-Length', data.length);
+ res.write(data, 'utf8', function (err) {
+ if (err) {
+ throw err;
+ }
+ res.end();
+ });
+ });
+ } else {
+ next();
+ }
+});
+
// Start server
console.log('Starting webserver on http://localhost:8080/');
http.createServer(app).listen(8080); |
534f5464d21d3b7ff5485422169e31366ddb1c41 | index.js | index.js | var core = require("./core");
var prompt = require("prompt-sync")();
var fs = require("fs");
var env = process.env.NODE_ENV || "development";
module.exports = function(filepath, password) {
var out = fs.readFileSync(filepath).toString();
var json = JSON.parse(out);
if(!password) {
if(env === "development") {
password = prompt("Passpharse to decrypt config: ", {echo: "*"});
} else {
throw "No password to decrypt config"
}
}
return core.decrypt(json, password, true);
}
| var core = require("./core");
var prompt = require("./bin/prompt");
var fs = require("fs");
var env = process.env.NODE_ENV || "development";
module.exports = function(filepath, password) {
var out = fs.readFileSync(filepath).toString();
var json = JSON.parse(out);
if(!password) {
if(env === "development") {
password = prompt("Passpharse to decrypt config: ", filepath);
} else {
throw "No password to decrypt config"
}
}
return core.decrypt(json, password, true);
}
| Fix for js API to store in key chain | Fix for js API to store in key chain
| JavaScript | mit | orangemug/encrypt-conf | ---
+++
@@ -1,5 +1,5 @@
var core = require("./core");
-var prompt = require("prompt-sync")();
+var prompt = require("./bin/prompt");
var fs = require("fs");
var env = process.env.NODE_ENV || "development";
@@ -10,7 +10,7 @@
if(!password) {
if(env === "development") {
- password = prompt("Passpharse to decrypt config: ", {echo: "*"});
+ password = prompt("Passpharse to decrypt config: ", filepath);
} else {
throw "No password to decrypt config"
} |
729e73e920ddfd4beb67d4558e7dc17a1fb648df | project/src/js/ui/tournament/tournamentCtrl.js | project/src/js/ui/tournament/tournamentCtrl.js | import socket from '../../socket';
import * as utils from '../../utils';
import * as xhr from './tournamentXhr';
import socketHandler from './socketHandler';
import helper from '../helper';
import m from 'mithril';
const tournament = m.prop([]);
export default function controller() {
let id = m.route.param('id');
helper.analyticsTrackView('Tournament ' + id);
let clockInterval = null;
xhr.tournament(id).then(data => {
tournament(data);
clockInterval = setInterval(tick, 1000);
return data;
}, err => utils.handleXhrError(err));
let returnVal = {
tournament,
reload,
onunload: () => {
socket.destroy();
if(clockInterval)
clearInterval(clockInterval);
}
};
socket.createTournament(tournament().socketVersion, id, socketHandler(returnVal));
return returnVal;
}
function reload (data) {
tournament(data);
if(data.socketVersion)
socket.setVersion(data.socketVersion);
m.redraw();
}
function tick () {
let data = tournament();
if(data.secondsToStart && data.secondsToStart > 0)
data.secondsToStart--;
if(data.secondsToFinish && data.secondsToFinish > 0)
data.secondsToFinish--;
m.redraw();
}
| import socket from '../../socket';
import * as utils from '../../utils';
import * as xhr from './tournamentXhr';
import socketHandler from './socketHandler';
import helper from '../helper';
import m from 'mithril';
export default function controller() {
const tournament = m.prop([]);
function reload (data) {
tournament(data);
if(data.socketVersion)
socket.setVersion(data.socketVersion);
m.redraw();
}
function tick () {
let data = tournament();
if(data.secondsToStart && data.secondsToStart > 0)
data.secondsToStart--;
if(data.secondsToFinish && data.secondsToFinish > 0)
data.secondsToFinish--;
m.redraw();
}
let id = m.route.param('id');
helper.analyticsTrackView('Tournament ' + id);
let clockInterval = null;
xhr.tournament(id).then(data => {
tournament(data);
clockInterval = setInterval(tick, 1000);
return data;
}, err => utils.handleXhrError(err));
let returnVal = {
tournament,
reload,
onunload: () => {
socket.destroy();
if(clockInterval)
clearInterval(clockInterval);
}
};
socket.createTournament(tournament().socketVersion, id, socketHandler(returnVal));
return returnVal;
}
| Make tournament a private variable of controller | Make tournament a private variable of controller
| JavaScript | mit | btrent/lichobile,btrent/lichobile,btrent/lichobile,btrent/lichobile | ---
+++
@@ -5,9 +5,28 @@
import helper from '../helper';
import m from 'mithril';
-const tournament = m.prop([]);
+
export default function controller() {
+ const tournament = m.prop([]);
+ function reload (data) {
+ tournament(data);
+ if(data.socketVersion)
+ socket.setVersion(data.socketVersion);
+ m.redraw();
+ }
+
+ function tick () {
+ let data = tournament();
+ if(data.secondsToStart && data.secondsToStart > 0)
+ data.secondsToStart--;
+
+ if(data.secondsToFinish && data.secondsToFinish > 0)
+ data.secondsToFinish--;
+
+ m.redraw();
+ }
+
let id = m.route.param('id');
helper.analyticsTrackView('Tournament ' + id);
@@ -31,21 +50,3 @@
socket.createTournament(tournament().socketVersion, id, socketHandler(returnVal));
return returnVal;
}
-
-function reload (data) {
- tournament(data);
- if(data.socketVersion)
- socket.setVersion(data.socketVersion);
- m.redraw();
-}
-
-function tick () {
- let data = tournament();
- if(data.secondsToStart && data.secondsToStart > 0)
- data.secondsToStart--;
-
- if(data.secondsToFinish && data.secondsToFinish > 0)
- data.secondsToFinish--;
-
- m.redraw();
-} |
2a284b62b649a352ddaa3810790ab26ef76edc3e | index.js | index.js | module.exports = function styleInject (css, returnValue) {
css = css || '';
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
return returnValue;
};
| module.exports = function styleInject (css, returnValue) {
if (typeof document === 'undefined') {
return returnValue;
}
css = css || '';
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
return returnValue;
};
| Allow usage in isomorphic components | Allow usage in isomorphic components
Any dependency of this package will fail if run in a Node environment. This commit allows code to be run on the server by simply returning if no `document` is available. | JavaScript | mit | egoist/style-inject | ---
+++
@@ -1,4 +1,7 @@
module.exports = function styleInject (css, returnValue) {
+ if (typeof document === 'undefined') {
+ return returnValue;
+ }
css = css || '';
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style'); |
1d7229a91ce127276235fa327ec33d8aba1335f9 | index.js | index.js | /**
* Module dependencies
*/
var request = require('superagent')
, _ = require('underscore');
// Factory
module.exports = function (opts) {
return new Affilinet(opts);
};
// Api endpoint
var endpoint = 'http://product-api.affili.net/V3/productservice.svc/JSON/SearchProducts';
var Affilinet = function Affilinet (opts) {
opts = ('string' === typeof opts) ? { keywords: opts } : opts;
if (opts.keywords) {
this._keywords = opts.keywords;
this.mode = 'search';
}
};
// Publisher identifier
Affilinet.prototype.id = function (id) {
return this._id = id, this;
};
// Affilinet api password, or key I guess
Affilinet.prototype.password = Affilinet.prototype.key = function (password) {
return this._password = password, this;
};
Affilinet.prototype.done = function (cb) {
request
.get(endpoint)
.query({publisherId: this._id})
.query({Password: this._password})
.done(function (err, result) {
if (err) return cb(err);
return cb(null, result.body);
});
};
| /**
* Module dependencies
*/
var request = require('superagent')
, _ = require('underscore');
// Factory
module.exports = function (opts) {
return new Affilinet(opts);
};
// Api endpoint
var endpoint = 'http://product-api.affili.net/V3/productservice.svc/JSON/SearchProducts';
var Affilinet = function Affilinet (opts) {
opts = ('string' === typeof opts) ? { keywords: opts } : opts;
if (opts.keywords) {
this._keywords = opts.keywords;
this.mode = 'search';
}
};
// Publisher identifier
Affilinet.prototype.id = function (id) {
return this._id = id, this;
};
// Affilinet api password, or key I guess
Affilinet.prototype.password = Affilinet.prototype.key = function (password) {
return this._password = password, this;
};
Affilinet.prototype.done = function (cb) {
request
.get(endpoint)
.query({publisherId: this._id})
.query({Password: this._password})
.done(function (err, result) {
if (err) return cb(err);
return cb(null, result.body);
});
};
// Take care of affilinet byte ordering foolishness
request.parse['application/json'] = function (res, fn) {
res.text = '';
res.setEncoding('utf8');
res.on('data', function (chunk) { res.text += chunk; });
res.on('end', function () {
try {
res.text = res.text.slice(1);
fn(null, JSON.parse(res.text));
} catch (err) {
fn(err);
}
});
};
| Remove byte order indicator before attempting parse | Remove byte order indicator before attempting parse
Really? Really? Really? Really?
| JavaScript | mit | urgeiolabs/node-affilinet-lookup | ---
+++
@@ -41,3 +41,18 @@
return cb(null, result.body);
});
};
+
+// Take care of affilinet byte ordering foolishness
+request.parse['application/json'] = function (res, fn) {
+ res.text = '';
+ res.setEncoding('utf8');
+ res.on('data', function (chunk) { res.text += chunk; });
+ res.on('end', function () {
+ try {
+ res.text = res.text.slice(1);
+ fn(null, JSON.parse(res.text));
+ } catch (err) {
+ fn(err);
+ }
+ });
+}; |
8d5527791bcc7f664a784e7e8554d700815a47a1 | play-audio.js | play-audio.js | module.exports = function(RED) {
function PlayAudioNode(config) {
RED.nodes.createNode(this,config);
var node = this;
this.on('input', function(msg) {
RED.comms.publish("playaudio", msg.payload);
});
}
RED.nodes.registerType("play audio", PlayAudioNode);
}
| module.exports = function(RED) {
function PlayAudioNode(config) {
RED.nodes.createNode(this,config);
var node = this;
this.on('input', function(msg) {
if(Buffer.isBuffer(msg.payload)){
RED.comms.publish("playaudio", msg.payload);
}
});
}
RED.nodes.registerType("play audio", PlayAudioNode);
}
| Make sure input data is a buffer | Make sure input data is a buffer
| JavaScript | apache-2.0 | lorentzlasson/node-red-contrib-play-audio,lorentzlasson/node-red-contrib-play-audio | ---
+++
@@ -3,7 +3,9 @@
RED.nodes.createNode(this,config);
var node = this;
this.on('input', function(msg) {
- RED.comms.publish("playaudio", msg.payload);
+ if(Buffer.isBuffer(msg.payload)){
+ RED.comms.publish("playaudio", msg.payload);
+ }
});
}
RED.nodes.registerType("play audio", PlayAudioNode); |
39dc300c60583cfa66cec96b01869f4ec33286d5 | examples/basic/babel.config.js | examples/basic/babel.config.js | module.exports = {
presets: [
[
'@babel/env',
{
debug: true,
modules: false,
useBuiltIns: 'usage',
},
],
'@babel/react',
],
plugins: ['@babel/plugin-proposal-class-properties'],
};
| module.exports = {
presets: [
[
'@babel/env',
{
modules: false,
useBuiltIns: 'usage',
},
],
'@babel/react',
],
plugins: ['@babel/plugin-proposal-class-properties'],
};
| Disable Babel debug mode in the basic example | Chore: Disable Babel debug mode in the basic example
| JavaScript | mit | styleguidist/react-styleguidist,sapegin/react-styleguidist,sapegin/react-styleguidist,styleguidist/react-styleguidist,styleguidist/react-styleguidist | ---
+++
@@ -3,7 +3,6 @@
[
'@babel/env',
{
- debug: true,
modules: false,
useBuiltIns: 'usage',
}, |
6ae83b945f7ca90b5886e50c4dbcb848cd5deab8 | public/javascripts/home/index.js | public/javascripts/home/index.js | $(function() {
var pageToFetch = 2;
$(".more").click(function() {
$(this).addClass("loading");
$.get("/home/mock_set", {page: pageToFetch}, function(data) {
$(".more").removeClass("loading");
if (data.trim().length > 0) {
$(data).insertBefore('.more');
}
if (pageToFetch === TOTAL_PAGES) {
$(".more").hide();
}
pageToFetch++;
});
});
$('#show_all_projects').click(function(evt) {
evt.preventDefault();
$('#all_projects').show();
$('#show_all_projects').hide();
});
$('.project_filter').keyup(function() {
var projects = $('.project_list li');
var filter = $.trim($(this).val());
projects.show();
if (filter) {
filter = new RegExp(filter ,'i');
projects
.filter(function() { return !filter.test($(this).text()); })
.hide();
}
});
});
| $(function() {
var pageToFetch = 2;
var prevQueryLength = 0;
$(".more").click(function() {
$(this).addClass("loading");
$.get("/home/mock_set", {page: pageToFetch}, function(data) {
$(".more").removeClass("loading");
if (data.trim().length > 0) {
$(data).insertBefore('.more');
}
if (pageToFetch === TOTAL_PAGES) {
$(".more").hide();
}
pageToFetch++;
});
});
$('#show_all_projects').click(function(evt) {
evt.preventDefault();
$('#all_projects').show();
$('#show_all_projects').hide();
});
$('.project_filter').keyup(function() {
var $projects = $('.project_list li');
var filter = $.trim($(this).val());
if (filter) {
filterRegexp = new RegExp(filter ,'i');
$projects
.filter(':visible')
.filter(function() { return !filterRegexp.test(this.textContent); })
.hide();
if (filter.length <= prevQueryLength) {
$projects
.filter(':hidden')
.filter(function() { return filterRegexp.test(this.textContent); })
.show();
}
} else {
$projects.show();
}
prevQueryLength = filter.length;
});
});
| Improve mockr project search speed | Improve mockr project search speed
As a hackathon project, we use some smarter search techniques to hide
and show fewer list elements when each search is performed. For each
keystroke, this narrows down or broadens the existing list instead of
hiding and showing everything.
This is motivated by the slowdown in speed with large quantities of
projects.
Change-Id: I6f5e916c2f2ac1a8a4e339e69116a513a23ac0da
Reviewed-on: https://gerrit.causes.com/18733
Reviewed-by: Joe Lencioni <1dd72cf724deaab5db236f616560fc7067b734e1@causes.com>
Tested-by: Tom Dooner <b3e827da77b8b5a24f08875e81b25cd8f6ab5d10@causes.com>
| JavaScript | mit | causes/mockr,causes/mockr,causes/mockr | ---
+++
@@ -1,5 +1,6 @@
$(function() {
var pageToFetch = 2;
+ var prevQueryLength = 0;
$(".more").click(function() {
$(this).addClass("loading");
@@ -22,14 +23,26 @@
});
$('.project_filter').keyup(function() {
- var projects = $('.project_list li');
+ var $projects = $('.project_list li');
var filter = $.trim($(this).val());
- projects.show();
+
if (filter) {
- filter = new RegExp(filter ,'i');
- projects
- .filter(function() { return !filter.test($(this).text()); })
+ filterRegexp = new RegExp(filter ,'i');
+ $projects
+ .filter(':visible')
+ .filter(function() { return !filterRegexp.test(this.textContent); })
.hide();
+
+ if (filter.length <= prevQueryLength) {
+ $projects
+ .filter(':hidden')
+ .filter(function() { return filterRegexp.test(this.textContent); })
+ .show();
+ }
+ } else {
+ $projects.show();
}
+
+ prevQueryLength = filter.length;
});
}); |
3b59fd06535fa25aa9611259a0eaf82e38df6a81 | editor/collections/commands.js | editor/collections/commands.js | var Q = require("q");
var _ = require("hr.utils");
var Collection = require("hr.collection");
var logger = require("hr.logger")("commands");
var Command = require("../models/command");
var Commands = Collection.extend({
model: Command,
// Initialize
initialize: function() {
Commands.__super__.initialize.apply(this, arguments);
this.context = {};
},
// Register a new command
register: function(cmd) {
if (_.isArray(cmd)) return _.map(cmd, this.register, this);
var c = this.get(cmd.id);
if (c) this.remove(c);
return this.add(cmd);
},
// Run a command
run: function(cmd, args) {
cmd = this.get(cmd);
if (!cmd) return Q.reject(new Error("Command not found: '"+cmd+"'"));
return cmd.run(args);
},
// Set context
setContext: function(id, data) {
logging.log("update context", id);
this.context = {
'type': id,
'data': data
};
this.trigger("context", this.context);
}
});
module.exports = Commands;
| var Q = require("q");
var _ = require("hr.utils");
var Collection = require("hr.collection");
var logger = require("hr.logger")("commands");
var Command = require("../models/command");
var Commands = Collection.extend({
model: Command,
// Initialize
initialize: function() {
Commands.__super__.initialize.apply(this, arguments);
this.context = {};
},
// Register a new command
register: function(cmd) {
if (_.isArray(cmd)) return _.map(cmd, this.register, this);
var c = this.get(cmd.id);
if (c) this.remove(c);
return this.add(cmd);
},
// Run a command
run: function(_cmd, args) {
var cmd = this.get(_cmd);
if (!cmd) return Q.reject(new Error("Command not found: '"+_cmd+"'"));
return cmd.run(args);
},
// Set context
setContext: function(id, data) {
logging.log("update context", id);
this.context = {
'type': id,
'data': data
};
this.trigger("context", this.context);
}
});
module.exports = Commands;
| Fix error message when command not found | Fix error message when command not found
| JavaScript | apache-2.0 | CodeboxIDE/codebox,indykish/codebox,kustomzone/codebox,quietdog/codebox,nobutakaoshiro/codebox,nobutakaoshiro/codebox,rodrigues-daniel/codebox,blubrackets/codebox,Ckai1991/codebox,LogeshEswar/codebox,code-box/codebox,ahmadassaf/Codebox,rodrigues-daniel/codebox,listepo/codebox,quietdog/codebox,LogeshEswar/codebox,ahmadassaf/Codebox,CodeboxIDE/codebox,kustomzone/codebox,indykish/codebox,listepo/codebox,lcamilo15/codebox,lcamilo15/codebox,smallbal/codebox,ronoaldo/codebox,smallbal/codebox,etopian/codebox,code-box/codebox,fly19890211/codebox,etopian/codebox,fly19890211/codebox,rajthilakmca/codebox,Ckai1991/codebox,blubrackets/codebox,rajthilakmca/codebox,ronoaldo/codebox | ---
+++
@@ -26,10 +26,9 @@
},
// Run a command
- run: function(cmd, args) {
-
- cmd = this.get(cmd);
- if (!cmd) return Q.reject(new Error("Command not found: '"+cmd+"'"));
+ run: function(_cmd, args) {
+ var cmd = this.get(_cmd);
+ if (!cmd) return Q.reject(new Error("Command not found: '"+_cmd+"'"));
return cmd.run(args);
}, |
27e6e8d24e213c9d7fb787a5103222c8ef28f1fe | src/article/converter/r2t/FootnoteConverter.js | src/article/converter/r2t/FootnoteConverter.js | import { findChild, findAllChildren } from '../util/domHelpers'
export default class FootnoteConverter {
get type () { return 'fn' }
get tagName () { return 'fn' }
import (el, node, importer) {
// TODO: at some point we want to retain the label and determine if the label should be treated as custom
// or be generated
let labelEl = findChild(el, 'label')
let pEls = findAllChildren(el, 'p')
if (labelEl) {
node.label = labelEl.text()
}
node._childNodes = pEls.map(el => importer.convertElement(el).id)
}
export (node, el, exporter) {
const $$ = exporter.$$
el.append($$('label').text(node.label))
el.append(node.getChildren().map(p => exporter.convertNode(p)))
}
}
| import { findChild, findAllChildren } from '../util/domHelpers'
import { getLabel } from '../../shared/nodeHelpers'
// TODO: at some point we want to retain the label and determine if the label should be treated as custom
// or be generated.
export default class FootnoteConverter {
get type () { return 'fn' }
get tagName () { return 'fn' }
import (el, node, importer) {
let labelEl = findChild(el, 'label')
let pEls = findAllChildren(el, 'p')
if (labelEl) {
node.label = labelEl.text()
}
node._childNodes = pEls.map(el => importer.convertElement(el).id)
}
export (node, el, exporter) {
const $$ = exporter.$$
// We gonna need to find another way for node states. I.e. for labels we will have
// a hybrid scenario where the labels are either edited manually, and thus we need to record ops,
// or they are generated without persisting operations (e.g. think about undo/redo, or collab)
// my suggestion would be to introduce volatile ops, they would be excluded from the DocumentChange, that is stored in the change history,
// or used for collaborative editing.
let label = getLabel(node)
if (label) {
el.append($$('label').text(label))
}
el.append(node.getChildren().map(p => exporter.convertNode(p)))
}
}
| Fix export of footnote labels. | Fix export of footnote labels.
| JavaScript | mit | substance/texture,substance/texture | ---
+++
@@ -1,16 +1,16 @@
import { findChild, findAllChildren } from '../util/domHelpers'
+import { getLabel } from '../../shared/nodeHelpers'
+// TODO: at some point we want to retain the label and determine if the label should be treated as custom
+// or be generated.
export default class FootnoteConverter {
get type () { return 'fn' }
get tagName () { return 'fn' }
import (el, node, importer) {
- // TODO: at some point we want to retain the label and determine if the label should be treated as custom
- // or be generated
let labelEl = findChild(el, 'label')
let pEls = findAllChildren(el, 'p')
-
if (labelEl) {
node.label = labelEl.text()
}
@@ -19,7 +19,15 @@
export (node, el, exporter) {
const $$ = exporter.$$
- el.append($$('label').text(node.label))
+ // We gonna need to find another way for node states. I.e. for labels we will have
+ // a hybrid scenario where the labels are either edited manually, and thus we need to record ops,
+ // or they are generated without persisting operations (e.g. think about undo/redo, or collab)
+ // my suggestion would be to introduce volatile ops, they would be excluded from the DocumentChange, that is stored in the change history,
+ // or used for collaborative editing.
+ let label = getLabel(node)
+ if (label) {
+ el.append($$('label').text(label))
+ }
el.append(node.getChildren().map(p => exporter.convertNode(p)))
}
} |
9ee1f3962dc33d4f0a431b81ac375900af3b866d | src/components/views/elements/AppPermission.js | src/components/views/elements/AppPermission.js | import React from 'react';
import PropTypes from 'prop-types';
import url from 'url';
export default class AppPermission extends React.Component {
constructor(props) {
super(props);
const curl = this.getCurl();
this.state = {
curl: curl,
};
console.log('curl', curl);
}
getCurl() {
const wurl = url.parse(this.props.url);
let curl;
const searchParams = new URLSearchParams(wurl.search);
if(searchParams && searchParams.get('url')) {
curl = searchParams.get('url');
}
curl = curl || wurl;
return curl;
}
render() {
return (
<div className='mx_AppPermissionWarning'>
<div className='mx_AppPermissionWarningImage'>
<img src='img/warning.svg' alt='Warning'/>
</div>
<div className='mx_AppPermissionWarningText'>
<span className='mx_AppPermissionWarningTextLabel'>Do you want to load widget from URL?:</span> <span className='mx_AppPermissionWarningTextURL'>{this.state.curl}</span>
</div>
<input
className='mx_AppPermissionButton'
type='button'
value='Allow'
onClick={this.props.onPermissionGranted}
/>
</div>
);
}
}
AppPermission.propTypes = {
url: PropTypes.string.isRequired,
onPermissionGranted: PropTypes.func.isRequired,
};
AppPermission.defaultPropTypes = {
onPermissionGranted: function() {},
};
| import React from 'react';
import PropTypes from 'prop-types';
import url from 'url';
export default class AppPermission extends React.Component {
constructor(props) {
super(props);
const curl = this.getCurl();
this.state = {
curl: curl,
};
console.log('curl', curl);
}
getCurl() {
const wurl = url.parse(this.props.url);
let curl;
const searchParams = new URLSearchParams(wurl.search);
if(searchParams && searchParams.get('url')) {
curl = searchParams.get('url');
}
if (!curl && wurl) {
wurl.search = wurl.query = "";
curl = wurl.format();
}
return curl;
}
render() {
return (
<div className='mx_AppPermissionWarning'>
<div className='mx_AppPermissionWarningImage'>
<img src='img/warning.svg' alt='Warning'/>
</div>
<div className='mx_AppPermissionWarningText'>
<span className='mx_AppPermissionWarningTextLabel'>Do you want to load widget from URL:</span> <span className='mx_AppPermissionWarningTextURL'>{this.state.curl}</span>
</div>
<input
className='mx_AppPermissionButton'
type='button'
value='Allow'
onClick={this.props.onPermissionGranted}
/>
</div>
);
}
}
AppPermission.propTypes = {
url: PropTypes.string.isRequired,
onPermissionGranted: PropTypes.func.isRequired,
};
AppPermission.defaultPropTypes = {
onPermissionGranted: function() {},
};
| Set display URL from wurl if curl not specified. | Set display URL from wurl if curl not specified.
| JavaScript | apache-2.0 | matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,aperezdc/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk | ---
+++
@@ -21,7 +21,10 @@
if(searchParams && searchParams.get('url')) {
curl = searchParams.get('url');
}
- curl = curl || wurl;
+ if (!curl && wurl) {
+ wurl.search = wurl.query = "";
+ curl = wurl.format();
+ }
return curl;
}
@@ -32,7 +35,7 @@
<img src='img/warning.svg' alt='Warning'/>
</div>
<div className='mx_AppPermissionWarningText'>
- <span className='mx_AppPermissionWarningTextLabel'>Do you want to load widget from URL?:</span> <span className='mx_AppPermissionWarningTextURL'>{this.state.curl}</span>
+ <span className='mx_AppPermissionWarningTextLabel'>Do you want to load widget from URL:</span> <span className='mx_AppPermissionWarningTextURL'>{this.state.curl}</span>
</div>
<input
className='mx_AppPermissionButton' |
e0f1af644da67217118f9b49caaac8d30816fd34 | src/createDisposableWorker.js | src/createDisposableWorker.js | export const createDisposableWorker = response => {
const URL = window.URL || window.webkitURL
const blob = new Blob([response], { type: 'application/javascript' }) // eslint-disable-line
const worker = new Worker(URL.createObjectURL(blob)) // eslint-disable-line
worker.post = message =>
new Promise((resolve, reject) => {
worker.onmessage = event => {
URL.revokeObjectURL(blob)
resolve(event.data)
}
worker.onerror = e => {
console.error(`Error: Line ${e.lineno} in ${e.filename}: ${e.message}`)
reject(e)
}
worker.postMessage({ message })
})
return worker
}
| export const createDisposableWorker = response => {
const URL = window.URL || window.webkitURL
const blob = new Blob([response], { type: 'application/javascript' }) // eslint-disable-line
const objectURL = URL.createObjectURL(blob)
const worker = new Worker(objectURL) // eslint-disable-line
worker.post = message =>
new Promise((resolve, reject) => {
worker.onmessage = event => {
URL.revokeObjectURL(objectURL)
resolve(event.data)
}
worker.onerror = e => {
console.error(`Error: Line ${e.lineno} in ${e.filename}: ${e.message}`)
reject(e)
}
worker.postMessage({ message })
})
return worker
}
| Fix object URL not being revoked at when the worker is not being used anymore | Fix object URL not being revoked at when the worker is not being used anymore
| JavaScript | mit | israelss/simple-web-worker,israelss/simple-web-worker | ---
+++
@@ -1,11 +1,12 @@
export const createDisposableWorker = response => {
const URL = window.URL || window.webkitURL
const blob = new Blob([response], { type: 'application/javascript' }) // eslint-disable-line
- const worker = new Worker(URL.createObjectURL(blob)) // eslint-disable-line
+ const objectURL = URL.createObjectURL(blob)
+ const worker = new Worker(objectURL) // eslint-disable-line
worker.post = message =>
new Promise((resolve, reject) => {
worker.onmessage = event => {
- URL.revokeObjectURL(blob)
+ URL.revokeObjectURL(objectURL)
resolve(event.data)
}
worker.onerror = e => { |
2e52ced1b1d03db640618ae2eba5cb6851435dd3 | components/subreddit/post-row.js | components/subreddit/post-row.js | const React = require('react-native');
const {
Image,
Text,
StyleSheet,
View,
} = React;
module.exports = React.createClass({
render: function() {
const data = this.props.rowData.data;
var Thumbnail;
if (data.thumbnail) {
Thumbnail = (
<Image source={{uri: data.thumbnail}} style={styles.rowImage}/>
);
}
return (
<View style={styles.row}>
{Thumbnail}
<Text style={styles.rowText}>{data.title}</Text>
</View>
);
},
});
const styles = StyleSheet.create({
row: {
backgroundColor: '#ffffff',
flexDirection: 'row',
borderBottomWidth: 1,
borderBottomColor: '#ddd',
padding: 10,
},
rowImage: {
borderRadius: 3,
height: 50,
marginRight: 15,
width: 50,
},
rowText: {
flex: 1,
},
});
| const React = require('react-native');
const {
Image,
Text,
StyleSheet,
View,
} = React;
module.exports = React.createClass({
render: function() {
const data = this.props.rowData.data;
var Thumbnail;
if (data.thumbnail) {
Thumbnail = (
<Image source={{uri: data.thumbnail}} style={styles.rowImage}/>
);
}
return (
<View style={styles.row}>
{Thumbnail}
<View style={styles.textContainer}>
<Text style={styles.title}>{data.title}</Text>
<Text style={styles.meta}>
{data.subreddit} - {data.domain} - {data.author}
</Text>
</View>
</View>
);
},
});
const styles = StyleSheet.create({
row: {
flex: 1,
flexDirection: 'row',
backgroundColor: '#ffffff',
borderBottomWidth: 1,
borderBottomColor: '#ddd',
padding: 10,
},
rowImage: {
borderRadius: 3,
height: 50,
marginRight: 15,
width: 50,
},
textContainer: {
flex: 1,
},
title: {
flex: 1,
flexDirection: 'column',
},
meta: {
flex: 1,
color: '#555',
fontSize: 11,
marginTop: 5,
},
});
| Add post meta to individual rows | Add post meta to individual rows
When viewing posts meta is shown below the title, including the
subreddit, the domain it was posted to, and the author.
| JavaScript | mit | BlakeWilliams/newred | ---
+++
@@ -21,7 +21,12 @@
return (
<View style={styles.row}>
{Thumbnail}
- <Text style={styles.rowText}>{data.title}</Text>
+ <View style={styles.textContainer}>
+ <Text style={styles.title}>{data.title}</Text>
+ <Text style={styles.meta}>
+ {data.subreddit} - {data.domain} - {data.author}
+ </Text>
+ </View>
</View>
);
},
@@ -29,8 +34,9 @@
const styles = StyleSheet.create({
row: {
+ flex: 1,
+ flexDirection: 'row',
backgroundColor: '#ffffff',
- flexDirection: 'row',
borderBottomWidth: 1,
borderBottomColor: '#ddd',
padding: 10,
@@ -43,7 +49,19 @@
width: 50,
},
- rowText: {
+ textContainer: {
flex: 1,
},
+
+ title: {
+ flex: 1,
+ flexDirection: 'column',
+ },
+
+ meta: {
+ flex: 1,
+ color: '#555',
+ fontSize: 11,
+ marginTop: 5,
+ },
}); |
935bb29bd5116a08a476592b49214d312d871244 | src/addon/pnacl/lib/axiom_pnacl/executables.js | src/addon/pnacl/lib/axiom_pnacl/executables.js | // Copyright (c) 2014 The Axiom Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import AxiomError from 'axiom/core/error';
import environment from 'axiom_shell/environment';
import PnaclCommand from 'axiom_pnacl/pnacl_command';
// @note ExecuteContext from 'axiom/bindings/fs/execute_context'
var createCommand = function(commandName, sourceUrl, tarFilename) {
var command = new PnaclCommand(commandName, sourceUrl, tarFilename);
return command.run.bind(command);
};
export var executables = function(sourceUrl) {
return {
'curl(@)': createCommand('curl', sourceUrl),
'nano(@)': createCommand('nano', sourceUrl, 'nano.tar'),
'nethack(@)': createCommand('nethack', sourceUrl, 'nethack.tar'),
'python(@)': createCommand('python', sourceUrl, 'pydata_pnacl.tar'),
'unzip(@)': createCommand('unzip', sourceUrl),
'vim(@)': createCommand('vim', sourceUrl, 'vim.tar'),
};
};
export default executables;
| // Copyright (c) 2014 The Axiom Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import AxiomError from 'axiom/core/error';
import environment from 'axiom_shell/environment';
import PnaclCommand from 'axiom_pnacl/pnacl_command';
// @note ExecuteContext from 'axiom/bindings/fs/execute_context'
var createCommand = function(name, sourceUrl, opt_tarFilename, opt_env) {
var command = new PnaclCommand(name, sourceUrl, opt_tarFilename, opt_env);
return command.run.bind(command);
};
export var executables = function(sourceUrl) {
return {
'curl(@)': createCommand('curl', sourceUrl),
'nano(@)': createCommand('nano', sourceUrl, 'nano.tar'),
'nethack(@)': createCommand('nethack', sourceUrl, 'nethack.tar'),
'python(@)':
// Note: We set PYTHONHOME to '/' so that the python library files
// are loaded from '/lib/python2.7', which is the prefix path used in
// 'pydata_pnacl.tar'. By default, python set PYTHONHOME to be the
// prefix of the executable from arg[0]. This conflicts with the way
// we set arg[0] to tell pnacl to where to load the .tar file from.
createCommand('python', sourceUrl, 'pydata_pnacl.tar', {
'$PYTHONHOME': '/'
}),
'unzip(@)': createCommand('unzip', sourceUrl),
'vim(@)': createCommand('vim', sourceUrl, 'vim.tar'),
};
};
export default executables;
| Fix running python by setting PYTHONHOME to '/'. | Fix running python by setting PYTHONHOME to '/'.
| JavaScript | apache-2.0 | umop/axiom_old_private,chromium/axiom,rpaquay/axiom,ussuri/axiom,mcanthony/axiom | ---
+++
@@ -10,8 +10,8 @@
// @note ExecuteContext from 'axiom/bindings/fs/execute_context'
-var createCommand = function(commandName, sourceUrl, tarFilename) {
- var command = new PnaclCommand(commandName, sourceUrl, tarFilename);
+var createCommand = function(name, sourceUrl, opt_tarFilename, opt_env) {
+ var command = new PnaclCommand(name, sourceUrl, opt_tarFilename, opt_env);
return command.run.bind(command);
};
@@ -20,7 +20,15 @@
'curl(@)': createCommand('curl', sourceUrl),
'nano(@)': createCommand('nano', sourceUrl, 'nano.tar'),
'nethack(@)': createCommand('nethack', sourceUrl, 'nethack.tar'),
- 'python(@)': createCommand('python', sourceUrl, 'pydata_pnacl.tar'),
+ 'python(@)':
+ // Note: We set PYTHONHOME to '/' so that the python library files
+ // are loaded from '/lib/python2.7', which is the prefix path used in
+ // 'pydata_pnacl.tar'. By default, python set PYTHONHOME to be the
+ // prefix of the executable from arg[0]. This conflicts with the way
+ // we set arg[0] to tell pnacl to where to load the .tar file from.
+ createCommand('python', sourceUrl, 'pydata_pnacl.tar', {
+ '$PYTHONHOME': '/'
+ }),
'unzip(@)': createCommand('unzip', sourceUrl),
'vim(@)': createCommand('vim', sourceUrl, 'vim.tar'),
}; |
f9923404dd63dc4ea1288dabde34332fb3ca8b58 | pkg/time/index.js | pkg/time/index.js | const timeout = (dispatch, props) =>
setTimeout(() => dispatch(props.action), props.delay)
const interval = (dispatch, props) => {
const id = setInterval(() => {
dispatch(props.action, Date.now())
}, props.delay)
return () => clearInterval(id)
}
const getTime = (dispatch, props) => dispatch(props.action, Date.now())
/**
* @example
*
app({
subscriptions: (state) => [
// Dispatch RequestResource every delayInMilliseconds
every(state.delayInMilliseconds, RequestResource),
],
})
*/
export const every = (delay, action) => [interval, { delay, action }]
/**
* @example
const SlowClap = (state, ms = 1200) => [state, delay(ms, Clap)]
*/
export const delay = (delay, action) => [timeout, { delay, action }]
/**
* @example
now(NewTime)
*/
export const now = (action) => [getTime, { action }]
| const timeout = (dispatch, props) =>
setTimeout(() => dispatch(props.action), props.delay)
const interval = (dispatch, props) => {
const id = setInterval(() => {
dispatch(props.action, Date.now())
}, props.delay)
return () => clearInterval(id)
}
const getTime = (dispatch, props) => dispatch(props.action, Date.now())
/**
* @example
* app({
* subscriptions: (state) => [
* // Dispatch RequestResource every delayInMilliseconds
* every(state.delayInMilliseconds, RequestResource),
* ],
* })
*/
export const every = (delay, action) => [interval, { delay, action }]
/**
* @example
* const SlowClap = (state, ms = 1200) => [state, delay(ms, Clap)]
*/
export const delay = (delay, action) => [timeout, { delay, action }]
/**
* @example
* now(NewTime)
*/
export const now = (action) => [getTime, { action }]
| Use valid jsdoc comment syntax | Use valid jsdoc comment syntax
| JavaScript | mit | hyperapp/hyperapp,hyperapp/hyperapp,jbucaran/hyperapp | ---
+++
@@ -10,26 +10,25 @@
const getTime = (dispatch, props) => dispatch(props.action, Date.now())
-/**
+/**
* @example
- *
- app({
- subscriptions: (state) => [
- // Dispatch RequestResource every delayInMilliseconds
- every(state.delayInMilliseconds, RequestResource),
- ],
- })
+ * app({
+ * subscriptions: (state) => [
+ * // Dispatch RequestResource every delayInMilliseconds
+ * every(state.delayInMilliseconds, RequestResource),
+ * ],
+ * })
*/
export const every = (delay, action) => [interval, { delay, action }]
-/**
+/**
* @example
- const SlowClap = (state, ms = 1200) => [state, delay(ms, Clap)]
+ * const SlowClap = (state, ms = 1200) => [state, delay(ms, Clap)]
*/
export const delay = (delay, action) => [timeout, { delay, action }]
-/**
+/**
* @example
- now(NewTime)
+ * now(NewTime)
*/
export const now = (action) => [getTime, { action }] |
2c0bd5dfeef5aaff007f5a1ff0391bdc89c16276 | app/assets/javascripts/factsheet/drawLegend.js | app/assets/javascripts/factsheet/drawLegend.js | /* globals I18n $ */
/**
* Given the definition for a chart, returns an array of <div/> elements
* describing each series in the chart.
*/
function drawLegend(definition, periods) {
var showPeriods = periods || ['future'];
var list = definition.map(function(series) {
var key = series.key.replace(/_/g, '-');
return $('<tr/>')
.addClass(key)
.append(
$('<td class="key"/>').append(
$('<span class="legend-item" />').css(
'background-color',
series.color
),
' ',
I18n.t('factsheet.series.' + series.key)
),
showPeriods.map(function(period) {
return $('<td class="value" />')
.attr('data-query', series.key)
.attr('data-as', 'TJ')
.attr('data-no-unit', true)
.attr('data-period', period)
.html('—');
})
);
});
list.reverse();
return list;
}
| /* globals I18n $ */
/**
* Given the definition for a chart, returns an array of <div/> elements
* describing each series in the chart.
*/
function drawLegend(definition, periods) {
var showPeriods = periods || ['future'];
var list = definition.map(function(series) {
var key = series.key.replace(/_/g, '-');
return $('<tr/>')
.addClass(key)
.append(
$('<td class="key"/>').append(
$('<span class="legend-item" />').css(
'background-color',
series.color
),
' ',
I18n.t('factsheet.series.' + series.key)
),
showPeriods.map(function(period) {
return $('<td class="value" />')
.attr('data-query', series.key)
.attr('data-no-unit', true)
.attr('data-period', period)
.html('—');
})
);
});
list.reverse();
return list;
}
| Remove hard-coded TJ unit from legends | Factsheet: Remove hard-coded TJ unit from legends
| JavaScript | mit | quintel/etmodel,quintel/etmodel,quintel/etmodel,quintel/etmodel | ---
+++
@@ -24,7 +24,6 @@
showPeriods.map(function(period) {
return $('<td class="value" />')
.attr('data-query', series.key)
- .attr('data-as', 'TJ')
.attr('data-no-unit', true)
.attr('data-period', period)
.html('—'); |
f301299ba20a0067f44d86e359bf1814d810a9a1 | public/app/ui/components/search/results/SearchResultsComponent.js | public/app/ui/components/search/results/SearchResultsComponent.js | (function () {
'use strict';
define(
[
'lodash',
'knockout',
'config/routes',
'util/container'
],
function (_, ko, routes, container) {
return function (parameters) {
var typeFor = function (result) {
return container.resolve('types')[result.data().type];
};
if (!parameters.results) {
throw new Error('SearchResultsComponent missing required parameter: `results`.');
}
if (!parameters.modeSwitcher) {
throw new Error('SearchResultsComponent missing required parameter: `modeSwitcher`.');
}
this.results = parameters.results;
this.modeSwitcher = parameters.modeSwitcher;
this.resultFields = parameters.resultFields;
this.displayFor = function (field, result) {
if (_.isString(field)) {
field = _.find(this.resultFields(), { key: field });
}
return {
name: 'display/' + (field.display || 'text'),
params: {
data: result.data,
name: field.key,
display: field.display,
placeholder: field.placeholder
}
};
};
this.resultFor = function (result) {
return {
name: 'collections/' + typeFor(result) + '/' + this.modeSwitcher.mode().toLowerCase() + '-result',
params: this
};
};
this.detailUrlFor = function (result) {
return routes.detailUrlFor(typeFor(result), result.id());
};
};
}
);
}());
| (function () {
'use strict';
define(
[
'lodash',
'knockout',
'config/routes',
'util/container'
],
function (_, ko, routes, container) {
return function (parameters) {
var typeFor = function (result) {
return container.resolve('types')[result.data().type];
};
if (!parameters.results) {
throw new Error('SearchResultsComponent missing required parameter: `results`.');
}
if (!parameters.modeSwitcher) {
throw new Error('SearchResultsComponent missing required parameter: `modeSwitcher`.');
}
if (!parameters.resultFields) {
throw new Error('SearchResultsComponent missing required parameter: `resultFields`.');
}
this.results = parameters.results;
this.modeSwitcher = parameters.modeSwitcher;
this.resultFields = parameters.resultFields;
this.displayFor = function (field, result) {
if (_.isString(field)) {
field = _.find(this.resultFields(), { key: field });
}
return {
name: 'display/' + (field.display || 'text'),
params: {
data: result.data,
name: field.key,
display: field.display,
placeholder: field.placeholder
}
};
};
this.resultFor = function (result) {
return {
name: 'collections/' + typeFor(result) + '/' + this.modeSwitcher.mode().toLowerCase() + '-result',
params: this
};
};
this.detailUrlFor = function (result) {
return routes.detailUrlFor(typeFor(result), result.id());
};
};
}
);
}());
| Add missing error handling logic. | Add missing error handling logic.
| JavaScript | mit | rwahs/research-frontend,rwahs/research-frontend | ---
+++
@@ -19,6 +19,9 @@
}
if (!parameters.modeSwitcher) {
throw new Error('SearchResultsComponent missing required parameter: `modeSwitcher`.');
+ }
+ if (!parameters.resultFields) {
+ throw new Error('SearchResultsComponent missing required parameter: `resultFields`.');
}
this.results = parameters.results; |
53827506709f2a501bb4328b848cfbf470dac5e7 | app/js/app/controllers/AdminPageControllers.js | app/js/app/controllers/AdminPageControllers.js | /**
* Copyright 2014 Ian Davies
*
* 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.
*/
define([], function() {
var PageController = ['$scope', 'auth', 'api', function($scope, auth, api) {
$scope.contentVersion = api.contentVersion.get();
$scope.$watch("contentVersion.liveVersion", function() {
$scope.versionChange = null;
});
$scope.setVersion = function() {
$scope.versionChange = "IN_PROGRESS"
api.contentVersion.set({version: $scope.contentVersion.liveVersion}, {}).$promise.then(function(data) {
$scope.contentVersion = api.contentVersion.get().$promise.then(function() {
$scope.versionChange = "SUCCESS"
});
}).catch(function(e) {
console.error(e);
$scope.versionChange = "ERROR"
});
}
}]
return {
PageController: PageController,
};
}) | /**
* Copyright 2014 Ian Davies
*
* 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.
*/
define([], function() {
var PageController = ['$scope', 'auth', 'api', function($scope, auth, api) {
$scope.contentVersion = api.contentVersion.get();
$scope.$watch("contentVersion.liveVersion", function() {
$scope.versionChange = null;
});
$scope.setVersion = function() {
$scope.versionChange = "IN_PROGRESS"
api.contentVersion.set({version: $scope.contentVersion.liveVersion}, {}).$promise.then(function(data) {
$scope.contentVersion = api.contentVersion.get();
$scope.contentVersion.$promise.then(function() {
$scope.versionChange = "SUCCESS"
});
}).catch(function(e) {
console.error(e);
$scope.versionChange = "ERROR"
});
}
}]
return {
PageController: PageController,
};
}) | Fix bug introduced in previous commit. | Fix bug introduced in previous commit.
| JavaScript | mit | ucam-cl-dtg/isaac-app,ucam-cl-dtg/isaac-app,ucam-cl-dtg/isaac-app,ucam-cl-dtg/isaac-app | ---
+++
@@ -25,7 +25,8 @@
$scope.setVersion = function() {
$scope.versionChange = "IN_PROGRESS"
api.contentVersion.set({version: $scope.contentVersion.liveVersion}, {}).$promise.then(function(data) {
- $scope.contentVersion = api.contentVersion.get().$promise.then(function() {
+ $scope.contentVersion = api.contentVersion.get();
+ $scope.contentVersion.$promise.then(function() {
$scope.versionChange = "SUCCESS"
});
}).catch(function(e) { |
19dfa3f30e552f3cfed7e176262a3282d0380a19 | lib/commit-panel-component.js | lib/commit-panel-component.js | /** @babel */
/** @jsx etch.dom */
import etch from 'etch'
import StagingAreaComponent from './staging-area-component'
export default class CommitPanelComponent {
constructor ({repository}) {
this.repository = repository
etch.initialize(this)
}
destroy () {
this.subscription.dispose()
return etch.destroy()
}
render () {
if (this.repository == null) {
return (
<div className='git-CommitPanel'>
<div className='git-CommitPanel-item no-repository'>
<div>In order to use git features, please open a file that belongs to a git repository.</div>
</div>
</div>
)
} else {
return (
<div className='git-CommitPanel' tabIndex='-1'>
<header className='git-CommitPanel-item is-header'>Changes</header>
<StagingAreaComponent stagingArea={this.repository.getStagingArea()} />
</div>
)
}
}
update ({repository}) {
if (this.repository !== repository) {
this.repository = repository
return etch.update(this)
} else {
return Promise.resolve()
}
}
}
| /** @babel */
/** @jsx etch.dom */
import etch from 'etch'
import StagingAreaComponent from './staging-area-component'
export default class CommitPanelComponent {
constructor ({repository}) {
this.repository = repository
etch.initialize(this)
}
destroy () {
this.subscription.dispose()
return etch.destroy()
}
render () {
if (this.repository == null) {
return (
<div className='git-CommitPanel'>
<div className='git-CommitPanel-item no-repository'>
In order to use git features, please open a file that belongs to a git repository.
</div>
</div>
)
} else {
return (
<div className='git-CommitPanel' tabIndex='-1'>
<header className='git-CommitPanel-item is-header'>Changes</header>
<StagingAreaComponent stagingArea={this.repository.getStagingArea()} />
</div>
)
}
}
update ({repository}) {
if (this.repository !== repository) {
this.repository = repository
return etch.update(this)
} else {
return Promise.resolve()
}
}
}
| Delete extra div that's not needed for position purposes | :fire: Delete extra div that's not needed for position purposes
| JavaScript | mit | atom/github,atom/github,atom/github | ---
+++
@@ -20,7 +20,7 @@
return (
<div className='git-CommitPanel'>
<div className='git-CommitPanel-item no-repository'>
- <div>In order to use git features, please open a file that belongs to a git repository.</div>
+ In order to use git features, please open a file that belongs to a git repository.
</div>
</div>
) |
e78b0b6f4c8ddd378da9c3e5c81d59cfd5746617 | src/main/resources/static/js/script.js | src/main/resources/static/js/script.js | $('body').scrollspy({
target: '.bs-docs-sidebar',
offset: 40
});
| $('body').scrollspy({
target: '.bs-docs-sidebar',
offset: 40
});
if ($('textarea#content').length > 0) {
var regex = new RegExp('https?://[^\\s]*', 'g');
var subst = new Array(24).join('.');
$('label[for="content"]').append('<div class="small text-muted">(<span id="charcount">0</span> of 140 chars)</div>');
$('textarea#content').on('input propertychange', function() {
var content = $(this).val().replace(regex, subst);
var length = $(this).val().length - content.length;
$(this).val($(this).val().substring(0, 140 + length));
$('span#charcount').html($(this).val().replace(regex, subst).length);
});
}
| Add JS char counter for Tweet content | Add JS char counter for Tweet content
| JavaScript | epl-1.0 | spinfo/autoChirp,spinfo/autoChirp,spinfo/autoChirp | ---
+++
@@ -2,3 +2,18 @@
target: '.bs-docs-sidebar',
offset: 40
});
+
+if ($('textarea#content').length > 0) {
+ var regex = new RegExp('https?://[^\\s]*', 'g');
+ var subst = new Array(24).join('.');
+
+ $('label[for="content"]').append('<div class="small text-muted">(<span id="charcount">0</span> of 140 chars)</div>');
+
+ $('textarea#content').on('input propertychange', function() {
+ var content = $(this).val().replace(regex, subst);
+ var length = $(this).val().length - content.length;
+
+ $(this).val($(this).val().substring(0, 140 + length));
+ $('span#charcount').html($(this).val().replace(regex, subst).length);
+ });
+} |
b78f6e0e9f8a9ca3e7c8c096400dd32428550397 | lib/fs/readdir-directories.js | lib/fs/readdir-directories.js | // Read all filenames from directory and it's subdirectories
'use strict';
var fs = require('fs')
, aritize = require('es5-ext/lib/Function/aritize').call
, curry = require('es5-ext/lib/Function/curry').call
, invoke = require('es5-ext/lib/Function/invoke')
, k = require('es5-ext/lib/Function/k')
, a2p = require('deferred/lib/async-to-promise').call
, ba2p = require('deferred/lib/async-to-promise').bind
, all = require('deferred/lib/join/all')
, concat = aritize(String.prototype.concat, 1)
, trim = require('../path/trim')
, readdir = ba2p(fs.readdir), stat = ba2p(fs.lstat);
require('deferred/lib/ext/cb');
module.exports = function self (path, callback) {
readdir(path = trim(path))
(function (files) {
return all(files, function (file) {
var npath = path + '/' + file;
return stat(npath)
(function (stats) {
return stats.isDirectory() ? file : null;
}, k(null));
})
(invoke('filter', Boolean));
}).cb(callback);
};
| // Read all filenames from directory and it's subdirectories
'use strict';
var fs = require('fs')
, aritize = require('es5-ext/lib/Function/prototype/aritize')
, invoke = require('es5-ext/lib/Function/invoke')
, k = require('es5-ext/lib/Function/k')
, a2p = require('deferred/lib/async-to-promise').call
, ba2p = require('deferred/lib/async-to-promise').bind
, all = require('deferred/lib/join/all')
, concat = aritize.call(String.prototype.concat, 1)
, trim = require('../path/trim')
, readdir = ba2p(fs.readdir), stat = ba2p(fs.lstat);
require('deferred/lib/ext/cb');
module.exports = function self (path, callback) {
readdir(path = trim(path))
(function (files) {
return all(files, function (file) {
var npath = path + '/' + file;
return stat(npath)
(function (stats) {
return stats.isDirectory() ? file : null;
}, k(null));
})
(invoke('filter', Boolean));
}).cb(callback);
};
| Update up to changes in es5-ext | Update up to changes in es5-ext
| JavaScript | mit | medikoo/node-ext | ---
+++
@@ -3,14 +3,13 @@
'use strict';
var fs = require('fs')
- , aritize = require('es5-ext/lib/Function/aritize').call
- , curry = require('es5-ext/lib/Function/curry').call
+ , aritize = require('es5-ext/lib/Function/prototype/aritize')
, invoke = require('es5-ext/lib/Function/invoke')
, k = require('es5-ext/lib/Function/k')
, a2p = require('deferred/lib/async-to-promise').call
, ba2p = require('deferred/lib/async-to-promise').bind
, all = require('deferred/lib/join/all')
- , concat = aritize(String.prototype.concat, 1)
+ , concat = aritize.call(String.prototype.concat, 1)
, trim = require('../path/trim')
|
5293f49e247b3cb8617e943f7e0b33431de8d1ae | assets/js/components/page-header-date-range.js | assets/js/components/page-header-date-range.js | /**
* PageHeaderDateRange 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.
*/
/**
* WordPress dependencies
*/
import { applyFilters } from '@wordpress/hooks';
/**
* Internal dependencies
*/
import DateRangeSelector from './date-range-selector';
export default function PageHeaderDateRange() {
const showDateRangeSelector = applyFilters( `googlesitekit.showDateRangeSelector`, false );
return showDateRangeSelector && (
<span className="googlesitekit-page-header__range">
<DateRangeSelector />
</span>
);
}
| /**
* PageHeaderDateRange 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 DateRangeSelector from './date-range-selector';
export default function PageHeaderDateRange() {
return (
<span className="googlesitekit-page-header__range">
<DateRangeSelector />
</span>
);
}
| Remove unnecessary filter from within . | Remove unnecessary filter from within .
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -17,19 +17,12 @@
*/
/**
- * WordPress dependencies
- */
-import { applyFilters } from '@wordpress/hooks';
-
-/**
* Internal dependencies
*/
import DateRangeSelector from './date-range-selector';
export default function PageHeaderDateRange() {
- const showDateRangeSelector = applyFilters( `googlesitekit.showDateRangeSelector`, false );
-
- return showDateRangeSelector && (
+ return (
<span className="googlesitekit-page-header__range">
<DateRangeSelector />
</span> |
d7107ec75e0be80a100705ce790f593f4014df90 | lib/server/plugins/map/src.js | lib/server/plugins/map/src.js | var fs = require('fs'),
path = require('path'),
_ = require('lodash'),
gulp = require('gulp'),
through = require('through2'),
file = require('gulp-file');
module.exports = mapSrcPlugin;
var contents = {};
/**
* @ignore
* Loads `map.json` into stream.
* @alias "map.src"
* @param {Object} data Cross-plugin request data
* @returns {stream.Transform} Stream
*/
function mapSrcPlugin (data) {
if (!contents[data.src]) {
contents[data.src] = stringifyMap(require(path.resolve(data.src + 'map.json')));
}
return file('map.json', contents[data.src], { src: true });
}
// TODO shared with ymb
function stringifyMap (map) {
var stack = [];
_.each(map, function (moduleInfo) {
stack.push('[' + _.map(moduleInfo, function (value, index) {
if (index == 2 && value.slice(0, 8) == 'function') {
return value;
} else if (index == 5 && typeof value == 'object') {
return '{ ' + _.map(value, function (v, k) { return k + ': ' + v; }).join(', ') + ' }';
} else {
return '\'' + value + '\'';
}
}).join(', ') + ']');
});
return '[\n ' + stack.join(',\n ') + '\n]';
}
| var fs = require('fs'),
path = require('path'),
_ = require('lodash'),
gulp = require('gulp'),
through = require('through2'),
file = require('gulp-file');
module.exports = mapSrcPlugin;
var contents = {};
function requireFresh (src) {
delete require.cache[require.resolve(src)];
return require(src);
}
/**
* @ignore
* Loads `map.json` into stream.
* @alias "map.src"
* @param {Object} data Cross-plugin request data
* @returns {stream.Transform} Stream
*/
function mapSrcPlugin (data) {
if (!data.cacheEnabled || !contents[data.src]) {
contents[data.src] = stringifyMap(
requireFresh(path.resolve(data.src + 'map.json'))
);
}
return file('map.json', contents[data.src], { src: true });
}
// TODO shared with ymb
function stringifyMap (map) {
var stack = [];
_.each(map, function (moduleInfo) {
stack.push('[' + _.map(moduleInfo, function (value, index) {
if (index == 2 && value.slice(0, 8) == 'function') {
return value;
} else if (index == 5 && typeof value == 'object') {
return '{ ' + _.map(value, function (v, k) { return k + ': ' + v; }).join(', ') + ' }';
} else {
return '\'' + value + '\'';
}
}).join(', ') + ']');
});
return '[\n ' + stack.join(',\n ') + '\n]';
}
| Allow watching changes in modules map for ymb dev mode | Allow watching changes in modules map for ymb dev mode
| JavaScript | mpl-2.0 | yandex/yms | ---
+++
@@ -9,6 +9,11 @@
var contents = {};
+function requireFresh (src) {
+ delete require.cache[require.resolve(src)];
+ return require(src);
+}
+
/**
* @ignore
* Loads `map.json` into stream.
@@ -17,8 +22,10 @@
* @returns {stream.Transform} Stream
*/
function mapSrcPlugin (data) {
- if (!contents[data.src]) {
- contents[data.src] = stringifyMap(require(path.resolve(data.src + 'map.json')));
+ if (!data.cacheEnabled || !contents[data.src]) {
+ contents[data.src] = stringifyMap(
+ requireFresh(path.resolve(data.src + 'map.json'))
+ );
}
return file('map.json', contents[data.src], { src: true }); |
7fcb5b81f41088cdcb780e6c42dd529f8160ced5 | src/js/app/global.js | src/js/app/global.js | import Helper from "./Helper";
const h = new Helper;
export let userItems;
if (h.detectEnvironment() === "development") {
userItems = "./src/data/list.json";
} else if (h.detectEnvironment() === "production") {
userItems = global.process.resourcesPath + "/app/src/data/list.json";
} else {
throw `global | userItems: ${userItems}`;
}
export const settings = "./src/data/settings.json"; | import Helper from "./Helper";
const h = new Helper;
export let userItems;
export let settings;
if (h.detectEnvironment() === "development") {
userItems = "./src/data/list.json";
settings = "./src/data/settings.json";
} else if (h.detectEnvironment() === "production") {
userItems = global.process.resourcesPath + "/app/src/data/list.json";
settings = global.process.resourcesPath + "/app/src/data/settings.json";
} else {
throw "Can't detect environment";
} | Fix wrong path to settings in production | Fix wrong path to settings in production
| JavaScript | mpl-2.0 | LosEagle/MediaWorld,LosEagle/MediaWorld | ---
+++
@@ -3,13 +3,14 @@
const h = new Helper;
export let userItems;
+export let settings;
if (h.detectEnvironment() === "development") {
userItems = "./src/data/list.json";
+ settings = "./src/data/settings.json";
} else if (h.detectEnvironment() === "production") {
userItems = global.process.resourcesPath + "/app/src/data/list.json";
+ settings = global.process.resourcesPath + "/app/src/data/settings.json";
} else {
- throw `global | userItems: ${userItems}`;
+ throw "Can't detect environment";
}
-
-export const settings = "./src/data/settings.json"; |
f8e2bc8801ddda5301f4ff7c473ee72583c442e8 | src/lib/analytics.js | src/lib/analytics.js | import GoogleAnalytics from 'react-ga';
GoogleAnalytics.initialize('UA-30688952-5', {
debug: (process.env.NODE_ENV !== 'production'),
titleCase: true,
sampleRate: 100,
forceSSL: true
});
export default GoogleAnalytics;
| import GoogleAnalytics from 'react-ga';
GoogleAnalytics.initialize('UA-30688952-5', {
debug: (process.env.NODE_ENV !== 'production'),
titleCase: true,
sampleRate: (process.env.NODE_ENV === 'production') ? 100 : 0,
forceSSL: true
});
export default GoogleAnalytics;
| Make sure GA events are not transmitted outside of production | Make sure GA events are not transmitted outside of production
| JavaScript | bsd-3-clause | cwillisf/scratch-gui,LLK/scratch-gui,cwillisf/scratch-gui,LLK/scratch-gui,cwillisf/scratch-gui | ---
+++
@@ -3,7 +3,7 @@
GoogleAnalytics.initialize('UA-30688952-5', {
debug: (process.env.NODE_ENV !== 'production'),
titleCase: true,
- sampleRate: 100,
+ sampleRate: (process.env.NODE_ENV === 'production') ? 100 : 0,
forceSSL: true
});
|
ae9d478e9abecb289c875ac9069dbff0dba96bcb | src/utils/storage.js | src/utils/storage.js | export default class Storage {
} | import fs from 'fs'
export default class Storage {
static async addHistoryItem (title, url) {
return new Promise((resolve, reject) => {
if (title != null && url != null) {
// Get today's date.
let today = new Date()
let dd = today.getDate()
let mm = today.getMonth() + 1
let yyyy = today.getFullYear()
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '-' + dd + '-' + yyyy
let data = Storage.getHistory()
if (!url.startsWith('wexond://') && !url.startsWith('about:blank')) {
// Get current time.
let date = new Date()
let currentHour = date.getHours()
let currentMinute = date.getMinutes()
let time = `${currentHour}:${currentMinute}`
// Configure newItem's data.
let newItem = {
'url': url,
'title': title,
'date': today,
'time': time
}
// Get newItem's new id.
if (data[data.length - 1] == null) {
newItem.id = 0
} else {
newItem.id = data[data.length - 1].id + 1
}
// Push new history item.
data.push(newItem)
try {
await Storage.saveHistory(data)
resolve()
} catch (error) {
reject(error)
}
}
}
})
}
static async saveHistory (jsonObject) {
return new Promise((resolve, reject) => {
fs.writeFile(global.historyPath, JSON.stringify(jsonObject), function (error) {
if (error) {
reject(error)
} else {
resolve()
}
})
})
}
static async resetHistory () {
return new Promise((resolve, reject) => {
try {
await Storage.saveHistory([])
resolve()
} catch (error) {
reject(error)
}
})
}
static getHistory () {
return new Promise((resolve, reject) => {
fs.readFile(global.historyPath, function (error, data) {
if (error) {
reject(error)
} else {
resolve(JSON.parse(data))
}
})
})
}
} | Add saving & reading history functions | Add saving & reading history functions
| JavaScript | apache-2.0 | Nersent/Wexond,Nersent/Wexond | ---
+++
@@ -1,3 +1,95 @@
+import fs from 'fs'
+
export default class Storage {
-
+ static async addHistoryItem (title, url) {
+ return new Promise((resolve, reject) => {
+ if (title != null && url != null) {
+ // Get today's date.
+ let today = new Date()
+ let dd = today.getDate()
+ let mm = today.getMonth() + 1
+ let yyyy = today.getFullYear()
+
+ if (dd < 10) {
+ dd = '0' + dd
+ }
+
+ if (mm < 10) {
+ mm = '0' + mm
+ }
+
+ today = mm + '-' + dd + '-' + yyyy
+
+ let data = Storage.getHistory()
+
+ if (!url.startsWith('wexond://') && !url.startsWith('about:blank')) {
+ // Get current time.
+ let date = new Date()
+ let currentHour = date.getHours()
+ let currentMinute = date.getMinutes()
+ let time = `${currentHour}:${currentMinute}`
+
+ // Configure newItem's data.
+ let newItem = {
+ 'url': url,
+ 'title': title,
+ 'date': today,
+ 'time': time
+ }
+
+ // Get newItem's new id.
+ if (data[data.length - 1] == null) {
+ newItem.id = 0
+ } else {
+ newItem.id = data[data.length - 1].id + 1
+ }
+
+ // Push new history item.
+ data.push(newItem)
+
+ try {
+ await Storage.saveHistory(data)
+ resolve()
+ } catch (error) {
+ reject(error)
+ }
+ }
+ }
+ })
+ }
+
+ static async saveHistory (jsonObject) {
+ return new Promise((resolve, reject) => {
+ fs.writeFile(global.historyPath, JSON.stringify(jsonObject), function (error) {
+ if (error) {
+ reject(error)
+ } else {
+ resolve()
+ }
+ })
+ })
+ }
+
+ static async resetHistory () {
+ return new Promise((resolve, reject) => {
+ try {
+ await Storage.saveHistory([])
+ resolve()
+ } catch (error) {
+ reject(error)
+ }
+ })
+ }
+
+ static getHistory () {
+ return new Promise((resolve, reject) => {
+ fs.readFile(global.historyPath, function (error, data) {
+ if (error) {
+ reject(error)
+ } else {
+ resolve(JSON.parse(data))
+ }
+ })
+ })
+ }
} |
46c0243fce1efc22a61998033f45956d88ed6421 | tools/static-assets/server/npm-rebuild-args.js | tools/static-assets/server/npm-rebuild-args.js | // Command-line arguments passed to npm when rebuilding binary packages.
var args = [
"rebuild",
// The --no-bin-links flag tells npm not to create symlinks in the
// node_modules/.bin/ directory when rebuilding packages, which helps
// avoid problems like https://github.com/meteor/meteor/issues/7401.
"--no-bin-links",
// The --update-binary flag tells node-pre-gyp to replace previously
// installed local binaries with remote binaries:
// https://github.com/mapbox/node-pre-gyp#options
"--update-binary"
];
exports.get = function () {
// Make a defensive copy.
return args.slice(0);
};
| // Command-line arguments passed to npm when rebuilding binary packages.
var args = [
"rebuild",
// The --no-bin-links flag tells npm not to create symlinks in the
// node_modules/.bin/ directory when rebuilding packages, which helps
// avoid problems like https://github.com/meteor/meteor/issues/7401.
"--no-bin-links",
// The --update-binary flag tells node-pre-gyp to replace previously
// installed local binaries with remote binaries:
// https://github.com/mapbox/node-pre-gyp#options
"--update-binary"
];
// Allow additional flags to be passed via the $METEOR_NPM_REBUILD_FLAGS
// environment variable.
var flags = process.env.METEOR_NPM_REBUILD_FLAGS;
if (flags) {
args.push.apply(args, flags.split(/\s+/g));
}
exports.get = function () {
// Make a defensive copy.
return args.slice(0);
};
| Support additional `meteor rebuild` flags via environment variable. | Support additional `meteor rebuild` flags via environment variable.
| JavaScript | mit | Hansoft/meteor,chasertech/meteor,mjmasn/meteor,Hansoft/meteor,chasertech/meteor,mjmasn/meteor,chasertech/meteor,mjmasn/meteor,chasertech/meteor,mjmasn/meteor,Hansoft/meteor,chasertech/meteor,Hansoft/meteor,chasertech/meteor,Hansoft/meteor,Hansoft/meteor,mjmasn/meteor,Hansoft/meteor,chasertech/meteor,mjmasn/meteor,mjmasn/meteor | ---
+++
@@ -13,6 +13,13 @@
"--update-binary"
];
+// Allow additional flags to be passed via the $METEOR_NPM_REBUILD_FLAGS
+// environment variable.
+var flags = process.env.METEOR_NPM_REBUILD_FLAGS;
+if (flags) {
+ args.push.apply(args, flags.split(/\s+/g));
+}
+
exports.get = function () {
// Make a defensive copy.
return args.slice(0); |
4d1935449f76de2fb775a6a70518e2a897e32b90 | src/content-tooltip/constants.js | src/content-tooltip/constants.js | export const TOOLTIP_DEFAULT_OPTION = true
export const POSITION_DEFAULT_OPTION = 'mouse'
export const HIGHLIGHTS_DEFAULT_OPTION = true
export const HIGHLIGHTS_STORAGE_NAME = 'memex_link_highlights'
export const TOOLTIP_STORAGE_NAME = 'memex_link_tooltip'
export const POSITION_STORAGE_NAME = 'memex_link_position'
export const INFO_URL =
'https://worldbrain.helprace.com/i62-feature-memex-links-highlight-any-text-and-create-a-link-to-it'
export const KEYBOARDSHORTCUTS_STORAGE_NAME = 'memex-keyboardshortcuts'
export const KEYBOARDSHORTCUTS_DEFAULT_STATE = {
shortcutsEnabled: false,
linkShortcut: 'shift+l',
toggleSidebarShortcut: 'shift+r',
toggleHighlightsShortcut: 'shift+h',
createAnnotationShortcut: 'shift+a',
createHighlightShortcut: 'shift+n',
createBookmarkShortcut: 'shift+b',
addTagShortcut: 'shift+t',
addToCollectionShortcut: 'shift+u',
addCommentShortcut: 'shift+c',
linkShortcutEnabled: true,
toggleSidebarShortcutEnabled: true,
toggleHighlightsShortcutEnabled: true,
createAnnotationShortcutEnabled: true,
createBookmarkShortcutEnabled: true,
createHighlightShortcutEnabled: true,
addTagShortcutEnabled: true,
addToCollectionShortcutEnabled: true,
addCommentShortcutEnabled: true,
}
| export const TOOLTIP_DEFAULT_OPTION = true
export const POSITION_DEFAULT_OPTION = 'mouse'
export const HIGHLIGHTS_DEFAULT_OPTION = true
export const HIGHLIGHTS_STORAGE_NAME = 'memex_link_highlights'
export const TOOLTIP_STORAGE_NAME = 'memex_link_tooltip'
export const POSITION_STORAGE_NAME = 'memex_link_position'
export const INFO_URL =
'https://worldbrain.helprace.com/i62-feature-memex-links-highlight-any-text-and-create-a-link-to-it'
export const KEYBOARDSHORTCUTS_STORAGE_NAME = 'memex-keyboardshortcuts'
export const KEYBOARDSHORTCUTS_DEFAULT_STATE = {
shortcutsEnabled: false,
linkShortcut: 'alt+l',
toggleSidebarShortcut: 'alt+r',
toggleHighlightsShortcut: 'alt+h',
createAnnotationShortcut: 'alt+a',
createHighlightShortcut: 'alt+n',
createBookmarkShortcut: 'alt+b',
addTagShortcut: 'alt+t',
addToCollectionShortcut: 'alt+u',
addCommentShortcut: 'alt+c',
linkShortcutEnabled: true,
toggleSidebarShortcutEnabled: true,
toggleHighlightsShortcutEnabled: true,
createAnnotationShortcutEnabled: true,
createBookmarkShortcutEnabled: true,
createHighlightShortcutEnabled: true,
addTagShortcutEnabled: true,
addToCollectionShortcutEnabled: true,
addCommentShortcutEnabled: true,
}
| Change keyboard shortcut defaults to shift+ | Change keyboard shortcut defaults to shift+
| JavaScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -10,15 +10,15 @@
export const KEYBOARDSHORTCUTS_DEFAULT_STATE = {
shortcutsEnabled: false,
- linkShortcut: 'shift+l',
- toggleSidebarShortcut: 'shift+r',
- toggleHighlightsShortcut: 'shift+h',
- createAnnotationShortcut: 'shift+a',
- createHighlightShortcut: 'shift+n',
- createBookmarkShortcut: 'shift+b',
- addTagShortcut: 'shift+t',
- addToCollectionShortcut: 'shift+u',
- addCommentShortcut: 'shift+c',
+ linkShortcut: 'alt+l',
+ toggleSidebarShortcut: 'alt+r',
+ toggleHighlightsShortcut: 'alt+h',
+ createAnnotationShortcut: 'alt+a',
+ createHighlightShortcut: 'alt+n',
+ createBookmarkShortcut: 'alt+b',
+ addTagShortcut: 'alt+t',
+ addToCollectionShortcut: 'alt+u',
+ addCommentShortcut: 'alt+c',
linkShortcutEnabled: true,
toggleSidebarShortcutEnabled: true,
toggleHighlightsShortcutEnabled: true, |
951089170b2b7c3e9e53f292c537165bbd1c5551 | lib/mailer/transporter.js | lib/mailer/transporter.js | const nodemailer = require('nodemailer')
const config = require('../config')
let opts = config.get('mailer.service')
? config.get('mailer')
: config.get('nodemailer')
// Use directTransport when nothing is configured
if (opts && Object.keys(opts).length === 0) {
opts = undefined
}
const transport = opts ?
nodemailer.createTransport(opts) :
nodemailer.createTransport()
module.exports = transport
| const nodemailer = require('nodemailer')
const config = require('../config')
let opts = config.get('mailer.service')
? config.get('mailer')
: config.get('nodemailer')
// Use directTransport when nothing is configured
if (opts && Object.keys(opts).length === 0) {
opts = undefined
}
const transport = opts ?
nodemailer.createTransport(opts) :
nodemailer.createTransport({})
module.exports = transport
| Fix Cannot set property 'mailer' of undefined error | Fix Cannot set property 'mailer' of undefined error
| JavaScript | mit | DemocracyOS/notifier | ---
+++
@@ -12,6 +12,6 @@
const transport = opts ?
nodemailer.createTransport(opts) :
- nodemailer.createTransport()
+ nodemailer.createTransport({})
module.exports = transport |
2136ad411edde6f3f2208acc12ce204c2d7137c6 | lib/collections/projects.js | lib/collections/projects.js | Projects = new Mongo.Collection('projects');
Meteor.methods({
insertProject: function(projectAttributes) {
check(Meteor.userId(), String);
check(projectAttributes, {
name: Match.Where(function(val) {
check(val, String);
return val.length > 0;
}),
description: String
});
var ownerAttributes = {
userId: Meteor.userId(),
username: Meteor.user().username
};
var project = _.extend(projectAttributes, {
owner: ownerAttributes,
members: [],
tasks: [],
createdAt: new Date()
});
var projectId = Projects.insert(project);
return {
_id: projectId
};
},
addUserToProject: function(requestAttributes) {
check(Meteor.userId(), String);
check(requestAttributes, {
userId: String,
requestingUserId: String,
requestId: String,
projectId: String,
notificationId: String
});
Projects.update({
_id : requestAttributes.projectId
}, {
$addToSet: {
members: requestAttributes.requestingUserId
}
});
Meteor.call('setNotificationAsRead', requestAttributes.notificationId, function(err, result) {
if (err) {
console.log(err);
}
});
}
});
| Projects = new Mongo.Collection('projects');
Meteor.methods({
insertProject: function(projectAttributes) {
check(Meteor.userId(), String);
check(projectAttributes, {
name: Match.Where(function(val) {
check(val, String);
return val.length > 0;
}),
description: String
});
var ownerAttributes = {
userId: Meteor.userId(),
username: Meteor.user().username
};
var project = _.extend(projectAttributes, {
owner: ownerAttributes,
members: [],
tasks: [],
createdAt: new Date()
});
var projectId = Projects.insert(project);
return {
_id: projectId
};
},
addUserToProject: function(requestAttributes) {
check(Meteor.userId(), String);
check(requestAttributes, {
userId: String,
requestingUserId: String,
requestId: String,
projectId: String,
notificationId: String
});
Projects.update({
_id : requestAttributes.projectId
}, {
$addToSet: {
members: requestAttributes.requestingUserId
}
});
Requests.update({_id: requestAttributes.requestId}, {
status: 'accepted'
});
Meteor.call('setNotificationAsRead', requestAttributes.notificationId, function(err, result) {
if (err) {
console.log(err);
}
});
}
});
| Update request status to 'accepted' | Update request status to 'accepted'
| JavaScript | mit | PUMATeam/puma,PUMATeam/puma | ---
+++
@@ -48,6 +48,10 @@
}
});
+ Requests.update({_id: requestAttributes.requestId}, {
+ status: 'accepted'
+ });
+
Meteor.call('setNotificationAsRead', requestAttributes.notificationId, function(err, result) {
if (err) {
console.log(err); |
4e6ebfc002b096753575f9bc966ffe30e201411f | test/git-describe.js | test/git-describe.js | /*
* Copyright 2017 HM Revenue & Customs
*
* 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.
*/
import path from 'path'
import test from 'tape'
import { execFileSync } from 'child_process'
import suiteName from './utils/suite'
import gitDescribe from '../lib/git-describe'
const suite = suiteName(__filename)
const repoDir = path.join(__dirname, 'test-repo')
test(`${suite} Fail if the given path is not a git repo`, (t) => {
t.throws(function () {
gitDescribe(repoDir)
}, new RegExp(/fatal: Not a git repository:/))
t.end()
})
test(`${suite} Return the sha of the parent repo if not given a path`, (t) => {
const execArgs = [
'describe',
'--long',
'--always'
]
const parentSha = execFileSync('git', execArgs)
const sha = gitDescribe()
t.equal(parentSha.toString('utf-8').trim(), sha)
t.end()
})
| /*
* Copyright 2017 HM Revenue & Customs
*
* 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.
*/
import path from 'path'
import test from 'tape'
import { spawnSync } from 'child_process'
import suiteName from './utils/suite'
import gitDescribe from '../lib/git-describe'
const suite = suiteName(__filename)
const repoDir = path.join(__dirname, 'test-repo')
test(`${suite} Fail if the given path is not a git repo`, (t) => {
t.throws(function () {
gitDescribe(repoDir)
}, new RegExp(/fatal: Not a git repository:/))
t.end()
})
test(`${suite} Return the sha of the parent repo if not given a path`, (t) => {
const parentSha = spawnSync('git', ['describe', '--long', '--always'])
const sha = gitDescribe()
t.equal(parentSha.stdout.toString('utf-8').trim(), sha)
t.end()
})
| Switch execFile out for spawn and flatten args in tests | Switch execFile out for spawn and flatten args in tests
| JavaScript | apache-2.0 | hmrc/node-git-versioning | ---
+++
@@ -16,7 +16,7 @@
import path from 'path'
import test from 'tape'
-import { execFileSync } from 'child_process'
+import { spawnSync } from 'child_process'
import suiteName from './utils/suite'
import gitDescribe from '../lib/git-describe'
@@ -33,15 +33,9 @@
})
test(`${suite} Return the sha of the parent repo if not given a path`, (t) => {
- const execArgs = [
- 'describe',
- '--long',
- '--always'
- ]
-
- const parentSha = execFileSync('git', execArgs)
+ const parentSha = spawnSync('git', ['describe', '--long', '--always'])
const sha = gitDescribe()
- t.equal(parentSha.toString('utf-8').trim(), sha)
+ t.equal(parentSha.stdout.toString('utf-8').trim(), sha)
t.end()
}) |
6fa2ccc5eee5e7d3fa76a989a029f4a8ba6ee0a7 | app.js | app.js | var express = require('express'), app = express(), swig = require('swig');
var bodyParser = require('body-parser');
var https = require('https'), config = require('./config');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/pages');
app.set('view cache', false);
swig.setDefaults({ cache: false });
app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.get('/', function(req, res) {
res.render('index', { 'foo': 'hi' });
});
app.post('/hook', function(req, res) {
if (req.body && req.body.after) {
console.log("checking: " + req.body.after);
var request = https.request({ 'host': 'api.github.com',
'path': '/repos/' + config.repoURL + '/status/' + req.body.after + '?access_token=' + config.githubToken,
'method': 'POST'}, function(res) {
res.on('data', function(data) {
console.log(data);
});
});
request.write(JSON.stringify({ 'state': 'pending' }));
request.end();
}
res.end();
});
app.listen(2345);
| var express = require('express'), app = express(), swig = require('swig');
var bodyParser = require('body-parser');
var https = require('https'), config = require('./config');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/pages');
app.set('view cache', false);
swig.setDefaults({ cache: false });
app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.get('/', function(req, res) {
res.render('index', { 'foo': 'hi' });
});
app.post('/hook', function(req, res) {
if (req.body && req.body.after) {
console.log("checking: " + req.body.after);
var request = https.request({ 'host': 'api.github.com',
'path': '/repos/' + config.repoURL + '/status/' + req.body.after + '?access_token=' + config.githubToken,
'method': 'POST'}, function(res) {
res.on('data', function(data) {
console.log(data.toString());
});
});
request.write(JSON.stringify({ 'state': 'pending' }));
request.end();
}
res.end();
});
app.listen(2345);
| Convert debug info to string | Convert debug info to string
| JavaScript | mit | iveysaur/PiCi | ---
+++
@@ -25,7 +25,7 @@
'path': '/repos/' + config.repoURL + '/status/' + req.body.after + '?access_token=' + config.githubToken,
'method': 'POST'}, function(res) {
res.on('data', function(data) {
- console.log(data);
+ console.log(data.toString());
});
});
request.write(JSON.stringify({ 'state': 'pending' })); |
17d489ce36b25598ee22a6eec5570b5395fd52c3 | app.js | app.js | var express = require('express');
var bunyan = require('bunyan');
var log = bunyan.createLogger({ name: 'app' });
var app = express();
var pkg = require('./index.js');
pkg.boot(app, 'somesecret');
app.post('/', pkg.router(function(req, res, event) {
log.info(req.body);
switch (event) {
case 'ping':
res.send('Ping');
}
}));
app.listen(8080);
| var express = require('express');
var bunyan = require('bunyan');
var log = bunyan.createLogger({ name: 'app' });
var app = express();
var pkg = require('./index.js');
pkg.boot(app, 'somesecret');
app.post('/', pkg.router(function(req, res, event) {
log.info(req.body, event);
switch (event) {
case 'ping':
res.send('Ping');
}
}));
app.listen(8080);
| Add the event to the log | Add the event to the log
| JavaScript | mit | datashaman/datashaman-webhooks | ---
+++
@@ -8,7 +8,7 @@
pkg.boot(app, 'somesecret');
app.post('/', pkg.router(function(req, res, event) {
- log.info(req.body);
+ log.info(req.body, event);
switch (event) {
case 'ping': |
a8688da380bd94ecc62c3b3e5591e39358fe2e05 | app.js | app.js | const express = require('express');
const app = express();
const port = 3000;
require('./middleware.js')(app, express);
app.listen(port, function() {
console.log('Now listening on port', port);
});
module.exports = app;
| const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
require('./middleware.js')(app, express);
app.listen(port, function() {
console.log('Now listening on port', port);
});
module.exports = app;
| Fix server port for Heroku deployment | Fix server port for Heroku deployment
| JavaScript | mit | MapReactor/SonderServer,aarontrank/SonderServer,aarontrank/SonderServer,MapReactor/SonderServer | ---
+++
@@ -1,6 +1,6 @@
const express = require('express');
const app = express();
-const port = 3000;
+const port = process.env.PORT || 3000;
require('./middleware.js')(app, express);
|
f72cae72a9227502282e63d5bacb7c520cbfdf73 | app.js | app.js | var WebSocketServer = require('websocket').server;
var http = require('http');
var argv = require('yargs')
.alias('e', 'exec')
.default('port', 8080)
.alias('p', 'password')
.describe('p', 'Set a specific password to the WebSocket server')
.demand(['e'])
.argv;
var controllers = require('./lib/connectionCtrl.js');
var utils = require('./lib/utils.js');
var PORT = argv.port;
if (argv.password === undefined) console.log("\033[31m\nWARNING: It is recommended to set a password and use encrypted connections with sensible data.\n \x1b[0m")
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(PORT, function() {
utils.log('Server is listening on port ' + PORT);
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
wsServer.on('request', function(request) {
controllers.onRequest(request, argv);
}); | var WebSocketServer = require('websocket').server;
var http = require('http');
var argv = require('yargs')
.alias('e', 'exec')
.default('port', 8080)
.alias('p', 'password')
.alias('ssl', 'https')
.boolean('ssl')
.describe('ssl', 'Add https support')
.describe('ssl-key', 'Route to SSL key')
.describe('ssl-cert', 'Route to SSL certificate')
.describe('port', 'Set the port to listen')
.describe('e', 'Set the command you want to execute')
.describe('p', 'Set a specific password to the WebSocket server')
.demand(['e'])
.implies('ssl', 'ssl-cert')
.implies('ssl-cert', 'ssl-key')
.argv;
var controllers = require('./lib/connectionCtrl.js');
var utils = require('./lib/utils.js');
var PORT = argv.port;
if (argv.password === undefined) console.log("\033[31m\nWARNING: It is recommended to set a password and use encrypted connections with sensible data.\n \x1b[0m")
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(PORT, function() {
utils.log('Server is listening on port ' + PORT);
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
wsServer.on('request', function(request) {
controllers.onRequest(request, argv);
}); | ADD https flags and flags improvement | ADD https flags and flags improvement
| JavaScript | mit | Drag0s/node-websocketd | ---
+++
@@ -4,8 +4,17 @@
.alias('e', 'exec')
.default('port', 8080)
.alias('p', 'password')
+ .alias('ssl', 'https')
+ .boolean('ssl')
+ .describe('ssl', 'Add https support')
+ .describe('ssl-key', 'Route to SSL key')
+ .describe('ssl-cert', 'Route to SSL certificate')
+ .describe('port', 'Set the port to listen')
+ .describe('e', 'Set the command you want to execute')
.describe('p', 'Set a specific password to the WebSocket server')
- .demand(['e'])
+ .demand(['e'])
+ .implies('ssl', 'ssl-cert')
+ .implies('ssl-cert', 'ssl-key')
.argv;
var controllers = require('./lib/connectionCtrl.js'); |
6935fb259a228bca7d11ac173e23c56235d235dc | app.js | app.js | /*
* Mailchimp AJAX form submit VanillaJS
* Vanilla JS
* Author: Michiel Vandewalle
* Github author: https://github.com/michiel-vandewalle
* Github project: https://github.com/michiel-vandewalle/Mailchimp-AJAX-form-submit-vanillaJS
*/
(function () {
document.getElementsByTagName('form')[0].addEventListener('submit', function (e) {
e.preventDefault();
// Check for spam
if(document.getElementById('js-validate-robot').value !== '') { return false }
// Get url for mailchimp
var url = this.action.replace('/post?', '/post-json?');
// Add form data to object
var data = '';
var inputs = this.querySelectorAll('#js-form-inputs input');
for (var i = 0; i < inputs.length; i++) {
data += '&' + inputs[i].name + '=' + encodeURIComponent(inputs[i].value);
}
// Create & add post script to the DOM
var script = document.createElement('script');
script.src = url + data;
document.body.appendChild(script);
// Callback function
var callback = 'callback';
window[callback] = function(data) {
// Remove post script from the DOM
delete window[callback];
document.body.removeChild(script);
// Display response message
document.getElementById('js-subscribe-response').innerHTML = data.msg
};
});
})(); | /*
* Mailchimp AJAX form submit VanillaJS
* Vanilla JS
* Author: Michiel Vandewalle
* Github author: https://github.com/michiel-vandewalle
* Github project: https://github.com/michiel-vandewalle/Mailchimp-AJAX-form-submit-vanillaJS
*/
(function () {
if (document.getElementsByTagName('form').length > 0) {
document.getElementsByTagName('form')[0].addEventListener('submit', function (e) {
e.preventDefault();
// Check for spam
if(document.getElementById('js-validate-robot').value !== '') { return false }
// Get url for mailchimp
var url = this.action.replace('/post?', '/post-json?');
// Add form data to object
var data = '';
var inputs = this.querySelectorAll('#js-form-inputs input');
for (var i = 0; i < inputs.length; i++) {
data += '&' + inputs[i].name + '=' + encodeURIComponent(inputs[i].value);
}
// Create & add post script to the DOM
var script = document.createElement('script');
script.src = url + data;
document.body.appendChild(script);
// Callback function
var callback = 'callback';
window[callback] = function(data) {
// Remove post script from the DOM
delete window[callback];
document.body.removeChild(script);
// Display response message
document.getElementById('js-subscribe-response').innerHTML = data.msg
};
});
}
})();
| Make sure the subscribe form is available before running the script | Make sure the subscribe form is available before running the script
| JavaScript | mit | michiel-vandewalle/Mailchimp-AJAX-form-submit-vanillaJS,michiel-vandewalle/Mailchimp-AJAX-form-submit-vanillaJS | ---
+++
@@ -7,37 +7,39 @@
*/
(function () {
- document.getElementsByTagName('form')[0].addEventListener('submit', function (e) {
- e.preventDefault();
+ if (document.getElementsByTagName('form').length > 0) {
+ document.getElementsByTagName('form')[0].addEventListener('submit', function (e) {
+ e.preventDefault();
- // Check for spam
- if(document.getElementById('js-validate-robot').value !== '') { return false }
+ // Check for spam
+ if(document.getElementById('js-validate-robot').value !== '') { return false }
- // Get url for mailchimp
- var url = this.action.replace('/post?', '/post-json?');
+ // Get url for mailchimp
+ var url = this.action.replace('/post?', '/post-json?');
- // Add form data to object
- var data = '';
- var inputs = this.querySelectorAll('#js-form-inputs input');
- for (var i = 0; i < inputs.length; i++) {
- data += '&' + inputs[i].name + '=' + encodeURIComponent(inputs[i].value);
- }
+ // Add form data to object
+ var data = '';
+ var inputs = this.querySelectorAll('#js-form-inputs input');
+ for (var i = 0; i < inputs.length; i++) {
+ data += '&' + inputs[i].name + '=' + encodeURIComponent(inputs[i].value);
+ }
- // Create & add post script to the DOM
- var script = document.createElement('script');
- script.src = url + data;
- document.body.appendChild(script);
+ // Create & add post script to the DOM
+ var script = document.createElement('script');
+ script.src = url + data;
+ document.body.appendChild(script);
- // Callback function
- var callback = 'callback';
- window[callback] = function(data) {
+ // Callback function
+ var callback = 'callback';
+ window[callback] = function(data) {
- // Remove post script from the DOM
- delete window[callback];
- document.body.removeChild(script);
+ // Remove post script from the DOM
+ delete window[callback];
+ document.body.removeChild(script);
- // Display response message
- document.getElementById('js-subscribe-response').innerHTML = data.msg
- };
- });
+ // Display response message
+ document.getElementById('js-subscribe-response').innerHTML = data.msg
+ };
+ });
+ }
})(); |
857435f7c5981286f2ac479661f5d60ad8360f45 | cli.js | cli.js | #!/usr/bin/env node
'use strict';
var npmMan = require('./');
var help = require('help-version')(usage()).help,
minimist = require('minimist'),
manPager = require('man-pager'),
defaultPager = require('default-pager');
function usage() {
return 'Usage: npm-man [--no-man] <package>';
}
var opts = minimist(process.argv.slice(2), {
boolean: 'man',
default: {
man: true
},
unknown: function (arg) {
if (arg[0] == '-') {
return help(1);
}
}
});
(function (opts, argv) {
if (argv.length != 1) {
return help(argv.length);
}
npmMan(argv[0], opts, function (err, man) {
if (err) return console.error(err);
manPager().end(man);
});
}(opts, opts._));
| #!/usr/bin/env node
'use strict';
var npmMan = require('./');
var help = require('help-version')(usage()).help,
minimist = require('minimist'),
manPager = require('man-pager'),
defaultPager = require('default-pager');
function usage() {
return 'Usage: npm-man [--no-man] <package>';
}
var opts = minimist(process.argv.slice(2), {
boolean: 'man',
default: {
man: true
},
unknown: function (arg) {
if (arg[0] == '-') {
return help(1);
}
}
});
(function (opts, argv) {
if (argv.length != 1) {
return help(argv.length);
}
var pager = opts.man ? manPager : defaultPager;
npmMan(argv[0], opts, function (err, man) {
if (err) return console.error(err);
pager().end(man);
});
}(opts, opts._));
| Use default pager for Markdown | Use default pager for Markdown
| JavaScript | mit | eush77/npm-man | ---
+++
@@ -32,8 +32,10 @@
return help(argv.length);
}
+ var pager = opts.man ? manPager : defaultPager;
+
npmMan(argv[0], opts, function (err, man) {
if (err) return console.error(err);
- manPager().end(man);
+ pager().end(man);
});
}(opts, opts._)); |
d659a3fb4492ebe6a782ada2407030fc47853487 | tests/integration/components/back-link-test.js | tests/integration/components/back-link-test.js | import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('back-link', 'Integration | Component | back link', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{back-link}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#back-link}}
template block text
{{/back-link}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
| import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('back-link', 'Integration | Component | back link', {
integration: true
});
test('it renders', function(assert) {
this.render(hbs`{{back-link}}`);
assert.equal(this.$().text().trim(), 'Back');
});
| Fix bad test for back-link helper | Fix bad test for back-link helper
| JavaScript | mit | ilios/common,ilios/common | ---
+++
@@ -6,20 +6,7 @@
});
test('it renders', function(assert) {
-
- // Set any properties with this.set('myProperty', 'value');
- // Handle any actions with this.on('myAction', function(val) { ... });
-
this.render(hbs`{{back-link}}`);
- assert.equal(this.$().text().trim(), '');
-
- // Template block usage:
- this.render(hbs`
- {{#back-link}}
- template block text
- {{/back-link}}
- `);
-
- assert.equal(this.$().text().trim(), 'template block text');
+ assert.equal(this.$().text().trim(), 'Back');
}); |
a45d5b16fe896c216622f429e0af95eb141f485b | web/src/main/ember/app/serializers/application.js | web/src/main/ember/app/serializers/application.js | import Ember from 'ember';
import DS from 'ember-data';
// Adapted from http://springember.blogspot.com.au/2014/08/using-ember-data-restadapter-with.html
export default DS.RESTSerializer.extend({
serializeIntoHash: function(hash, type, record, options) {
var serialized = this.serialize(record, options);
//Remove id from the payload for new records
//Jackson was complaining when it received a null or 'new' id ...
if (record.get('id') == null || record.get('isNew')) {
delete serialized.id;
}
//Remove null values
Object.keys(serialized).forEach(function(k) {
if (!serialized[k]) {
delete serialized[k];
}
});
//Remove the root element
Ember.merge(hash, serialized);
},
extractMeta: function (store, type, payload) {
// Read the meta information about objects that should be
// reloaded - purge them from the store to force reload
if (payload && payload.meta && payload.meta.purge) {
payload.meta.purge.forEach(function (p) {
var entity = store.getById(p.type, p.id);
if (!Ember.isNone(entity)) {
Ember.run.next(entity, "reload");
}
});
}
return this._super(store, type, payload);
}
});
| import Ember from 'ember';
import DS from 'ember-data';
// Adapted from http://springember.blogspot.com.au/2014/08/using-ember-data-restadapter-with.html
export default DS.RESTSerializer.extend({
serializeIntoHash: function(hash, type, record, options) {
var serialized = this.serialize(record, options);
//Remove id from the payload for new records
//Jackson was complaining when it received a null or 'new' id ...
if (record.get('id') == null || record.get('isNew')) {
delete serialized.id;
}
//Remove null values
Object.keys(serialized).forEach(function(k) {
if (serialized[k] === null) {
delete serialized[k];
}
});
//Remove the root element
Ember.merge(hash, serialized);
},
extractMeta: function (store, type, payload) {
// Read the meta information about objects that should be
// reloaded - purge them from the store to force reload
if (payload && payload.meta && payload.meta.purge) {
payload.meta.purge.forEach(function (p) {
var entity = store.getById(p.type, p.id);
if (!Ember.isNone(entity)) {
Ember.run.next(entity, "reload");
}
});
}
return this._super(store, type, payload);
}
});
| Fix serializer to keep 'false' values | Fix serializer to keep 'false' values
| JavaScript | agpl-3.0 | MarSik/shelves,MarSik/shelves,MarSik/shelves,MarSik/shelves | ---
+++
@@ -14,7 +14,7 @@
//Remove null values
Object.keys(serialized).forEach(function(k) {
- if (!serialized[k]) {
+ if (serialized[k] === null) {
delete serialized[k];
}
}); |
d44e463495dc2636253a747018eaafd447d652a6 | src/routes/index.js | src/routes/index.js | import React from 'react'
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import App from '../containers/App'
import Article from '../containers/Article'
import Blank from '../containers/Blank'
import Category from '../containers/Category'
import Home from '../containers/Home'
import Photography from '../containers/Photography'
import Search from '../containers/Search'
import Tag from '../containers/Tag'
import Topic from '../containers/Topic'
export default function (history = browserHistory) {
return (
<Router history={history} onUpdate={() => window.scrollTo(0, 0)}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="category/:category" component={Category}/>
<Route path="topic/:topicId" component={Topic} />
<Route path="tag/:tagId" component={Tag} />
<Route path="photography" component={Photography}/>
<Route path="search" component={Search}/>
<Route path="check" component={Blank}/>
<Route path="a/:slug" component={Article}/>
</Route>
</Router>
)
}
| import React from 'react'
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import App from '../containers/App'
import Article from '../containers/Article'
import Blank from '../containers/Blank'
import Category from '../containers/Category'
import Home from '../containers/Home'
import Photography from '../containers/Photography'
import Search from '../containers/Search'
import Tag from '../containers/Tag'
import Topic from '../containers/Topic'
import TopicLandingPage from '../containers/TopicLandingPage'
export default function (history = browserHistory) {
return (
<Router history={history} onUpdate={() => window.scrollTo(0, 0)}>
<Route path="/topics/:slug" component={TopicLandingPage} />
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="category/:category" component={Category}/>
<Route path="topic/:topicId" component={Topic} />
<Route path="tag/:tagId" component={Tag} />
<Route path="photography" component={Photography}/>
<Route path="search" component={Search}/>
<Route path="check" component={Blank}/>
<Route path="a/:slug" component={Article}/>
</Route>
</Router>
)
}
| Add Topic landing page route | [Add] Add Topic landing page route
| JavaScript | agpl-3.0 | garfieldduck/twreporter-react,twreporter/twreporter-react,nickhsine/twreporter-react,hanyulo/twreporter-react,garfieldduck/twreporter-react,hanyulo/twreporter-react | ---
+++
@@ -10,10 +10,12 @@
import Search from '../containers/Search'
import Tag from '../containers/Tag'
import Topic from '../containers/Topic'
+import TopicLandingPage from '../containers/TopicLandingPage'
export default function (history = browserHistory) {
return (
<Router history={history} onUpdate={() => window.scrollTo(0, 0)}>
+ <Route path="/topics/:slug" component={TopicLandingPage} />
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="category/:category" component={Category}/> |
9f4973cb9a688c1b611895472c7285b68aa90896 | src/sources/tlds.js | src/sources/tlds.js | 'use babel';
import fs from 'fs';
import readInTld from '../readInTld';
import {add as addToRegistry} from '../registry';
export function register() {
const userHome = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
let tldPathes = [];
// TODO: refresh on config change
atom.config.get('autocomplete-jsp.tldSources').forEach(dir => {
dir = dir.replace('~', userHome);
fs.readdirSync(dir)
.filter(fileName => fileName.endsWith('.tld'))
.forEach(fileName => {
const path = `${dir.replace(/\/$/, '')}/${fileName}`;
tldPathes.push(path);
});
});
// TODO: when a tld changes, we have to some how reload it..
Promise.all(tldPathes.map(readInTld))
.then(tldDescs => {
tldDescs.forEach(tldDesc => {
tldDesc.functions.forEach(fnDesc => {
addToRegistry({
element: fnDesc,
// TODO: not Infinity
liveTime: Infinity,
});
});
tldDesc.tags.forEach(tagDesc => {
addToRegistry({
element: tagDesc,
// TODO: not Infinity
liveTime: Infinity,
});
});
});
})
.catch(err => {
atom.notifications.addWarning(err.msg, {
dismissable: true,
detail: `Caused by:\n${err.causedBy}`,
});
});
}
| 'use babel';
import fs from 'fs';
import readInTld from '../readInTld';
import {add as addToRegistry} from '../registry';
export function register() {
const userHome = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
const tldSources = atom.config.get('autocomplete-jsp.tldSources');
// TODO: refresh on config change
Promise.all(tldSources
.map(path => path = path.replace('~', userHome))
.map(path => new Promise((resolve, reject) =>
fs.readdir(path, (err, fileNames) => {
if (err) {
return reject(err);
}
resolve(fileNames
.filter(name => name.endsWith('.tld'))
.map(name => `${path.replace(/\/$/, '')}/${name}`)
);
})
))
)
// TODO: reload on change
.then(result => Promise.all(result
.reduce((all, next) => all.concat(next), [])
.map(readInTld)
)
)
.then(tldDescs => tldDescs
.forEach(tldDesc => {
tldDesc.functions.forEach(fnDesc =>
addToRegistry({
element: fnDesc,
liveTime: Infinity,
})
);
tldDesc.tags.forEach(tagDesc =>
addToRegistry({
element: tagDesc,
liveTime: Infinity,
})
);
})
)
.catch(err =>
atom.notifications.addWarning(err.msg, {
dismissable: true,
detail: `Caused by:\n${err.causedBy}`,
})
);
}
| Load tld files completely async | Load tld files completely async
| JavaScript | mit | MoritzKn/atom-autocomplete-jsp | ---
+++
@@ -6,46 +6,53 @@
export function register() {
- const userHome = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
+ const userHome = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
+ const tldSources = atom.config.get('autocomplete-jsp.tldSources');
- let tldPathes = [];
// TODO: refresh on config change
- atom.config.get('autocomplete-jsp.tldSources').forEach(dir => {
- dir = dir.replace('~', userHome);
+ Promise.all(tldSources
+ .map(path => path = path.replace('~', userHome))
+ .map(path => new Promise((resolve, reject) =>
+ fs.readdir(path, (err, fileNames) => {
+ if (err) {
+ return reject(err);
+ }
- fs.readdirSync(dir)
- .filter(fileName => fileName.endsWith('.tld'))
- .forEach(fileName => {
- const path = `${dir.replace(/\/$/, '')}/${fileName}`;
- tldPathes.push(path);
- });
- });
- // TODO: when a tld changes, we have to some how reload it..
- Promise.all(tldPathes.map(readInTld))
- .then(tldDescs => {
- tldDescs.forEach(tldDesc => {
- tldDesc.functions.forEach(fnDesc => {
+ resolve(fileNames
+ .filter(name => name.endsWith('.tld'))
+ .map(name => `${path.replace(/\/$/, '')}/${name}`)
+ );
+ })
+ ))
+ )
+ // TODO: reload on change
+ .then(result => Promise.all(result
+ .reduce((all, next) => all.concat(next), [])
+ .map(readInTld)
+ )
+ )
+ .then(tldDescs => tldDescs
+ .forEach(tldDesc => {
+ tldDesc.functions.forEach(fnDesc =>
addToRegistry({
element: fnDesc,
- // TODO: not Infinity
liveTime: Infinity,
- });
- });
+ })
+ );
- tldDesc.tags.forEach(tagDesc => {
+ tldDesc.tags.forEach(tagDesc =>
addToRegistry({
element: tagDesc,
- // TODO: not Infinity
liveTime: Infinity,
- });
- });
- });
- })
- .catch(err => {
+ })
+ );
+ })
+ )
+ .catch(err =>
atom.notifications.addWarning(err.msg, {
dismissable: true,
detail: `Caused by:\n${err.causedBy}`,
- });
- });
+ })
+ );
} |
1d4203d51cea5ebc090bec9772e03ad89a892127 | vendor/assets/javascripts/vis.js | vendor/assets/javascripts/vis.js | //= require ../vis/module/header
//= require moment
//= require hammer
//= require ../component/emitter
//= require ../vis/shim
//= require ../vis/util
//= require ../vis/DataSet
//= require ../vis/DataView
//= require ../vis/timeline/stack
//= require ../vis/timeline/TimeStep
//= require ../vis/timeline/component/Component
//= require ../vis/timeline/Range
//= require ../vis/timeline/component/TimeAxis
//= require ../vis/timeline/component/CurrentTime
//= require ../vis/timeline/component/CustomTime
//= require_tree ../vis/timeline/component/item
//= require ../vis/timeline/component/ItemSet
//= require ../vis/timeline/component/Group
//= require ../vis/timeline/Timeline
//= require ../vis/graph/dotparser
//= require ../vis/graph/shapes
//= require ../vis/graph/Node
//= require ../vis/graph/Edge
//= require ../vis/graph/Popup
//= require ../vis/graph/Groups
//= require ../vis/graph/Images
//= require_tree ../vis/graph/graphMixins
//= require ../vis/graph/Graph
//= require ../vis/graph3d/Graph3d
//= require ../vis/module/exports
| //= require_relative ../vis/module/header
//= require moment
//= require hammer
//= require_relative ../component/emitter
//= require_relative ../vis/shim
//= require_relative ../vis/util
//= require_relative ../vis/DataSet
//= require_relative ../vis/DataView
//= require_relative ../vis/timeline/stack
//= require_relative ../vis/timeline/TimeStep
//= require_relative ../vis/timeline/component/Component
//= require_relative ../vis/timeline/Range
//= require_relative ../vis/timeline/component/TimeAxis
//= require_relative ../vis/timeline/component/CurrentTime
//= require_relative ../vis/timeline/component/CustomTime
//= require_tree ../vis/timeline/component/item
//= require_relative ../vis/timeline/component/ItemSet
//= require_relative ../vis/timeline/component/Group
//= require_relative ../vis/timeline/Timeline
//= require_relative ../vis/graph/dotparser
//= require_relative ../vis/graph/shapes
//= require_relative ../vis/graph/Node
//= require_relative ../vis/graph/Edge
//= require_relative ../vis/graph/Popup
//= require_relative ../vis/graph/Groups
//= require_relative ../vis/graph/Images
//= require_tree ../vis/graph/graphMixins
//= require_relative ../vis/graph/Graph
//= require_relative ../vis/graph3d/Graph3d
//= require_relative ../vis/module/exports
| Add require_relative to work with Rails 4.1.5 | Add require_relative to work with Rails 4.1.5
| JavaScript | apache-2.0 | AlexVangelov/vis-rails,mariowise/vis-rails | ---
+++
@@ -1,35 +1,35 @@
-//= require ../vis/module/header
+//= require_relative ../vis/module/header
//= require moment
//= require hammer
-//= require ../component/emitter
+//= require_relative ../component/emitter
-//= require ../vis/shim
-//= require ../vis/util
-//= require ../vis/DataSet
-//= require ../vis/DataView
+//= require_relative ../vis/shim
+//= require_relative ../vis/util
+//= require_relative ../vis/DataSet
+//= require_relative ../vis/DataView
-//= require ../vis/timeline/stack
-//= require ../vis/timeline/TimeStep
-//= require ../vis/timeline/component/Component
-//= require ../vis/timeline/Range
-//= require ../vis/timeline/component/TimeAxis
-//= require ../vis/timeline/component/CurrentTime
-//= require ../vis/timeline/component/CustomTime
+//= require_relative ../vis/timeline/stack
+//= require_relative ../vis/timeline/TimeStep
+//= require_relative ../vis/timeline/component/Component
+//= require_relative ../vis/timeline/Range
+//= require_relative ../vis/timeline/component/TimeAxis
+//= require_relative ../vis/timeline/component/CurrentTime
+//= require_relative ../vis/timeline/component/CustomTime
//= require_tree ../vis/timeline/component/item
-//= require ../vis/timeline/component/ItemSet
-//= require ../vis/timeline/component/Group
-//= require ../vis/timeline/Timeline
+//= require_relative ../vis/timeline/component/ItemSet
+//= require_relative ../vis/timeline/component/Group
+//= require_relative ../vis/timeline/Timeline
-//= require ../vis/graph/dotparser
-//= require ../vis/graph/shapes
-//= require ../vis/graph/Node
-//= require ../vis/graph/Edge
-//= require ../vis/graph/Popup
-//= require ../vis/graph/Groups
-//= require ../vis/graph/Images
+//= require_relative ../vis/graph/dotparser
+//= require_relative ../vis/graph/shapes
+//= require_relative ../vis/graph/Node
+//= require_relative ../vis/graph/Edge
+//= require_relative ../vis/graph/Popup
+//= require_relative ../vis/graph/Groups
+//= require_relative ../vis/graph/Images
//= require_tree ../vis/graph/graphMixins
-//= require ../vis/graph/Graph
+//= require_relative ../vis/graph/Graph
-//= require ../vis/graph3d/Graph3d
+//= require_relative ../vis/graph3d/Graph3d
-//= require ../vis/module/exports
+//= require_relative ../vis/module/exports |
1f5a5d92290005b2301e41f0e7fe69e24569b489 | vendor/leaflet.div-control.js | vendor/leaflet.div-control.js | L.Control.Div = L.Control.extend({
initialize(element, options) {
L.Control.prototype.initialize.call(this, options);
this._container = element || L.DomUtil.create('div', '');
if(this.options.disableClickPropagation) {
L.DomEvent.disableClickPropagation(this._container);
}
if(this.options.disableScrollPropagation) {
L.DomEvent.disableScrollPropagation(this._container);
}
},
onAdd: function (map) {
return this._container;
},
appendContent(domElement) {
this._container.appendChild(domElement);
}
});
| L.Control.Div = L.Control.extend({
initialize: function(element, options) {
L.Control.prototype.initialize.call(this, options);
this._container = element || L.DomUtil.create('div', '');
if(this.options.disableClickPropagation) {
L.DomEvent.disableClickPropagation(this._container);
}
if(this.options.disableScrollPropagation) {
L.DomEvent.disableScrollPropagation(this._container);
}
},
onAdd: function (map) {
return this._container;
},
appendContent: function(domElement) {
this._container.appendChild(domElement);
}
});
| Fix travis hang on vendor file, change es6 to es5 style | Fix travis hang on vendor file, change es6 to es5 style
| JavaScript | mit | Flexberry/ember-flexberry-gis,Flexberry/ember-flexberry-gis,Flexberry/ember-flexberry-gis | ---
+++
@@ -1,5 +1,5 @@
L.Control.Div = L.Control.extend({
- initialize(element, options) {
+ initialize: function(element, options) {
L.Control.prototype.initialize.call(this, options);
this._container = element || L.DomUtil.create('div', '');
@@ -16,7 +16,7 @@
return this._container;
},
- appendContent(domElement) {
+ appendContent: function(domElement) {
this._container.appendChild(domElement);
}
}); |
7a9a992ed7ea73f67a31944035dc8e7a5779d3f4 | src/http/action-http.js | src/http/action-http.js | import * as actionCore from '../core/action-core';
import {createJsonRoute, throwStatus} from '../util/express';
import {assert} from '../validation';
import * as imageHttp from './image-http';
import * as throttleCore from '../core/throttle-core';
let postAction = createJsonRoute(function(req, res) {
const action = assert(req.body, 'action');
if (!throttleCore.canDoAction(action.user, action.type)) {
throwStatus(429, `Too many actions of type ${ action.type }`);
}
let handleAction;
if (action.type === 'IMAGE') {
handleAction = imageHttp.postImage(req, res, action);
} else {
action.ip = req.ip;
handleAction = actionCore.getActionType(action.type)
.then(type => {
if (type === null) {
throwStatus(400, 'Action type ' + action.type + ' does not exist');
}
})
.then(() => {
return actionCore.createAction(action).then(rowsInserted => undefined);
});
}
return handleAction
.then(() => throttleCore.executeAction(action.user, action.type));
});
export {
postAction
};
| import * as actionCore from '../core/action-core';
import {createJsonRoute, throwStatus} from '../util/express';
import {assert} from '../validation';
import * as banCore from '../core/ban-core';
import * as imageHttp from './image-http';
import * as throttleCore from '../core/throttle-core';
let postAction = createJsonRoute(function(req, res) {
const action = assert(req.body, 'action');
if (!throttleCore.canDoAction(action.user, action.type)) {
throwStatus(429, `Too many actions of type ${ action.type }`);
} else if (banCore.isUserBanned(action.user)) {
banCore.throwBannedError();
}
let handleAction;
if (action.type === 'IMAGE') {
handleAction = imageHttp.postImage(req, res, action);
} else {
action.ip = req.ip;
handleAction = actionCore.getActionType(action.type)
.then(type => {
if (type === null) {
throwStatus(400, 'Action type ' + action.type + ' does not exist');
}
})
.then(() => {
return actionCore.createAction(action).then(rowsInserted => undefined);
});
}
return handleAction
.then(() => throttleCore.executeAction(action.user, action.type));
});
export {
postAction
};
| Check if user is banned in /actions API | Check if user is banned in /actions API
| JavaScript | mit | futurice/wappuapp-backend,futurice/wappuapp-backend,kaupunki-apina/prahapp-backend,kaupunki-apina/prahapp-backend | ---
+++
@@ -1,6 +1,7 @@
import * as actionCore from '../core/action-core';
import {createJsonRoute, throwStatus} from '../util/express';
import {assert} from '../validation';
+import * as banCore from '../core/ban-core';
import * as imageHttp from './image-http';
import * as throttleCore from '../core/throttle-core';
@@ -9,6 +10,8 @@
if (!throttleCore.canDoAction(action.user, action.type)) {
throwStatus(429, `Too many actions of type ${ action.type }`);
+ } else if (banCore.isUserBanned(action.user)) {
+ banCore.throwBannedError();
}
let handleAction; |
c8679aa22383c8966844788d6af1b8c0e232fd91 | gpm-dlv/js/main.js | gpm-dlv/js/main.js | (function() {
var element = null;
var nav_elements = document.querySelectorAll('.nav-item-container');
for (var i = 0; i < nav_elements.length; i++) {
var current = nav_elements[i];
if (current.innerHTML == 'My Library') {
element = current;
break;
}
}
if (element != null) {
chrome.storage.sync.get({'gpmDefaultLibraryView': 'albums'}, function(item) {
element.setAttribute('data-type', item.gpmDefaultLibraryView);
});
} else {
console.error('No element found; did Google change the page?');
}
})();
| (function() {
function findTarget(element) {
if (element.nodeType === 1) {
var candidates = element.querySelectorAll('.nav-item-container');
for (var i = 0; i < candidates.length; i++) {
if (candidates[i].textContent == 'My Library') {
return candidates[i];
}
}
}
}
function modifyTarget(element) {
chrome.storage.sync.get({'gpmDefaultLibraryView': 'albums'}, function(item) {
element.setAttribute('data-type', item.gpmDefaultLibraryView);
});
}
var observer = new MutationObserver(function(mutations, observer) {
mutations.forEach(function(mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++) {
var element = findTarget(mutation.addedNodes[i]);
if (element) {
modifyTarget(element);
observer.disconnect();
}
}
});
});
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
})();
| Handle dynamic insertion of page elements | Handle dynamic insertion of page elements
| JavaScript | mit | bluekeyes/gpm-dlv,bluekeyes/gpm-dlv | ---
+++
@@ -1,20 +1,38 @@
(function() {
- var element = null;
- var nav_elements = document.querySelectorAll('.nav-item-container');
- for (var i = 0; i < nav_elements.length; i++) {
- var current = nav_elements[i];
- if (current.innerHTML == 'My Library') {
- element = current;
- break;
+ function findTarget(element) {
+ if (element.nodeType === 1) {
+ var candidates = element.querySelectorAll('.nav-item-container');
+ for (var i = 0; i < candidates.length; i++) {
+ if (candidates[i].textContent == 'My Library') {
+ return candidates[i];
+ }
+ }
}
}
- if (element != null) {
+ function modifyTarget(element) {
chrome.storage.sync.get({'gpmDefaultLibraryView': 'albums'}, function(item) {
element.setAttribute('data-type', item.gpmDefaultLibraryView);
});
- } else {
- console.error('No element found; did Google change the page?');
}
+
+ var observer = new MutationObserver(function(mutations, observer) {
+ mutations.forEach(function(mutation) {
+ for (var i = 0; i < mutation.addedNodes.length; i++) {
+ var element = findTarget(mutation.addedNodes[i]);
+ if (element) {
+ modifyTarget(element);
+ observer.disconnect();
+ }
+ }
+ });
+ });
+ observer.observe(document.body, {
+ childList: true,
+ subtree: true,
+ attributes: false,
+ characterData: false
+ });
+
})(); |
c40900b5793ae62b3b6747f5c4f95e077acc636f | app/scripts/app/utils/parse-fields-metadata.js | app/scripts/app/utils/parse-fields-metadata.js | function parseFields (payload) {
if (Array.isArray(payload)) {
payload.forEach(parseFields);
return;
}
if (typeof payload === 'object' && payload.hasOwnProperty('fields')) {
payload.fields = JSON.parse(payload.fields);
}
}
export default parseFields;
| var fields = ['fields', 'date'];
function parseFields (payload) {
var i;
if (Array.isArray(payload)) {
payload.forEach(parseFields);
return;
}
if (typeof payload !== 'object') {
return;
}
for (i = 0; i !== fields.length; ++i) {
if (payload.hasOwnProperty(fields[i])) {
if (fields[i] === 'date') {
payload[fields[i]] = new Date(payload[fields[i]]);
} else {
payload[fields[i]] = JSON.parse(payload[fields[i]]);
}
}
}
}
export default parseFields;
| Update parseFields to handle `date` property | Update parseFields to handle `date` property
| JavaScript | mit | darvelo/wishlist,darvelo/wishlist | ---
+++
@@ -1,11 +1,25 @@
+var fields = ['fields', 'date'];
+
function parseFields (payload) {
+ var i;
+
if (Array.isArray(payload)) {
payload.forEach(parseFields);
return;
}
- if (typeof payload === 'object' && payload.hasOwnProperty('fields')) {
- payload.fields = JSON.parse(payload.fields);
+ if (typeof payload !== 'object') {
+ return;
+ }
+
+ for (i = 0; i !== fields.length; ++i) {
+ if (payload.hasOwnProperty(fields[i])) {
+ if (fields[i] === 'date') {
+ payload[fields[i]] = new Date(payload[fields[i]]);
+ } else {
+ payload[fields[i]] = JSON.parse(payload[fields[i]]);
+ }
+ }
}
}
|
41eb7a6919ea9693543ce10fd4dd40e6553a1d0a | app/assets/javascripts/components/ClearInput.js | app/assets/javascripts/components/ClearInput.js | define(['jquery', 'DoughBaseComponent'], function($, DoughBaseComponent) {
'use strict';
var ClearInput,
uiEvents = {
'keydown [data-dough-clear-input]' : 'updateResetButton',
'click [data-dough-clear-input-button]' : 'resetForm'
};
ClearInput = function($el, config) {
this.uiEvents = uiEvents;
ClearInput.baseConstructor.call(this, $el, config);
this.$resetInput = this.$el.find('[data-dough-clear-input]');
this.$resetButton = this.$el.find('[data-dough-clear-input-button]');
};
/**
* Inherit from base module, for shared methods and interface
*/
DoughBaseComponent.extend(ClearInput);
/**
* Set up and populate the model from the form inputs
* @param {Promise} initialised
*/
ClearInput.prototype.init = function(initialised) {
this._initialisedSuccess(initialised);
};
ClearInput.prototype.updateResetButton = function() {
var fn = this.$resetInput.val() === '' ? 'removeClass' : 'addClass';
this.$resetButton[fn]('is-active');
};
// We are progressively enhancing the form with JS. The CSS button, type 'reset'
// resets the form faster than the JS can run, so we need to invoke reset() to ensure the correct behaviour.
ClearInput.prototype.resetForm = function() {
this.$el[0].reset();
this.updateResetButton();
};
return ClearInput;
});
| define(['jquery', 'DoughBaseComponent'], function($, DoughBaseComponent) {
'use strict';
var ClearInput,
uiEvents = {
'keydown [data-dough-clear-input]' : 'updateResetButton',
'click [data-dough-clear-input-button]' : 'resetForm'
};
ClearInput = function($el, config) {
this.uiEvents = uiEvents;
ClearInput.baseConstructor.call(this, $el, config);
this.$resetInput = this.$el.find('[data-dough-clear-input]');
this.$resetButton = this.$el.find('[data-dough-clear-input-button]');
this.updateResetButton();
};
/**
* Inherit from base module, for shared methods and interface
*/
DoughBaseComponent.extend(ClearInput);
/**
* Set up and populate the model from the form inputs
* @param {Promise} initialised
*/
ClearInput.prototype.init = function(initialised) {
this._initialisedSuccess(initialised);
};
ClearInput.prototype.updateResetButton = function() {
var fn = this.$resetInput.val() === '' ? 'removeClass' : 'addClass';
this.$resetButton[fn]('is-active');
};
// We are progressively enhancing the form with JS. The CSS button, type 'reset'
// resets the form faster than the JS can run, so we need to invoke reset() to ensure the correct behaviour.
ClearInput.prototype.resetForm = function(e) {
this.$resetInput.val('');
this.updateResetButton();
this.$resetInput.focus();
e.preventDefault();
};
return ClearInput;
});
| Fix search box with initial value after search | Fix search box with initial value after search
| JavaScript | mit | moneyadviceservice/frontend,moneyadviceservice/frontend,moneyadviceservice/frontend,moneyadviceservice/frontend | ---
+++
@@ -14,6 +14,8 @@
this.$resetInput = this.$el.find('[data-dough-clear-input]');
this.$resetButton = this.$el.find('[data-dough-clear-input-button]');
+
+ this.updateResetButton();
};
/**
@@ -37,9 +39,11 @@
// We are progressively enhancing the form with JS. The CSS button, type 'reset'
// resets the form faster than the JS can run, so we need to invoke reset() to ensure the correct behaviour.
- ClearInput.prototype.resetForm = function() {
- this.$el[0].reset();
+ ClearInput.prototype.resetForm = function(e) {
+ this.$resetInput.val('');
this.updateResetButton();
+ this.$resetInput.focus();
+ e.preventDefault();
};
return ClearInput; |
194e348fa2691a12e8360cadae714b971b77df97 | test/stream.spec.js | test/stream.spec.js | "use strict";
let chai = require('chai');
let expect = chai.expect;
let Stream = require('../src/stream');
describe('Stream', () => {
describe('#constructor', () => {
it('returns an instanceof stream', () => {
let stream = new Stream.default("123");
expect(stream).to.be.an.instanceof(Stream.default);
});
it('can get the current value', () => {
let stream = new Stream.default("123");
expect(stream.current()).to.eql("1");
});
it('can move the position forward', () => {
let stream = new Stream.default("123");
stream.forward();
expect(stream.current()).to.eql('2');
});
it('can stream until condition is met', () => {
let stream = new Stream.default("A stream of things");
let segment = stream.until(character => (character === 'o'));
expect(segment).to.eql('A stream ');
});
it('can move backwards in the stream', () => {
let stream = new Stream.default("123");
let segment = stream.until(character => (character === '3'));
expect(segment).to.eql('12');
stream.backward();
expect(stream.current()).to.eql('2');
});
});
});
| "use strict";
let chai = require('chai');
let expect = chai.expect;
let Stream = require('../src/stream');
describe('Stream', () => {
describe('#constructor', () => {
it('returns an instanceof stream', () => {
let stream = new Stream.default("123");
expect(stream).to.be.an.instanceof(Stream.default);
});
it('can get the current value', () => {
let stream = new Stream.default("123");
expect(stream.current()).to.eql("1");
});
it('can move the position forward', () => {
let stream = new Stream.default("123");
stream.forward();
expect(stream.current()).to.eql('2');
});
it('can stream until condition is met', () => {
let stream = new Stream.default("A stream of things");
let segment = stream.until(character => (character === 'o'));
expect(segment).to.eql('A stream ');
});
it('can move backwards in the stream', () => {
let stream = new Stream.default("123");
let segment = stream.until(character => (character === '3'));
expect(segment).to.eql('12');
stream.backward();
expect(stream.current()).to.eql('2');
});
it('will fail', () => {
let stream = new Stream.default("123");
let segment = stream.until(character => (character === '3'));
expect(segment).to.eql('12');
stream.backward();
expect(stream.current()).to.eql('1');
});
});
});
| Test what happens in dockerhub when a node test fails | Test what happens in dockerhub when a node test fails
Signed-off-by: Tobias Sjöndin <04a8cd48feee91827ce7c6d1356384bcca091996@op5.com>
| JavaScript | mit | tsjondin/cody,tsjondin/cody | ---
+++
@@ -38,5 +38,13 @@
expect(stream.current()).to.eql('2');
});
+ it('will fail', () => {
+ let stream = new Stream.default("123");
+ let segment = stream.until(character => (character === '3'));
+ expect(segment).to.eql('12');
+ stream.backward();
+ expect(stream.current()).to.eql('1');
+ });
+
});
}); |
a448207928f130cd13a0a109138b0ff0b93d84c4 | test/utils/index.js | test/utils/index.js | 'use strict'
let cp = require('child_process'),
fs = require('fs'),
started = false
module.exports.start = function (done) {
if (started) {
return done()
}
// Fork server
fs.copyFileSync('node_modules/log-sink-server/example-config.js', 'node_modules/log-sink-server/config.js')
let children = cp.fork('.', ['--test-mode'], {
cwd: 'node_modules/log-sink-server'
})
children.on('message', data => {
if (data === 'online') {
started = true
return done()
}
})
} | 'use strict'
let cp = require('child_process'),
fs = require('fs'),
started = false
module.exports.start = function (done) {
if (started) {
return done()
}
fs.writeFileSync(
'node_modules/log-sink-server/config.js',
fs.readFileSync('node_modules/log-sink-server/example-config.js')
)
// Fork server
let children = cp.fork('.', ['--test-mode'], {
cwd: 'node_modules/log-sink-server'
})
children.on('message', data => {
if (data === 'online') {
started = true
return done()
}
})
} | Remove copyFileSync call from test | Remove copyFileSync call from test
| JavaScript | mit | clubedaentrega/log-sink | ---
+++
@@ -9,8 +9,12 @@
return done()
}
+ fs.writeFileSync(
+ 'node_modules/log-sink-server/config.js',
+ fs.readFileSync('node_modules/log-sink-server/example-config.js')
+ )
+
// Fork server
- fs.copyFileSync('node_modules/log-sink-server/example-config.js', 'node_modules/log-sink-server/config.js')
let children = cp.fork('.', ['--test-mode'], {
cwd: 'node_modules/log-sink-server'
}) |
86a91b9727883cbd9635ca6e48c48661548c98ef | app/facebook/facebook.js | app/facebook/facebook.js | 'use strict';
angular.module('ngSocial.facebook', ['ngRoute','ngFacebook'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/facebook', {
templateUrl: 'facebook/facebook.html',
controller: 'FacebookCtrl'
});
}])
.config( function( $facebookProvider ) {
$facebookProvider.setAppId('450853485276464');
$facebookProvider.setPermissions("email","public_profile","user_posts","publish_actions","user_photos");
})
.run( function( $rootScope ) {
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
})
.controller('FacebookCtrl', ['$scope', '$facebook', function($scope,$facebook) {
$scope.isLoggedIn = false;
$scope.login = function(){
$facebook.login().then(function(){
console.log('Logged in...');
});
}
}]); | 'use strict';
angular.module('ngSocial.facebook', ['ngRoute','ngFacebook'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/facebook', {
templateUrl: 'facebook/facebook.html',
controller: 'FacebookCtrl'
});
}])
.config( function( $facebookProvider ) {
$facebookProvider.setAppId('450853485276464');
$facebookProvider.setPermissions("email","public_profile","user_posts","publish_actions","user_photos");
})
.run( function( $rootScope ) {
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
})
.controller('FacebookCtrl', ['$scope', '$facebook', function($scope,$facebook) {
console.log('hello!');
$scope.isLoggedIn = false;
$scope.login = function(){
$facebook.login().then(function(){
console.log('Logged in...');
});
}
}]); | Add Facebook login test 2 | Add Facebook login test 2
| JavaScript | mit | PohrebniakOleskandr/ng-facebook-app,PohrebniakOleskandr/ng-facebook-app | ---
+++
@@ -26,6 +26,7 @@
.controller('FacebookCtrl', ['$scope', '$facebook', function($scope,$facebook) {
+ console.log('hello!');
$scope.isLoggedIn = false;
$scope.login = function(){
$facebook.login().then(function(){ |
1591d0f60a8db1ba924959ec5aa6891fd3b74aa5 | app/assets/javascripts/solidus_subscription_boxes/subscription_selection.js | app/assets/javascripts/solidus_subscription_boxes/subscription_selection.js | // Meal Selection Page
$('.meal-selection').click( function(event) {
if( $('.meal-selection input:checked').length > 3) {
alert("Please only pick 3 feals");
event.target.checked = false;
event.preventDefault();
}
if( $('.meal-selection input:checked').length == 3) {
$('input[type=submit]').removeAttr('disabled');
$('input[type=submit]').attr("value","Subscribe Now");
} else {
$('input[type=submit]').attr("disabled","disabled");
$('input[type=submit]').attr("value","Choose " + (3 - $('.meal-selection input:checked').length).toString() + " More");
}
$('.number_more_meals').text(3 - $('.meal-selection input:checked').length);
});
| // Meal Selection Page
$('.meal-selection').click( function(event) {
if( $('.meal-selection input:checked').length > 3) {
alert("Please only pick 3 meals");
event.target.checked = false;
event.preventDefault();
}
if( $('.meal-selection input:checked').length == 3) {
$('input[type=submit]').removeAttr('disabled');
$('input[type=submit]').attr("value","Subscribe Now");
} else {
$('input[type=submit]').attr("disabled","disabled");
$('input[type=submit]').attr("value","Choose " + (3 - $('.meal-selection input:checked').length).toString() + " More");
}
$('.number_more_meals').text(3 - $('.meal-selection input:checked').length);
});
| Change the word "feals" to "meals" in error messaging. | Change the word "feals" to "meals" in error messaging.
| JavaScript | bsd-3-clause | joeljackson/solidus_subscription_boxes,joeljackson/solidus_subscription_boxes,joeljackson/solidus_subscription_boxes | ---
+++
@@ -1,7 +1,7 @@
// Meal Selection Page
$('.meal-selection').click( function(event) {
if( $('.meal-selection input:checked').length > 3) {
- alert("Please only pick 3 feals");
+ alert("Please only pick 3 meals");
event.target.checked = false;
event.preventDefault();
} |
b50067997bf1c1bb78b078b4333f199baf9f42b4 | app/assets/javascripts/cancel_appointment.js | app/assets/javascripts/cancel_appointment.js | var cancelAppointment = function(timeslot_id) {
$("#modal_remote").modal('hide');
swal({
title: "Are you sure?",
text: "You will be removed from this appointment.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, cancel my appointment.",
cancelButtonText: "No, I don't want to cancel.",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
$.ajax({
type: "PATCH",
url: "/api/timeslots/" + timeslot_id + "/cancel",
beforeSend: customBlockUi(this)
}).done(function(){
swal({
title: "Cancelled",
text: "Your mentoring appointment has been cancelled.",
confirmButtonColor: "#66BB6A",
type: "info"
});
$('#tutor-cal').fullCalendar('refetchEvents');
}).fail(function() {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
}
else {
swal({
title: "Never Mind!",
text: "Your Appointment is still on!",
confirmButtonColor: "#2196F3",
type: "error"
});
}
});
}
| var cancelAppointment = function(timeslot_id) {
$("#modal_remote").modal('hide');
swal({
title: "Are you sure?",
text: "You will be removed from this appointment.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, cancel my appointment.",
cancelButtonText: "No, I don't want to cancel.",
closeOnConfirm: false,
closeOnCancel: true
},
function(isConfirm){
if (isConfirm) {
$.ajax({
type: "PATCH",
url: "/api/timeslots/" + timeslot_id + "/cancel",
beforeSend: customBlockUi(this)
}).done(function(){
swal({
title: "Cancelled",
text: "Your mentoring appointment has been cancelled.",
confirmButtonColor: "#FFFFFF",
showConfirmButton: false,
allowOutsideClick: true,
timer: 1500,
type: "info"
});
$('#tutor-cal').fullCalendar('refetchEvents');
}).fail(function() {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
}
});
}
| Hide button, enable timer for swal, note confirm color is white swal doesn't completely hide the button | Hide button, enable timer for swal, note confirm color is white swal doesn't completely hide the button
| JavaScript | mit | theresaboard/theres-a-board,theresaboard/theres-a-board,theresaboard/theres-a-board | ---
+++
@@ -9,7 +9,7 @@
confirmButtonText: "Yes, cancel my appointment.",
cancelButtonText: "No, I don't want to cancel.",
closeOnConfirm: false,
- closeOnCancel: false
+ closeOnCancel: true
},
function(isConfirm){
if (isConfirm) {
@@ -21,7 +21,10 @@
swal({
title: "Cancelled",
text: "Your mentoring appointment has been cancelled.",
- confirmButtonColor: "#66BB6A",
+ confirmButtonColor: "#FFFFFF",
+ showConfirmButton: false,
+ allowOutsideClick: true,
+ timer: 1500,
type: "info"
});
$('#tutor-cal').fullCalendar('refetchEvents');
@@ -34,14 +37,6 @@
});
});
}
- else {
- swal({
- title: "Never Mind!",
- text: "Your Appointment is still on!",
- confirmButtonColor: "#2196F3",
- type: "error"
- });
- }
});
}
|
8f9737a551807974a261c4afa1a1c48f0eedf2a3 | app/assets/javascripts/helpers/prop_types.js | app/assets/javascripts/helpers/prop_types.js | (function() {
window.shared || (window.shared = {});
// Allow a prop to be null, if the prop type explicitly allows this.
// Then fall back to another validator if a value is passed.
var nullable = function(validator) {
return function(props, propName, componentName) {
if (props[propName] === null) return null;
return validator(props, propName, componentName);
};
};
var PropTypes = window.shared.PropTypes = {
nullable: nullable,
// UI actions, stepping stone to Flux
actions: React.PropTypes.shape({
onColumnClicked: React.PropTypes.func.isRequired,
onClickSaveNotes: React.PropTypes.func.isRequired,
onClickSaveService: React.PropTypes.func.isRequired,
onClickDiscontinueService: React.PropTypes.func.isRequired
}),
requests: React.PropTypes.shape({
saveNotes: nullable(React.PropTypes.string).isRequired
}),
api: React.PropTypes.shape({
saveNotes: React.PropTypes.func.isRequired
}),
// The feed of all notes and data entered in Student Insights for
// a student.
feed: React.PropTypes.shape({
event_notes: React.PropTypes.array.isRequired,
services: React.PropTypes.shape({
active: React.PropTypes.array.isRequired,
discontinued: React.PropTypes.array.isRequired
}),
deprecated: React.PropTypes.shape({
notes: React.PropTypes.array.isRequired,
interventions: React.PropTypes.array.isRequired
})
})
};
})(); | (function() {
window.shared || (window.shared = {});
// Allow a prop to be null, if the prop type explicitly allows this.
// Then fall back to another validator if a value is passed.
var nullable = function(validator) {
return function(props, propName, componentName) {
if (props[propName] === null) return null;
return validator(props, propName, componentName);
};
};
var PropTypes = window.shared.PropTypes = {
nullable: nullable,
// UI actions, stepping stone to Flux
actions: React.PropTypes.shape({
onColumnClicked: React.PropTypes.func.isRequired,
onClickSaveNotes: React.PropTypes.func.isRequired,
onClickSaveService: React.PropTypes.func.isRequired,
onClickDiscontinueService: React.PropTypes.func.isRequired
}),
requests: React.PropTypes.shape({
saveNotes: nullable(React.PropTypes.string).isRequired
}),
api: React.PropTypes.shape({
saveNotes: React.PropTypes.func.isRequired
}),
// The feed of all notes and data entered in Student Insights for
// a student.
feed: React.PropTypes.shape({
event_notes: React.PropTypes.array.isRequired,
services: React.PropTypes.shape({
active: React.PropTypes.array.isRequired,
discontinued: React.PropTypes.array.isRequired
}),
deprecated: React.PropTypes.shape({
interventions: React.PropTypes.array.isRequired
})
})
};
})();
| Remove deprecated notes from PropTypes helper | Remove deprecated notes from PropTypes helper
| JavaScript | mit | erose/studentinsights,erose/studentinsights,jhilde/studentinsights,studentinsights/studentinsights,jhilde/studentinsights,studentinsights/studentinsights,erose/studentinsights,studentinsights/studentinsights,studentinsights/studentinsights,jhilde/studentinsights,jhilde/studentinsights,erose/studentinsights | ---
+++
@@ -36,7 +36,6 @@
discontinued: React.PropTypes.array.isRequired
}),
deprecated: React.PropTypes.shape({
- notes: React.PropTypes.array.isRequired,
interventions: React.PropTypes.array.isRequired
})
}) |
7fa187cc34d53cfda7189d95cda2e0970a9c8d11 | bugminer-server/src/main/frontend/app/js/app.js | bugminer-server/src/main/frontend/app/js/app.js | (function(angular) {
'use strict';
var app = angular.module('bugminerApp', ['ngResource', 'ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/projects/index.html',
controller: 'ProjectsCtrl'
})
.when('/projects/:name/bugs', {
templateUrl: 'partials/projects/bugs.html',
controller: 'ProjectBugsCtrl'
});
}]);
app.factory('Project', function($resource) {
return $resource("/api/projects/:name");
});
app.factory('Bug', function($resource) {
return $resource("/api/projects/:name/bugs");
});
app.controller('ProjectsCtrl', function($scope, Project) {
Project.query(function(data) {
$scope.projects = data;
console.log(data);
});
});
app.controller('ProjectBugsCtrl', function($scope, Bug) {
Bug.query({name: 'Bugminer'}, function(data) {
$scope.bugs = data;
console.log(data);
});
});
})(angular);
| (function(angular) {
'use strict';
var app = angular.module('bugminerApp', ['ngResource', 'ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/projects/index.html',
controller: 'ProjectsCtrl'
})
.when('/projects/:name/bugs', {
templateUrl: 'partials/projects/bugs.html',
controller: 'ProjectBugsCtrl'
});
}]);
app.factory('Project', function($resource) {
return $resource("/api/projects/:name");
});
app.factory('Bug', function($resource) {
return $resource("/api/projects/:name/bugs");
});
app.controller('ProjectsCtrl', function($scope, Project) {
Project.query(function(data) {
$scope.projects = data;
console.log(data);
});
});
app.controller('ProjectBugsCtrl', function($scope, $routeParams, Bug) {
Bug.query({name: $routeParams.name}, function(data) {
$scope.bugs = data;
console.log(data);
});
});
})(angular);
| Use $routeParams for retrieving project name | Use $routeParams for retrieving project name
| JavaScript | mit | bugminer/bugminer,bugminer/bugminer,bugminer/bugminer,bugminer/bugminer | ---
+++
@@ -30,8 +30,8 @@
});
});
- app.controller('ProjectBugsCtrl', function($scope, Bug) {
- Bug.query({name: 'Bugminer'}, function(data) {
+ app.controller('ProjectBugsCtrl', function($scope, $routeParams, Bug) {
+ Bug.query({name: $routeParams.name}, function(data) {
$scope.bugs = data;
console.log(data);
}); |
3662d990b6b0b438b7223ba403ee39c6c16a75d0 | ui/frontend/index.js | ui/frontend/index.js | /* global process:false */
import "babel-polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore, compose } from 'redux';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
import persistState from 'redux-localstorage';
import url from 'url';
import { configureRustErrors } from './highlighting';
import { serialize, deserialize } from './local_storage';
import playgroundApp from './reducers';
import { gotoPosition, performGistLoad } from './actions';
import Playground from './Playground';
const mw = [thunk];
if (process.env.NODE_ENV !== 'production') {
mw.push(createLogger());
}
const middlewares = applyMiddleware(...mw);
const enhancers = compose(middlewares, persistState(undefined, { serialize, deserialize }));
const store = createStore(playgroundApp, enhancers);
configureRustErrors((line, col) => store.dispatch(gotoPosition(line, col)));
// Process query parameters
const urlObj = url.parse(window.location.href, true);
const query = urlObj.query;
if (query.gist) {
store.dispatch(performGistLoad(query.gist));
}
ReactDOM.render(
<Provider store={store}>
<Playground />
</Provider>,
document.getElementById('playground')
);
| /* global process:false */
import "babel-polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore, compose } from 'redux';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
import persistState from 'redux-localstorage';
import url from 'url';
import { configureRustErrors } from './highlighting';
import { serialize, deserialize } from './local_storage';
import playgroundApp from './reducers';
import { gotoPosition, editCode, performGistLoad } from './actions';
import Playground from './Playground';
const mw = [thunk];
if (process.env.NODE_ENV !== 'production') {
mw.push(createLogger());
}
const middlewares = applyMiddleware(...mw);
const enhancers = compose(middlewares, persistState(undefined, { serialize, deserialize }));
const store = createStore(playgroundApp, enhancers);
configureRustErrors((line, col) => store.dispatch(gotoPosition(line, col)));
// Process query parameters
const urlObj = url.parse(window.location.href, true);
const query = urlObj.query;
if (query.code) {
store.dispatch(editCode(query.code));
} else if (query.gist) {
store.dispatch(performGistLoad(query.gist));
}
ReactDOM.render(
<Provider store={store}>
<Playground />
</Provider>,
document.getElementById('playground')
);
| Allow loading code from a CGI parameter | Allow loading code from a CGI parameter
Closes #62
| JavaScript | apache-2.0 | integer32llc/rust-playground,integer32llc/rust-playground,integer32llc/rust-playground,integer32llc/rust-playground,integer32llc/rust-playground | ---
+++
@@ -14,7 +14,7 @@
import { configureRustErrors } from './highlighting';
import { serialize, deserialize } from './local_storage';
import playgroundApp from './reducers';
-import { gotoPosition, performGistLoad } from './actions';
+import { gotoPosition, editCode, performGistLoad } from './actions';
import Playground from './Playground';
const mw = [thunk];
@@ -31,7 +31,9 @@
const urlObj = url.parse(window.location.href, true);
const query = urlObj.query;
-if (query.gist) {
+if (query.code) {
+ store.dispatch(editCode(query.code));
+} else if (query.gist) {
store.dispatch(performGistLoad(query.gist));
}
|
65809e2efdea1c7a7952def23dbcf100c6f82bd7 | app/settings/settings.js | app/settings/settings.js | export default {
'vt-source': 'http://52.207.244.74', // source of current vector tiles
'vt-hist-source': 'http://52.207.244.74', // source of historic vector tiles for compare feature
}
| export default {
'vt-source': 'http://da-tiles.osm-analytics.org', // source of current vector tiles
'vt-hist-source': 'http://da-tiles.osm-analytics.org', // source of historic vector tiles for compare feature
}
| Use DNS for da-tiles server | Use DNS for da-tiles server
| JavaScript | bsd-3-clause | hotosm/osm-analytics,ekastimo/osm-analytics-fsp,ekastimo/osm-analytics-fsp,hotosm/osm-analytics,ekastimo/osm-analytics-fsp,hotosm/osm-analytics | ---
+++
@@ -1,4 +1,4 @@
export default {
- 'vt-source': 'http://52.207.244.74', // source of current vector tiles
- 'vt-hist-source': 'http://52.207.244.74', // source of historic vector tiles for compare feature
+ 'vt-source': 'http://da-tiles.osm-analytics.org', // source of current vector tiles
+ 'vt-hist-source': 'http://da-tiles.osm-analytics.org', // source of historic vector tiles for compare feature
} |
28d611136cb715dba5c9df021d026d611576153d | cla_frontend/assets-src/javascripts/app/js/controllers/case_edit_details.js | cla_frontend/assets-src/javascripts/app/js/controllers/case_edit_details.js | (function(){
'use strict';
angular.module('cla.controllers')
.controller('CaseEditDetailCtrl',
['$scope', 'AlternativeHelpService', '$state',
function($scope, AlternativeHelpService, $state){
// when viewing coming back to the details view
// clear out the Alternative Help selections.
AlternativeHelpService.clear();
$scope.diagnosisIcon = function () {
return $scope.diagnosis.isInScopeTrue() ? 'Icon Icon--right Icon--solidTick Icon--green' : ($scope.diagnosis.isInScopeFalse() ? 'Icon Icon--right Icon--solidCross Icon--red' : 'Icon Icon--right Icon--info');
};
$scope.eligibilityIcon = function () {
return $scope.eligibility_check.isEligibilityTrue() ? 'Icon Icon--right Icon--solidTick Icon--green' : ($scope.eligibility_check.isEligibilityFalse() ? 'Icon Icon--right Icon--solidCross Icon--red' : 'Icon Icon--right Icon--info');
};
$state.go('case_detail.edit.diagnosis');
}
]
);
})(); | (function(){
'use strict';
angular.module('cla.controllers')
.controller('CaseEditDetailCtrl',
['$scope', 'AlternativeHelpService',
function($scope, AlternativeHelpService){
// when viewing coming back to the details view
// clear out the Alternative Help selections.
AlternativeHelpService.clear();
$scope.diagnosisIcon = function () {
return $scope.diagnosis.isInScopeTrue() ? 'Icon Icon--right Icon--solidTick Icon--green' : ($scope.diagnosis.isInScopeFalse() ? 'Icon Icon--right Icon--solidCross Icon--red' : 'Icon Icon--right Icon--info');
};
$scope.eligibilityIcon = function () {
return $scope.eligibility_check.isEligibilityTrue() ? 'Icon Icon--right Icon--solidTick Icon--green' : ($scope.eligibility_check.isEligibilityFalse() ? 'Icon Icon--right Icon--solidCross Icon--red' : 'Icon Icon--right Icon--info');
};
}
]
);
})(); | Remove case detail redirect to diagnosis as blocks deep linking into means test tabs | Remove case detail redirect to diagnosis as blocks deep linking into means test tabs
| JavaScript | mit | ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend | ---
+++
@@ -3,8 +3,8 @@
angular.module('cla.controllers')
.controller('CaseEditDetailCtrl',
- ['$scope', 'AlternativeHelpService', '$state',
- function($scope, AlternativeHelpService, $state){
+ ['$scope', 'AlternativeHelpService',
+ function($scope, AlternativeHelpService){
// when viewing coming back to the details view
// clear out the Alternative Help selections.
AlternativeHelpService.clear();
@@ -15,8 +15,6 @@
$scope.eligibilityIcon = function () {
return $scope.eligibility_check.isEligibilityTrue() ? 'Icon Icon--right Icon--solidTick Icon--green' : ($scope.eligibility_check.isEligibilityFalse() ? 'Icon Icon--right Icon--solidCross Icon--red' : 'Icon Icon--right Icon--info');
};
-
- $state.go('case_detail.edit.diagnosis');
}
]
); |
72e7ec921e523e7088c9305aa323f586d4f995e5 | src/Jailor.js | src/Jailor.js | var Jailor;
(function(GLOBAL) {
var conditions = [];
Jailor = {
init: function initJailor() {
var previousBeforeUnloadHandler = GLOBAL.onbeforeunload;
GLOBAL.onbeforeunload = Jailor.check;
Jailor.lock(previousBeforeUnloadHandler);
},
lock: function lock(condition) {
if (condition)
conditions.push(condition);
return this;
},
check: function check() {
var result = '';
conditions.forEach(function(condition) {
var evaluationResult = condition();
if (typeof result == 'string')
result += evaluationResult;
});
return result;
}
}
Jailor.init();
})(window);
| var Jailor;
(function(GLOBAL) {
var conditions = [];
Jailor = {
init: function initJailor() {
var previousBeforeUnloadHandler = GLOBAL.onbeforeunload;
GLOBAL.onbeforeunload = Jailor.check;
Jailor.lock(previousBeforeUnloadHandler);
},
lock: function lock(condition) {
if (condition)
conditions.push(condition);
return this;
},
check: function check() {
var result = [];
conditions.forEach(function(condition) {
var evaluationResult = condition();
if (typeof evaluationResult == 'string')
result.push(evaluationResult);
});
if (result.length)
return result.join('\n');
}
}
Jailor.init();
})(window);
| Correct attachment with no condition | Correct attachment with no condition | JavaScript | mit | MESHMD/Jailor | ---
+++
@@ -21,16 +21,17 @@
},
check: function check() {
- var result = '';
+ var result = [];
conditions.forEach(function(condition) {
var evaluationResult = condition();
- if (typeof result == 'string')
- result += evaluationResult;
+ if (typeof evaluationResult == 'string')
+ result.push(evaluationResult);
});
- return result;
+ if (result.length)
+ return result.join('\n');
}
}
|
cbe0db51d7806fb07ee4b4d87f1c1f12f1eba7bb | util/test-regexp.js | util/test-regexp.js | let tests = [
// expect, string to match against
[ true, 'foobar' ],
[ false, 'foobaz' ],
[ true, 'wheelbarrow' ],
];
let re = /bar/;
for (let i = 0; i < tests.length; i++) {
var test = tests[i];
var expected = test[0];
var string = test[1];
var result = !!string.match(re);
print(i + ": '" + string + "': " +
"expected " + expected + ", got " + result + ": " +
(result == expected ? "OK" : "FAIL"));
}
| let tests = [
// what result to expect, string to match against
[ true, '/home/mike/git/work/stripes-experiments/stripes-connect' ],
[ true, '/home/mike/git/work/stripes-loader/' ],
[ true, '/home/mike/git/work/stripes-experiments/okapi-console/' ],
[ true, '/home/mike/git/work/stripes-experiments/stripes-core/src/' ],
[ false, '/home/mike/git/work/stripes-experiments/stripes-core/node_modules/camelcase' ],
];
// The regexp used in webpack.config.base.js to choose which source files get transpiled
let re = /\/stripes-/;
for (let i = 0; i < tests.length; i++) {
var test = tests[i];
var expected = test[0];
var string = test[1];
var result = !!string.match(re);
print(i + ": '" + string + "': " +
"expected " + expected + ", got " + result + ": " +
(result == expected ? "OK" : "FAIL"));
}
| Switch to actual regexp and paths. Rather obvious demo that Jason was right about node_modules. | Switch to actual regexp and paths. Rather obvious demo that Jason was right about node_modules.
| JavaScript | apache-2.0 | folio-org/stripes-experiments,folio-org/stripes-experiments | ---
+++
@@ -1,11 +1,14 @@
let tests = [
- // expect, string to match against
- [ true, 'foobar' ],
- [ false, 'foobaz' ],
- [ true, 'wheelbarrow' ],
+ // what result to expect, string to match against
+ [ true, '/home/mike/git/work/stripes-experiments/stripes-connect' ],
+ [ true, '/home/mike/git/work/stripes-loader/' ],
+ [ true, '/home/mike/git/work/stripes-experiments/okapi-console/' ],
+ [ true, '/home/mike/git/work/stripes-experiments/stripes-core/src/' ],
+ [ false, '/home/mike/git/work/stripes-experiments/stripes-core/node_modules/camelcase' ],
];
-let re = /bar/;
+// The regexp used in webpack.config.base.js to choose which source files get transpiled
+let re = /\/stripes-/;
for (let i = 0; i < tests.length; i++) {
var test = tests[i]; |
6284d330c64d3b8323032bc7a002349cc35f3a29 | src/config.js | src/config.js | 'use strict';
var load = require('../src/loader.js');
function config(params) {
var cfg = false;
if ('object' == typeof params) cfg = params;
if ('string' == typeof params && (params.endsWith('.yaml') || params.endsWith('.yml'))) cfg = load.yaml(params);
if ('string' == typeof params && params.endsWith('.json')) cfg = load.json(params);
if ('function' == typeof params) cfg = params();
if (!cfg) throw new Error('Invalid arguments');
return cfg;
}
module.exports = config; | 'use strict';
var load = require('../src/loader.js');
function config(params) {
var cfg = false;
if ('object' == typeof params) cfg = params;
if ('string' == typeof params && /\.ya?ml$/.test(params)) cfg = load.yaml(params);
if ('string' == typeof params && /\.json$/.test(params)) cfg = load.json(params);
if ('function' == typeof params) cfg = params();
if (!cfg) throw new Error('Invalid arguments');
return cfg;
}
module.exports = config; | Change String.endsWith() calls with regex tests to make compatible with node 0.10+ | Change String.endsWith() calls with regex tests to make compatible with node 0.10+
| JavaScript | mit | mrajo/metalsmith-grep | ---
+++
@@ -5,8 +5,8 @@
function config(params) {
var cfg = false;
if ('object' == typeof params) cfg = params;
- if ('string' == typeof params && (params.endsWith('.yaml') || params.endsWith('.yml'))) cfg = load.yaml(params);
- if ('string' == typeof params && params.endsWith('.json')) cfg = load.json(params);
+ if ('string' == typeof params && /\.ya?ml$/.test(params)) cfg = load.yaml(params);
+ if ('string' == typeof params && /\.json$/.test(params)) cfg = load.json(params);
if ('function' == typeof params) cfg = params();
if (!cfg) throw new Error('Invalid arguments');
return cfg; |
1636d6643cfb5f77089886bac4d6921a3c3915e0 | src/api/thrusterRoutes.js | src/api/thrusterRoutes.js | var shipSystems = require('../shipSystems.js');
var thrusters = shipSystems.getSystemById('thrusters');
exports.registerRoutes = function (app, config) {
app.post('/api/systems/thrusters/attitude', function (request, response) {
thrusters.setAttitude(request.body);
response.send(thrusters.attitude);
});
};
| var shipSystems = require('../shipSystems.js');
var thrusters = shipSystems.getSystemById('thrusters');
exports.registerRoutes = function (app, config) {
app.post('/api/systems/thrusters/attitude', function (request, response) {
thrusters.setAttitude(request.body);
response.send(thrusters.attitude);
});
app.post('/api/systems/thrusters/velocity', function (request, response) {
thrusters.setVelocity(request.body);
response.send(thrusters.velocity);
});
};
| Add route for updating thruster velocity | Add route for updating thruster velocity
| JavaScript | apache-2.0 | openstardrive/server,openstardrive/server,openstardrive/server | ---
+++
@@ -6,4 +6,9 @@
thrusters.setAttitude(request.body);
response.send(thrusters.attitude);
});
+
+ app.post('/api/systems/thrusters/velocity', function (request, response) {
+ thrusters.setVelocity(request.body);
+ response.send(thrusters.velocity);
+ });
}; |
0d9b89986950ce0e4089f8c98f15a33568c83ae5 | spec/exfmt-atom-spec.js | spec/exfmt-atom-spec.js | "use babel";
import AtomExfmt from "../lib/exfmt-atom";
// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.
describe("AtomExfmt", () => {
let workspaceElement, activationPromise;
beforeEach(() => {
workspaceElement = atom.views.getView(atom.workspace);
activationPromise = atom.packages.activatePackage("exfmt-atom");
});
});
| "use babel";
import * as path from "path";
import ExfmtAtom from "../lib/exfmt-atom";
const simplePath = path.join(__dirname, "fixtures", "simple.ex");
// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.
describe("ExfmtAtom", () => {
let workspaceElement, activationPromise;
beforeEach(() => {
workspaceElement = atom.views.getView(atom.workspace);
activationPromise = atom.packages.activatePackage("exfmt-atom");
waitsForPromise(() =>
atom.packages
.activatePackage("language-elixir")
.then(() => atom.workspace.open(simplePath))
);
atom.packages.triggerDeferredActivationHooks();
waitsForPromise(() => activationPromise);
});
it("should be in packages list", () => {
console.log(atom.workspace.getActiveTextEditor().getText());
expect(atom.packages.isPackageLoaded("exfmt-atom")).toBe(true);
});
it("should be an active package", () => {
expect(atom.packages.isPackageActive("exfmt-atom")).toBe(true);
});
describe("package settings", () => {
it("should default formatOnSave to false", () => {
expect(atom.config.get("exfmt-atom.formatOnSave")).toBe(false);
});
it("should default showErrorNotifications to false", () => {
expect(atom.config.get("exfmt-atom.showErrorNotifications")).toBe(true);
});
it("should default externalExfmtDirectory to blank string", () => {
expect(atom.config.get("exfmt-atom.externalExfmtDirectory")).toEqual("");
});
});
});
| Add spec tests for package activation and default setting values | Add spec tests for package activation and default setting values
| JavaScript | mit | rgreenjr/exfmt-atom | ---
+++
@@ -1,17 +1,50 @@
"use babel";
-import AtomExfmt from "../lib/exfmt-atom";
+import * as path from "path";
+import ExfmtAtom from "../lib/exfmt-atom";
+
+const simplePath = path.join(__dirname, "fixtures", "simple.ex");
// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.
-describe("AtomExfmt", () => {
+describe("ExfmtAtom", () => {
let workspaceElement, activationPromise;
beforeEach(() => {
workspaceElement = atom.views.getView(atom.workspace);
activationPromise = atom.packages.activatePackage("exfmt-atom");
+ waitsForPromise(() =>
+ atom.packages
+ .activatePackage("language-elixir")
+ .then(() => atom.workspace.open(simplePath))
+ );
+ atom.packages.triggerDeferredActivationHooks();
+ waitsForPromise(() => activationPromise);
+ });
+
+ it("should be in packages list", () => {
+ console.log(atom.workspace.getActiveTextEditor().getText());
+ expect(atom.packages.isPackageLoaded("exfmt-atom")).toBe(true);
+ });
+
+ it("should be an active package", () => {
+ expect(atom.packages.isPackageActive("exfmt-atom")).toBe(true);
+ });
+
+ describe("package settings", () => {
+ it("should default formatOnSave to false", () => {
+ expect(atom.config.get("exfmt-atom.formatOnSave")).toBe(false);
+ });
+
+ it("should default showErrorNotifications to false", () => {
+ expect(atom.config.get("exfmt-atom.showErrorNotifications")).toBe(true);
+ });
+
+ it("should default externalExfmtDirectory to blank string", () => {
+ expect(atom.config.get("exfmt-atom.externalExfmtDirectory")).toEqual("");
+ });
});
}); |
eb2055576a4f10c31c020e00f520d4fc260df095 | dear.js | dear.js | var tablePrefix = '__dear_';
function createTable(tableName) {
if (!localStorage[tableName]) {
localStorage[tablePrefix + tableName] = '{}';
}
}
function readTable(tableName) {
// Read tableModel from local storage
return JSON.parse(localStorage[tablePrefix + tableName]);
}
function writeTable(tableName, tableModel) {
// Write tableModel to local storage
localStorage[tablePrefix + tableName] = JSON.stringify(tableModel);
}
function createRecord(tableName, recordName, value) {
var tableModel = readTable(tableName);
if (!tableModel[recordName]) {
tableModel[recordName] = value;
}
writeTable(tableName, tableModel);
}
function writeRecord(tableName, recordName, value) {
var tableModel = readTable(tableName);
tableModel[recordName] = value;
writeTable(tableName, tableModel);
}
function deleteRecord(tableName, recordName) {
var tableModel = readTable(tableName);
delete tableModel[recordName];
writeTable(tableName, tableModel);
}
function deleteTable(tableName) {
delete localStorage[tablePrefix + tableName];
$('#changeTable option[value=' + tableName + ']').remove();
}
function listTables() {
return Object.keys(localStorage).filter(function(str) {
return str.slice(0, tablePrefix.length) == tablePrefix;
}).map(function(str) {
return str.slice(tablePrefix.length);
});
}
| var tablePrefix = '__dear_';
function createTable(tableName) {
if (!localStorage[tableName]) {
localStorage[tablePrefix + tableName] = '{}';
}
}
function readTable(tableName) {
// Read tableModel from local storage
return JSON.parse(localStorage[tablePrefix + tableName]);
}
function writeTable(tableName, tableModel) {
// Write tableModel to local storage
localStorage[tablePrefix + tableName] = JSON.stringify(tableModel);
}
function createRecord(tableName, recordName, value) {
var tableModel = readTable(tableName);
if (!tableModel[recordName]) {
tableModel[recordName] = value;
}
writeTable(tableName, tableModel);
}
function writeRecord(tableName, recordName, value) {
var tableModel = readTable(tableName);
tableModel[recordName] = value;
writeTable(tableName, tableModel);
}
function deleteRecord(tableName, recordName) {
var tableModel = readTable(tableName);
delete tableModel[recordName];
writeTable(tableName, tableModel);
}
function deleteTable(tableName) {
delete localStorage[tablePrefix + tableName];
}
function listTables() {
return Object.keys(localStorage).filter(function(str) {
return str.slice(0, tablePrefix.length) == tablePrefix;
}).map(function(str) {
return str.slice(tablePrefix.length);
});
}
| Remove demo-related jQuery from library code | Remove demo-related jQuery from library code
| JavaScript | mit | strburst/dear,strburst/dear | ---
+++
@@ -39,7 +39,6 @@
function deleteTable(tableName) {
delete localStorage[tablePrefix + tableName];
- $('#changeTable option[value=' + tableName + ']').remove();
}
function listTables() { |
67696ac08bf39662aa796ce44e556b73e96594a5 | html.js | html.js | import React from 'react'
import Helmet from 'react-helmet'
import { prefixLink } from 'gatsby-helpers'
const BUILD_TIME = new Date().getTime()
module.exports = React.createClass({
displayName: 'HTML',
propTypes: {
body: React.PropTypes.string,
},
render() {
const {body, route} = this.props
const head = Helmet.rewind()
const font = <link href='https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,700&subset=latin,cyrillic' rel='stylesheet' type='text/css' />
let css
if (process.env.NODE_ENV === 'production') {
css = <style dangerouslySetInnerHTML={ { __html: require('!raw!./public/styles.css')} } />
}
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" />
<title>
{ head.title }
</title>
{ font }
{ css }
</head>
<body>
<div id="react-mount" dangerouslySetInnerHTML={ { __html: this.props.body} } />
<script src={ prefixLink(`/bundle.js?t=${BUILD_TIME}`) } />
</body>
</html>
)
},
})
| import React from 'react'
import Helmet from 'react-helmet'
import { prefixLink } from 'gatsby-helpers'
const BUILD_TIME = new Date().getTime()
module.exports = React.createClass({
displayName: 'HTML',
propTypes: {
body: React.PropTypes.string,
},
render() {
const {body, route} = this.props
const {title} = Helmet.rewind()
const font = <link href='https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,700&subset=latin,cyrillic' rel='stylesheet' type='text/css' />
let css
if (process.env.NODE_ENV === 'production') {
css = <style dangerouslySetInnerHTML={ { __html: require('!raw!./public/styles.css')} } />
}
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" />
{ title.toComponent() }
{ font }
{ css }
</head>
<body>
<div id="react-mount" dangerouslySetInnerHTML={ { __html: this.props.body} } />
<script src={ prefixLink(`/bundle.js?t=${BUILD_TIME}`) } />
</body>
</html>
)
},
})
| Correct the usage of title as a component | Correct the usage of title as a component
Documentation for this feature can be found [here](https://github.com/nfl/react-helmet#as-react-components) | JavaScript | mit | maxgrok/maxgrok.github.io,ochaloup/blog.chalda.cz,renegens/blog,wpioneer/gatsby-starter-lumen,hb-gatsby/gatsby-starter-lumen,Chogyuwon/chogyuwon.github.io,maxgrok/maxgrok.github.io,nicklanasa/nicklanasa.github.io,Chogyuwon/chogyuwon.github.io,alxshelepenok/gatsby-starter-lumen,alxshelepenok/gatsby-starter-lumen,YoruNoHikage/yorunohikage.github.io,YoruNoHikage/blog,renegens/blog,YoruNoHikage/yorunohikage.github.io,ochaloup/blog.chalda.cz,nicklanasa/nicklanasa.github.io | ---
+++
@@ -11,7 +11,7 @@
},
render() {
const {body, route} = this.props
- const head = Helmet.rewind()
+ const {title} = Helmet.rewind()
const font = <link href='https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,700&subset=latin,cyrillic' rel='stylesheet' type='text/css' />
let css
if (process.env.NODE_ENV === 'production') {
@@ -24,9 +24,7 @@
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" />
- <title>
- { head.title }
- </title>
+ { title.toComponent() }
{ font }
{ css }
</head> |
41a256c6fc37c7754520eb7df4582f6ae3276838 | src/components/TldrApp.js | src/components/TldrApp.js | import React from 'react';
//import { createHistory } from 'history';
import createHistory from 'history/lib/createHashHistory';
// Import components
import SearchBar from './SearchBar';
import Results from './Results';
let history = createHistory();
class TldrApp extends React.Component {
render () {
return (
<div>
<SearchBar history={history}/>
<Results history={history}/>
</div>
);
}
}
export default TldrApp;
| import React from 'react';
//import { createHistory } from 'history';
import createHistory from 'history/lib/createHashHistory';
// Import components
import SearchBar from './SearchBar';
import Results from './Results';
import { Command } from '../actions/Command';
let history = createHistory();
class TldrApp extends React.Component {
componentWillMount () {
Command.getIndex().subscribe();
}
render () {
return (
<div>
<SearchBar history={history}/>
<Results history={history}/>
</div>
);
}
}
export default TldrApp;
| Load index earlier because it's safe now | Load index earlier because it's safe now
| JavaScript | mit | ostera/tldr.jsx,ostera/tldr.jsx,ostera/tldr.jsx,ostera/tldr.jsx | ---
+++
@@ -6,9 +6,15 @@
import SearchBar from './SearchBar';
import Results from './Results';
+import { Command } from '../actions/Command';
+
let history = createHistory();
class TldrApp extends React.Component {
+
+ componentWillMount () {
+ Command.getIndex().subscribe();
+ }
render () {
return ( |
0a46358c5f1cafe9ff8b2cd946e6ac19fd298b08 | src/eeh-flot-directive.js | src/eeh-flot-directive.js | (function (angular) {
'use strict';
function FlotDirective(eehFlot) {
return {
restrict: 'AE',
scope: {
dataset: '=',
options: '@'
},
link: function link(scope, element) {
eehFlot(element, scope.dataset, scope.options);
}
};
}
angular.module('eehFlot').directive('eehFlot', FlotDirective);
})(angular); | (function (angular) {
'use strict';
function FlotDirective(eehFlot) {
return {
restrict: 'AE',
template: '<div class="eeh-flot"></div>',
scope: {
dataset: '=',
options: '@'
},
link: function link(scope, element) {
var renderArea = element.find('.eeh-flot');
eehFlot(renderArea, scope.dataset, scope.options);
}
};
}
angular.module('eehFlot').directive('eehFlot', FlotDirective);
})(angular);
| Use the inner div to render the chart | Use the inner div to render the chart
| JavaScript | mit | ethanhann/eeh-flot | ---
+++
@@ -4,12 +4,14 @@
function FlotDirective(eehFlot) {
return {
restrict: 'AE',
+ template: '<div class="eeh-flot"></div>',
scope: {
dataset: '=',
options: '@'
},
link: function link(scope, element) {
- eehFlot(element, scope.dataset, scope.options);
+ var renderArea = element.find('.eeh-flot');
+ eehFlot(renderArea, scope.dataset, scope.options);
}
};
} |
88df148411b9cb891a73933f2139a4a069fcec6f | app/serializers/agent.js | app/serializers/agent.js | import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: 'id',
attrs: {
division: 'divisionID',
},
});
| import DS from 'ember-data';
export default DS.JSONSerializer.extend({
attrs: {
division: 'divisionID',
},
});
| Remove primaryKey def since default | Remove primaryKey def since default
| JavaScript | agpl-3.0 | DINA-Web/collections-ui,DINA-Web/collections-ui,DINA-Web/collections-ui | ---
+++
@@ -1,7 +1,6 @@
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
- primaryKey: 'id',
attrs: {
division: 'divisionID',
}, |
20122bc58b6bce1441494c9f502801e95af07631 | imports/ui/components/menu/drawer-navigation.js | imports/ui/components/menu/drawer-navigation.js | import React from 'react';
import Drawer from 'material-ui/Drawer';
import DrawerMenuItems from '../../containers/drawer-menu-items.js';
export default class DrawerNavigation extends React.Component {
render() {
return (
<Drawer docked={ false } width={ 300 } open={ this.props.isOpen } onRequestChange={ isOpen => this.props.setDrawerOpen(isOpen) }>
<DrawerMenuItems closeDrawer={ this.props.closeDrawer } />
</Drawer>
);
}
}
DrawerNavigation.propTypes = {
isOpen: React.PropTypes.bool.isRequired,
closeDrawer: React.PropTypes.func,
} | import React from 'react';
import Drawer from 'material-ui/Drawer';
import DrawerMenuItems from '../../containers/drawer-menu-items.js';
export default class DrawerNavigation extends React.Component {
render() {
return (
<Drawer docked={ false } width={ 250 } open={ this.props.isOpen } onRequestChange={ isOpen => this.props.setDrawerOpen(isOpen) }>
<DrawerMenuItems closeDrawer={ this.props.closeDrawer } />
</Drawer>
);
}
}
DrawerNavigation.propTypes = {
isOpen: React.PropTypes.bool.isRequired,
closeDrawer: React.PropTypes.func,
}
| Set drawer size to 250 instead of 300, need space on mobile to close overlay | Set drawer size to 250 instead of 300, need space on mobile to close overlay
| JavaScript | mit | irvinlim/free4all,irvinlim/free4all | ---
+++
@@ -5,7 +5,7 @@
export default class DrawerNavigation extends React.Component {
render() {
return (
- <Drawer docked={ false } width={ 300 } open={ this.props.isOpen } onRequestChange={ isOpen => this.props.setDrawerOpen(isOpen) }>
+ <Drawer docked={ false } width={ 250 } open={ this.props.isOpen } onRequestChange={ isOpen => this.props.setDrawerOpen(isOpen) }>
<DrawerMenuItems closeDrawer={ this.props.closeDrawer } />
</Drawer>
); |
c6a20794a55c3ee982c42b92a845b7b9a2582794 | src/resources/checkMinifiedJsFiles.js | src/resources/checkMinifiedJsFiles.js | import fetch from '../default/fetch.js';
import checkMinifiedJs from './checkMinifiedJs.js';
export default function(urls) {
return new Promise(function(resolve, reject) {
let chain = Promise.resolve();
urls.forEach((url) => {
chain = chain.then(() => {
return Promise.resolve(url)
.then(fetch)
.then(checkMinifiedJs);
});
});
chain.then(() => { resolve(urls); });
});
};
| import fetch from '../default/fetch.js';
import checkMinifiedJs from './checkMinifiedJs.js';
import checkHttpStatus from '../default/checkHttpStatus.js';
export default function(urls) {
return new Promise(function(resolve, reject) {
let chain = Promise.resolve();
urls.forEach((url) => {
chain = chain.then(() => {
return Promise.resolve(url)
.then(fetch)
.then(checkHttpStatus)
.then(checkMinifiedJs)
.catch(() => {
outcome.warning('resources', url, 'Not found!');
});
});
});
chain.then(() => { resolve(urls); });
});
};
| Add check resources http status code | Add check resources http status code
| JavaScript | mit | juffalow/pentest-tool-lite,juffalow/pentest-tool-lite | ---
+++
@@ -1,5 +1,6 @@
import fetch from '../default/fetch.js';
import checkMinifiedJs from './checkMinifiedJs.js';
+import checkHttpStatus from '../default/checkHttpStatus.js';
export default function(urls) {
return new Promise(function(resolve, reject) {
@@ -9,7 +10,11 @@
chain = chain.then(() => {
return Promise.resolve(url)
.then(fetch)
- .then(checkMinifiedJs);
+ .then(checkHttpStatus)
+ .then(checkMinifiedJs)
+ .catch(() => {
+ outcome.warning('resources', url, 'Not found!');
+ });
});
});
|
1cd7c41e29c98712c984676b1ad152bbfc8e88b5 | chrome.js | chrome.js | var extend = require('cog/extend');
var OPT_DEFAULTS = {
target: 'rtc.io screenshare'
};
module.exports = function(opts) {
var lastRequestId;
var extension = require('chromex/client')(extend({}, OPT_DEFAULTS, opts, {
target: (opts || {}).chromeExtension
}));
extension.available = function(callback) {
return extension.satisfies((opts || {}).version, callback);
};
// patch in our capture function
extension.request = function(callback) {
extension.sendCommand('share', function(err, sourceId, requestId) {
if (err) {
return callback(err);
}
if (! sourceId) {
return callback(new Error('user rejected screen share request'));
}
// update the last requestId
lastRequestId = requestId;
// pass the constraints through
return callback(null, {
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: sourceId,
maxWidth: screen.width,
maxHeight: screen.height,
minFrameRate: 1,
maxFrameRate: 5
},
optional: []
}
});
});
};
extension.cancel = function(requestId) {
var opts = {
requestId: requestId || lastRequestId
};
extension.sendCommand('cancel', opts, function(err) {
});
};
return extension;
};
| var extend = require('cog/extend');
var OPT_DEFAULTS = {
target: 'rtc.io screenshare'
};
module.exports = function(opts) {
var extension = require('chromex/client')(extend({}, OPT_DEFAULTS, opts, {
target: (opts || {}).chromeExtension
}));
extension.available = function(callback) {
return extension.satisfies((opts || {}).version, callback);
};
// patch in our capture function
extension.request = function(callback) {
extension.sendCommand('share', function(err, sourceId) {
if (err) {
return callback(err);
}
if (! sourceId) {
return callback(new Error('user rejected screen share request'));
}
// pass the constraints through
return callback(null, {
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: sourceId,
maxWidth: screen.width,
maxHeight: screen.height,
minFrameRate: 1,
maxFrameRate: 5
},
optional: []
}
});
});
};
extension.cancel = function() {
extension.sendCommand('cancel', function(err) {
});
};
return extension;
};
| Refactor the cancel logic - the extension will track the request id to cancel | Refactor the cancel logic - the extension will track the request id to cancel
| JavaScript | apache-2.0 | rtc-io/rtc-screenshare | ---
+++
@@ -4,7 +4,6 @@
};
module.exports = function(opts) {
- var lastRequestId;
var extension = require('chromex/client')(extend({}, OPT_DEFAULTS, opts, {
target: (opts || {}).chromeExtension
}));
@@ -15,7 +14,7 @@
// patch in our capture function
extension.request = function(callback) {
- extension.sendCommand('share', function(err, sourceId, requestId) {
+ extension.sendCommand('share', function(err, sourceId) {
if (err) {
return callback(err);
}
@@ -24,9 +23,6 @@
return callback(new Error('user rejected screen share request'));
}
- // update the last requestId
- lastRequestId = requestId;
-
// pass the constraints through
return callback(null, {
audio: false,
@@ -46,12 +42,8 @@
});
};
- extension.cancel = function(requestId) {
- var opts = {
- requestId: requestId || lastRequestId
- };
-
- extension.sendCommand('cancel', opts, function(err) {
+ extension.cancel = function() {
+ extension.sendCommand('cancel', function(err) {
});
};
|
49d4e7791e0daa9de597e228cbc82c70e8e7c027 | src/javascripts/module.js | src/javascripts/module.js | angular.module('rs.popover', []).run(function () {
'use strict';
var styleContent, styleTag;
styleContent = document.createTextNode('.rs-popover-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; opacity: 0 } \
.rs-popover-loading, .rs-popover-error { width: 200px; height: 140px } \
.rs-popover-error { color: #c40022 } \
.rs-popover-message { width: 100%; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; } \
.rs-popover-body { margin: 0; padding: 20px }');
styleTag = document.createElement('style');
styleTag.type = 'text/css';
styleTag.appendChild(styleContent);
document.head.appendChild(styleTag);
});
| angular.module('rs.popover', []).run(function () {
'use strict';
var styleContent, styleTag;
styleContent = document.createTextNode('.rs-popover-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; opacity: 0 } \
.rs-popover-loading, .rs-popover-error { width: 200px; height: 140px } \
.rs-popover-error { color: #c40022 } \
.rs-popover-message { width: 100%; position: absolute; top: 50%; left: 50%; -moz-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; } \
.rs-popover-body { margin: 0; padding: 20px }');
styleTag = document.createElement('style');
styleTag.type = 'text/css';
styleTag.appendChild(styleContent);
document.head.appendChild(styleTag);
});
| Add more browser prefixes for rs-popover-message | Add more browser prefixes for rs-popover-message
| JavaScript | mit | rackerlabs/rs-popover | ---
+++
@@ -6,7 +6,7 @@
styleContent = document.createTextNode('.rs-popover-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; opacity: 0 } \
.rs-popover-loading, .rs-popover-error { width: 200px; height: 140px } \
.rs-popover-error { color: #c40022 } \
- .rs-popover-message { width: 100%; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; } \
+ .rs-popover-message { width: 100%; position: absolute; top: 50%; left: 50%; -moz-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; } \
.rs-popover-body { margin: 0; padding: 20px }');
styleTag = document.createElement('style');
styleTag.type = 'text/css'; |
ac90b26cb0bba0ac5b27899686938533e08b0767 | src/tasks/tasks-router.js | src/tasks/tasks-router.js | /**
* Entry point for Step Functions Tasks Handler
*/
'use strict';
const
constants = require('../common/constants'),
error = require('../services/error'),
bottle = constants.BOTTLE_CONTAINER;
module.exports.handler = (event, context, callback) => {
event.parsedBody = JSON.parse(event.body || '{}');
let taskEvent = event.parsedBody.event;
let taskHandler = bottle.container[`tasks-event-${taskEvent}`];
if(!taskHandler) {
throw new error.EventHandlerNotRegistered();
}
return taskHandler.handle(event, context, callback);
}; | /**
* Entry point for Step Functions Tasks Handler
*/
'use strict';
const
constants = require('../common/constants'),
error = require('../services/error'),
bottle = constants.BOTTLE_CONTAINER;
module.exports.handler = (event, context, callback) => {
let taskEvent = event.event;
let taskHandler = bottle.container[`tasks-event-${taskEvent}`];
if(!taskHandler) {
throw new error.EventHandlerNotRegistered();
}
return taskHandler.handle(event, context, callback);
}; | Add 2 states for state machine | Add 2 states for state machine
| JavaScript | mit | totem/totem-v3-orchestrator | ---
+++
@@ -9,9 +9,8 @@
bottle = constants.BOTTLE_CONTAINER;
module.exports.handler = (event, context, callback) => {
- event.parsedBody = JSON.parse(event.body || '{}');
- let taskEvent = event.parsedBody.event;
+ let taskEvent = event.event;
let taskHandler = bottle.container[`tasks-event-${taskEvent}`];
if(!taskHandler) { |
f2b71a43e13c7e43da55f3f856db842f1a17b258 | vao.js | vao.js | "use strict"
var createVAONative = require("./lib/vao-native.js")
var createVAOEmulated = require("./lib/vao-emulated.js")
function createVAO(gl, attributes, elements, elementsType) {
var ext = gl.getExtension('OES_vertex_array_object')
var vao
if(ext) {
vao = createVAONative(gl, ext)
} else {
vao = createVAOEmulated(gl)
}
vao.update(attributes, elements, elementsType)
return vao
}
module.exports = createVAO
| "use strict"
var createVAONative = require("./lib/vao-native.js")
var createVAOEmulated = require("./lib/vao-emulated.js")
function ExtensionShim (gl) {
this.bindVertexArrayOES = gl.bindVertexArray.bind(gl)
this.createVertexArrayOES = gl.createVertexArray.bind(gl)
this.deleteVertexArrayOES = gl.deleteVertexArray.bind(gl)
}
function createVAO(gl, attributes, elements, elementsType) {
var ext = gl.createVertexArray
? new ExtensionShim(gl)
: gl.getExtension('OES_vertex_array_object')
var vao
if(ext) {
vao = createVAONative(gl, ext)
} else {
vao = createVAOEmulated(gl)
}
vao.update(attributes, elements, elementsType)
return vao
}
module.exports = createVAO
| Add support for WebGL 2 | Add support for WebGL 2
| JavaScript | mit | stackgl/gl-vao | ---
+++
@@ -3,9 +3,18 @@
var createVAONative = require("./lib/vao-native.js")
var createVAOEmulated = require("./lib/vao-emulated.js")
+function ExtensionShim (gl) {
+ this.bindVertexArrayOES = gl.bindVertexArray.bind(gl)
+ this.createVertexArrayOES = gl.createVertexArray.bind(gl)
+ this.deleteVertexArrayOES = gl.deleteVertexArray.bind(gl)
+}
+
function createVAO(gl, attributes, elements, elementsType) {
- var ext = gl.getExtension('OES_vertex_array_object')
+ var ext = gl.createVertexArray
+ ? new ExtensionShim(gl)
+ : gl.getExtension('OES_vertex_array_object')
var vao
+
if(ext) {
vao = createVAONative(gl, ext)
} else { |
afd7d74acfd98069832f52c5fb899d2c9325e53f | config.js | config.js | export default {
authToken: process.env.AUTH_TOKEN || 'secret',
env: process.env.NODE_ENV,
host: process.env.HOST || 'localhost',
github: {
apiUrl: 'https://api.github.com',
username: process.env.GITHUB_USERNAME || 'username'
},
jobs: {
frequency: {
githubActivity: process.env.JOBS_FREQUENCY_GITHUB || '00 */1 * * * *',
updateCache: process.env.JOBS_FREQUENCY_CACHE || '00 */2 * * * *'
}
},
mongo: {
url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney'
},
port: process.env.PORT || 8000
}
| export default {
authToken: process.env.AUTH_TOKEN || 'secret',
env: process.env.NODE_ENV,
host: process.env.HOST || 'localhost',
github: {
apiUrl: 'https://api.github.com',
username: process.env.GITHUB_USERNAME || 'username',
accessToken: process.env.GITHUB_ACCESS_TOKEN || '123abc'
},
jobs: {
frequency: {
githubActivity: process.env.JOBS_FREQUENCY_GITHUB || '00 */1 * * * *',
updateCache: process.env.JOBS_FREQUENCY_CACHE || '00 */2 * * * *'
}
},
mongo: {
url: process.env.MONGO_URL || 'mongodb://localhost:27017/FranVarney'
},
port: process.env.PORT || 8000
}
| Add GitHub access token option | Add GitHub access token option
| JavaScript | mit | franvarney/franvarney-api | ---
+++
@@ -4,7 +4,8 @@
host: process.env.HOST || 'localhost',
github: {
apiUrl: 'https://api.github.com',
- username: process.env.GITHUB_USERNAME || 'username'
+ username: process.env.GITHUB_USERNAME || 'username',
+ accessToken: process.env.GITHUB_ACCESS_TOKEN || '123abc'
},
jobs: {
frequency: { |
ce2781b4057e950a2ab23a0244e347bce2d0ccae | test/rules.href_type.js | test/rules.href_type.js | describe('rules.href_type', function () {
var rule = require('../lib/rules/href_type'),
htmllint = require('../'),
Parser = require('../lib/parser'),
parser = null;
describe('process', function () {
var Parser = require('../lib/parser'),
parser = null;
it('should return an array', function () {
var output = rule.process([]);
expect(output).to.be.an.instanceOf(Array);
});
//this code is for if the flag is set to absolute
it('should not match absolute links', function () {
var parser = new Parser(),
dom = parser.parse('<a href="http://www.google.com"></a>'),
output = rule.process(dom, {'href-type':'absolute'});
expect(output).to.have.length(0);
});
it('should match relative links', function () {
var parser = new Parser(),
dom = parser.parse('<a href="/dog/cat"></a>'),
output = rule.process(dom, {'href-type':'absolute'});
expect(output).to.have.length(1);
});
});
});
| describe('rules.href_type', function () {
var rule = require('../lib/rules/href_type'),
htmllint = require('../'),
Parser = require('../lib/parser'),
parser = null;
describe('process', function () {
var Parser = require('../lib/parser'),
parser = null;
it('should return an array', function () {
var output = rule.process([]);
expect(output).to.be.an.instanceOf(Array);
});
//this code is for if the flag is set to absolute
it('should not match absolute links given absolute option', function () {
var parser = new Parser(),
dom = parser.parse('<a href="http://www.google.com"></a>'),
output = rule.process(dom, {'href-type':'absolute'});
expect(output).to.have.length(0);
});
it('should match relative links given absolute option', function () {
var parser = new Parser(),
dom = parser.parse('<a href="/dog/cat"></a>'),
output = rule.process(dom, {'href-type':'absolute'});
expect(output).to.have.length(1);
});
it('should not match relative links given relative option', function () {
var parser = new Parser(),
dom = parser.parse('<a href="/dog/cat"></a>'),
output = rule.process(dom, {'href-type':'relative'});
expect(output).to.have.length(0);
});
it('should match absolute links given relative option', function () {
var parser = new Parser(),
dom = parser.parse('<a href="http://www.google.com"></a>'),
output = rule.process(dom, {'href-type':'relative'});
expect(output).to.have.length(1);
});
});
});
| Add more tests to href-type | Add more tests to href-type
| JavaScript | isc | htmllint/htmllint,htmllint/htmllint,KrekkieD/htmllint,KrekkieD/htmllint | ---
+++
@@ -14,7 +14,7 @@
expect(output).to.be.an.instanceOf(Array);
});
//this code is for if the flag is set to absolute
- it('should not match absolute links', function () {
+ it('should not match absolute links given absolute option', function () {
var parser = new Parser(),
dom = parser.parse('<a href="http://www.google.com"></a>'),
@@ -23,12 +23,29 @@
expect(output).to.have.length(0);
});
- it('should match relative links', function () {
+ it('should match relative links given absolute option', function () {
var parser = new Parser(),
dom = parser.parse('<a href="/dog/cat"></a>'),
output = rule.process(dom, {'href-type':'absolute'});
expect(output).to.have.length(1);
});
+
+ it('should not match relative links given relative option', function () {
+
+ var parser = new Parser(),
+ dom = parser.parse('<a href="/dog/cat"></a>'),
+ output = rule.process(dom, {'href-type':'relative'});
+
+ expect(output).to.have.length(0);
+ });
+
+ it('should match absolute links given relative option', function () {
+ var parser = new Parser(),
+ dom = parser.parse('<a href="http://www.google.com"></a>'),
+ output = rule.process(dom, {'href-type':'relative'});
+
+ expect(output).to.have.length(1);
+ });
});
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.