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 |
|---|---|---|---|---|---|---|---|---|---|---|
b71c2f7fbf9d7aa16ef5c7e702f19ad50a9dc6d0 | index.js | index.js | #!/usr/bin/env node
'use strict'; /*jslint node: true, es5: true, indent: 2 */
var Parser = exports.Parser = require('./parser');
var Stringifier = exports.Stringifier = require('./stringifier');
// function logEvents(emitter, prefix, names) {
// names.forEach(function(name) {
// emitter.on(name, function(/*...*/) {
// console.error(prefix + ':' + name, arguments);
// });
// });
// }
if (require.main === module) {
var argv = require('optimist')
.usage([
'Consolidate any tabular format.',
'',
' argv will be passed directly to the Stringifier constructor.',
' process.stdin will be set to utf8',
].join('\n'))
.argv;
var parser = new Parser();
var stringifier = new Stringifier(argv);
process.stdin.setEncoding('utf8');
process.stdin.pipe(parser).pipe(stringifier).pipe(process.stdout);
}
| #!/usr/bin/env node
'use strict'; /*jslint node: true, es5: true, indent: 2 */
var Parser = exports.Parser = require('./parser');
var Stringifier = exports.Stringifier = require('./stringifier');
// function logEvents(emitter, prefix, names) {
// names.forEach(function(name) {
// emitter.on(name, function(/*...*/) {
// console.error(prefix + ':' + name, arguments);
// });
// });
// }
if (require.main === module) {
var optimist = require('optimist')
.usage([
'Consolidate any tabular format.',
'',
' argv will be passed directly to the Stringifier constructor.',
' process.stdin will be set to utf8',
'',
' cat data.tsv | sv > data.csv'
].join('\n'));
var parser = new Parser();
var stringifier = new Stringifier(optimist.argv);
if (process.stdin.isTTY) {
optimist.showHelp();
console.error("You must supply data via STDIN");
}
else {
process.stdin.setEncoding('utf8');
process.stdin.pipe(parser).pipe(stringifier).pipe(process.stdout);
}
}
| Check for process.stdin.isTTY when run directly | Check for process.stdin.isTTY when run directly
| JavaScript | mit | chbrown/sv,chbrown/sv | ---
+++
@@ -13,18 +13,25 @@
// }
if (require.main === module) {
- var argv = require('optimist')
+ var optimist = require('optimist')
.usage([
'Consolidate any tabular format.',
'',
' argv will be passed directly to the Stringifier constructor.',
' process.stdin will be set to utf8',
- ].join('\n'))
- .argv;
+ '',
+ ' cat data.tsv | sv > data.csv'
+ ].join('\n'));
var parser = new Parser();
- var stringifier = new Stringifier(argv);
+ var stringifier = new Stringifier(optimist.argv);
- process.stdin.setEncoding('utf8');
- process.stdin.pipe(parser).pipe(stringifier).pipe(process.stdout);
+ if (process.stdin.isTTY) {
+ optimist.showHelp();
+ console.error("You must supply data via STDIN");
+ }
+ else {
+ process.stdin.setEncoding('utf8');
+ process.stdin.pipe(parser).pipe(stringifier).pipe(process.stdout);
+ }
} |
e6c66260031b793e25b2c4c50859699b9d0d7e17 | index.js | index.js | "use strict"
var fs = require("fs")
var path = require("path")
var dz = require("dezalgo")
var npa = require("npm-package-arg")
module.exports = function (spec, where, cb) {
if (where instanceof Function) cb = where, where = null
if (where == null) where = "."
cb = dz(cb)
try {
var dep = npa(spec)
}
catch (e) {
return cb(e)
}
var specpath = path.resolve(where, dep.type == "local" ? dep.spec : spec)
fs.stat(specpath, function (er, s) {
if (er) return finalize()
if (!s.isDirectory()) return finalize("local")
fs.stat(path.join(specpath, "package.json"), function (er) {
finalize(er ? null : "directory")
})
})
function finalize(type) {
if (type != null) dep.type = type
if (dep.type == "local" || dep.type == "directory") dep.spec = specpath
cb(null, dep)
}
}
| "use strict"
var fs = require("fs")
var path = require("path")
var dz = require("dezalgo")
var npa = require("npm-package-arg")
module.exports = function (spec, where, cb) {
if (where instanceof Function) cb = where, where = null
if (where == null) where = "."
cb = dz(cb)
try {
var dep = npa(spec)
}
catch (e) {
return cb(e)
}
var specpath = dep.type == "local"
? path.resolve(where, dep.spec)
: path.resolve(spec)
fs.stat(specpath, function (er, s) {
if (er) return finalize()
if (!s.isDirectory()) return finalize("local")
fs.stat(path.join(specpath, "package.json"), function (er) {
finalize(er ? null : "directory")
})
})
function finalize(type) {
if (type != null) dep.type = type
if (dep.type == "local" || dep.type == "directory") dep.spec = specpath
cb(null, dep)
}
}
| Resolve ONLY file:// deps relative to package root, everything else CWD | Resolve ONLY file:// deps relative to package root, everything else CWD
| JavaScript | isc | npm/realize-package-specifier | ---
+++
@@ -14,7 +14,9 @@
catch (e) {
return cb(e)
}
- var specpath = path.resolve(where, dep.type == "local" ? dep.spec : spec)
+ var specpath = dep.type == "local"
+ ? path.resolve(where, dep.spec)
+ : path.resolve(spec)
fs.stat(specpath, function (er, s) {
if (er) return finalize()
if (!s.isDirectory()) return finalize("local") |
922e3caa9810b45a173524a4f9b7b451835c86c0 | index.js | index.js | 'use strict'
var svg = require('virtual-dom/virtual-hyperscript/svg')
var bezier = require('bezier-easing')
var Size = require('create-svg-size')
var Circle = require('./circle')
var Mask = require('./mask')
module.exports = function CircleBounce (data) {
return function render (time) {
var mask = Mask(renderInner(data.radius, time))
var outer = renderOuter(data.radius, time, data.fill, mask.id)
var options = Size({x: data.radius * 2, y: data.radius * 2})
return svg('svg', options, [
mask.vtree,
outer
])
}
}
function renderInner (radius, time) {
var coefficient = curve(time < 0.5 ? time : 1 - time)
return Circle({
radius: radius * coefficient,
center: radius
})
}
function renderOuter (radius, time, fill, mask) {
var coefficent = curve(time < 0.5 ? 1 - time : time)
return Circle({
id: 'circle-bounce-circle',
radius: radius * coefficent,
center: radius,
fill: fill,
mask: mask
})
}
function curve (value) {
return bezier(.10, 0.45, .9, .45).get(value)
}
| 'use strict'
var svg = require('virtual-dom/virtual-hyperscript/svg')
var bezier = require('bezier-easing')
var Size = require('create-svg-size')
var Circle = require('./circle')
var Mask = require('./mask')
module.exports = function CircleBounce (data) {
return function render (time) {
var mask = Mask(renderInner(data.radius, time))
var outer = renderOuter(data.radius, time, data.fill, mask.id)
var options = Size({x: data.radius * 2, y: data.radius * 2})
return svg('svg', options, [
mask.vtree,
outer
])
}
}
function renderInner (radius, time) {
var coefficient = 0.95 * curve(time < 0.5 ? time : 1 - time)
return Circle({
radius: radius * coefficient,
center: radius
})
}
function renderOuter (radius, time, fill, mask) {
var coefficent = curve(time < 0.5 ? 1 - time : time)
return Circle({
id: 'circle-bounce-circle',
radius: radius * coefficent,
center: radius,
fill: fill,
mask: mask
})
}
function curve (value) {
return bezier(.10, 0.45, .9, .45).get(value)
}
| Multiply inner circle coefficient by .95 to ensure a stroke remains | Multiply inner circle coefficient by .95 to ensure a stroke remains
| JavaScript | mit | bendrucker/circle-bounce | ---
+++
@@ -21,7 +21,7 @@
}
function renderInner (radius, time) {
- var coefficient = curve(time < 0.5 ? time : 1 - time)
+ var coefficient = 0.95 * curve(time < 0.5 ? time : 1 - time)
return Circle({
radius: radius * coefficient, |
c6eb2c136ed61fc0ac5e38a1c2e16872a7f99822 | index.js | index.js | const onepass = require("onepass")({
bundleId: "com.sudolikeaboss.sudolikeaboss"
});
exports.decorateTerm = (Term, { React }) => {
return class extends React.Component {
_onTerminal (term) {
if (this.props && this.props.onTerminal) this.props.onTerminal(term);
term.uninstallKeyboard();
term.keyboard.handlers_ = term.keyboard.handlers_.map(handler => {
if (handler[0] !== "keydown") {
return handler;
}
return [
"keydown",
function(e) {
if (e.metaKey && e.keyCode === 220) {
onepass.password("sudolikeaboss://local")
.then(pass => this.terminal.io.sendString(pass))
.catch(() => {});
}
return this.onKeyDown_(e);
}.bind(term.keyboard)
];
});
term.installKeyboard();
}
render () {
return React.createElement(Term, Object.assign({}, this.props, {
onTerminal: this._onTerminal
}));
}
};
};
| const onepass = require("onepass")({
bundleId: "com.sudolikeaboss.sudolikeaboss"
});
exports.decorateTerm = (Term, { React }) => {
return class extends React.Component {
_onTerminal (term) {
if (this.props && this.props.onTerminal) this.props.onTerminal(term);
term.uninstallKeyboard();
term.keyboard.handlers_ = term.keyboard.handlers_.map(handler => {
if (handler[0] !== "keydown") {
return handler;
}
const fn = handler[1];
return [
"keydown",
function(e) {
if (e.metaKey && e.keyCode === 220) {
onepass.password("sudolikeaboss://local")
.then(pass => this.terminal.io.sendString(pass))
.catch(() => {});
}
return fn(e);
}.bind(term.keyboard)
];
});
term.installKeyboard();
}
render () {
return React.createElement(Term, Object.assign({}, this.props, {
onTerminal: this._onTerminal
}));
}
};
};
| Extend existing keydown handler, instead of overriding it | Extend existing keydown handler, instead of overriding it
| JavaScript | mit | sibartlett/hyperterm-1password | ---
+++
@@ -15,6 +15,8 @@
return handler;
}
+ const fn = handler[1];
+
return [
"keydown",
function(e) {
@@ -23,7 +25,7 @@
.then(pass => this.terminal.io.sendString(pass))
.catch(() => {});
}
- return this.onKeyDown_(e);
+ return fn(e);
}.bind(term.keyboard)
];
}); |
91b608d905aa602fd9f8d7b0019602b6d077f6ea | src/umd-wrapper.js | src/umd-wrapper.js | (function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore', 'backbone.paginator'], function(Backbone, Underscore, PageableCollection) {
return (root.Hal = factory(root, Backbone, _, PageableCollection));
});
}
else if (typeof exports !== 'undefined') {
var Backbone = require('backbone');
var _ = require('underscore');
var PageableCollection = require('backbone.paginator');
module.exports = factory(root, Backbone, _, PageableCollection);
}
else {
root.Hal = factory(root, root.Backbone, root._, root.PageableCollection);
}
}(this, function(root) {
'use strict';
/**
* @namespace Hal
*/
var Hal = {};
// @include link.js
// @include model.js
// @include collection.js
return Hal;
}));
| (function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore', 'backbone.paginator'], function(Backbone, Underscore, PageableCollection) {
Backbone.PageableCollection = PageableCollection;
return (root.Hal = factory(root, Backbone, _));
});
}
else if (typeof exports !== 'undefined') {
var Backbone = require('backbone');
var _ = require('underscore');
Backbone.PageableCollection = require('backbone.paginator');
module.exports = factory(root, Backbone, _);
}
else {
root.Hal = factory(root, root.Backbone, root._);
}
}(this, function(root, Backbone, _) {
'use strict';
/**
* @namespace Hal
*/
var Hal = {};
// @include link.js
// @include model.js
// @include collection.js
return Hal;
}));
| Fix AMD / UMD problems. | Fix AMD / UMD problems. | JavaScript | mit | gomoob/backbone.hateoas,gomoob/backbone.hateoas,gomoob/backbone.hateoas | ---
+++
@@ -4,7 +4,9 @@
define(['backbone', 'underscore', 'backbone.paginator'], function(Backbone, Underscore, PageableCollection) {
- return (root.Hal = factory(root, Backbone, _, PageableCollection));
+ Backbone.PageableCollection = PageableCollection;
+
+ return (root.Hal = factory(root, Backbone, _));
});
@@ -14,19 +16,19 @@
var Backbone = require('backbone');
var _ = require('underscore');
- var PageableCollection = require('backbone.paginator');
+ Backbone.PageableCollection = require('backbone.paginator');
- module.exports = factory(root, Backbone, _, PageableCollection);
+ module.exports = factory(root, Backbone, _);
}
else {
- root.Hal = factory(root, root.Backbone, root._, root.PageableCollection);
+ root.Hal = factory(root, root.Backbone, root._);
}
-}(this, function(root) {
+}(this, function(root, Backbone, _) {
'use strict';
|
48aeb44374abc3baae4bb098f9e94dea26c91494 | index.js | index.js | #! /usr/bin/env node
var opts = require('optimist').argv
var through = require('through2');
function indexhtmlify(opts) {
var s = through(function onwrite(chunk, enc, cb) {
s.push(chunk)
cb()
}, function onend(cb) {
s.push('</script>\n')
s.push('</html>\n')
cb()
})
s.push('<!DOCTYPE html>\n')
s.push('<html>\n')
s.push('<head>\n')
s.push('<title>---</title>\n')
s.push('<meta content="width=device-width, initial-scale=1.0, ' +
'maximum-scale=1.0, user-scalable=0" name="viewport" />\n')
s.push('<meta charset=utf-8></head>\n')
if (opts.style) {
s.push('<style>\n')
s.push(require('fs').readFileSync(opts.style, 'utf8'))
s.push('</style>\n')
}
s.push('<body></body>\n')
s.push('<script language=javascript>\n')
return s
}
module.exports = indexhtmlify
if (require.main === module) {
if(process.stdin.isTTY) {
console.error('USAGE: browserify client.js | indexhtmlify ' +
'--style style.css > index.html')
process.exit(1)
}
process.stdin
.pipe(indexhtmlify(opts))
.pipe(process.stdout)
}
| #! /usr/bin/env node
var opts = require('optimist').argv
var through = require('through2');
function indexhtmlify(opts) {
opts = opts || {}
var s = through(function onwrite(chunk, enc, cb) {
s.push(chunk)
cb()
}, function onend(cb) {
s.push('</script>\n')
s.push('</html>\n')
cb()
})
s.push('<!DOCTYPE html>\n')
s.push('<html>\n')
s.push('<head>\n')
s.push('<title>' + (opts.title || '---') + '</title>\n')
s.push('<meta content="width=device-width, initial-scale=1.0, ' +
'maximum-scale=1.0, user-scalable=0" name="viewport" />\n')
s.push('<meta charset=utf-8></head>\n')
if (opts.style) {
s.push('<style>\n')
s.push(require('fs').readFileSync(opts.style, 'utf8'))
s.push('</style>\n')
}
s.push('<body></body>\n')
s.push('<script language=javascript>\n')
return s
}
module.exports = indexhtmlify
if (require.main === module) {
if(process.stdin.isTTY) {
console.error('USAGE: browserify client.js | indexhtmlify ' +
'--style style.css > index.html')
process.exit(1)
}
process.stdin
.pipe(indexhtmlify(opts))
.pipe(process.stdout)
}
| Allow passing in a title | Allow passing in a title
| JavaScript | mit | dominictarr/indexhtmlify | ---
+++
@@ -4,6 +4,8 @@
var through = require('through2');
function indexhtmlify(opts) {
+ opts = opts || {}
+
var s = through(function onwrite(chunk, enc, cb) {
s.push(chunk)
cb()
@@ -16,7 +18,7 @@
s.push('<!DOCTYPE html>\n')
s.push('<html>\n')
s.push('<head>\n')
- s.push('<title>---</title>\n')
+ s.push('<title>' + (opts.title || '---') + '</title>\n')
s.push('<meta content="width=device-width, initial-scale=1.0, ' +
'maximum-scale=1.0, user-scalable=0" name="viewport" />\n')
s.push('<meta charset=utf-8></head>\n') |
cd460dadc9bd85f4dc7356b20abf7cb3e3401dd0 | index.js | index.js | const Automerge = require('automerge')
function applyCodeMirrorChangeToAutomerge(state, findList, change, cm) {
const startPos = cm.indexFromPos(change.from)
if (change.to.line === change.from.line && change.to.ch === change.from.ch) {
// nothing was removed.
} else {
// delete.removed contains an array of removed lines as strings, so this adds
// all the lengths. Later change.removed.length - 1 is added for the \n-chars
// (-1 because the linebreak on the last line won't get deleted)
let delLen = 0
for (let rm = 0; rm < change.removed.length; rm++) {
delLen += change.removed[rm].length
}
delLen += change.removed.length - 1
state = Automerge.changeset(state, 'Delete', doc => {
findList(doc).splice(startPos, delLen)
})
}
if (change.text) {
state = Automerge.changeset(state, 'Insert', doc => {
findList(doc).splice(startPos, 0, ...change.text.join('\n').split(''))
})
}
if (change.next) {
state = applyCodeMirrorChangeToAutomerge(state, change.next, cm)
}
return state
}
module.exports = {
applyCodeMirrorChangeToAutomerge,
}
| const Automerge = require('automerge')
function applyCodeMirrorChangeToAutomerge(state, findList, change, cm) {
const startPos = cm.indexFromPos(change.from)
if (change.to.line === change.from.line && change.to.ch === change.from.ch) {
// nothing was removed.
} else {
// delete.removed contains an array of removed lines as strings.
// each removed line does not include the \n, so we add +1
// Finally remove 1 because the last \n won't be deleted
let delLen =
change.removed.reduce((sum, remove) => sum + remove.length + 1, 0) - 1
state = Automerge.changeset(state, 'Delete', doc => {
findList(doc).splice(startPos, delLen)
})
}
if (change.text) {
state = Automerge.changeset(state, 'Insert', doc => {
findList(doc).splice(startPos, 0, ...change.text.join('\n').split(''))
})
}
if (change.next) {
state = applyCodeMirrorChangeToAutomerge(state, change.next, cm)
}
return state
}
module.exports = {
applyCodeMirrorChangeToAutomerge,
}
| Use Array.reduce to compute how much to delete | Use Array.reduce to compute how much to delete
| JavaScript | mit | aslakhellesoy/automerge-codemirror,aslakhellesoy/automerge-codemirror | ---
+++
@@ -6,14 +6,12 @@
if (change.to.line === change.from.line && change.to.ch === change.from.ch) {
// nothing was removed.
} else {
- // delete.removed contains an array of removed lines as strings, so this adds
- // all the lengths. Later change.removed.length - 1 is added for the \n-chars
- // (-1 because the linebreak on the last line won't get deleted)
- let delLen = 0
- for (let rm = 0; rm < change.removed.length; rm++) {
- delLen += change.removed[rm].length
- }
- delLen += change.removed.length - 1
+ // delete.removed contains an array of removed lines as strings.
+ // each removed line does not include the \n, so we add +1
+ // Finally remove 1 because the last \n won't be deleted
+ let delLen =
+ change.removed.reduce((sum, remove) => sum + remove.length + 1, 0) - 1
+
state = Automerge.changeset(state, 'Delete', doc => {
findList(doc).splice(startPos, delLen)
}) |
5b5e156f3581cce8ecca166198e4a2d758eb576e | websites/submit.vefverdlaun.is/src/App.js | websites/submit.vefverdlaun.is/src/App.js | import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
)
}
}
export default App
| import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<p className="App-intro">
This project will be the form to submit projects to the Icelandic Web
Awards.
</p>
</div>
)
}
}
export default App
| Add some text to try out ci setup | Add some text to try out ci setup
| JavaScript | mit | svef/www,svef/www | ---
+++
@@ -13,6 +13,10 @@
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
+ <p className="App-intro">
+ This project will be the form to submit projects to the Icelandic Web
+ Awards.
+ </p>
</div>
)
} |
065ba9eda7d93f2bb956ac74166b241af83c6202 | modules/core/content/services/url-helper.js | modules/core/content/services/url-helper.js | // DecentCMS (c) 2015 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
function UrlHelper(scope) {
this.scope = scope;
}
UrlHelper.prototype.feature = 'content';
UrlHelper.prototype.service = 'url-helper';
UrlHelper.prototype.scope = 'shell';
UrlHelper.prototype.getUrl = function getUrl(id) {
var middlewares = this.scope.getServices('middleware')
.sort(function(m1, m2) {
return m1.routePriority - m2.routePriority;});
for (var i = 0; i < middlewares.length; i++) {
var middleware = middlewares[i];
if (middleware.getUrl) {
var url = middleware.getUrl(id);
if (url) return url;
}
}
return '/';
};
module.exports = UrlHelper; | // DecentCMS (c) 2015 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
function UrlHelper(scope) {
this.scope = scope;
}
UrlHelper.feature = 'content';
UrlHelper.service = 'url-helper';
UrlHelper.scope = 'shell';
UrlHelper.prototype.getUrl = function getUrl(id) {
var middlewares = this.scope.getServices('middleware')
.sort(function(m1, m2) {
return m1.routePriority - m2.routePriority;});
for (var i = 0; i < middlewares.length; i++) {
var middleware = middlewares[i];
if (middleware.getUrl) {
var url = middleware.getUrl(id);
if (url) return url;
}
}
return '/';
};
module.exports = UrlHelper; | Define UrlHelper meta-data on the class instead of the prototype. | Define UrlHelper meta-data on the class instead of the prototype.
| JavaScript | mit | DecentCMS/DecentCMS | ---
+++
@@ -4,9 +4,9 @@
function UrlHelper(scope) {
this.scope = scope;
}
-UrlHelper.prototype.feature = 'content';
-UrlHelper.prototype.service = 'url-helper';
-UrlHelper.prototype.scope = 'shell';
+UrlHelper.feature = 'content';
+UrlHelper.service = 'url-helper';
+UrlHelper.scope = 'shell';
UrlHelper.prototype.getUrl = function getUrl(id) {
var middlewares = this.scope.getServices('middleware')
.sort(function(m1, m2) { |
6cae911047d15eef3bb48c39a448f8b66f54ee49 | tests/trafficSpec.js | tests/trafficSpec.js | describe('traffic', function() {
beforeEach(function() {
window.matrix.settings = {
profileId: ''
};
subject = window.matrix.traffic;
});
it('has initial points', function() {
expect(subject.points).to.eq(720);
});
it('has empty counts', function() {
expect(subject.counts).to.eql([]);
});
it('has interval of 2 minutes', function() {
expect(subject.interval).to.eq(120000);
});
});
| describe('traffic', function() {
beforeEach(function() {
window.matrix.settings = {
profileId: ''
};
subject = window.matrix.traffic;
});
it('has initial points', function() {
expect(subject.points).to.eq(720);
});
it('has empty counts', function() {
expect(subject.counts).to.eql([]);
});
it('has interval of 2 minutes', function() {
expect(subject.interval).to.eq(120000);
});
describe('#endpoint', function() {
it('returns the path to the servers realtime endpoint', function() {
expect(subject.endpoint()).to.eql('/realtime?ids=ga:&metrics=rt:activeUsers&max-results=10');
});
context('with profileId', function() {
beforeEach(function() {
window.matrix.settings = {
profileId: 'Test'
};
});
it('returns correct profile Id in the endpoint path', function() {
expect(subject.endpoint()).to.eql('/realtime?ids=ga:Test&metrics=rt:activeUsers&max-results=10');
});
});
});
});
| Add test for the endpoint method | Add test for the endpoint method
| JavaScript | mit | codeforamerica/city-analytics-dashboard,codeforamerica/city-analytics-dashboard,codeforamerica/city-analytics-dashboard | ---
+++
@@ -14,4 +14,19 @@
it('has interval of 2 minutes', function() {
expect(subject.interval).to.eq(120000);
});
+ describe('#endpoint', function() {
+ it('returns the path to the servers realtime endpoint', function() {
+ expect(subject.endpoint()).to.eql('/realtime?ids=ga:&metrics=rt:activeUsers&max-results=10');
+ });
+ context('with profileId', function() {
+ beforeEach(function() {
+ window.matrix.settings = {
+ profileId: 'Test'
+ };
+ });
+ it('returns correct profile Id in the endpoint path', function() {
+ expect(subject.endpoint()).to.eql('/realtime?ids=ga:Test&metrics=rt:activeUsers&max-results=10');
+ });
+ });
+ });
}); |
e25ee1f46a21bcee96821e459617090a5bb922e5 | spec/arethusa.core/key_capture_spec.js | spec/arethusa.core/key_capture_spec.js | "use strict";
describe('keyCapture', function() {
beforeEach(module('arethusa.core'));
describe('onKeyPressed', function() {
it('calls the given callback', inject(function(keyCapture) {
var event = {
keyCode: 27,
target: { tagname: '' }
};
var callbackCalled = false;
var callback = function() { callbackCalled = true; };
keyCapture.onKeyPressed('esc', callback);
keyCapture.keyup(event);
expect(callbackCalled).toBe(true);
}));
});
});
| "use strict";
describe('keyCapture', function() {
beforeEach(module('arethusa.core'));
var keyCapture;
beforeEach(inject(function(_keyCapture_) {
keyCapture = _keyCapture_;
}));
var Event = function(key, shift) {
this.keyCode = key;
this.shiftKey = shift;
this.target = { tagname: '' };
};
describe('onKeyPressed', function() {
it('calls the given callback', function() {
// 27 is esc
var event = new Event(27);
var callbackCalled = false;
var callback = function() { callbackCalled = true; };
keyCapture.onKeyPressed('esc', callback);
keyCapture.keyup(event);
expect(callbackCalled).toBe(true);
});
it('handles shifted keys', function() {
// 74 is j
var eventWithShift = new Event(74, true);
var eventWithoutShift = new Event(74);
var e1callbackCalled = 0;
var e2callbackCalled = 0;
var e1callback = function() { e1callbackCalled++; };
var e2callback = function() { e2callbackCalled++; };
keyCapture.onKeyPressed('J', e1callback);
keyCapture.onKeyPressed('j', e2callback);
keyCapture.keyup(eventWithShift);
expect(e1callbackCalled).toEqual(1);
expect(e2callbackCalled).toEqual(0);
keyCapture.keyup(eventWithoutShift);
expect(e1callbackCalled).toEqual(1);
expect(e2callbackCalled).toEqual(1);
});
});
});
| Add spec for new keyCapture modifier handling | Add spec for new keyCapture modifier handling
| JavaScript | mit | alpheios-project/arethusa,Masoumeh/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa | ---
+++
@@ -3,12 +3,22 @@
describe('keyCapture', function() {
beforeEach(module('arethusa.core'));
+ var keyCapture;
+ beforeEach(inject(function(_keyCapture_) {
+ keyCapture = _keyCapture_;
+ }));
+
+ var Event = function(key, shift) {
+ this.keyCode = key;
+ this.shiftKey = shift;
+ this.target = { tagname: '' };
+ };
+
describe('onKeyPressed', function() {
- it('calls the given callback', inject(function(keyCapture) {
- var event = {
- keyCode: 27,
- target: { tagname: '' }
- };
+ it('calls the given callback', function() {
+ // 27 is esc
+ var event = new Event(27);
+
var callbackCalled = false;
var callback = function() { callbackCalled = true; };
keyCapture.onKeyPressed('esc', callback);
@@ -16,6 +26,27 @@
keyCapture.keyup(event);
expect(callbackCalled).toBe(true);
- }));
+ });
+
+ it('handles shifted keys', function() {
+ // 74 is j
+ var eventWithShift = new Event(74, true);
+ var eventWithoutShift = new Event(74);
+ var e1callbackCalled = 0;
+ var e2callbackCalled = 0;
+ var e1callback = function() { e1callbackCalled++; };
+ var e2callback = function() { e2callbackCalled++; };
+
+ keyCapture.onKeyPressed('J', e1callback);
+ keyCapture.onKeyPressed('j', e2callback);
+
+ keyCapture.keyup(eventWithShift);
+ expect(e1callbackCalled).toEqual(1);
+ expect(e2callbackCalled).toEqual(0);
+
+ keyCapture.keyup(eventWithoutShift);
+ expect(e1callbackCalled).toEqual(1);
+ expect(e2callbackCalled).toEqual(1);
+ });
});
}); |
d4edd2fba11ee073a65807f347ca9857a1663572 | spec/javascripts/helpers/SpecHelper.js | spec/javascripts/helpers/SpecHelper.js | require.config({
paths:{
jquery: "vendor/assets/javascripts/jquery/jquery-1.7.2.min",
jsmin: "vendor/assets/javascripts/jsmin",
polyfills: "vendor/assets/javascripts/polyfills",
lib: 'public/assets/javascripts/lib',
handlebars: 'vendor/assets/javascripts/handlebars',
underscore: 'vendor/assets/javascripts/underscore',
jplugs: "vendor/assets/javascripts/jquery/plugins",
pointer: "vendor/assets/javascripts/pointer",
touchwipe: "vendor/assets/javascripts/jquery.touchwipe.1.1.1",
s_code: "vendor/assets/javascripts/omniture/s_code"
}
});
| require.config({
paths:{
jquery: "vendor/assets/javascripts/jquery/jquery-1.7.2.min",
jsmin: "vendor/assets/javascripts/jsmin",
lib: 'public/assets/javascripts/lib',
handlebars: 'vendor/assets/javascripts/handlebars',
underscore: 'vendor/assets/javascripts/underscore',
jplugs: "vendor/assets/javascripts/jquery/plugins",
pointer: "vendor/assets/javascripts/pointer",
touchwipe: "vendor/assets/javascripts/jquery.touchwipe.1.1.1",
s_code: "vendor/assets/javascripts/omniture/s_code"
}
});
| Remove polyfills from the specHelper temporarily (as it fixes a weird bug) | Remove polyfills from the specHelper temporarily (as it fixes a weird bug)
| JavaScript | mit | Lostmyname/rizzo,lonelyplanet/rizzo,Lostmyname/rizzo,lonelyplanet/rizzo,lonelyplanet/rizzo,Lostmyname/rizzo,Lostmyname/rizzo,lonelyplanet/rizzo,lonelyplanet/rizzo,Lostmyname/rizzo | ---
+++
@@ -2,7 +2,6 @@
paths:{
jquery: "vendor/assets/javascripts/jquery/jquery-1.7.2.min",
jsmin: "vendor/assets/javascripts/jsmin",
- polyfills: "vendor/assets/javascripts/polyfills",
lib: 'public/assets/javascripts/lib',
handlebars: 'vendor/assets/javascripts/handlebars',
underscore: 'vendor/assets/javascripts/underscore', |
0c313cf2f04bc5f769f1fa1e4ba9dc31da615861 | packages/components/hooks/useBlackFriday.js | packages/components/hooks/useBlackFriday.js | import { useEffect, useState } from 'react';
import { isBlackFridayPeriod } from 'proton-shared/lib/helpers/blackfriday';
const EVERY_TEN_MINUTES = 10 * 60 * 1000;
const useBlackFriday = () => {
const [blackFriday, setBlackFriday] = useState(isBlackFridayPeriod());
useEffect(() => {
const intervalID = setInterval(() => {
setBlackFriday(isBlackFridayPeriod());
}, EVERY_TEN_MINUTES);
return () => {
clearInterval(intervalID);
};
}, []);
return blackFriday;
};
export default useBlackFriday;
| import { useEffect, useState } from 'react';
import { isBlackFridayPeriod } from 'proton-shared/lib/helpers/blackfriday';
const EVERY_MINUTE = 60 * 1000;
const useBlackFriday = () => {
const [blackFriday, setBlackFriday] = useState(isBlackFridayPeriod());
useEffect(() => {
const intervalID = setInterval(() => {
setBlackFriday(isBlackFridayPeriod());
}, EVERY_MINUTE);
return () => {
clearInterval(intervalID);
};
}, []);
return blackFriday;
};
export default useBlackFriday;
| Check BF condition every minute | Check BF condition every minute
| JavaScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react';
import { isBlackFridayPeriod } from 'proton-shared/lib/helpers/blackfriday';
-const EVERY_TEN_MINUTES = 10 * 60 * 1000;
+const EVERY_MINUTE = 60 * 1000;
const useBlackFriday = () => {
const [blackFriday, setBlackFriday] = useState(isBlackFridayPeriod());
@@ -9,7 +9,7 @@
useEffect(() => {
const intervalID = setInterval(() => {
setBlackFriday(isBlackFridayPeriod());
- }, EVERY_TEN_MINUTES);
+ }, EVERY_MINUTE);
return () => {
clearInterval(intervalID); |
65cdcae6172ce01bcc8be4e31252f9740816438d | index.js | index.js | var isPatched = false;
if (isPatched) return console.log('already patched');
function addColor(string, name) {
var colors = {
green: ['\x1B[32m', '\x1B[39m'],
red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'],
yellow: ['\x1B[33m', '\x1B[39m']
}
return colors[name][0] + string + colors[name][1];
}
function getColorName(methodName) {
switch (methodName) {
case 'error': return 'red';
case 'warn': return 'yellow';
default: return 'green';
}
}
['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) {
var baseConsoleMethod = console[method];
var slice = Array.prototype.slice;
var color = getColorName(method);
var messageType = method.toUpperCase();
var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout';
console[method] = function() {
var date = (new Date()).toISOString();
var args = slice.call(arguments);
if (process[output].isTTY)
messageType = addColor(messageType, color);
process[output].write('[' + date + '] ' + messageType + ' ');
return baseConsoleMethod.apply(console, args);
}
});
isPatched = true;
| var isPatched = false;
var slice = Array.prototype.slice;
if (isPatched) return console.log('already patched');
function addColor(string, name) {
var colors = {
green: ['\x1B[32m', '\x1B[39m'],
red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'],
yellow: ['\x1B[33m', '\x1B[39m']
}
return colors[name][0] + string + colors[name][1];
}
function getColorName(methodName) {
switch (methodName) {
case 'error': return 'red';
case 'warn': return 'yellow';
default: return 'green';
}
}
['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) {
var baseConsoleMethod = console[method];
var color = getColorName(method);
var messageType = method.toUpperCase();
var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout';
console[method] = function() {
var date = (new Date()).toISOString();
var args = slice.call(arguments);
if (process[output].isTTY)
messageType = addColor(messageType, color);
process[output].write('[' + date + '] ' + messageType + ' ');
return baseConsoleMethod.apply(console, args);
}
});
isPatched = true;
| Move slice variable assignment out of loop | Move slice variable assignment out of loop
| JavaScript | mit | coachme/console-time | ---
+++
@@ -1,4 +1,5 @@
var isPatched = false;
+var slice = Array.prototype.slice;
if (isPatched) return console.log('already patched');
@@ -22,7 +23,6 @@
['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) {
var baseConsoleMethod = console[method];
- var slice = Array.prototype.slice;
var color = getColorName(method);
var messageType = method.toUpperCase();
var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout'; |
022e9339a27d89511811bff56e417e069d21610e | index.js | index.js | var fs = require('fs');
var path = require('path');
var sass = require('node-sass');
module.exports = function dmpSass ($, document, done) {
sass.render({
file: 'assets/css/style.scss',
outputStyle: 'compressed',
sourceMap: false,
success: function (result) {
var cache = require('documark-cache')(document);
var file = cache.fileWriteStream('sass-cache.css');
file.end(result.css);
$.root().append('<link rel="stylesheet" type="text/css" href="' + cache.filePath('sass-cache.css') + '">');
},
error: function (error) {
console.log(error.message);
}
});
done();
};
| var fs = require('fs');
var path = require('path');
var sass = require('node-sass');
var cacheHelper = require('documark-cache');
module.exports = function dmpSass ($, document, done) {
sass.render({
file: 'assets/css/style.scss',
outputStyle: 'compressed',
sourceMap: false,
success: function (result) {
var cache = cacheHelper(document);
var file = cache.fileWriteStream('sass-cache.css');
var container = $.('head');
if ( !container.length ) {
container = $.root();
}
file.end(result.css);
container.append('<link rel="stylesheet" type="text/css" href="' + cache.filePath('sass-cache.css') + '">');
done();
},
error: function (error) {
done(error.message);
}
});
};
| Move documark-cache dependency to top of the document. Check for head container | Move documark-cache dependency to top of the document. Check for head container
| JavaScript | mit | jeroenkruis/dmp-sass | ---
+++
@@ -1,6 +1,7 @@
-var fs = require('fs');
-var path = require('path');
-var sass = require('node-sass');
+var fs = require('fs');
+var path = require('path');
+var sass = require('node-sass');
+var cacheHelper = require('documark-cache');
module.exports = function dmpSass ($, document, done) {
sass.render({
@@ -8,16 +9,21 @@
outputStyle: 'compressed',
sourceMap: false,
success: function (result) {
- var cache = require('documark-cache')(document);
+ var cache = cacheHelper(document);
var file = cache.fileWriteStream('sass-cache.css');
-
+ var container = $.('head');
+
+ if ( !container.length ) {
+ container = $.root();
+ }
+
file.end(result.css);
- $.root().append('<link rel="stylesheet" type="text/css" href="' + cache.filePath('sass-cache.css') + '">');
+ container.append('<link rel="stylesheet" type="text/css" href="' + cache.filePath('sass-cache.css') + '">');
+
+ done();
},
error: function (error) {
- console.log(error.message);
+ done(error.message);
}
});
-
- done();
}; |
34cd265eb9284effdffb6b6314ea4632e80fbd86 | index.js | index.js |
var postcss = require('postcss'),
colors = require('color');
module.exports = postcss.plugin('postcss-lowvision', function () {
return function (css) {
css.walkDecls('color', function (decl) {
var color = decl.value
var rgb = colors.rgb(color);
decl.value = rgb;
decl.cloneAfter({ prop: 'text-shadow',
value: '0 0 5px rgba(0,0,0,0.5)' });
});
};
});
|
var postcss = require('postcss'),
color = require('color');
module.exports = postcss.plugin('postcss-lowvision', function () {
return function (css) {
css.walkDecls('color', function (decl) {
var val = decl.value
var rgb = color(val);
rgb.rgb();
decl.value = rgb;
decl.cloneAfter({ prop: 'text-shadow',
value: '0 0 5px rgba(0,0,0,0.5)' });
});
};
});
| Test to see if colors package works | Test to see if colors package works
| JavaScript | mit | keukenrolletje/postcss-lowvision | ---
+++
@@ -1,12 +1,13 @@
var postcss = require('postcss'),
- colors = require('color');
+ color = require('color');
module.exports = postcss.plugin('postcss-lowvision', function () {
return function (css) {
css.walkDecls('color', function (decl) {
- var color = decl.value
- var rgb = colors.rgb(color);
+ var val = decl.value
+ var rgb = color(val);
+ rgb.rgb();
decl.value = rgb;
decl.cloneAfter({ prop: 'text-shadow',
value: '0 0 5px rgba(0,0,0,0.5)' }); |
56415d857b49a427736679050a0b59cddbbfb65f | index.js | index.js | 'use strict'
const driver = require('node-phantom-simple')
function genPromiseFunc(originalFunc) {
return function () {
const _args = Array.prototype.slice.call(arguments)
const _this = this
return new Promise(function (resolve, reject) {
_args.push(function () {
const _args2 = Array.prototype.slice.call(arguments)
const err = _args2.shift()
if (err) {
reject(err)
} else {
const _arg3 = _args2.map(function (arg) {
return promisifyAll(arg)
})
resolve.apply(null, _arg3)
}
})
originalFunc.apply(_this, _args)
})
}
}
function promisifyAll(target) {
if (typeof target !== 'object' || Array.isArray(target)) {
return target
}
const promisifiedTarget = {}
for (let targetPropName of Object.keys(target)) {
if (typeof target[targetPropName] !== 'function') {
promisifiedTarget[targetPropName] = target[targetPropName]
continue
}
promisifiedTarget[targetPropName] = genPromiseFunc(target[targetPropName])
}
return promisifiedTarget
}
return promisifyAll(driver)
| 'use strict'
const driver = require('node-phantom-simple')
function genPromiseFunc(originalFunc) {
return function () {
const _args = Array.prototype.slice.call(arguments)
const _this = this
return new Promise(function (resolve, reject) {
_args.push(function () {
const _args2 = Array.prototype.slice.call(arguments)
const err = _args2.shift()
if (err) {
reject(err)
} else {
const _arg3 = _args2.map(function (arg) {
return promisifyAll(arg)
})
resolve.apply(null, _arg3)
}
})
originalFunc.apply(_this, _args)
})
}
}
function promisifyAll(target) {
if (typeof target !== 'object' || Array.isArray(target)) {
return target
}
const promisifiedTarget = {}
for (let targetPropName of Object.keys(target)) {
if (typeof target[targetPropName] !== 'function') {
promisifiedTarget[targetPropName] = target[targetPropName]
continue
}
promisifiedTarget[targetPropName] = genPromiseFunc(target[targetPropName])
}
return promisifiedTarget
}
module.exports = promisifyAll(driver)
| Use module.exports instead of return | Use module.exports instead of return
| JavaScript | mit | foray1010/node-phantom-promise | ---
+++
@@ -48,4 +48,4 @@
return promisifiedTarget
}
-return promisifyAll(driver)
+module.exports = promisifyAll(driver) |
f7a134a8ebe7fa255932ceb9aba9bb8197dbdfac | index.js | index.js | var fs = require('fs'),
path = require('path');
// Load all stated versions into the module exports
module.exports.version = {};
['2.0.0', '2.0.1', '2.0.2', '2.1.0', '2.1.1', 'latest'].map(function(version) {
module.exports.version[version] = JSON.parse(
fs.readFileSync(
path.join(__dirname, version, 'reference.json'), 'utf8'));
});
| var fs = require('fs'),
path = require('path');
// Load all stated versions into the module exports
module.exports.version = {};
['2.0.0', '2.0.1', '2.0.2', '2.1.0', '2.1.1', 'latest'].map(function(version) {
module.exports.version[version] = JSON.parse(
fs.readFileSync(
path.join(__dirname, version, 'reference.json'), 'utf8'));
if (version === 'latest') {
module.exports.version[version].datasources = JSON.parse(
fs.readFileSync(
path.join(__dirname, version, 'datasources.json'), 'utf8')).datasources;
}
});
| Include datasources key in latest reference. | Include datasources key in latest reference.
| JavaScript | unlicense | mapycz/mapnik-reference,CartoDB/mapnik-reference,mapnik/mapnik-reference,mapnik/mapnik-reference,mojodna/mapnik-reference,florianf/mapnik-reference,mapycz/mapnik-reference,florianf/mapnik-reference,gravitystorm/mapnik-reference,mojodna/mapnik-reference,gravitystorm/mapnik-reference,CartoDB/mapnik-reference,mapnik/mapnik-reference | ---
+++
@@ -8,4 +8,9 @@
module.exports.version[version] = JSON.parse(
fs.readFileSync(
path.join(__dirname, version, 'reference.json'), 'utf8'));
+ if (version === 'latest') {
+ module.exports.version[version].datasources = JSON.parse(
+ fs.readFileSync(
+ path.join(__dirname, version, 'datasources.json'), 'utf8')).datasources;
+ }
}); |
5239a5418abaac18e3a15cf1f0581f361f54449e | index.js | index.js | "use strict";
// Return the panorama ID
var getPanoID = function(string) {
let value = decodeURIComponent(string).match("^https:\/\/.*\!1s(.*)\!2e.*$");
if (value === null) {
throw "URL incorrect";
}
value = "F:" + value[1];
return value;
};
// Return Embed URL to use on iframe
var getEmbed = function(string) {
let id = getPanoID(string);
let embedURL = "https://www.google.com/maps/embed/v1/streetview?pano=" + id + "&key=YOUR_APIKEY";
return embedURL;
};
// Method main
var main = function(url, options) {
try {
options = options || {};
if (typeof options !== "object") {
throw "Expected an object";
}
return options.embed === true ? getEmbed(url) : getPanoID(url);
} catch (error) {
return error;
}
};
module.exports = main; | "use strict";
// Return the panorama ID
var getPanoID = function(string) {
let value = decodeURIComponent(string).match("^https:\/\/.*\!1s(.*)\!2e.*$");
if (value === null) {
throw "Incorrect URL";
}
return "F:" + value[1];
};
// Return Embed URL to use on iframe
var getEmbed = function(string) {
let id = getPanoID(string);
let embedURL = "https://www.google.com/maps/embed/v1/streetview?pano=" + id + "&key=YOUR_APIKEY";
return embedURL;
};
// Method main
var main = function(url, options) {
try {
options = options || {};
if (typeof options !== "object") {
throw "Expected an object";
}
return options.embed ? getEmbed(url) : getPanoID(url);
} catch (error) {
return error;
}
};
module.exports = main; | Fix typo and remove some illogical code | Fix typo and remove some illogical code
| JavaScript | mit | dorianneto/get-streetview-panorama-id | ---
+++
@@ -5,12 +5,10 @@
let value = decodeURIComponent(string).match("^https:\/\/.*\!1s(.*)\!2e.*$");
if (value === null) {
- throw "URL incorrect";
+ throw "Incorrect URL";
}
- value = "F:" + value[1];
-
- return value;
+ return "F:" + value[1];
};
// Return Embed URL to use on iframe
@@ -30,7 +28,7 @@
throw "Expected an object";
}
- return options.embed === true ? getEmbed(url) : getPanoID(url);
+ return options.embed ? getEmbed(url) : getPanoID(url);
} catch (error) {
return error;
} |
2c534a16c1bfabb72ba01f40f8a50ab941df15fe | index.js | index.js | /*
* This is a very basic webserver and HTTP Client.
* In production, you may want to use something like Express.js
* or Botkit to host a webserver and manage API calls
*/
const {TOKEN, PORT} = process.env,
triage = require('./triage'),
qs = require('querystring'),
axios = require('axios'),
http = require('http');
// Handle any request to this server and parse the POST
function handleRequest(req, res){
let body = "";
req.on('data', data => body += data);
req.on('end', () => handleCommand(qs.parse(body)));
res.end('');
}
// Get channel history, build triage report, and respond with results
function handleCommand(payload) {
let {channel_id, response_url} = payload;
// load channel history
let params = qs.stringify({ count: 1000, token: TOKEN, channel: channel_id });
let getHistory = axios.post('https://slack.com/api/channels.history', params);
// build the triage report
let buildReport = result => Promise.resolve( triage(payload, result.data.messages) );
// post back to channel
let postResults = results => axios.post(response_url, results);
// execute
getHistory.then(buildReport).then(postResults);
}
// start server
http.createServer(handleRequest).listen(PORT, () => console.log(`server started on ${PORT}`));
| /*
* This is a very basic webserver and HTTP Client.
* In production, you may want to use something like Express.js
* or Botkit to host a webserver and manage API calls
*/
const {TOKEN, PORT} = process.env,
triage = require('./triage'),
qs = require('querystring'),
axios = require('axios'),
http = require('http');
// Handle any request to this server and parse the POST
function handleRequest(req, res){
let body = "";
req.on('data', data => body += data);
req.on('end', () => handleCommand(qs.parse(body)));
res.end('');
}
// Get channel history, build triage report, and respond with results
function handleCommand(payload) {
let {channel_id, response_url} = payload;
// load channel history
let params = qs.stringify({ count: 1000, token: TOKEN, channel: channel_id });
let getHistory = axios.post('https://slack.com/api/channels.history', params);
// build the triage report
let buildReport = result => Promise.resolve( triage(payload, result.data.messages || []) );
// post back to channel
let postResults = results => axios.post(response_url, results);
// execute
getHistory.then(buildReport).then(postResults).catch(console.error);
}
// start server
http.createServer(handleRequest).listen(PORT, () => console.log(`server started on ${PORT}`));
| Handle rejected promise, handle zero message case. | Handle rejected promise, handle zero message case.
| JavaScript | mit | Ihamblen/slacktriage | ---
+++
@@ -28,13 +28,13 @@
let getHistory = axios.post('https://slack.com/api/channels.history', params);
// build the triage report
- let buildReport = result => Promise.resolve( triage(payload, result.data.messages) );
+ let buildReport = result => Promise.resolve( triage(payload, result.data.messages || []) );
// post back to channel
let postResults = results => axios.post(response_url, results);
// execute
- getHistory.then(buildReport).then(postResults);
+ getHistory.then(buildReport).then(postResults).catch(console.error);
}
// start server |
24093d73f2b3b7518f7447d9261f0bf896f13526 | index.js | index.js | /* eslint-env node */
'use strict';
module.exports = {
name: 'ember-cli-chart',
included: function included(app) {
this._super.included(app);
app.import(app.bowerDirectory + '/chartjs/dist/Chart.js');
}
};
| /* eslint-env node */
'use strict';
module.exports = {
name: 'ember-cli-chart',
included: function(app, parentAddon) {
this._super.included.apply(this, arguments);
var target = (parentAddon || app);
if (target.app) {
target = target.app;
}
var bowerDir = target.bowerDirectory;
app.import(bowerDir + '/chartjs/dist/Chart.js');
}
};
| Allow usage in nested addons | Allow usage in nested addons | JavaScript | mit | aomra015/ember-cli-chart,aomran/ember-cli-chart,aomran/ember-cli-chart,aomra015/ember-cli-chart | ---
+++
@@ -3,8 +3,15 @@
module.exports = {
name: 'ember-cli-chart',
- included: function included(app) {
- this._super.included(app);
- app.import(app.bowerDirectory + '/chartjs/dist/Chart.js');
+ included: function(app, parentAddon) {
+ this._super.included.apply(this, arguments);
+
+ var target = (parentAddon || app);
+ if (target.app) {
+ target = target.app;
+ }
+
+ var bowerDir = target.bowerDirectory;
+ app.import(bowerDir + '/chartjs/dist/Chart.js');
}
}; |
662aaae249f1411499aaf21b02c6527ceec1cca4 | app/js/arethusa.conf_editor/directives/plugin_conf.js | app/js/arethusa.conf_editor/directives/plugin_conf.js | "use strict";
angular.module('arethusa.confEditor').directive('pluginConf', function() {
return {
restrict: 'AE',
scope: true,
link: function(scope, element, attrs) {
var name = scope.$eval(attrs.name);
scope.template = 'templates/configs/' + name + '.html';
},
templateUrl: 'templates/plugin_conf.html'
};
});
| "use strict";
angular.module('arethusa.confEditor').directive('pluginConf', function() {
return {
restrict: 'AE',
scope: true,
link: function(scope, element, attrs) {
var name = scope.$eval(attrs.name);
// Right now paths to such configuration are hardcoded to a specific
// folder. This will be much more dynamic in the future.
scope.template = 'templates/configs/' + name + '.html';
},
templateUrl: 'templates/plugin_conf.html'
};
});
| Add comment to plugin conf | Add comment to plugin conf
| JavaScript | mit | fbaumgardt/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa | ---
+++
@@ -6,6 +6,9 @@
scope: true,
link: function(scope, element, attrs) {
var name = scope.$eval(attrs.name);
+
+ // Right now paths to such configuration are hardcoded to a specific
+ // folder. This will be much more dynamic in the future.
scope.template = 'templates/configs/' + name + '.html';
},
templateUrl: 'templates/plugin_conf.html' |
93f0d993dbfc7bbbd88c452c5aace505b73c761f | index.js | index.js | 'use strict';
module.exports = function(){
};
| 'use strict';
var fs = require('fs');
var stream = require('stream');
var readline = require('readline');
var moment = require('moment');
function readFileContent(filename, callback){
var lines = [];
var instream = fs.createReadStream(filename);
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;
var rl = readline.createInterface({
input: instream,
output: outstream,
terminal: false
});
rl.on('line', function(line){
lines.push(formatLine(line));
});
rl.on('close', function(){
callback(null, lines);
});
}
function formatLine(line) {
// Remove empty lines
if(!line || !line.length) {
return;
}
var lineParts = line.split(': ');
return messageDetails(lineParts);
}
function messageDetails(parts){
var date = formatDate(parts[0]);
var details = {
date: date
};
if(parts[2]){
details.sender = parts[1];
// remove timestamp and sender info
parts.splice(0, 2);
details.message = parts.join(': ');
return details;
}
details.message = parts[1];
details.announcement = true;
return details;
}
function formatDate(timestamp){
if(timestamp.length !== 17){
throw new Error('Timestamp is of the wrong length:', timestamp);
}
return moment(timestamp, 'DD/MM/YY HH:mm:ss').format();
}
module.exports = function(filename){
return readFileContent.apply(this, arguments);
};
| Add initial file-reading and line formatting | Add initial file-reading and line formatting
| JavaScript | mit | matiassingers/whatsapp-log-parser | ---
+++
@@ -1,5 +1,73 @@
'use strict';
-module.exports = function(){
+var fs = require('fs');
+var stream = require('stream');
+var readline = require('readline');
+var moment = require('moment');
+function readFileContent(filename, callback){
+ var lines = [];
+
+ var instream = fs.createReadStream(filename);
+ var outstream = new stream;
+ outstream.readable = true;
+ outstream.writable = true;
+
+ var rl = readline.createInterface({
+ input: instream,
+ output: outstream,
+ terminal: false
+ });
+
+ rl.on('line', function(line){
+ lines.push(formatLine(line));
+ });
+
+ rl.on('close', function(){
+ callback(null, lines);
+ });
+}
+
+function formatLine(line) {
+ // Remove empty lines
+ if(!line || !line.length) {
+ return;
+ }
+
+ var lineParts = line.split(': ');
+ return messageDetails(lineParts);
+}
+function messageDetails(parts){
+ var date = formatDate(parts[0]);
+
+ var details = {
+ date: date
+ };
+
+ if(parts[2]){
+ details.sender = parts[1];
+
+ // remove timestamp and sender info
+ parts.splice(0, 2);
+
+ details.message = parts.join(': ');
+
+ return details;
+ }
+
+ details.message = parts[1];
+ details.announcement = true;
+
+ return details;
+}
+function formatDate(timestamp){
+ if(timestamp.length !== 17){
+ throw new Error('Timestamp is of the wrong length:', timestamp);
+ }
+
+ return moment(timestamp, 'DD/MM/YY HH:mm:ss').format();
+}
+
+module.exports = function(filename){
+ return readFileContent.apply(this, arguments);
}; |
d42fcb9add392e3cca86600b494af6bb7c51468d | index.js | index.js | var forIn = require('for-in'),
xobj = require('xhr'),
XhrError = require('xhrerror');
function noop() { }
function xhr(options, callback, errback) {
var req = xobj();
if(Object.prototype.toString.call(options) == '[object String]') {
options = { url: options };
}
req.open(options.method || 'GET', options.url, true);
if(options.credentials) {
req.withCredentials = true;
}
forIn(options.headers || {}, function (value, key) {
req.setRequestHeader(key, value);
});
req.onreadystatechange = function() {
if(req.readyState != 4) return;
if([
200,
304,
0
].indexOf(req.status) === -1) {
(errback || noop)(new XhrError('Server responded with a status of ' + req.status, req.status));
} else {
(callback || noop)(req.responseText);
}
};
req.send(options.data || void 0);
}
module.exports = xhr;
| var forIn = require('for-in'),
xobj = require('xhr'),
XhrError = require('xhrerror');
function noop() { }
function xhr(options, callback, errback) {
var req = xobj();
if(Object.prototype.toString.call(options) == '[object String]') {
options = { url: options };
}
req.open(options.method || 'GET', options.url, true);
if(options.credentials) {
req.withCredentials = true;
}
forIn(options.headers || {}, function (value, key) {
req.setRequestHeader(key, value);
});
req.onreadystatechange = function() {
if(req.readyState != 4) return;
if([
200,
304,
0
].indexOf(req.status) === -1) {
(errback || noop)(new XhrError('Server responded with a status of ' + req.status, req.status));
} else {
(callback || noop)(req);
}
};
req.send(options.data || void 0);
}
module.exports = xhr;
| Send the req to the callback. | Send the req to the callback.
| JavaScript | mit | matthewp/xhr,npmcomponent/matthewp-xhr | ---
+++
@@ -31,7 +31,7 @@
].indexOf(req.status) === -1) {
(errback || noop)(new XhrError('Server responded with a status of ' + req.status, req.status));
} else {
- (callback || noop)(req.responseText);
+ (callback || noop)(req);
}
};
|
e5d46a0a24acd994ccd5c2f59c89f8c7c69485c6 | example/src/pages/MeshPage.js | example/src/pages/MeshPage.js | import React, {Component, PropTypes} from 'react';
import {Akkad, Scene, shapes, cameras, lights, systems} from "akkad";
const googleStorageEndpoint = `http://storage.googleapis.com/akkad-assets-1/`;
const {ArcRotateCamera} = cameras;
const {HemisphericLight} = lights;
const {Mesh, Position, Rotate} = systems;
class MeshPage extends Component {
render() {
return (
<div>
<h2>
Mesh Example
</h2>
<Akkad>
<Scene>
<ArcRotateCamera
initialPosition={[0, 0, 100]}
target={[0, 0, 0]}
/>
<HemisphericLight />
<Mesh
path={googleStorageEndpoint}
fileName={'skull.babylon'}
>
<Position vector={[0, 0, 0]}/>
<Rotate
axis={[0, 1.2, 0]}
amount={60}
space="LOCAL"
/>
</Mesh>
</Scene>
</Akkad>
</div>
);
}
}
export default MeshPage;
| import React, {Component, PropTypes} from 'react';
import {Akkad, Scene, shapes, cameras, lights, systems} from "akkad";
const googleStorageEndpoint = `https://storage.googleapis.com/akkad-assets-1/`;
const {ArcRotateCamera} = cameras;
const {HemisphericLight} = lights;
const {Mesh, Position, Rotate} = systems;
class MeshPage extends Component {
render() {
return (
<div>
<h2>
Mesh Example
</h2>
<Akkad>
<Scene>
<ArcRotateCamera
initialPosition={[0, 0, 100]}
target={[0, 0, 0]}
/>
<HemisphericLight />
<Mesh
path={googleStorageEndpoint}
fileName={'skull.babylon'}
>
<Position vector={[0, 0, 0]}/>
<Rotate
axis={[0, 1.2, 0]}
amount={60}
space="LOCAL"
/>
</Mesh>
</Scene>
</Akkad>
</div>
);
}
}
export default MeshPage;
| Change google storage endpoint to us https | Change google storage endpoint to us https
| JavaScript | mit | brochington/Akkad,cgrinker/Akkad,brochington/Akkad,cgrinker/Akkad | ---
+++
@@ -1,7 +1,7 @@
import React, {Component, PropTypes} from 'react';
import {Akkad, Scene, shapes, cameras, lights, systems} from "akkad";
-const googleStorageEndpoint = `http://storage.googleapis.com/akkad-assets-1/`;
+const googleStorageEndpoint = `https://storage.googleapis.com/akkad-assets-1/`;
const {ArcRotateCamera} = cameras;
const {HemisphericLight} = lights; |
3a18004c4d66395faf0559e37c68d02370f5e1b5 | index.js | index.js | var mozjpeg = require('mozjpeg')
var dcp = require('duplex-child-process')
/**
* @param {Object} options
* @param {Number} opts.quality the 1 to 100. Docs suggest 5 to 95 is actual useable range.
* @param {String} opts.args raw `mozjpeg` args for the connoisseur. See: https://github.com/mozilla/mozjpeg/blob/master/usage.txt#L70
*/
module.exports = function (opts) {
opts = opts || {}
// Force the quality flag to be specified, because: https://github.com/mozilla/mozjpeg/issues/181
opts.quality = opts.quality || 75
var args = []
if (opts.quality) args.push('-quality', opts.quality)
if (opts.args) args.push(opts.args.split[' '])
var foo = dcp.spawn(mozjpeg, args)
return foo
}
| var mozjpeg = require('mozjpeg')
var dcp = require('duplex-child-process')
/**
* @param {Object} options
* @param {Number} opts.quality the 1 to 100. Docs suggest 5 to 95 is actual useable range.
* @param {String} opts.args raw `mozjpeg` args for the connoisseur. See: https://github.com/mozilla/mozjpeg/blob/master/usage.txt#L70
*/
module.exports = function (opts) {
opts = opts || {}
// Force the quality flag to be specified, because: https://github.com/mozilla/mozjpeg/issues/181
opts.quality = opts.quality || 75
var args = []
if (opts.quality) args.push('-quality', opts.quality)
if (opts.args) {
args = args.concat(opts.args.split(' '))
}
return dcp.spawn(mozjpeg, args)
}
| Fix args option not functioning | Fix args option not functioning | JavaScript | isc | tableflip/mozjpeg-stream | ---
+++
@@ -12,8 +12,8 @@
opts.quality = opts.quality || 75
var args = []
if (opts.quality) args.push('-quality', opts.quality)
- if (opts.args) args.push(opts.args.split[' '])
-
- var foo = dcp.spawn(mozjpeg, args)
- return foo
+ if (opts.args) {
+ args = args.concat(opts.args.split(' '))
+ }
+ return dcp.spawn(mozjpeg, args)
} |
e374134bd7ff60faeaa561ee984f2d23802d486e | index.js | index.js | var Promise = require('bluebird')
var request = require('got')
var extend = require('xtend')
var BASE_URL = 'http://www.broadbandmap.gov/broadbandmap/broadband/jun2014/'
module.exports = function broadbandMap (lat, long, options) {
options = extend({
types: ['wireline', 'wireless']
}, options || {})
var promises = []
options.types.forEach(function (type) {
promises.push(buildRequest(lat, long, type))
})
return Promise.all(promises)
.spread(function (res1, res2) {
var results = []
if (res1 && res1.body) results.push(JSON.parse(res1.body).Results)
if (res2 && res2.body) results.push(JSON.parse(res2.body).Results)
return results
})
.catch(function (err) {
throw err
})
}
function buildRequest (lat, long, type) {
return request.get(BASE_URL + type + '?latitude=' +
lat + '&longitude=' + long + '&format=json')
}
| var Promise = require('bluebird')
var request = require('got')
var extend = require('xtend')
var BASE_URL = 'http://www.broadbandmap.gov/broadbandmap/broadband/jun2014/'
module.exports = function broadbandMap (lat, long, options) {
options = extend({
types: ['wireline', 'wireless']
}, options || {})
return Promise.map(options.type, buildRequest)
.spread(function (res1, res2) {
var results = []
if (res1 && res1.body) results.push(JSON.parse(res1.body).Results)
if (res2 && res2.body) results.push(JSON.parse(res2.body).Results)
return results
})
.catch(function (err) {
throw err
})
function buildRequest (type) {
return request.get(BASE_URL + type + '?latitude=' +
lat + '&longitude=' + long + '&format=json')
}
}
| Use promise.map to build requests | Use promise.map to build requests
Requires moving buildRequest into inner fn scope
| JavaScript | mit | bsiddiqui/broadband-map | ---
+++
@@ -9,13 +9,7 @@
types: ['wireline', 'wireless']
}, options || {})
- var promises = []
-
- options.types.forEach(function (type) {
- promises.push(buildRequest(lat, long, type))
- })
-
- return Promise.all(promises)
+ return Promise.map(options.type, buildRequest)
.spread(function (res1, res2) {
var results = []
@@ -27,9 +21,9 @@
.catch(function (err) {
throw err
})
+
+ function buildRequest (type) {
+ return request.get(BASE_URL + type + '?latitude=' +
+ lat + '&longitude=' + long + '&format=json')
+ }
}
-
-function buildRequest (lat, long, type) {
- return request.get(BASE_URL + type + '?latitude=' +
- lat + '&longitude=' + long + '&format=json')
-} |
954762c783fa53ab6772f2ff08a63b7dc018b396 | index.js | index.js | /*!
* data-driven
* Copyright(c) 2013 Fluent Software Solutions Ltd <info@fluentsoftware.co.uk>
* MIT Licensed
*/
module.exports = function(data, fn) {
var mochaIt = it
data.forEach(function(testData) {
try {
it = function(title, f) {
for (var key in testData) {
title = title.replace('{'+key+'}',testData[key])
}
var testFn = f.length < 2 ?
function() {
f(testData)
} :
function(done) {
f(testData,done)
}
mochaIt(title, testFn)
}
fn()
} finally {
it = mochaIt
}
})
} | /*!
* data-driven
* Copyright(c) 2013 Fluent Software Solutions Ltd <info@fluentsoftware.co.uk>
* MIT Licensed
*/
module.exports = function(data, fn) {
var mochaIt = it
var mochaBefore = before
data.forEach(function(testData) {
try {
it = function(title, f) {
for (var key in testData) {
title = title.replace('{'+key+'}',testData[key])
}
if (f !== undefined) {
var testFn = f.length < 2 ?
function() {
f(testData)
} :
function(done) {
f(testData,done)
}
}
mochaIt(title, testFn)
}
before = function(f) {
var testFn = f.length < 2 ?
function() {
f(testData)
} :
function(done) {
f(testData,done)
}
mochaBefore(testFn)
}
fn()
} finally {
it = mochaIt
before = mochaBefore
}
})
}
| Add support for pending, undefined it() tests and for data-driving Mocha's before() | Add support for pending, undefined it() tests and for data-driving Mocha's before()
| JavaScript | mit | danbehar/data-driven,fluentsoftware/data-driven | ---
+++
@@ -6,29 +6,44 @@
module.exports = function(data, fn) {
var mochaIt = it
-
+ var mochaBefore = before
+
data.forEach(function(testData) {
try {
it = function(title, f) {
-
for (var key in testData) {
title = title.replace('{'+key+'}',testData[key])
}
- var testFn = f.length < 2 ?
+ if (f !== undefined) {
+ var testFn = f.length < 2 ?
+ function() {
+ f(testData)
+ } :
+ function(done) {
+ f(testData,done)
+ }
+ }
+
+ mochaIt(title, testFn)
+ }
+
+ before = function(f) {
+ var testFn = f.length < 2 ?
function() {
f(testData)
- } :
+ } :
function(done) {
f(testData,done)
}
-
- mochaIt(title, testFn)
+
+ mochaBefore(testFn)
}
fn()
} finally {
it = mochaIt
+ before = mochaBefore
}
})
} |
a16fe50dad78d42b10fe9fd6af24a3b63754afa3 | index.js | index.js | 'use strict';
function DefaultRegistry(){
this._tasks = {};
}
DefaultRegistry.prototype.get = function get(name){
return this._tasks[name];
};
DefaultRegistry.prototype.set = function set(name, fn){
this._tasks[name] = fn;
};
DefaultRegistry.prototype.tasks = function tasks(){
return Object.keys(this._tasks).map(this.get, this);
};
module.exports = DefaultRegistry;
| 'use strict';
function DefaultRegistry(){
this._tasks = {};
}
DefaultRegistry.prototype.get = function get(name){
return this._tasks[name];
};
DefaultRegistry.prototype.set = function set(name, fn){
this._tasks[name] = fn;
};
DefaultRegistry.prototype.tasks = function tasks(){
var self = this;
return Object.keys(this._tasks).reduce(function(tasks, name){
tasks[name] = self.get(name);
return tasks;
}, {});
};
module.exports = DefaultRegistry;
| Make `.tasks` return an object instead of array | Breaking: Make `.tasks` return an object instead of array
| JavaScript | mit | phated/undertaker-registry,gulpjs/undertaker-registry | ---
+++
@@ -13,7 +13,12 @@
};
DefaultRegistry.prototype.tasks = function tasks(){
- return Object.keys(this._tasks).map(this.get, this);
+ var self = this;
+
+ return Object.keys(this._tasks).reduce(function(tasks, name){
+ tasks[name] = self.get(name);
+ return tasks;
+ }, {});
};
module.exports = DefaultRegistry; |
8decbaffecdfa2528f6dafaeb3dcde940a208c61 | index.js | index.js | /**
* Turnpike.JS
*
* A lightweight and politely opinionated MVC framework for Node.js. Turnpike can be used as a traditional
* framework, with code generation and rapid deployment, or invoked as a library for more obscure use cases.
*
* Within the framework, some elements will be documented as "plumbing". If you are using Turnpike as a rapid
* deployment framework, then these should be treated as the internal workings of the Turnpike "black box".
* You shouldn't need or want to use or call any of the plumbing yourself.
* If you are using Turnpike as a library, you will probably need use use a good deal of the plumbing directly.
* If you do this, that's fine, but be aware that continuing development of the Turnpike framework may radically
* alter the plumbing interfaces at any time, even between minor versions and revisions.
*
* Other elements of the framework are documented as "porcelain". These are the entry points to the framework we
* expect any app relying on Turnpike to use. In general, after the 0.1.0 release, we will aim to maintain the
* existing plumbing interfaces with few to no changes without a bump in the major version number.
*/
var turnpike = {};
//Porcelain interfaces:
turnpike.EndpointController = require("./lib/EndpointController");
//Plumbing interfaces:
turnpike.ModelPool = require("./lib/ModelPool");
module.exports.turnpike = turnpike;
| /**
* Turnpike.JS
*
* A lightweight and politely opinionated MVC framework for Node.js. Turnpike can be used as a traditional
* framework, with code generation and rapid deployment, or invoked as a library for more obscure use cases.
*
* Within the framework, some elements will be documented as "plumbing". If you are using Turnpike as a rapid
* deployment framework, then these should be treated as the internal workings of the Turnpike "black box".
* You shouldn't need or want to use or call any of the plumbing yourself.
* If you are using Turnpike as a library, you will probably need use use a good deal of the plumbing directly.
* If you do this, that's fine, but be aware that continuing development of the Turnpike framework may radically
* alter the plumbing interfaces at any time, even between minor versions and revisions.
*
* Other elements of the framework are documented as "porcelain". These are the entry points to the framework we
* expect any app relying on Turnpike to use. In general, after the 0.1.0 release, we will aim to maintain the
* existing plumbing interfaces with few to no changes without a bump in the major version number.
*/
var turnpike = {};
//Porcelain interfaces:
turnpike.EndpointController = require("./lib/EndpointController");
turnpike.drive = require("./lib/Drive");
//Plumbing interfaces:
turnpike.ModelPool = require("./lib/ModelPool");
turnpike.Connection = require("./lib/Connection");
module.exports = turnpike;
| Declare a few more entry points | Declare a few more entry points
| JavaScript | mit | jay-depot/turnpike,jay-depot/turnpike | ---
+++
@@ -20,8 +20,10 @@
//Porcelain interfaces:
turnpike.EndpointController = require("./lib/EndpointController");
+turnpike.drive = require("./lib/Drive");
//Plumbing interfaces:
turnpike.ModelPool = require("./lib/ModelPool");
+turnpike.Connection = require("./lib/Connection");
-module.exports.turnpike = turnpike;
+module.exports = turnpike; |
cca531597c989497759bdcf3bbd6cd8da0a0a4ef | index.js | index.js | var es = require('event-stream');
var coffee = require('coffee-script');
var gutil = require('gulp-util');
var formatError = require('./lib/formatError');
var Buffer = require('buffer').Buffer;
module.exports = function(opt){
function modifyFile(file, cb){
if (file.isNull()) return cb(null, file); // pass along
if (file.isStream()) return cb(new Error("gulp-coffee: Streaming not supported"));
var str = file.contents.toString('utf8');
try {
file.contents = new Buffer(coffee.compile(str, opt));
} catch (err) {
var newError = formatError(file, err);
return cb(newError);
}
file.path = gutil.replaceExtension(file.path, ".js");
cb(null, file);
}
return es.map(modifyFile);
}; | var es = require('event-stream');
var coffee = require('coffee-script');
var gutil = require('gulp-util');
var formatError = require('./lib/formatError');
var Buffer = require('buffer').Buffer;
module.exports = function(opt){
function modifyFile(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');
try {
file.contents = new Buffer(coffee.compile(str, opt));
} catch (err) {
var newError = formatError(file, err);
return this.emit('error', newError);
}
file.path = gutil.replaceExtension(file.path, ".js");
this.emit('data', file);
}
return es.through(modifyFile);
};
| Use es.through instead of es.map | Use es.through instead of es.map
See https://github.com/gulpjs/gulp/issues/75#issuecomment-31581317
Partial results for continue-on-error behaviour. | JavaScript | mit | steveluscher/gulp-coffee,develar/gulp-coffee,t3chnoboy/gulp-coffee-es6,doublerebel/gulp-iced-coffee,contra/gulp-coffee,coffee-void/gulp-coffee,jrolfs/gulp-coffee,leny/gulp-coffee,stevelacy/gulp-coffee,dereke/gulp-pogo,mattparlane/gulp-coffee,halhenke/gulp-coffee,typicode/gulp-coffee,wearefractal/gulp-coffee | ---
+++
@@ -5,9 +5,9 @@
var Buffer = require('buffer').Buffer;
module.exports = function(opt){
- function modifyFile(file, cb){
- if (file.isNull()) return cb(null, file); // pass along
- if (file.isStream()) return cb(new Error("gulp-coffee: Streaming not supported"));
+ function modifyFile(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');
@@ -15,11 +15,11 @@
file.contents = new Buffer(coffee.compile(str, opt));
} catch (err) {
var newError = formatError(file, err);
- return cb(newError);
+ return this.emit('error', newError);
}
file.path = gutil.replaceExtension(file.path, ".js");
- cb(null, file);
+ this.emit('data', file);
}
- return es.map(modifyFile);
+ return es.through(modifyFile);
}; |
836cdee104ab82d2d1eebebf403ae415563a20f2 | src/yunity/materialConfig.js | src/yunity/materialConfig.js | export default function materialConfig($mdThemingProvider) {
'ngInject';
$mdThemingProvider.theme('default')
.primaryPalette('pink')
.accentPalette('orange');
} | export default function materialConfig($mdThemingProvider) {
'ngInject';
$mdThemingProvider.theme('default')
.primaryPalette('brown')
.accentPalette('orange');
} | Change primary palette to brown | Change primary palette to brown
| JavaScript | agpl-3.0 | yunity/yunity-webapp-mobile,yunity/yunity-webapp-mobile,yunity/yunity-webapp-mobile | ---
+++
@@ -1,6 +1,6 @@
export default function materialConfig($mdThemingProvider) {
'ngInject';
$mdThemingProvider.theme('default')
- .primaryPalette('pink')
+ .primaryPalette('brown')
.accentPalette('orange');
} |
60aabaa0d9c071939b7960557f122224d4e5231b | config.js | config.js | 'use strict';
/**
* Global config settings.
* (C) 2015 Diego Lafuente.
*/
// requires
var Log = require('log');
// globals
exports.logLevel = 'info';
var log = new Log(exports.logLevel);
exports.limit = 100;
exports.expressPort = 8080;
exports.packagesCollection = 'packages';
exports.mongoConnection = 'mongodb://localhost/quality?autoReconnect=true&connectTimeoutMS=5000';
exports.testMongoConnection = 'mongodb://localhost/qualitytest?autoReconnect=true&connectTimeoutMS=5000';
try {
var localConfig = require("./local-config.js");
for (var key in localConfig) {
exports[key] = localConfig[key];
}
} catch(exception) {
log.notice("local-config.js not found");
} | 'use strict';
/**
* Global config settings.
* (C) 2015 Diego Lafuente.
*/
// requires
var Log = require('log');
// globals
exports.logLevel = 'info';
var log = new Log(exports.logLevel);
exports.limit = 100;
exports.expressPort = 8080;
exports.packagesCollection = 'packages';
exports.mongoConnection = 'mongodb://localhost/quality?autoReconnect=true&connectTimeoutMS=5000';
exports.testMongoConnection = 'mongodb://localhost/qualitytest?autoReconnect=true&connectTimeoutMS=5000';
exports.githubToken = '';
try {
var localConfig = require("./local-config.js");
for (var key in localConfig) {
exports[key] = localConfig[key];
}
} catch(exception) {
log.notice("local-config.js not found");
}
| Add an empty githubToken to avoid request auth crash | Add an empty githubToken to avoid request auth crash
| JavaScript | mit | alexfernandez/package-quality,alexfernandez/package-quality,alexfernandez/package-quality | ---
+++
@@ -17,6 +17,7 @@
exports.packagesCollection = 'packages';
exports.mongoConnection = 'mongodb://localhost/quality?autoReconnect=true&connectTimeoutMS=5000';
exports.testMongoConnection = 'mongodb://localhost/qualitytest?autoReconnect=true&connectTimeoutMS=5000';
+exports.githubToken = '';
try {
var localConfig = require("./local-config.js"); |
84562c0e47351abb6a2db7d58e58b5820af15131 | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'emberfire-utils'
};
| /* jshint node: true */
'use strict';
var Funnel = require('broccoli-funnel');
var featuresToExclude = [];
function filterFeatures(addonConfig) {
addonConfig.exclude.forEach((exclude) => {
if (exclude === 'firebase-util') {
featuresToExclude.push('**/firebase-util.js');
featuresToExclude.push('**/has-limited.js');
}
});
}
module.exports = {
name: 'emberfire-utils',
included: function(app) {
this._super.included.apply(this, arguments);
var addonConfig = this.app.options[this.name];
if (addonConfig) {
filterFeatures(addonConfig);
}
},
treeForApp: function() {
var tree = this._super.treeForApp.apply(this, arguments);
return new Funnel(tree, { exclude: featuresToExclude });
},
treeForAddon: function() {
var tree = this._super.treeForAddon.apply(this, arguments);
return new Funnel(tree, { exclude: featuresToExclude });
},
};
| Add base code for tree-shaking | Add base code for tree-shaking
| JavaScript | mit | rmmmp/emberfire-utils,rmmmp/emberfire-utils | ---
+++
@@ -1,6 +1,40 @@
/* jshint node: true */
'use strict';
+var Funnel = require('broccoli-funnel');
+var featuresToExclude = [];
+
+function filterFeatures(addonConfig) {
+ addonConfig.exclude.forEach((exclude) => {
+ if (exclude === 'firebase-util') {
+ featuresToExclude.push('**/firebase-util.js');
+ featuresToExclude.push('**/has-limited.js');
+ }
+ });
+}
+
module.exports = {
- name: 'emberfire-utils'
+ name: 'emberfire-utils',
+
+ included: function(app) {
+ this._super.included.apply(this, arguments);
+
+ var addonConfig = this.app.options[this.name];
+
+ if (addonConfig) {
+ filterFeatures(addonConfig);
+ }
+ },
+
+ treeForApp: function() {
+ var tree = this._super.treeForApp.apply(this, arguments);
+
+ return new Funnel(tree, { exclude: featuresToExclude });
+ },
+
+ treeForAddon: function() {
+ var tree = this._super.treeForAddon.apply(this, arguments);
+
+ return new Funnel(tree, { exclude: featuresToExclude });
+ },
}; |
e0fc535bba6b9e08548a43ef47b2d692ec0a8119 | index.js | index.js | var fs = require( "fs" );
var path = require( "path" );
var slash = require( "slash" );
var through = require( "through2" );
module.exports = function( jadeFile, options ) {
var scriptTags = "";
options.root = options.root || process.cwd();
var write = function( file, encoding, callback ) {
if( file.path != "undefined" ) {
scriptTags = scriptTags + "\n" + "script(src=\"" + slash( path.relative( options.root, file.path ) ) + "\")";
}
this.push( file );
callback();
};
var flush = function( callback ) {
fs.writeFile( jadeFile, scriptTags, callback );
};
return through.obj( write, flush );
};
| var fs = require( "fs" );
var path = require( "path" );
var slash = require( "slash" );
var through = require( "through2" );
module.exports = function( jadeFile, options ) {
var scriptTags = "";
options.root = options.root || process.cwd();
var write = function( file, encoding, callback ) {
if( file.path != "undefined" ) {
scriptTags = scriptTags + "script(src=\"" + slash( path.relative( options.root, file.path ) ) + "\")" + "\n";
}
this.push( file );
callback();
};
var flush = function( callback ) {
fs.writeFile( jadeFile, scriptTags, callback );
};
return through.obj( write, flush );
};
| Put newline at end of output | Put newline at end of output
| JavaScript | mit | oliversalzburg/gulp-pug-script,oliversalzburg/gulp-jade-script | ---
+++
@@ -9,7 +9,7 @@
var write = function( file, encoding, callback ) {
if( file.path != "undefined" ) {
- scriptTags = scriptTags + "\n" + "script(src=\"" + slash( path.relative( options.root, file.path ) ) + "\")";
+ scriptTags = scriptTags + "script(src=\"" + slash( path.relative( options.root, file.path ) ) + "\")" + "\n";
}
this.push( file );
callback(); |
8bb53eb34850bc0ff0cc7aab1a3bacd39b0a6acc | index.js | index.js | 'use strict';
var buttons = require('sdk/ui/button/action');
buttons.ActionButton({
id: 'elasticmarks-sidebar-button',
label: 'Open Elastic Bookmarks Sidebar',
icon: {
'16': './bookmark-16.png',
'32': './bookmark-32.png',
'64': './bookmark-64.png'
},
onClick: handleClick
});
function handleClick() {
sidebar.show();
}
var sidebar = require('sdk/ui/sidebar').Sidebar({
id: 'elasticmarks-sidebar',
title: 'Elastic Bookmarks Sidebar',
url: './sidebar.html',
onAttach: function (worker) {
worker.port.on('bmquery', function(query, queryId) {
let { search } = require('sdk/places/bookmarks');
search(
{ query: query }
).on('end', function (results) {
worker.port.emit('queryResults', results, queryId);
});
});
}
});
| 'use strict';
var buttons = require('sdk/ui/button/action');
buttons.ActionButton({
id: 'elasticmarks-sidebar-button',
label: 'Open Elastic Bookmarks Sidebar',
icon: {
'16': './bookmark-16.png',
'32': './bookmark-32.png',
'64': './bookmark-64.png'
},
onClick: handleClick
});
function handleClick() {
sidebar.show();
}
var sidebar = require('sdk/ui/sidebar').Sidebar({
id: 'elasticmarks-sidebar',
title: 'Elastic Bookmarks Sidebar',
url: './sidebar.html',
onAttach: function (worker) {
worker.port.on('bmquery', function(query, queryId) {
let { search } = require('sdk/places/bookmarks');
search(
{ query: query }
).on('end', function (bookmarks) {
const fixedBookmarks = bookmarks.map(bookmark => {bookmark.tags = [...bookmark.tags]; return bookmark;});
worker.port.emit('queryResults', fixedBookmarks, queryId);
});
});
}
});
| Make tags accessible in sidebar | Make tags accessible in sidebar
The tags as provided by the query are a Set element.
The sidebar js does not understand Set elements, so
we convert the set to an array.
This is prework for issue #4
| JavaScript | agpl-3.0 | micgro42/firefox-addon-elasticmarks,micgro42/firefox-addon-elasticmarks | ---
+++
@@ -28,8 +28,9 @@
search(
{ query: query }
- ).on('end', function (results) {
- worker.port.emit('queryResults', results, queryId);
+ ).on('end', function (bookmarks) {
+ const fixedBookmarks = bookmarks.map(bookmark => {bookmark.tags = [...bookmark.tags]; return bookmark;});
+ worker.port.emit('queryResults', fixedBookmarks, queryId);
});
});
} |
d06d593a348d01a633b7ac23babfbe0f96e563ad | index.js | index.js | var path = require('path');
var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');
module.exports = function(source, map) {
this.cacheable && this.cacheable();
this.addDependency(this.resourcePath);
var callback = this.async();
// Pass on query parameters as an options object to the DtsCreator. This lets
// you change the default options of the DtsCreator and e.g. use a different
// output folder.
var options = loaderUtils.getOptions(this) || {};
var context = options.context || this.context || this.rootContext;
var emitFile = !options.noEmit;
// Make sure to not modify options object directly
var creatorOptions = JSON.parse(JSON.stringify(options));
delete creatorOptions.noEmit;
var creator = new DtsCreator(creatorOptions);
// creator.create(..., source) tells the module to operate on the
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
if (emitFile) {
// Emit the created content as well
this.emitFile(path.relative(context, content.outputFilePath), content.contents || [''], map);
}
content.writeFile().then(_ => {
callback(null, source, map);
});
});
};
| var path = require('path');
var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');
module.exports = function(source, map) {
this.cacheable && this.cacheable();
this.addDependency(this.resourcePath);
var callback = this.async();
// Pass on query parameters as an options object to the DtsCreator. This lets
// you change the default options of the DtsCreator and e.g. use a different
// output folder.
var options = loaderUtils.getOptions(this) || {};
var context = options.context || this.context || this.rootContext;
var emitFile = !options.noEmit;
// Make sure to not modify options object directly
var creatorOptions = Object.assign({}, options);
delete creatorOptions.noEmit;
var creator = new DtsCreator(creatorOptions);
// creator.create(..., source) tells the module to operate on the
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
if (emitFile) {
// Emit the created content as well
this.emitFile(path.relative(context, content.outputFilePath), content.contents || [''], map);
}
content.writeFile().then(_ => {
callback(null, source, map);
});
});
};
| Use Object.assign for better performance | Use Object.assign for better performance | JavaScript | mit | olegstepura/typed-css-modules-loader | ---
+++
@@ -15,7 +15,7 @@
var emitFile = !options.noEmit;
// Make sure to not modify options object directly
- var creatorOptions = JSON.parse(JSON.stringify(options));
+ var creatorOptions = Object.assign({}, options);
delete creatorOptions.noEmit;
var creator = new DtsCreator(creatorOptions); |
7e4d2ccc6a1ecfabcdd70ec73a3d49a1fc835721 | index.js | index.js | var build = require('./build');
var clean = require('./clean');
var copy = require('./copy');
var karma = require('./default-karma.conf');
var lint = require('./lint');
var requirejs = require('./requirejs');
var resolve = require('./resolve');
var test = require('./test');
var teamCity = require('./teamCity');
var typescript = require('./typescript');
module.exports = {
build: build,
clean: clean,
copy: copy,
karma: karma,
lint: lint,
requirejs: requirejs,
resolve: resolve,
test: test,
teamCity: teamCity,
typescript: typescript,
};
| var build = require('./build');
var clean = require('./clean');
var compile = require('./compile');
var copy = require('./copy');
var karma = require('./default-karma.conf');
var lint = require('./lint');
var requirejs = require('./requirejs');
var resolve = require('./resolve');
var teamCity = require('./teamCity');
var test = require('./test');
var typescript = require('./typescript');
module.exports = {
build: build,
clean: clean,
compile: compile,
copy: copy,
karma: karma,
lint: lint,
requirejs: requirejs,
resolve: resolve,
teamCity: teamCity,
test: test,
typescript: typescript,
};
| Add compile and rearrange (alphabetical) | Add compile and rearrange (alphabetical)
| JavaScript | mit | RenovoSolutions/Gulp-Typescript-Utilities,SonofNun15/Gulp-Typescript-Utilities | ---
+++
@@ -1,23 +1,25 @@
var build = require('./build');
var clean = require('./clean');
+var compile = require('./compile');
var copy = require('./copy');
var karma = require('./default-karma.conf');
var lint = require('./lint');
var requirejs = require('./requirejs');
var resolve = require('./resolve');
+var teamCity = require('./teamCity');
var test = require('./test');
-var teamCity = require('./teamCity');
var typescript = require('./typescript');
module.exports = {
build: build,
clean: clean,
+ compile: compile,
copy: copy,
karma: karma,
lint: lint,
requirejs: requirejs,
resolve: resolve,
+ teamCity: teamCity,
test: test,
- teamCity: teamCity,
typescript: typescript,
}; |
5eaee47df9738da4fe488289e2b3220d9585f0ca | index.js | index.js | const Assert = require('assert');
const FS = require('fs');
const Winston = require('winston');
const Factory = require('./lib/factory');
var exceptionLogger;
function isString(str) {
return typeof str === 'string';
}
module.exports = function (namespace) {
var level;
Assert(namespace && isString(namespace), 'must provide namespace');
level = process.env.LOG_LEVEL || 'info'; // eslint-disable-line no-process-env
return Factory(namespace, level, !exceptionLogger);
};
module.exports.writeExceptions = function (path) {
Assert(path && isString(path), 'must provide a file path');
// TODO use FS.accessSync(path, FS.F_OK | FS.W_OK), node > 4.0
FS.appendFileSync(path, ''); // eslint-disable-line no-sync
exceptionLogger = new Winston.Logger({
transports: [
new Winston.transports.File({
exitOnError: true,
filename: path,
handleExceptions: true,
humanReadableUnhandledException: true
})
]
});
};
| const Assert = require('assert');
const FS = require('fs');
const Winston = require('winston');
const Factory = require('./lib/factory');
var exceptionLogger;
function isString(str) {
return typeof str === 'string';
}
module.exports = function (namespace) {
var level;
Assert(namespace && isString(namespace), 'must provide namespace');
level = process.env.LOG_LEVEL || 'info'; // eslint-disable-line no-process-env
return Factory(namespace, level, !exceptionLogger);
};
module.exports.writeExceptions = function (path, exitOnError) {
Assert(path && isString(path), 'must provide a file path');
// TODO use FS.accessSync(path, FS.F_OK | FS.W_OK), node > 4.0
FS.appendFileSync(path, ''); // eslint-disable-line no-sync
exceptionLogger = new Winston.Logger({
transports: [
new Winston.transports.File({
exitOnError: exitOnError,
filename: path,
handleExceptions: true,
humanReadableUnhandledException: true
})
]
});
};
| Add exitOnError as optional parameter | Add exitOnError as optional parameter
| JavaScript | mit | onmodulus/logger | ---
+++
@@ -20,7 +20,7 @@
return Factory(namespace, level, !exceptionLogger);
};
-module.exports.writeExceptions = function (path) {
+module.exports.writeExceptions = function (path, exitOnError) {
Assert(path && isString(path), 'must provide a file path');
// TODO use FS.accessSync(path, FS.F_OK | FS.W_OK), node > 4.0
@@ -29,7 +29,7 @@
exceptionLogger = new Winston.Logger({
transports: [
new Winston.transports.File({
- exitOnError: true,
+ exitOnError: exitOnError,
filename: path,
handleExceptions: true,
humanReadableUnhandledException: true |
063113769c777c480732856fb66d575856a3b1b4 | app/assets/javascripts/admin/analytics.js | app/assets/javascripts/admin/analytics.js | $(document).ready(function() {
$("#date_range").daterangepicker({ format: 'YYYY-MM-DD' });
$("#date_range").on('apply.daterangepicker', function(ev, picker){
Chartkick.eachChart( function(chart) {
var path, search;
[path, search] = chart.dataSource.split('?')
var params = new URLSearchParams(search);
params.set('date_start', picker.startDate.format('YYYY-MM-DD'));
params.set('date_end', picker.endDate.format('YYYY-MM-DD'));
chart.dataSource = path + '?' + params.toString();
chart.refreshData();
});
});
});
| $(document).ready(function() {
$("#date_range").daterangepicker({
locale: { format: 'YYYY-MM-DD' }
});
$("#date_range").on('apply.daterangepicker', function(ev, picker){
Chartkick.eachChart( function(chart) {
var path, search;
[path, search] = chart.dataSource.split('?')
var params = new URLSearchParams(search);
params.set('date_start', picker.startDate.format('YYYY-MM-DD'));
params.set('date_end', picker.endDate.format('YYYY-MM-DD'));
chart.dataSource = path + '?' + params.toString();
chart.refreshData();
});
});
});
| Fix date ranrge picker format | Fix date ranrge picker format
| JavaScript | agpl-3.0 | EFForg/action-center-platform,EFForg/action-center-platform,EFForg/action-center-platform,EFForg/action-center-platform | ---
+++
@@ -1,5 +1,7 @@
$(document).ready(function() {
- $("#date_range").daterangepicker({ format: 'YYYY-MM-DD' });
+ $("#date_range").daterangepicker({
+ locale: { format: 'YYYY-MM-DD' }
+ });
$("#date_range").on('apply.daterangepicker', function(ev, picker){
Chartkick.eachChart( function(chart) { |
d219f427858f0bf97e2ae13564113e49659acb5b | index.js | index.js | 'use strict'
const port = 5000
var server = require('./server')
server.listen(port, () => console.log('Server is up on port %d.', port))
| 'use strict'
let ENV
try { // look for local environment variable file first
ENV = require('./env')
} catch (LocalEnvFileNotFound) {
ENV = process.env
}
const PORT = ENV.PORT || 5000
let server = require('./server')
server.listen(PORT, () => console.log('Server is up on port %d.', PORT))
| Use port specified in environment for server | Use port specified in environment for server
| JavaScript | mit | mooniker/captran | ---
+++
@@ -1,7 +1,14 @@
'use strict'
-const port = 5000
+let ENV
+try { // look for local environment variable file first
+ ENV = require('./env')
+} catch (LocalEnvFileNotFound) {
+ ENV = process.env
+}
-var server = require('./server')
+const PORT = ENV.PORT || 5000
-server.listen(port, () => console.log('Server is up on port %d.', port))
+let server = require('./server')
+
+server.listen(PORT, () => console.log('Server is up on port %d.', PORT)) |
24f59d9b90e634932e801870ade69e2fa6cd9a84 | index.js | index.js | 'use strict';
var catchErrors = require('./lib/catchErrors');
var log = require('./lib/log');
var transportConsole = require('./lib/transports/console');
var transportFile = require('./lib/transports/file');
var transportRemote = require('./lib/transports/remote');
var transportMainConsole = require('./lib/transports/mainConsole');
var transportRendererConsole = require('./lib/transports/rendererConsole');
var utils = require('./lib/utils');
module.exports = {
catchErrors: function callCatchErrors(options) {
var opts = Object.assign({}, {
log: module.exports.error,
showDialog: process.type === 'browser'
}, options || {});
catchErrors(opts);
},
hooks: [],
isDev: utils.isDev(),
levels: ['error', 'warn', 'info', 'verbose', 'debug', 'silly'],
variables: {
processType: process.type
}
};
module.exports.transports = {
console: transportConsole(module.exports),
file: transportFile(module.exports),
remote: transportRemote(module.exports),
mainConsole: transportMainConsole(module.exports),
rendererConsole: transportRendererConsole(module.exports)
};
module.exports.levels.forEach(function (level) {
module.exports[level] = log.bind(null, module.exports, level);
});
module.exports.default = module.exports;
| 'use strict';
var catchErrors = require('./lib/catchErrors');
var log = require('./lib/log');
var transportConsole = require('./lib/transports/console');
var transportFile = require('./lib/transports/file');
var transportRemote = require('./lib/transports/remote');
var transportMainConsole = require('./lib/transports/mainConsole');
var transportRendererConsole = require('./lib/transports/rendererConsole');
var utils = require('./lib/utils');
module.exports = {
catchErrors: function callCatchErrors(options) {
var opts = Object.assign({}, {
log: module.exports.error,
showDialog: process.type === 'browser'
}, options || {});
catchErrors(opts);
},
hooks: [],
isDev: utils.isDev(),
levels: ['error', 'warn', 'info', 'verbose', 'debug', 'silly'],
variables: {
processType: process.type
}
};
module.exports.transports = {
console: transportConsole(module.exports),
file: transportFile(module.exports),
remote: transportRemote(module.exports),
mainConsole: transportMainConsole(module.exports),
rendererConsole: transportRendererConsole(module.exports)
};
module.exports.levels.forEach(function (level) {
module.exports[level] = log.bind(null, module.exports, level);
});
module.exports.log = log.bind(null, module.exports, 'info');
module.exports.default = module.exports;
| Add log function for compatibility with Console API | Add log function for compatibility with Console API
| JavaScript | mit | megahertz/electron-log,megahertz/electron-log,megahertz/electron-log | ---
+++
@@ -38,4 +38,6 @@
module.exports[level] = log.bind(null, module.exports, level);
});
+module.exports.log = log.bind(null, module.exports, 'info');
+
module.exports.default = module.exports; |
2dfb621099b647dd5b513fef9abc02256dcd74ec | index.js | index.js | var ls = require('ls');
var fs = require('fs');
exports.generate = function(dir) {
if(dir === undefined || dir === null) {
dir = __dirname;
}
fs.mkdir(dir);
var decks = ls(__dirname + "/decks/*.js");
for(var i = 0, len = decks.length; i < len; i++) {
var json = require(decks[i].full).generate();
var out = JSON.stringify(json, null, 2);
var filename = json.name.replace(" ", "_").replace("[^a-zA-Z0-9]", "");
fs.writeFile(dir + "/" + filename + ".json", out, function(err) {
if(err) {
return console.log(err);
}
console.log(filename + " was saved!");
});
}
}
if(module.parent == null) {
exports.generate();
}
| var ls = require('ls');
var fs = require('fs');
exports.generate = function(dir) {
if(dir === undefined || dir === null) {
dir = __dirname;
}
fs.mkdir(dir, 0777, function(err) {
if(err && err.code != 'EEXIST') {
return console.error(err);
}
var decks = ls(__dirname + "/decks/*.js");
for(var i = 0, len = decks.length; i < len; i++) {
var json = require(decks[i].full).generate();
var out = JSON.stringify(json, null, 2);
var filename = json.name.replace(" ", "_").replace("[^a-zA-Z0-9]", "");
fs.writeFile(dir + "/" + filename + ".json", out, function(err) {
if(err) {
return console.log(err);
}
console.log(filename + " was saved!");
});
}
});
}
if(module.parent == null) {
exports.generate();
}
| Handle mkdir error when directory exists | Handle mkdir error when directory exists
| JavaScript | mit | DataDecks/DataDecks-Data | ---
+++
@@ -4,19 +4,23 @@
if(dir === undefined || dir === null) {
dir = __dirname;
}
- fs.mkdir(dir);
- var decks = ls(__dirname + "/decks/*.js");
- for(var i = 0, len = decks.length; i < len; i++) {
- var json = require(decks[i].full).generate();
- var out = JSON.stringify(json, null, 2);
- var filename = json.name.replace(" ", "_").replace("[^a-zA-Z0-9]", "");
- fs.writeFile(dir + "/" + filename + ".json", out, function(err) {
- if(err) {
- return console.log(err);
- }
- console.log(filename + " was saved!");
- });
- }
+ fs.mkdir(dir, 0777, function(err) {
+ if(err && err.code != 'EEXIST') {
+ return console.error(err);
+ }
+ var decks = ls(__dirname + "/decks/*.js");
+ for(var i = 0, len = decks.length; i < len; i++) {
+ var json = require(decks[i].full).generate();
+ var out = JSON.stringify(json, null, 2);
+ var filename = json.name.replace(" ", "_").replace("[^a-zA-Z0-9]", "");
+ fs.writeFile(dir + "/" + filename + ".json", out, function(err) {
+ if(err) {
+ return console.log(err);
+ }
+ console.log(filename + " was saved!");
+ });
+ }
+ });
}
if(module.parent == null) {
exports.generate(); |
14edb196096b9263a5e119a69a83d729dc0607f2 | api/signup/index.js | api/signup/index.js | var async = require( 'async' );
var Validation = require( './validation' );
var Data = require( './data' );
var Output = require( './output' );
var utils = require( '../utils' );
var validationError = require( '../utils/error_messages' ).validationError;
exports.userSignup = function ( req, res ) {
async.waterfall( [
function ( callback ) {
req.checkBody( 'email', "Must be an email address" ).isEmail();
req.checkBody( 'password', "Field is required" ).notEmpty();
var errors = req.validationErrors();
if ( errors ) {
return callback( errors );
}
return callback( null, req.body );
},
function ( requestBody, callback ) {
Data.createUser( req.body.email, req.body.password, callback );
},
function ( newUserData, callback ) {
Output.forSignup( newUserData, callback );
}
], function ( err, outputData ) {
if ( err ) {
return utils.handleRouteError( err, res );
}
return res.json( outputData, 201 );
} );
};
| var async = require( 'async' );
var Data = require( './data' );
var Output = require( './output' );
var utils = require( '../utils' );
exports.userSignup = function ( req, res ) {
async.waterfall( [
function ( callback ) {
req.checkBody( 'email', "Must be an email address" ).isEmail();
req.checkBody( 'password', "Field is required" ).notEmpty();
var errors = req.validationErrors();
if ( errors ) {
return callback( errors );
}
return callback( null, req.body );
},
function ( requestBody, callback ) {
Data.createUser( req.body.email, req.body.password, callback );
},
function ( newUserData, callback ) {
Output.forSignup( newUserData, callback );
}
], function ( err, outputData ) {
if ( err ) {
return utils.handleRouteError( err, res );
}
return res.json( outputData, 201 );
} );
};
| Clean out old validation stuff from Signup | Clean out old validation stuff from Signup
| JavaScript | mit | projectweekend/Node-Backend-Seed | ---
+++
@@ -1,9 +1,7 @@
var async = require( 'async' );
-var Validation = require( './validation' );
var Data = require( './data' );
var Output = require( './output' );
var utils = require( '../utils' );
-var validationError = require( '../utils/error_messages' ).validationError;
exports.userSignup = function ( req, res ) { |
09920accba7a74d481e57b6389af6c45b3307375 | index.js | index.js | var rollbar = require("rollbar");
module.exports = {
install: function(Vue, options) {
Vue.rollbar = rollbar.init(options);
}
};
| var Rollbar = require("rollbar");
module.exports = {
install: function(Vue, options) {
Vue.rollbar = new Rollbar(options);
}
};
| Use new Rollbar initialization method | Use new Rollbar initialization method
| JavaScript | mit | Zevran/vue-rollbar,Zevran/vue-rollbar | ---
+++
@@ -1,7 +1,7 @@
-var rollbar = require("rollbar");
+var Rollbar = require("rollbar");
module.exports = {
install: function(Vue, options) {
- Vue.rollbar = rollbar.init(options);
+ Vue.rollbar = new Rollbar(options);
}
}; |
03a39b08a64b898717a46405c92d67b285dae98f | index.js | index.js | var fs = require('fs');
var postcss = require('postcss');
var autoprefixer = require('autoprefixer');
var app = 'src/app.css';
var dist = 'dist/build.css';
var css = fs.readFileSync(app);
postcss([autoprefixer])
.process(css, {
from: app,
to: dist
})
.then(function(res) {
fs.writeFileSync(dist, res.css);
});
| var fs = require('fs');
var postcss = require('postcss');
var autoprefixer = require('autoprefixer');
var app = 'src/app.css';
var dist = 'dist/build.css';
var css = fs.readFileSync(app);
var processors = [
autoprefixer({
browsers: ['> 1%', 'last 2 versions'],
cascade: false
})
];
postcss(processors)
.process(css, {
from: app,
to: dist
})
.then(function(res) {
fs.writeFileSync(dist, res.css);
});
| Store processors into array. Pass through options to Autoprefixer. | Store processors into array. Pass through options to Autoprefixer.
| JavaScript | mit | cahamilton/postcss-test | ---
+++
@@ -7,7 +7,14 @@
var css = fs.readFileSync(app);
-postcss([autoprefixer])
+var processors = [
+ autoprefixer({
+ browsers: ['> 1%', 'last 2 versions'],
+ cascade: false
+ })
+];
+
+postcss(processors)
.process(css, {
from: app,
to: dist |
8ef4d85fd4fcc1a90841730fd01b3dd95354bd9c | index.js | index.js | module.exports = {
parser: 'babel-eslint',
extends: 'airbnb',
globals: {
describe: true,
it: true,
},
};
| module.exports = {
parser: 'babel-eslint',
extends: 'airbnb',
globals: {
before: true,
beforeEach: true,
after: true,
afterEach: true,
describe: true,
it: true,
},
};
| Allow some more test functions. | Allow some more test functions.
| JavaScript | mit | crewmeister/eslint-config-crewmeister | ---
+++
@@ -2,6 +2,10 @@
parser: 'babel-eslint',
extends: 'airbnb',
globals: {
+ before: true,
+ beforeEach: true,
+ after: true,
+ afterEach: true,
describe: true,
it: true,
}, |
fb3cfeda6e6f3dcb7c72df8ae750005067b7ed94 | test/docco_test.js | test/docco_test.js | "use strict"
var grunt = require('grunt');
var rr = require("rimraf");
exports.docco = {
tests: function(test) {
var css = grunt.file.read("docs/docco.css");
var html = grunt.file.read("docs/docco.html");
test.expect(2);
test.equal(css.length, 7207, "Should create CSS.");
test.equal(html.length, 1017, "Should create HTML.");
test.done();
rr('docs', function(){});
}
};
| "use strict";
var grunt = require('grunt');
var rr = require("rimraf");
exports.docco = {
tearDown: function (callback) {
rr('docs', function(){});
callback();
},
tests: function(test) {
var css = grunt.file.read("docs/docco.css");
var html = grunt.file.read("docs/docco.html");
test.expect(2);
test.ok(css.length > 0, "Should create CSS.");
test.ok(html.length > 0, "Should create HTML.");
test.done();
}
};
| Change of assertion to not depend on exact file length. Removal of docs moved to tearDown, to call it on test failure. | Change of assertion to not depend on exact file length. Removal of docs moved to tearDown, to call it on test failure.
| JavaScript | mit | DavidSouther/grunt-docco,neocotic/grunt-docco,joseph-jja/grunt-docco-dir,joseph-jja/grunt-docco-dir | ---
+++
@@ -1,18 +1,21 @@
-"use strict"
+"use strict";
var grunt = require('grunt');
var rr = require("rimraf");
exports.docco = {
+ tearDown: function (callback) {
+ rr('docs', function(){});
+ callback();
+ },
+
tests: function(test) {
var css = grunt.file.read("docs/docco.css");
var html = grunt.file.read("docs/docco.html");
test.expect(2);
- test.equal(css.length, 7207, "Should create CSS.");
- test.equal(html.length, 1017, "Should create HTML.");
+ test.ok(css.length > 0, "Should create CSS.");
+ test.ok(html.length > 0, "Should create HTML.");
test.done();
-
- rr('docs', function(){});
}
}; |
1a54820bbac1c3fff9f68ecee7b979cb9679bbc8 | index.js | index.js | var importcss = require('rework-npm')
, rework = require('rework')
, variables = require('rework-vars')
, path = require('path')
, read = require('fs').readFileSync
module.exports = function (opts, cb) {
opts = opts || {}
var css = rework(read(opts.entry, 'utf8'))
css.use(importcss(path.dirname(opts.entry)))
if (opts.variables) {
css.use(variables(opts.variables))
}
if (opts.transform) {
opts.transform(css.toString(), cb)
} else {
cb(null, css.toString())
}
}
| var importcss = require('rework-npm')
, rework = require('rework')
, variables = require('rework-vars')
, path = require('path')
, read = require('fs').readFileSync
module.exports = function (opts, cb) {
opts = opts || {}
var css = rework(read(opts.entry, 'utf8'))
css.use(importcss(path.dirname(opts.entry)))
if (opts.variables) {
css.use(variables(opts.variables))
}
// utilize any custom rework plugins provided
if (opts.plugins) {
opts.plugins.forEach(function (plugin) {
css.use(plugin)
})
}
if (opts.transform) {
opts.transform(css.toString(), cb)
} else {
cb(null, css.toString())
}
}
| Add opts.plugins for specifying additional rework plugins | Add opts.plugins for specifying additional rework plugins | JavaScript | mit | atomify/atomify-css | ---
+++
@@ -8,9 +8,18 @@
opts = opts || {}
var css = rework(read(opts.entry, 'utf8'))
css.use(importcss(path.dirname(opts.entry)))
+
if (opts.variables) {
css.use(variables(opts.variables))
}
+
+ // utilize any custom rework plugins provided
+ if (opts.plugins) {
+ opts.plugins.forEach(function (plugin) {
+ css.use(plugin)
+ })
+ }
+
if (opts.transform) {
opts.transform(css.toString(), cb)
} else { |
5904b6e737d32dd743a2c323c56e105ab5a710b6 | gulpfile.babel.js | gulpfile.babel.js | 'use strict';
import gulp from 'gulp';
import ignite from 'gulp-ignite';
import browserify from 'gulp-ignite-browserify';
import babelify from 'babelify';
import inject from 'gulp-inject';
import uglify from 'uglify-js';
const ASSET_PATH = './src/Bonfire.JavascriptLoader/Assets';
const INJECT_PATH = './src/Bonfire.JavascriptLoader/Core';
const buildTask = {
name: 'build',
fn() {
return gulp.src(INJECT_PATH + '/JavascriptLoaderHtmlHelper.cs')
.pipe(inject(gulp.src(`${ASSET_PATH}/loader.js`), {
starttag: '/*INJECT:JS*/',
endtag: '/*ENDINJECT*/',
transform: (filepath, file) => {
return `"${uglify.minify(file.contents.toString('utf8'), { fromString: true }).code.slice(1)}"`;
}
}))
.pipe(gulp.dest(INJECT_PATH));
}
}
const tasks = [
browserify,
buildTask,
];
const options = {
browserify: {
src: './src/Bonfire.JavascriptLoader.Demo/Assets/main.js',
dest: './src/Bonfire.JavascriptLoader.Demo/Content/js',
options: {
transform: [babelify],
},
watchFiles: [
'./src/Bonfire.JavascriptLoader.Demo/Assets/*',
],
},
};
ignite.start(tasks, options);
| 'use strict';
import gulp from 'gulp';
import ignite from 'gulp-ignite';
import browserify from 'gulp-ignite-browserify';
import babelify from 'babelify';
import inject from 'gulp-inject';
import uglify from 'uglify-js';
import yargs from 'yargs';
const ASSET_PATH = './src/Bonfire.JavascriptLoader/Assets';
const INJECT_PATH = './src/Bonfire.JavascriptLoader/Core';
const buildTask = {
name: 'build',
fn() {
return gulp.src(INJECT_PATH + '/JavascriptLoaderHtmlHelper.cs')
.pipe(inject(gulp.src(`${ASSET_PATH}/loader.js`), {
starttag: '/*INJECT:JS*/',
endtag: '/*ENDINJECT*/',
transform: (filepath, file) => {
return `"${uglify.minify(file.contents.toString('utf8'), { fromString: true }).code.slice(1)}"`;
}
}))
.pipe(gulp.dest(INJECT_PATH));
}
}
const tasks = [
browserify,
buildTask,
];
const filename = yargs.argv.filename || yargs.argv.f || 'main.js';
const options = {
browserify: {
src: `./src/Bonfire.JavascriptLoader.Demo/Assets/${filename}`,
dest: './src/Bonfire.JavascriptLoader.Demo/Content/js',
filename: filename,
options: {
transform: [babelify],
},
watchFiles: [
'./src/Bonfire.JavascriptLoader.Demo/Assets/*',
],
},
};
ignite.start(tasks, options);
| Add ability to build other js files | Add ability to build other js files
| JavaScript | mit | buildabonfire/Bonfire.JavascriptLoader,buildabonfire/Bonfire.JavascriptLoader,buildabonfire/Bonfire.JavascriptLoader | ---
+++
@@ -6,6 +6,7 @@
import babelify from 'babelify';
import inject from 'gulp-inject';
import uglify from 'uglify-js';
+import yargs from 'yargs';
const ASSET_PATH = './src/Bonfire.JavascriptLoader/Assets';
const INJECT_PATH = './src/Bonfire.JavascriptLoader/Core';
@@ -30,10 +31,13 @@
buildTask,
];
+const filename = yargs.argv.filename || yargs.argv.f || 'main.js';
+
const options = {
browserify: {
- src: './src/Bonfire.JavascriptLoader.Demo/Assets/main.js',
+ src: `./src/Bonfire.JavascriptLoader.Demo/Assets/${filename}`,
dest: './src/Bonfire.JavascriptLoader.Demo/Content/js',
+ filename: filename,
options: {
transform: [babelify],
}, |
e8dffdae918fd10fdc547b80a10c5fb09e8fe188 | app/scripts/map-data.js | app/scripts/map-data.js | (function(window, undefined) {
var data = window.data = window.data || { };
var map = data.map = data.map || { };
map['Germany'] = [52.5, 13.4];
map['France'] = [48.9, 2.4];
})(window); | (function(window, undefined) {
var data = window.data = window.data || { };
var map = data.map = data.map || { };
map['Germany'] = [52.5, 13.4];
map['France'] = [48.9, 2.4];
map['Spain'] = [40.4, -3.7];
map['Russia'] = [55.7, 37.6];
map['Italy'] = [41.9, 12.5];
map['Ukraine'] = [50.5, 30.5];
map['Sweden'] = [59.3, 18.0];
map['Norway'] = [60.0, 10.8];
map['Estonia'] = [59.4, 24.7];
})(window); | Add remaining capitals for FPO dataset | Add remaining capitals for FPO dataset
| JavaScript | apache-2.0 | SF-Housing-Visualization/mids-sf-housing-visualization,SF-Housing-Visualization/mids-sf-housing-visualization | ---
+++
@@ -4,5 +4,12 @@
var map = data.map = data.map || { };
map['Germany'] = [52.5, 13.4];
map['France'] = [48.9, 2.4];
+ map['Spain'] = [40.4, -3.7];
+ map['Russia'] = [55.7, 37.6];
+ map['Italy'] = [41.9, 12.5];
+ map['Ukraine'] = [50.5, 30.5];
+ map['Sweden'] = [59.3, 18.0];
+ map['Norway'] = [60.0, 10.8];
+ map['Estonia'] = [59.4, 24.7];
})(window); |
5190e1409985f4c1e1268772fd378e8a275c128e | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-sinon',
options: {
nodeAssets: {
'sinon': {
import: [{ path: 'pkg/sinon.js', type: 'test' }]
}
}
},
included: function (app) {
this._super.included.apply(this, arguments);
app.import('vendor/shims/sinon.js', { type: 'test' });
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-sinon',
options: {
nodeAssets: {
'sinon': {
import: [{ path: 'pkg/sinon.js', type: 'test' }]
}
}
},
included: function(app) {
this._super.included.apply(this, arguments);
while (typeof app.import !== 'function' && app.app) {
app = app.app;
}
app.import('vendor/shims/sinon.js', { type: 'test' });
}
};
| Add support for being a nested dependency | Add support for being a nested dependency
| JavaScript | mit | csantero/ember-sinon,csantero/ember-sinon | ---
+++
@@ -12,8 +12,12 @@
}
},
- included: function (app) {
+ included: function(app) {
this._super.included.apply(this, arguments);
+
+ while (typeof app.import !== 'function' && app.app) {
+ app = app.app;
+ }
app.import('vendor/shims/sinon.js', { type: 'test' });
} |
2b5ca9641957a664b772d8d146273abd0fcf286b | index.js | index.js | const loaderUtils = require('loader-utils');
const path = require('path');
const deepMerge = require('./lib/deep-merge');
module.exports = function(source) {
const HEADER = '/**** Start Merge Loader ****/';
const FOOTER = '/**** End Merge Loader ****/';
const callback = this.async();
const options = loaderUtils.getOptions(this);
const thisLoader = this;
const overridePath = path.resolve(__dirname,
`test/cases/lib/${options.override}`);
this.cacheable && this.cacheable();
this.loadModule(overridePath,
function(err, overrideSource, sourceMap, module) {
if (err) { return callback(err); }
const override = overrideSource
.replace(/^ ?module.exports ?= ?/i, '')
.replace(/\;/g, '');
const mergedModule = deepMerge(JSON.parse(source), JSON.parse(override));
callback(null, mergedModule);
});
};
| const loaderUtils = require('loader-utils');
const path = require('path');
const deepMerge = require('./lib/deep-merge');
module.exports = function(source) {
const callback = this.async();
const options = loaderUtils.getOptions(this);
const overridePath = path.resolve(__dirname,
`test/cases/lib/${options.override}`);
this.cacheable && this.cacheable();
this.loadModule(overridePath,
function(err, overrideSource, sourceMap, module) {
if (err) { return callback(err); }
const override = overrideSource
.replace(/^ ?module.exports ?= ?/i, '')
.replace(/\;/g, '');
const mergedModule = deepMerge(JSON.parse(source), JSON.parse(override));
callback(null, mergedModule);
});
};
| Remove unnecessary variables in loader | Remove unnecessary variables in loader
| JavaScript | mit | bitfyre/config-merge-loader | ---
+++
@@ -3,11 +3,8 @@
const deepMerge = require('./lib/deep-merge');
module.exports = function(source) {
- const HEADER = '/**** Start Merge Loader ****/';
- const FOOTER = '/**** End Merge Loader ****/';
const callback = this.async();
const options = loaderUtils.getOptions(this);
- const thisLoader = this;
const overridePath = path.resolve(__dirname,
`test/cases/lib/${options.override}`);
|
c22b100cbd55f6bb4e4097f2def34839f5d70780 | packages/generator-react-server/generators/app/templates/test.js | packages/generator-react-server/generators/app/templates/test.js | import cp from 'child_process';
import http from 'http';
import test from 'ava';
let rs;
test.before('start the server', async () => {
rs = cp.spawn('npm', ['start']);
rs.stderr.on('data', data => console.error(data.toString()));
await sleep(10000);
});
test('server is running', async t => {
t.is(200, await getResponseCode('/'));
});
test.after.always('shut down the server', async () => {
rs.kill('SIGHUP');
});
// gets the response code for an http request
function getResponseCode(url) {
return new Promise((resolve, reject) => {
const req = http.get({
hostname: 'localhost',
port: 3000,
path: url,
}, res => {
resolve(res.statusCode);
});
req.on('error', e => reject(e));
});
}
function sleep(time) {
return new Promise(resolve => {
setTimeout(resolve, time);
});
}
| import cp from 'child_process';
import http from 'http';
import test from 'ava';
let rs;
test.before('start the server', async () => {
rs = cp.spawn('npm', ['start']);
rs.stderr.on('data', data => console.error(data.toString()));
await sleep(15000);
});
test('server is running', async t => {
t.is(200, await getResponseCode('/'));
});
test.after.always('shut down the server', async () => {
rs.kill('SIGHUP');
});
// gets the response code for an http request
function getResponseCode(url) {
return new Promise((resolve, reject) => {
const req = http.get({
hostname: 'localhost',
port: 3000,
path: url,
}, res => {
resolve(res.statusCode);
});
req.on('error', e => reject(e));
});
}
function sleep(time) {
return new Promise(resolve => {
setTimeout(resolve, time);
});
}
| Increase wait time for server start to 15s | Increase wait time for server start to 15s
| JavaScript | apache-2.0 | emecell/react-server,lidawang/react-server,redfin/react-server,lidawang/react-server,emecell/react-server,redfin/react-server | ---
+++
@@ -7,7 +7,7 @@
test.before('start the server', async () => {
rs = cp.spawn('npm', ['start']);
rs.stderr.on('data', data => console.error(data.toString()));
- await sleep(10000);
+ await sleep(15000);
});
test('server is running', async t => { |
33ab3db66a6f37f0e8c8f48a19035464fea358c1 | index.js | index.js | import { Kefir as K } from "kefir";
const NEVER = K.never();
const ZERO = K.constant(0);
const ADD1 = (x) => x + 1;
const SUBTRACT1 = (x) => x - 1;
const ALWAYS = (x) => () => x;
const delay = (n, s) => s.slidingWindow(n + 1, 2).map(([i, _]) => i);
function galvo({ advance = NEVER, recede = NEVER, index = ZERO } = {}, slides) {
const length = slides.length;
const nextT = advance.map(() => ADD1);
const previousT = recede.map(() => SUBTRACT1);
const indexT = index.map(ALWAYS);
const transformations = K.merge([
nextT,
previousT,
indexT
]);
const currentIndex =
transformations
.scan((i, transform) => transform(i), 0)
.map((i) => (i + length) % length);
const current = currentIndex.map((i) => slides[i]);
const previousIndex = delay(1, currentIndex);
const previous = delay(1, current);
return {
current,
currentIndex,
previous,
previousIndex
}
}
module.exports = galvo;
| import { Kefir as K } from "kefir";
const NEVER = K.never();
const ZERO = K.constant(0);
const ADD1 = (x) => x + 1;
const SUBTRACT1 = (x) => x - 1;
const ALWAYS = (x) => () => x;
const delay = (n, s) => s.slidingWindow(n + 1, 2).map(([i, _]) => i);
function galvo({ advance = NEVER, recede = NEVER, index = ZERO } = {}, collection) {
const length = collection.length;
const nextT = advance.map(() => ADD1);
const previousT = recede.map(() => SUBTRACT1);
const indexT = index.map(ALWAYS);
const transformations = K.merge([
nextT,
previousT,
indexT
]);
const currentIndex =
transformations
.scan((i, transform) => transform(i), 0)
.map((i) => (i + length) % length);
const current = currentIndex.map((i) => collection[i]);
const previousIndex = delay(1, currentIndex);
const previous = delay(1, current);
return {
current,
currentIndex,
previous,
previousIndex
}
}
module.exports = galvo;
| Change slides variable to collection | Change slides variable to collection
| JavaScript | mit | standard-library/galvo | ---
+++
@@ -9,8 +9,8 @@
const delay = (n, s) => s.slidingWindow(n + 1, 2).map(([i, _]) => i);
-function galvo({ advance = NEVER, recede = NEVER, index = ZERO } = {}, slides) {
- const length = slides.length;
+function galvo({ advance = NEVER, recede = NEVER, index = ZERO } = {}, collection) {
+ const length = collection.length;
const nextT = advance.map(() => ADD1);
const previousT = recede.map(() => SUBTRACT1);
@@ -26,7 +26,7 @@
.scan((i, transform) => transform(i), 0)
.map((i) => (i + length) % length);
- const current = currentIndex.map((i) => slides[i]);
+ const current = currentIndex.map((i) => collection[i]);
const previousIndex = delay(1, currentIndex);
const previous = delay(1, current); |
266931cf123010a232981421b96c6d7381f9fe57 | index.js | index.js | 'use strict';
var ejs = require('ejs');
var fs = require('fs');
exports.name = 'ejs';
exports.outputFormat = 'xml';
exports.compile = ejs.compile;
exports.compileClient = function (source, options) {
options = options || {};
options.client = true;
return exports.compile(source, options).toString();
};
exports.compileFile = function (path, options) {
options = options || {};
options.filename = options.filename || path;
return exports.compile(fs.readFileSync(path, 'utf8'), options);
};
| 'use strict';
var ejs = require('ejs');
var fs = require('fs');
exports.name = 'ejs';
exports.outputFormat = 'html';
exports.compile = ejs.compile;
exports.compileClient = function (source, options) {
options = options || {};
options.client = true;
return exports.compile(source, options).toString();
};
exports.compileFile = function (path, options) {
options = options || {};
options.filename = options.filename || path;
return exports.compile(fs.readFileSync(path, 'utf8'), options);
};
| Use `'html'` as output format | Use `'html'` as output format
Per jstransformers/jstransformer#3.
| JavaScript | mit | jstransformers/jstransformer-ejs,jstransformers/jstransformer-ejs | ---
+++
@@ -4,7 +4,7 @@
var fs = require('fs');
exports.name = 'ejs';
-exports.outputFormat = 'xml';
+exports.outputFormat = 'html';
exports.compile = ejs.compile;
exports.compileClient = function (source, options) {
options = options || {}; |
aba731a6b68d09a065e2b97c4eff2d51a86195e1 | index.js | index.js | const express = require('express');
const helmet = require('helmet');
const winston = require('winston');
const bodyParser = require('body-parser');
const env = require('./src/env');
var server = express();
var router = require('./src/router');
var PORT = env.PORT || 8000;
server.use(bodyParser.urlencoded({ extended: false }));
server.use(helmet());
server.use('/', router);
function _get() {
return server;
}
function run(fn) {
fn = fn || function _defaultStart() {
winston.info('Listening at ' + PORT);
};
return server.listen(PORT, fn);
}
if (require.main === module) {
run();
}
module.exports = {
_get: _get,
run: run
};
| const express = require('express');
const helmet = require('helmet');
const winston = require('winston');
const bodyParser = require('body-parser');
const env = require('./src/env');
var server = express();
var router = require('./src/router');
var PORT = env.PORT || 8000;
server.use(bodyParser.json());
server.use(helmet());
server.use('/', router);
function _get() {
return server;
}
function run(fn) {
fn = fn || function _defaultStart() {
winston.info('Listening at ' + PORT);
};
return server.listen(PORT, fn);
}
if (require.main === module) {
run();
}
module.exports = {
_get: _get,
run: run
};
| Switch to use JSON payload parser | fix: Switch to use JSON payload parser
| JavaScript | mit | NSAppsTeam/nickel-bot | ---
+++
@@ -8,7 +8,7 @@
var router = require('./src/router');
var PORT = env.PORT || 8000;
-server.use(bodyParser.urlencoded({ extended: false }));
+server.use(bodyParser.json());
server.use(helmet());
server.use('/', router);
|
4dec8ace74bc153a67cd32b1e5be026bfbf852be | index.js | index.js | /**
* A lightweight promise-based Reddit API wrapper.
* @module reddit-api
*/
exports = module.exports = Reddit;
function Reddit() {
this.baseApiUrl = 'http://www.reddit.com';
return this;
};
/**
* Logs in a Reddit user.
*
* @param {string} username
* @param {string} password
*/
Reddit.prototype.login = function(username, password) {
};
/**
* Logs out a Reddit user.
*/
Reddit.prototype.logout = function() {
};
/**
* Retrieves the comments associated with a URL.
*
* @param {string} url
*/
Reddit.prototype.getComments = function(url) {
};
/**
* Posts a comment on a Reddit "thing".
*
* @param {string} parentId - The
* {@link http://www.reddit.com/dev/api#fullnames fullname} of a parent
* "thing".
* @param {string} text - The comment body.
* @link http://www.reddit.com/dev/api#POST_api_comment
*/
Reddit.prototype.comment = function(parentId, text) {
};
| /**
* A lightweight promise-based Reddit API wrapper.
* @module reddit-api
*/
exports = module.exports = Reddit;
function Reddit() {
this._baseApiUrl = 'http://www.reddit.com';
return this;
};
/**
* Logs in a Reddit user.
*
* @param {string} username
* @param {string} password
*/
Reddit.prototype.login = function(username, password) {
};
/**
* Logs out a Reddit user.
*/
Reddit.prototype.logout = function() {
};
/**
* Retrieves the comments associated with a URL.
*
* @param {string} url
*/
Reddit.prototype.getComments = function(url) {
};
/**
* Posts a comment on a Reddit "thing".
*
* @param {string} parentId - The
* {@link http://www.reddit.com/dev/api#fullnames fullname} of a parent
* "thing".
* @param {string} text - The comment body.
* @link http://www.reddit.com/dev/api#POST_api_comment
*/
Reddit.prototype.comment = function(parentId, text) {
};
| Use underscore for private properties | Use underscore for private properties
| JavaScript | mit | imiric/reddit-api | ---
+++
@@ -7,7 +7,7 @@
exports = module.exports = Reddit;
function Reddit() {
- this.baseApiUrl = 'http://www.reddit.com';
+ this._baseApiUrl = 'http://www.reddit.com';
return this;
};
|
5a58033f8cc97ac0d07b220ac73c8ae76a34d5c3 | index.js | index.js | /*!
* Mongoose findOrCreate Plugin
* Copyright(c) 2012 Nicholas Penree <nick@penree.com>
* MIT Licensed
*/
function findOrCreatePlugin(schema, options) {
schema.statics.findOrCreate = function findOrCreate(conditions, doc, options, callback) {
if (arguments.length < 4) {
if (typeof options === 'function') {
// Scenario: findOrCreate(conditions, doc, callback)
callback = options;
options = {};
} else if (typeof doc === 'function') {
// Scenario: findOrCreate(conditions, callback);
callback = doc;
doc = {};
options = {};
}
}
var self = this;
this.findOne(conditions, function(err, result) {
if(err || result) {
if(options && options.upsert && !err) {
self.update(conditions, doc, function(err, count){
self.findOne(conditions, function(err, result) {
callback(err, result, false);
});
})
} else {
callback(err, result, false)
}
} else {
for (var key in conditions) {
doc[key] = conditions[key];
}
var obj = new self(conditions)
obj.save(function(err) {
callback(err, obj, true);
});
}
})
}
}
/**
* Expose `findOrCreatePlugin`.
*/
module.exports = findOrCreatePlugin; | /*!
* Mongoose findOrCreate Plugin
* Copyright(c) 2012 Nicholas Penree <nick@penree.com>
* MIT Licensed
*/
function findOrCreatePlugin(schema, options) {
schema.statics.findOrCreate = function findOrCreate(conditions, doc, options, callback) {
if (arguments.length < 4) {
if (typeof options === 'function') {
// Scenario: findOrCreate(conditions, doc, callback)
callback = options;
options = {};
} else if (typeof doc === 'function') {
// Scenario: findOrCreate(conditions, callback);
callback = doc;
doc = {};
options = {};
}
}
var self = this;
this.findOne(conditions, function(err, result) {
if(err || result) {
if(options && options.upsert && !err) {
self.update(conditions, doc, function(err, count){
self.findOne(conditions, function(err, result) {
callback(err, result, false);
});
})
} else {
callback(err, result, false)
}
} else {
for (var key in conditions) {
doc[key] = conditions[key];
}
var obj = new self(doc)
obj.save(function(err) {
callback(err, obj, true);
});
}
})
}
}
/**
* Expose `findOrCreatePlugin`.
*/
module.exports = findOrCreatePlugin; | Use doc instead of conditions | Use doc instead of conditions | JavaScript | mit | yura415/mongoose-findorcreate | ---
+++
@@ -34,7 +34,7 @@
for (var key in conditions) {
doc[key] = conditions[key];
}
- var obj = new self(conditions)
+ var obj = new self(doc)
obj.save(function(err) {
callback(err, obj, true);
}); |
3bc450b26c681b10efc3144e1e83cd97f703aa3b | app/models/users.js | app/models/users.js | 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
name: String,
username: String,
password: String,
date: Date
});
module.exports = mongoose.model('User', User);
| 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
name: String,
username: String,
password: String,
date: Date,
friends: Array
});
module.exports = mongoose.model('User', User);
| Add friends column to store info | Add friends column to store info
| JavaScript | mit | mirabalj/graphriend,mirabalj/graphriend | ---
+++
@@ -7,7 +7,8 @@
name: String,
username: String,
password: String,
- date: Date
+ date: Date,
+ friends: Array
});
module.exports = mongoose.model('User', User); |
bb95b8a1375f5bd395e6cb9d3db40b7b427d12b7 | production/defaults/collective.js | production/defaults/collective.js | var CELOS_USER = "celos";
var CELOS_DEFAULT_OOZIE = "http://oozie002.ny7.collective-media.net:11000/oozie";
var CELOS_DEFAULT_HDFS = "hdfs://nameservice1";
var NAME_NODE = CELOS_DEFAULT_HDFS;
var JOB_TRACKER = "admin1.ny7.collective-media.net:8032";
var HIVE_METASTORE = "thrift://hive002.ny7.collective-media.net:9083";
var OUTPUT_ROOT = NAME_NODE + "/output";
var CELOS_DEFAULT_OOZIE_PROPERTIES = {
"user.name": CELOS_USER,
"jobTracker" : JOB_TRACKER,
"nameNode" : CELOS_DEFAULT_HDFS,
"hiveMetastore": HIVE_METASTORE,
"hiveDefaults": NAME_NODE + "/deploy/TheOneWorkflow/hive/hive-site.xml",
"oozie.use.system.libpath": "true",
"outputRoot": OUTPUT_ROOT
};
| var CELOS_USER = "celos";
var CELOS_DEFAULT_OOZIE = "http://oozie002.ny7.collective-media.net:11000/oozie";
var CELOS_DEFAULT_HDFS = "hdfs://nameservice1";
var NAME_NODE = CELOS_DEFAULT_HDFS;
var JOB_TRACKER = "admin1.ny7.collective-media.net:8032";
var HIVE_METASTORE = "thrift://hive002.ny7.collective-media.net:9083";
var ETL002 = "etl002.ny7.collective-media.net";
var OUTPUT_ROOT = NAME_NODE + "/output";
var CELOS_DEFAULT_OOZIE_PROPERTIES = {
"user.name": CELOS_USER,
"jobTracker" : JOB_TRACKER,
"nameNode" : CELOS_DEFAULT_HDFS,
"hiveMetastore": HIVE_METASTORE,
"hiveDefaults": NAME_NODE + "/deploy/TheOneWorkflow/hive/hive-site.xml",
"oozie.use.system.libpath": "true",
"outputRoot": OUTPUT_ROOT,
"etl002": ETL002
};
| Add etl002 FQDN to Celos Oozie default properties. | Add etl002 FQDN to Celos Oozie default properties.
| JavaScript | apache-2.0 | collectivemedia/celos,collectivemedia/celos,collectivemedia/celos | ---
+++
@@ -10,6 +10,8 @@
var HIVE_METASTORE = "thrift://hive002.ny7.collective-media.net:9083";
+var ETL002 = "etl002.ny7.collective-media.net";
+
var OUTPUT_ROOT = NAME_NODE + "/output";
var CELOS_DEFAULT_OOZIE_PROPERTIES = {
@@ -19,5 +21,6 @@
"hiveMetastore": HIVE_METASTORE,
"hiveDefaults": NAME_NODE + "/deploy/TheOneWorkflow/hive/hive-site.xml",
"oozie.use.system.libpath": "true",
- "outputRoot": OUTPUT_ROOT
+ "outputRoot": OUTPUT_ROOT,
+ "etl002": ETL002
}; |
f086077dd8eee8503192c13f646e9d63231e0174 | app/routes/index.js | app/routes/index.js | import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import Analytics from 'ember-osf/mixins/analytics';
/**
* @module ember-preprints
* @submodule routes
*/
/**
* Loads all disciplines and preprint providers to the index page
* @class Index Route Handler
*/
export default Ember.Route.extend(Analytics, ResetScrollMixin, {
// store: Ember.inject.service(),
theme: Ember.inject.service(),
model() {
return Ember.RSVP.hash({
taxonomies: this.get('theme.provider')
.then(provider => provider
.query('taxonomies', {
filter: {
parents: 'null'
},
page: {
size: 20
}
})
),
brandedProviders: this
.store
.findAll('preprint-provider', { reload: true })
.then(result => result
.filter(item => item.id !== 'osf')
)
});
},
actions: {
search(q) {
let route = 'discover';
if (this.get('theme.isSubRoute'))
route = `provider.${route}`;
this.transitionTo(route, { queryParams: { q: q } });
}
}
});
| import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import Analytics from 'ember-osf/mixins/analytics';
/**
* @module ember-preprints
* @submodule routes
*/
/**
* Loads all disciplines and preprint providers to the index page
* @class Index Route Handler
*/
export default Ember.Route.extend(Analytics, ResetScrollMixin, {
// store: Ember.inject.service(),
theme: Ember.inject.service(),
model() {
return Ember.RSVP.hash({
taxonomies: this.get('theme.provider')
.then(provider => provider
.query('highlightedTaxonomies', {
page: {
size: 20
}
})
),
brandedProviders: this
.store
.findAll('preprint-provider', { reload: true })
.then(result => result
.filter(item => item.id !== 'osf')
)
});
},
actions: {
search(q) {
let route = 'discover';
if (this.get('theme.isSubRoute'))
route = `provider.${route}`;
this.transitionTo(route, { queryParams: { q: q } });
}
}
});
| Use highlighted taxonomies instead of top level taxonomies | Use highlighted taxonomies instead of top level taxonomies
| JavaScript | apache-2.0 | laurenrevere/ember-preprints,baylee-d/ember-preprints,baylee-d/ember-preprints,laurenrevere/ember-preprints,CenterForOpenScience/ember-preprints,CenterForOpenScience/ember-preprints | ---
+++
@@ -19,10 +19,7 @@
return Ember.RSVP.hash({
taxonomies: this.get('theme.provider')
.then(provider => provider
- .query('taxonomies', {
- filter: {
- parents: 'null'
- },
+ .query('highlightedTaxonomies', {
page: {
size: 20
} |
08b84474bedcc17f810289364b91011ebd6219ec | public/javascripts/application.js | public/javascripts/application.js | $(document).ready(function() {
$('.add_child').click(function() {
var assoc = $(this).attr('data-association');
var content = $('#' + assoc + '_fields_template').html();
var regexp = new RegExp('new_' + assoc, 'g')
var new_id = new Date().getTime();
$(this).parent().before(content.replace(regexp, new_id));
});
$('.remove_child').live('click', function() {
var hidden_field = $(this).prev('input[type=hidden]')[0];
if(hidden_field) {
hidden_field.value = '1';
}
$(this).parents('.fields').hide();
return false;
});
}); | $(document).ready(function() {
$('.add_child').click(function() {
var assoc = $(this).attr('data-association');
var content = $('#' + assoc + '_fields_template').html();
var regexp = new RegExp('new_' + assoc, 'g')
var new_id = new Date().getTime();
$(this).parent().before(content.replace(regexp, new_id));
return false;
});
$('.remove_child').live('click', function() {
var hidden_field = $(this).prev('input[type=hidden]')[0];
if(hidden_field) {
hidden_field.value = '1';
}
$(this).parents('.fields').hide();
return false;
});
}); | Add a missing return false at the end of a jquery event | Add a missing return false at the end of a jquery event
| JavaScript | mit | timriley/complex-form-examples,timriley/complex-form-examples | ---
+++
@@ -6,6 +6,7 @@
var new_id = new Date().getTime();
$(this).parent().before(content.replace(regexp, new_id));
+ return false;
});
$('.remove_child').live('click', function() { |
c333a80c898397ff2905a67cf2b28b1833157841 | public/modules/common/readMode.js | public/modules/common/readMode.js | 'use strict';
angular.module('theLawFactory')
.directive('readMode', ['$location', function($location) {
return {
restrict: 'A',
controller: function($scope) {
$scope.read = $location.search()['read'] === '1';
$scope.readmode = function () {
$("#sidebar").addClass('readmode');
if ($scope.mod === 'amendements') {
$location.replace();
$location.search('read', '1');
}
$scope.read = true;
};
$scope.viewmode = function () {
$("#sidebar").removeClass('readmode');
if ($scope.mod === 'amendements') {
$location.replace();
$location.search('read', null);
}
$scope.read = false;
};
if ($scope.read) {
$scope.readmode();
}
}
}
}]);
| 'use strict';
angular.module('theLawFactory')
.directive('readMode', ['$location', function($location) {
return {
restrict: 'A',
controller: function($rootScope, $scope) {
$rootScope.read = $location.search()['read'] === '1';
$rootScope.readmode = function () {
$("#sidebar").addClass('readmode');
if ($scope.mod === 'amendements') {
$location.replace();
$location.search('read', '1');
}
$rootScope.read = true;
};
$rootScope.viewmode = function () {
$("#sidebar").removeClass('readmode');
if ($scope.mod === 'amendements') {
$location.replace();
$location.search('read', null);
}
$rootScope.read = false;
};
if ($rootScope.read) {
$rootScope.readmode();
}
}
}
}]);
| Move readmode to root scope | Move readmode to root scope
Prevents incorrect angular scope inheritance behaviour (calling $scope.readmode()
would set the "read" variable on the calling scope, not in the readMode controller
scope).
| JavaScript | agpl-3.0 | regardscitoyens/the-law-factory,regardscitoyens/the-law-factory,regardscitoyens/the-law-factory | ---
+++
@@ -4,29 +4,29 @@
.directive('readMode', ['$location', function($location) {
return {
restrict: 'A',
- controller: function($scope) {
- $scope.read = $location.search()['read'] === '1';
+ controller: function($rootScope, $scope) {
+ $rootScope.read = $location.search()['read'] === '1';
- $scope.readmode = function () {
+ $rootScope.readmode = function () {
$("#sidebar").addClass('readmode');
if ($scope.mod === 'amendements') {
$location.replace();
$location.search('read', '1');
}
- $scope.read = true;
+ $rootScope.read = true;
};
- $scope.viewmode = function () {
+ $rootScope.viewmode = function () {
$("#sidebar").removeClass('readmode');
if ($scope.mod === 'amendements') {
$location.replace();
$location.search('read', null);
}
- $scope.read = false;
+ $rootScope.read = false;
};
- if ($scope.read) {
- $scope.readmode();
+ if ($rootScope.read) {
+ $rootScope.readmode();
}
}
} |
0716c83e8ec9bbd3b7359d962c95ecb1b43e00e4 | application/src/main/resources/assets/js/app/controller.js | application/src/main/resources/assets/js/app/controller.js | define([
'backbone',
'marionette'
], function(Backbone, Marionette) {
var Controller = Marionette.Controller.extend({
initialize: function(options) {
this.app = options.app;
this.addressBar = new Backbone.Router();
},
navigateHome: function() {
this.addressBar.navigate('/');
console.log('controller: navigateHome');
},
navigateAbout: function() {
this.addressBar.navigate('/about');
console.log('controller: navigateAbout');
}
});
return Controller;
});
| define([
'backbone',
'marionette'
], function(Backbone, Marionette) {
var Controller = Marionette.Controller.extend({
initialize: function(options) {
this.app = options.app;
},
navigateHome: function() {
Backbone.history.navigate('/');
console.log('controller: navigateHome');
},
navigateAbout: function() {
Backbone.history.navigate('/about');
console.log('controller: navigateAbout');
}
});
return Controller;
});
| Call Backbone.history directly (instead of through a dummy router) | Call Backbone.history directly (instead of through a dummy router)
| JavaScript | apache-2.0 | tumbarumba/dropwizard-marionette,tumbarumba/dropwizard-marionette,tumbarumba/dropwizard-marionette | ---
+++
@@ -5,16 +5,15 @@
var Controller = Marionette.Controller.extend({
initialize: function(options) {
this.app = options.app;
- this.addressBar = new Backbone.Router();
},
navigateHome: function() {
- this.addressBar.navigate('/');
+ Backbone.history.navigate('/');
console.log('controller: navigateHome');
},
navigateAbout: function() {
- this.addressBar.navigate('/about');
+ Backbone.history.navigate('/about');
console.log('controller: navigateAbout');
}
}); |
5a66d394be7c4ac22693fa4fce38da2c40c64d53 | index.js | index.js | /* ==================================
Express server - main server side file
===================================== */
var path = require('path');
var fs = require('fs');
var http = require('http');
var express = require('express');
var app = express();
// block access to src folder
app.get('/js/src/*', function(req, res) {
res.status(404);
res.end();
});
// Serve the ./static/ folder to the public
app.use(express.static('static'));
app.use('/stream', express.static('stream')); // need to optimize this
// Route all requests to static/index.html
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'static/index.html'));
});
// Start the server
var server = http.createServer(app);
server.listen(8080);
// Socekt io
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('control-start', function(data) {
io.emit('start', data);
});
socket.on('control-pause', function(data) {
io.emit('pause');
});
socket.on('report', function(data) {
io.emit('report', data);
});
});
| /* ==================================
Express server - main server side file
===================================== */
var path = require('path');
var fs = require('fs');
var http = require('http');
var express = require('express');
var app = express();
// block access to src folder
app.get('/js/src/*', function(req, res) {
res.status(404);
res.end();
});
// Serve the ./static/ folder to the public
app.use(express.static('static'));
app.use('/stream', express.static('stream')); // need to optimize this
// Route all requests to static/index.html
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'static/index.html'));
});
// Start the server
var server = http.createServer(app);
server.listen(process.env.PORT || 8080);
// Socekt io
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('control-start', function(data) {
io.emit('start', data);
});
socket.on('control-pause', function(data) {
io.emit('pause');
});
socket.on('report', function(data) {
io.emit('report', data);
});
});
| Allow port to be defined by env | Allow port to be defined by env
| JavaScript | apache-2.0 | arthuralee/nito,arthuralee/nito | ---
+++
@@ -28,7 +28,7 @@
// Start the server
var server = http.createServer(app);
-server.listen(8080);
+server.listen(process.env.PORT || 8080);
// Socekt io
var io = require('socket.io')(server); |
a096b4d565db8d713c1bdb78ad3bc881f5817b10 | gulp/tasks/webpack.js | gulp/tasks/webpack.js | import gulp from 'gulp';
import gulpWebpack from 'webpack-stream';
import webpack from 'webpack';
import config from '../config';
let app = './src/main.js';
gulp.task('webpack', () => {
return gulp.src(app)
.pipe(gulpWebpack({
output: {
filename: config.mainFile + '.js'
},
devtool: 'inline-source-map',
plugins: [
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.DedupePlugin()
],
module: {
loaders: [
{
loaders: ['ng-annotate', 'babel-loader']
}
]
}
}, webpack, () => 'done'))
.pipe(gulp.dest(config.destFolder));
});
gulp.task('webpack-build', () => {
return gulp.src(app)
.pipe(gulpWebpack({
output: {
filename: config.mainFile + '.js'
},
plugins: [
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: {
except: ['goog', 'gapi', 'angular']
}
})
],
module: {
loaders: [
{
loaders: ['ng-annotate', 'babel-loader']
}
]
}
}, webpack, () => 'done'))
.pipe(gulp.dest(config.destFolder));
});
| import gulp from 'gulp';
import gulpWebpack from 'webpack-stream';
import webpack from 'webpack';
import config from '../config';
let app = './src/main.js';
gulp.task('webpack', () => {
return gulp.src(app)
.pipe(gulpWebpack({
output: {
filename: config.mainFile + '.js'
},
devtool: 'inline-source-map',
plugins: [
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.DedupePlugin()
],
module: {
loaders: [
{
loaders: ['babel-loader']
}
]
}
}, webpack, () => 'done'))
.pipe(gulp.dest(config.destFolder));
});
gulp.task('webpack-build', () => {
return gulp.src(app)
.pipe(gulpWebpack({
output: {
filename: config.mainFile + '.js'
},
plugins: [
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: {
except: ['goog', 'gapi', 'angular']
}
})
],
module: {
loaders: [
{
loaders: ['ng-annotate', 'babel-loader']
}
]
}
}, webpack, () => 'done'))
.pipe(gulp.dest(config.destFolder));
});
| Remove annotate from default task | Remove annotate from default task
| JavaScript | mit | marcosmoura/angular-material-steppers,marcosmoura/angular-material-steppers | ---
+++
@@ -19,7 +19,7 @@
module: {
loaders: [
{
- loaders: ['ng-annotate', 'babel-loader']
+ loaders: ['babel-loader']
}
]
} |
88ad1c1a133236e609d6fad45c80d637a2ad9a55 | test/harvest-client-tests.js | test/harvest-client-tests.js | var assert = require('assert'),
config = require('config'),
Harvest = require('../index');
describe('The Harvest API Client', function() {
describe('Instantiating a Harvest instance', function() {
it('should be able to work with HTTP basic authentication', function() {
// TODO
});
it('should be able to work with OAuth 2.0', function() {
// TODO
});
});
}); | var assert = require('assert'),
config = require('config'),
Harvest = require('../index');
describe('The Harvest API Client', function() {
describe('Instantiating a Harvest instance', function() {
it('should be able to work with HTTP basic authentication', function() {
var harvest = new Harvest({
subdomain: config.harvest.subdomain,
email: config.harvest.email,
password: config.harvest.password
});
assert(typeof harvest === "object");
});
it('should be able to work with OAuth 2.0', function() {
var harvest = new Harvest({
subdomain: config.harvest.subdomain,
identifier: config.harvest.identifier,
secret: config.harvest.secret
});
assert(typeof harvest === "object");
});
});
}); | Test for instantiation of harvest client with login or api credentials | Test for instantiation of harvest client with login or api credentials
| JavaScript | mit | peterbraden/node-harvest,log0ymxm/node-harvest,Pezmc/node-harvest-2,clearhead/node-harvest | ---
+++
@@ -5,10 +5,20 @@
describe('The Harvest API Client', function() {
describe('Instantiating a Harvest instance', function() {
it('should be able to work with HTTP basic authentication', function() {
- // TODO
+ var harvest = new Harvest({
+ subdomain: config.harvest.subdomain,
+ email: config.harvest.email,
+ password: config.harvest.password
+ });
+ assert(typeof harvest === "object");
});
it('should be able to work with OAuth 2.0', function() {
- // TODO
+ var harvest = new Harvest({
+ subdomain: config.harvest.subdomain,
+ identifier: config.harvest.identifier,
+ secret: config.harvest.secret
+ });
+ assert(typeof harvest === "object");
});
});
}); |
03f6c68e7e66fe8bdba9164702e5102c0793e186 | index.js | index.js | "use strict"
var http = require('http')
var shoe = require('shoe');
var app = http.createServer()
module.exports = function(options, cb) {
if (typeof options === 'function') cb = options, options = undefined
options = options || {}
if (!options.file || typeof options.file !== 'string') return cb(new Error('file path required'))
var sf = require('slice-file');
var words = sf(options.file);
var sock = shoe(function(stream) {
words.follow(0).pipe(stream)
})
sock.install(app, '/logs');
return app
}
| "use strict"
var http = require('http')
var shoe = require('shoe');
var app = http.createServer()
module.exports = function(options, cb) {
if (typeof options === 'function') cb = options, options = undefined
if(typeof cb !== 'function') { cb = function(err) { if(err) { throw err; }}}
options = options || {}
if (!options.file || typeof options.file !== 'string') return cb(new Error('file path required'))
var sf = require('slice-file');
var words = sf(options.file);
var sock = shoe(function(stream) {
words.follow(0).pipe(stream)
})
sock.install(app, '/logs');
return app
}
| Make default callback throw error | Make default callback throw error
| JavaScript | mit | ninjablocks/ninja-tail-stream | ---
+++
@@ -7,6 +7,7 @@
module.exports = function(options, cb) {
if (typeof options === 'function') cb = options, options = undefined
+ if(typeof cb !== 'function') { cb = function(err) { if(err) { throw err; }}}
options = options || {}
if (!options.file || typeof options.file !== 'string') return cb(new Error('file path required'))
|
0ae4e58f86bad13975fd816b9260e78c187aea05 | index.js | index.js | #!/usr/bin/env node
const fs = require('fs');
const components = process.argv.slice(2);
const componentDefaultContent = componentName => `
import React, {
Component,
PropTypes,
} from 'react';
class ${componentName} extends Component {
render() {
return (
<div></div>
);
}
}
export default ${componentName};
`;
const indexDefaultContent = componentName => `
import ${componentName} from './${componentName}';
export default ${componentName};
`;
const createFile = (fileName, contents) => fs.writeFile(fileName, contents, err => {
if (err) {
return console.log(err);
}
});
components.forEach(component => {
const componentName = component.charAt(0).toUpperCase() + component.slice(1);
const folderPrefix = `${component}/`;
fs.existsSync(componentName) || fs.mkdirSync(componentName);
createFile(`${folderPrefix + componentName}.js`, componentDefaultContent(componentName));
createFile(`${folderPrefix + componentName}.scss`, '');
createFile(`${folderPrefix}index.js`, indexDefaultContent(componentName));
console.log('Successfully created '+componentName+' component!');
});
| const fs = require('fs');
const components = process.argv.slice(2);
const componentDefaultContent = componentName =>
`import React, {
Component,
PropTypes,
} from 'react';
class ${componentName} extends Component {
render() {
return (
<div></div>
);
}
}
export default ${componentName};
`;
const indexDefaultContent = componentName =>
`import ${componentName} from './${componentName}';
export default ${componentName};
`;
const createFile = (fileName, contents) => fs.writeFile(fileName, contents, err => {
if (err) {
return console.log(err);
}
});
components.forEach(component => {
const componentName = component.charAt(0).toUpperCase() + component.slice(1);
const folderPrefix = `${component}/`;
fs.existsSync(componentName) || fs.mkdirSync(componentName);
createFile(`${folderPrefix + componentName}.js`, componentDefaultContent(componentName));
createFile(`${folderPrefix + componentName}.scss`, '');
createFile(`${folderPrefix}index.js`, indexDefaultContent(componentName));
console.log('Successfully created '+componentName+' component!');
});
| Update script to remove empty line | Update script to remove empty line
| JavaScript | mit | Lukavyi/generate-reactjs-component-folder-css-modules | ---
+++
@@ -1,10 +1,8 @@
-#!/usr/bin/env node
-
const fs = require('fs');
const components = process.argv.slice(2);
-const componentDefaultContent = componentName => `
-import React, {
+const componentDefaultContent = componentName =>
+`import React, {
Component,
PropTypes,
} from 'react';
@@ -20,8 +18,8 @@
export default ${componentName};
`;
-const indexDefaultContent = componentName => `
-import ${componentName} from './${componentName}';
+const indexDefaultContent = componentName =>
+`import ${componentName} from './${componentName}';
export default ${componentName};
@@ -35,13 +33,13 @@
components.forEach(component => {
const componentName = component.charAt(0).toUpperCase() + component.slice(1);
- const folderPrefix = `${component}/`;
+const folderPrefix = `${component}/`;
- fs.existsSync(componentName) || fs.mkdirSync(componentName);
+fs.existsSync(componentName) || fs.mkdirSync(componentName);
- createFile(`${folderPrefix + componentName}.js`, componentDefaultContent(componentName));
- createFile(`${folderPrefix + componentName}.scss`, '');
- createFile(`${folderPrefix}index.js`, indexDefaultContent(componentName));
+createFile(`${folderPrefix + componentName}.js`, componentDefaultContent(componentName));
+createFile(`${folderPrefix + componentName}.scss`, '');
+createFile(`${folderPrefix}index.js`, indexDefaultContent(componentName));
- console.log('Successfully created '+componentName+' component!');
+console.log('Successfully created '+componentName+' component!');
}); |
d97b5e5392e118bca6a30d1eaa3601af5fa9ec32 | index.js | index.js | 'use strict';
var parse = require('coffee-script').compile;
exports.extension = 'coffee';
exports.compile = function (src, options) {
var opts = { bare: true }, code, data, map;
if (!options.sourceMap) return { code: parse(src, opts) };
opts.sourceMap = true;
data = parse(src, opts);
// Include original coffee file in the map.
map = JSON.parse(data.v3SourceMap);
map.sourcesContent = [src];
map = JSON.stringify(map);
code = data.js;
if (code[code.length - 1] !== '\n') code += '\n';
code += '//@ sourceMappingURL=data:application/json;base64,' +
new Buffer(map).toString('base64') + '\n';
return { code: code };
};
| 'use strict';
var parse = require('coffee-script').compile;
exports.extension = 'coffee';
exports.compile = function (src, options) {
var opts = { bare: true }, code, data, map;
if (!options.sourceMap) return { code: parse(src, opts) };
opts.sourceMap = true;
data = parse(src, opts);
// Include original coffee file in the map.
map = JSON.parse(data.v3SourceMap);
map.sourcesContent = [src];
map = JSON.stringify(map);
code = data.js;
if (code[code.length - 1] !== '\n') code += '\n';
code += '//# sourceMappingURL=data:application/json;base64,' +
new Buffer(map).toString('base64') + '\n';
return { code: code };
};
| Update sourceMappingURL syntax to latest change | Update sourceMappingURL syntax to latest change
| JavaScript | mit | medikoo/webmake-coffee | ---
+++
@@ -16,7 +16,7 @@
code = data.js;
if (code[code.length - 1] !== '\n') code += '\n';
- code += '//@ sourceMappingURL=data:application/json;base64,' +
+ code += '//# sourceMappingURL=data:application/json;base64,' +
new Buffer(map).toString('base64') + '\n';
return { code: code };
}; |
e6f9b7b2eb9e7e651aa0a7ea37b4543d64d3d3bc | app/scripts/main.js | app/scripts/main.js | $(function () {
$('#sidebar').affix({
offset: {
//top: $('.navbar-fixed-top').height()
//top: $('.navbar-fixed-top').offset().top
top: $('main').offset().top + 10
}
});
});
| $(function () {
$('#sidebar').affix({
offset: {
top: $('main').offset().top + 10
}
});
});
| Fix ESLint Errors and Warnings | Fix ESLint Errors and Warnings
| JavaScript | mit | Ecotrust/Measuring-Our-Impact-Wireframes,Ecotrust/Measuring-Our-Impact-Wireframes | ---
+++
@@ -1,11 +1,7 @@
$(function () {
- $('#sidebar').affix({
- offset: {
- //top: $('.navbar-fixed-top').height()
- //top: $('.navbar-fixed-top').offset().top
- top: $('main').offset().top + 10
- }
- });
+ $('#sidebar').affix({
+ offset: {
+ top: $('main').offset().top + 10
+ }
+ });
});
-
- |
0c665c9998bf7d7619184d073cdf832b30a1d8af | test/special/subLanguages.js | test/special/subLanguages.js | 'use strict';
var fs = require('fs');
var utility = require('../utility');
describe('sub-languages', function() {
before(function() {
this.block = document.querySelector('#sublanguages');
});
it('should highlight XML with PHP and JavaScript', function() {
var filename = utility.buildPath('expect', 'sublanguages.txt'),
expected = fs.readFileSync(filename, 'utf-8'),
actual = this.block.innerHTML;
actual.should.equal(expected);
});
});
| 'use strict';
var fs = require('fs');
var utility = require('../utility');
describe('sub-languages', function() {
before(function() {
this.block = document.querySelector('#sublanguages');
});
it('should highlight XML with PHP and JavaScript', function(done) {
var filename = utility.buildPath('expect', 'sublanguages.txt'),
actual = this.block.innerHTML;
fs.readFile(filename, 'utf-8',
utility.handleExpectedFile(actual, done));
});
});
| Change sub languages to asynchronous testing | Change sub languages to asynchronous testing
| JavaScript | bsd-3-clause | SibuStephen/highlight.js,isagalaev/highlight.js,0x7fffffff/highlight.js,yxxme/highlight.js,tenbits/highlight.js,aurusov/highlight.js,tenbits/highlight.js,jean/highlight.js,STRML/highlight.js,snegovick/highlight.js,snegovick/highlight.js,MakeNowJust/highlight.js,tenbits/highlight.js,weiyibin/highlight.js,martijnrusschen/highlight.js,Sannis/highlight.js,SibuStephen/highlight.js,krig/highlight.js,alex-zhang/highlight.js,isagalaev/highlight.js,devmario/highlight.js,Ankirama/highlight.js,alex-zhang/highlight.js,ysbaddaden/highlight.js,brennced/highlight.js,christoffer/highlight.js,teambition/highlight.js,robconery/highlight.js,christoffer/highlight.js,ysbaddaden/highlight.js,zachaysan/highlight.js,SibuStephen/highlight.js,sourrust/highlight.js,aristidesstaffieri/highlight.js,dublebuble/highlight.js,abhishekgahlot/highlight.js,CausalityLtd/highlight.js,1st1/highlight.js,palmin/highlight.js,daimor/highlight.js,kba/highlight.js,bluepichu/highlight.js,Delermando/highlight.js,VoldemarLeGrand/highlight.js,robconery/highlight.js,palmin/highlight.js,yxxme/highlight.js,liang42hao/highlight.js,Amrit01/highlight.js,kevinrodbe/highlight.js,ehornbostel/highlight.js,zachaysan/highlight.js,ponylang/highlight.js,Amrit01/highlight.js,CausalityLtd/highlight.js,Ajunboys/highlight.js,liang42hao/highlight.js,highlightjs/highlight.js,Ajunboys/highlight.js,jean/highlight.js,0x7fffffff/highlight.js,kba/highlight.js,teambition/highlight.js,Sannis/highlight.js,aurusov/highlight.js,ilovezy/highlight.js,lizhil/highlight.js,dublebuble/highlight.js,axter/highlight.js,J2TeaM/highlight.js,VoldemarLeGrand/highlight.js,martijnrusschen/highlight.js,alex-zhang/highlight.js,lizhil/highlight.js,delebash/highlight.js,taoger/highlight.js,kevinrodbe/highlight.js,adam-lynch/highlight.js,kayyyy/highlight.js,xing-zhi/highlight.js,carlokok/highlight.js,VoldemarLeGrand/highlight.js,ehornbostel/highlight.js,ilovezy/highlight.js,adjohnson916/highlight.js,dYale/highlight.js,dx285/highlight.js,lizhil/highlight.js,sourrust/highlight.js,brennced/highlight.js,adjohnson916/highlight.js,bluepichu/highlight.js,abhishekgahlot/highlight.js,dx285/highlight.js,StanislawSwierc/highlight.js,aurusov/highlight.js,0x7fffffff/highlight.js,delebash/highlight.js,highlightjs/highlight.js,adam-lynch/highlight.js,axter/highlight.js,kayyyy/highlight.js,J2TeaM/highlight.js,Ankirama/highlight.js,delebash/highlight.js,MakeNowJust/highlight.js,brennced/highlight.js,devmario/highlight.js,taoger/highlight.js,liang42hao/highlight.js,ysbaddaden/highlight.js,ponylang/highlight.js,adjohnson916/highlight.js,Sannis/highlight.js,kayyyy/highlight.js,snegovick/highlight.js,aristidesstaffieri/highlight.js,lead-auth/highlight.js,christoffer/highlight.js,highlightjs/highlight.js,bluepichu/highlight.js,cicorias/highlight.js,dx285/highlight.js,xing-zhi/highlight.js,robconery/highlight.js,xing-zhi/highlight.js,axter/highlight.js,dbkaplun/highlight.js,palmin/highlight.js,Delermando/highlight.js,carlokok/highlight.js,ponylang/highlight.js,yxxme/highlight.js,aristidesstaffieri/highlight.js,devmario/highlight.js,jean/highlight.js,abhishekgahlot/highlight.js,adam-lynch/highlight.js,cicorias/highlight.js,weiyibin/highlight.js,dbkaplun/highlight.js,Ajunboys/highlight.js,sourrust/highlight.js,weiyibin/highlight.js,daimor/highlight.js,teambition/highlight.js,CausalityLtd/highlight.js,dbkaplun/highlight.js,Delermando/highlight.js,kba/highlight.js,Amrit01/highlight.js,carlokok/highlight.js,MakeNowJust/highlight.js,taoger/highlight.js,1st1/highlight.js,dYale/highlight.js,kevinrodbe/highlight.js,carlokok/highlight.js,daimor/highlight.js,cicorias/highlight.js,krig/highlight.js,J2TeaM/highlight.js,StanislawSwierc/highlight.js,dYale/highlight.js,Ankirama/highlight.js,1st1/highlight.js,ilovezy/highlight.js,krig/highlight.js,martijnrusschen/highlight.js,ehornbostel/highlight.js,dublebuble/highlight.js,highlightjs/highlight.js,zachaysan/highlight.js,STRML/highlight.js,STRML/highlight.js | ---
+++
@@ -8,12 +8,11 @@
this.block = document.querySelector('#sublanguages');
});
- it('should highlight XML with PHP and JavaScript', function() {
+ it('should highlight XML with PHP and JavaScript', function(done) {
var filename = utility.buildPath('expect', 'sublanguages.txt'),
-
- expected = fs.readFileSync(filename, 'utf-8'),
actual = this.block.innerHTML;
- actual.should.equal(expected);
+ fs.readFile(filename, 'utf-8',
+ utility.handleExpectedFile(actual, done));
});
}); |
cceb968c9c98e961938595b68602466bcb75e350 | src/c/filter-dropdown.js | src/c/filter-dropdown.js | import m from 'mithril';
import dropdown from './dropdown';
const filterDropdown = {
view(ctrl, args) {
const wrapper_c = args.wrapper_class || '.w-col.w-col-3.w-col-small-6';
return m(wrapper_c, [
m(`label.fontsize-smaller[for="${args.index}"]`,
(args.custom_label ? m.component(args.custom_label[0], args.custom_label[1]) : args.label)),
m.component(dropdown, {
id: args.index,
onchange: args.onchange,
classes: '.w-select.text-field.positive',
valueProp: args.vm,
options: args.options
})
]);
}
};
export default filterDropdown;
| import m from 'mithril';
import dropdown from './dropdown';
const filterDropdown = {
view(ctrl, args) {
const wrapper_c = args.wrapper_class || '.w-col.w-col-3.w-col-small-6';
return m(wrapper_c, [
m(`label.fontsize-smaller[for="${args.index}"]`,
(args.custom_label ? m.component(args.custom_label[0], args.custom_label[1]) : args.label)),
m.component(dropdown, {
id: args.index,
onchange: _.isFunction(args.onchange) ? args.onchange : () => {},
classes: '.w-select.text-field.positive',
valueProp: args.vm,
options: args.options
})
]);
}
};
export default filterDropdown;
| Check for onchange before try executing to avoid errors | Check for onchange before try executing to avoid errors
| JavaScript | mit | sushant12/catarse.js,catarse/catarse.js,catarse/catarse_admin | ---
+++
@@ -9,7 +9,7 @@
(args.custom_label ? m.component(args.custom_label[0], args.custom_label[1]) : args.label)),
m.component(dropdown, {
id: args.index,
- onchange: args.onchange,
+ onchange: _.isFunction(args.onchange) ? args.onchange : () => {},
classes: '.w-select.text-field.positive',
valueProp: args.vm,
options: args.options |
03d408714f001c291ea9ce97c4077ffceb0a94b7 | gulp/tasks/mochify.js | gulp/tasks/mochify.js | 'use strict';
var gulp = require('gulp');
var mochify = require('mochify');
var config = require('../config').js;
gulp.task('mochify', ['jshint'], function () {
mochify( config.test, {
reporter : 'spec'
//debug: true,
//cover : true,
//consolify : 'build/runner.html'
//TODO require : 'chai' and expose expect https://github.com/gulpjs/gulp/blob/master/docs/recipes/mocha-test-runner-with-gulp.md
}).bundle();
});
| 'use strict';
var gulp = require('gulp');
var mochify = require('mochify');
var config = require('../config').js;
gulp.task('mochify', ['jshint'], function () {
mochify( config.test, {
reporter : 'spec'
//debug: true,
//cover : true,
//consolify : 'test/runner.html'
//TODO require : 'chai' and expose expect https://github.com/gulpjs/gulp/blob/master/docs/recipes/mocha-test-runner-with-gulp.md
}).bundle();
});
| Put runner.html in test directory | Put runner.html in test directory
| JavaScript | mit | aboutlo/gulp-starter-kit,aboutlo/gulp-starter-kit | ---
+++
@@ -9,7 +9,7 @@
reporter : 'spec'
//debug: true,
//cover : true,
- //consolify : 'build/runner.html'
+ //consolify : 'test/runner.html'
//TODO require : 'chai' and expose expect https://github.com/gulpjs/gulp/blob/master/docs/recipes/mocha-test-runner-with-gulp.md
}).bundle();
}); |
5d302a96832bae71bf110479683659ace7e6377f | index.js | index.js | var express = require('express');
var app = express();
var url = require('url');
var request = require('request');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('port', (process.env.PORT || 9001));
app.get('/', function(req, res) {
res.send('It works!');
});
app.post('/post', function(req, res) {
var body = {
response_type: "in_channel",
text: req.body.text + " http://vignette4.wikia.nocookie.net/imperial-assault/images/d/d7/Imperial_Assault_Die_Face.png/revision/latest?cb=20150825022932 http://epilepsyu.com/epilepsyassociation/files/2016/01/FUN.gif"
};
res.send(body);
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
| var express = require('express');
var app = express();
var url = require('url');
var request = require('request');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('port', (process.env.PORT || 9001));
app.get('/', function(req, res) {
res.send('It works!');
});
app.post('/post', function(req, res) {
var body = {
response_type: "in_channel",
text: req.body.text + "https://dicemaster.herokuapp.com/resources/ia/blue3.png"
};
res.send(body);
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
| Load ia dice image and see what it looks like | Load ia dice image and see what it looks like
| JavaScript | mit | WilliamBZA/DiceMaster | ---
+++
@@ -16,7 +16,7 @@
app.post('/post', function(req, res) {
var body = {
response_type: "in_channel",
- text: req.body.text + " http://vignette4.wikia.nocookie.net/imperial-assault/images/d/d7/Imperial_Assault_Die_Face.png/revision/latest?cb=20150825022932 http://epilepsyu.com/epilepsyassociation/files/2016/01/FUN.gif"
+ text: req.body.text + "https://dicemaster.herokuapp.com/resources/ia/blue3.png"
};
res.send(body); |
55c823e3fd29a9ed4eee7bac24fec69f518c5edf | index.js | index.js | 'use strict';
var events = require('events');
var configs = require('./configs');
var rump = module.exports = new events.EventEmitter();
rump.addGulpTasks = function() {
require('./gulp');
};
rump.reconfigure = function(options) {
configs.rebuild(options);
rump.emit('update:main');
};
rump.configs = {
get main() {
return configs.main;
},
get watch() {
return configs.watch;
}
};
| 'use strict';
var events = require('events');
var path = require('path');
var configs = require('./configs');
var rump = module.exports = new events.EventEmitter();
rump.autoload = function() {
var pkg = require(path.resolve('package.json'));
var modules = [].concat(Object.keys(pkg.dependencies || {}),
Object.keys(pkg.devDependencies || {}),
Object.keys(pkg.peerDependencies || {}));
modules.forEach(function(mod) {
try { require(mod); } catch(e) {}
});
};
rump.addGulpTasks = function() {
require('./gulp');
};
rump.reconfigure = function(options) {
configs.rebuild(options);
rump.emit('update:main');
};
rump.configs = {
get main() {
return configs.main;
},
get watch() {
return configs.watch;
}
};
| Add ability to automatically load available modules defined | Add ability to automatically load available modules defined
| JavaScript | mit | rumps/core,rumps/rump | ---
+++
@@ -1,8 +1,20 @@
'use strict';
var events = require('events');
+var path = require('path');
var configs = require('./configs');
var rump = module.exports = new events.EventEmitter();
+
+rump.autoload = function() {
+ var pkg = require(path.resolve('package.json'));
+ var modules = [].concat(Object.keys(pkg.dependencies || {}),
+ Object.keys(pkg.devDependencies || {}),
+ Object.keys(pkg.peerDependencies || {}));
+
+ modules.forEach(function(mod) {
+ try { require(mod); } catch(e) {}
+ });
+};
rump.addGulpTasks = function() {
require('./gulp'); |
eb11d289fd6924ea178c2200b6e96c3763c2ca16 | index.js | index.js | // Copyright 2014 Andrei Karpushonak
"use strict";
var _ = require('lodash');
var ECMA_SIZES = require('./byte_size');
/**
* Main module's entry point
* Calculates Bytes for the provided parameter
* @param object - handles object/string/boolean/buffer
* @returns {*}
*/
function sizeof(object) {
if (_.isObject(object)) {
if (Buffer.isBuffer(object)) {
return object.length;
}
else {
var bytes = 0;
_.forOwn(object, function (value, key) {
bytes += sizeof(key);
try {
bytes += sizeof(value);
} catch (ex) {
if(ex instanceof RangeError) {
console.error('Circular dependency detected, result might be incorrect: ', object)
}
}
});
return bytes;
}
} else if (_.isString(object)) {
return object.length * ECMA_SIZES.STRING;
} else if (_.isBoolean(object)) {
return ECMA_SIZES.BOOLEAN;
} else if (_.isNumber(object)) {
return ECMA_SIZES.NUMBER;
} else {
return 0;
}
}
module.exports = sizeof;
| // Copyright 2014 Andrei Karpushonak
"use strict";
var _ = require('lodash');
var ECMA_SIZES = require('./byte_size');
/**
* Main module's entry point
* Calculates Bytes for the provided parameter
* @param object - handles object/string/boolean/buffer
* @returns {*}
*/
function sizeof(object) {
if (_.isObject(object)) {
if (Buffer.isBuffer(object)) {
return object.length;
}
else {
var bytes = 0;
_.forOwn(object, function (value, key) {
bytes += sizeof(key);
try {
bytes += sizeof(value);
} catch (ex) {
if(ex instanceof RangeError) {
console.log('Circular dependency detected, result might be incorrect: ', object)
}
}
});
return bytes;
}
} else if (_.isString(object)) {
return object.length * ECMA_SIZES.STRING;
} else if (_.isBoolean(object)) {
return ECMA_SIZES.BOOLEAN;
} else if (_.isNumber(object)) {
return ECMA_SIZES.NUMBER;
} else {
return 0;
}
}
module.exports = sizeof;
| Use console.log instead of console.warn | Use console.log instead of console.warn
| JavaScript | mit | miktam/sizeof,avrora/sizeof | ---
+++
@@ -24,7 +24,7 @@
bytes += sizeof(value);
} catch (ex) {
if(ex instanceof RangeError) {
- console.error('Circular dependency detected, result might be incorrect: ', object)
+ console.log('Circular dependency detected, result might be incorrect: ', object)
}
}
}); |
b658af5d5c150f1597fba03063821aafa801f601 | src/components/Navbar.js | src/components/Navbar.js | /*
* @flow
*/
import * as React from 'react';
export default function Navbar() {
return (
<nav className="navbar navbar-default navbar-fixed-top navbar-inverse">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" href="/" onClick={(e: SyntheticEvent<>) => {
e.preventDefault();
window.location.hash = '';
window.location.reload();
}}>
Bonsai
</a>
<p className="navbar-text">
Trim your dependency trees
</p>
</div>
<ul className="nav navbar-nav navbar-right">
<li>
<a className="navbar-link" href="https://pinterest.github.io/bonsai/">
Docs
</a>
</li>
<li>
<a className="navbar-link" href="https://github.com/pinterest/bonsai">
Github
</a>
</li>
</ul>
</div>
</nav>
);
}
| /*
* @flow
*/
import * as React from 'react';
import {getClassName} from './Bootstrap/GlyphiconNames';
export default function Navbar() {
return (
<nav className="navbar navbar-default navbar-fixed-top navbar-inverse">
<div className="container-fluid">
<div className="navbar-header">
<a className="navbar-brand" href="/" onClick={(e: SyntheticEvent<>) => {
e.preventDefault();
window.location.hash = '';
window.location.reload();
}}>
Bonsai
</a>
<p className="navbar-text">
<span
className={getClassName('tree-conifer')}
aria-hidden="true"></span>
Trim your dependency trees
</p>
</div>
<ul className="nav navbar-nav navbar-right">
<li>
<a className="navbar-link" href="https://pinterest.github.io/bonsai/">
<span
className={getClassName('book')}
aria-hidden="true"></span>
Docs
</a>
</li>
<li>
<a className="navbar-link" href="https://github.com/pinterest/bonsai">
Github
</a>
</li>
</ul>
</div>
</nav>
);
}
| Use glyphicons in the header so they download earlier. | Use glyphicons in the header so they download earlier.
| JavaScript | apache-2.0 | pinterest/bonsai,pinterest/bonsai,pinterest/bonsai | ---
+++
@@ -3,6 +3,8 @@
*/
import * as React from 'react';
+
+import {getClassName} from './Bootstrap/GlyphiconNames';
export default function Navbar() {
return (
@@ -17,12 +19,18 @@
Bonsai
</a>
<p className="navbar-text">
+ <span
+ className={getClassName('tree-conifer')}
+ aria-hidden="true"></span>
Trim your dependency trees
</p>
</div>
<ul className="nav navbar-nav navbar-right">
<li>
<a className="navbar-link" href="https://pinterest.github.io/bonsai/">
+ <span
+ className={getClassName('book')}
+ aria-hidden="true"></span>
Docs
</a>
</li> |
53c7d27f9097c6c80b080f2708f34cbfa296db5e | index.js | index.js | 'use strict';
const path = require('path');
const pkg = require(path.resolve('./package.json'));
const semver = require('semver');
const versions = require('./versions.json');
const presetEnv = require.resolve('babel-preset-env');
const presetStage3 = require.resolve('babel-preset-stage-3');
module.exports = function() {
const targets = {};
if (typeof pkg.browserslist === 'object' && pkg.browserslist.length) {
targets.browsers = pkg.browserslist;
}
if (typeof pkg.engines === 'object' && pkg.engines.node) {
const version = pkg.engines.node;
if (semver.valid(version)) {
targets.node = version;
} else if (semver.validRange(version)) {
targets.node = semver.minSatisfying(versions.node, version);
}
}
return {
presets: [
[presetEnv, {targets}],
presetStage3,
],
};
};
| 'use strict';
const path = require('path');
const pkg = require(path.resolve('./package.json'));
const semver = require('semver');
const versions = require('./versions.json');
const presetEnv = require.resolve('babel-preset-env');
const presetStage3 = require.resolve('babel-preset-stage-3');
module.exports = function() {
const targets = {};
if (pkg.browserslist) {
targets.browsers = pkg.browserslist;
}
if (pkg.engines && pkg.engines.node) {
const version = pkg.engines.node;
if (semver.valid(version)) {
targets.node = version;
} else if (semver.validRange(version)) {
targets.node = semver.minSatisfying(versions.node, version);
}
}
return {
presets: [
[presetEnv, {targets}],
presetStage3,
],
};
};
| Simplify the checks for package.json objects | :hammer: Simplify the checks for package.json objects
| JavaScript | mit | jamieconnolly/babel-preset | ---
+++
@@ -11,11 +11,11 @@
module.exports = function() {
const targets = {};
- if (typeof pkg.browserslist === 'object' && pkg.browserslist.length) {
+ if (pkg.browserslist) {
targets.browsers = pkg.browserslist;
}
- if (typeof pkg.engines === 'object' && pkg.engines.node) {
+ if (pkg.engines && pkg.engines.node) {
const version = pkg.engines.node;
if (semver.valid(version)) { |
f997f034b1a028448b266b617f6cb4c3b0269d0b | index.js | index.js | 'use strict';
var userHome = require('user-home');
module.exports = function (str) {
return userHome ? str.replace(/^~\//, userHome + '/') : str;
};
| 'use strict';
var userHome = require('user-home');
module.exports = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return userHome ? str.replace(/^~\//, userHome + '/') : str;
};
| Throw if input is not a string | Throw if input is not a string
| JavaScript | mit | sindresorhus/untildify,sindresorhus/untildify | ---
+++
@@ -2,5 +2,8 @@
var userHome = require('user-home');
module.exports = function (str) {
+ if (typeof str !== 'string') {
+ throw new TypeError('Expected a string');
+ }
return userHome ? str.replace(/^~\//, userHome + '/') : str;
}; |
a2c4f70e192793f2f241a3acba5878c79090d0d8 | client/app/dashboard/students/new/route.js | client/app/dashboard/students/new/route.js | import Ember from 'ember';
export default Ember.Route.extend({
titleToken: 'Add a student',
model() {
return this.store.createRecord('student');
}
});
| import Ember from 'ember';
export default Ember.Route.extend({
titleToken: 'Add a student',
model() {
return this.store.createRecord('student');
},
resetController(controller, isExiting) {
if (isExiting) {
controller.set('didValidate', false);
controller.set('errorMessage', false);
}
}
});
| Clean up repeat visits to add student view. | Clean up repeat visits to add student view.
| JavaScript | bsd-2-clause | mblayman/lcp,mblayman/lcp,mblayman/lcp | ---
+++
@@ -5,5 +5,12 @@
model() {
return this.store.createRecord('student');
+ },
+
+ resetController(controller, isExiting) {
+ if (isExiting) {
+ controller.set('didValidate', false);
+ controller.set('errorMessage', false);
+ }
}
}); |
5f032a0fe59a2bbea943bf79fcb40e0382872310 | public/js/csv-generator.js | public/js/csv-generator.js | const csvGenerator = {
init() {
const downloadCsvBtnEl = document.querySelector(".js-download-csv-btn");
if (downloadCsvBtnEl) {
downloadCsvBtnEl.addEventListener("click", e => {
window.open(window.location.href, '_blank');
});
}
}
}
export default csvGenerator; | const csvGenerator = {
init() {
const downloadCsvBtnEl = document.querySelector(".js-download-csv-btn");
if (downloadCsvBtnEl) {
downloadCsvBtnEl.addEventListener("click", e => {
let url = `${window.location.href}&returns=csv`;
window.open(url, '_blank');
});
}
}
}
export default csvGenerator; | Refactor CSV generator button script | Refactor CSV generator button script
| JavaScript | mit | participedia/api,participedia/api,participedia/api,participedia/api | ---
+++
@@ -3,7 +3,8 @@
const downloadCsvBtnEl = document.querySelector(".js-download-csv-btn");
if (downloadCsvBtnEl) {
downloadCsvBtnEl.addEventListener("click", e => {
- window.open(window.location.href, '_blank');
+ let url = `${window.location.href}&returns=csv`;
+ window.open(url, '_blank');
});
}
} |
697b1268296a2aa9b753f0306166f18ca6598884 | js/db.js | js/db.js | var app = app || {};
(function() {
app.db = {
id: "todoDB",
description: "Database of the todo list",
migrations : [
{
version: "1.0",
migrate: function(transaction, next) {
transaction.db.createObjectStore("todos");
next();
}
}
]
}
})();
| var app = app || {};
(function() {
app.db = {
id: "todoDB",
description: "Database of the todo list",
nolog: true,
migrations : [
{
version: "1.0",
migrate: function(transaction, next) {
transaction.db.createObjectStore("todos");
next();
}
}
]
}
})();
| Disable verbose output of the indexedDB | Disable verbose output of the indexedDB
| JavaScript | mit | Vicos/viTodo | ---
+++
@@ -4,6 +4,7 @@
app.db = {
id: "todoDB",
description: "Database of the todo list",
+ nolog: true,
migrations : [
{
version: "1.0", |
0ceee8a2ad1e72ad628fe31974670b1fc11220d8 | src/web/js/collections/localStorage.js | src/web/js/collections/localStorage.js | /**
* Collection for interfacing with localStorage.
*/
'use strict';
var Backbone = require('backbone');
var _ = require('lodash');
module.exports = Backbone.Collection.extend({
model: Backbone.Model,
initialize: function() {
this.localStorage = window.localStorage;
},
fetch: function() {
var history = [];
var session = {};
var keys = Object.keys(this.localStorage);
for (var i = 0; i < keys.length; i++) {
session = {};
session.id = keys[i];
session.tree = JSON.parse(this.localStorage.getItem(this.localStorage.key(i)));
history.push(session);
}
this.parse(history);
this.trigger('sync');
},
parse: function(history) {
_.each(history, _.bind(function(session) {
session.checked = false;
this.add(session);
}, this));
},
getLatest: function() {
this.fetch();
var len = this.models.length;
return this.models[len-1];
}
});
| /**
* Collection for interfacing with localStorage.
*/
'use strict';
var Backbone = require('backbone');
var _ = require('lodash');
module.exports = Backbone.Collection.extend({
model: Backbone.Model,
initialize: function() {
this.localStorage = window.localStorage;
},
fetch: function() {
var history = [];
var session = {};
var keys = Object.keys(this.localStorage);
for (var i = 0; i < keys.length; i++) {
session = {};
session.id = keys[i];
session.tree = JSON.parse(this.localStorage.getItem(this.localStorage.key(i)));
history.push(session);
}
this.parse(history);
this.trigger('sync');
},
parse: function(history) {
_.each(history, _.bind(function(session) {
session.checked = false;
this.add(session);
}, this));
},
getLatest: function() {
this.fetch();
var len = this.models.length;
return this.models[len-1];
},
deleteChecked: function() {
var self = this;
this.each(function(session) {
var sessionId = session.get('id');
if (session.get('checked')) {
console.log('Deleting session ' + sessionId);
self.remove(sessionId);
self.localStorage.removeItem(sessionId);
}
});
this.trigger('sync');
}
});
| Implement delete in history collection | Implement delete in history collection
| JavaScript | mit | ptmccarthy/wikimapper,ptmccarthy/wikimapper | ---
+++
@@ -42,6 +42,20 @@
this.fetch();
var len = this.models.length;
return this.models[len-1];
+ },
+
+ deleteChecked: function() {
+ var self = this;
+
+ this.each(function(session) {
+ var sessionId = session.get('id');
+ if (session.get('checked')) {
+ console.log('Deleting session ' + sessionId);
+ self.remove(sessionId);
+ self.localStorage.removeItem(sessionId);
+ }
+ });
+
+ this.trigger('sync');
}
-
}); |
445c6fcf835af3c7af438864765a6a1ded2edecd | javascript/multivaluefield.js | javascript/multivaluefield.js | jQuery(function($) {
function addNewField() {
var self = $(this);
var val = self.val();
// check to see if the one after us is there already - if so, we don't need a new one
var li = $(this).closest('li').next('li');
if (!val) {
// lets also clean up if needbe
var nextText = li.find('input.mventryfield');
var detach = true;
nextText.each (function () {
if ($(this) && $(this).val() && $(this).val().length > 0) {
detach = false;
}
});
if (detach) {
li.detach();
}
} else {
if (li.length) {
return;
}
self.closest("li").clone()
.find("input").val("").end()
.find("select").val("").end()
.appendTo(self.parents("ul.multivaluefieldlist"));
}
$(this).trigger('multiValueFieldAdded');
}
$(document).on("keyup", ".mventryfield", addNewField);
$(document).on("change", ".mventryfield:not(input)", addNewField);
});
| jQuery(function($) {
function addNewField() {
var self = $(this);
var val = self.val();
// check to see if the one after us is there already - if so, we don't need a new one
var li = $(this).closest('li').next('li');
if (!val) {
// lets also clean up if needbe
var nextText = li.find('input.mventryfield');
var detach = true;
nextText.each (function () {
if ($(this) && $(this).val() && $(this).val().length > 0) {
detach = false;
}
});
if (detach) {
li.detach();
}
} else {
if (li.length) {
return;
}
var append = self.closest("li").clone()
.find(".has-chzn").show().removeClass("").data("chosen", null).end()
.find(".chzn-container").remove().end();
// Assign the new inputs a unique ID, so that chosen picks up
// the correct container.
append.find("input, select").val("").attr("id", function() {
var pos = this.id.lastIndexOf(":");
var num = parseInt(this.id.substr(pos + 1));
return this.id.substr(0, pos + 1) + (num + 1).toString();
});
append.appendTo(self.parents("ul.multivaluefieldlist"));
}
$(this).trigger('multiValueFieldAdded');
}
$(document).on("keyup", ".mventryfield", addNewField);
$(document).on("change", ".mventryfield:not(input)", addNewField);
});
| Allow multi value dropdowns to be used with chosen. | Allow multi value dropdowns to be used with chosen.
| JavaScript | bsd-3-clause | souldigital/silverstripe-multivaluefield,souldigital/silverstripe-multivaluefield,designcity/silverstripe-multivaluefield,silverstripe-australia/silverstripe-multivaluefield,silverstripe-australia/silverstripe-multivaluefield,designcity/silverstripe-multivaluefield | ---
+++
@@ -26,10 +26,20 @@
return;
}
- self.closest("li").clone()
- .find("input").val("").end()
- .find("select").val("").end()
- .appendTo(self.parents("ul.multivaluefieldlist"));
+ var append = self.closest("li").clone()
+ .find(".has-chzn").show().removeClass("").data("chosen", null).end()
+ .find(".chzn-container").remove().end();
+
+ // Assign the new inputs a unique ID, so that chosen picks up
+ // the correct container.
+ append.find("input, select").val("").attr("id", function() {
+ var pos = this.id.lastIndexOf(":");
+ var num = parseInt(this.id.substr(pos + 1));
+
+ return this.id.substr(0, pos + 1) + (num + 1).toString();
+ });
+
+ append.appendTo(self.parents("ul.multivaluefieldlist"));
}
$(this).trigger('multiValueFieldAdded'); |
18b18dd15046c89d4e81ab0d17f87a1733159cf7 | app/assets/javascripts/directives/validation/validation_status.js | app/assets/javascripts/directives/validation/validation_status.js | ManageIQ.angular.app.directive('validationStatus', function() {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
ctrl.$validators.validationRequired = function (modelValue, viewValue) {
if (angular.isDefined(viewValue) && viewValue === true) {
scope.postValidationModelRegistry(attrs.prefix);
return true;
}
return false;
};
}
}
});
| ManageIQ.angular.app.directive('validationStatus', ['$rootScope', function($rootScope) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
ctrl.$validators.validationRequired = function (modelValue, viewValue) {
if (angular.isDefined(viewValue) && viewValue === true) {
scope.postValidationModelRegistry(attrs.prefix);
return true;
} else {
$rootScope.$broadcast('setErrorOnTab', {tab: attrs.prefix});
return false;
}
};
}
}
}]);
| Mark the tab with the error indicator the moment error is detected | Mark the tab with the error indicator the moment error is detected
| JavaScript | apache-2.0 | djberg96/manageiq,KevinLoiseau/manageiq,yaacov/manageiq,gmcculloug/manageiq,israel-hdez/manageiq,lpichler/manageiq,ailisp/manageiq,jvlcek/manageiq,gmcculloug/manageiq,tzumainn/manageiq,chessbyte/manageiq,jameswnl/manageiq,borod108/manageiq,kbrock/manageiq,romaintb/manageiq,jvlcek/manageiq,chessbyte/manageiq,mfeifer/manageiq,d-m-u/manageiq,gmcculloug/manageiq,gmcculloug/manageiq,aufi/manageiq,ailisp/manageiq,tinaafitz/manageiq,durandom/manageiq,josejulio/manageiq,agrare/manageiq,NickLaMuro/manageiq,josejulio/manageiq,mzazrivec/manageiq,agrare/manageiq,maas-ufcg/manageiq,romaintb/manageiq,mresti/manageiq,andyvesel/manageiq,jntullo/manageiq,branic/manageiq,romaintb/manageiq,skateman/manageiq,mkanoor/manageiq,juliancheal/manageiq,mresti/manageiq,tinaafitz/manageiq,tzumainn/manageiq,hstastna/manageiq,chessbyte/manageiq,mzazrivec/manageiq,skateman/manageiq,branic/manageiq,ManageIQ/manageiq,ilackarms/manageiq,gerikis/manageiq,mfeifer/manageiq,israel-hdez/manageiq,aufi/manageiq,maas-ufcg/manageiq,lpichler/manageiq,syncrou/manageiq,matobet/manageiq,israel-hdez/manageiq,jrafanie/manageiq,jntullo/manageiq,syncrou/manageiq,NaNi-Z/manageiq,branic/manageiq,maas-ufcg/manageiq,mzazrivec/manageiq,yaacov/manageiq,agrare/manageiq,romanblanco/manageiq,mkanoor/manageiq,djberg96/manageiq,romanblanco/manageiq,matobet/manageiq,tzumainn/manageiq,josejulio/manageiq,juliancheal/manageiq,kbrock/manageiq,mzazrivec/manageiq,pkomanek/manageiq,ManageIQ/manageiq,jameswnl/manageiq,ailisp/manageiq,jvlcek/manageiq,aufi/manageiq,maas-ufcg/manageiq,mresti/manageiq,yaacov/manageiq,d-m-u/manageiq,NickLaMuro/manageiq,josejulio/manageiq,jvlcek/manageiq,mresti/manageiq,aufi/manageiq,NickLaMuro/manageiq,billfitzgerald0120/manageiq,romaintb/manageiq,mfeifer/manageiq,pkomanek/manageiq,tinaafitz/manageiq,durandom/manageiq,mfeifer/manageiq,mkanoor/manageiq,hstastna/manageiq,ManageIQ/manageiq,branic/manageiq,andyvesel/manageiq,d-m-u/manageiq,fbladilo/manageiq,kbrock/manageiq,agrare/manageiq,fbladilo/manageiq,jameswnl/manageiq,romaintb/manageiq,djberg96/manageiq,mkanoor/manageiq,maas-ufcg/manageiq,fbladilo/manageiq,tzumainn/manageiq,jameswnl/manageiq,skateman/manageiq,jrafanie/manageiq,syncrou/manageiq,gerikis/manageiq,NaNi-Z/manageiq,fbladilo/manageiq,skateman/manageiq,ManageIQ/manageiq,durandom/manageiq,ailisp/manageiq,matobet/manageiq,ilackarms/manageiq,jntullo/manageiq,romanblanco/manageiq,borod108/manageiq,gerikis/manageiq,andyvesel/manageiq,NaNi-Z/manageiq,yaacov/manageiq,durandom/manageiq,romaintb/manageiq,KevinLoiseau/manageiq,tinaafitz/manageiq,pkomanek/manageiq,matobet/manageiq,chessbyte/manageiq,jntullo/manageiq,borod108/manageiq,hstastna/manageiq,gerikis/manageiq,juliancheal/manageiq,romanblanco/manageiq,kbrock/manageiq,jrafanie/manageiq,billfitzgerald0120/manageiq,juliancheal/manageiq,d-m-u/manageiq,andyvesel/manageiq,NaNi-Z/manageiq,KevinLoiseau/manageiq,ilackarms/manageiq,ilackarms/manageiq,pkomanek/manageiq,djberg96/manageiq,billfitzgerald0120/manageiq,borod108/manageiq,israel-hdez/manageiq,KevinLoiseau/manageiq,KevinLoiseau/manageiq,KevinLoiseau/manageiq,jrafanie/manageiq,lpichler/manageiq,NickLaMuro/manageiq,hstastna/manageiq,syncrou/manageiq,maas-ufcg/manageiq,billfitzgerald0120/manageiq,lpichler/manageiq | ---
+++
@@ -1,4 +1,4 @@
-ManageIQ.angular.app.directive('validationStatus', function() {
+ManageIQ.angular.app.directive('validationStatus', ['$rootScope', function($rootScope) {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
@@ -6,9 +6,11 @@
if (angular.isDefined(viewValue) && viewValue === true) {
scope.postValidationModelRegistry(attrs.prefix);
return true;
+ } else {
+ $rootScope.$broadcast('setErrorOnTab', {tab: attrs.prefix});
+ return false;
}
- return false;
};
}
}
-});
+}]); |
2346a2e653ba30424ac5a5be08a6bd741d7c3814 | jest/moveSnapshots.js | jest/moveSnapshots.js | const fs = require('fs')
const glob = require('glob')
const outputDirectory = [process.argv[2] || 'snapshots']
.filter(x => x)
.join('/')
const createDir = dir => {
const splitPath = dir.split('/')
splitPath.reduce((path, subPath) => {
if (!fs.existsSync(path)) {
console.log(`Create directory at ${path}.`);
fs.mkdirSync(path)
}
return `${path}/${subPath}`
})
}
glob('src/__snapshots__/*.snap', {}, (er, files) => {
console.log({
argv: process.argv
})
files.forEach(fileName => {
const newName = fileName
.replace(/__snapshots__\//g, '')
.replace('src/', `${outputDirectory}/`)
console.log(`Move file ${fileName} to ${newName}.`);
createDir(newName)
fs.renameSync(fileName, newName)
})
glob('src/__snapshots__', {}, (er, files) => {
files.forEach(fileName => {
fs.rmdirSync(fileName)
})
})
})
| const fs = require('fs')
const glob = require('glob')
const outputDirectory = [process.argv[2] || 'snapshots']
.filter(x => x)
.join('/')
const createDir = dir => {
const splitPath = dir.split('/')
splitPath.reduce((path, subPath) => {
if (path && !fs.existsSync(path)) {
console.log(`Create directory at ${path}.`);
fs.mkdirSync(path)
}
return `${path}/${subPath}`
})
}
glob('src/__snapshots__/*.snap', {}, (er, files) => {
console.log({
argv: process.argv
})
files.forEach(fileName => {
const newName = fileName
.replace(/__snapshots__\//g, '')
.replace('src/', `${outputDirectory}/`)
console.log(`Move file ${fileName} to ${newName}.`);
createDir(newName)
fs.renameSync(fileName, newName)
})
glob('src/__snapshots__', {}, (er, files) => {
files.forEach(fileName => {
fs.rmdirSync(fileName)
})
})
})
| Fix path existence ensuring function | Fix path existence ensuring function
| JavaScript | mit | Ciunkos/ciunkos.com | ---
+++
@@ -8,7 +8,7 @@
const createDir = dir => {
const splitPath = dir.split('/')
splitPath.reduce((path, subPath) => {
- if (!fs.existsSync(path)) {
+ if (path && !fs.existsSync(path)) {
console.log(`Create directory at ${path}.`);
fs.mkdirSync(path)
} |
78c19a634a06277e134c3af1024f9648bc3d3b26 | kolibri/core/assets/src/api-resources/facilityTask.js | kolibri/core/assets/src/api-resources/facilityTask.js | import { Resource } from 'kolibri.lib.apiResource';
export default new Resource({
name: 'facilitytask',
/**
* @param {string} facility
* @return {Promise}
*/
dataportalsync(facility) {
return this.postListEndpoint('startdataportalsync', { facility });
},
/**
* @return {Promise}
*/
dataportalbulksync() {
return this.postListEndpoint('startdataportalbulksync');
},
deleteFinishedTasks() {
return this.postListEndpoint('deletefinishedtasks');
},
});
| import { Resource } from 'kolibri.lib.apiResource';
export default new Resource({
name: 'facilitytask',
/**
* @param {string} facility
* @return {Promise}
*/
dataportalsync(facility) {
return this.postListEndpoint('startdataportalsync', { facility });
},
/**
* @return {Promise}
*/
dataportalbulksync() {
return this.postListEndpoint('startdataportalbulksync');
},
/**
* @return {Promise}
*/
deleteFinishedTasks() {
return this.postListEndpoint('deletefinishedtasks');
},
/**
* @param {string} facility
* @return {Promise}
*/
deleteFacility(facility) {
return this.postListEndpoint('deletefacility', { facility });
},
});
| Add JS resource for new endpoint | Add JS resource for new endpoint
| JavaScript | mit | mrpau/kolibri,indirectlylit/kolibri,mrpau/kolibri,mrpau/kolibri,learningequality/kolibri,mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,indirectlylit/kolibri,learningequality/kolibri | ---
+++
@@ -18,7 +18,18 @@
return this.postListEndpoint('startdataportalbulksync');
},
+ /**
+ * @return {Promise}
+ */
deleteFinishedTasks() {
return this.postListEndpoint('deletefinishedtasks');
},
+
+ /**
+ * @param {string} facility
+ * @return {Promise}
+ */
+ deleteFacility(facility) {
+ return this.postListEndpoint('deletefacility', { facility });
+ },
}); |
1827499c2e834072c488c5ec7b1e67eccde8e4ea | src/Select/partials/SelectInputFieldSize.js | src/Select/partials/SelectInputFieldSize.js | import styled from 'styled-components'
import SelectInputField from './SelectInputField';
export default SelectInputField.withComponent('div').extend`
position: absolute;
top: 0px;
left: 0px;
visibility: hidden;
height: 0px;
white-space: pre;
`;
| import styled from 'styled-components'
import SelectInputField from './SelectInputField';
export default styled(SelectInputField.withComponent('div'))`
position: absolute;
top: 0px;
left: 0px;
visibility: hidden;
height: 0px;
white-space: pre;
`;
| Remove use of extend API | Remove use of extend API
To prevent warning
`Warning: The "extend" API will be removed in the upcoming v4.0 release. Use styled(StyledComponent) instead. You can find more information here: https://github.com/styled-components/styled-components/issues/1546` | JavaScript | mit | agutoli/react-styled-select | ---
+++
@@ -1,7 +1,7 @@
import styled from 'styled-components'
import SelectInputField from './SelectInputField';
-export default SelectInputField.withComponent('div').extend`
+export default styled(SelectInputField.withComponent('div'))`
position: absolute;
top: 0px;
left: 0px; |
8a175bd8b14dc91719fcd2aa40137fc1e20370b5 | src/article/shared/InsertFootnoteCommand.js | src/article/shared/InsertFootnoteCommand.js | import { findParentByType } from './nodeHelpers'
// TODO: move AddEntityCommand into shared
import AddEntityCommand from '../metadata/AddEntityCommand'
export default class InsertFootnoteCommand extends AddEntityCommand {
detectScope (params) {
const xpath = params.selectionState.xpath
return xpath.indexOf('table-figure') > -1 ? 'table-figure' : 'default'
}
_getCollection (params, context) {
const scope = this.detectScope(params)
if (scope === 'default') {
const collectionName = 'footnotes'
return context.api.getModelById(collectionName)
} else {
const doc = params.editorSession.getDocument()
const nodeId = params.selection.getNodeId()
const node = doc.get(nodeId)
const parentTable = findParentByType(node, 'table-figure')
const tableModel = context.api.getModelById(parentTable.id)
return tableModel.getFootnotes()
}
}
}
| import { findParentByType } from './nodeHelpers'
// TODO: move AddEntityCommand into shared
import AddEntityCommand from '../metadata/AddEntityCommand'
export default class InsertFootnoteCommand extends AddEntityCommand {
detectScope (params) {
const xpath = params.selectionState.xpath
return xpath.indexOf('table-figure') > -1 ? 'table-figure' : 'default'
}
_getCollection (params, context) {
const scope = this.detectScope(params)
if (scope === 'default') {
const collectionName = 'footnotes'
return context.api.getModelById(collectionName)
} else {
const doc = params.editorSession.getDocument()
const nodeId = params.selection.getNodeId()
const node = doc.get(nodeId)
let tableNodeId = node.id
// check if we are already selected table-figure
if (node.type !== 'table-figure') {
const parentTable = findParentByType(node, 'table-figure')
tableNodeId = parentTable.id
}
const tableModel = context.api.getModelById(tableNodeId)
return tableModel.getFootnotes()
}
}
}
| Address edge case when table-figure already selected. | Address edge case when table-figure already selected.
| JavaScript | mit | substance/texture,substance/texture | ---
+++
@@ -14,11 +14,16 @@
const collectionName = 'footnotes'
return context.api.getModelById(collectionName)
} else {
- const doc = params.editorSession.getDocument()
- const nodeId = params.selection.getNodeId()
- const node = doc.get(nodeId)
- const parentTable = findParentByType(node, 'table-figure')
- const tableModel = context.api.getModelById(parentTable.id)
+ const doc = params.editorSession.getDocument()
+ const nodeId = params.selection.getNodeId()
+ const node = doc.get(nodeId)
+ let tableNodeId = node.id
+ // check if we are already selected table-figure
+ if (node.type !== 'table-figure') {
+ const parentTable = findParentByType(node, 'table-figure')
+ tableNodeId = parentTable.id
+ }
+ const tableModel = context.api.getModelById(tableNodeId)
return tableModel.getFootnotes()
}
} |
79a7e9a58d3d6e724ae1e5b434210084f0e908bf | phantom/graph.js | phantom/graph.js | "use strict";
var page = require('webpage').create(),
system = require('system'),
address, output;
if (system.args.length < 3 || system.args.length > 4) {
console.log('Usage: graph.js IP filename');
phantom.exit();
} else {
address = system.args[1];
output = system.args[2];
console.log("Fetching", address, "for", output);
page.viewportSize = { width: 501, height: 233 };
page.onConsoleMessage = function (msg) {
console.log('Page msg:', msg);
};
page.customHeaders = {
// "Referer": "http://www.pool.ntp.org/?graphs"
};
page.settings.userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2";
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function () {
page.clipRect = { top: 0, left: 20, width: 501, height: 233 };
page.render(output);
phantom.exit();
}, 200);
}
});
}
| "use strict";
var page = require('webpage').create(),
system = require('system'),
address, output;
if (system.args.length < 3 || system.args.length > 4) {
console.log('Usage: graph.js url filename');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
console.log("Fetching", address, "for", output);
page.viewportSize = { width: 501, height: 233 };
page.onConsoleMessage = function (msg) {
console.log('Page msg:', msg);
};
page.customHeaders = {
// "Referer": "http://www.pool.ntp.org/?graphs"
};
page.settings.userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2";
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!', status);
phantom.exit(2);
} else {
window.setTimeout(function () {
page.clipRect = { top: 0, left: 20, width: 501, height: 233 };
page.render(output);
phantom.exit();
}, 200);
}
});
}
| Make sure the phantomjs script doesn't hang on failures | Make sure the phantomjs script doesn't hang on failures
| JavaScript | apache-2.0 | punitvara/ntppool,punitvara/ntppool,tklauser/ntppool,tklauser/ntppool,tklauser/ntppool,tklauser/ntppool,punitvara/ntppool | ---
+++
@@ -5,8 +5,8 @@
address, output;
if (system.args.length < 3 || system.args.length > 4) {
- console.log('Usage: graph.js IP filename');
- phantom.exit();
+ console.log('Usage: graph.js url filename');
+ phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
@@ -22,7 +22,8 @@
page.open(address, function (status) {
if (status !== 'success') {
- console.log('Unable to load the address!');
+ console.log('Unable to load the address!', status);
+ phantom.exit(2);
} else {
window.setTimeout(function () {
page.clipRect = { top: 0, left: 20, width: 501, height: 233 }; |
a03061c9710dda8faf1d10eb664206b41835be96 | lib/assets/javascripts/dashboard/components/footer/footer-view.js | lib/assets/javascripts/dashboard/components/footer/footer-view.js | const CoreView = require('backbone/core-view');
const template = require('./footer.tpl');
const checkAndBuildOpts = require('builder/helpers/required-opts');
const REQUIRED_OPTS = [
'configModel'
];
/**
* Decide what support block app should show
*/
module.exports = CoreView.extend({
tagName: 'footer',
className: function () {
let classes = 'CDB-Text CDB-FontSize-medium Footer Footer--public u-pr';
if (this.options.light) {
classes += ' Footer--light';
}
return classes;
},
initialize: function (options) {
checkAndBuildOpts(options, REQUIRED_OPTS, this);
},
render: function () {
this.$el.html(
template({
onpremiseVersion: this._configModel.get('onpremise_version'),
isHosted: this._configModel.get('cartodb_com_hosted')
})
);
return this;
}
});
| const CoreView = require('backbone/core-view');
const template = require('./footer.tpl');
const checkAndBuildOpts = require('builder/helpers/required-opts');
const REQUIRED_OPTS = [
'configModel'
];
/**
* Decide what support block app should show
*/
module.exports = CoreView.extend({
tagName: 'footer',
className: function () {
let classes = 'CDB-Text CDB-FontSize-medium Footer';
if (this.options.light) {
classes += ' Footer--light';
}
return classes;
},
initialize: function (options) {
checkAndBuildOpts(options, REQUIRED_OPTS, this);
},
render: function () {
this.$el.html(
template({
onpremiseVersion: this._configModel.get('onpremise_version'),
isHosted: this._configModel.get('cartodb_com_hosted')
})
);
return this;
}
});
| Fix footer in static pages | Fix footer in static pages
| JavaScript | bsd-3-clause | CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb | ---
+++
@@ -14,7 +14,7 @@
tagName: 'footer',
className: function () {
- let classes = 'CDB-Text CDB-FontSize-medium Footer Footer--public u-pr';
+ let classes = 'CDB-Text CDB-FontSize-medium Footer';
if (this.options.light) {
classes += ' Footer--light'; |
4122f817b94d9f518c12a01c5d77e719726c2ac6 | src/gallery.js | src/gallery.js | import mediumZoom from 'src/config/medium-zoom';
import lqip from 'src/modules/lqip';
import galleryLoader from 'src/modules/gallery-lazy-load';
window.addEventListener('DOMContentLoaded', () => {
galleryLoader({
afterInsert(lastPost) {
lqip({
selectorRoot: lastPost,
afterReplace: (lqipImage, originalImage) => {
if (lqipImage) lqipImage.remove();
mediumZoom(originalImage);
},
})
},
});
lqip({
afterReplace: (lqipImage, originalImage) => {
if (lqipImage) lqipImage.remove();
mediumZoom(originalImage);
},
});
});
| import mediumZoom from 'src/config/medium-zoom';
import lqip from 'src/modules/lqip';
import galleryLoader from 'src/modules/gallery-lazy-load';
window.addEventListener('DOMContentLoaded', () => {
galleryLoader({
afterInsert(lastPost) {
lqip({
selectorRoot: lastPost,
rootMargin: '0px',
afterReplace: (lqipImage, originalImage) => {
if (lqipImage) lqipImage.remove();
mediumZoom(originalImage);
},
})
},
});
lqip({
afterReplace: (lqipImage, originalImage) => {
if (lqipImage) lqipImage.remove();
mediumZoom(originalImage);
},
});
});
| Use low root margin to prevent premature loading of images | Use low root margin to prevent premature loading of images
| JavaScript | mit | tuelsch/bolg,tuelsch/bolg | ---
+++
@@ -7,6 +7,7 @@
afterInsert(lastPost) {
lqip({
selectorRoot: lastPost,
+ rootMargin: '0px',
afterReplace: (lqipImage, originalImage) => {
if (lqipImage) lqipImage.remove();
mediumZoom(originalImage); |
784c672f4b0c9b42d5b6431a0a155a164493669d | client/src/sagas.js | client/src/sagas.js | export default function* rootSaga() {
}
| import { createBrowserHistory as createHistory, saga as router } from 'redux-tower';
import routes from './routes'
import { fork } from 'redux-saga/effects'
const history = createHistory();
export default function* rootSaga() {
yield fork(router, {history, routes});
}
| Add router saga to rootSaga | Add router saga to rootSaga
| JavaScript | mit | ygkn/DJ-YAGICHAN-SYSTEM,ygkn/DJ-YAGICHAN-SYSTEM | ---
+++
@@ -1,2 +1,10 @@
+import { createBrowserHistory as createHistory, saga as router } from 'redux-tower';
+import routes from './routes'
+import { fork } from 'redux-saga/effects'
+
+const history = createHistory();
+
export default function* rootSaga() {
+ yield fork(router, {history, routes});
+
} |
73918b480e9f028b7884eec9658376788f07b6fc | src/js/menu.js | src/js/menu.js | (function() {
'use strict';
function Menu() {
this.titleTxt = null;
this.startTxt = null;
}
Menu.prototype = {
create: function () {
this.background = this.add.tileSprite(0, 0, this.world.width, this.world.height, 'background');
var text = 'Dodger\n\nClick to start'
, style = { font: '40px Arial', fill: '#ffffff', align: 'center' }
, t = this.add.text(this.game.world.centerX, this.game.world.centerY, text, style);
t.anchor.set(0.5, 0.5);
this.input.onDown.add(this.onDown, this);
},
update: function () {
this.background.tilePosition.y += 2;
},
onDown: function () {
this.game.state.start('game');
}
};
window['dodger'] = window['dodger'] || {};
window['dodger'].Menu = Menu;
}());
| (function() {
'use strict';
function Menu() {
this.titleTxt = null;
this.startTxt = null;
}
Menu.prototype = {
create: function () {
this.background = this.add.tileSprite(0, 0, this.world.width, this.world.height, 'background');
var text = 'Dodger'
, style = { font: '40px Arial', fill: '#ffffff', align: 'center' }
, t = this.add.text(this.game.world.centerX, this.game.world.centerY, text, style);
t.anchor.set(0.5, 0.5);
text = 'Click to start'
style = { font: '30px Arial', fill: '#ffffff', align: 'center' }
t = this.add.text(this.game.world.centerX, this.game.world.centerY + 80, text, style);
t.anchor.set(0.5, 0.5);
this.input.onDown.add(this.onDown, this);
},
update: function () {
this.background.tilePosition.y += 2;
},
onDown: function () {
this.game.state.start('game');
}
};
window['dodger'] = window['dodger'] || {};
window['dodger'].Menu = Menu;
}());
| Change text style for instructions | Change text style for instructions
| JavaScript | mit | cravesoft/dodger,cravesoft/dodger | ---
+++
@@ -11,9 +11,14 @@
create: function () {
this.background = this.add.tileSprite(0, 0, this.world.width, this.world.height, 'background');
- var text = 'Dodger\n\nClick to start'
+ var text = 'Dodger'
, style = { font: '40px Arial', fill: '#ffffff', align: 'center' }
, t = this.add.text(this.game.world.centerX, this.game.world.centerY, text, style);
+ t.anchor.set(0.5, 0.5);
+
+ text = 'Click to start'
+ style = { font: '30px Arial', fill: '#ffffff', align: 'center' }
+ t = this.add.text(this.game.world.centerX, this.game.world.centerY + 80, text, style);
t.anchor.set(0.5, 0.5);
this.input.onDown.add(this.onDown, this); |
69220b4c4c2ec3d4c24db037db0f5a0c7319299c | pairs.js | pairs.js | var People = new Mongo.Collection("people");
if (Meteor.isClient) {
Template.body.helpers({
people: function () {
return People.find({});
}
});
Template.body.events({
"submit .new-person": function (event) {
var commaSeparator = /\s*,\s*/;
var name = event.target.name.value;
var learning = event.target.learning.value.split(commaSeparator);
var teaching = event.target.teaching.value.split(commaSeparator);
People.insert({
name: name,
learning: learning,
teaching: teaching
});
event.target.name.value = "";
$(event.target.learning).clearOptions();
$(event.target.teaching).clearOptions();
return false;
}
});
$(document).ready(function () {
$('.input-list').selectize({
create: function (input) {
return {
value: input,
text: input
};
}
});
});
}
| var People = new Mongo.Collection("people");
if (Meteor.isClient) {
Template.body.helpers({
people: function () {
return People.find({});
}
});
Template.body.events({
"submit .new-person": function (event) {
var commaSeparator = /\s*,\s*/;
var name = event.target.name.value;
var learning = event.target.learning.value.split(commaSeparator);
var teaching = event.target.teaching.value.split(commaSeparator);
People.insert({
name: name,
learning: learning,
teaching: teaching
});
event.target.name.value = "";
$(event.target.learning).clearOptions();
$(event.target.teaching).clearOptions();
return false;
}
});
$(document).ready(function () {
$('.input-list').selectize({
create: function (input) {
return {
value: input,
text: input
};
},
plugins: [
'remove_button'
]
});
});
}
| Add remove buttons to selectize tags | Add remove buttons to selectize tags
| JavaScript | mit | paircolumbus/pairs,paircolumbus/pairs | ---
+++
@@ -36,7 +36,10 @@
value: input,
text: input
};
- }
+ },
+ plugins: [
+ 'remove_button'
+ ]
});
});
} |
27fbc59c87a41eebd9e6a4ebf0a7d87c0d3ba5f1 | lib/app/getBaseurl.js | lib/app/getBaseurl.js | /**
* Module dependencies
*/
var _ = require ('lodash');
/**
* Calculate the base URL (useful in emails, etc.)
* @return {String} [description]
*/
module.exports = function getBaseurl() {
var sails = this;
var usingSSL = sails.config.ssl && sails.config.ssl.key && sails.config.ssl.cert;
var host = sails.getHost() || 'localhost';
var port = sails.config.proxyPort || sails.config.port;
var probablyUsingSSL = (port === 443);
// If host doesn't contain `http*` already, include the protocol string.
var protocolString = '';
if (!_.contains(host,'http')) {
protocolString = ((usingSSL || probablyUsingSSL) ? 'https' : 'http') + '://';
}
var portString = (port === 80 || port === 443 ? '' : ':' + port);
var localAppURL = protocolString + host + portString;
return localAppURL;
};
| /**
* Module dependencies
*/
var _ = require ('lodash');
/**
* Calculate the base URL (useful in emails, etc.)
* @return {String} [description]
*/
module.exports = function getBaseurl() {
var sails = this;
var usingSSL = sails.config.ssl === true || (sails.config.ssl && ((sails.config.ssl.key && sails.config.ssl.cert) || sails.config.ssl.pfx));
var host = sails.getHost() || 'localhost';
var port = sails.config.proxyPort || sails.config.port;
var probablyUsingSSL = (port === 443);
// If host doesn't contain `http*` already, include the protocol string.
var protocolString = '';
if (!_.contains(host,'http')) {
protocolString = ((usingSSL || probablyUsingSSL) ? 'https' : 'http') + '://';
}
var portString = (port === 80 || port === 443 ? '' : ':' + port);
var localAppURL = protocolString + host + portString;
return localAppURL;
};
| Update logic in getBaseUrl determining if SSL is being used, to match http hook | Update logic in getBaseUrl determining if SSL is being used, to match http hook
| JavaScript | mit | jianpingw/sails,balderdashy/sails,Hanifb/sails,rlugojr/sails,rlugojr/sails,jianpingw/sails | ---
+++
@@ -15,7 +15,7 @@
module.exports = function getBaseurl() {
var sails = this;
- var usingSSL = sails.config.ssl && sails.config.ssl.key && sails.config.ssl.cert;
+ var usingSSL = sails.config.ssl === true || (sails.config.ssl && ((sails.config.ssl.key && sails.config.ssl.cert) || sails.config.ssl.pfx));
var host = sails.getHost() || 'localhost';
var port = sails.config.proxyPort || sails.config.port;
var probablyUsingSSL = (port === 443); |
8c499badf087794fc5d9f2109a6a2d64e03cb53d | frontend/app/models/release.js | frontend/app/models/release.js | import Model from 'ember-data/model';
import {belongsTo, hasMany} from 'ember-data/relationships';
import attr from 'ember-data/attr';
export default Model.extend({
artist: attr('string'),
title: attr('string'),
year: attr('number'),
genre: attr('string'),
company: attr('string'),
cpa: attr('string'),
arrivaldate: attr('date'),
local: attr('boolean'),
demo: attr('boolean'),
female: attr('boolean'),
compilation: attr('boolean'),
owner: attr('string'),
timestamp: attr('date'),
tracks: hasMany('track', {inverse: 'release'})
});
| import Model from 'ember-data/model';
import {belongsTo, hasMany} from 'ember-data/relationships';
import attr from 'ember-data/attr';
export default Model.extend({
artist: attr('string'),
title: attr('string'),
year: attr('number'),
genre: attr('string'),
company: attr('string'),
cpa: attr('string'),
arrivaldate: attr('date'),
local: attr('number'),
demo: attr('number'),
female: attr('number'),
compilation: attr('number'),
owner: attr('string'),
timestamp: attr('date'),
tracks: hasMany('track', {inverse: 'release'}),
isLocal: Ember.computed('local', function() {
if (this.get('local') == 1) {
return false;
}
else if (this.get('local') == 2) {
return 'Local';
}
else if (this.get('local') == 3) {
return 'Some Local';
}
}),
isFemale: Ember.computed('female', function() {
if (this.get('female') == 1) {
return false;
}
else if (this.get('female') == 2) {
return 'Female';
}
else if (this.get('female') == 3) {
return 'Some Female';
}
}),
isCompilation: Ember.computed('compilation', function() {
return this.get('compilation') != 1;
})
});
| Change some Release attributes to match the json. | Change some Release attributes to match the json.
| JavaScript | mit | ThreeDRadio/playlists,ThreeDRadio/playlists,ThreeDRadio/playlists | ---
+++
@@ -12,14 +12,42 @@
cpa: attr('string'),
arrivaldate: attr('date'),
- local: attr('boolean'),
- demo: attr('boolean'),
- female: attr('boolean'),
- compilation: attr('boolean'),
+ local: attr('number'),
+ demo: attr('number'),
+ female: attr('number'),
+ compilation: attr('number'),
owner: attr('string'),
timestamp: attr('date'),
- tracks: hasMany('track', {inverse: 'release'})
+ tracks: hasMany('track', {inverse: 'release'}),
+
+ isLocal: Ember.computed('local', function() {
+ if (this.get('local') == 1) {
+ return false;
+ }
+ else if (this.get('local') == 2) {
+ return 'Local';
+ }
+ else if (this.get('local') == 3) {
+ return 'Some Local';
+ }
+ }),
+
+ isFemale: Ember.computed('female', function() {
+ if (this.get('female') == 1) {
+ return false;
+ }
+ else if (this.get('female') == 2) {
+ return 'Female';
+ }
+ else if (this.get('female') == 3) {
+ return 'Some Female';
+ }
+ }),
+
+ isCompilation: Ember.computed('compilation', function() {
+ return this.get('compilation') != 1;
+ })
}); |
46f1cd6aed617e033ef0705c1b012a36d521f95c | src/js/Helpers/AccelerationLogic.js | src/js/Helpers/AccelerationLogic.js | import { translate, rand, vLog, objToArr, getR,
massToRadius, filterClose, vectorToString } from './VectorHelpers';
import { GRAVITY, PLANET_SPRING } from './Constants';
const getGravityAccel = (vR, mass) => {
const rMag2 = vR.lengthSq();
const rNorm = vR.normalize();
const accel = rNorm.multiplyScalar(GRAVITY * mass / rMag2);
return accel;
};
// const getCollisionAccel = (vR, m1, r1, r2) => {
// return vr.normalize().multiplyScalar(PLANET_SPRING / m1 * (vr.length() - (r1 + r2)));
// };
const getNetAccel = (originBody, otherBodies) => {
let netAccel = new THREE.Vector3();
let vR;
for (var i = 0; i < otherBodies.length; i++) {
vR = getR(originBody, otherBodies[i]);
netAccel.add(getGravityAccel(vR, otherBodies[i].mass))
}
return netAccel;
};
export {
getNetAccel,
}
| import { translate, rand, vLog, objToArr, getR,
massToRadius, filterClose, vectorToString } from './VectorHelpers';
import { GRAVITY, PLANET_SPRING } from './Constants';
const getGravityAccel = (vR, mass) => {
const rMag2 = vR.lengthSq();
const rNorm = vR.normalize();
return rNorm.multiplyScalar(GRAVITY * mass / rMag2);
};
const getCollisionAccel = (vR, m1, r1, r2) => {
return new THREE.Vector3(vR).normalize().multiplyScalar(PLANET_SPRING / m1 * (vR.length() - (r1 + r2)));
};
const getNetAccel = (originBody, otherBodies) => {
return otherBodies.reduce((netAccel, otherBody) => {
const vR = getR(originBody, otherBody);
if (vR.length() < originBody.radius + otherBody.radius) {
netAccel.add(getCollisionAccel(vR, originBody.mass, originBody.radius, otherBody.radius));
}
return netAccel.add(getGravityAccel(vR, otherBody.mass));
}, new THREE.Vector3());
};
export {
getNetAccel,
}
| Add code for collisions (untested) | Add code for collisions (untested)
| JavaScript | mit | elliotaplant/celestial-dance,elliotaplant/celestial-dance | ---
+++
@@ -5,22 +5,21 @@
const getGravityAccel = (vR, mass) => {
const rMag2 = vR.lengthSq();
const rNorm = vR.normalize();
- const accel = rNorm.multiplyScalar(GRAVITY * mass / rMag2);
- return accel;
+ return rNorm.multiplyScalar(GRAVITY * mass / rMag2);
};
-// const getCollisionAccel = (vR, m1, r1, r2) => {
-// return vr.normalize().multiplyScalar(PLANET_SPRING / m1 * (vr.length() - (r1 + r2)));
-// };
+const getCollisionAccel = (vR, m1, r1, r2) => {
+ return new THREE.Vector3(vR).normalize().multiplyScalar(PLANET_SPRING / m1 * (vR.length() - (r1 + r2)));
+};
const getNetAccel = (originBody, otherBodies) => {
- let netAccel = new THREE.Vector3();
- let vR;
- for (var i = 0; i < otherBodies.length; i++) {
- vR = getR(originBody, otherBodies[i]);
- netAccel.add(getGravityAccel(vR, otherBodies[i].mass))
- }
- return netAccel;
+ return otherBodies.reduce((netAccel, otherBody) => {
+ const vR = getR(originBody, otherBody);
+ if (vR.length() < originBody.radius + otherBody.radius) {
+ netAccel.add(getCollisionAccel(vR, originBody.mass, originBody.radius, otherBody.radius));
+ }
+ return netAccel.add(getGravityAccel(vR, otherBody.mass));
+ }, new THREE.Vector3());
};
export { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.