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
462cae04fb596a3cd8c05f8a6c472796adbc710b
index.js
index.js
var window = require('global/window'); var nodeCrypto = require('crypto'); function getRandomValues(buf) { if (window.crypto && window.crypto.getRandomValues) { window.crypto.getRandomValues(buf); } else if (typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') { window.msCrypto.getRandomValues(buf); } else if (nodeCrypto) { if (buf.length > 65536) { var e = new Error(); e.code = 22; e.message = 'Failed to execute \'getRandomValues\' on \'Crypto\': The ' + 'ArrayBufferView\'s byte length (' + buf.length + ') exceeds the ' + 'number of bytes of entropy available via this API (65536).'; e.name = 'QuotaExceededError'; throw e; } var bytes = nodeCrypto.randomBytes(buf.length); buf.set(bytes); } else { throw new Error('No secure random number generator available.'); } }; module.exports = getRandomValues;
var window = require('global/window'); var nodeCrypto = require('crypto'); function getRandomValues(buf) { if (window.crypto && window.crypto.getRandomValues) { window.crypto.getRandomValues(buf); } else if (typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') { window.msCrypto.getRandomValues(buf); } else if (nodeCrypto.randomBytes) { if (buf.length > 65536) { var e = new Error(); e.code = 22; e.message = 'Failed to execute \'getRandomValues\' on \'Crypto\': The ' + 'ArrayBufferView\'s byte length (' + buf.length + ') exceeds the ' + 'number of bytes of entropy available via this API (65536).'; e.name = 'QuotaExceededError'; throw e; } var bytes = nodeCrypto.randomBytes(buf.length); buf.set(bytes); } else { throw new Error('No secure random number generator available.'); } }; module.exports = getRandomValues;
Check for `randomBytes` before trying to use Node.js crypto
Check for `randomBytes` before trying to use Node.js crypto Browserify's `require()` will return an empty Object here, which evaluates to `true`, so check for the function we need before trying to use it.
JavaScript
mit
KenanY/get-random-values
--- +++ @@ -8,7 +8,7 @@ else if (typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') { window.msCrypto.getRandomValues(buf); } - else if (nodeCrypto) { + else if (nodeCrypto.randomBytes) { if (buf.length > 65536) { var e = new Error(); e.code = 22;
162a37b07e9770fb2c5b8893541843495bcdd1df
index.js
index.js
(function() { var Dependument = require('dependument').Dependument; var d = new Dependument({ source: 'package.json', output: 'DEPENDENCIES.md' }); d.process(); })();
#!/usr/bin/env node (function() { var Dependument = require('dependument').Dependument; var d = new Dependument({ source: 'package.json', output: 'DEPENDENCIES.md' }); d.process(); })();
Add declaration to top of script
Add declaration to top of script
JavaScript
unlicense
dependument/dependument-cli
--- +++ @@ -1,3 +1,5 @@ +#!/usr/bin/env node + (function() { var Dependument = require('dependument').Dependument;
aab3854d6cfee4ee909cb79fc333cda60da850af
index.js
index.js
const RunPluginScriptCommand = require('./src/commands/runPluginScript') const CreateProjectCommand = require('./src/commands/createProject') const AddPluginsCommand = require('./src/commands/addPlugins') const RemovePluginsCommand = require('./src/commands/removePlugins') const UpdatePluginsCommand = require('./src/commands/updatePlugins') const GenerateCommand = require('./src/commands/generate') const CommitCommand = require('./src/commands/commit') const ReleaseCommand = require('./src/commands/release') const AssembleCommand = require('./src/commands/assemble') const commands = [ RunPluginScriptCommand, CreateProjectCommand, AddPluginsCommand, RemovePluginsCommand, UpdatePluginsCommand, GenerateCommand, CommitCommand, AssembleCommand, ReleaseCommand, ] const runCommand = (commandName, argv, params, options) => { const Command = commands.find(command => command.commandName === commandName) if (!Command) { throw new Error('Can\'t find command') } const command = new Command(argv, options) command.init() return command.run(params) } module.exports = { runCommand, }
const RunPluginScriptCommand = require('./src/commands/runPluginScript') const CreateProjectCommand = require('./src/commands/createProject') const AddPluginsCommand = require('./src/commands/addPlugins') const RemovePluginsCommand = require('./src/commands/removePlugins') const UpdatePluginsCommand = require('./src/commands/updatePlugins') const GenerateCommand = require('./src/commands/generate') const CommitCommand = require('./src/commands/commit') const ReleaseCommand = require('./src/commands/release') const AssembleCommand = require('./src/commands/assemble') const commands = [ RunPluginScriptCommand, CreateProjectCommand, AddPluginsCommand, RemovePluginsCommand, UpdatePluginsCommand, GenerateCommand, CommitCommand, AssembleCommand, ReleaseCommand, ] const runCommand = (commandName, argv, params, options) => { const Command = commands.find(command => command.commandName === commandName) if (!Command) { throw new Error('Can\'t find command') } const command = new Command(argv, options) return command.run(params) } module.exports = { runCommand, }
Remove init in public api
Remove init in public api
JavaScript
mit
rispa-io/rispa-cli
--- +++ @@ -27,8 +27,6 @@ } const command = new Command(argv, options) - command.init() - return command.run(params) }
8adef8bff6e8a192a0a06388f3f4213bbf0e13a0
index.js
index.js
'use strict' const http = require('http') const express = require('express') const bodyParser = require('body-parser') const Bot = require('messenger-bot') let bot = new Bot({ token: process.env.PAGE_TOKEN, verify: 'VERIFY_TOKEN', app_secret: 'APP_SECRET' }) bot.on('error', (err) => { console.log(err.message) }) bot.on('message', (payload, reply) => { let text = payload.message.text bot.getProfile(payload.sender.id, (err, profile) => { if (err) throw err reply({ text }, (err) => { if (err) throw err console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`) }) }) }) let app = express() app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.get('/', (req, res) => { return bot._verify(req, res) }) app.post('/', (req, res) => { bot._handleMessage(req.body) res.end(JSON.stringify({ status: 'ok' })) }) http.createServer(app).listen(3000)
'use strict' const http = require('http') const express = require('express') const bodyParser = require('body-parser') const Bot = require('messenger-bot') let bot = new Bot({ token: process.env.PAGE_TOKEN, verify: 'VERIFY_TOKEN', app_secret: 'APP_SECRET' }) bot.on('error', (err) => { console.log(err.message) }) bot.on('message', (payload, reply) => { let text = payload.message.text bot.getProfile(payload.sender.id, (err, profile) => { if (err) throw err reply({ text }, (err) => { if (err) throw err console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`) }) }) }) let app = express() app.set('port', process.env.PORT || 8080); app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.get('/', (req, res) => { return bot._verify(req, res) }) app.post('/', (req, res) => { bot._handleMessage(req.body) res.end(JSON.stringify({ status: 'ok' })) }) app.listen(app.get('port'), () => { console.log('Node app is running on port', app.get('port')); });
Add message for starting the server
Add message for starting the server
JavaScript
mit
nikolay-radkov/ebudgie-server,nikolay-radkov/ebudgie-server
--- +++ @@ -29,6 +29,7 @@ }) let app = express() +app.set('port', process.env.PORT || 8080); app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ @@ -44,4 +45,6 @@ res.end(JSON.stringify({ status: 'ok' })) }) -http.createServer(app).listen(3000) +app.listen(app.get('port'), () => { + console.log('Node app is running on port', app.get('port')); +});
4b68f23939190a878e3a8e45bad2145b0cbf285f
index.js
index.js
var excludeMethods = [ /^constructor$/, /^render$/, /^component[A-Za-z]+$/ ]; var displayNameReg = /^function\s+([a-zA-Z]+)/; function isExcluded(methodName) { return excludeMethods.some(function (reg) { return reg.test(methodName) === false; }); } function bindToClass(scope, methods) { var componentName = scope.constructor.toString().match(displayNameReg)[1]; methods = Array.isArray(methods) ? methods : []; methods.forEach(function(methodName) { if (methodName in scope) { scope[methodName] = scope[methodName].bind(scope); } else { throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"'); } }); // for debugging purposes only? // if (process.env.NODE_ENV != 'production') { if (Object.getOwnPropertyNames) { var proto = scope.constructor.prototype; Object.getOwnPropertyNames(proto).forEach(function(methodName) { var original = scope[methodName]; if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) { scope[methodName] = function () { // test whether the scope is different if (this !== scope) { var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!'; console.error(e); } return original.apply(scope, arguments); }; } }); } // } } module.exports = bindToClass;
var excludeMethods = [ /^constructor$/, /^render$/, /^component[A-Za-z]+$/, /^shouldComponentUpdate$/ ]; var displayNameReg = /^function\s+([a-zA-Z]+)/; function isExcluded(methodName) { return excludeMethods.some(function (reg) { return reg.test(methodName) === false; }); } function bindToClass(scope, methods) { var componentName = scope.constructor.toString().match(displayNameReg)[1]; methods = Array.isArray(methods) ? methods : []; methods.forEach(function(methodName) { if (methodName in scope) { scope[methodName] = scope[methodName].bind(scope); } else { throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"'); } }); // for debugging purposes only? // if (process.env.NODE_ENV != 'production') { if (Object.getOwnPropertyNames) { var proto = scope.constructor.prototype; Object.getOwnPropertyNames(proto).forEach(function(methodName) { var original = scope[methodName]; if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) { scope[methodName] = function () { // test whether the scope is different if (this !== scope) { var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!'; console.error(e); } return original.apply(scope, arguments); }; } }); } // } } module.exports = bindToClass;
Add shouldComponentUpdate to excludeMethods array.
Add shouldComponentUpdate to excludeMethods array.
JavaScript
mit
nemisj/react-bind-to-class
--- +++ @@ -1,7 +1,8 @@ var excludeMethods = [ /^constructor$/, /^render$/, - /^component[A-Za-z]+$/ + /^component[A-Za-z]+$/, + /^shouldComponentUpdate$/ ]; var displayNameReg = /^function\s+([a-zA-Z]+)/;
a1ef61ffd7d55bbbcd5bc3db2dbe50578b09b1a1
index.js
index.js
var isArray = require('isArray'); /** * Returns the maximum array depth of the array, meaning the maximum number of nests in the nested arrays. * @param {Anything} array The array to find the dimensionality of * @param {Boolean} shallowSearch If the search should *not* search all element * @return {Integer} The dimensionality of the array */ function dimensionality (array, shallowSearch) { var dimensions = 0; if (isArray(array)) { if (shallowSearch) { dimensions = 1 + dimensionality(array[0], shallowSearch); } else { dimensions = 1 + array.reduce(function (a, b) { return Math.max(dimensionality(a), dimensionality(b)); }, 0); } } return dimensions; } module.exports = dimensionality;
var isArray = require('isarray'); /** * Returns the maximum array depth of the array, meaning the maximum number of nests in the nested arrays. * @param {Anything} array The array to find the dimensionality of * @param {Boolean} shallowSearch If the search should *not* search all element * @return {Integer} The dimensionality of the array */ function dimensionality (array, shallowSearch) { var dimensions = 0; if (isArray(array)) { if (shallowSearch) { dimensions = 1 + dimensionality(array[0], shallowSearch); } else { dimensions = 1 + array.reduce(function (a, b) { return Math.max(dimensionality(a), dimensionality(b)); }, 0); } } return dimensions; } module.exports = dimensionality;
Fix casing of require('isarray') for cross-platform compatibility
Fix casing of require('isarray') for cross-platform compatibility
JavaScript
mit
grant/dimensionality
--- +++ @@ -1,4 +1,4 @@ -var isArray = require('isArray'); +var isArray = require('isarray'); /** * Returns the maximum array depth of the array, meaning the maximum number of nests in the nested arrays.
d0643b62badc45f85a358a6bdec4a2408325fe27
index.js
index.js
var once = require('once'); module.exports = function () { var collections = [].slice.call(arguments); if(!Array.isArray(collections[0])) { collections = [ collections ]; } return Promise.all( collections.map(function(plugins) { var i = -1; return new Promise(function(resolve, reject){ var next = function(data) { var result, done; if (++i < plugins.length) { done = once(function(err, data){ if(err) { reject(err); } else { next(data); } }); result = plugins[i](data, done); if(typeof result.then == 'function') { result.then(function(data){ done(null, data); }, done); } } else { resolve(data); } }; next([]); }); }) ); };
var once = require('once'); module.exports = function () { var collections = [].slice.call(arguments); if(!Array.isArray(collections[0])) { collections = [ collections ]; } return Promise.all( collections.map(function(plugins) { var i = -1; return new Promise(function(resolve, reject){ var next = function(data) { var result, done; if (++i < plugins.length) { done = once(function(err, data){ if(err) { reject(err); } else { next(data); } }); result = plugins[i](data, done); if(result && typeof result.then == 'function') { result.then(function(data){ done(null, data); }, done); } } else { resolve(data); } }; next([]); }); }) ); };
Fix can not read property of undefined error
Fix can not read property of undefined error
JavaScript
mit
erickmerchant/static-engine
--- +++ @@ -35,7 +35,7 @@ result = plugins[i](data, done); - if(typeof result.then == 'function') { + if(result && typeof result.then == 'function') { result.then(function(data){
b411f030dd296756fb77cd50b64ae1a7649dadb7
index.js
index.js
/*jslint indent: 2, vars: true */ var es = require('event-stream'); var gutil = require('gulp-util'); var Buffer = require('buffer').Buffer; var cheerio = require('cheerio'); function modify(elem, attr, modifier) { "use strict"; var val = elem.attr(attr); if (val) { elem.attr(attr, modifier(val)); } } module.exports = function (query, modifier) { "use strict"; var queryHtml = function (file) { if (file.isNull()) { return this.emit('data', file); } // pass along if (file.isStream()) { return this.emit('error', new Error("gulp-coffee: Streaming not supported")); } var str = file.contents.toString('utf8'); var $ = cheerio.load(str); $(query).each(function () { var elem = $(this); modify(elem, 'href', modifier); modify(elem, 'src', modifier); }); file.contents = new Buffer($.root().html()); this.emit('data', file); }; return es.through(queryHtml); };
/*jslint indent: 2, vars: true */ var es = require('event-stream'); var gutil = require('gulp-util'); var Buffer = require('buffer').Buffer; var cheerio = require('cheerio'); function modify(file, elem, attr, modifier) { "use strict"; var val = elem.attr(attr); if (val) { elem.attr(attr, modifier(val, file)); } } module.exports = function (query, modifier) { "use strict"; var queryHtml = function (file) { if (file.isNull()) { return this.emit('data', file); } // pass along if (file.isStream()) { return this.emit('error', new Error("gulp-coffee: Streaming not supported")); } var str = file.contents.toString('utf8'); var $ = cheerio.load(str); $(query).each(function () { var elem = $(this); modify(file, elem, 'href', modifier); modify(file, elem, 'src', modifier); }); file.contents = new Buffer($.root().html()); this.emit('data', file); }; return es.through(queryHtml); };
Add file as second param
Add file as second param
JavaScript
mit
othree/gulp-path-modifier
--- +++ @@ -5,11 +5,11 @@ var cheerio = require('cheerio'); -function modify(elem, attr, modifier) { +function modify(file, elem, attr, modifier) { "use strict"; var val = elem.attr(attr); - if (val) { elem.attr(attr, modifier(val)); } + if (val) { elem.attr(attr, modifier(val, file)); } } module.exports = function (query, modifier) { @@ -24,8 +24,8 @@ $(query).each(function () { var elem = $(this); - modify(elem, 'href', modifier); - modify(elem, 'src', modifier); + modify(file, elem, 'href', modifier); + modify(file, elem, 'src', modifier); }); file.contents = new Buffer($.root().html());
475a2c1ed04a08a93196a9d809da3f3181d9d04e
index.js
index.js
'use strict' var visit = require('unist-util-visit') var toString = require('nlcst-to-string') var posjs = require('pos') module.exports = pos var tagger = new posjs.Tagger() function pos() { return transformer } function transformer(tree) { var queue = [] visit(tree, 'WordNode', visitor) /* Gather a parent if not already gathered. */ function visitor(node, index, parent) { if (parent && queue.indexOf(parent) === -1) { queue.push(parent) one(parent) } } /* Patch all words in `parent`. */ function one(node) { var children = node.children var length = children.length var index = -1 var values = [] var words = [] var child var tags while (++index < length) { child = children[index] if (child.type === 'WordNode') { values.push(toString(child)) words.push(child) } } tags = tagger.tag(values) index = -1 length = tags.length while (++index < length) { patch(words[index], tags[index][1]) } } // Patch a `partOfSpeech` property on `node`s. function patch(node, tag) { var data = node.data || (node.data = {}) data.partOfSpeech = tag } }
'use strict' var visit = require('unist-util-visit') var toString = require('nlcst-to-string') var posjs = require('pos') module.exports = pos var tagger = new posjs.Tagger() function pos() { return transformer } function transformer(tree) { visit(tree, 'SentenceNode', visitor) // Patch all words in `parent`. function visitor(node) { var children = node.children var length = children.length var index = -1 var values = [] var words = [] var child var tags // Find words. while (++index < length) { child = children[index] if (child.type === 'WordNode') { values.push(toString(child)) words.push(child) } } // Apply tags if there are words. if (values.length !== 0) { tags = tagger.tag(values) length = tags.length index = -1 while (++index < length) { patch(words[index], tags[index][1]) } } // Don’t enter sentences. return visit.SKIP } // Patch a `partOfSpeech` property on `node`s. function patch(node, tag) { var data = node.data || (node.data = {}) data.partOfSpeech = tag } }
Refactor algorithm to perform better
Refactor algorithm to perform better
JavaScript
mit
wooorm/retext-pos
--- +++ @@ -13,20 +13,10 @@ } function transformer(tree) { - var queue = [] + visit(tree, 'SentenceNode', visitor) - visit(tree, 'WordNode', visitor) - - /* Gather a parent if not already gathered. */ - function visitor(node, index, parent) { - if (parent && queue.indexOf(parent) === -1) { - queue.push(parent) - one(parent) - } - } - - /* Patch all words in `parent`. */ - function one(node) { + // Patch all words in `parent`. + function visitor(node) { var children = node.children var length = children.length var index = -1 @@ -35,6 +25,7 @@ var child var tags + // Find words. while (++index < length) { child = children[index] @@ -44,13 +35,19 @@ } } - tags = tagger.tag(values) - index = -1 - length = tags.length + // Apply tags if there are words. + if (values.length !== 0) { + tags = tagger.tag(values) + length = tags.length + index = -1 - while (++index < length) { - patch(words[index], tags[index][1]) + while (++index < length) { + patch(words[index], tags[index][1]) + } } + + // Don’t enter sentences. + return visit.SKIP } // Patch a `partOfSpeech` property on `node`s.
b75755f3de66305458831e283e65bfc7edaac088
app/assets/javascripts/project-gallery.js
app/assets/javascripts/project-gallery.js
/* Launches project gallery lightbox from button on project show pages */ $("#launch-gallery").on("click", function(event) { event.preventDefault(); $("#project-gallery .image:first-child > img").trigger("click"); });
/* Launches project gallery lightbox from button on project show pages */ $("#launch-gallery").on("click", function(event) { event.preventDefault(); document.getElementById('project-gallery').querySelector('.image').click(); });
Fix ordering issue when launching lightgallery from the button
Fix ordering issue when launching lightgallery from the button
JavaScript
agpl-3.0
awesomefoundation/awesomebits,awesomefoundation/awesomebits,awesomefoundation/awesomebits,awesomefoundation/awesomebits,awesomefoundation/awesomebits
--- +++ @@ -2,5 +2,5 @@ $("#launch-gallery").on("click", function(event) { event.preventDefault(); - $("#project-gallery .image:first-child > img").trigger("click"); + document.getElementById('project-gallery').querySelector('.image').click(); });
c246eff923c49175bda78b217e86d76371041cf2
imports/ldap/transformUser.js
imports/ldap/transformUser.js
let _ = require('underscore'); module.exports = function (ldapSettings, userData) { let searchDn = ldapSettings.searchDn || 'cn'; // userData.mail may be a string with one mail address or an array. // Nevertheless we are only interested in the first mail address here - if there should be more... let tmpEMail = userData.mail; if (Array.isArray(userData.mail)) { tmpEMail = userData.mail[0]; } let tmpEMailArray = [{ address: tmpEMail, verified: true, fromLDAP: true }]; let user = { createdAt: new Date(), emails: tmpEMailArray, username: userData[searchDn], profile: _.pick(userData, _.without(ldapSettings.whiteListedFields, 'mail')) }; // copy over the LDAP user's long name from "cn" field to the meteor accounts long name field if (user.profile.cn) { user.profile.name = user.profile.cn; delete user.profile.cn; } if (userData.isInactive) { user.isInactive = true; } return user; };
let _ = require('underscore'); module.exports = function (ldapSettings, userData) { let searchDn = ldapSettings.searchDn || 'cn'; // userData.mail may be a string with one mail address or an array. // Nevertheless we are only interested in the first mail address here - if there should be more... let tmpEMail = userData.mail; if (Array.isArray(userData.mail)) { tmpEMail = userData.mail[0]; } let tmpEMailArray = [{ address: tmpEMail, verified: true, fromLDAP: true }]; let user = { createdAt: new Date(), emails: tmpEMailArray, username: userData[searchDn].toLowerCase(), profile: _.pick(userData, _.without(ldapSettings.whiteListedFields, 'mail')) }; // copy over the LDAP user's long name from "cn" field to the meteor accounts long name field if (user.profile.cn) { user.profile.name = user.profile.cn; delete user.profile.cn; } if (userData.isInactive) { user.isInactive = true; } return user; };
Make sure the username is lower case when imported from ldap
Make sure the username is lower case when imported from ldap Otherwise the meteor accounts package cannot find the user document which leads to errors when logging in with an username that has upper case letters
JavaScript
mit
RobNeXX/4minitz,RobNeXX/4minitz,4minitz/4minitz,4minitz/4minitz,Huggle77/4minitz,Huggle77/4minitz,RobNeXX/4minitz,4minitz/4minitz,Huggle77/4minitz
--- +++ @@ -17,7 +17,7 @@ let user = { createdAt: new Date(), emails: tmpEMailArray, - username: userData[searchDn], + username: userData[searchDn].toLowerCase(), profile: _.pick(userData, _.without(ldapSettings.whiteListedFields, 'mail')) }; // copy over the LDAP user's long name from "cn" field to the meteor accounts long name field
223d7bfa811075c03ec196e4e14302048ad3919b
test/specs/test-utils.js
test/specs/test-utils.js
/*! resol-vbus | Copyright (c) 2013-2014, Daniel Wippermann | MIT license */ 'use strict'; var _ = require('lodash'); var Q = require('q'); var testUtils = { performAsyncTest: function(done, callback) { return Q.fcall(callback).then(function() { done(); }).fail(function(reason) { done(reason); }); }, expectPromise: function(promise) { expect(promise).to.be.an('object'); expect(promise).to.have.a.property('then').that.is.a('function'); return promise; }, expectRanges: function(ranges) { expect(ranges).a('array'); var comparableRanges = _.map(ranges, function(range) { return { minTimestamp: range.minTimestamp.toISOString(), maxTimestamp: range.maxTimestamp.toISOString(), }; }); return expect(comparableRanges); }, }; module.exports = testUtils;
/*! resol-vbus | Copyright (c) 2013-2014, Daniel Wippermann | MIT license */ 'use strict'; var _ = require('lodash'); var Q = require('q'); var testUtils = { performAsyncTest: function(done, callback) { return Q.fcall(callback).then(function() { done(); }).fail(function(reason) { done(reason); }); }, expectPromise: function(promise) { expect(promise).to.be.an('object'); expect(promise).to.have.a.property('then').that.is.a('function'); return promise; }, expectRanges: function(ranges) { expect(ranges).a('array'); var comparableRanges = _.map(ranges, function(range) { return { minTimestamp: range.minTimestamp.toISOString(), maxTimestamp: range.maxTimestamp.toISOString(), }; }); return expect(comparableRanges); }, adaptTimeout: function(timeout) { var factor = process.env.TRAVIS ? 1000 : 1; return timeout * factor; }, }; module.exports = testUtils;
Add `adaptTimeout` helper that changes timeouts during Travis test.
Add `adaptTimeout` helper that changes timeouts during Travis test.
JavaScript
mit
danielwippermann/resol-vbus,Thorsten71/resol-vbus
--- +++ @@ -37,6 +37,11 @@ return expect(comparableRanges); }, + adaptTimeout: function(timeout) { + var factor = process.env.TRAVIS ? 1000 : 1; + return timeout * factor; + }, + };
684daa5fcc92e8347374678fe008faf3a4744763
public/javascripts/forum-post.js
public/javascripts/forum-post.js
var oldContents = null; var editForumPost = function(postId, postNumber) { var postSelector = $("#" + postNumber); // We grab the text element of the post and turn it into a textarea to make it editable oldContents = postSelector.find(".message") var postContents = oldContents.text(); var editForm = $('<form>', { id: 'post-edit-form-' + postNumber, method: 'POST', action:"/forum/post/" + postId }); var formTextArea = $('<textarea>', {id:'post-edit-area-' + postNumber, name:"changes", class:'edit-post-box'}); formTextArea.text(postContents); var formSubmitButton = $('<input>', {type:'submit', value: 'Submit'}); var formCancelButton = $('<a>', {'data-icon':'s', onclick:'cancelEdit(' + postNumber + ')' }).text("Cancel"); editForm.append(formTextArea); editForm.append(formSubmitButton); editForm.append(formCancelButton); oldContents.replaceWith(editForm); $("#edit-button-" + postNumber).hide(); }; var cancelEdit = function(postNumber) { $('#post-edit-form-' + postNumber).replaceWith(oldContents); $("#edit-button-" + postNumber).show(); }
// Map of old post contents by post number in case the user clicks 'edit' on multiple posts // on the same page (although rare.) var oldContents = {}; var editForumPost = function(postId, postNumber) { var postSelector = $("#" + postNumber); // We grab the text element of the post and turn it into a textarea to make it editable oldContents[postNumber] = postSelector.find(".message"); var old = oldContents[postNumber]; var postContents = old.text(); var editForm = $('<form>', { id: 'post-edit-form-' + postNumber, method: 'POST', action:"/forum/post/" + postId }); var formTextArea = $('<textarea>', {id:'post-edit-area-' + postNumber, name:"changes", class:'edit-post-box'}); formTextArea.text(postContents); var formSubmitButton = $('<input>', {type:'submit', value: 'Submit'}); var formCancelButton = $('<a>', {'data-icon':'s', onclick:'cancelEdit(' + postNumber + ')' }).text("Cancel"); editForm.append(formTextArea); editForm.append(formSubmitButton); editForm.append(formCancelButton); old.replaceWith(editForm); $("#edit-button-" + postNumber).hide(); }; var cancelEdit = function(postNumber) { $('#post-edit-form-' + postNumber).replaceWith(oldContents[postNumber]); $("#edit-button-" + postNumber).show(); }
Fix issue when edit is clicked on more than one post and then cancelled on both.
Fix issue when edit is clicked on more than one post and then cancelled on both.
JavaScript
agpl-3.0
clarkerubber/lila,arex1337/lila,arex1337/lila,clarkerubber/lila,arex1337/lila,arex1337/lila,arex1337/lila,clarkerubber/lila,luanlv/lila,luanlv/lila,luanlv/lila,clarkerubber/lila,luanlv/lila,arex1337/lila,luanlv/lila,luanlv/lila,luanlv/lila,arex1337/lila,clarkerubber/lila,clarkerubber/lila,clarkerubber/lila
--- +++ @@ -1,13 +1,17 @@ -var oldContents = null; +// Map of old post contents by post number in case the user clicks 'edit' on multiple posts +// on the same page (although rare.) +var oldContents = {}; var editForumPost = function(postId, postNumber) { var postSelector = $("#" + postNumber); // We grab the text element of the post and turn it into a textarea to make it editable - oldContents = postSelector.find(".message") + oldContents[postNumber] = postSelector.find(".message"); - var postContents = oldContents.text(); + var old = oldContents[postNumber]; + + var postContents = old.text(); var editForm = $('<form>', { id: 'post-edit-form-' + postNumber, @@ -25,13 +29,13 @@ editForm.append(formSubmitButton); editForm.append(formCancelButton); - oldContents.replaceWith(editForm); + old.replaceWith(editForm); $("#edit-button-" + postNumber).hide(); }; var cancelEdit = function(postNumber) { - $('#post-edit-form-' + postNumber).replaceWith(oldContents); + $('#post-edit-form-' + postNumber).replaceWith(oldContents[postNumber]); $("#edit-button-" + postNumber).show(); }
a84b191d71cef5d4a5f68c2da3dcc32c33e10351
js/yt-player.js
js/yt-player.js
$('.close-modal').click(function () { $('#yt-player').hide(); $('#yt-player iframe').attr("src", jQuery("#yt-player iframe").attr("src")); });
jQuery(document).bind('hidden.bs.modal', function() { var vid = jQuery('#monologueForThree iframe[src*="youtube"]'); if ( vid.length > 0 ){ var src = vid.attr('src'); vid.attr('src', ''); vid.attr('src', src); } });
Fix issue with 2 embed modals interferring with YouTube close
fix: Fix issue with 2 embed modals interferring with YouTube close
JavaScript
mit
DeltaSpark/deltaspark.github.io,DeltaSpark/deltaspark.github.io
--- +++ @@ -1,4 +1,8 @@ -$('.close-modal').click(function () { - $('#yt-player').hide(); - $('#yt-player iframe').attr("src", jQuery("#yt-player iframe").attr("src")); +jQuery(document).bind('hidden.bs.modal', function() { + var vid = jQuery('#monologueForThree iframe[src*="youtube"]'); + if ( vid.length > 0 ){ + var src = vid.attr('src'); + vid.attr('src', ''); + vid.attr('src', src); + } });
6f4da9a8dfc46f760d9116f53eb137e6554377e9
src/effects/animated-selector.js
src/effects/animated-selector.js
define([ "../core", "../selector", "../effects", ], function( jQuery ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; });
define([ "../core", "../selector", "../effects" ], function( jQuery ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; });
Remove trailing comma in define array. Close gh-1336.
Remove trailing comma in define array. Close gh-1336.
JavaScript
mit
quiaro/request-agent,jquery/jquery,rwaldron/jquery,eburgos/jquery,roytoo/jquery,roytoo/jquery,eburgos/jquery,eburgos/jquery,rwaldron/jquery,roytoo/jquery,jquery/jquery,jquery/jquery
--- +++ @@ -1,7 +1,7 @@ define([ "../core", "../selector", - "../effects", + "../effects" ], function( jQuery ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) {
bc21e2861d12c0c4174a68610a1b94bcfb2c0f7d
config/routes.js
config/routes.js
module.exports.routes = { 'post /register': 'UserController.create', 'post /logout': 'AuthController.logout', 'post /auth/local': 'AuthController.callback', 'post /auth/local/:action': 'AuthController.callback', 'post /auth/:provider/:action': 'AuthController.callback', 'get /auth/:provider': 'AuthController.provider', 'get /auth/:provider/callback': 'AuthController.callback', 'get /auth/:provider/:action': 'AuthController.callback' };
module.exports.routes = { 'post /register': 'UserController.create', 'post /logout': 'AuthController.logout', 'post /auth/local': 'AuthController.callback', 'post /auth/local/:action': 'AuthController.callback', 'post /auth/:provider': 'AuthController.callback', 'post /auth/:provider/:action': 'AuthController.callback', 'get /auth/:provider': 'AuthController.provider', 'get /auth/:provider/callback': 'AuthController.callback', 'get /auth/:provider/:action': 'AuthController.callback' };
Add new Delegated Authentication Protocol
Add new Delegated Authentication Protocol Add new simpler POST route to support delegated authentication, which utilises a default action.
JavaScript
mit
tjwebb/sails-auth,danielsharvey/sails-auth,onlyurei/sails-auth,langateam/sails-auth
--- +++ @@ -5,6 +5,7 @@ 'post /auth/local': 'AuthController.callback', 'post /auth/local/:action': 'AuthController.callback', + 'post /auth/:provider': 'AuthController.callback', 'post /auth/:provider/:action': 'AuthController.callback', 'get /auth/:provider': 'AuthController.provider',
d6d356c9382b2bc2efe5e278fc831892f5312983
examples/babel/destructuring-assignment/index.js
examples/babel/destructuring-assignment/index.js
#!/usr/bin/env babel-node import assert from 'assert'; function getObj() { return { x: 2, y: 3 }; } let { x, y, z = 6 } = getObj(); assert.strictEqual(x, 2); assert.strictEqual(y, 3); assert.strictEqual(z, 6);
#!/usr/bin/env babel-node import assert from 'assert'; // // 分割代入内で代入ができる // function getObj() { return { x: 2, y: 3 }; } let { x, y, z = 6 } = getObj(); assert.strictEqual(x, 2); assert.strictEqual(y, 3); assert.strictEqual(z, 6); // // 別変数名で展開できる // function stringifyObj({ x: xVar, y: yVar }) { return xVar + yVar; } assert.strictEqual(stringifyObj({ x: 'foo', y: 'bar' }), 'foobar');
Update a sample of ES6
Update a sample of ES6
JavaScript
mit
kjirou/nodejs-codes
--- +++ @@ -3,6 +3,9 @@ import assert from 'assert'; +// +// 分割代入内で代入ができる +// function getObj() { return { x: 2, @@ -16,7 +19,15 @@ z = 6 } = getObj(); - assert.strictEqual(x, 2); assert.strictEqual(y, 3); assert.strictEqual(z, 6); + + +// +// 別変数名で展開できる +// +function stringifyObj({ x: xVar, y: yVar }) { + return xVar + yVar; +} +assert.strictEqual(stringifyObj({ x: 'foo', y: 'bar' }), 'foobar');
382b2099940ec2bf42646ff1f01a9f5005e5d52a
route-styles.js
route-styles.js
/** * Created by Zack Boman on 1/31/14. * http://www.zackboman.com or tennisgent@gmail.com */ (function(){ var mod = angular.module('routeStyles', ['ngRoute']); mod.directive('head', ['$rootScope','$compile', function($rootScope, $compile){ return { restrict: 'E', link: function(scope, elem){ var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" >'; elem.append($compile(html)(scope)); scope.routeStyles = {}; $rootScope.$on('$routeChangeStart', function (e, next, current) { if(current && current.$$route && current.$$route.css){ if(!Array.isArray(current.$$route.css)){ current.$$route.css = [current.$$route.css]; } angular.forEach(current.$$route.css, function(sheet){ scope.routeStyles[sheet] = undefined; }); } if(next && next.$$route && next.$$route.css){ if(!Array.isArray(next.$$route.css)){ next.$$route.css = [next.$$route.css]; } angular.forEach(next.$$route.css, function(sheet){ if (angular.isFunction(sheet)){ sheet = sheet(next.params); } scope.routeStyles[sheet] = sheet; }); } }); } }; } ]); })();
/** * Created by Zack Boman on 1/31/14. * http://www.zackboman.com or tennisgent@gmail.com */ 'use strict'; (function(){ var mod = angular.module('routeStyles', ['ngRoute']); mod.directive('head', ['$rootScope','$compile', function($rootScope, $compile){ return { restrict: 'E', link: function(scope, elem){ var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" >'; elem.append($compile(html)(scope)); scope.routeStyles = {}; $rootScope.$on('$routeChangeStart', function (e, next) { if(next && next.$$route && next.$$route.css){ if(!Array.isArray(next.$$route.css)){ next.$$route.css = [next.$$route.css]; } angular.forEach(next.$$route.css, function(sheet){ scope.routeStyles[sheet] = sheet; }); } }); $rootScope.$on('$routeChangeSuccess', function(e, current, previous) { if (previous && previous.$$route && previous.$$route.css) { if (!Array.isArray(previous.$$route.css)) { previous.$$route.css = [previous.$$route.css]; } angular.forEach(previous.$$route.css, function (sheet) { scope.routeStyles[sheet] = undefined; }); } }); } }; } ]); })();
Switch to use two separate events instead of the single event to prevent the CSS transition problem.
Switch to use two separate events instead of the single event to prevent the CSS transition problem.
JavaScript
mit
freedomdebug/angular-route-styles,elantion/angular-route-styles,freedomdebug/angular-route-styles,elantion/angular-route-styles,tennisgent/angular-route-styles
--- +++ @@ -2,6 +2,8 @@ * Created by Zack Boman on 1/31/14. * http://www.zackboman.com or tennisgent@gmail.com */ + +'use strict'; (function(){ @@ -15,24 +17,23 @@ var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" >'; elem.append($compile(html)(scope)); scope.routeStyles = {}; - $rootScope.$on('$routeChangeStart', function (e, next, current) { - if(current && current.$$route && current.$$route.css){ - if(!Array.isArray(current.$$route.css)){ - current.$$route.css = [current.$$route.css]; - } - angular.forEach(current.$$route.css, function(sheet){ - scope.routeStyles[sheet] = undefined; - }); - } + $rootScope.$on('$routeChangeStart', function (e, next) { if(next && next.$$route && next.$$route.css){ if(!Array.isArray(next.$$route.css)){ next.$$route.css = [next.$$route.css]; } angular.forEach(next.$$route.css, function(sheet){ - if (angular.isFunction(sheet)){ - sheet = sheet(next.params); - } scope.routeStyles[sheet] = sheet; + }); + } + }); + $rootScope.$on('$routeChangeSuccess', function(e, current, previous) { + if (previous && previous.$$route && previous.$$route.css) { + if (!Array.isArray(previous.$$route.css)) { + previous.$$route.css = [previous.$$route.css]; + } + angular.forEach(previous.$$route.css, function (sheet) { + scope.routeStyles[sheet] = undefined; }); } });
2995bcb5fa948204d2382c2fba1275cdffbff2c9
generate.js
generate.js
const fs = require('fs'); const glob = require('glob'); const yaml = require('js-yaml'); const extendify = require('extendify'); glob("templates/*.yml", function (er, files) { const contents = files.map(f => { return yaml.safeLoad(fs.readFileSync(f, 'utf8')); }); const extend = extendify({ inPlace: false, isDeep: true }); const merged = contents.reduce(extend); console.log("Generating build/aws-stack.json"); fs.existsSync("build") || fs.mkdirSync("build"); fs.writeFileSync("build/aws-stack.yaml", yaml.safeDump(merged)); fs.writeFileSync("build/aws-stack.json", JSON.stringify(merged, null, 2)); });
const fs = require('fs'); const glob = require('glob'); const yaml = require('js-yaml'); const extendify = require('extendify'); const proc = require('child_process'); const sortOrder = [ 'AWSTemplateFormatVersion', 'Description', 'Parameters', 'Mappings', 'Conditions', 'Resources', 'Metadata', 'Outputs', ] glob("templates/*.yml", function (er, files) { const contents = files.map(f => { return yaml.safeLoad(fs.readFileSync(f, 'utf8')); }); const extend = extendify({ inPlace: false, isDeep: true }); var merged = contents.reduce(extend); var sorted = {}; // sort by a specific key order var keys = Object.keys(merged).sort(function(a,b){ return sortOrder.indexOf(a) - sortOrder.indexOf(b); }); for(var index in keys) { var key = keys[index]; sorted[key] = merged[key]; } const version = proc.execSync('git describe --tags --candidates=1'); // set a description sorted.Description = "Buildkite stack " + String(version).trim(); fs.existsSync("build") || fs.mkdirSync("build"); console.log("Generating build/aws-stack.yml"); fs.writeFileSync("build/aws-stack.yml", yaml.safeDump(sorted)); console.log("Generating build/aws-stack.json"); fs.writeFileSync("build/aws-stack.json", JSON.stringify(sorted, null, 2)); });
Sort output in build files
Sort output in build files
JavaScript
mit
buildkite/elastic-ci-stack-for-aws,holmesjr/elastic-ci-stack-for-aws,holmesjr/elastic-ci-stack-for-aws
--- +++ @@ -2,6 +2,18 @@ const glob = require('glob'); const yaml = require('js-yaml'); const extendify = require('extendify'); +const proc = require('child_process'); + +const sortOrder = [ + 'AWSTemplateFormatVersion', + 'Description', + 'Parameters', + 'Mappings', + 'Conditions', + 'Resources', + 'Metadata', + 'Outputs', +] glob("templates/*.yml", function (er, files) { const contents = files.map(f => { @@ -11,9 +23,29 @@ inPlace: false, isDeep: true }); - const merged = contents.reduce(extend); + + var merged = contents.reduce(extend); + var sorted = {}; + + // sort by a specific key order + var keys = Object.keys(merged).sort(function(a,b){ + return sortOrder.indexOf(a) - sortOrder.indexOf(b); + }); + + for(var index in keys) { + var key = keys[index]; + sorted[key] = merged[key]; + } + + const version = proc.execSync('git describe --tags --candidates=1'); + + // set a description + sorted.Description = "Buildkite stack " + String(version).trim(); + + fs.existsSync("build") || fs.mkdirSync("build"); + console.log("Generating build/aws-stack.yml"); + fs.writeFileSync("build/aws-stack.yml", yaml.safeDump(sorted)); + console.log("Generating build/aws-stack.json"); - fs.existsSync("build") || fs.mkdirSync("build"); - fs.writeFileSync("build/aws-stack.yaml", yaml.safeDump(merged)); - fs.writeFileSync("build/aws-stack.json", JSON.stringify(merged, null, 2)); + fs.writeFileSync("build/aws-stack.json", JSON.stringify(sorted, null, 2)); });
b7886cf31b0bdcd61bd96540f425a8a2aa8161aa
nails.js
nails.js
var Server = require("./server.js").Server; var Config = require("./config.js").Config; exports.nails = appRoot => { var cfg = new Config(appRoot + "/config.json"); cfg.set('appRoot', appRoot); new Server(cfg).run(); };
var path = require("path"); var Server = require("./server.js").Server; var Config = require("./config.js").Config; exports.nails = (appRoot = path.dirname(require.main.filename)) => { var cfg = new Config(appRoot + "/config.json"); cfg.set('appRoot', appRoot); new Server(cfg).run(); };
Make the appRoot param optional
Make the appRoot param optional
JavaScript
mit
ArtOfCode-/nails,ArtOfCode-/nails
--- +++ @@ -1,7 +1,8 @@ +var path = require("path"); var Server = require("./server.js").Server; var Config = require("./config.js").Config; -exports.nails = appRoot => { +exports.nails = (appRoot = path.dirname(require.main.filename)) => { var cfg = new Config(appRoot + "/config.json"); cfg.set('appRoot', appRoot); new Server(cfg).run();
8a2de05444524ba913052a1bd838fbb4aa4fbf1d
app/stores/FlashesStore.js
app/stores/FlashesStore.js
import EventEmitter from 'eventemitter3'; class FlashesStore extends EventEmitter { constructor() { super(...arguments); this.ERROR = "error"; } flash(type, message) { // See if the message is actually a GraphQL exception if(message.source && message.message) { if(message.source.errors[0] && message.source.errors[0].message) { message = message.source.errors[0].message; } else { message = "An unknown error occured"; } } this.emit("flash", { id: (new Date()).valueOf(), type: type, message: message }); } } export default new FlashesStore()
import EventEmitter from 'eventemitter3'; class FlashesStore extends EventEmitter { constructor() { super(...arguments); this.ERROR = "error"; } flash(type, message) { // See if the message is actually a GraphQL exception if(message.source && message.message) { if(message.source.errors[0] && message.source.errors[0].message) { if(message.source.type == "unknown_error") { message = "Sorry, there’s been an unexpected error and our engineers have been notified"; } else { message = message.source.errors[0].message; } } else { message = "An unknown error occured"; } } this.emit("flash", { id: (new Date()).valueOf(), type: type, message: message }); } } export default new FlashesStore()
Use a different message if GraphQL errors and we show a flash
Use a different message if GraphQL errors and we show a flash
JavaScript
mit
fotinakis/buildkite-frontend,buildkite/frontend,fotinakis/buildkite-frontend,buildkite/frontend
--- +++ @@ -10,7 +10,11 @@ // See if the message is actually a GraphQL exception if(message.source && message.message) { if(message.source.errors[0] && message.source.errors[0].message) { - message = message.source.errors[0].message; + if(message.source.type == "unknown_error") { + message = "Sorry, there’s been an unexpected error and our engineers have been notified"; + } else { + message = message.source.errors[0].message; + } } else { message = "An unknown error occured"; }
afcbfb968f872b2f1462926bcb1956d43cd9cb05
lib/util/media_ready_state_utils.js
lib/util/media_ready_state_utils.js
/** @license * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.util.MediaReadyState'); shaka.util.MediaReadyState = class { /* * @param {!HTMLMediaElement} mediaElement * @param {HTMLMediaElement.ReadyState} readyState * @param {!function()} callback */ static waitForReadyState(mediaElement, readyState, eventManager, callback) { if (readyState == HTMLMediaElement.HAVE_NOTHING || mediaElement.readyState >= readyState) { callback(); } else { const MediaReadyState = shaka.util.MediaReadyState; const eventName = MediaReadyState.READY_STATES_TO_EVENT_NAMES_.get(readyState); eventManager.listenOnce(mediaElement, eventName, callback); } } }; /** * @const {!Map.<number, string>} * @private */ shaka.util.MediaReadyState.READY_STATES_TO_EVENT_NAMES_ = new Map([ [HTMLMediaElement.HAVE_METADATA, 'loadedmetadata'], [HTMLMediaElement.HAVE_CURRENT_DATA, 'loadeddata'], [HTMLMediaElement.HAVE_FUTURE_DATA, 'canplay'], [HTMLMediaElement.HAVE_ENOUGH_DATA, 'canplaythrough'], ]);
/** @license * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.util.MediaReadyState'); goog.require('shaka.util.EventManager'); shaka.util.MediaReadyState = class { /** * @param {!HTMLMediaElement} mediaElement * @param {number} readyState * @param {shaka.util.EventManager} eventManager * @param {function()} callback */ static waitForReadyState(mediaElement, readyState, eventManager, callback) { if (readyState == HTMLMediaElement.HAVE_NOTHING || mediaElement.readyState >= readyState) { callback(); } else { const MediaReadyState = shaka.util.MediaReadyState; const eventName = MediaReadyState.READY_STATES_TO_EVENT_NAMES_.get(readyState); eventManager.listenOnce(mediaElement, eventName, callback); } } }; /** * @const {!Map.<number, string>} * @private */ shaka.util.MediaReadyState.READY_STATES_TO_EVENT_NAMES_ = new Map([ [HTMLMediaElement.HAVE_METADATA, 'loadedmetadata'], [HTMLMediaElement.HAVE_CURRENT_DATA, 'loadeddata'], [HTMLMediaElement.HAVE_FUTURE_DATA, 'canplay'], [HTMLMediaElement.HAVE_ENOUGH_DATA, 'canplaythrough'], ]);
Fix annotations in MediaReadyState util
Fix annotations in MediaReadyState util For some reason, the new compiler in the master branch let this by, but the old compiler in the v2.5.x branch complained when I cherry-picked the utility. Change-Id: I1e688f72594b74ed7d2a7c2801eb179b8ec13e8c
JavaScript
apache-2.0
shaka-project/shaka-player,tvoli/shaka-player,shaka-project/shaka-player,tvoli/shaka-player,tvoli/shaka-player,tvoli/shaka-player,shaka-project/shaka-player,shaka-project/shaka-player
--- +++ @@ -5,13 +5,16 @@ goog.provide('shaka.util.MediaReadyState'); +goog.require('shaka.util.EventManager'); + shaka.util.MediaReadyState = class { - /* - * @param {!HTMLMediaElement} mediaElement - * @param {HTMLMediaElement.ReadyState} readyState - * @param {!function()} callback - */ + /** + * @param {!HTMLMediaElement} mediaElement + * @param {number} readyState + * @param {shaka.util.EventManager} eventManager + * @param {function()} callback + */ static waitForReadyState(mediaElement, readyState, eventManager, callback) { if (readyState == HTMLMediaElement.HAVE_NOTHING || mediaElement.readyState >= readyState) {
f93e584853de62a3df9da48dbe07786dee3d098c
assets/src/components/has-minimum-story-poster-dimensions.js
assets/src/components/has-minimum-story-poster-dimensions.js
/** * Gets whether the AMP story's featured image has the right minimum dimensions. * * The featured image populates teh AMP story poster image. * The 3 minimum dimensions for that are 696px x 928px, 928px x 696px, or 928px x 928px. * * @param {Object} media A media object with width and height values. * @return {boolean} Whether the media has the minimum dimensions. */ export default ( media ) => { const largeDimension = 928; const smallDimension = 696; return ( ( media.width && media.height ) && ( media.width >= smallDimension && media.height >= smallDimension ) && ( ( media.width >= largeDimension && media.height >= largeDimension ) || ( media.width < largeDimension && media.height >= largeDimension ) || ( media.height < largeDimension && media.width >= largeDimension ) ) ); }
/** * Gets whether the AMP story's featured image has the right minimum dimensions. * * The featured image populates teh AMP story poster image. * The 3 minimum dimensions for that are 696px x 928px, 928px x 696px, or 928px x 928px. * * @param {Object} media A media object with width and height values. * @return {boolean} Whether the media has the minimum dimensions. */ export default ( media ) => { const largeDimension = 928; const smallDimension = 696; return ( ( media.width && media.height ) && ( media.width >= smallDimension && media.height >= smallDimension ) && ( ( media.width >= largeDimension && media.height >= largeDimension ) || ( media.width < largeDimension && media.height >= largeDimension ) || ( media.height < largeDimension && media.width >= largeDimension ) ) ); };
Add a semicolon to address ESLint issue
Add a semicolon to address ESLint issue This might be the cause of a failed Travis build.
JavaScript
apache-2.0
ampproject/amp-toolbox-php,ampproject/amp-toolbox-php
--- +++ @@ -19,4 +19,4 @@ ( media.height < largeDimension && media.width >= largeDimension ) ) ); -} +};
563f1a51ca73c8c50d12c8420542965770c6a28f
shared/oae/js/jquery-plugins/jquery.jeditable-focus.js
shared/oae/js/jquery-plugins/jquery.jeditable-focus.js
/*! * Copyright 2012 Sakai Foundation (SF) Licensed under the * Educational Community 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.osedu.org/licenses/ECL-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(['jquery'], function (jQuery) { (function() { /** * Catch the keypress event for `enter` when an editable field has focus */ $(document).on('focus', '.jeditable-field', function(ev) { $(this).keypress(function(ev) { if (ev.which == 13){ $(this).trigger('click.editable'); } }); }); })(); });
/*! * Copyright 2012 Sakai Foundation (SF) Licensed under the * Educational Community 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.osedu.org/licenses/ECL-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(['jquery'], function (jQuery) { (function() { /** * Catch the keypress event for `enter` and `space` when an editable field has focus */ $(document).on('focus', '.jeditable-field', function(ev) { $(this).keypress(function(ev) { if (ev.which == 13 || ev.which == 32){ ev.preventDefault(); $(this).trigger('click.editable'); } }); }); })(); });
Make the spacebar usable for inline edit
Make the spacebar usable for inline edit
JavaScript
apache-2.0
Orodan/3akai-ux-jitsi-fork,Orodan/3akai-ux-jitsi-fork,nicolaasmatthijs/3akai-ux,timdegroote/3akai-ux,jfederico/3akai-ux,timdegroote/3akai-ux,nicolaasmatthijs/3akai-ux,stuartf/3akai-ux,mrvisser/3akai-ux,Coenego/avocet-ui,stuartf/3akai-ux,stuartf/3akai-ux,jfederico/3akai-ux,Orodan/3akai-ux-jitsi-fork,jfederico/3akai-ux,simong/3akai-ux,mrvisser/3akai-ux,simong/3akai-ux,simong/3akai-ux,timdegroote/3akai-ux,Orodan/3akai-ux,Coenego/avocet-ui,mrvisser/3akai-ux,Orodan/3akai-ux,nicolaasmatthijs/3akai-ux,Orodan/3akai-ux
--- +++ @@ -17,11 +17,12 @@ (function() { /** - * Catch the keypress event for `enter` when an editable field has focus + * Catch the keypress event for `enter` and `space` when an editable field has focus */ $(document).on('focus', '.jeditable-field', function(ev) { $(this).keypress(function(ev) { - if (ev.which == 13){ + if (ev.which == 13 || ev.which == 32){ + ev.preventDefault(); $(this).trigger('click.editable'); } });
5b231c4177876cc25ed503a30c94afd7babc390d
lib/calendar.js
lib/calendar.js
var icalendar = require('icalendar'); exports.generateIcal = function(boards) { var ical = new icalendar.iCalendar(); boards.each(function(board) { board.cards().each(function(card) { // no arm, no chocolate if (!card.get('badges').due) return; var event = new icalendar.VEvent(); event.setSummary(card.get('name')); event.setDescription(card.get('description')); event.setDate(card.get('badges').due); ical.addComponent(event); }); }); return ical; }
var icalendar = require('icalendar'); exports.generateIcal = function(boards) { var ical = new icalendar.iCalendar(); boards.each(function(board) { board.cards().each(function(card) { // no arm, no chocolate if (!card.get('badges').due) return; var event = new icalendar.VEvent(); event.setSummary(card.get('name')); event.setDescription(card.get('description')); event.setDate(card.get('badges').due); event.addProperty('ATTACH', card.get('url')); ical.addComponent(event); }); }); return ical; }
Attach the URL to the event.
Attach the URL to the event. Signed-off-by: François de Metz <5187da0b934cc25eb2201a3ec9206c24b13cb23b@stormz.me>
JavaScript
agpl-3.0
francois2metz/trello-calendar,francois2metz/trello-calendar
--- +++ @@ -10,6 +10,7 @@ event.setSummary(card.get('name')); event.setDescription(card.get('description')); event.setDate(card.get('badges').due); + event.addProperty('ATTACH', card.get('url')); ical.addComponent(event); }); });
418df71223c33559cea3dc822cd16fab8c912dba
src/commands/IDBanCommand.js
src/commands/IDBanCommand.js
import BaseCommand from './BaseCommand'; /** * Simple command to ban a uaer by their ID. */ class IDBanCommand extends BaseCommand { constructor(bot) { super(bot); } /** * This event method we should listen for. * * @type {string} */ method = 'message'; /** * The pattern to match against. If the message matches this pattern then we will respond to it with the action method. * * @type {RegExp} */ pattern = /^!idban/; /** * The function that should be called when the event is fired. * * @param {Message} message */ action(action, message) { if (this.hasBypassRole(message)) { const ids = message.cleanContent.substr(7); ids.split(' ').forEach((id) => { message.guild.ban(id, 1); message.reply(`User with ID of '${id}' has been banned.`); }); } message.delete(); } } export default IDBanCommand;
import BaseCommand from './BaseCommand'; /** * Simple command to ban a uaer by their ID. */ class IDBanCommand extends BaseCommand { constructor(bot) { super(bot); } /** * This event method we should listen for. * * @type {string} */ method = 'message'; /** * The pattern to match against. If the message matches this pattern then we will respond to it with the action method. * * @type {RegExp} */ pattern = /^!idban/; /** * The function that should be called when the event is fired. * * @param {Message} message */ action(action, message) { message.delete(); if (this.hasBypassRole(message)) { const ids = message.cleanContent.substr(7); if (!ids.length) { return; } if (ids.indexOf(' ') === -1) { return; } const splitIDs = ids.split(' '); splitIDs.forEach((id) => { message.guild.ban(id, 1); message.channel.send(`User with ID of '${id}' has been banned.`); }); } } } export default IDBanCommand;
Upgrade IDBan command to do some more checking
Upgrade IDBan command to do some more checking
JavaScript
mit
ATLauncher/Discord-Bot
--- +++ @@ -28,17 +28,27 @@ * @param {Message} message */ action(action, message) { + message.delete(); + if (this.hasBypassRole(message)) { const ids = message.cleanContent.substr(7); - ids.split(' ').forEach((id) => { + if (!ids.length) { + return; + } + + if (ids.indexOf(' ') === -1) { + return; + } + + const splitIDs = ids.split(' '); + + splitIDs.forEach((id) => { message.guild.ban(id, 1); - message.reply(`User with ID of '${id}' has been banned.`); + message.channel.send(`User with ID of '${id}' has been banned.`); }); } - - message.delete(); } }
f3f7541d46624e65ff90022c8ff0e66c5da4e786
client/src/actions.js
client/src/actions.js
export const FETCH_QUEUE = 'FETCH_QUEUE' export const FETCH_QUEUE_DONE = 'FETCH_QUEUE_DONE' export const FETCH_ACCOUNTS = 'FETCH_ACCOUNTS' export const FETCH_TAGS = 'FETCH_TAGS' export const ADD_TAG = 'ADD_TAG' export const REMOVE_TAG = 'REMOVE_TAG' export function fetchQueue() { return { type: FETCH_QUEUE } } export function fetchQueueDone(queue) { return { type: FETCH_QUEUE_DONE, queue } } export function fetchAccounts() { return { type: FETCH_ACCOUNTS, } } export function fetchTags() { return { type: FETCH_TAGS } } export function addTag(account, tag) { return { type: ADD_TAG, account: account, tag: tag } } export function removeTag(account, tag) { return { type: REMOVE_TAG, account: account, tag: tag } }
export const FETCH_QUEUE = 'FETCH_QUEUE' export const FETCH_QUEUE_DONE = 'FETCH_QUEUE_DONE' export const FETCH_ACCOUNTS = 'FETCH_ACCOUNTS' export const FETCH_TAGS = 'FETCH_TAGS' export const ADD_TAG = 'ADD_TAG' export const REMOVE_TAG = 'REMOVE_TAG' export const SET_ACTIVE_DONATION = 'SET_ACTIVE_DONATION' export function fetchQueue() { return { type: FETCH_QUEUE } } export function fetchQueueDone(queue) { return { type: FETCH_QUEUE_DONE, queue } } export function fetchAccounts() { return { type: FETCH_ACCOUNTS } } export function fetchTags() { return { type: FETCH_TAGS } } export function addTag(account, tag) { return { type: ADD_TAG, account: account, tag: tag } } export function removeTag(account, tag) { return { type: REMOVE_TAG, account: account, tag: tag } } export function setActiveDonation() { return { type: SET_ACTIVE_DONATION } }
Add action to set active donation
Add action to set active donation
JavaScript
mit
rymdkraftverk/q,rymdkraftverk/q,rymdkraftverk/q
--- +++ @@ -4,6 +4,7 @@ export const FETCH_TAGS = 'FETCH_TAGS' export const ADD_TAG = 'ADD_TAG' export const REMOVE_TAG = 'REMOVE_TAG' +export const SET_ACTIVE_DONATION = 'SET_ACTIVE_DONATION' export function fetchQueue() { return { @@ -20,7 +21,7 @@ export function fetchAccounts() { return { - type: FETCH_ACCOUNTS, + type: FETCH_ACCOUNTS } } @@ -45,3 +46,9 @@ tag: tag } } + +export function setActiveDonation() { + return { + type: SET_ACTIVE_DONATION + } +}
1e4a3cf9a1db9c124f3b44aaf9e55f40e9073ee5
ui/server/proxies/api.js
ui/server/proxies/api.js
'use strict'; // Issue to improve: https://github.com/hashicorp/nomad/issues/7465 const proxyPath = '/v1'; module.exports = function(app, options) { // For options, see: // https://github.com/nodejitsu/node-http-proxy let proxyAddress = options.proxy; let server = options.httpServer; let proxy = require('http-proxy').createProxyServer({ target: proxyAddress, ws: true, changeOrigin: true, }); proxy.on('error', function(err, req) { // eslint-disable-next-line console.error(err, req.url); }); app.use(proxyPath, function(req, res) { // include root path in proxied request req.url = proxyPath + req.url; proxy.web(req, res, { target: proxyAddress }); }); server.on('upgrade', function(req, socket, head) { if (req.url.startsWith('/v1/client/allocation') && req.url.includes('exec?')) { req.headers.origin = proxyAddress; proxy.ws(req, socket, head, { target: proxyAddress }); } }); };
'use strict'; // Issue to improve: https://github.com/hashicorp/nomad/issues/7465 const proxyPath = '/v1'; module.exports = function(app, options) { // For options, see: // https://github.com/nodejitsu/node-http-proxy // This is probably not safe to do, but it works for now. let cacheKey = `${options.project.configPath()}|${options.environment}`; let config = options.project.configCache.get(cacheKey); // Disable the proxy completely when Mirage is enabled. No requests to the API // will be being made, and having the proxy attempt to connect to Nomad when it // is not running can result in socket max connections that block the livereload // server from reloading. if (config['ember-cli-mirage'].enabled !== false) { options.ui.writeInfoLine('Mirage is enabled. Not starting proxy'); delete options.proxy; return; } let proxyAddress = options.proxy; let server = options.httpServer; let proxy = require('http-proxy').createProxyServer({ target: proxyAddress, ws: true, changeOrigin: true, }); proxy.on('error', function(err, req) { // eslint-disable-next-line console.error(err, req.url); }); app.use(proxyPath, function(req, res) { // include root path in proxied request req.url = proxyPath + req.url; proxy.web(req, res, { target: proxyAddress }); }); server.on('upgrade', function(req, socket, head) { if (req.url.startsWith('/v1/client/allocation') && req.url.includes('exec?')) { req.headers.origin = proxyAddress; proxy.ws(req, socket, head, { target: proxyAddress }); } }); };
Disable the proxy when Mirage is enabled
Disable the proxy when Mirage is enabled This is to prevent max socket connection errors that can stop the live reload server from responding.
JavaScript
mpl-2.0
dvusboy/nomad,dvusboy/nomad,burdandrei/nomad,hashicorp/nomad,burdandrei/nomad,dvusboy/nomad,hashicorp/nomad,hashicorp/nomad,burdandrei/nomad,dvusboy/nomad,dvusboy/nomad,burdandrei/nomad,dvusboy/nomad,burdandrei/nomad,hashicorp/nomad,burdandrei/nomad,hashicorp/nomad,burdandrei/nomad,dvusboy/nomad,hashicorp/nomad
--- +++ @@ -6,6 +6,20 @@ module.exports = function(app, options) { // For options, see: // https://github.com/nodejitsu/node-http-proxy + + // This is probably not safe to do, but it works for now. + let cacheKey = `${options.project.configPath()}|${options.environment}`; + let config = options.project.configCache.get(cacheKey); + + // Disable the proxy completely when Mirage is enabled. No requests to the API + // will be being made, and having the proxy attempt to connect to Nomad when it + // is not running can result in socket max connections that block the livereload + // server from reloading. + if (config['ember-cli-mirage'].enabled !== false) { + options.ui.writeInfoLine('Mirage is enabled. Not starting proxy'); + delete options.proxy; + return; + } let proxyAddress = options.proxy;
e53197be96bbbad51af8ad91dae000e607076f6d
github/index.js
github/index.js
const fetch = require("node-fetch"); const qs = require("qs"); const { load } = require("js-yaml"); const { getInstallationToken } = require("./installation-token"); module.exports.GitHub = class GitHub { constructor (installationId) { this.installationId = installationId; } get (urlSegment) { return this.fetch("GET", urlSegment); } post (urlSegment, body) { return this.fetch("POST", urlSegment, body); } async fetch (method, urlSegment, body) { const installationToken = await getInstallationToken(this.installationId); const headers = { "User-Agent": "divmain/semver-as-a-service", "Accept": "application/vnd.github.machine-man-preview+json", "Authorization": `token ${installationToken}` }; const opts = { method, headers }; if (method === "POST") { headers["Content-Type"] = "application/json"; opts.body = body; } return fetch(`https://api.github.com${urlSegment}`, opts); } }
const fetch = require("node-fetch"); const qs = require("qs"); const { load } = require("js-yaml"); const { getInstallationToken } = require("./installation-token"); module.exports.GitHub = class GitHub { constructor (installationId) { this.installationId = installationId; } get (urlSegment) { return this.fetch("GET", urlSegment); } post (urlSegment, body) { return this.fetch("POST", urlSegment, body); } async fetch (method, urlSegment, body) { const installationToken = await getInstallationToken(this.installationId); const headers = { "User-Agent": "divmain/semver-as-a-service", "Accept": "application/vnd.github.machine-man-preview+json", "Authorization": `token ${installationToken}` }; const opts = { method, headers }; if (method === "POST") { headers["Content-Type"] = "application/json"; opts.body = body; } return fetch(`https://api.github.com${urlSegment}`, opts); } getConfig (repoPath) { return this.get(`/repos/${repoPath}/contents/.maintainerd`) .then(response => response.json()) .then(json => Buffer.from(json.content, "base64").toString()) .then(yamlString => load(yamlString, "utf8")); } }
Add GH method for retrieving maintainerd config file.
Add GH method for retrieving maintainerd config file.
JavaScript
mit
divmain/maintainerd,divmain/maintainerd
--- +++ @@ -38,4 +38,11 @@ return fetch(`https://api.github.com${urlSegment}`, opts); } + + getConfig (repoPath) { + return this.get(`/repos/${repoPath}/contents/.maintainerd`) + .then(response => response.json()) + .then(json => Buffer.from(json.content, "base64").toString()) + .then(yamlString => load(yamlString, "utf8")); + } }
ad4e2c92062dfa1ab07510afa217cae83b1866d4
index.js
index.js
/* eslint-disable global-require */ 'use strict'; const allRules = { 'no-unused-styles': require('./lib/rules/no-unused-styles'), 'no-inline-styles': require('./lib/rules/no-inline-styles'), 'no-color-literals': require('./lib/rules/no-color-literals'), 'split-platform-components': require('./lib/rules/split-platform-components'), }; function configureAsError(rules) { const result = {}; for (const key in rules) { if (!rules.hasOwnProperty(key)) { continue; } result['react-native/' + key] = 2; } return result; } const allRulesConfig = configureAsError(allRules); module.exports = { deprecatedRules: {}, rules: allRules, rulesConfig: { 'no-unused-styles': 0, 'no-inline-styles': 0, 'no-color-literals': 0, 'split-platform-components': 0, }, configs: { all: { plugin: [ 'react-native', ], parserOptions: { ecmaFeatures: { jsx: true, }, }, rules: allRulesConfig, }, }, };
/* eslint-disable global-require */ 'use strict'; const allRules = { 'no-unused-styles': require('./lib/rules/no-unused-styles'), 'no-inline-styles': require('./lib/rules/no-inline-styles'), 'no-color-literals': require('./lib/rules/no-color-literals'), 'split-platform-components': require('./lib/rules/split-platform-components'), }; function configureAsError(rules) { const result = {}; for (const key in rules) { if (!rules.hasOwnProperty(key)) { continue; } result['react-native/' + key] = 2; } return result; } const allRulesConfig = configureAsError(allRules); module.exports = { deprecatedRules: {}, rules: allRules, rulesConfig: { 'no-unused-styles': 0, 'no-inline-styles': 0, 'no-color-literals': 0, 'split-platform-components': 0, }, configs: { all: { plugins: [ 'react-native', ], parserOptions: { ecmaFeatures: { jsx: true, }, }, rules: allRulesConfig, }, }, };
Fix all config for Eslint 4
Fix all config for Eslint 4
JavaScript
mit
Intellicode/eslint-plugin-react-native
--- +++ @@ -33,7 +33,7 @@ }, configs: { all: { - plugin: [ + plugins: [ 'react-native', ], parserOptions: {
0a256cc090a1577dc9af7574351c1bf76f802c5d
build/responsive.js
build/responsive.js
const paths = require('./paths'); const fs = require('fs-extra'); const glob = require('glob'); /** * Build the breakpoint * * @param {*} breakpoint * @param {*} count */ function buildBreakpoint(breakpoint, count) { let html = `html { font-family: '${count}'; }`; return `@${breakpoint} { ${html} }\n`; } module.exports = breakpoints => { let count = 2, result = ''; for (let breakpoint in breakpoints) { result += buildBreakpoint(breakpoint, count); count++; } fs.mkdirsSync(paths.temp); fs.writeFileSync(paths.temp + '/responsive.scss', result); };
const paths = require('./paths'); const fs = require('fs-extra'); const glob = require('glob'); /** * Build the breakpoint * * @param {*} breakpoint * @param {*} count */ function buildBreakpoint(breakpoint, count) { let html = `html { font-family: '${count}'; }`; return `@${breakpoint} { ${html} }\n`; } module.exports = breakpoints => { let count = 2, result = '/* stylelint-disable */\n\n'; for (let breakpoint in breakpoints) { result += buildBreakpoint(breakpoint, count); count++; } fs.mkdirsSync(paths.temp); fs.writeFileSync(paths.temp + '/responsive.scss', result); };
Disable linting for generated file
Disable linting for generated file
JavaScript
apache-2.0
weepower/wee,weepower/wee
--- +++ @@ -16,7 +16,7 @@ module.exports = breakpoints => { let count = 2, - result = ''; + result = '/* stylelint-disable */\n\n'; for (let breakpoint in breakpoints) { result += buildBreakpoint(breakpoint, count);
f0bc01603b491f14e593cc24329c18efc2beaf40
lib/amazon/metadata-config.js
lib/amazon/metadata-config.js
// -------------------------------------------------------------------------------------------------------------------- // // metadata-config.js - config for AWS Instance Metadata // // Copyright (c) 2011, 2012 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <chilts@appsattic.com> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- function pathCategory(options, args) { return '/' + args.Version + args.Category; } function pathLatest(options, args) { return '/latest/' + args.Category; } // -------------------------------------------------------------------------------------------------------------------- // From: http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html module.exports = { 'ListApiVersions' : { // request 'path' : '/', // response 'body' : 'blob', }, 'Get' : { // request 'path' : pathCategory, 'args' : { Category : { 'required' : true, 'type' : 'special', }, Version : { 'required' : true, 'type' : 'special', }, }, // response 'body' : 'blob', }, }; // --------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------- // // metadata-config.js - config for AWS Instance Metadata // // Copyright (c) 2011, 2012 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <chilts@appsattic.com> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- function path(options, args) { return '/' + args.Version + args.Category; } // -------------------------------------------------------------------------------------------------------------------- // From: http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html module.exports = { 'ListApiVersions' : { // request 'path' : '/', // response 'extractBody' : 'blob', }, 'Get' : { // request 'path' : path, 'args' : { Category : { 'required' : true, 'type' : 'special', }, Version : { 'required' : true, 'type' : 'special', }, }, // response 'extractBody' : 'blob', }, }; // --------------------------------------------------------------------------------------------------------------------
Make sure the extractBody is set (not just body)
Make sure the extractBody is set (not just body)
JavaScript
mit
chilts/awssum
--- +++ @@ -9,12 +9,8 @@ // // -------------------------------------------------------------------------------------------------------------------- -function pathCategory(options, args) { +function path(options, args) { return '/' + args.Version + args.Category; -} - -function pathLatest(options, args) { - return '/latest/' + args.Category; } // -------------------------------------------------------------------------------------------------------------------- @@ -27,12 +23,12 @@ // request 'path' : '/', // response - 'body' : 'blob', + 'extractBody' : 'blob', }, 'Get' : { // request - 'path' : pathCategory, + 'path' : path, 'args' : { Category : { 'required' : true, @@ -44,7 +40,7 @@ }, }, // response - 'body' : 'blob', + 'extractBody' : 'blob', }, };
e40c302a81525957b523d07f287dab6bad0d4381
src/components/search_bar.js
src/components/search_bar.js
import React, { Component } from 'react' //class-based component (ES6) class SearchBar extends Component { render() { //method definition in ES6 return <input onChange={event => console.log(event.target.value)} />; } } export default SearchBar;
import React, { Component } from 'react' //class-based component (ES6) class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' } } render() { //method definition in ES6 return <input onChange={event => console.log(event.target.value)} />; } } export default SearchBar;
Initialize state in class-based component
Initialize state in class-based component
JavaScript
mit
phirefly/react-redux-starter,phirefly/react-redux-starter
--- +++ @@ -2,6 +2,12 @@ //class-based component (ES6) class SearchBar extends Component { + constructor(props) { + super(props); + + this.state = { term: '' } + } + render() { //method definition in ES6 return <input onChange={event => console.log(event.target.value)} />; }
b870cb035827f13be864ba7efd4cc7a3476130c5
grunt/yuidoc.js
grunt/yuidoc.js
module.exports = { js: { lintNatives: true, name: '<%= pkg.name %>', url: '<%= pkg.homepage %>', version: '<%= pkg.version %>', description: '<%= pkg.description %>', options: { nocode: true, paths: './src/', outdir: './build/documentation', themedir: './node_modules/yuidoc-theme-blue' } } };
module.exports = { js: { lintNatives: true, name: '<%= pkg.name %> by <%= pkg.author.name %>', url: '<%= pkg.homepage %>', version: '<%= pkg.version %>', description: '<%= pkg.description %>', options: { nocode: true, paths: './src/', outdir: './build/documentation', themedir: './node_modules/yuidoc-theme-blue' } } };
Add author information for SEO purposes
Add author information for SEO purposes
JavaScript
mit
Skelware/node-file-parser,Skelware/node-file-parser
--- +++ @@ -1,7 +1,7 @@ module.exports = { js: { lintNatives: true, - name: '<%= pkg.name %>', + name: '<%= pkg.name %> by <%= pkg.author.name %>', url: '<%= pkg.homepage %>', version: '<%= pkg.version %>', description: '<%= pkg.description %>',
76865f1c78009871ea8f0ec2e565f7b462481539
lib/bundler/loaders/static.js
lib/bundler/loaders/static.js
export default () => { return { test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/i, loader: "file", query: { name: "assets/[name]-[hash].[ext]" } }; }
export default () => { return { test: /\.(png|jpg|gif|eot|ttf|woff|woff2)$/i, loader: "file", query: { name: "assets/[name]-[hash].[ext]" } }; }
Remove svg from file-loader test pattern
Remove svg from file-loader test pattern
JavaScript
mit
kiurchv/frontend,mkyurchev/frontend,sunshine-code/frontend-cli,sunshine-code/frontend-cli
--- +++ @@ -1,6 +1,6 @@ export default () => { return { - test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/i, + test: /\.(png|jpg|gif|eot|ttf|woff|woff2)$/i, loader: "file", query: { name: "assets/[name]-[hash].[ext]" } };
43e31be248938a974944553c0152781f068f5122
public/app/accounts/accounts.js
public/app/accounts/accounts.js
angular.module('shortly.shorten', []) .controller('AccountsController', function ($scope, $window, $location, $http, Links) { // $scope.hasStripeConnectAccount = function() { // var currentUser = sessionStorage.getItem('user'); // console.log('user',currentUser); // }; $scope.authorize = function() { var currentUser = sessionStorage.getItem('user'); return $http({ method: 'POST', url: '/authorize', data: { username: currentUser, } }) .then(function (resp) { console.log(resp); $window.location.href = resp.data; }); }; $scope.stripeCallback = function (code, result) { var currentUser = sessionStorage.getItem('user'); if (result.error) { console.log('it failed! error: ' + result.error.message); } else { return $http({ method: 'POST', url: '/stripe/debit-token', data: { username: currentUser, cardToken: result.id } }) .then(function (resp) { console.log(resp); }); } }; });
angular.module('shortly.shorten', []) .controller('AccountsController', function ($scope, $window, $location, $http, Links) { /** * Handles Stripe 'Connect' button submit. * Gets Connect account creation redirect url from server and manually sets href. */ $scope.authorize = function() { var currentUser = sessionStorage.getItem('user'); return $http({ method: 'POST', url: '/authorize', data: { username: currentUser, } }) .then(function (resp) { console.log(resp); $window.location.href = resp.data; }); }; /** * On form submit, card info is sent to Stripe for processing. * Stripe returns a one time use token to stripeCallback, which passes it to server for customerId creation and saving. */ $scope.stripeCallback = function (code, result) { var currentUser = sessionStorage.getItem('user'); if (result.error) { console.log('it failed! error: ' + result.error.message); } else { return $http({ method: 'POST', url: '/stripe/debit-token', data: { username: currentUser, cardToken: result.id } }) .then(function (resp) { console.log(resp); }); } }; });
Add comments for functions that handle user account info submission
Add comments for functions that handle user account info submission
JavaScript
mit
arosenberg01/headcount,kyleshockey/headcount,Illustrious-Dirigble/headcount,kyleshockey/headcount,rockytang/headcount,rockytang/headcount,arosenberg01/headcount,henrymollman/headcount,Za1batsu/FinIt,Za1batsu/FinIt,henrymollman/headcount,Illustrious-Dirigble/headcount
--- +++ @@ -2,13 +2,10 @@ .controller('AccountsController', function ($scope, $window, $location, $http, Links) { - // $scope.hasStripeConnectAccount = function() { - - // var currentUser = sessionStorage.getItem('user'); - // console.log('user',currentUser); - - // }; - + /** + * Handles Stripe 'Connect' button submit. + * Gets Connect account creation redirect url from server and manually sets href. + */ $scope.authorize = function() { var currentUser = sessionStorage.getItem('user'); @@ -25,6 +22,10 @@ }); }; + /** + * On form submit, card info is sent to Stripe for processing. + * Stripe returns a one time use token to stripeCallback, which passes it to server for customerId creation and saving. + */ $scope.stripeCallback = function (code, result) { var currentUser = sessionStorage.getItem('user');
bd7ff400fa44892019ec97cfda1c93f8e0e33d02
bin/fileTemplater.js
bin/fileTemplater.js
"use strict"; var fs = require('fs'); var path = require('path'); var extend = require('extend'); var template = require('lodash/template'); var errorHandler = require('./errorHandler'); var _fileNumber = 1; var _config = { onEachFile: function() {}, onCompleted: function() {} }; var fileTemplaterApi = {}; fileTemplaterApi.run = function() { _config.files.forEach(function(element, index, array) { templateFile(element); }); } fileTemplaterApi.setConfig = function(config) { _config = extend(_config, config); } function templateFile(filePaths) { var compiled; var output; fs.readFile(filePaths.src, 'utf8', function(err, fileContents) { if (err) errorHandler(err); compiled = template(fileContents); output = compiled(_config.data); fs.writeFile(filePaths.dest, output, 'utf8', function(err) { if (err) errorHandler(err); _config.onEachFile(filePaths.dest); if(_fileNumber === _config.files.length) { _config.onCompleted(); } _fileNumber++; }); }); } module.exports = fileTemplaterApi;
"use strict"; var fs = require('fs'); var path = require('path'); var extend = require('extend'); var template = require('lodash/template'); var errorHandler = require('./errorHandler'); var _fileNumber = 1; var _config = { onEachFile: function() {}, onCompleted: function() {} }; var fileTemplaterApi = {}; /** * Run file templating */ fileTemplaterApi.run = function() { _config.files.forEach(function(element, index, array) { templateFile(element); }); } /** * Sets internal config object */ fileTemplaterApi.setConfig = function(config) { _config = extend(_config, config); } /** * Template a single file. * Get the contents of a file, template it and re-write to the same file * @param {Object} filePaths File paths data, containing file src and dest */ function templateFile(filePaths) { var compiled; var output; fs.readFile(filePaths.src, 'utf8', function(err, fileContents) { if (err) errorHandler(err); compiled = template(fileContents); output = compiled(_config.data); fs.writeFile(filePaths.dest, output, 'utf8', function(err) { if (err) errorHandler(err); _config.onEachFile(filePaths.dest); if(_fileNumber === _config.files.length) { _config.onCompleted(); } _fileNumber++; }); }); } module.exports = fileTemplaterApi;
Add doc comments for file templater
docs: Add doc comments for file templater
JavaScript
mit
cartridge/cartridge-cli,code-computerlove/quarry,code-computerlove/slate-cli
--- +++ @@ -15,16 +15,27 @@ var fileTemplaterApi = {}; +/** + * Run file templating + */ fileTemplaterApi.run = function() { _config.files.forEach(function(element, index, array) { templateFile(element); }); } +/** + * Sets internal config object + */ fileTemplaterApi.setConfig = function(config) { _config = extend(_config, config); } +/** + * Template a single file. + * Get the contents of a file, template it and re-write to the same file + * @param {Object} filePaths File paths data, containing file src and dest + */ function templateFile(filePaths) { var compiled; var output;
dddef42d59dc3af1cd2a43b311774dc286251d15
app/instance-initializers/active-model-adapter.js
app/instance-initializers/active-model-adapter.js
import ActiveModelAdapter from 'active-model-adapter'; import ActiveModelSerializer from 'active-model-adapter/active-model-serializer'; export default { name: 'active-model-adapter', initialize: function(applicationOrRegistry) { var registry, container; if (applicationOrRegistry.registry && applicationOrRegistry.container) { // initializeStoreService was registered with an // instanceInitializer. The first argument is the application // instance. registry = applicationOrRegistry.registry; container = applicationOrRegistry.container; } else { // initializeStoreService was called by an initializer instead of // an instanceInitializer. The first argument is a registy. This // case allows ED to support Ember pre 1.12 registry = applicationOrRegistry; if (registry.container) { // Support Ember 1.10 - 1.11 container = registry.container(); } else { // Support Ember 1.9 container = registry; } } registry.register('adapter:-active-model', ActiveModelAdapter); registry.register('serializer:-active-model', ActiveModelSerializer.extend({ isNewSerializerAPI: true })); } };
import ActiveModelAdapter from 'active-model-adapter'; import ActiveModelSerializer from 'active-model-adapter/active-model-serializer'; export default { name: 'active-model-adapter', initialize: function(applicationOrRegistry) { var registry; if (applicationOrRegistry.registry) { // initializeStoreService was registered with an // instanceInitializer. The first argument is the application // instance. registry = applicationOrRegistry.registry; } else { // initializeStoreService was called by an initializer instead of // an instanceInitializer. The first argument is a registy. This // case allows ED to support Ember pre 1.12 registry = applicationOrRegistry; } registry.register('adapter:-active-model', ActiveModelAdapter); registry.register('serializer:-active-model', ActiveModelSerializer.extend({ isNewSerializerAPI: true })); } };
Remove unused container in instance initializer
Remove unused container in instance initializer
JavaScript
mit
bmac/active-model-adapter,ember-data/active-model-adapter,fivetanley/active-model-adapter,ember-data/active-model-adapter,jcope2013/active-model-adapter,ember-data/active-model-adapter,jcope2013/active-model-adapter,fivetanley/active-model-adapter,fivetanley/active-model-adapter,fivetanley/active-model-adapter,bmac/active-model-adapter,jcope2013/active-model-adapter,jcope2013/active-model-adapter,bmac/active-model-adapter,bmac/active-model-adapter
--- +++ @@ -4,23 +4,17 @@ export default { name: 'active-model-adapter', initialize: function(applicationOrRegistry) { - var registry, container; - if (applicationOrRegistry.registry && applicationOrRegistry.container) { + var registry; + if (applicationOrRegistry.registry) { // initializeStoreService was registered with an // instanceInitializer. The first argument is the application // instance. registry = applicationOrRegistry.registry; - container = applicationOrRegistry.container; } else { // initializeStoreService was called by an initializer instead of // an instanceInitializer. The first argument is a registy. This // case allows ED to support Ember pre 1.12 registry = applicationOrRegistry; - if (registry.container) { // Support Ember 1.10 - 1.11 - container = registry.container(); - } else { // Support Ember 1.9 - container = registry; - } } registry.register('adapter:-active-model', ActiveModelAdapter);
1c528dd7dbe806411b0f2efcdf0e219b6c8c6e21
example/example/App.js
example/example/App.js
/** * Sample React Native Calendar Strip * https://github.com/BugiDev/react-native-calendar-strip * @flow */ import React, { Component } from 'react'; import CalendarStrip from "react-native-calendar-strip"; export default class App extends Component<{}> { render() { return ( <CalendarStrip calendarAnimation={{type: 'sequence', duration: 30}} daySelectionAnimation={{type: 'background', duration: 300, highlightColor: '#9265DC'}} style={{height:100, paddingTop: 20, paddingBottom: 10}} calendarHeaderStyle={{color: 'white'}} calendarColor={'#7743CE'} dateNumberStyle={{color: 'white'}} dateNameStyle={{color: 'white'}} iconLeft={require('./img/left-arrow.png')} iconRight={require('./img/right-arrow.png')} iconContainer={{flex: 0.1}} /> ); } }
/** * Sample React Native Calendar Strip * https://github.com/BugiDev/react-native-calendar-strip * @flow */ import React, { Component } from 'react'; import CalendarStrip from "react-native-calendar-strip"; import moment from 'moment'; export default class App extends Component<{}> { render() { let customDatesStyles = []; let markedDates = []; let startDate = moment(); for (let i=0; i<6; i++) { let _date = startDate.clone().add(i, 'days'); customDatesStyles.push({ startDate: _date, // Single date since no endDate provided dateNameStyle: {color: 'blue'}, dateNumberStyle: {color: 'purple'}, // Random color... dateContainerStyle: { backgroundColor: `#${(`#00000${(Math.random() * (1 << 24) | 0).toString(16)}`).slice(-6)}` }, }); markedDates.push({ date: _date, dots: [ { key: i, color: 'red', selectedDotColor: 'yellow', }, ], }); } return ( <CalendarStrip calendarAnimation={{type: 'sequence', duration: 30}} daySelectionAnimation={{type: 'background', duration: 300, highlightColor: '#9265DC'}} style={{height:200, paddingTop: 20, paddingBottom: 10}} calendarHeaderStyle={{color: 'white'}} calendarColor={'#7743CE'} dateNumberStyle={{color: 'white'}} dateNameStyle={{color: 'white'}} iconLeft={require('./img/left-arrow.png')} iconRight={require('./img/right-arrow.png')} iconContainer={{flex: 0.1}} customDatesStyles={customDatesStyles} markedDates={markedDates} /> ); } }
Update example with customDatesStyles and markedDates.
Update example with customDatesStyles and markedDates.
JavaScript
mit
BugiDev/react-native-calendar-strip,BugiDev/react-native-calendar-strip,BugiDev/react-native-calendar-strip
--- +++ @@ -6,14 +6,39 @@ import React, { Component } from 'react'; import CalendarStrip from "react-native-calendar-strip"; +import moment from 'moment'; export default class App extends Component<{}> { render() { + let customDatesStyles = []; + let markedDates = []; + let startDate = moment(); + for (let i=0; i<6; i++) { + let _date = startDate.clone().add(i, 'days'); + customDatesStyles.push({ + startDate: _date, // Single date since no endDate provided + dateNameStyle: {color: 'blue'}, + dateNumberStyle: {color: 'purple'}, + // Random color... + dateContainerStyle: { backgroundColor: `#${(`#00000${(Math.random() * (1 << 24) | 0).toString(16)}`).slice(-6)}` }, + }); + markedDates.push({ + date: _date, + dots: [ + { + key: i, + color: 'red', + selectedDotColor: 'yellow', + }, + ], + }); + } + return ( <CalendarStrip calendarAnimation={{type: 'sequence', duration: 30}} daySelectionAnimation={{type: 'background', duration: 300, highlightColor: '#9265DC'}} - style={{height:100, paddingTop: 20, paddingBottom: 10}} + style={{height:200, paddingTop: 20, paddingBottom: 10}} calendarHeaderStyle={{color: 'white'}} calendarColor={'#7743CE'} dateNumberStyle={{color: 'white'}} @@ -21,6 +46,8 @@ iconLeft={require('./img/left-arrow.png')} iconRight={require('./img/right-arrow.png')} iconContainer={{flex: 0.1}} + customDatesStyles={customDatesStyles} + markedDates={markedDates} /> ); }
e58cd331e4c5a21d42592d4b48333789ef1cfd50
replace-values.js
replace-values.js
module.exports = { "replace": { "_i18n/template.en-US.json": { "author": /docprofsky/g, "info-name": "info.name", "info-use": "info.use", "info-detail": "info.detail" }, "package.json": { "author": /docprofsky/g, "name": /template(?!_)/g }, "template.js": { "name": /template/g }, "template.ps.js": { "name": /template/g }, "template.html": { "name": /template/g }, "template.css": { "name": /template/g } }, "files": { "rename": [ "_i18n/template.en-US.json", "template.css", "template.html", "template.js", "template.ps.js" ], "delete": [ ".git" ] } }
module.exports = { "replace": { "_i18n/template.en-US.json": { "author": /docprofsky/g, "info-name": "info.name", "info-use": "info.use", "info-detail": "info.detail" }, "package.json": { "author": /docprofsky/g, "name": /template(?!_)/g }, "template.js": { "name": /template/g }, "template.ps.js": { "name": /template/g }, "template.html": { "name": /template/g }, "template.css": { "name": /template/g } }, "files": { "rename": [ "_i18n/template.en-US.json", "template.css", "template.html", "template.js", "template.ps.js" ], "delete": [ ".git", "replace-values.js" ] } }
Remove template file when done configuring
Remove template file when done configuring
JavaScript
mit
docprofsky/robopaint-mode-template,docprofsky/robopaint-mode-template
--- +++ @@ -37,7 +37,8 @@ "template.ps.js" ], "delete": [ - ".git" + ".git", + "replace-values.js" ] } }
2ccca7dca1b4c6bbdcc5bf3faf408c6f14d388bf
gulpfile.js
gulpfile.js
var gulp = require('gulp') , gutil = require('gulp-util') , help = require('gulp-help') , path = require('path') , packageJson = require(path.resolve(__dirname, 'package.json')) , noop = function(){} help(gulp, { aliases: ['h'] }) gulp.task('version', 'Prints the version number.', [], function() { console.log(packageJson.version) }, { aliases: ['v'] }) gulp.task('init', 'Initializes the project.', function() { }) gulp.task('migrate', 'Run pending migrations.', function() { }) gulp.task('migrate:undo', 'Undo the last migration.', function() { }) gulp.task('migration:create', 'Creates a new migration.', function() { })
var gulp = require('gulp') , path = require('path') , fs = require('fs') , helpers = require(path.resolve(__dirname, 'lib', 'helpers')) require('gulp-help')(gulp, { aliases: ['h'] }) fs .readdirSync(path.resolve(__dirname, 'lib', 'tasks')) .filter(function(file) { return file.indexOf('.') !== 0 }) .map(function(file) { return require(path.resolve(__dirname, 'lib', 'tasks', file)) }) .forEach(function(tasks) { Object.keys(tasks).forEach(function(taskName) { helpers.addTask(gulp, taskName, tasks[taskName]) helpers.addHelp(gulp, taskName, tasks[taskName]) }) })
Load the tasks from lib/tasks
Load the tasks from lib/tasks
JavaScript
mit
my-archives/cli,martinLE/cli,cogpie/cli,itslenny/cli,sequelize/cli,ataube/cli,martinLE/cli,Americas/cli,timrourke/cli,brad-decker/cli,sequelize/cli,Americas/cli,skv-headless/cli,jteplitz602/cli,xpepermint/cli,brad-decker/cli,brad-decker/cli,martinLE/cli,Americas/cli,sequelize/cli,fundon/cli,cusspvz/sequelize-cli
--- +++ @@ -1,30 +1,19 @@ var gulp = require('gulp') - , gutil = require('gulp-util') - , help = require('gulp-help') , path = require('path') - , packageJson = require(path.resolve(__dirname, 'package.json')) - , noop = function(){} + , fs = require('fs') + , helpers = require(path.resolve(__dirname, 'lib', 'helpers')) -help(gulp, { aliases: ['h'] }) +require('gulp-help')(gulp, { aliases: ['h'] }) -gulp.task('version', 'Prints the version number.', [], function() { - console.log(packageJson.version) -}, { - aliases: ['v'] -}) - -gulp.task('init', 'Initializes the project.', function() { - -}) - -gulp.task('migrate', 'Run pending migrations.', function() { - -}) - -gulp.task('migrate:undo', 'Undo the last migration.', function() { - -}) - -gulp.task('migration:create', 'Creates a new migration.', function() { - -}) +fs + .readdirSync(path.resolve(__dirname, 'lib', 'tasks')) + .filter(function(file) { return file.indexOf('.') !== 0 }) + .map(function(file) { + return require(path.resolve(__dirname, 'lib', 'tasks', file)) + }) + .forEach(function(tasks) { + Object.keys(tasks).forEach(function(taskName) { + helpers.addTask(gulp, taskName, tasks[taskName]) + helpers.addHelp(gulp, taskName, tasks[taskName]) + }) + })
f1cd6f85dd6fc7ccd1aa8d259ecdb9f34a149f9f
config/webpack/demo/webpack.config.hot.js
config/webpack/demo/webpack.config.hot.js
"use strict"; var _ = require("lodash"); // devDependency var base = require("./webpack.config.dev"); // Clone our own module object. var mod = _.cloneDeep(base.module); var firstLoader = mod.loaders[0]; // Update loaders array. First loader needs react-hot-loader. firstLoader.loaders = [require.resolve("react-hot-loader")] .concat(firstLoader.loader ? [firstLoader.loader] : []) .concat(firstLoader.loaders || []); // Remove single loader if any. firstLoader.loader = null; module.exports = _.merge({}, _.omit(base, "entry", "module"), { entry: { app: [ require.resolve("webpack/hot/dev-server"), "./demo/app.jsx" ] }, module: mod });
"use strict"; var _ = require("lodash"); // devDependency var base = require("./webpack.config.dev"); // Clone our own module object. var mod = _.cloneDeep(base.module); var firstLoader = mod.loaders[0]; // Update loaders array. First loader needs react-hot-loader. firstLoader.loaders = [require.resolve("react-hot-loader")] .concat(firstLoader.loader ? [firstLoader.loader] : []) .concat(firstLoader.loaders || []); // Remove single loader if any. firstLoader.loader = null; module.exports = _.merge({}, _.omit(base, "entry", "module"), { entry: { app: [ require.resolve("webpack/hot/only-dev-server"), "./demo/app.jsx" ] }, module: mod });
Use only-dev-server to not reload on syntax errors
Use only-dev-server to not reload on syntax errors
JavaScript
mit
FormidableLabs/builder-radium-component,FormidableLabs/builder-radium-component,FormidableLabs/builder-victory-component
--- +++ @@ -18,7 +18,7 @@ module.exports = _.merge({}, _.omit(base, "entry", "module"), { entry: { app: [ - require.resolve("webpack/hot/dev-server"), + require.resolve("webpack/hot/only-dev-server"), "./demo/app.jsx" ] },
a701b0fb2bd2008aef1fdb0a56ddccb8f7331f91
src/objects/isNumber/isNumber.js
src/objects/isNumber/isNumber.js
/** * Checks if 'value' is a number. * Note: NaN is considered a number. * @param {*} value The value to check. * @returns {Boolean} Returns true if 'value' is a number, else false. */ function isNumber(value) { 'use strict'; return value && Object.prototype.toString.call(value) === '[object Number]' && typeof value === 'number' || false; }
/** * Checks if 'value' is a number. * Note: NaN is considered a number. * @param {*} value The value to check. * @return {Boolean} Returns true if 'value' is a number, else false. */ function isNumber(value) { 'use strict'; return value != null && // NOTE: Using non strict equality to check against null and undefined. Object.prototype.toString.call(value) === '[object Number]' && typeof value === 'number' || false; }
Fix to return true for NaN
Fix to return true for NaN
JavaScript
mit
georapbox/smallsJS,georapbox/jsEssentials,georapbox/smallsJS
--- +++ @@ -1,13 +1,13 @@ /** * Checks if 'value' is a number. * Note: NaN is considered a number. - * @param {*} value The value to check. - * @returns {Boolean} Returns true if 'value' is a number, else false. + * @param {*} value The value to check. + * @return {Boolean} Returns true if 'value' is a number, else false. */ function isNumber(value) { 'use strict'; - return value && + return value != null && // NOTE: Using non strict equality to check against null and undefined. Object.prototype.toString.call(value) === '[object Number]' && typeof value === 'number' || false;
c074e61d2506f472fedd8810b8e1f188df400b42
src/card.js
src/card.js
import m from 'mithril'; import attributes from './attributes'; export let Card = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {shadow} = args; attr.class.push('mdl-card'); if(shadow) attr.class.push(`mdl-shadow--${shadow}dp`); return <div {...attr}>{children}</div>; } }; export let CardTitle = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {expand, size} = args; attr.class.push('mdl-card__title'); if(expand) attr.class.push('mdl-card--expand'); size = size || 2; return <div {...attr}><h2 class="mdl-card__title-text">{children}</h2></div>; } }; export let CardSupportingText = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {border, expand} = attr; attr.class.push('mdl-card__title-text'); if(border) attr.class.push('mdl-shadow--border'); if(expand) attr.class.push('mdl-card--expand'); return <div {...attr}>{children}</div>; } };
import m from 'mithril'; import attributes from './attributes'; export let Card = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {shadow} = args; attr.class.push('mdl-card'); if(shadow) attr.class.push(`mdl-shadow--${shadow}dp`); return <div {...attr}>{children}</div>; } }; export let CardTitle = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {expand, size} = args; attr.class.push('mdl-card__title'); if(expand) attr.class.push('mdl-card--expand'); size = size || 2; return <div {...attr}><h2 class="mdl-card__title-text">{children}</h2></div>; } }; export let CardSupportingText = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {border, expand} = attr; attr.class.push('mdl-card__title-text'); if(border) attr.class.push('mdl-card--border'); if(expand) attr.class.push('mdl-card--expand'); return <div {...attr}>{children}</div>; } };
Fix wrong class name in CardSupportingText
Fix wrong class name in CardSupportingText
JavaScript
bsd-3-clause
reminyborg/node-mithril-mdl,PaulAvery/node-mithril-mdl,boazy/node-mithril-mdl,PaulAvery/mithril-mdl
--- +++ @@ -36,7 +36,7 @@ let {border, expand} = attr; attr.class.push('mdl-card__title-text'); - if(border) attr.class.push('mdl-shadow--border'); + if(border) attr.class.push('mdl-card--border'); if(expand) attr.class.push('mdl-card--expand'); return <div {...attr}>{children}</div>;
5a695d9e91ba8783e6fe9cbe48ed7544f6642a94
lib/lint_css.js
lib/lint_css.js
var _ = require('lodash'); var stylelint = require('stylelint'); var STYLELINT_CONFIG = require('./config/stylelint'); var glob = require('glob'); var ruleUtils = require('./rule_utils'); var customRules = {}; var runLinter = function(contents, file, context) { var customRules = context.customRules || {}; _.merge(stylelint.rules, customRules); var config = context.lintConfig; var configs = [{}, STYLELINT_CONFIG]; if (_.isObject(config)) { configs.push(config); } config = _.merge.apply(_, configs); return stylelint.lint( { code: contents, codeFileName: file, config: config, formatter: 'json', syntax: 'scss' } ); }; var globOptions = { cwd: __dirname }; module.exports = function(contents, file, context) { context.customRules = customRules; glob.sync( './lint_css_rules/*.js', globOptions ).forEach( function(item, index) { var id = ruleUtils.getRuleId(item); customRules[id] = require(item); } ); return runLinter(contents, file, context); }; module.exports.stylelint = stylelint; module.exports.linter = stylelint.linter; module.exports.runLinter = runLinter;
var _ = require('lodash'); var path = require('path'); var stylelint = require('stylelint'); var STYLELINT_CONFIG = require('./config/stylelint'); var glob = require('glob'); var ruleUtils = require('./rule_utils'); var customRules = {}; var runLinter = function(contents, file, context) { var customRules = context.customRules || {}; _.merge(stylelint.rules, customRules); var config = context.lintConfig; var configs = [{}, STYLELINT_CONFIG]; if (_.isObject(config)) { configs.push(config); } config = _.merge.apply(_, configs); return stylelint.lint( { code: contents, codeFileName: file, config: config, configBasedir: path.resolve(__dirname, '..'), formatter: 'json', syntax: 'scss' } ); }; var globOptions = { cwd: __dirname }; module.exports = function(contents, file, context) { context.customRules = customRules; glob.sync( './lint_css_rules/*.js', globOptions ).forEach( function(item, index) { var id = ruleUtils.getRuleId(item); customRules[id] = require(item); } ); return runLinter(contents, file, context); }; module.exports.stylelint = stylelint; module.exports.linter = stylelint.linter; module.exports.runLinter = runLinter;
Add configBasedir to properly look up the plugins
Add configBasedir to properly look up the plugins
JavaScript
mit
natecavanaugh/check-source-formatting,natecavanaugh/check-source-formatting,natecavanaugh/check-source-formatting
--- +++ @@ -1,4 +1,5 @@ var _ = require('lodash'); +var path = require('path'); var stylelint = require('stylelint'); var STYLELINT_CONFIG = require('./config/stylelint'); var glob = require('glob'); @@ -27,6 +28,7 @@ code: contents, codeFileName: file, config: config, + configBasedir: path.resolve(__dirname, '..'), formatter: 'json', syntax: 'scss' }
13ca3b76cb5d8b9ff6818b13308f979f82f2a4b2
gulpfile.js
gulpfile.js
var gulp = require('gulp'), sass = require('gulp-sass'), rename = require('gulp-rename'), minifyCss = require('gulp-minify-css'), autoprefixer = require('gulp-autoprefixer'), browserSync = require('browser-sync').create(); gulp.task('dependencies', function() { gulp.src('bower_components/normalize-css/normalize.css') .pipe(rename('_normalize.scss')) .pipe(gulp.dest('scss/libs')); }); gulp.task('sass', function() { gulp.src('scss/style.scss') .pipe(sass().on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['last 20 versions'], cascade: false })) .pipe(gulp.dest('./css/')) .pipe(minifyCss()) .pipe(rename('style.min.css')) .pipe(gulp.dest('./css/')); }); gulp.task('dist', function() { gulp.src(['index.html']) .pipe(gulp.dest('./')); }); gulp.task('watch', function() { browserSync.init({ server: "./" }); gulp.watch('scss/**/*.scss', ['sass']).on('change', browserSync.reload); gulp.watch('index.html', ['dist']).on('change', browserSync.reload); }); gulp.task('default', ['clean', 'dependencies', 'sass'], function() { gulp.start('dist'); });
var gulp = require('gulp'), sass = require('gulp-sass'), rename = require('gulp-rename'), minifyCss = require('gulp-minify-css'), autoprefixer = require('gulp-autoprefixer'), browserSync = require('browser-sync').create(); gulp.task('dependencies', function() { gulp.src('bower_components/normalize-css/normalize.css') .pipe(rename('_normalize.scss')) .pipe(gulp.dest('scss/libs')); }); gulp.task('sass', function() { gulp.src('scss/style.scss') .pipe(sass().on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['last 20 versions'], cascade: false })) .pipe(gulp.dest('./css/')) .pipe(minifyCss()) .pipe(rename('style.min.css')) .pipe(gulp.dest('./css/')); }); gulp.task('dist', function() { gulp.src(['index.html']) .pipe(gulp.dest('./')); }); gulp.task('watch', function() { browserSync.init({ server: "./" }); gulp.watch('scss/**/*.scss', ['sass']).on('change', browserSync.reload); gulp.watch('index.html', ['dist']).on('change', browserSync.reload); gulp.watch('js/*.js', ['dist']).on('change', browserSync.reload); }); gulp.task('default', ['clean', 'dependencies', 'sass'], function() { gulp.start('dist'); });
Update to gulp watch js folder
Update to gulp watch js folder
JavaScript
cc0-1.0
FatecSorocaba/semana-da-tecnologia,FatecSorocaba/semana-da-tecnologia
--- +++ @@ -36,6 +36,8 @@ }); gulp.watch('scss/**/*.scss', ['sass']).on('change', browserSync.reload); gulp.watch('index.html', ['dist']).on('change', browserSync.reload); + gulp.watch('js/*.js', ['dist']).on('change', browserSync.reload); + }); gulp.task('default', ['clean', 'dependencies', 'sass'], function() {
31269953529541f7c0d65dd6a9d2107867c190d2
src/reducers/compiledProjects.js
src/reducers/compiledProjects.js
import {List} from 'immutable'; import {CompiledProject} from '../records'; const initialState = new List(); function trimRight(list, maxLength) { if (list.size <= maxLength) { return list; } return list.splice(0, list.size - maxLength); } export default function compiledProjects(stateIn, action) { let state = stateIn; if (state === undefined) { state = initialState; } switch (action.type) { case 'PROJECT_COMPILED': return trimRight( state.push(new CompiledProject({ source: action.payload.source, title: action.payload.title, timestamp: action.meta.timestamp, })), 2, ); case 'USER_DONE_TYPING': return trimRight(state, 1); case 'VALIDATED_SOURCE': if (action.payload.errors.length) { return initialState; } return state; } return state; }
import {List} from 'immutable'; import {CompiledProject} from '../records'; const initialState = new List(); function trimRight(list, maxLength) { if (list.size <= maxLength) { return list; } return list.splice(0, list.size - maxLength); } export default function compiledProjects(stateIn, action) { let state = stateIn; if (state === undefined) { state = initialState; } switch (action.type) { case 'PROJECT_CREATED': return initialState; case 'CHANGE_CURRENT_PROJECT': return initialState; case 'PROJECT_COMPILED': return trimRight( state.push(new CompiledProject({ source: action.payload.source, title: action.payload.title, timestamp: action.meta.timestamp, })), 2, ); case 'USER_DONE_TYPING': return trimRight(state, 1); case 'VALIDATED_SOURCE': if (action.payload.errors.length) { return initialState; } return state; } return state; }
Clear compiled projects when a project is created or switched to
Clear compiled projects when a project is created or switched to If you create a new project, or start the process of switching to an existing project, we want to clear the preview state. Otherwise: * When you create a new project, the old project sticks around * When switching projects, the preview is unpleasantly flashy between old and new state
JavaScript
mit
jwang1919/popcode,outoftime/learnpad,popcodeorg/popcode,outoftime/learnpad,popcodeorg/popcode,popcodeorg/popcode,jwang1919/popcode,jwang1919/popcode,jwang1919/popcode,popcodeorg/popcode
--- +++ @@ -18,6 +18,12 @@ } switch (action.type) { + case 'PROJECT_CREATED': + return initialState; + + case 'CHANGE_CURRENT_PROJECT': + return initialState; + case 'PROJECT_COMPILED': return trimRight( state.push(new CompiledProject({
8b2cad5472e9aef24e3848e77a661ef04e16c468
server/index.js
server/index.js
var express = require('express'); var bodyParser = require('body-parser'); var app = express(); // host static client files on server // app.use(express.static(__dirname + '/client'/* TODO: insert/change client folder path here */)); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); // configure server with routes require('./config/routes')(app, express); //start listening on given port var port = 3000; app.listen(port, function() { console.log('Listening on port', port); }); module.exports = app;
var express = require('express'); var bodyParser = require('body-parser'); var app = express(); // host static client files on server // app.use(express.static(__dirname + '/client'/* TODO: insert/change client folder path here */)); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); // configure server with routes require('./config/routes')(app, express); //start listening on given port var port = process.env.PORT || 3000; app.listen(port, function() { console.log('Listening on port', port); }); module.exports = app;
Remove hardcoding of port number for Heroku
Remove hardcoding of port number for Heroku
JavaScript
mit
hr-memories/TagMe,BillZito/greenfield,hr-memories/greenfield,hr-memories/greenfield,BillZito/greenfield,hr-memories/TagMe
--- +++ @@ -14,7 +14,7 @@ require('./config/routes')(app, express); //start listening on given port -var port = 3000; +var port = process.env.PORT || 3000; app.listen(port, function() { console.log('Listening on port', port); });
492b9d78a6a16daa3a9059b7bd24769c97d0443b
src/bin/commit-link-dependencies.js
src/bin/commit-link-dependencies.js
import {exec} from 'node-promise-es6/child-process'; import fs from 'node-promise-es6/fs'; async function run() { const {linkDependencies = {}} = await fs.readJson('package.json'); for (const dependencyName of Object.keys(linkDependencies)) { const dependencyPath = linkDependencies[dependencyName]; const {stdout: diff} = await exec( 'git diff-index HEAD', {cwd: dependencyPath}); if (diff.trim().indexOf('package.json') === -1) { continue; } await exec( [ 'git commit', `--author 'Vinson Chuong <vinsonchuong@gmail.com>'`, `-m 'Automatically update dependencies'`, 'package.json' ].join(' '), {cwd: dependencyPath} ); await exec( [ 'git push', `https://${process.env.GITHUB_TOKEN}@github.com/vinsonchuong/${dependencyName}`, 'master' ].join(' '), {cwd: dependencyPath} ); } } run().catch(e => { process.stderr.write(`${e.stack}\n`); process.exit(1); });
import {exec} from 'node-promise-es6/child-process'; import fs from 'node-promise-es6/fs'; async function run() { const {linkDependencies = {}} = await fs.readJson('package.json'); for (const dependencyName of Object.keys(linkDependencies)) { const dependencyPath = linkDependencies[dependencyName]; const {stdout: diff} = await exec( 'git diff-index HEAD', {cwd: dependencyPath}); if (diff.trim().indexOf('package.json') === -1) { continue; } await exec( `git config user.email 'vinsonchuong@gmail.com'`, {cwd: dependencyPath} ); await exec( `git config user.name 'Vinson Chuong'`, {cwd: dependencyPath} ); await exec( [ 'git commit', `-m 'Automatically update dependencies'`, 'package.json' ].join(' '), {cwd: dependencyPath} ); await exec( [ 'git push', `https://${process.env.GITHUB_TOKEN}@github.com/vinsonchuong/${dependencyName}`, 'master' ].join(' '), {cwd: dependencyPath} ); } } run().catch(e => { process.stderr.write(`${e.stack}\n`); process.exit(1); });
Use alternate way of setting git author
Use alternate way of setting git author
JavaScript
mit
vinsonchuong/npm-integration
--- +++ @@ -11,9 +11,16 @@ if (diff.trim().indexOf('package.json') === -1) { continue; } await exec( + `git config user.email 'vinsonchuong@gmail.com'`, + {cwd: dependencyPath} + ); + await exec( + `git config user.name 'Vinson Chuong'`, + {cwd: dependencyPath} + ); + await exec( [ 'git commit', - `--author 'Vinson Chuong <vinsonchuong@gmail.com>'`, `-m 'Automatically update dependencies'`, 'package.json' ].join(' '),
5304671a6aff5a08b33464e8ff181766d00f6acd
src/layouts/column-layout.js
src/layouts/column-layout.js
export default class ColumnLayout { constructor (options) { this._options = { columns: 5 }; Object.assign(this._options, options); this._tileWidth = 0; this.height = 0; } layout (layoutParams) { const row = Math.floor(layoutParams.position / this._options.columns); const col = layoutParams.position - row * this._options.columns; const translateX = col * this._tileWidth; const translateY = row * this._tileWidth; this.height = Math.max(this.height, (row + 1) * this._tileWidth); return { x: translateX, y: translateY, width: this._tileWidth, height: this._tileWidth }; } onWidthChanged (width) { this._tileWidth = width / this._options.columns; this.height = 0; } }
export default class ColumnLayout { constructor (options) { this._options = { columns: 5, margin: 8, outerMargin: true }; Object.assign(this._options, options); this._tileWidth = 0; this.height = 0; } layout (layoutParams) { const row = Math.floor(layoutParams.position / this._options.columns); const col = layoutParams.position - row * this._options.columns; let translateX = col * (this._tileWidth + this._options.margin); let translateY = row * (this._tileWidth + this._options.margin); if (this._options.outerMargin) { translateX += this._options.margin; translateY += this._options.margin; } this.height = Math.max(this.height, (row + 1) * (this._tileWidth + this._options.margin) + (this._options.outerMargin ? this._options.margin : -this._options.margin)); return { x: translateX, y: translateY, width: this._tileWidth, height: this._tileWidth }; } onWidthChanged (width) { if (this._options.outerMargin) { this._tileWidth = (width - (this._options.columns + 1) * this._options.margin) / this._options.columns; } else { this._tileWidth = (width - (this._options.columns - 1) * this._options.margin) / this._options.columns; } this.height = 0; } }
Add support for margins in column layout.
Add support for margins in column layout.
JavaScript
mit
frigus02/silky-tiles
--- +++ @@ -1,7 +1,9 @@ export default class ColumnLayout { constructor (options) { this._options = { - columns: 5 + columns: 5, + margin: 8, + outerMargin: true }; Object.assign(this._options, options); @@ -12,10 +14,14 @@ layout (layoutParams) { const row = Math.floor(layoutParams.position / this._options.columns); const col = layoutParams.position - row * this._options.columns; - const translateX = col * this._tileWidth; - const translateY = row * this._tileWidth; + let translateX = col * (this._tileWidth + this._options.margin); + let translateY = row * (this._tileWidth + this._options.margin); + if (this._options.outerMargin) { + translateX += this._options.margin; + translateY += this._options.margin; + } - this.height = Math.max(this.height, (row + 1) * this._tileWidth); + this.height = Math.max(this.height, (row + 1) * (this._tileWidth + this._options.margin) + (this._options.outerMargin ? this._options.margin : -this._options.margin)); return { x: translateX, @@ -26,7 +32,12 @@ } onWidthChanged (width) { - this._tileWidth = width / this._options.columns; + if (this._options.outerMargin) { + this._tileWidth = (width - (this._options.columns + 1) * this._options.margin) / this._options.columns; + } else { + this._tileWidth = (width - (this._options.columns - 1) * this._options.margin) / this._options.columns; + } + this.height = 0; } }
c29d2f92456d35b5f92e521f551e089c7f8c94f8
src/Paths.js
src/Paths.js
let argv = require('yargs').argv; class Paths { /** * Create a new Paths instance. */ constructor() { if (argv['$0'].includes('ava')) { this.rootPath = path.resolve(__dirname, '../'); } else { this.rootPath = process.cwd(); } } /** * Set the root path to resolve webpack.mix.js. * * @param {string} path */ setRootPath(path) { this.rootPath = path; return this; } /** * Determine the path to the user's webpack.mix.js file. */ mix() { return this.root( argv.env && argv.env.mixfile ? argv.env.mixfile : 'webpack.mix' ); } /** * Determine the project root. * * @param {string|null} append */ root(append = '') { return path.resolve(this.rootPath, append); } } module.exports = Paths;
let argv = require('yargs').argv; class Paths { /** * Create a new Paths instance. */ constructor() { if (argv['$0'].includes('ava')) { this.rootPath = path.resolve(__dirname, '../'); } else { this.rootPath = process.cwd(); } } /** * Set the root path to resolve webpack.mix.js. * * @param {string} path */ setRootPath(path) { this.rootPath = path; return this; } /** * Determine the path to the user's webpack.mix.js file. */ mix() { return this.root( process.env && process.env.MIX_FILE ? process.env.MIX_FILE : 'webpack.mix' ); } /** * Determine the project root. * * @param {string|null} append */ root(append = '') { return path.resolve(this.rootPath, append); } } module.exports = Paths;
Use real env var for custom mix file
Use real env var for custom mix file The previous approach doesn’t work with current webpack cli now.
JavaScript
mit
JeffreyWay/laravel-mix
--- +++ @@ -28,7 +28,9 @@ */ mix() { return this.root( - argv.env && argv.env.mixfile ? argv.env.mixfile : 'webpack.mix' + process.env && process.env.MIX_FILE + ? process.env.MIX_FILE + : 'webpack.mix' ); }
415925e578d732aa584d84282fbf62edd873d164
gulpfile.js
gulpfile.js
'use strict'; var gulp = require( 'gulp' ); var g = require( 'gulp-load-plugins' )(); var allTestFiles = './tests/**/*.js'; gulp.task( 'assets', function() { gulp.src([ 'node_modules/gulp-mocha/node_modules/mocha/mocha.{js,css}', 'node_modules/chai/chai.js' ]) .pipe( gulp.dest( 'public' ) ); }); gulp.task( 'test', function( done ) { gulp.src([ allTestFiles ]) .pipe( g.istanbul() ) .on( 'finish', function() { gulp.src([ 'src/ajax.js', allTestFiles ]) .pipe( g.istanbul.writeReports() ) .on( 'end', done ); }); }); gulp.task( 'default', [ 'assets' ], function() { require( './api/app' ); gulp.watch([ allTestFiles, 'src/ajax.js' ], [ 'test' ]); });
'use strict'; var gulp = require( 'gulp' ); var g = require( 'gulp-load-plugins' )(); var exec = require( 'child_process' ).exec; var allTestFiles = './tests/**/*.js'; gulp.task( 'assets', function() { gulp.src([ 'node_modules/gulp-mocha/node_modules/mocha/mocha.{js,css}', 'node_modules/chai/chai.js' ]) .pipe( gulp.dest( 'public' ) ); }); gulp.task( 'test', function( done ) { gulp.src([ allTestFiles ]) .pipe( g.istanbul() ) .on( 'finish', function() { gulp.src([ 'src/ajax.js', allTestFiles ]) .pipe( g.istanbul.writeReports() ) .on( 'end', done ); }); }); gulp.task( 'python', function() { exec( 'python -m SimpleHTTPServer 9001' ); }); gulp.task( 'default', [ 'assets' ], function() { require( './api/app' ); gulp.watch([ allTestFiles, 'src/ajax.js' ], [ 'test' ]); });
Add Python server to localhost
Add Python server to localhost
JavaScript
mit
Ibanheiz/ajax,negherbon/ajax,denis-itskovich/ajax,ggviana/ajax,felipegtx/ajax,caiocutrim/ajax,afgoulart/ajax
--- +++ @@ -2,6 +2,7 @@ var gulp = require( 'gulp' ); var g = require( 'gulp-load-plugins' )(); +var exec = require( 'child_process' ).exec; var allTestFiles = './tests/**/*.js'; @@ -23,6 +24,10 @@ }); }); +gulp.task( 'python', function() { + exec( 'python -m SimpleHTTPServer 9001' ); +}); + gulp.task( 'default', [ 'assets' ], function() { require( './api/app' ); gulp.watch([ allTestFiles, 'src/ajax.js' ], [ 'test' ]);
f0e6d9a889711086a581afe731c6916325343198
gulpfile.js
gulpfile.js
var elixir = require('laravel-elixir'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Less | file for our application, as well as publishing vendor resources. | */ elixir(function(mix) { mix.less('app.less'); mix.scriptsIn("resources/assets/js", "public/js/app.js"); }); require('laravel-elixir-browser-sync'); elixir(function(mix) { mix.browserSync([ 'public/**/*', 'resources/views/**/*' ], { proxy: 'netsocadmin.dev', reloadDelay: 500 }); });
var elixir = require('laravel-elixir'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Less | file for our application, as well as publishing vendor resources. | */ elixir(function(mix) { mix.less('app.less'); mix.scriptsIn("resources/assets/js", "public/js/app.js"); }); require('laravel-elixir-browser-sync'); elixir(function(mix) { mix.browserSync([ 'public/**/*', 'resources/**/*' ], { proxy: 'netsocadmin.dev', reloadDelay: 500 }); });
Change browsersync to listen for changes to JS/LESS as well
Change browsersync to listen for changes to JS/LESS as well
JavaScript
mit
UCCNetworkingSociety/NetsocAdmin,UCCNetworkingSociety/NetsocAdmin,UCCNetworkingSociety/NetsocAdmin,UCCNetworkingSociety/NetsocAdmin
--- +++ @@ -21,7 +21,7 @@ elixir(function(mix) { mix.browserSync([ 'public/**/*', - 'resources/views/**/*' + 'resources/**/*' ], { proxy: 'netsocadmin.dev', reloadDelay: 500
485cb7a0aff21ab4f8dd28db86935774a1fbf1b7
lib/main.js
lib/main.js
/* @flow */ const useLSP = atom.config.get('flow-ide.useLSP') // possible improvement: check if flow really supports lsp if (useLSP === true) { // eslint-disable-next-line global-require const { FlowLanguageClient } = require('./language-client') module.exports = new FlowLanguageClient() } else { // eslint-disable-next-line global-require const { Flow } = require('./index') module.exports = new Flow() }
/* @flow */ const useLSP = atom.config.get('flow-ide.useLSP') // notify to restart if the value changes atom.config.onDidChange('flow-ide.useLSP', () => { const buttons = [{ text: 'Restart', onDidClick () { return atom.restartApplication() }, }] atom.notifications.addInfo('Changing this value requires a restart of atom.', { dismissable: true, buttons }) }) // possible improvement: check if flow really supports lsp if (useLSP === true) { // eslint-disable-next-line global-require const { FlowLanguageClient } = require('./language-client') module.exports = new FlowLanguageClient() } else { // eslint-disable-next-line global-require const { Flow } = require('./index') module.exports = new Flow() }
Add notification to restart atom when switching to/from LSP
Add notification to restart atom when switching to/from LSP
JavaScript
mit
steelbrain/flow-ide
--- +++ @@ -1,6 +1,15 @@ /* @flow */ const useLSP = atom.config.get('flow-ide.useLSP') + +// notify to restart if the value changes +atom.config.onDidChange('flow-ide.useLSP', () => { + const buttons = [{ + text: 'Restart', + onDidClick () { return atom.restartApplication() }, + }] + atom.notifications.addInfo('Changing this value requires a restart of atom.', { dismissable: true, buttons }) +}) // possible improvement: check if flow really supports lsp
c0f7f3373ed393ea22f44ee65c39ba411300db1e
lib/main.js
lib/main.js
var NwBuilder = require("node-webkit-builder"); var asap = require("pdenodeify"); var path = require("path"); var rimraf = require("rimraf"); module.exports = function(options, buildResult){ var nwOptions = {}; // Convert the options to camelcase Object.keys(options).forEach(function(optName){ nwOptions[toCamelcase(optName)] = options[optName]; }); // Set the bundlesPath as a file to use. var files = nwOptions.files || nwOptions.glob || []; files = Array.isArray(files) ? files : [files]; if(buildResult && buildResult.configuration && buildResult.configuration.bundlesPath) { var bundlesPath = buildResult.configuration.bundlesPath; files.unshift(path.join(bundlesPath, "**/*")); } nwOptions.files = files; var nw = new NwBuilder(nwOptions); nw.on("log", function(msg){ console.error(msg); }); var buildPromise = asap(rimraf)(nwOptions.buildDir); var builder = asap(nw.build.bind(nw)); return buildPromise.then(builder); }; function toCamelcase(str) { return str.replace(/\_+([a-z])/g, function (x, chr) { return chr.toUpperCase(); }); }
var NwBuilder = require("node-webkit-builder"); var asap = require("pdenodeify"); var path = require("path"); var rimraf = require("rimraf"); module.exports = function(options, buildResult){ var nwOptions = {}; // Convert the options to camelcase Object.keys(options).forEach(function(optName){ nwOptions[toCamelcase(optName)] = options[optName]; }); // Set the bundlesPath as a file to use. var files = nwOptions.files || nwOptions.glob || []; files = Array.isArray(files) ? files : [files]; if(buildResult && buildResult.configuration && buildResult.configuration.bundlesPath) { var bundlesPath = buildResult.configuration.bundlesPath; var globPath = path.relative(process.cwd(), bundlesPath) + "/**/*"; files.unshift(globPath); } nwOptions.files = files; var nw = new NwBuilder(nwOptions); nw.on("log", function(msg){ console.error(msg); }); var buildPromise = asap(rimraf)(nwOptions.buildDir); var builder = asap(nw.build.bind(nw)); return buildPromise.then(builder); }; function toCamelcase(str) { return str.replace(/\_+([a-z])/g, function (x, chr) { return chr.toUpperCase(); }); }
Use path.relative to create the bundles glob
Use path.relative to create the bundles glob
JavaScript
mit
stealjs/steal-nw,stealjs/steal-nw
--- +++ @@ -17,7 +17,8 @@ if(buildResult && buildResult.configuration && buildResult.configuration.bundlesPath) { var bundlesPath = buildResult.configuration.bundlesPath; - files.unshift(path.join(bundlesPath, "**/*")); + var globPath = path.relative(process.cwd(), bundlesPath) + "/**/*"; + files.unshift(globPath); } nwOptions.files = files;
44458bfb9a8c3f191336e6afc2a245eed4773afa
src/services/user/services/UserLinkImportService.js
src/services/user/services/UserLinkImportService.js
const { BadRequest } = require('@feathersjs/errors'); const userDataFilter = user => ({ userId: user._id, email: user.email, firstName: user.firstName, lastName: user.lastName, importHash: user.importHash, schoolId: user.schoolId, birthday: user.birthday, }); class UserLinkImportService { constructor(userService) { this.userService = userService; this.docs = {}; } get(hash) { // can not use get becouse the hash can have / that mapped to non existing routes return this.userService.find({ query: { importHash: hash } }) .then((users) => { if (users.data.length !== 1) { throw new BadRequest('Can not match the hash.'); } return userDataFilter(users.data[0]); }).catch(err => err); } } module.exports = UserLinkImportService;
const { BadRequest } = require('@feathersjs/errors'); const userDataFilter = user => ({ userId: user._id, email: user.email, firstName: user.firstName, lastName: user.lastName, importHash: user.importHash, schoolId: user.schoolId, birthday: user.birthday, }); class UserLinkImportService { constructor(userService) { this.userService = userService; this.docs = {}; } get(hash) { // can not use get becouse the hash can have / that mapped to non existing routes return this.userService.find({ query: { importHash: hash } }) .then((users) => { if (users.data.length !== 1) { throw new BadRequest('Can not match the hash.'); } return userDataFilter(users.data[0]); }).catch(err => err); } setup(app) { this.app = app; } } module.exports = UserLinkImportService;
Add missing setup in class.
Add missing setup in class.
JavaScript
agpl-3.0
schul-cloud/schulcloud-server,schul-cloud/schulcloud-server,schul-cloud/schulcloud-server
--- +++ @@ -25,6 +25,10 @@ return userDataFilter(users.data[0]); }).catch(err => err); } + + setup(app) { + this.app = app; + } } module.exports = UserLinkImportService;
f43e339602f096e781d5a9c82e3befc94c73bcf3
src/KillrVideo/scripts/requirejs-config.js
src/KillrVideo/scripts/requirejs-config.js
// Common configuration for RequireJS var require = { baseUrl: "/scripts", paths: { "jquery": "bower_components/jquery/dist/jquery.min", "knockout": "bower_components/knockout/dist/knockout", "bootstrap": "bower_components/bootstrap/dist/js/bootstrap.min", "text": "bower_components/requirejs-text/text", "domReady": "bower_components/requirejs-domReady/domReady", "moment": "bower_components/moment/min/moment.min", "videojs": "bower_components/videojs/dist/video-js/video", "knockout-postbox": "bower_components/knockout-postbox/build/knockout-postbox.min", "knockout-validation": "bower_components/knockout-validation/Dist/knockout.validation.min", "perfect-scrollbar": "bower_components/perfect-scrollbar/src/perfect-scrollbar", "jquery-expander": "bower_components/jquery-expander/jquery.expander", "bootstrap-select": "bower_components/bootstrap-select/dist/js/bootstrap-select", "bootstrap-tagsinput": "bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput", }, shim: { "bootstrap": { deps: ["jquery"], exports: "$.fn.popover" }, "jquery-expander": ["jquery"] } };
// Common configuration for RequireJS var require = { baseUrl: "/scripts", paths: { "jquery": "bower_components/jquery/dist/jquery.min", "knockout": "bower_components/knockout/dist/knockout", "bootstrap": "bower_components/bootstrap/dist/js/bootstrap.min", "text": "bower_components/requirejs-text/text", "domReady": "bower_components/requirejs-domReady/domReady", "moment": "bower_components/moment/min/moment.min", "videojs": "bower_components/videojs/dist/video-js/video", "knockout-postbox": "bower_components/knockout-postbox/build/knockout-postbox.min", "knockout-validation": "bower_components/knockout-validation/Dist/knockout.validation.min", "perfect-scrollbar": "bower_components/perfect-scrollbar/src/perfect-scrollbar", "jquery-expander": "bower_components/jquery-expander/jquery.expander", "bootstrap-select": "bower_components/bootstrap-select/dist/js/bootstrap-select", "bootstrap-tagsinput": "bower_components/bootstrap-tagsinput/dist/bootstrap-tagsinput", }, shim: { "bootstrap": { deps: ["jquery"], exports: "$.fn.popover" }, "jquery-expander": ["jquery"], "perfect-scrollbar": ["jquery"], "bootstrap-select": ["bootstrap"], "bootstrap-tagsinput": ["bootstrap"] } };
Fix javascript dependencies for a couple other plugins that aren't AMD modules
Fix javascript dependencies for a couple other plugins that aren't AMD modules
JavaScript
apache-2.0
LukeTillman/killrvideo-csharp,LukeTillman/killrvideo-csharp,rustyrazorblade/killrvideo-csharp,LukeTillman/killrvideo-csharp,rustyrazorblade/killrvideo-csharp,rustyrazorblade/killrvideo-csharp
--- +++ @@ -21,6 +21,9 @@ deps: ["jquery"], exports: "$.fn.popover" }, - "jquery-expander": ["jquery"] + "jquery-expander": ["jquery"], + "perfect-scrollbar": ["jquery"], + "bootstrap-select": ["bootstrap"], + "bootstrap-tagsinput": ["bootstrap"] } };
568d969199234703fd987407f5ba438abd8e0eba
web/src/containers/page/overview/table/cell-inner.js
web/src/containers/page/overview/table/cell-inner.js
import { Map as map } from 'immutable'; import React from 'react'; import PropTypes from 'prop-types'; import Editable from '../../../editable'; import { formatCurrency } from '../../../../misc/format'; export default function OverviewTableCellInner({ cell, cellKey, rowKey, editable }) { if (editable) { // editable balance column const props = { page: 'overview', row: rowKey, col: 0, id: null, item: 'cost', value: cell.get('value') }; return <Editable {...props} />; } const value = cellKey > 0 ? formatCurrency(cell.get('value'), { abbreviate: true, precision: 1 }) : cell.get('value'); return <span className="text">{value}</span>; } OverviewTableCellInner.propTypes = { cell: PropTypes.instanceOf(map).isRequired, cellKey: PropTypes.number.isRequired, rowKey: PropTypes.number.isRequired, editable: PropTypes.bool.isRequired };
import { Map as map } from 'immutable'; import React from 'react'; import PropTypes from 'prop-types'; import Editable from '../../../editable'; import { formatCurrency } from '../../../../misc/format'; export default function OverviewTableCellInner({ cell, cellKey, rowKey, editable }) { if (editable) { // editable balance column const props = { page: 'overview', row: rowKey, col: 0, id: null, item: 'cost', value: cell.get('value') }; return <Editable {...props} />; } const value = cellKey > 0 ? formatCurrency(cell.get('value'), { abbreviate: true, precision: 1, brackets: true }) : cell.get('value'); return <span className="text">{value}</span>; } OverviewTableCellInner.propTypes = { cell: PropTypes.instanceOf(map).isRequired, cellKey: PropTypes.number.isRequired, rowKey: PropTypes.number.isRequired, editable: PropTypes.bool.isRequired };
Use brackets to indicate negative values on overview table
Use brackets to indicate negative values on overview table
JavaScript
mit
felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget
--- +++ @@ -20,7 +20,11 @@ } const value = cellKey > 0 - ? formatCurrency(cell.get('value'), { abbreviate: true, precision: 1 }) + ? formatCurrency(cell.get('value'), { + abbreviate: true, + precision: 1, + brackets: true + }) : cell.get('value'); return <span className="text">{value}</span>;
b7613e8983281c1549a3c69e8c75698a45f00309
app/scripts/queryparser.js
app/scripts/queryparser.js
/* jshint devel:true */ /* global exports, require, URI */ exports.parser = function(url, callbacks) { if (url) { var queryMap = new URI(url).search(true); if (queryMap.CFTemplateURL && callbacks.onTemplate) { callbacks.onTemplate(queryMap.CFTemplateURL); } } };
/* jshint devel:true */ /* global exports, URI */ exports.parser = function(url, callbacks) { 'use strict'; if (url) { var queryMap = new URI(url).search(true); if (queryMap.CFTemplateURL && callbacks.onTemplate) { callbacks.onTemplate(queryMap.CFTemplateURL); } } };
Fix JSHint errors & warnings
Fix JSHint errors & warnings
JavaScript
mit
dmgress/cloudgrapher,dmgress/cloudgrapher
--- +++ @@ -1,7 +1,8 @@ /* jshint devel:true */ -/* global exports, require, URI */ +/* global exports, URI */ exports.parser = function(url, callbacks) { + 'use strict'; if (url) { var queryMap = new URI(url).search(true); if (queryMap.CFTemplateURL && callbacks.onTemplate) {
5ce651027d342ada2e4162f0f1d1f9e6bbcf51b3
scripts/routes/route-handler.js
scripts/routes/route-handler.js
import { genKey } from './key'; export default class RouteHandler { constructor(conf) { this.id = genKey(); this.init = conf.init; this.beforeInit = conf.beforeInit || null; this.beforeUpdate = conf.beforeUpdate || null; this.init = conf.init || null; this.update = conf.update || null; this.unload = conf.unload || null; } }
import { genKey } from './key'; export default class RouteHandler { constructor(conf) { this.id = genKey(); this.beforeInit = conf.beforeInit || null; this.beforeUpdate = conf.beforeUpdate || null; this.init = conf.init || null; this.update = conf.update || null; this.unload = conf.unload || null; } }
Remove duplcate init property on RouteHandler
Remove duplcate init property on RouteHandler
JavaScript
apache-2.0
weepower/wee-core
--- +++ @@ -3,7 +3,6 @@ export default class RouteHandler { constructor(conf) { this.id = genKey(); - this.init = conf.init; this.beforeInit = conf.beforeInit || null; this.beforeUpdate = conf.beforeUpdate || null; this.init = conf.init || null;
c14b51de61fac64aa8e1d05634885d00903fcca1
docgen/config.js
docgen/config.js
var algoliaComponents = require('algolia-frontend-components'); var fs = require('fs'); import {rootPath} from './path'; const prod = process.env.NODE_ENV === 'production'; const docsDist = process.env.DOCS_DIST; var content = JSON.parse(fs.readFileSync('./src/data/communityHeader.json', 'utf8').toString()); var header = algoliaComponents.communityHeader(content); export default { docsDist: docsDist? docsDist : prod ? rootPath('docs') : // avoids publishing an `npm start`ed build if running. rootPath('docs-preview'), publicPath: prod ? '/instantsearch-android/' : '/', header: header };
var algoliaComponents = require('algolia-frontend-components'); var fs = require('fs'); import {rootPath} from './path'; const prod = process.env.NODE_ENV === 'production'; const docsDist = process.env.DOCS_DIST; var content = JSON.parse(fs.readFileSync('./src/data/communityHeader.json', 'utf8').toString()); var header = algoliaComponents.communityHeader(content); export default { docsDist: docsDist? docsDist : prod ? rootPath('docs') : // avoids publishing an `npm start`ed build if running. rootPath('docs-preview'), publicPath: prod ? '/instantsearch.js/' : '/', header: header };
Update root url for prod
chore(build-doc): Update root url for prod
JavaScript
mit
algolia/instantsearch.js,algolia/instantsearch.js,algolia/instantsearch.js
--- +++ @@ -13,6 +13,6 @@ docsDist: docsDist? docsDist : prod ? rootPath('docs') : // avoids publishing an `npm start`ed build if running. rootPath('docs-preview'), - publicPath: prod ? '/instantsearch-android/' : '/', + publicPath: prod ? '/instantsearch.js/' : '/', header: header };
49b3fb5255e9234d7817ce73a7b448372090bd17
routes/index.js
routes/index.js
var express = require('express'); var Git = require("nodegit"); var router = express.Router(); var token = process.env.GITHUB_TOKEN; router.post('/issues', function(req, res, next) { Git.Clone("https://" + token + ":x-oauth-basic@github.com/kewang/information-people", "./tmp", { checkoutBranch: "gh-pages" }).then(function(repo){ console.log("getHeadCommit"); return repo.getHeadCommit(); }).then(function(commit){ console.log("getEntry"); return commit.getEntry("index.htm"); }).then(function(entry){ console.log("getBlob"); return entry.getBlob(); }).then(function(blob){ var str = String(blob); console.log(str); return res.json(str); }); }); module.exports = router;
var express = require('express'); var Git = require("nodegit"); var fs = require('fs'); var router = express.Router(); var GITHUB_TOKEN = process.env.GITHUB_TOKEN; var FILE_NAME = "index.htm"; var content; var repo; var head; var oid; router.post('/issues', function(req, res, next) { Git.Clone("https://" + GITHUB_TOKEN + ":x-oauth-basic@github.com/kewang/information-people", "./tmp", { checkoutBranch: "gh-pages" }).then(function(repoResult){ repo = repoResult; console.log("getHeadCommit"); return repo.getHeadCommit(); }).then(function(headResult){ head = headResult; console.log("getEntry"); return head.getEntry(FILE_NAME); }).then(function(entry){ console.log("getBlob"); return entry.getBlob(); }).then(function(blob){ content = "DEF" + String(blob) + "ABC"; fs.writeFileSync("./tmp/" + FILE_NAME, content); return repo.index(); }).then(function(index){ index.addByPath(FILE_NAME); index.write(); return index.writeTree(); }).then(function(oidResult){ oid = oidResult; var author = Git.Signature.now("kewang", "cpckewang@gmail.com"); return repo.createCommit("HEAD", author, author, "Add test", oid, [head]); }).then(function(commitId){ console.log("New Commit: " + commitId); var remote = repo.getRemote("origin"); // var remote = Git.Remote.create(repo, "origin", "https://" + GITHUB_TOKEN + ":x-oauth-basic@github.com/kewang/information-people"); console.log("remote: " + remote); return remote.push(["refs/heads/master:refs/heads/master"]); }).done(function(){ console.log("Push OK"); return res.json(content); }); }); module.exports = router;
Add push flow, but test fail
Add push flow, but test fail
JavaScript
mit
kewang/information-people,kewang/information-people
--- +++ @@ -1,29 +1,63 @@ var express = require('express'); var Git = require("nodegit"); +var fs = require('fs'); var router = express.Router(); -var token = process.env.GITHUB_TOKEN; +var GITHUB_TOKEN = process.env.GITHUB_TOKEN; +var FILE_NAME = "index.htm"; +var content; +var repo; +var head; +var oid; router.post('/issues', function(req, res, next) { - Git.Clone("https://" + token + ":x-oauth-basic@github.com/kewang/information-people", "./tmp", { + Git.Clone("https://" + GITHUB_TOKEN + ":x-oauth-basic@github.com/kewang/information-people", "./tmp", { checkoutBranch: "gh-pages" - }).then(function(repo){ + }).then(function(repoResult){ + repo = repoResult; + console.log("getHeadCommit"); return repo.getHeadCommit(); - }).then(function(commit){ + }).then(function(headResult){ + head = headResult; console.log("getEntry"); - return commit.getEntry("index.htm"); + return head.getEntry(FILE_NAME); }).then(function(entry){ console.log("getBlob"); return entry.getBlob(); }).then(function(blob){ - var str = String(blob); + content = "DEF" + String(blob) + "ABC"; - console.log(str); + fs.writeFileSync("./tmp/" + FILE_NAME, content); - return res.json(str); + return repo.index(); + }).then(function(index){ + index.addByPath(FILE_NAME); + index.write(); + + return index.writeTree(); + }).then(function(oidResult){ + oid = oidResult; + + var author = Git.Signature.now("kewang", "cpckewang@gmail.com"); + + return repo.createCommit("HEAD", author, author, "Add test", oid, [head]); + }).then(function(commitId){ + console.log("New Commit: " + commitId); + + var remote = repo.getRemote("origin"); + + // var remote = Git.Remote.create(repo, "origin", "https://" + GITHUB_TOKEN + ":x-oauth-basic@github.com/kewang/information-people"); + + console.log("remote: " + remote); + + return remote.push(["refs/heads/master:refs/heads/master"]); + }).done(function(){ + console.log("Push OK"); + + return res.json(content); }); });
ec81364906306227b9e4d40160c3a4921c458ea3
examples/server-rendering/views/main.js
examples/server-rendering/views/main.js
const assert = require('assert') const choo = require('../../../') module.exports = function (params, state, send) { const serverMessage = state.message.server const clientMessage = state.message.client assert.equal(typeof serverMessage, 'string', 'server should be a string') assert.equal(typeof clientMessage, 'string', 'server should be a string') return choo.view` <section id="app-root"> <h1>server message: ${serverMessage}</h1> <h1>client message: ${clientMessage}</h1> <p>${` The first message is passed in by the server on compile time, the second message was set by the client. The more static the data you pass in, the more cachable your site beocmes (and thus performant). Try and keep the amount of properties you pass in on the server to a minimum for most applications - it'll make life a lot easier in the long run, hah. `}</p> </section> ` }
const assert = require('assert') const choo = require('../../../') module.exports = function (params, state, send) { const serverMessage = state.message.server const clientMessage = state.message.client assert.equal(typeof serverMessage, 'string', 'server should be a string') assert.equal(typeof clientMessage, 'string', 'client should be a string') return choo.view` <section id="app-root"> <h1>server message: ${serverMessage}</h1> <h1>client message: ${clientMessage}</h1> <p>${` The first message is passed in by the server on compile time, the second message was set by the client. The more static the data you pass in, the more cachable your site beocmes (and thus performant). Try and keep the amount of properties you pass in on the server to a minimum for most applications - it'll make life a lot easier in the long run, hah. `}</p> </section> ` }
Fix typo in server rendering view
Fix typo in server rendering view
JavaScript
mit
yoshuawuyts/choo,antiBaconMachine/choo,antiBaconMachine/choo
--- +++ @@ -6,7 +6,7 @@ const clientMessage = state.message.client assert.equal(typeof serverMessage, 'string', 'server should be a string') - assert.equal(typeof clientMessage, 'string', 'server should be a string') + assert.equal(typeof clientMessage, 'string', 'client should be a string') return choo.view` <section id="app-root">
59120a3e1cd6fa2024d587af0655a0269f161211
routes/users.js
routes/users.js
var express = require('express'); var router = express.Router(); import encryptUtils from '../utilities/encrypt'; import userUtils from '../utilities/users_service.js'; import { userAuth, adminAuth } from '../utilities/auth'; router.post('/', (req, res) => { const { first_name, last_name, email, username, password } = req.body; encryptUtils.encryptPassword(password).then((hashedPassword) => { const newUser = { first_name, last_name, email, username, password: hashedPassword }; userUtils.createUser(newUser).then((createdUser) => { res.json(createdUser); }, () => res.sendStatus(400)); }, () => res.sendStatus(500)); }); router.get('/', adminAuth, (req, res) => { userUtils.getUsers().then((users) => { res.json(users); }, () => res.sendStatus(404)); }); router.get('/:id', adminAuth, (req, res) => { const userID = req.params.id; userUtils.getUser(userID).then((user) => { res.json(user); }, () => res.sendStatus(404)); }); module.exports = router;
var express = require('express'); var router = express.Router(); import encryptUtils from '../utilities/encrypt'; import userUtils from '../utilities/users_service.js'; import { userAuth, adminAuth } from '../utilities/auth'; router.post('/', (req, res) => { const { first_name, last_name, email, username, password } = req.body; encryptUtils.encryptPassword(password).then((hashedPassword) => { const newUser = { first_name, last_name, email, username, password: hashedPassword }; userUtils.createUser(newUser).then((createdUser) => { req.session.username = createdUser.username; req.session.status = createdUser.status; res.json(createdUser); }, () => res.sendStatus(400)); }, () => res.sendStatus(500)); }); router.get('/', adminAuth, (req, res) => { userUtils.getUsers().then((users) => { res.json(users); }, () => res.sendStatus(404)); }); router.get('/:id', adminAuth, (req, res) => { const userID = req.params.id; userUtils.getUser(userID).then((user) => { res.json(user); }, () => res.sendStatus(404)); }); module.exports = router;
Add user to session when they create a new account
Add user to session when they create a new account
JavaScript
mit
davidlamt/antfinder-api
--- +++ @@ -13,15 +13,18 @@ const newUser = { first_name, last_name, email, username, password: hashedPassword }; userUtils.createUser(newUser).then((createdUser) => { + req.session.username = createdUser.username; + req.session.status = createdUser.status; + res.json(createdUser); }, () => res.sendStatus(400)); }, () => res.sendStatus(500)); }); router.get('/', adminAuth, (req, res) => { - userUtils.getUsers().then((users) => { - res.json(users); - }, () => res.sendStatus(404)); + userUtils.getUsers().then((users) => { + res.json(users); + }, () => res.sendStatus(404)); }); router.get('/:id', adminAuth, (req, res) => {
584226c87cc41d09b28932972a55a22c74e420d2
config/db.config.js
config/db.config.js
module.exports = { db: { qrest_api:{ $filter: 'env', $base: { options: {} }, production: { url: 'mongodb://mongodb:27017/qrest_api' }, $default: { url: 'mongodb://localhost:27017/qrest_api' } }, default_db: 'qrest_api' } };
module.exports = { db: { qrest_api:{ $filter: 'env', $base: { options: {} }, production: { url: process.env.MONGODB_URL || 'mongodb://mongodb:27017/qrest_api' }, $default: { url: process.env.MONGODB_URL || 'mongodb://localhost:27017/qrest_api' } }, default_db: 'qrest_api' } };
Add env override for mongodb url
Add env override for mongodb url
JavaScript
apache-2.0
jgrenon/qrest-api-server
--- +++ @@ -6,10 +6,10 @@ options: {} }, production: { - url: 'mongodb://mongodb:27017/qrest_api' + url: process.env.MONGODB_URL || 'mongodb://mongodb:27017/qrest_api' }, $default: { - url: 'mongodb://localhost:27017/qrest_api' + url: process.env.MONGODB_URL || 'mongodb://localhost:27017/qrest_api' } }, default_db: 'qrest_api'
86fd65dddd74cc679ca1dea3fcdbb36c3ed7e723
bin/cli.js
bin/cli.js
#!/usr/bin/env node console.log('hits cli.js file');
#!/usr/bin/env node var program = require('commander'); var prompt = require('inquirer'); var path = require('path'); var pkg = require(path.resolve(__dirname, '..', 'package.json')); program.version(pkg.version) program .command('new') .action(function() { console.log('hits new command'); }); program.parse(process.argv);
Add in base CLI interface
feat: Add in base CLI interface
JavaScript
mit
code-computerlove/quarry,code-computerlove/slate-cli,cartridge/cartridge-cli
--- +++ @@ -1,3 +1,17 @@ #!/usr/bin/env node -console.log('hits cli.js file'); +var program = require('commander'); +var prompt = require('inquirer'); +var path = require('path'); + +var pkg = require(path.resolve(__dirname, '..', 'package.json')); + +program.version(pkg.version) + +program + .command('new') + .action(function() { + console.log('hits new command'); + }); + +program.parse(process.argv);
964abe02bbcfa8db34d6886feb79088397da5700
build/concat.js
build/concat.js
module.exports = { all: { options: { separator: ';', }, files: { 'dist/js/binary.js': [ 'src/javascript/lib/jquery.js', 'src/javascript/lib/highstock/highstock.js', 'src/javascript/lib/highstock/highstock-exporting.js', 'src/javascript/lib/moment/moment.js', 'src/javascript/lib/**/*.js', 'src/javascript/autogenerated/idd_codes.js', 'src/javascript/autogenerated/texts.js', 'src/javascript/autogenerated/*.js', 'src/javascript/binary/base/*.js', 'src/javascript/binary/**/*.js', 'src/javascript/binary_japan/*.js' ] } } };
module.exports = { all: { options: { separator: ';', }, files: { 'dist/js/binary.js': [ 'src/javascript/lib/jquery.js', 'src/javascript/lib/highstock/highstock.js', 'src/javascript/lib/highstock/highstock-exporting.js', 'src/javascript/lib/moment/moment.js', 'src/javascript/lib/**/*.js', 'src/javascript/autogenerated/idd_codes.js', 'src/javascript/autogenerated/texts.js', 'src/javascript/autogenerated/*.js', 'src/javascript/binary/base/*.js', 'src/javascript/binary/**/*.js', 'src/javascript/binary_japan/**/*.js' ] } } };
Allow binary_japan to have dir
Allow binary_japan to have dir
JavaScript
apache-2.0
junbon/binary-static-www2,junbon/binary-static-www2
--- +++ @@ -15,7 +15,7 @@ 'src/javascript/autogenerated/*.js', 'src/javascript/binary/base/*.js', 'src/javascript/binary/**/*.js', - 'src/javascript/binary_japan/*.js' + 'src/javascript/binary_japan/**/*.js' ] } }
1a420d9d243983fad908021fc13e90a101f8e58b
src/anol/geocoder/base.js
src/anol/geocoder/base.js
anol.geocoder.Base = function(_options) { if(_options === undefined) { return; } this.url = _options.url; this.options = _options; }; anol.geocoder.Base.prototype = { CLASS_NAME: 'anol.geocoder.Base', handleResponse: function(response) { var self = this; var results = []; $.each(response, function(idx, result) { results.push({ displayText: self.extractDisplayText(result), coordinate: self.extractCoordinate(result), projectionCode: self.RESULT_PROJECTION }); }); return results; }, request: function(searchString) { var self = this; var deferred = $.Deferred(); if(this.options.method === 'post') { $.post(self.url, self.getData(searchString)) .success(function(response) { var results = self.handleResponse(response); deferred.resolve(results); }); } else { $.get(self.getUrl(searchString)) .success(function(response) { var results = self.handleResponse(response); deferred.resolve(results); }); } return deferred.promise(); }, extractDisplayText: function() { throw 'Not implemented'; }, extractCoordinate: function() { throw 'Not implemented'; }, getUrl: function() { throw 'Not implemented'; }, getData: function(searchString) { return { search: searchString }; } };
anol.geocoder.Base = function(_options) { if(_options === undefined) { return; } this.url = _options.url; this.options = _options; }; anol.geocoder.Base.prototype = { CLASS_NAME: 'anol.geocoder.Base', handleResponse: function(response) { var self = this; var results = []; $.each(response, function(idx, result) { results.push({ displayText: self.extractDisplayText(result), coordinate: self.extractCoordinate(result), projectionCode: self.RESULT_PROJECTION }); }); return results; }, request: function(searchString) { var self = this; var deferred = $.Deferred(); if(this.options.method === 'post') { $.post(self.url, self.getData(searchString)) .success(function(response) { var results = self.handleResponse(response); deferred.resolve(results); }) .fail(function() { deferred.resolve([]); }); } else { $.get(self.getUrl(searchString)) .success(function(response) { var results = self.handleResponse(response); deferred.resolve(results); }) .fail(function() { deferred.resolve([]); }); } return deferred.promise(); }, extractDisplayText: function() { throw 'Not implemented'; }, extractCoordinate: function() { throw 'Not implemented'; }, getUrl: function() { throw 'Not implemented'; }, getData: function(searchString) { return { search: searchString }; } };
Handle failed geocoder requests correct
Handle failed geocoder requests correct
JavaScript
mit
omniscale/anol,omniscale/anol
--- +++ @@ -28,12 +28,18 @@ .success(function(response) { var results = self.handleResponse(response); deferred.resolve(results); + }) + .fail(function() { + deferred.resolve([]); }); } else { $.get(self.getUrl(searchString)) .success(function(response) { var results = self.handleResponse(response); deferred.resolve(results); + }) + .fail(function() { + deferred.resolve([]); }); } return deferred.promise();
3209c40ebe0070a4430009f6f703cf3fcf95e6f8
assets/js/modules/pagespeed-insights/settings/index.js
assets/js/modules/pagespeed-insights/settings/index.js
/** * WordPress dependencies */ import { __, sprintf } from '@wordpress/i18n'; /** * External dependencies */ import { sanitizeHTML } from 'assets/js/util'; export const settingsDetails = () => { const { dashboardPermalink } = global.googlesitekit; /* translators: %s is the URL to the Site Kit dashboard. */ const content = sprintf( __( 'To view insights, <a href="%s">visit the dashboard</a>.', 'google-site-kit' ), dashboardPermalink ); return ( <p dangerouslySetInnerHTML={ sanitizeHTML( content, { ALLOWED_TAGS: [ 'a' ], ALLOWED_ATTR: [ 'href' ], } ) } /> ); };
/** * WordPress dependencies */ import { __, sprintf } from '@wordpress/i18n'; /** * External dependencies */ import { sanitizeHTML } from 'assets/js/util'; export const settingsDetails = () => { const { dashboardPermalink } = global.googlesitekit; const content = sprintf( /* translators: %s is the URL to the Site Kit dashboard. */ __( 'To view insights, <a href="%s">visit the dashboard</a>.', 'google-site-kit' ), dashboardPermalink ); return ( <p dangerouslySetInnerHTML={ sanitizeHTML( content, { ALLOWED_TAGS: [ 'a' ], ALLOWED_ATTR: [ 'href' ], } ) } /> ); };
Fix placement of translators comment.
Fix placement of translators comment.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -11,8 +11,8 @@ export const settingsDetails = () => { const { dashboardPermalink } = global.googlesitekit; - /* translators: %s is the URL to the Site Kit dashboard. */ const content = sprintf( + /* translators: %s is the URL to the Site Kit dashboard. */ __( 'To view insights, <a href="%s">visit the dashboard</a>.', 'google-site-kit' ), dashboardPermalink );
f0c7e9ae7ee156ddce2ab5c715b0f281deb3e8b8
source/javascripts/octopress.js
source/javascripts/octopress.js
function renderDeliciousLinks(items) { var output = '<ul class="divided">'; for (var i = 0, l = items.length; i < l; i++) { output += '<li><a href="' + items[i].u + '" title="Tags: ' + (items[i].t == "" ? "" : items[i].t.join(', ')) + '">' + items[i].d + '</a></li>'; } output += '</ul>'; jQuery('#delicious').html(output); } jQuery(function(){ var gravatarImage = jQuery('img.gravatar'), email = jQuery(gravatarImage).data('gravatar'); if (email) { jQuery(gravatarImage).attr({src: 'http://www.gravatar.com/avatar/' + CryptoJS.MD5(email) + '?s=250'}).removeAttr('data-gravatar'); } });
function renderDeliciousLinks(items) { var output = '<ul class="divided">'; for (var i = 0, l = items.length; i < l; i++) { output += '<li><a href="' + items[i].u + '" title="Tags: ' + (items[i].t == "" ? "" : items[i].t.join(', ')) + '">' + items[i].d + '</a></li>'; } output += '</ul>'; jQuery('#delicious').html(output); } jQuery(function(){ var gravatarImage = jQuery('img.hero__gravatar'), email = jQuery(gravatarImage).data('gravatar'); if (email) { jQuery(gravatarImage).attr({src: 'http://www.gravatar.com/avatar/' + CryptoJS.MD5(email) + '?s=250'}).removeAttr('data-gravatar'); } });
Fix reference to Gravatar img tag
Fix reference to Gravatar img tag
JavaScript
mit
coogie/oscailte,coogie/oscailte
--- +++ @@ -8,7 +8,7 @@ } jQuery(function(){ - var gravatarImage = jQuery('img.gravatar'), + var gravatarImage = jQuery('img.hero__gravatar'), email = jQuery(gravatarImage).data('gravatar'); if (email) { jQuery(gravatarImage).attr({src: 'http://www.gravatar.com/avatar/' + CryptoJS.MD5(email) + '?s=250'}).removeAttr('data-gravatar');
ecd6381d3fa70c393aa8892ed696093600583111
src/App/Body/ErrorDialog.js
src/App/Body/ErrorDialog.js
import React from 'react'; import Dialog from 'material-ui/lib/dialog'; import FlatButton from 'material-ui/lib/flat-button'; export default ({ open, closeMe }) => ( <Dialog title="Error" open={open} actions={[ <FlatButton label="OK" primary={true} onTouchTap={this.closeErrorModal} /> ]} modal={false} onRequestClose={closeMe} > The input was invalid. </Dialog> );
Split out error dialog into component
Split out error dialog into component
JavaScript
cc0-1.0
ksmithbaylor/emc-license-summarizer,ksmithbaylor/emc-license-summarizer,ksmithbaylor/emc-license-summarizer
--- +++ @@ -0,0 +1,22 @@ +import React from 'react'; + +import Dialog from 'material-ui/lib/dialog'; +import FlatButton from 'material-ui/lib/flat-button'; + +export default ({ open, closeMe }) => ( + <Dialog + title="Error" + open={open} + actions={[ + <FlatButton + label="OK" + primary={true} + onTouchTap={this.closeErrorModal} + /> + ]} + modal={false} + onRequestClose={closeMe} + > + The input was invalid. + </Dialog> +);
c190d2d5317b6075a2a923bd6b61764c25fbd099
rollup.config.js
rollup.config.js
import uglify from 'rollup-plugin-uglify'; import commonjs from 'rollup-plugin-commonjs'; import resolve from 'rollup-plugin-node-resolve'; export default { name: 'KeyCode', input: 'index.js', output: { format: 'umd', file: 'dist/keycode.min.js' }, sourcemap: true, plugins: [ resolve({ jsnext: true, main: true, browser: true, }), commonjs(), uglify() ] };
import { uglify } from 'rollup-plugin-uglify'; import commonjs from 'rollup-plugin-commonjs'; import resolve from 'rollup-plugin-node-resolve'; export default { name: 'KeyCode', input: 'index.js', output: { format: 'umd', file: 'dist/keycode.min.js' }, sourcemap: true, plugins: [ resolve({ jsnext: true, main: true, browser: true, }), commonjs(), uglify() ] };
Use named import for uglify rollup plugin
Use named import for uglify rollup plugin
JavaScript
mit
kabirbaidhya/keycode-js,kabirbaidhya/keycode-js,kabirbaidhya/keycode-js,kabirbaidhya/keycode-js
--- +++ @@ -1,4 +1,4 @@ -import uglify from 'rollup-plugin-uglify'; +import { uglify } from 'rollup-plugin-uglify'; import commonjs from 'rollup-plugin-commonjs'; import resolve from 'rollup-plugin-node-resolve';
cecc6b4c8ce022b874b63450005d2e52ddc9cde7
guts/router.js
guts/router.js
var routeList = require('../config/routeList'); var router = require('koa-router'); var controllers = require('./controllers') var views = require('./views'); module.exports = function(app){ app.use(views('./views', { map: { html: 'underscore' }, locals: { title: 'with underscore' }, cache: false })); app.use(router(app)); for(var k in routeList){ var functionsToCall = [] var routeData = k.split(' '); var method = routeData[0].toLowerCase(); var route = routeData[1]; functionsToCall.push(route); var actionList = routeList[k].split(' '); for(var i=0; i<actionList.length; i+=1){ var actionData = actionList[i].split('.'); var cont = actionData[0]; var action = actionData[1]; functionsToCall.push(controllers[cont][action]); } // var actionData = routeList[k].split('.'); // var cont = actionData[0]; // var action = actionData[1]; app[method].apply(null, functionsToCall); } }
var routeList = require('../config/routeList'); var router = require('koa-router'); var controllers = require('./controllers') var views = require('./views'); module.exports = function(app){ app.use(views('./views', { map: { html: 'ejs', ejs: 'ejs' }, locals: { title: 'with underscore' }, cache: false })); app.use(router(app)); for(var k in routeList){ var functionsToCall = [] var routeData = k.split(' '); var method = routeData[0].toLowerCase(); var route = routeData[1]; functionsToCall.push(route); var actionList = routeList[k].split(' '); for(var i=0; i<actionList.length; i+=1){ var actionData = actionList[i].split('.'); var cont = actionData[0]; var action = actionData[1]; functionsToCall.push(controllers[cont][action]); } // var actionData = routeList[k].split('.'); // var cont = actionData[0]; // var action = actionData[1]; app[method].apply(null, functionsToCall); } }
Make it so HTML and EJS are both rendering via EJS.
Make it so HTML and EJS are both rendering via EJS.
JavaScript
bsd-2-clause
Tombert/frameworkey
--- +++ @@ -6,7 +6,8 @@ module.exports = function(app){ app.use(views('./views', { map: { - html: 'underscore' + html: 'ejs', + ejs: 'ejs' }, locals: { title: 'with underscore'
1d5fade0858d0c95b89dacd6db51c14250755f27
app/routes/interestgroups/InterestGroupDetailRoute.js
app/routes/interestgroups/InterestGroupDetailRoute.js
import { compose } from 'redux'; import { connect } from 'react-redux'; import prepare from 'app/utils/prepare'; import { joinGroup, leaveGroup, fetchGroup, fetchMemberships, } from 'app/actions/GroupActions'; import InterestGroupDetail from './components/InterestGroupDetail'; import { selectMembershipsForGroup } from 'app/reducers/memberships'; import { selectGroup } from 'app/reducers/groups'; import loadingIndicator from 'app/utils/loadingIndicator'; const mapStateToProps = (state, props) => { const { interestGroupId } = props.match.params; const group = selectGroup(state, { groupId: interestGroupId }); const memberships = selectMembershipsForGroup(state, { groupId: interestGroupId, }); return { group: { ...group, memberships, }, interestGroupId, }; }; const mapDispatchToProps = { joinGroup, leaveGroup, }; export default compose( prepare( ( { match: { params: { interestGroupId }, }, }, dispatch ) => Promise.all([ dispatch(fetchGroup(Number(interestGroupId))), dispatch(fetchMemberships(interestGroupId)), ]), ['match.params.interestGroupId'] ), connect(mapStateToProps, mapDispatchToProps), loadingIndicator(['group']) )(InterestGroupDetail);
import { compose } from 'redux'; import { connect } from 'react-redux'; import prepare from 'app/utils/prepare'; import { joinGroup, leaveGroup, fetchGroup, fetchAllMemberships, } from 'app/actions/GroupActions'; import InterestGroupDetail from './components/InterestGroupDetail'; import { selectMembershipsForGroup } from 'app/reducers/memberships'; import { selectGroup } from 'app/reducers/groups'; import loadingIndicator from 'app/utils/loadingIndicator'; const mapStateToProps = (state, props) => { const { interestGroupId } = props.match.params; const group = selectGroup(state, { groupId: interestGroupId }); const memberships = selectMembershipsForGroup(state, { groupId: interestGroupId, }); return { group: { ...group, memberships, }, interestGroupId, }; }; const mapDispatchToProps = { joinGroup, leaveGroup, }; export default compose( prepare( ( { match: { params: { interestGroupId }, }, }, dispatch ) => Promise.all([ dispatch(fetchGroup(Number(interestGroupId))), dispatch(fetchAllMemberships(interestGroupId)), ]), ['match.params.interestGroupId'] ), connect(mapStateToProps, mapDispatchToProps), loadingIndicator(['group']) )(InterestGroupDetail);
Update interestGroup to fetch all members
Update interestGroup to fetch all members
JavaScript
mit
webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp
--- +++ @@ -5,7 +5,7 @@ joinGroup, leaveGroup, fetchGroup, - fetchMemberships, + fetchAllMemberships, } from 'app/actions/GroupActions'; import InterestGroupDetail from './components/InterestGroupDetail'; import { selectMembershipsForGroup } from 'app/reducers/memberships'; @@ -46,7 +46,7 @@ ) => Promise.all([ dispatch(fetchGroup(Number(interestGroupId))), - dispatch(fetchMemberships(interestGroupId)), + dispatch(fetchAllMemberships(interestGroupId)), ]), ['match.params.interestGroupId']
685f58c77394c593f9af98dd9dfbfea8bbc4c239
src/modules/controls/OrbitModule.js
src/modules/controls/OrbitModule.js
import {Vector3} from 'three'; import {ThreeOrbitControls} from './lib/ThreeOrbitControls'; export class OrbitModule { constructor(params = {}) { this.params = Object.assign({ target: new Vector3(0, 0, 0), follow: false }, params); } manager(manager) { this.controls = new ThreeOrbitControls( manager.get('camera').native, manager.get('renderer').domElement ); manager.update({ camera: (camera) => { this.controls.object = camera.native; } }); } integrate(self) { const {params, controls} = self; const updateProcessor = params.follow ? (c) => { controls.update(c.getDelta()); controls.target.copy(params.target); } : (c) => { controls.update(c.getDelta()); }; self.updateLoop = new WHS.Loop(updateProcessor).start(this); controls.target.copy(params.target); } }
import {Vector3} from 'three'; import {Loop} from '../../core/Loop'; import {ThreeOrbitControls} from './lib/ThreeOrbitControls'; export class OrbitModule { constructor(params = {}) { this.params = Object.assign({ target: new Vector3(0, 0, 0), follow: false }, params); } manager(manager) { this.controls = new ThreeOrbitControls( manager.get('camera').native, manager.get('renderer').domElement ); manager.update({ camera: (camera) => { this.controls.object = camera.native; } }); } integrate(self) { const {params, controls} = self; const updateProcessor = params.follow ? (c) => { controls.update(c.getDelta()); controls.target.copy(params.target); } : (c) => { controls.update(c.getDelta()); }; self.updateLoop = new Loop(updateProcessor).start(this); controls.target.copy(params.target); } }
Fix Loop dependency in OrbitControls
Fix Loop dependency in OrbitControls Former-commit-id: 8a856c3abacefad6dd5679baa714fe7bc24446ee
JavaScript
mit
WhitestormJS/whs.js,WhitestormJS/whs.js
--- +++ @@ -1,4 +1,6 @@ import {Vector3} from 'three'; + +import {Loop} from '../../core/Loop'; import {ThreeOrbitControls} from './lib/ThreeOrbitControls'; export class OrbitModule { @@ -32,7 +34,7 @@ controls.update(c.getDelta()); }; - self.updateLoop = new WHS.Loop(updateProcessor).start(this); + self.updateLoop = new Loop(updateProcessor).start(this); controls.target.copy(params.target); }
6a619aa2629dc6bc049e7209265d8ee2cb9b72b2
rollup.config.js
rollup.config.js
import babel from 'rollup-plugin-babel'; import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import { terser } from 'rollup-plugin-terser'; import pkg from './package.json'; const input = 'src/index.js'; const plugins = [ babel({ exclude: '**/node_modules/**' }), ]; const name = 'ReactStayScrolled'; const globals = { react: 'React' }; const external = id => !id.startsWith('.') && !id.startsWith('/'); export default [{ external, input, output: { file: `dist/${pkg.name}.cjs.js`, format: 'cjs' }, plugins, }, { external, input, output: { file: `dist/${pkg.name}.esm.js`, format: 'esm' }, plugins, }, { external: Object.keys(globals), input, output: { file: `dist/${pkg.name}.umd.js`, format: 'umd', globals, name, }, plugins: [ ...plugins, resolve(), commonjs(), terser(), ], }];
import babel from 'rollup-plugin-babel'; import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import { terser } from 'rollup-plugin-terser'; import pkg from './package.json'; const input = 'src/index.js'; const plugins = [ babel({ exclude: '**/node_modules/**' }), ]; const name = 'ReactStayScrolled'; const globals = { react: 'React' }; const external = id => !id.startsWith('.') && !id.startsWith('/'); export default [{ external, input, output: { file: `dist/${pkg.name}.cjs.js`, format: 'cjs', exports: 'named' }, plugins, }, { external, input, output: { file: `dist/${pkg.name}.esm.js`, format: 'esm' }, plugins, }, { external: Object.keys(globals), input, output: { file: `dist/${pkg.name}.umd.js`, format: 'umd', globals, name, exports: 'named', }, plugins: [ ...plugins, resolve(), commonjs(), terser(), ], }];
Fix umd and cjs export names
Fix umd and cjs export names
JavaScript
mit
perrin4869/react-stay-scrolled
--- +++ @@ -17,7 +17,7 @@ export default [{ external, input, - output: { file: `dist/${pkg.name}.cjs.js`, format: 'cjs' }, + output: { file: `dist/${pkg.name}.cjs.js`, format: 'cjs', exports: 'named' }, plugins, }, { external, @@ -28,7 +28,7 @@ external: Object.keys(globals), input, output: { - file: `dist/${pkg.name}.umd.js`, format: 'umd', globals, name, + file: `dist/${pkg.name}.umd.js`, format: 'umd', globals, name, exports: 'named', }, plugins: [ ...plugins,
7a47a3665290f18a51a13fb183e3c388bff83691
src/index.js
src/index.js
// Loaded ready states const loadedStates = ['interactive', 'complete']; // Return Promise module.exports = (cb, doc) => new Promise(resolve => { // Use global document if we don't have one doc = doc || document; // Handle DOM load const done = () => resolve(cb && cb()); // Resolve now if DOM has already loaded // Otherwise wait for DOMContentLoaded if (loadedStates.includes(doc.readyState)) { done(); } else { doc.addEventListener('DOMContentLoaded', done); } });
// Loaded ready states const loadedStates = ['interactive', 'complete']; // Return Promise module.exports = (cb, doc) => new Promise(resolve => { // Allow doc to be passed in as the lone first param if (cb && typeof cb !== 'function') { doc = cb; cb = null; } // Use global document if we don't have one doc = doc || document; // Handle DOM load const done = () => resolve(cb && cb()); // Resolve now if DOM has already loaded // Otherwise wait for DOMContentLoaded if (loadedStates.includes(doc.readyState)) { done(); } else { doc.addEventListener('DOMContentLoaded', done); } });
Allow doc to be passed in as the lone first param
Allow doc to be passed in as the lone first param
JavaScript
mit
lukechilds/when-dom-ready
--- +++ @@ -3,6 +3,12 @@ // Return Promise module.exports = (cb, doc) => new Promise(resolve => { + // Allow doc to be passed in as the lone first param + if (cb && typeof cb !== 'function') { + doc = cb; + cb = null; + } + // Use global document if we don't have one doc = doc || document;
ed3ec4d2b860c259bb4d50dc972a891f8e1492c8
src/components/Sidebar.js
src/components/Sidebar.js
import React, { Component } from 'react'; import GBox from 'grommet/components/Box'; import GParagraph from 'grommet/components/Paragraph'; import GHeading from 'grommet/components/Heading'; import CLineList from '../containers/CLineList'; const Sidebar = ({ mode, toggleMode, numberOfBends, totalLength }) => { const style = { padding: '0px', margin: '0px', marginBottom: '5px', WebkitUserSelect: 'none' }; return ( <GBox style={{ width: '300px' }}> <GBox pad="medium"> <GHeading tag="h3" style={{ WebkitUserSelect: 'none' }}>Details</GHeading> <GParagraph size="small" style={style}># of Bends: { numberOfBends }</GParagraph> <GParagraph size="small" style={style}>Total Length: { totalLength }</GParagraph> </GBox> <CLineList /> </GBox> ); }; export default Sidebar;
import React, { Component } from 'react'; import GBox from 'grommet/components/Box'; import GParagraph from 'grommet/components/Paragraph'; import GHeading from 'grommet/components/Heading'; import CLineList from '../containers/CLineList'; class Sidebar extends React.Component { constructor(props) { super(props); this.handleSelect = this.handleSelect.bind(this); this.state = { type: undefined, color: undefined, }; } handleSelect(e) { const name = e.target.name; const value = e.target.value; this.setState({ [name]: value, }); } render() { const { numberOfBends, totalLength } = this.props; const style = { padding: '0px', margin: '0px', marginBottom: '5px', WebkitUserSelect: 'none' }; return ( <GBox style={{ width: '300px' }}> <GBox pad="medium"> <GHeading tag="h3" style={{ WebkitUserSelect: 'none' }}>Details</GHeading> <GParagraph size="small" style={style}>Number of Bends: { numberOfBends }</GParagraph> <GParagraph size="small" style={style}>Total Length: { totalLength }</GParagraph> <GParagraph size="small" style={style}> Type: <select name="type" onChange={this.handleSelect}> <option>Type A</option> <option>Type B</option> </select> </GParagraph> <GParagraph size="small" style={style}> Color: <select name="color" onChange={this.handleSelect}> <option>Color A</option> <option>Color B</option> </select> </GParagraph> </GBox> <CLineList /> </GBox> ); } } export default Sidebar;
Transform sidebar into traditional class and add type and color selectors
Transform sidebar into traditional class and add type and color selectors
JavaScript
mit
rjbernaldo/lines,rjbernaldo/lines
--- +++ @@ -6,18 +6,57 @@ import CLineList from '../containers/CLineList'; -const Sidebar = ({ mode, toggleMode, numberOfBends, totalLength }) => { - const style = { padding: '0px', margin: '0px', marginBottom: '5px', WebkitUserSelect: 'none' }; - return ( - <GBox style={{ width: '300px' }}> - <GBox pad="medium"> - <GHeading tag="h3" style={{ WebkitUserSelect: 'none' }}>Details</GHeading> - <GParagraph size="small" style={style}># of Bends: { numberOfBends }</GParagraph> - <GParagraph size="small" style={style}>Total Length: { totalLength }</GParagraph> +class Sidebar extends React.Component { + constructor(props) { + super(props); + + this.handleSelect = this.handleSelect.bind(this); + + this.state = { + type: undefined, + color: undefined, + }; + } + + handleSelect(e) { + const name = e.target.name; + const value = e.target.value; + + this.setState({ + [name]: value, + }); + } + + render() { + const { numberOfBends, totalLength } = this.props; + + const style = { padding: '0px', margin: '0px', marginBottom: '5px', WebkitUserSelect: 'none' }; + return ( + <GBox style={{ width: '300px' }}> + <GBox pad="medium"> + <GHeading tag="h3" style={{ WebkitUserSelect: 'none' }}>Details</GHeading> + <GParagraph size="small" style={style}>Number of Bends: { numberOfBends }</GParagraph> + <GParagraph size="small" style={style}>Total Length: { totalLength }</GParagraph> + <GParagraph size="small" style={style}> + Type: + <select name="type" onChange={this.handleSelect}> + <option>Type A</option> + <option>Type B</option> + </select> + </GParagraph> + <GParagraph size="small" style={style}> + Color: + <select name="color" onChange={this.handleSelect}> + <option>Color A</option> + <option>Color B</option> + </select> + </GParagraph> + </GBox> + <CLineList /> </GBox> - <CLineList /> - </GBox> - ); -}; + ); + } +} export default Sidebar; +
eff5178476db5a6326312b5c4f6026d86c1546e5
lib/helpers.js
lib/helpers.js
var exec = require('child_process').exec module.exports.asyncIterate = function(array, callback, done) { function iterate(idx) { var current = array[idx] if (current) { callback(current, function() { iterate(idx+1) }, function(err) { done(err) }) } else { done() } } iterate(0) } module.exports.checkRunning = function(container, callback) { exec('docker inspect ' + container.name, function(err) { var isRunning = err ? false : true callback(isRunning) }) }
var exec = require('child_process').exec, _ = require('lodash') module.exports.asyncIterate = function(array, callback, done) { function iterate(idx) { var current = array[idx] if (current) { callback(current, function() { iterate(idx+1) }, function(err) { done(err) }) } else { done() } } iterate(0) } module.exports.checkRunning = function(container, callback) { exec('docker inspect ' + container.name, function(err, stdout) { if (err) { callback(false) } else { var info = _.head(JSON.parse(stdout)) var isRunning = info && info.State ? !!info.State.Running : false callback(isRunning) } }) }
Fix “checkRunning” to return right container’s running status
Fix “checkRunning” to return right container’s running status
JavaScript
mit
mnylen/pig,mnylen/pig
--- +++ @@ -1,4 +1,6 @@ -var exec = require('child_process').exec +var exec = require('child_process').exec, + _ = require('lodash') + module.exports.asyncIterate = function(array, callback, done) { function iterate(idx) { @@ -15,9 +17,14 @@ } module.exports.checkRunning = function(container, callback) { - exec('docker inspect ' + container.name, function(err) { - var isRunning = err ? false : true - callback(isRunning) + exec('docker inspect ' + container.name, function(err, stdout) { + if (err) { + callback(false) + } else { + var info = _.head(JSON.parse(stdout)) + var isRunning = info && info.State ? !!info.State.Running : false + callback(isRunning) + } }) }
2daafd8e8c94bb3baa6c3a0a92bfef469e237b34
contourd/recommendation/plugins/scripted/links/main.js
contourd/recommendation/plugins/scripted/links/main.js
index = 0; config = self.getConfig(); function add(url, title, description, icon) { if (config.BoolValue(url, false) == false) { self.addRecommendation(0.0, url, title, description, icon); } } add("http://www.kde.org/", "KDE community", "The people behind Plasma Active", "kde"); add("http://plasma.kde.org/active/help", "Usage manual", "How to use Plasma Active", "help-about"); self.activationRequested.connect(function fn(id, action) { self.openUrl(id); config.SetBoolValue(id, true); });
index = 0; config = self.getConfig(); function add(url, title, description, icon) { if (config.BoolValue(url, false) == false) { self.addRecommendation(0.0, url, title, description, icon); } } add("http://www.kde.org/", "KDE community", "The people behind Plasma Active", "kde"); add("http://community.kde.org/Plasma/Active/Info#FAQ", "Usage manual", "How to use Plasma Active", "help-about"); self.activationRequested.connect(function fn(id, action) { self.openUrl(id); config.SetBoolValue(id, true); });
Change broken url for one with usefull info.
Change broken url for one with usefull info.
JavaScript
lgpl-2.1
KDE/contour,KDE/contour,KDE/contour
--- +++ @@ -9,7 +9,7 @@ } add("http://www.kde.org/", "KDE community", "The people behind Plasma Active", "kde"); -add("http://plasma.kde.org/active/help", "Usage manual", "How to use Plasma Active", "help-about"); +add("http://community.kde.org/Plasma/Active/Info#FAQ", "Usage manual", "How to use Plasma Active", "help-about"); self.activationRequested.connect(function fn(id, action) { self.openUrl(id);
29ecf0322654ac415df36802f403dad414bc5afe
server/auth/index.js
server/auth/index.js
const logger = require('../logging'); const passport = require('passport'); const { setupOIDC } = require('./oidc'); const { deserializeUser } = require('./user'); module.exports = async (app) => { await setupOIDC(); passport.serializeUser((user, done) => { logger.silly('Serializing user', { userId: user.id }); done(null, user.id); }); passport.deserializeUser(deserializeUser); app.use(passport.initialize()); app.use(passport.session()); app.get('/login', passport.authenticate('oidc')); app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); app.get('/auth', passport.authenticate('oidc', { successRedirect: '/', failureRedirect: '/' })); return app; };
const passport = require('passport'); const { setupOIDC } = require('./oidc'); const { deserializeUser } = require('./user'); module.exports = async (app) => { await setupOIDC(); passport.serializeUser((user, done) => done(null, user.id)); passport.deserializeUser(deserializeUser); app.use(passport.initialize()); app.use(passport.session()); app.get('/login', passport.authenticate('oidc')); app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); app.get('/auth', passport.authenticate('oidc', { successRedirect: '/', failureRedirect: '/' })); return app; };
Simplify deserialization call and remove unnecessary logging.
Simplify deserialization call and remove unnecessary logging.
JavaScript
mit
dotkom/super-duper-fiesta,dotkom/super-duper-fiesta,dotkom/super-duper-fiesta
--- +++ @@ -1,4 +1,3 @@ -const logger = require('../logging'); const passport = require('passport'); const { setupOIDC } = require('./oidc'); const { deserializeUser } = require('./user'); @@ -6,11 +5,7 @@ module.exports = async (app) => { await setupOIDC(); - passport.serializeUser((user, done) => { - logger.silly('Serializing user', { userId: user.id }); - done(null, user.id); - }); - + passport.serializeUser((user, done) => done(null, user.id)); passport.deserializeUser(deserializeUser); app.use(passport.initialize()); app.use(passport.session());
d9b87491c95c1caaf6e14f31723ae3978babc918
lib/helpers.js
lib/helpers.js
'use babel' const COLOR_EXTRACTION_REGEXP = /rgb\(\d+, \d+, \d+\)|\#[0-9a-f]{3,6}/ export function isColor(textEditor, bufferPosition) { const lineText = textEditor.getTextInRange([[bufferPosition.row, 0], [bufferPosition.row, Infinity]]) const matches = COLOR_EXTRACTION_REGEXP.exec(lineText) if (matches === null) { return false } const offsetStart = matches.index const offsetEnd = offsetStart + matches[0].length return bufferPosition.column >= offsetStart && offsetEnd >= bufferPosition.column }
'use babel' const COLOR_EXTRACTION_REGEXP = /rgb\(\d+, ?\d+, ?\d+\)|rgba\(\d+, ?\d+, ?\d+, ?\d?\.?\d+\)|#[0-9a-f]{3,6}/ export function isColor(textEditor, bufferPosition) { const lineText = textEditor.getTextInRange([[bufferPosition.row, 0], [bufferPosition.row, Infinity]]) const matches = COLOR_EXTRACTION_REGEXP.exec(lineText) if (matches === null) { return false } const offsetStart = matches.index const offsetEnd = offsetStart + matches[0].length return bufferPosition.column >= offsetStart && offsetEnd >= bufferPosition.column }
Add rgba support to regex
:new: Add rgba support to regex
JavaScript
mit
steelbrain/intentions-colorpicker
--- +++ @@ -1,6 +1,6 @@ 'use babel' -const COLOR_EXTRACTION_REGEXP = /rgb\(\d+, \d+, \d+\)|\#[0-9a-f]{3,6}/ +const COLOR_EXTRACTION_REGEXP = /rgb\(\d+, ?\d+, ?\d+\)|rgba\(\d+, ?\d+, ?\d+, ?\d?\.?\d+\)|#[0-9a-f]{3,6}/ export function isColor(textEditor, bufferPosition) { const lineText = textEditor.getTextInRange([[bufferPosition.row, 0], [bufferPosition.row, Infinity]])
e99b789a7086f889355edea3ab293640c3f719be
src/sass.js
src/sass.js
'use strict' let sass = require('node-sass') /* * Transform SASS to CSS. * @public * @param {string} folderPath - Path to the folder containing the SASS file. * @param {string} str - SASS. * @param {Object} opts - Options for the task. * @param {function} next - The callback that handles the response. Receives the following properties: err, css. */ module.exports = function(folderPath, str, opts, next) { // Dismiss sourceMap when output should be optimized let map = (opts.optimize===true ? false : true) sass.render({ data : str, includePaths : [ folderPath ], sourceMap : map, sourceMapEmbed : true, sourceMapContents : true }, (err, result) => { if (err!=null) { next(err, null) return false } next(null, result.css.toString()) }) }
'use strict' let sass = require('node-sass') /* * Transform SASS to CSS. * @public * @param {string} folderPath - Path to the folder containing the SASS file. * @param {string} str - SASS. * @param {Object} opts - Options for the task. * @param {function} next - The callback that handles the response. Receives the following properties: err, css. */ module.exports = function(folderPath, str, opts, next) { // Dismiss sourceMap when output should be optimized let map = (opts.optimize===true ? false : true) sass.render({ data : str, includePaths : [ folderPath ], sourceMap : sourceMap, sourceMapEmbed : sourceMap, sourceMapContents : sourceMap }, (err, result) => { if (err!=null) { next(err, null) return false } next(null, result.css.toString()) }) }
Disable inline source map when optimization enabled
Disable inline source map when optimization enabled
JavaScript
mit
electerious/rosid-handler-sass,electerious/rosid-handler-scss
--- +++ @@ -19,9 +19,9 @@ data : str, includePaths : [ folderPath ], - sourceMap : map, - sourceMapEmbed : true, - sourceMapContents : true + sourceMap : sourceMap, + sourceMapEmbed : sourceMap, + sourceMapContents : sourceMap }, (err, result) => {
5eeb17a1aff26aa6d6ed38534af134aea905c065
src/app/store/createDevStore.js
src/app/store/createDevStore.js
export default function createDevToolsStore(onDispatch) { let currentState = { committedState: {}, stagedActions: [], computedStates: [], skippedActions: {}, currentStateIndex: 0 }; let listeners = []; function dispatch(action) { if (action.type[0] !== '@') onDispatch(action); return action; } function getState() { return currentState; } function setState(state) { currentState = state; listeners.forEach(listener => listener()); } function subscribe(listener) { listeners.push(listener); return function unsubscribe() { const index = listeners.indexOf(listener); listeners.splice(index, 1); }; } return { dispatch, getState, subscribe, liftedStore: { dispatch, getState, setState, subscribe } }; }
export default function createDevToolsStore(onDispatch) { let currentState = { committedState: {}, stagedActions: [], computedStates: [], skippedActions: {}, currentStateIndex: 0 }; let listeners = []; let initiated = false; function dispatch(action) { if (action.type[0] !== '@') onDispatch(action); return action; } function getState() { return currentState; } function isSet() { return initiated; } function setState(state) { currentState = state; listeners.forEach(listener => listener()); initiated = true; } function subscribe(listener) { listeners.push(listener); return function unsubscribe() { const index = listeners.indexOf(listener); listeners.splice(index, 1); }; } return { dispatch, getState, subscribe, liftedStore: { dispatch, getState, setState, subscribe, isSet } }; }
Check whether liftedStore is initiated
Check whether liftedStore is initiated
JavaScript
mit
zalmoxisus/redux-devtools-extension,zalmoxisus/redux-devtools-extension
--- +++ @@ -7,6 +7,7 @@ currentStateIndex: 0 }; let listeners = []; + let initiated = false; function dispatch(action) { if (action.type[0] !== '@') onDispatch(action); @@ -17,9 +18,14 @@ return currentState; } + function isSet() { + return initiated; + } + function setState(state) { currentState = state; listeners.forEach(listener => listener()); + initiated = true; } function subscribe(listener) { @@ -39,7 +45,8 @@ dispatch, getState, setState, - subscribe + subscribe, + isSet } }; }
e9cd59b69ecd25a80a71fdbbfdf2b96bcc1ff677
src/index.js
src/index.js
import { debug, context } from './utils' const version = require('../package.json').version import config from './config/config' import setup from './config/setup' import groups from './registry/registry' import { create, load } from './data/parser' if (debug) { console.warn('You are running the development build of Spirit.') const Spirit = function() { this.config = config this.version = version this.setup = setup this.groups = groups this.create = create this.load = load } export { config, version, setup, groups, create, load } const spirit = new Spirit() module.exports = spirit }
import { debug, context } from './utils' const version = require('../package.json').version import config from './config/config' import setup from './config/setup' import groups from './registry/registry' import { create, load } from './data/parser' if (debug) { console.warn(`You are running the development build of Spirit v${version}.`) } const Spirit = function() { this.config = config this.version = version this.setup = setup this.groups = groups this.create = create this.load = load } export { config, version, setup, groups, create, load } const spirit = new Spirit() module.exports = spirit }
Add version to debug info
Add version to debug info
JavaScript
mit
spirit/spirit
--- +++ @@ -8,7 +8,8 @@ import { create, load } from './data/parser' if (debug) { - console.warn('You are running the development build of Spirit.') + console.warn(`You are running the development build of Spirit v${version}.`) +} const Spirit = function() { this.config = config
8675d11a8aafe341e3146bd42c90c8b794d61243
packages/reddio-ui/src/screens/ListingResolver.js
packages/reddio-ui/src/screens/ListingResolver.js
import React from "react"; import { View } from "react-native"; import { withRouter } from "react-router"; import ListingProvider from "../app/ListingProvider"; import PostListSort from "../components/PostListSort"; import PostList from "../components/PostList"; class ListingResolver extends React.Component { render() { return ( <View> <ListingProvider pathname="/"> {({ data }) => { const posts = data.listing.posts; return ( <View> <PostListSort /> <PostList posts={posts} /> </View> ); }} </ListingProvider> </View> ); } } export default withRouter(ListingResolver);
import React from "react"; import { View } from "react-native"; import { withRouter } from "react-router"; import ListingProvider from "../app/ListingProvider"; import PostListSort from "../components/PostListSort"; import PostList from "../components/PostList"; class ListingResolver extends React.Component { render() { const { location } = this.props; const pathname = location.pathname + location.search; return ( <View> <ListingProvider pathname={pathname}> {({ data }) => { const posts = data.listing.posts; return ( <View> <PostListSort /> <PostList posts={posts} /> </View> ); }} </ListingProvider> </View> ); } } export default withRouter(ListingResolver);
Use real pathname from location
Use real pathname from location
JavaScript
mit
yanglinz/reddio-next,yanglinz/reddio-next,yanglinz/reddio-next
--- +++ @@ -8,9 +8,12 @@ class ListingResolver extends React.Component { render() { + const { location } = this.props; + const pathname = location.pathname + location.search; + return ( <View> - <ListingProvider pathname="/"> + <ListingProvider pathname={pathname}> {({ data }) => { const posts = data.listing.posts; return (
909b2837f927a4b5afdcccc2cb6e29a5e4b278c1
app/client/admin/components/shared/toolbar/toolbar.controller.js
app/client/admin/components/shared/toolbar/toolbar.controller.js
'use strict'; /** * @module opa */ (function(app) { /** * Manages opaToolbar component. * * @class OpaToolbarController * @constructor * @param {Object} $scope opa-toolbar isolated scope * @param {Object} $window JQLite element of the window * @param {Object} $mdMedia AngularJS Material service to evaluate media queries * @param {Object} $mdSidenav AngularJS Material service to manipulate sidenav directives * @param {Object} opaUserFactory User factory to manage authenticated user */ function OpaToolbarController($scope, $window, $mdMedia, $mdSidenav, opaUserFactory) { var ctrl = this; Object.defineProperties(ctrl, { /** * AngularJS Material $mdMedia service. * * @property $mdMedia * @type Object * @final */ $mdMedia: { value: $mdMedia } }); } app.controller('OpaToolbarController', OpaToolbarController); OpaToolbarController.$inject = ['$scope', '$window', '$mdMedia', '$mdSidenav', 'opaUserFactory']; })(angular.module('opa'));
'use strict'; /** * @module opa */ (function(app) { /** * Manages opaToolbar component. * * @class OpaToolbarController * @constructor * @param {Object} $mdMedia AngularJS Material service to evaluate media queries */ function OpaToolbarController($mdMedia) { var ctrl = this; Object.defineProperties(ctrl, { /** * AngularJS Material $mdMedia service. * * @property $mdMedia * @type Object * @final */ $mdMedia: { value: $mdMedia } }); } app.controller('OpaToolbarController', OpaToolbarController); OpaToolbarController.$inject = ['$mdMedia']; })(angular.module('opa'));
Remove unused dependencies from toolbar component
Remove unused dependencies from toolbar component
JavaScript
agpl-3.0
veo-labs/openveo-portal,veo-labs/openveo-portal,veo-labs/openveo-portal
--- +++ @@ -11,13 +11,9 @@ * * @class OpaToolbarController * @constructor - * @param {Object} $scope opa-toolbar isolated scope - * @param {Object} $window JQLite element of the window * @param {Object} $mdMedia AngularJS Material service to evaluate media queries - * @param {Object} $mdSidenav AngularJS Material service to manipulate sidenav directives - * @param {Object} opaUserFactory User factory to manage authenticated user */ - function OpaToolbarController($scope, $window, $mdMedia, $mdSidenav, opaUserFactory) { + function OpaToolbarController($mdMedia) { var ctrl = this; Object.defineProperties(ctrl, { @@ -37,6 +33,6 @@ } app.controller('OpaToolbarController', OpaToolbarController); - OpaToolbarController.$inject = ['$scope', '$window', '$mdMedia', '$mdSidenav', 'opaUserFactory']; + OpaToolbarController.$inject = ['$mdMedia']; })(angular.module('opa'));
c10cab06a2115995e818e4e7f8fde6882c554bed
test/all.js
test/all.js
/** * General test runner */ var fs = require('fs'); var files = fs.readdirSync(fs.realpathSync('./test')); console.log(files); for (var i in files) { var pattern = /^(test)\w*\.js$/; if (files.hasOwnProperty(i)) { pattern.lastIndex = 0; if (pattern.test(files[i])) { exports[files[i]] = require('./' + files[i].replace(/\.js/, '')); } } } require('test').run(exports);
/** * General test runner */ var fs = require('fs'); var files = fs.readdirSync(fs.realpathSync('./test')); for (var i in files) { var pattern = /^(test)\w*\.js$/; if (files.hasOwnProperty(i)) { pattern.lastIndex = 0; if (pattern.test(files[i])) { exports[files[i]] = require('./' + files[i].replace(/\.js/, '')); } } } require('test').run(exports);
Clean up overly verbose test output
Clean up overly verbose test output
JavaScript
mit
jay-depot/turnpike,jay-depot/turnpike
--- +++ @@ -4,8 +4,6 @@ var fs = require('fs'); var files = fs.readdirSync(fs.realpathSync('./test')); - -console.log(files); for (var i in files) { var pattern = /^(test)\w*\.js$/;
f0c0b33c3e7c69bc8e1b704a18f8e206e346cb57
src/index.js
src/index.js
var speculation = function speculation (fn) { // Don't cancel by default: var cancel = ( arguments.length > 1 && arguments[1] !== undefined ) ? arguments[1] : Promise.reject(); return new Promise(function (resolve, reject) { var noop = function noop () {}; var onCancel = function onCancel (handleCancel) { return cancel.then( handleCancel, // Filter out the expected "not cancelled" rejection: noop ).catch(function (e) { // Reject the speculation if there's a an error in // onCancel: return reject(e); }); }; return fn(resolve, reject, onCancel); }); }; module.exports = speculation;
var noop = function noop () {}; // HOF Wraps the native Promise API // to add take a shouldCancel promise and add // an onCancel() callback. var speculation = function speculation (fn) { // Don't cancel by default var cancel = ( arguments.length > 1 && arguments[1] !== undefined ) ? arguments[1] : Promise.reject(); return new Promise(function (resolve, reject) { var onCancel = function onCancel (handleCancel) { return cancel.then( handleCancel, // Ignore expected cancel rejections: noop ) // handle onCancel errors .catch(function (e) { return reject(e); }); }; fn(resolve, reject, onCancel); }); }; module.exports = speculation;
Add comments & cleanup formatting.
Add comments & cleanup formatting.
JavaScript
mit
ericelliott/speculation
--- +++ @@ -1,26 +1,29 @@ +var noop = function noop () {}; + +// HOF Wraps the native Promise API +// to add take a shouldCancel promise and add +// an onCancel() callback. var speculation = function speculation (fn) { - // Don't cancel by default: + // Don't cancel by default var cancel = ( arguments.length > 1 && arguments[1] !== undefined ) ? arguments[1] : Promise.reject(); return new Promise(function (resolve, reject) { - var noop = function noop () {}; - var onCancel = function onCancel (handleCancel) { return cancel.then( handleCancel, - // Filter out the expected "not cancelled" rejection: + // Ignore expected cancel rejections: noop - ).catch(function (e) { - // Reject the speculation if there's a an error in - // onCancel: + ) + // handle onCancel errors + .catch(function (e) { return reject(e); }); }; - return fn(resolve, reject, onCancel); + fn(resolve, reject, onCancel); }); };
1e6590e401dc544e7c6e3c608216124e240ee6ce
jest.config.js
jest.config.js
module.exports = { transform: { ".(ts|tsx)": "ts-jest" }, "testEnvironment": "node", "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", "moduleFileExtensions": [ "ts", "tsx", "js" ], "coveragePathIgnorePatterns": [ "/node_modules/", "/test/" ], "collectCoverageFrom": [ "src/*.{js,ts}" ] }
module.exports = { transform: { ".(ts|tsx)": "ts-jest" }, "testEnvironment": "node", "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", "moduleFileExtensions": [ "ts", "tsx", "js" ], "coveragePathIgnorePatterns": [ "/node_modules/", "/test/" ], "collectCoverageFrom": [ "src/**/*.{js,ts}" ] }
Include all TypeScript files in coverage
fix(tests): Include all TypeScript files in coverage
JavaScript
mit
aholstenson/transitory,aholstenson/transitory
--- +++ @@ -14,6 +14,6 @@ "/test/" ], "collectCoverageFrom": [ - "src/*.{js,ts}" + "src/**/*.{js,ts}" ] }
a73de96c4707b91ea11f92889ada2124528161b9
lib/runtime/alterant/decode-alterant.js
lib/runtime/alterant/decode-alterant.js
/*jslint node: true*/ 'use strict'; /** * Decode the value. * * @param value The value. * @returns The value. */ module.exports = function (value) { // Check if the value is not a string. if (typeof value !== 'string') { // Return the value. return value; } // Return the value. return value.replace(/&#([0-9]{2});/g, function (match, oct) { // Parse the base 10 number. return String.fromCharCode(parseInt(oct, 10)); }); };
/*jslint node: true*/ 'use strict'; /** * Decode the value. * * @param value The value. * @returns The value. */ module.exports = function (value) { // Check if the value is not a string. if (typeof value !== 'string') { // Return the value. return value; } // Return the value. return value.replace(/&#([0-9]{1,3});/g, function (match, oct) { // Parse the base 10 number. return String.fromCharCode(parseInt(oct, 10)); }); };
Allow decode of characters between 1 and 3 digits long
Allow decode of characters between 1 and 3 digits long
JavaScript
mit
barringtonhaynes/gaikan
--- +++ @@ -14,7 +14,7 @@ return value; } // Return the value. - return value.replace(/&#([0-9]{2});/g, function (match, oct) { + return value.replace(/&#([0-9]{1,3});/g, function (match, oct) { // Parse the base 10 number. return String.fromCharCode(parseInt(oct, 10)); });
9b457064997fde1aa218bd65ce9bd04a8dcabddb
index.android.js
index.android.js
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import {Provider} from 'react-redux' import MatchView from './src/components/MatchView' import store from './src/store' class Fussbolito extends Component { render() { return ( <Provider store={store}> <MatchView/> </Provider> ); } } AppRegistry.registerComponent('Fussbolito', () => Fussbolito);
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; import {Provider} from 'react-redux' import store from './src/store' import RootView from './src/components/RootView' const Fussbolito = React.createClass({ render() { return ( <Provider store={store}> <RootView /> </Provider> ); } }) AppRegistry.registerComponent('Fussbolito', () => Fussbolito);
Use new RootView also on Android
Use new RootView also on Android
JavaScript
mit
asharov/fussbolito,asharov/fussbolito,asharov/fussbolito
--- +++ @@ -6,24 +6,21 @@ import React, { Component } from 'react'; import { - AppRegistry, - StyleSheet, - Text, - View + AppRegistry } from 'react-native'; import {Provider} from 'react-redux' -import MatchView from './src/components/MatchView' import store from './src/store' +import RootView from './src/components/RootView' -class Fussbolito extends Component { +const Fussbolito = React.createClass({ render() { return ( <Provider store={store}> - <MatchView/> + <RootView /> </Provider> ); } -} +}) AppRegistry.registerComponent('Fussbolito', () => Fussbolito);
f49e4db8c5be936ecf711a8cda3e86d425f7e96d
src/js/helpers/prepare.js
src/js/helpers/prepare.js
/* Clearing variables */ import { getPositionIn, getPositionOut } from './offsetCalculator'; import getInlineOption from './getInlineOption'; const prepare = function($elements, options) { $elements.forEach((el, i) => { const mirror = getInlineOption(el.node, 'mirror', options.mirror); const once = getInlineOption(el.node, 'once', options.once); const id = getInlineOption(el.node, 'id'); const customClassNames = options.useClassNames && el.node.getAttribute('data-aos'); const animatedClassNames = [ options.animatedClassName, ...(customClassNames && customClassNames.split(' ')) ].filter(className => typeof className === 'string'); if (options.initClassName) { el.node.classList.add(options.initClassName); } el.position = { in: getPositionIn(el.node, options.offset), out: mirror && getPositionOut(el.node, options.offset) }; el.data = el.node.getAttributeNames().reduce((acc, attr) => { return Object.assign({}, acc, { [attr]: el.node.getAttribute(attr) }); }, {}); el.options = { once, mirror, animatedClassNames, id }; }); return $elements; }; export default prepare;
/* Clearing variables */ import { getPositionIn, getPositionOut } from './offsetCalculator'; import getInlineOption from './getInlineOption'; const prepare = function($elements, options) { $elements.forEach((el, i) => { const mirror = getInlineOption(el.node, 'mirror', options.mirror); const once = getInlineOption(el.node, 'once', options.once); const id = getInlineOption(el.node, 'id'); const customClassNames = options.useClassNames && el.node.getAttribute('data-aos'); const animatedClassNames = [ options.animatedClassName, ...(customClassNames && customClassNames.split(' ')) ].filter(className => typeof className === 'string'); if (options.initClassName) { el.node.classList.add(options.initClassName); } el.position = { in: getPositionIn(el.node, options.offset), out: mirror && getPositionOut(el.node, options.offset) }; el.options = { once, mirror, animatedClassNames, id }; }); return $elements; }; export default prepare;
Remove redundant code breaking tests
Remove redundant code breaking tests
JavaScript
mit
michalsnik/aos
--- +++ @@ -25,12 +25,6 @@ out: mirror && getPositionOut(el.node, options.offset) }; - el.data = el.node.getAttributeNames().reduce((acc, attr) => { - return Object.assign({}, acc, { - [attr]: el.node.getAttribute(attr) - }); - }, {}); - el.options = { once, mirror,
522968de5fe048b701f7cd6600f5592e44bc6a4f
src/index.js
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import Navbar from './components/Navbar.js'; import Header from './components/Header.js'; import Home from './components/Home.js'; import Instruction from './components/Instruction.js'; import AboutUs from './components/AboutUs.js'; import ContactForm from './components/ContactForm.js'; import ColorBlindnessView from './components/ColorBlindnessView.js'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom' const OtherComponent = () => ( <div>Other component is rendered as well</div> ) const root = document.getElementById('root'); ReactDOM.render( <Router> <div> <Navbar></Navbar> <hr/> <Header></Header> <Route exact path="/" component={Home}/> {/*<Route exact path="/" component={OtherComponent}/>*/} <Route path="/instructions" component={Instruction}/> <Route path="/quiz" component={App}/> <Route path="/about-us" component={AboutUs}/> <Route path="/contact-us" component={ContactForm}/> <Route path="/color-view" component={ColorBlindnessView}/> </div> </Router>, root); registerServiceWorker();
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import Navbar from './components/Navbar.js'; import Header from './components/Header.js'; import Home from './components/Home.js'; import Instruction from './components/Instruction.js'; import AboutUs from './components/AboutUs.js'; import ContactForm from './components/ContactForm.js'; import ColorBlindnessView from './components/ColorBlindnessView.js'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom' const root = document.getElementById('root'); ReactDOM.render( <Router> <div> <Navbar></Navbar> <hr/> <Header></Header> <Route exact path="/" component={Home}/> {/*<Route exact path="/" component={OtherComponent}/>*/} <Route path="/instructions" component={Instruction}/> <Route path="/quiz" component={App}/> <Route path="/about-us" component={AboutUs}/> <Route path="/contact-us" component={ContactForm}/> <Route path="/color-view" component={ColorBlindnessView}/> </div> </Router>, root); registerServiceWorker();
Remove unused lines of code.
Remove unused lines of code.
JavaScript
mit
FilmonFeMe/coloreyes,FilmonFeMe/coloreyes
--- +++ @@ -10,12 +10,7 @@ import AboutUs from './components/AboutUs.js'; import ContactForm from './components/ContactForm.js'; import ColorBlindnessView from './components/ColorBlindnessView.js'; - import { BrowserRouter as Router, Route, Link } from 'react-router-dom' - -const OtherComponent = () => ( - <div>Other component is rendered as well</div> -) const root = document.getElementById('root');
623926ce52dd881b9cec00c05b6c9a7996c9636c
lib/eval.js
lib/eval.js
var _ = require('underscore'); SYMBOL_TABLE = {} exports.define = function (sym, val) { SYMBOL_TABLE[sym] = val; } exports.eval = function eval(form, stack_frame) { if (typeof stack_frame == 'undefined') { stack_frame = SYMBOL_TABLE; } if (_.isEqual(form, null)) { return null; } if (form.type == 'id') return stack_frame[form.name]; else if (_.isArray(form)) { var func = eval(form[0], stack_frame); var args = form.slice(1); args.unshift(stack_frame); return func.apply(undefined, args); } else { return form; } } exports.evalAll = function (forms, stack_frame) { if (typeof stack_frame == 'undefined') { stack_frame = SYMBOL_TABLE; } var results = []; for (var i = 0; i < forms.length; i++) { results[i] = exports.eval(forms[i], stack_frame); } return results[results.length - 1]; // return last form } exports.define('stack', function (_s) { console.log(_s); }); exports.define('sym', function () { console.log(SYMBOL_TABLE); });
var _ = require('underscore'); SYMBOL_TABLE = {} exports.define = function (sym, val) { SYMBOL_TABLE[sym] = val; } exports.apply = function (fn, args, stack_frame) { if (typeof fn != 'function') throw "cannot evaluate non-function value: " + fn; args.unshift(stack_frame); return fn.apply(undefined, args); } exports.eval = function eval(form, stack_frame) { if (typeof stack_frame == 'undefined') { stack_frame = SYMBOL_TABLE; } if (_.isEqual(form, null)) { return null; } if (form.type == 'id') return stack_frame[form.name]; else if (_.isArray(form)) { var func = eval(form[0], stack_frame); var args = form.slice(1); return exports.apply(func, args, stack_frame); } else { return form; } } exports.evalAll = function (forms, stack_frame) { if (typeof stack_frame == 'undefined') { stack_frame = SYMBOL_TABLE; } var results = []; for (var i = 0; i < forms.length; i++) { results[i] = exports.eval(forms[i], stack_frame); } return results[results.length - 1]; // return last form } exports.define('stack', function (_s) { console.log(_s); }); exports.define('sym', function () { console.log(SYMBOL_TABLE); });
Refactor out applying function. Throw if invalid.
Refactor out applying function. Throw if invalid.
JavaScript
mit
mikedouglas/conspiracy
--- +++ @@ -4,6 +4,13 @@ exports.define = function (sym, val) { SYMBOL_TABLE[sym] = val; +} + +exports.apply = function (fn, args, stack_frame) { + if (typeof fn != 'function') + throw "cannot evaluate non-function value: " + fn; + args.unshift(stack_frame); + return fn.apply(undefined, args); } exports.eval = function eval(form, stack_frame) { @@ -20,8 +27,7 @@ else if (_.isArray(form)) { var func = eval(form[0], stack_frame); var args = form.slice(1); - args.unshift(stack_frame); - return func.apply(undefined, args); + return exports.apply(func, args, stack_frame); } else { return form;
8e4fbf59e00475f90dbf7d096550fa906db88370
src/fetch-feed.js
src/fetch-feed.js
var util = require('./util'); module.exports = function fetchFeed(delegate) { // delegate.url: a url string // delegate.verbose: a bool // delegate.onError: an error handler // delegate.onResponse: a response and data handler var request = util.request(delegate.url); request.on('error', function(e) { util.log(e.message); delegate.onError(e); }); request.on('response', function(response) { util.log('status', response.statusCode); util.log('headers', JSON.stringify(response.headers)); var data = ''; response.setEncoding('utf8'); response.on('data', function(chunk) { data += chunk; }).on('end', function() { if (delegate.verbose) { util.log('data', data); } delegate.onResponse(response, data); }); }); request.end(); };
var util = require('./util'); module.exports = function fetchFeed(delegate) { // delegate.url: a url string // delegate.verbose: a bool // delegate.onError: an error handler // delegate.onResponse: a response and data handler var request = util.request(delegate.url); request.on('error', function(e) { util.log(e.message); delegate.onError(e); }); request.on('response', function(response) { util.log('status', response.statusCode); util.log('headers', JSON.stringify(response.headers)); if (response.statusCode !== 200) { delegate.onError({ code: response.statusCode, message: response.statusMessage }); return; } var data = ''; response.setEncoding('utf8'); response.on('data', function(chunk) { data += chunk; }).on('end', function() { if (delegate.verbose) { util.log('data', data); } delegate.onResponse(response, data); }); }); request.end(); };
Convert non-200 fetch responses into errors
Convert non-200 fetch responses into errors
JavaScript
mit
hlfcoding/custom-rss
--- +++ @@ -17,6 +17,14 @@ util.log('status', response.statusCode); util.log('headers', JSON.stringify(response.headers)); + if (response.statusCode !== 200) { + delegate.onError({ + code: response.statusCode, + message: response.statusMessage + }); + return; + } + var data = ''; response.setEncoding('utf8'); response.on('data', function(chunk) {
fcde897bd7fbe28579e6a3c2307bd715da1a014f
.eslintrc.js
.eslintrc.js
module.exports = { root: true, env: { 'browser': true }, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, extends: 'airbnb', plugins: [ 'html' ], rules: { 'import/extensions': ['error', 'always', { 'js': 'never', 'vue': 'never' }], } };
module.exports = { root: true, env: { 'browser': true }, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, extends: 'airbnb', plugins: [ 'html' ], rules: { 'import/extensions': ['error', 'always', { 'js': 'never', 'vue': 'never' }], 'no-underscore-dangle': 0 } };
Remove comma dangle rule from eslint rules (VueComponent methods use _comma dangle)
Remove comma dangle rule from eslint rules (VueComponent methods use _comma dangle)
JavaScript
mit
eddyerburgh/avoriaz,eddyerburgh/avoriaz,eddyerburgh/avoriaz
--- +++ @@ -16,5 +16,6 @@ 'js': 'never', 'vue': 'never' }], + 'no-underscore-dangle': 0 } };
1bf03374b7edefdabacefbceb43ca02c6b702920
test/browser/browserstack-runner.js
test/browser/browserstack-runner.js
const reporter = require('mocha/lib/reporters').min; const bridgeTests = require('mocha-selenium-bridge'); const { Builder } = require('selenium-webdriver'); const bsConfig = { project: 'messageformat', 'browserstack.local': 'true', 'browserstack.user': process.env.BROWSERSTACK_USER, 'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER }; const PORT = 3000; const url = `http://localhost:${PORT}/test/browser/test.html`; /* eslint-disable camelcase */ exports.testBrowser = async function (browserName, browser_version) { const cap = Object.assign({ browserName, browser_version }, bsConfig); const driver = new Builder() .usingServer('http://hub-cloud.browserstack.com/wd/hub') .withCapabilities(cap) .build(); const code = await bridgeTests(driver, reporter, url, { timeout: 20000 }); driver.quit(); if (code > 0) throw new Error(`Failed ${code} tests`); if (code < 0) throw new Error(`MSB error ${code}`); };
const reporter = require('mocha/lib/reporters').min; const bridgeTests = require('mocha-selenium-bridge'); const { Builder } = require('selenium-webdriver'); const bsConfig = { project: 'messageformat', 'browserstack.local': 'true', 'browserstack.user': process.env.BROWSERSTACK_USER || process.env.BROWSERSTACK_USERNAME, 'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER }; const PORT = 3000; const url = `http://localhost:${PORT}/test/browser/test.html`; /* eslint-disable camelcase */ exports.testBrowser = async function (browserName, browser_version) { const cap = Object.assign({ browserName, browser_version }, bsConfig); const driver = new Builder() .usingServer('http://hub-cloud.browserstack.com/wd/hub') .withCapabilities(cap) .build(); const code = await bridgeTests(driver, reporter, url, { timeout: 20000 }); driver.quit(); if (code > 0) throw new Error(`Failed ${code} tests`); if (code < 0) throw new Error(`MSB error ${code}`); };
Fix env var name for BrowserStack user
ci: Fix env var name for BrowserStack user
JavaScript
mit
SlexAxton/messageformat.js,SlexAxton/messageformat.js
--- +++ @@ -5,7 +5,8 @@ const bsConfig = { project: 'messageformat', 'browserstack.local': 'true', - 'browserstack.user': process.env.BROWSERSTACK_USER, + 'browserstack.user': + process.env.BROWSERSTACK_USER || process.env.BROWSERSTACK_USERNAME, 'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER };
8361884021d550d663afce82583f1d0cd6807283
neo4j-ogm-docs/src/main/resources/javascript/version.js
neo4j-ogm-docs/src/main/resources/javascript/version.js
window.docMeta = (function () { var version = '3.2'; var name = 'ogm-manual'; var href = window.location.href; return { name: name, version: version, availableDocVersions: ["2.0", "2.1", "3.0", "3.1"], thisPubBaseUri: href.substring(0, href.indexOf(name) + name.length) + '/' + version, unversionedDocBaseUri: href.substring(0, href.indexOf(name) + name.length) + '/', commonDocsBaseUri: href.substring(0, href.indexOf(name) - 1) } })(); (function () { var baseUri = window.docMeta.unversionedDocBaseUri + window.location.pathname.split(window.docMeta.name + '/')[1].split('/')[0] + '/'; var docPath = window.location.href.replace(baseUri, ''); window.neo4jPageId = docPath; })(); // vim: set sw=2 ts=2:
window.docMeta = (function () { var version = '3.2'; var name = 'ogm-manual'; var href = window.location.href; return { name: name, version: version, availableDocVersions: ["2.1", "3.0", "3.1", "3.2"], thisPubBaseUri: href.substring(0, href.indexOf(name) + name.length) + '/' + version, unversionedDocBaseUri: href.substring(0, href.indexOf(name) + name.length) + '/', commonDocsBaseUri: href.substring(0, href.indexOf(name) - 1) } })(); (function () { var baseUri = window.docMeta.unversionedDocBaseUri + window.location.pathname.split(window.docMeta.name + '/')[1].split('/')[0] + '/'; var docPath = window.location.href.replace(baseUri, ''); window.neo4jPageId = docPath; })(); // vim: set sw=2 ts=2:
Add link to 3.2 documentation and remove 2.0 link.
Add link to 3.2 documentation and remove 2.0 link.
JavaScript
apache-2.0
neo4j/neo4j-ogm,neo4j/neo4j-ogm,neo4j/neo4j-ogm,neo4j/neo4j-ogm
--- +++ @@ -5,7 +5,7 @@ return { name: name, version: version, - availableDocVersions: ["2.0", "2.1", "3.0", "3.1"], + availableDocVersions: ["2.1", "3.0", "3.1", "3.2"], thisPubBaseUri: href.substring(0, href.indexOf(name) + name.length) + '/' + version, unversionedDocBaseUri: href.substring(0, href.indexOf(name) + name.length) + '/', commonDocsBaseUri: href.substring(0, href.indexOf(name) - 1)
2da65957e020bab97b6f3c0ddb67bf291ed0f925
website/static/js/waterbutler.js
website/static/js/waterbutler.js
var $ = require('jquery'); var settings = require('settings'); function getCookie() { match = document.cookie.match(/osf=(.*?)(;|$)/); return match ? match[1] : null; } function buildUrl(metadata, path, provider, file) { path = path || '/'; var baseUrl = settings.WATERBUTLER_URL + (metadata ? 'data?': 'file?'); if (file) { path += file.name; } return baseUrl + $.param({ path: path, token: '', nid: nodeId, provider: provider, cookie: getCookie() }); } function buildFromTreebeard(metadata, item, file) { return buildUrl(metadata, item.data.path, item.data.provider, file); } module.exports = { buildFileUrlFromPath: buildUrl.bind(this, false), buildFileUrl: buildFromTreebeard.bind(this, false), buildMetadataUrlFromPath: buildUrl.bind(this, true), buildMetadataUrl: buildFromTreebeard.bind(this, true), };
var $ = require('jquery'); var $osf = require('osfHelpers'); var settings = require('settings'); function getCookie() { match = document.cookie.match(/osf=(.*?)(;|$)/); return match ? match[1] : null; } function getViewOnly() { return $osf.urlParams().view_only; } function buildUrl(metadata, path, provider, file) { path = path || '/'; var baseUrl = settings.WATERBUTLER_URL + (metadata ? 'data?': 'file?'); if (file) { path += file.name; } return baseUrl + $.param({ path: path, token: '', nid: nodeId, provider: provider, cookie: getCookie(), viewOnly: getViewOnly() }); } function buildFromTreebeard(metadata, item, file) { return buildUrl(metadata, item.data.path, item.data.provider, file); } module.exports = { buildFileUrlFromPath: buildUrl.bind(this, false), buildFileUrl: buildFromTreebeard.bind(this, false), buildMetadataUrlFromPath: buildUrl.bind(this, true), buildMetadataUrl: buildFromTreebeard.bind(this, true), };
Include view-only key in WaterButler URLs.
Include view-only key in WaterButler URLs.
JavaScript
apache-2.0
hmoco/osf.io,amyshi188/osf.io,caseyrollins/osf.io,zkraime/osf.io,asanfilippo7/osf.io,monikagrabowska/osf.io,hmoco/osf.io,lyndsysimon/osf.io,dplorimer/osf,felliott/osf.io,samchrisinger/osf.io,crcresearch/osf.io,aaxelb/osf.io,reinaH/osf.io,Nesiehr/osf.io,sbt9uc/osf.io,cosenal/osf.io,HarryRybacki/osf.io,monikagrabowska/osf.io,cosenal/osf.io,revanthkolli/osf.io,TomHeatwole/osf.io,kushG/osf.io,barbour-em/osf.io,DanielSBrown/osf.io,kwierman/osf.io,jinluyuan/osf.io,CenterForOpenScience/osf.io,billyhunt/osf.io,kwierman/osf.io,ticklemepierce/osf.io,mluke93/osf.io,danielneis/osf.io,mluo613/osf.io,cosenal/osf.io,jeffreyliu3230/osf.io,HalcyonChimera/osf.io,revanthkolli/osf.io,KAsante95/osf.io,ZobairAlijan/osf.io,mluke93/osf.io,danielneis/osf.io,DanielSBrown/osf.io,monikagrabowska/osf.io,SSJohns/osf.io,asanfilippo7/osf.io,mluo613/osf.io,adlius/osf.io,caseyrygt/osf.io,aaxelb/osf.io,MerlinZhang/osf.io,Ghalko/osf.io,sloria/osf.io,adlius/osf.io,laurenrevere/osf.io,TomHeatwole/osf.io,brianjgeiger/osf.io,cldershem/osf.io,doublebits/osf.io,mluo613/osf.io,haoyuchen1992/osf.io,cosenal/osf.io,rdhyee/osf.io,GageGaskins/osf.io,reinaH/osf.io,chrisseto/osf.io,samanehsan/osf.io,sloria/osf.io,ticklemepierce/osf.io,jinluyuan/osf.io,icereval/osf.io,mluke93/osf.io,kch8qx/osf.io,KAsante95/osf.io,caneruguz/osf.io,alexschiller/osf.io,leb2dg/osf.io,reinaH/osf.io,barbour-em/osf.io,brianjgeiger/osf.io,reinaH/osf.io,jolene-esposito/osf.io,wearpants/osf.io,leb2dg/osf.io,rdhyee/osf.io,rdhyee/osf.io,alexschiller/osf.io,haoyuchen1992/osf.io,acshi/osf.io,ckc6cz/osf.io,brandonPurvis/osf.io,zamattiac/osf.io,chennan47/osf.io,mfraezz/osf.io,sbt9uc/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,njantrania/osf.io,doublebits/osf.io,samchrisinger/osf.io,Johnetordoff/osf.io,jnayak1/osf.io,caneruguz/osf.io,ckc6cz/osf.io,cwisecarver/osf.io,caneruguz/osf.io,zachjanicki/osf.io,billyhunt/osf.io,cslzchen/osf.io,petermalcolm/osf.io,abought/osf.io,chennan47/osf.io,erinspace/osf.io,binoculars/osf.io,njantrania/osf.io,lyndsysimon/osf.io,wearpants/osf.io,petermalcolm/osf.io,dplorimer/osf,binoculars/osf.io,lamdnhan/osf.io,arpitar/osf.io,danielneis/osf.io,dplorimer/osf,chrisseto/osf.io,caseyrygt/osf.io,brianjgeiger/osf.io,jnayak1/osf.io,saradbowman/osf.io,felliott/osf.io,GageGaskins/osf.io,cwisecarver/osf.io,fabianvf/osf.io,kushG/osf.io,ckc6cz/osf.io,pattisdr/osf.io,brandonPurvis/osf.io,Nesiehr/osf.io,jmcarp/osf.io,jnayak1/osf.io,RomanZWang/osf.io,brianjgeiger/osf.io,jinluyuan/osf.io,zachjanicki/osf.io,GaryKriebel/osf.io,asanfilippo7/osf.io,RomanZWang/osf.io,adlius/osf.io,MerlinZhang/osf.io,himanshuo/osf.io,cldershem/osf.io,cslzchen/osf.io,baylee-d/osf.io,GageGaskins/osf.io,kch8qx/osf.io,doublebits/osf.io,barbour-em/osf.io,acshi/osf.io,kwierman/osf.io,wearpants/osf.io,HarryRybacki/osf.io,dplorimer/osf,felliott/osf.io,mattclark/osf.io,TomBaxter/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,monikagrabowska/osf.io,zkraime/osf.io,pattisdr/osf.io,chrisseto/osf.io,zachjanicki/osf.io,jolene-esposito/osf.io,emetsger/osf.io,zamattiac/osf.io,lamdnhan/osf.io,TomBaxter/osf.io,kch8qx/osf.io,Johnetordoff/osf.io,alexschiller/osf.io,KAsante95/osf.io,jmcarp/osf.io,ckc6cz/osf.io,TomHeatwole/osf.io,KAsante95/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,Ghalko/osf.io,ZobairAlijan/osf.io,jinluyuan/osf.io,lyndsysimon/osf.io,fabianvf/osf.io,mluo613/osf.io,wearpants/osf.io,barbour-em/osf.io,zamattiac/osf.io,KAsante95/osf.io,caneruguz/osf.io,icereval/osf.io,arpitar/osf.io,brandonPurvis/osf.io,pattisdr/osf.io,abought/osf.io,kch8qx/osf.io,jnayak1/osf.io,jmcarp/osf.io,mluo613/osf.io,haoyuchen1992/osf.io,bdyetton/prettychart,himanshuo/osf.io,mattclark/osf.io,arpitar/osf.io,ZobairAlijan/osf.io,revanthkolli/osf.io,GageGaskins/osf.io,sloria/osf.io,zamattiac/osf.io,haoyuchen1992/osf.io,fabianvf/osf.io,emetsger/osf.io,monikagrabowska/osf.io,samanehsan/osf.io,GageGaskins/osf.io,emetsger/osf.io,zachjanicki/osf.io,hmoco/osf.io,brandonPurvis/osf.io,saradbowman/osf.io,cldershem/osf.io,cslzchen/osf.io,lyndsysimon/osf.io,RomanZWang/osf.io,Nesiehr/osf.io,bdyetton/prettychart,zkraime/osf.io,ticklemepierce/osf.io,cwisecarver/osf.io,chrisseto/osf.io,hmoco/osf.io,samchrisinger/osf.io,SSJohns/osf.io,caseyrygt/osf.io,mattclark/osf.io,SSJohns/osf.io,acshi/osf.io,fabianvf/osf.io,caseyrollins/osf.io,bdyetton/prettychart,samanehsan/osf.io,lamdnhan/osf.io,kch8qx/osf.io,binoculars/osf.io,adlius/osf.io,bdyetton/prettychart,sbt9uc/osf.io,GaryKriebel/osf.io,njantrania/osf.io,Ghalko/osf.io,petermalcolm/osf.io,felliott/osf.io,SSJohns/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,MerlinZhang/osf.io,TomHeatwole/osf.io,ZobairAlijan/osf.io,mfraezz/osf.io,asanfilippo7/osf.io,MerlinZhang/osf.io,danielneis/osf.io,himanshuo/osf.io,jeffreyliu3230/osf.io,brandonPurvis/osf.io,samanehsan/osf.io,acshi/osf.io,jeffreyliu3230/osf.io,aaxelb/osf.io,jeffreyliu3230/osf.io,HarryRybacki/osf.io,HarryRybacki/osf.io,ticklemepierce/osf.io,zkraime/osf.io,GaryKriebel/osf.io,Johnetordoff/osf.io,amyshi188/osf.io,HalcyonChimera/osf.io,caseyrygt/osf.io,kushG/osf.io,jolene-esposito/osf.io,caseyrollins/osf.io,acshi/osf.io,GaryKriebel/osf.io,erinspace/osf.io,samchrisinger/osf.io,abought/osf.io,billyhunt/osf.io,crcresearch/osf.io,jolene-esposito/osf.io,emetsger/osf.io,rdhyee/osf.io,sbt9uc/osf.io,DanielSBrown/osf.io,CenterForOpenScience/osf.io,doublebits/osf.io,chennan47/osf.io,leb2dg/osf.io,kushG/osf.io,petermalcolm/osf.io,crcresearch/osf.io,amyshi188/osf.io,cslzchen/osf.io,Ghalko/osf.io,icereval/osf.io,cwisecarver/osf.io,abought/osf.io,billyhunt/osf.io,Johnetordoff/osf.io,himanshuo/osf.io,mfraezz/osf.io,revanthkolli/osf.io,alexschiller/osf.io,RomanZWang/osf.io,njantrania/osf.io,Nesiehr/osf.io,TomBaxter/osf.io,kwierman/osf.io,laurenrevere/osf.io,mluke93/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,doublebits/osf.io,amyshi188/osf.io,arpitar/osf.io,erinspace/osf.io,billyhunt/osf.io,baylee-d/osf.io,cldershem/osf.io,jmcarp/osf.io,baylee-d/osf.io,lamdnhan/osf.io,alexschiller/osf.io
--- +++ @@ -1,10 +1,15 @@ var $ = require('jquery'); +var $osf = require('osfHelpers'); var settings = require('settings'); function getCookie() { match = document.cookie.match(/osf=(.*?)(;|$)/); return match ? match[1] : null; +} + +function getViewOnly() { + return $osf.urlParams().view_only; } function buildUrl(metadata, path, provider, file) { @@ -20,7 +25,8 @@ token: '', nid: nodeId, provider: provider, - cookie: getCookie() + cookie: getCookie(), + viewOnly: getViewOnly() }); }