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 |
|---|---|---|---|---|---|---|---|---|---|---|
bc83a3b4a6b834e972cb2a723e692ec8491a290b | gulpfile.js | gulpfile.js | /**
* @author Frank David Corona Prendes <frankdavid.corona@gmail.com>
* @copyright MIT 2016 Frank David Corona Prendes
* @description Tarea Gulp para la compresion de ficheros JS
* @version 1.0.1
*/
(function () {
'use strict';
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var pump = require('pump');
var argv = require('yargs').argv;
var recursive = require('recursive-readdir');
var logger = require('gulp-logger');
gulp.task('gcompress', function () {
recursive('"' + [argv.source + '"' + '/**/*.js'], function (err, file) {
var options = {
mangle: false
};
pump([
gulp.src([argv.source + '/**/*.js'])
.pipe(logger({
before: 'Starting compression...',
after: 'Compression complete!',
showChange: true
}))
.pipe(uglify(options, uglify)),
gulp.dest(argv.destino + '/dist/')
]);
});
});
})();
| /**
* @author Frank David Corona Prendes <frankdavid.corona@gmail.com>
* @copyright MIT 2016 Frank David Corona Prendes
* @description Tarea Gulp para la compresion de ficheros JS
* @version 1.0.1
*/
(function () {
'use strict';
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var pump = require('pump');
var argv = require('yargs').argv;
var recursive = require('recursive-readdir');
var logger = require('gulp-logger');
gulp.task('default', function () {
recursive('"' + [argv.source + '"' + '/**/*.js'], function (err, file) {
var options = {
mangle: false
};
pump([
gulp.src([argv.source + '/**/*.js'])
.pipe(logger({
before: 'Starting compression...',
after: 'Compression complete!',
showChange: true
}))
.pipe(uglify(options, uglify)),
gulp.dest(argv.destino + '/dist/')
]);
});
});
})();
| Change name of the default task | Change name of the default task | JavaScript | mit | frankdavidcorona/gcompress | ---
+++
@@ -14,7 +14,7 @@
var recursive = require('recursive-readdir');
var logger = require('gulp-logger');
- gulp.task('gcompress', function () {
+ gulp.task('default', function () {
recursive('"' + [argv.source + '"' + '/**/*.js'], function (err, file) {
var options = {
mangle: false |
1e0b79aa7b62e3162b98c277db248236b75f3a4a | gulpfile.js | gulpfile.js | var gulp = require('gulp'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify');
var SRC = 'src/*.js';
var DEST = 'dist/';
gulp.task('build', function() {
gulp.src(SRC)
.pipe(concat('jsonapi-datastore.js'))
.pipe(gulp.dest(DEST))
.pipe(uglify())
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest(DEST));
});
gulp.task('default', ['build']);
| var gulp = require('gulp'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
mocha = require('gulp-mocha');
var SRC = 'src/*.js',
DEST = 'dist/';
gulp.task('build', function() {
gulp.src(SRC)
.pipe(concat('jsonapi-datastore.js'))
.pipe(gulp.dest(DEST))
.pipe(uglify())
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest(DEST));
});
gulp.task('test', ['build'], function() {
gulp.src('test/*.js')
.pipe(mocha());
});
gulp.task('default', ['build']);
| Add gulp task for testing. | Add gulp task for testing.
| JavaScript | mit | jamesdixon/jsonapi-datastore,niksy/jsonapi-datastore,beauby/jsonapi-datastore,jprincipe/jsonapi-datastore | ---
+++
@@ -1,10 +1,11 @@
var gulp = require('gulp'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
- uglify = require('gulp-uglify');
+ uglify = require('gulp-uglify'),
+ mocha = require('gulp-mocha');
-var SRC = 'src/*.js';
-var DEST = 'dist/';
+var SRC = 'src/*.js',
+ DEST = 'dist/';
gulp.task('build', function() {
gulp.src(SRC)
@@ -15,4 +16,9 @@
.pipe(gulp.dest(DEST));
});
+gulp.task('test', ['build'], function() {
+ gulp.src('test/*.js')
+ .pipe(mocha());
+});
+
gulp.task('default', ['build']); |
ffd4229e0940e26d7e4d5e948180c40bf14eb871 | lib/sandbox.js | lib/sandbox.js | /*
* Sandbox - A stripped down object of things that plugins can perform.
* This object will be passed to plugins on command and hook execution.
*/
Sandbox = function(irc, commands, usage) {
this.bot = {
say: function(to, msg) {
irc.say(to, msg);
},
action: function(to, msg) {
irc.action(to, msg);
},
commands: commands,
usage: usage
};
};
exports.Sandbox = Sandbox;
| var path = require('path');
/*
* Sandbox - A stripped down object of things that plugins can perform.
* This object will be passed to plugins on command and hook execution.
*/
Sandbox = function(irc, commands, usage) {
this.bot = {
say: function(to, msg) {
irc.say(to, msg);
},
action: function(to, msg) {
irc.action(to, msg);
},
commands: commands,
usage: usage
};
};
/*
* Update Sandbox.
*/
Sandbox.prototype.update = function(commands, usage) {
this.bot.commands = commands;
this.bot.usage = usage;
};
/*
* AdminSandbox - A less stripped down object of things that admin plugin
* can take advantage of.
*/
AdminSandbox = function(treslek) {
this.bot = {
say: function(to, msg) {
treslek.irc.say(to, msg);
},
action: function(to, msg) {
treslek.irc.action(to, msg);
},
join: function(channel, callback) {
treslek.irc.join(channel, callback);
},
part: function(channel, callback) {
treslek.irc.part(channel, callback);
},
load: function(plugin, callback) {
var pluginFile = path.resolve(treslek.conf.plugins_dir, plugin);
treslek.loadPlugin(pluginFile, function(err) {
callback();
});
},
reload: function(plugin, callback) {
var pluginFile = path.resolve(treslek.conf.plugins_dir, plugin);
if (!treslek.plugins.hasOwnProperty(pluginFile)) {
callback('Unknown plugin: ' + plugin);
return;
}
treslek.reloadPlugin(pluginFile, function(err) {
callback();
});
},
unload: function(plugin, callback) {
var pluginFile = path.resolve(treslek.conf.plugins_dir, plugin);
if (!treslek.plugins.hasOwnProperty(pluginFile)) {
callback('Unknown plugin: ' + plugin);
return;
}
treslek.unloadPlugin(pluginFile, function(err) {
callback();
});
},
ignore: function(nick) {
treslek.ignoreNick(nick);
},
unignore: function(nick) {
treslek.unignoreNick(nick);
}
};
};
exports.Sandbox = Sandbox;
exports.AdminSandbox = AdminSandbox;
| Add AdminSandbox for use with admin plugins. | Add AdminSandbox for use with admin plugins.
| JavaScript | mit | jirwin/treslek,rackerlabs/treslek | ---
+++
@@ -1,3 +1,5 @@
+var path = require('path');
+
/*
* Sandbox - A stripped down object of things that plugins can perform.
* This object will be passed to plugins on command and hook execution.
@@ -19,4 +21,76 @@
};
+/*
+ * Update Sandbox.
+ */
+Sandbox.prototype.update = function(commands, usage) {
+ this.bot.commands = commands;
+ this.bot.usage = usage;
+};
+
+
+/*
+ * AdminSandbox - A less stripped down object of things that admin plugin
+ * can take advantage of.
+ */
+AdminSandbox = function(treslek) {
+ this.bot = {
+ say: function(to, msg) {
+ treslek.irc.say(to, msg);
+ },
+ action: function(to, msg) {
+ treslek.irc.action(to, msg);
+ },
+
+ join: function(channel, callback) {
+ treslek.irc.join(channel, callback);
+ },
+ part: function(channel, callback) {
+ treslek.irc.part(channel, callback);
+ },
+
+ load: function(plugin, callback) {
+ var pluginFile = path.resolve(treslek.conf.plugins_dir, plugin);
+
+ treslek.loadPlugin(pluginFile, function(err) {
+ callback();
+ });
+ },
+ reload: function(plugin, callback) {
+ var pluginFile = path.resolve(treslek.conf.plugins_dir, plugin);
+
+ if (!treslek.plugins.hasOwnProperty(pluginFile)) {
+ callback('Unknown plugin: ' + plugin);
+ return;
+ }
+
+ treslek.reloadPlugin(pluginFile, function(err) {
+ callback();
+ });
+ },
+ unload: function(plugin, callback) {
+ var pluginFile = path.resolve(treslek.conf.plugins_dir, plugin);
+
+ if (!treslek.plugins.hasOwnProperty(pluginFile)) {
+ callback('Unknown plugin: ' + plugin);
+ return;
+ }
+
+ treslek.unloadPlugin(pluginFile, function(err) {
+ callback();
+ });
+ },
+
+ ignore: function(nick) {
+ treslek.ignoreNick(nick);
+ },
+ unignore: function(nick) {
+ treslek.unignoreNick(nick);
+ }
+ };
+};
+
+
exports.Sandbox = Sandbox;
+exports.AdminSandbox = AdminSandbox; |
d4b4d280ac3948dba4fe682deded95423e165685 | polyglot/src/test/resources/test-js-plugins/hello-interceptor.js | polyglot/src/test/resources/test-js-plugins/hello-interceptor.js | export const options = {
name: "helloWorldInterceptor",
description: "modifies the response of helloWorldService",
interceptPoint: "RESPONSE"
}
export function handle(req, res) {
LOGGER.debug('response {}', res.getContent());
const rc = JSON.parse(res.getContent() || '{}');
let modifiedBody = {
msg: rc.msg + ' from Italy with Love',
note: '\'from Italy with Love\' was added by \'helloWorldInterceptor\' that modifies the response of \'helloWorldService\''
}
res.setContent(JSON.stringify(modifiedBody));
res.setContentTypeAsJson();
}
export function resolve(req) {
return req.isHandledBy("helloWorldService") && req.isGet() && req.getContent();
} | export const options = {
name: "helloWorldInterceptor",
description: "modifies the response of helloWorldService",
interceptPoint: "RESPONSE"
}
export function handle(req, res) {
LOGGER.debug('response {}', res.getContent());
const rc = JSON.parse(res.getContent() || '{}');
let modifiedBody = {
msg: rc.msg + ' from Italy with Love',
note: '\'from Italy with Love\' was added by \'helloWorldInterceptor\' that modifies the response of \'helloWorldService\''
}
res.setContent(JSON.stringify(modifiedBody));
res.setContentTypeAsJson();
}
export function resolve(req) {
return req.isHandledBy("helloWorldService") && req.isGet() && req.getContent() !== null;
} | Fix resolve() on test js interceptor | :bug: Fix resolve() on test js interceptor [skip ci]
| JavaScript | agpl-3.0 | SoftInstigate/restheart,SoftInstigate/restheart,SoftInstigate/restheart,SoftInstigate/restheart | ---
+++
@@ -18,5 +18,5 @@
}
export function resolve(req) {
- return req.isHandledBy("helloWorldService") && req.isGet() && req.getContent();
+ return req.isHandledBy("helloWorldService") && req.isGet() && req.getContent() !== null;
} |
d1eb4d23bdf6d84a17a9ef7175f6901ca7f40178 | migrations/2_deploy_contracts.js | migrations/2_deploy_contracts.js | // var usingOraclize = artifacts.require("./usingOraclize.sol");
var Arbiter = artifacts.require("./Arbiter.sol");
var Judge = artifacts.require("./Judge.sol");
var ComputationService = artifacts.require("./ComputationService.sol");
module.exports = function(deployer) {
//deployer.deploy(usingOraclize);
//deployer.link(ConvertLib, MetaCoin);
var contracts = [];
// deploy one Arbiter
contracts.push(Arbiter);
// deploy one Judge
contracts.push(Judge);
// deploy six computation services
for (i = 0; i < 6; i++) {
contracts.push(ComputationService);
}
deployer.deploy(contracts);
};
| // var usingOraclize = artifacts.require("./usingOraclize.sol");
var Arbiter = artifacts.require("./Arbiter.sol");
var Judge = artifacts.require("./Judge.sol");
var ComputationService = artifacts.require("./ComputationService.sol");
module.exports = function(deployer) {
var arbiter, judge, computation;
deployer.deploy(Arbiter);
deployer.deploy(Judge);
deployer.then(function() {
return Judge.deployed();
}).then(function(instance) {
judge = instance;
return Arbiter.deployed();
}).then(function(instance) {
arbiter = instance;
return arbiter.setJudge(judge.address);
});
// deploy six computation services
for (i = 0; i < 6; i++) {
deployer.deploy(ComputationService);
deployer.then(function() {
return ComputationService.deployed();
}).then(function(instance) {
computation = instance;
return computation.registerOperation(0);
});
deployer.then(function() {
return Arbiter.deployed();
}).then(function(instance) {
arbiter = instance;
return ComputationService.deployed();
}).then(function(instance) {
computation = instance;
return computation.enableArbiter(arbiter.address);
});
}
};
| Include registratin of judge and services in arbiter | Include registratin of judge and services in arbiter
| JavaScript | mit | nud3l/verifying-computation-solidity,nud3l/verifying-computation-solidity | ---
+++
@@ -4,20 +4,40 @@
var ComputationService = artifacts.require("./ComputationService.sol");
module.exports = function(deployer) {
- //deployer.deploy(usingOraclize);
- //deployer.link(ConvertLib, MetaCoin);
- var contracts = [];
+ var arbiter, judge, computation;
- // deploy one Arbiter
- contracts.push(Arbiter);
+ deployer.deploy(Arbiter);
+ deployer.deploy(Judge);
- // deploy one Judge
- contracts.push(Judge);
+ deployer.then(function() {
+ return Judge.deployed();
+ }).then(function(instance) {
+ judge = instance;
+ return Arbiter.deployed();
+ }).then(function(instance) {
+ arbiter = instance;
+ return arbiter.setJudge(judge.address);
+ });
// deploy six computation services
for (i = 0; i < 6; i++) {
- contracts.push(ComputationService);
+ deployer.deploy(ComputationService);
+
+ deployer.then(function() {
+ return ComputationService.deployed();
+ }).then(function(instance) {
+ computation = instance;
+ return computation.registerOperation(0);
+ });
+
+ deployer.then(function() {
+ return Arbiter.deployed();
+ }).then(function(instance) {
+ arbiter = instance;
+ return ComputationService.deployed();
+ }).then(function(instance) {
+ computation = instance;
+ return computation.enableArbiter(arbiter.address);
+ });
}
-
- deployer.deploy(contracts);
}; |
a1354ce9155bb6609f56421033a5e889372d2b63 | tetris.js | tetris.js | var removeExcessSpaces = function(htmlString) {
var processedString = htmlString.replace(/\s+</g, '<');
processedString = processedString.replace(/>\s+/g, '>');
processedString = processedString.replace(/\:</g, ': <');
return processedString;
}
var ready = function(fn) {
if(document.readyState != 'loading') {
fn();
}
else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(function() {
document.querySelector('body').innerHTML = removeExcessSpaces(document.querySelector('body').innerHTML);
// Ensure the periodic table overlay is positioned correctly
var tableLeft = document.querySelector('#tetris-table').offsetLeft;
var tableTop = document.querySelector('#tetris-table').offsetTop;
document.querySelector('#table-overlay').style.left = tableLeft + 1 + 'px';
document.querySelector('#table-overlay').style.top = tableTop + 1 + 'px';
// This variable is global for the purposes of development and debugging
// Once the game is complete, remove the variable assignment
window.gameControl = new Controller();
});
| var removeExcessSpaces = function(htmlString) {
var processedString = htmlString.replace(/\s+</g, '<');
processedString = processedString.replace(/>\s+/g, '>');
processedString = processedString.replace(/_/g, ' ');
return processedString;
}
var ready = function(fn) {
if(document.readyState != 'loading') {
fn();
}
else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(function() {
document.querySelector('body').innerHTML = removeExcessSpaces(document.querySelector('body').innerHTML);
// Ensure the periodic table overlay is positioned correctly
var tableLeft = document.querySelector('#tetris-table').offsetLeft;
var tableTop = document.querySelector('#tetris-table').offsetTop;
document.querySelector('#table-overlay').style.left = tableLeft + 1 + 'px';
document.querySelector('#table-overlay').style.top = tableTop + 1 + 'px';
// This variable is global for the purposes of development and debugging
// Once the game is complete, remove the variable assignment
window.gameControl = new Controller();
});
| Update whitespace removal to convert underscores to spaces | Update whitespace removal to convert underscores to spaces
| JavaScript | mit | peternatewood/tetrelementis,RoyTuesday/tetrelementis,RoyTuesday/tetrelementis,peternatewood/tetrelementis | ---
+++
@@ -1,7 +1,7 @@
var removeExcessSpaces = function(htmlString) {
var processedString = htmlString.replace(/\s+</g, '<');
processedString = processedString.replace(/>\s+/g, '>');
- processedString = processedString.replace(/\:</g, ': <');
+ processedString = processedString.replace(/_/g, ' ');
return processedString;
}
|
b48f8416fd6637d7fce284ff4e47b01df4829d57 | src/core/AudioletParameter.js | src/core/AudioletParameter.js | var AudioletParameter = new Class({
initialize: function(node, inputIndex, value) {
this.node = node;
if (typeof inputIndex != 'undefined' && inputIndex != null) {
this.input = node.inputs[inputIndex];
}
else {
this.input = null;
}
this.value = value || 0;
},
isStatic: function() {
var input = this.input;
return (!(input &&
input.connectedFrom.length &&
!(input.buffer.isEmpty)));
},
isDynamic: function() {
var input = this.input;
return (input && input.connectedFrom.length && !(input.buffer.isEmpty));
},
setValue: function(value) {
this.value = value;
},
getValue: function() {
return this.value;
},
getChannel: function() {
return this.input.buffer.channels[0];
}
});
| var AudioletParameter = new Class({
initialize: function(node, inputIndex, value) {
this.node = node;
if (typeof inputIndex != 'undefined' && inputIndex != null) {
this.input = node.inputs[inputIndex];
}
else {
this.input = null;
}
this.value = value || 0;
},
isStatic: function() {
var input = this.input;
return (input == null ||
input.connectedFrom.length == 0 ||
input.buffer.isEmpty);
},
isDynamic: function() {
var input = this.input;
return (input != null &&
input.connectedFrom.length > 0 &&
!input.buffer.isEmpty);
},
setValue: function(value) {
this.value = value;
},
getValue: function() {
return this.value;
},
getChannel: function() {
return this.input.buffer.channels[0];
}
});
| Simplify isStatic and isDynamic logic, and make sure they return boolean values | Simplify isStatic and isDynamic logic, and make sure they return boolean values
| JavaScript | apache-2.0 | oampo/Audiolet,Kosar79/Audiolet,oampo/Audiolet,kn0ll/Audiolet,Kosar79/Audiolet,Kosar79/Audiolet,mcanthony/Audiolet,kn0ll/Audiolet,mcanthony/Audiolet,bobby-brennan/Audiolet,bobby-brennan/Audiolet | ---
+++
@@ -12,14 +12,16 @@
isStatic: function() {
var input = this.input;
- return (!(input &&
- input.connectedFrom.length &&
- !(input.buffer.isEmpty)));
+ return (input == null ||
+ input.connectedFrom.length == 0 ||
+ input.buffer.isEmpty);
},
isDynamic: function() {
var input = this.input;
- return (input && input.connectedFrom.length && !(input.buffer.isEmpty));
+ return (input != null &&
+ input.connectedFrom.length > 0 &&
+ !input.buffer.isEmpty);
},
setValue: function(value) { |
1935b925cc03c9e0d711b7e63c441580394e6d16 | addon-test-support/index.js | addon-test-support/index.js | import { getContext, settled } from '@ember/test-helpers';
import { run } from '@ember/runloop';
export function setBreakpoint(breakpoint) {
let breakpointArray = Array.isArray(breakpoint) ? breakpoint : [breakpoint];
let { owner } = getContext();
let breakpoints = owner.lookup('breakpoints:main');
let media = owner.lookup('service:media');
for (let breakpointName of breakpointArray) {
if (breakpointName === 'auto') {
media.set('_mocked', false);
return;
}
if (Object.keys(breakpoints).indexOf(breakpointName) === -1) {
throw new Error(`Breakpoint "${breakpointName}" is not defined in your breakpoints file`);
}
}
run(() => {
media.matches = breakpointArray;
media._triggerMediaChanged();
});
return settled();
}
| import { getContext, settled } from '@ember/test-helpers';
import { run } from '@ember/runloop';
export function setBreakpoint(breakpoint) {
let breakpointArray = Array.isArray(breakpoint) ? breakpoint : [breakpoint];
let { owner } = getContext();
let breakpoints = owner.lookup('breakpoints:main');
let media = owner.lookup('service:media');
for (let i = 0; i < breakpointArray.length; i++) {
let breakpointName = breakpointArray[i];
if (breakpointName === 'auto') {
media.set('_mocked', false);
return;
}
if (Object.keys(breakpoints).indexOf(breakpointName) === -1) {
throw new Error(`Breakpoint "${breakpointName}" is not defined in your breakpoints file`);
}
}
run(() => {
media.matches = breakpointArray;
media._triggerMediaChanged();
});
return settled();
}
| Make test support setBreakpoint IE11 compatible | Make test support setBreakpoint IE11 compatible
| JavaScript | mit | freshbooks/ember-responsive,freshbooks/ember-responsive | ---
+++
@@ -7,7 +7,8 @@
let breakpoints = owner.lookup('breakpoints:main');
let media = owner.lookup('service:media');
- for (let breakpointName of breakpointArray) {
+ for (let i = 0; i < breakpointArray.length; i++) {
+ let breakpointName = breakpointArray[i];
if (breakpointName === 'auto') {
media.set('_mocked', false);
return; |
c3a05985a25b38714e54de13c865f5322dc1b9d3 | examples/method_routing/server.js | examples/method_routing/server.js | var jayson = require(__dirname + '/../..');
var format = require('util').format;
var methods = {
// a method that prints every request
add: function(a, b, callback) {
callback(null, a + b);
}
};
var server = jayson.server(methods, {
router: function(method) {
// regular by-name routing first
if(typeof(this._methods[method]) === 'function') return this._methods[method];
if(method === 'add_2') return this._methods.add.bind(this, 2);
}
});
server.http().listen(3000);
| var jayson = require(__dirname + '/../..');
var format = require('util').format;
var methods = {
// a method that prints every request
add: function(a, b, callback) {
callback(null, a + b);
}
};
var server = jayson.server(methods, {
router: function(method) {
// regular by-name routing first
if(typeof(this._methods[method]) === 'function') return this._methods[method];
if(method === 'add_2') {
var fn = server.getMethod('add').getHandler();
return jayson.Method(fn.bind(null, 2));
}
}
});
server.http().listen(3000);
| Convert method routing example to new method definition | Convert method routing example to new method definition
| JavaScript | mit | taoyuan/jayson,Lughino/jayson,Meettya/jayson,tedeh/jayson,taoyuan/remjson,tedeh/jayson | ---
+++
@@ -12,7 +12,10 @@
router: function(method) {
// regular by-name routing first
if(typeof(this._methods[method]) === 'function') return this._methods[method];
- if(method === 'add_2') return this._methods.add.bind(this, 2);
+ if(method === 'add_2') {
+ var fn = server.getMethod('add').getHandler();
+ return jayson.Method(fn.bind(null, 2));
+ }
}
});
|
253d4358a60fb685b2e5583bb9a9245ed42ef140 | examples/method_routing/server.js | examples/method_routing/server.js | var jayson = require(__dirname + '/../..');
var format = require('util').format;
var methods = {
// a method that prints every request
add: function(a, b, callback) {
callback(null, a + b);
}
};
var server = jayson.server(methods, {
router: function(method) {
// regular by-name routing first
if(typeof(this._methods[method]) === 'function') return this._methods[method];
if(method === 'add_2') return this._methods.add.bind(this, 2);
}
});
server.http().listen(3000);
| var jayson = require(__dirname + '/../..');
var format = require('util').format;
var methods = {
// a method that prints every request
add: function(a, b, callback) {
callback(null, a + b);
}
};
var server = jayson.server(methods, {
router: function(method) {
// regular by-name routing first
if(typeof(this._methods[method]) === 'function') return this._methods[method];
if(method === 'add_2') {
var fn = server.getMethod('add').getHandler();
return jayson.Method(fn.bind(null, 2));
}
}
});
server.http().listen(3000);
| Convert method routing example to new method definition | Convert method routing example to new method definition
| JavaScript | mit | Meettya/jayson,tedeh/jayson,Lughino/jayson,taoyuan/jayson,tedeh/jayson,taoyuan/remjson | ---
+++
@@ -12,7 +12,10 @@
router: function(method) {
// regular by-name routing first
if(typeof(this._methods[method]) === 'function') return this._methods[method];
- if(method === 'add_2') return this._methods.add.bind(this, 2);
+ if(method === 'add_2') {
+ var fn = server.getMethod('add').getHandler();
+ return jayson.Method(fn.bind(null, 2));
+ }
}
});
|
627acdbfdeae585e449162fa15275df7ea270215 | src/js/ripple/utils.web.js | src/js/ripple/utils.web.js | var exports = module.exports = require('./utils.js');
// We override this function for browsers, because they print objects nicer
// natively than JSON.stringify can.
exports.logObject = function (msg, obj) {
if (/MSIE/.test(navigator.userAgent)) {
console.log(msg, JSON.stringify(obj));
} else {
console.log(msg, "", obj);
}
};
| var exports = module.exports = require('./utils.js');
// We override this function for browsers, because they print objects nicer
// natively than JSON.stringify can.
exports.logObject = function (msg, obj) {
var args = Array.prototype.slice.call(arguments, 1);
args = args.map(function(arg) {
if (/MSIE/.test(navigator.userAgent)) {
return JSON.stringify(arg, null, 2);
} else {
return arg;
}
});
args.unshift(msg);
console.log.apply(console, args);
};
| Update in-browser logging to accommodate n-args | Update in-browser logging to accommodate n-args
| JavaScript | isc | darkdarkdragon/ripple-lib,ripple/ripple-lib,ripple/ripple-lib,wilsonianb/ripple-lib,wilsonianb/ripple-lib,darkdarkdragon/ripple-lib,ripple/ripple-lib,darkdarkdragon/ripple-lib,wilsonianb/ripple-lib,ripple/ripple-lib | ---
+++
@@ -3,9 +3,17 @@
// We override this function for browsers, because they print objects nicer
// natively than JSON.stringify can.
exports.logObject = function (msg, obj) {
- if (/MSIE/.test(navigator.userAgent)) {
- console.log(msg, JSON.stringify(obj));
- } else {
- console.log(msg, "", obj);
- }
+ var args = Array.prototype.slice.call(arguments, 1);
+
+ args = args.map(function(arg) {
+ if (/MSIE/.test(navigator.userAgent)) {
+ return JSON.stringify(arg, null, 2);
+ } else {
+ return arg;
+ }
+ });
+
+ args.unshift(msg);
+
+ console.log.apply(console, args);
}; |
4b0c212b213b91fc37031c08aae5a30337728c79 | public/script.js | public/script.js | 'use strict';
/*
* Tanura demo app.
*
* This is the main script of the app demonstrating Tanura's features.
*/
/**
* Bootstrapping routine.
*/
window.onload = () => {
console.log("Initializing Tanura...");
tanura.init(
{video: true},
() => {
console.log("Initialized.");
// Example of how to handle Tanura's internally generated events.
tanura.eventHandler.register(
'resize',
() => console.log("Caught a resize."));
});
}
| 'use strict';
/*
* Tanura demo app.
*
* This is the main script of the app demonstrating Tanura's features.
*/
/**
* Bootstrapping routine.
*/
window.onload = () => {
console.log("Initializing Tanura...");
tanura.init(
{video: true},
() => {
console.log("Initialized.");
// Example of how to handle Tanura's internally generated events.
tanura.eventHandler.register(
'client_resized',
() => console.log("Caught a resize."));
});
}
| Use the new event names in the demo. | Use the new event names in the demo.
| JavaScript | agpl-3.0 | theOtherNuvanda/Tanura,theOtherNuvanda/Tanura,theOtherNuvanda/Tanura | ---
+++
@@ -18,7 +18,7 @@
// Example of how to handle Tanura's internally generated events.
tanura.eventHandler.register(
- 'resize',
+ 'client_resized',
() => console.log("Caught a resize."));
});
} |
1a024423c0ca91047eaeaa2d7fdc397d5a3b0635 | src/components/apply/SubmitButton.js | src/components/apply/SubmitButton.js | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import api from 'api'
import { LargeButton } from '@hackclub/design-system'
class SubmitButton extends Component {
static propTypes = {
status: PropTypes.oneOf(['incomplete', 'complete', 'submitted']).isRequired,
applicationId: PropTypes.number.isRequired,
callback: PropTypes.func
}
state = {
loading: false
}
handleSubmit = () => {
const { status, applicationId, callback } = this.props
this.setState({ loading: true })
// NOTE(@maxwofford): Give it 3 seconds of waiting to build up anticipation
if (status !== 'complete') return null
const startTime = Time.now
api
.post(`v1/new_club_applications/${applicationId}/submit`)
.then(json => {
callback(json)
})
.catch(e => {
alert(e.statusText)
})
.finally(_ => {
this.setState({ loading: false })
})
}
render() {
const { status } = this.props
const { loading } = this.state
return (
<LargeButton
onClick={this.handleSubmit}
bg={loading ? 'black' : status === 'submitted' ? 'success' : 'primary'}
disabled={status !== 'complete' || loading}
w={1}
mt={2}
mb={4}
f={3}
children={
status === 'submitted'
? 'We’ve recieved your application'
: 'Submit your application'
}
/>
)
}
}
export default SubmitButton
| import React, { Component } from 'react'
import PropTypes from 'prop-types'
import api from 'api'
import { LargeButton } from '@hackclub/design-system'
class SubmitButton extends Component {
static propTypes = {
status: PropTypes.oneOf(['incomplete', 'complete', 'submitted']).isRequired,
applicationId: PropTypes.number.isRequired,
callback: PropTypes.func
}
state = {
loading: false
}
handleSubmit = () => {
const { status, applicationId, callback } = this.props
this.setState({ loading: true })
if (status !== 'complete') return null
// NOTE(@maxwofford): Give it 3 seconds of waiting to build up anticipation
setTimeout(() => {
api
.post(`v1/new_club_applications/${applicationId}/submit`)
.then(json => {
callback(json)
})
.catch(e => {
alert(e.statusText)
})
.finally(_ => {
this.setState({ loading: false })
})
}, 3000)
}
render() {
const { status } = this.props
const { loading } = this.state
return (
<LargeButton
onClick={this.handleSubmit}
bg={loading ? 'black' : status === 'submitted' ? 'success' : 'primary'}
disabled={status !== 'complete' || loading}
w={1}
mt={2}
mb={4}
f={3}
children={
status === 'submitted'
? 'We’ve recieved your application'
: 'Submit your application'
}
/>
)
}
}
export default SubmitButton
| Add 3 second delay to application submission | Add 3 second delay to application submission
| JavaScript | mit | hackclub/website,hackclub/website,hackclub/website | ---
+++
@@ -16,20 +16,21 @@
handleSubmit = () => {
const { status, applicationId, callback } = this.props
this.setState({ loading: true })
+ if (status !== 'complete') return null
// NOTE(@maxwofford): Give it 3 seconds of waiting to build up anticipation
- if (status !== 'complete') return null
- const startTime = Time.now
- api
- .post(`v1/new_club_applications/${applicationId}/submit`)
- .then(json => {
- callback(json)
- })
- .catch(e => {
- alert(e.statusText)
- })
- .finally(_ => {
- this.setState({ loading: false })
- })
+ setTimeout(() => {
+ api
+ .post(`v1/new_club_applications/${applicationId}/submit`)
+ .then(json => {
+ callback(json)
+ })
+ .catch(e => {
+ alert(e.statusText)
+ })
+ .finally(_ => {
+ this.setState({ loading: false })
+ })
+ }, 3000)
}
render() { |
faa0e6ac15aca4dbae679cc20da587b4254f91ed | src/chrome/notification.js | src/chrome/notification.js | export class Notification {
/**
* @typedef NotificationOptions
* @property {string} title
* @property {string} message
* @property {('basic'|'sms')} [type='basic']
*/
/**
*
* @param {NotificationOptions} options
*/
constructor(options) {
this.read = false;
this.title = options.title;
this.message = options.message;
}
/**
* Converts the notification to a JSON object
* @return {object}
*/
toJSON() {
return {
read: false,
title: this.title,
message: this.message,
};
}
}
| export class Notification {
/**
* @typedef NotificationData
* @property {boolean} [read]
* @property {string} title
* @property {string} message
* @property {('basic'|'sms')} [type='basic']
*/
/**
*
* @param {NotificationData} data
*/
constructor(data) {
this.read = 'read' in data ? data.read : false;
this.title = data.title;
this.message = data.message;
}
/**
* Converts the notification to a JSON object
* @return {object}
*/
toJSON() {
return {
read: this.read,
title: this.title,
message: this.message,
};
}
static fromJSON(json) {
return new Notification(json);
}
}
| Add fromJSON, fix bug in toJSON | Add fromJSON, fix bug in toJSON
| JavaScript | mit | nextgensparx/quantum-router,nextgensparx/quantum-router | ---
+++
@@ -1,6 +1,7 @@
export class Notification {
/**
- * @typedef NotificationOptions
+ * @typedef NotificationData
+ * @property {boolean} [read]
* @property {string} title
* @property {string} message
* @property {('basic'|'sms')} [type='basic']
@@ -8,12 +9,12 @@
/**
*
- * @param {NotificationOptions} options
+ * @param {NotificationData} data
*/
- constructor(options) {
- this.read = false;
- this.title = options.title;
- this.message = options.message;
+ constructor(data) {
+ this.read = 'read' in data ? data.read : false;
+ this.title = data.title;
+ this.message = data.message;
}
/**
@@ -22,9 +23,13 @@
*/
toJSON() {
return {
- read: false,
+ read: this.read,
title: this.title,
message: this.message,
};
}
+
+ static fromJSON(json) {
+ return new Notification(json);
+ }
} |
067de672c56f6e61d0563bf2deac4a0b67a8f8e4 | src/components/apply/SubmitButton.js | src/components/apply/SubmitButton.js | import React, { Component } from 'react'
import api from 'api'
import storage from 'storage'
import { LargeButton } from '@hackclub/design-system'
class SubmitButton extends Component {
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit() {
const { status, applicationId, callback } = this.props
if (status !== 'complete') {
return null
}
api
.post(`v1/new_club_applications/${applicationId}/submit`, {
authToken: storage.get('authToken')
})
.then(json => {
callback(json)
alert('Your application has been submitted!')
})
.catch(e => {
alert(e.statusText)
})
}
render() {
// this.updateState() // I'm trying to update the update button state when an application is reset
const { status } = this.props
// incomplete, complete, submitted
return (
<LargeButton
onClick={this.handleSubmit}
bg={status === 'submitted' ? 'accent' : 'primary'}
disabled={status !== 'complete'}
w={1}
mb={2}
>
{status === 'submitted'
? 'We’ve recieved your application'
: 'Submit your application'}
</LargeButton>
)
}
}
export default SubmitButton
| import React, { Component } from 'react'
import api from 'api'
import storage from 'storage'
import { LargeButton } from '@hackclub/design-system'
class SubmitButton extends Component {
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit() {
const { status, applicationId, callback } = this.props
if (status !== 'complete') {
return null
}
api
.post(`v1/new_club_applications/${applicationId}/submit`, {
authToken: storage.get('authToken')
})
.then(json => {
callback(json)
})
.catch(e => {
alert(e.statusText)
})
}
render() {
// this.updateState() // I'm trying to update the update button state when an application is reset
const { status } = this.props
// incomplete, complete, submitted
return (
<LargeButton
onClick={this.handleSubmit}
bg={status === 'submitted' ? 'accent' : 'primary'}
disabled={status !== 'complete'}
w={1}
mb={2}
>
{status === 'submitted'
? 'We’ve recieved your application'
: 'Submit your application'}
</LargeButton>
)
}
}
export default SubmitButton
| Remove alert on application submission | Remove alert on application submission | JavaScript | mit | hackclub/website,hackclub/website,hackclub/website | ---
+++
@@ -22,7 +22,6 @@
})
.then(json => {
callback(json)
- alert('Your application has been submitted!')
})
.catch(e => {
alert(e.statusText) |
87fd189a152a926ba4a5b66bcdc70f09e7e6f6ec | js/turducken.js | js/turducken.js | "use strict";
function User( fName, lName) {
this.fName = fName;
this.lName = lName;
//this.img = img; //need to add images and urls...
this.posts = [];
}
User.prototype.newPost = function( content, socMedia ) {
this.posts.push( new Post( content, socMedia ));
}
function pushToLocalStorage( user ) {
var userString = JSON.stringify( user );
localStorage.setItem('user', userString);
console.log("pushed " + userString);
}
function getFromLocalStorage( ) {
var userString = localStorage.getItem('user');
var user = JSON.parse(userString);
if ( user ){
console.log( user.posts);
};
}
User.prototype.render = function() {
console.table( this.posts );
// var row = document.createElement( 'tr' );
// createCell( 'td', this.posts.content, row );
// for (var i = 0; i < times.length; i++) {
// createCell( 'td', this.posts.content, row );
// }
// table.appendChild( row );
}
// function createCell( cellType, content, row ) {
// var cell = document.createElement( cellType );
// cell.innerText = content;
// row.appendChild( cell );
// }
function Post( content, socMedia ){
this.content = content;
this.socMedia = socMedia;
this.time = new Date().getTime();
}
function init(){
populate();
bensonwigglepuff.render();
pushToLocalStorage( bensonwigglepuff );
getFromLocalStorage( bensonwigglepuff );
}
window.addEventListener("load", init);
| "use strict";
function User( fName, lName) {
this.fName = fName;
this.lName = lName;
//this.img = img; //need to add images and urls...
this.posts = [];
}
User.prototype.newPost = function( content, socMedia ) {
this.posts.push( new Post( content, socMedia ));
}
User.prototype.render = function() {
console.table( this.posts );
}
function Post( content, socMedia ){
this.content = content;
this.socMedia = socMedia;
this.time = new Date().getTime();
}
function pushToLocalStorage( user ) {
var userString = JSON.stringify( user );
localStorage.setItem('user', userString);
console.log("pushed " + userString);
}
function getFromLocalStorage( ) {
var userString = localStorage.getItem('user');
var user = JSON.parse(userString);
if ( user ){
console.log( user.posts);
};
}
function init(){
populate();
bensonwigglepuff.render();
pushToLocalStorage( bensonwigglepuff );
getFromLocalStorage( bensonwigglepuff );
}
window.addEventListener("load", init);
| Reorder functions to align with execution flow. | Reorder functions to align with execution flow.
| JavaScript | mit | sevfitz/turducken,sevfitz/turducken | ---
+++
@@ -9,6 +9,17 @@
User.prototype.newPost = function( content, socMedia ) {
this.posts.push( new Post( content, socMedia ));
+}
+
+
+User.prototype.render = function() {
+ console.table( this.posts );
+}
+
+function Post( content, socMedia ){
+ this.content = content;
+ this.socMedia = socMedia;
+ this.time = new Date().getTime();
}
function pushToLocalStorage( user ) {
@@ -27,27 +38,6 @@
};
}
-User.prototype.render = function() {
- console.table( this.posts );
-// var row = document.createElement( 'tr' );
-// createCell( 'td', this.posts.content, row );
-// for (var i = 0; i < times.length; i++) {
-// createCell( 'td', this.posts.content, row );
-// }
-// table.appendChild( row );
- }
-
-// function createCell( cellType, content, row ) {
-// var cell = document.createElement( cellType );
-// cell.innerText = content;
-// row.appendChild( cell );
-// }
-
-function Post( content, socMedia ){
- this.content = content;
- this.socMedia = socMedia;
- this.time = new Date().getTime();
-}
function init(){
populate(); |
8885b2f7712407d05d677b2c03822a40843509aa | js/calci.js | js/calci.js | $(document).ready(function() {
$('.key').click(function() {
var number = $(this).text();
$('#preview').append(number);
});
});
| function handleInput(key) {
$('#preview').append(key);
}
$(document).ready(function() {
$('.key').click(function() {
var key = $(this).text();
if(key == "0") {
if($('#preview').html() != "0") {
handleInput(key);
}
} else {
handleInput(key);
}
});
});
| Handle edge cases with zero key | Handle edge cases with zero key
| JavaScript | mit | CodeAstra/calculator,CodeAstra/calculator | ---
+++
@@ -1,6 +1,16 @@
+function handleInput(key) {
+ $('#preview').append(key);
+}
+
$(document).ready(function() {
$('.key').click(function() {
- var number = $(this).text();
- $('#preview').append(number);
+ var key = $(this).text();
+ if(key == "0") {
+ if($('#preview').html() != "0") {
+ handleInput(key);
+ }
+ } else {
+ handleInput(key);
+ }
});
}); |
bd87fe2da4bbf994ad72226de12c00ecf01223a2 | src/client/sendMessages.js | src/client/sendMessages.js | 'use strict';
/* This declares the function that will send a message
*/
function sendMessage(e) {
e.preventDefault();
const inputNode = e.target.message;
const message = inputNode.value;
console.log("Sending message:", message);
// Clear node
inputNode.value = '';
// Send the message
const xhr = new XMLHttpRequest();
xhr.onload = (e) => {
const response = xhr.response;
console.log(response);
}
xhr.addEventListener("error", (e) => {
console.log(e);
});
xhr.open("POST", config.hostUrl);
xhr.setRequestHeader("Content-type", "text/plain");
xhr.send(message);
}
function initializeForm() {
const form = document.getElementsByTagName('form')[0];
form.addEventListener('submit', sendMessage);
}
initializeForm();
| 'use strict';
/* This declares the function that will send a message
*/
function sendMessage(e) {
e.preventDefault();
const inputNode = e.target.message;
const message = inputNode.value + '\n';
console.log("Sending message:", message);
// Clear node
inputNode.value = '';
// Send the message
const xhr = new XMLHttpRequest();
xhr.onload = (e) => {
const response = xhr.response;
console.log(response);
}
xhr.addEventListener("error", (e) => {
console.log(e);
});
xhr.open("POST", config.hostUrl);
xhr.setRequestHeader("Content-type", "text/plain");
xhr.send(message);
}
function initializeForm() {
const form = document.getElementsByTagName('form')[0];
form.addEventListener('submit', sendMessage);
}
initializeForm();
| Add newline to all sent messages | Add newline to all sent messages
| JavaScript | mit | The1502Initiative/Instantaneous,The1502Initiative/Instantaneous,The1502Initiative/Instantaneous | ---
+++
@@ -5,7 +5,7 @@
function sendMessage(e) {
e.preventDefault();
const inputNode = e.target.message;
- const message = inputNode.value;
+ const message = inputNode.value + '\n';
console.log("Sending message:", message);
// Clear node
inputNode.value = ''; |
f262509674196d05fc929b5b7c111a3a66f6f92c | app/actions/asyncActions.js | app/actions/asyncActions.js | import AsyncQueue from '../utils/asyncQueueStructures';
let asyncQueue = new AsyncQueue();
const endAsync = () => {
return { type: 'ASYNC_INACTIVE' };
};
const callAsync = (dispatchFn, delay = 500, dispatchEnd, newState) => {
if (!asyncQueue.size) {
asyncQueue.listenForEnd(dispatchEnd);
}
asyncQueue.add(dispatchFn, delay, newState);
return { type: 'ASYNC_ACTIVE' };
};
const setDelay = (newDelay) => {
return {
type: 'SET_DELAY',
newDelay
};
};
export default {
callAsync,
endAsync,
setDelay
};
| import AsyncQueue from '../utils/asyncQueueStructures';
let asyncQueue = new AsyncQueue();
const endAsync = () => ({ type: 'ASYNC_INACTIVE' });
const startAsync = () => ({ type: 'ASYNC_ACTIVE' });
const callAsync = (dispatchFn, newState) => (dispatch, getState) => {
if (!asyncQueue.size) {
asyncQueue.listenForEnd(dispatch.bind(null, endAsync));
}
asyncQueue.add(dispatchFn, getState().async.delay, newState);
dispatch(startAsync());
};
const setDelay = (newDelay) => {
return {
type: 'SET_DELAY',
newDelay
};
};
export default {
callAsync,
endAsync,
setDelay,
startAsync
};
| Use thunx to access delay state | Use thunx to access delay state
| JavaScript | mit | ivtpz/brancher,ivtpz/brancher | ---
+++
@@ -2,16 +2,16 @@
let asyncQueue = new AsyncQueue();
-const endAsync = () => {
- return { type: 'ASYNC_INACTIVE' };
-};
+const endAsync = () => ({ type: 'ASYNC_INACTIVE' });
-const callAsync = (dispatchFn, delay = 500, dispatchEnd, newState) => {
+const startAsync = () => ({ type: 'ASYNC_ACTIVE' });
+
+const callAsync = (dispatchFn, newState) => (dispatch, getState) => {
if (!asyncQueue.size) {
- asyncQueue.listenForEnd(dispatchEnd);
+ asyncQueue.listenForEnd(dispatch.bind(null, endAsync));
}
- asyncQueue.add(dispatchFn, delay, newState);
- return { type: 'ASYNC_ACTIVE' };
+ asyncQueue.add(dispatchFn, getState().async.delay, newState);
+ dispatch(startAsync());
};
const setDelay = (newDelay) => {
@@ -24,5 +24,6 @@
export default {
callAsync,
endAsync,
- setDelay
+ setDelay,
+ startAsync
}; |
07f4d6e7ab4899cb1b85f12e9b0b05c0c0171341 | src/community/community.js | src/community/community.js | import sqlite from 'sqlite'
import winston from 'winston'
export default class Community {
static async init() {
if (this.db) { return }
this.db = await sqlite.open('/data/community.sqlite3').catch(winston.error)
await this.db
.run('CREATE TABLE IF NOT EXISTS villagers (guildId INTEGER, userId INTEGER, bnetServer TEXT, bnetId TEXT, PRIMARY KEY(guildId, userId, bnetServer))')
.catch(winston.error)
}
}
| import sqlite from 'sqlite'
import winston from 'winston'
export default class Community {
static async init() {
if (this.db) { return }
this.db = await sqlite.open('/data/community.sqlite3').catch(winston.error)
await this.db
.run('CREATE TABLE IF NOT EXISTS villagers (guildId INTEGER, userId INTEGER, bnetServer TEXT, bnetId TEXT, PRIMARY KEY(guildId, userId, bnetServer))')
.catch(winston.error)
await this.db
.run('CREATE TABLE IF NOT EXISTS quests (guildId INTEGER, userId INTEGER, bnetServer TEXT, bnetId TEXT, createdAt INTEGER, PRIMARY KEY(guildId, userId, bnetServer))')
.catch(winston.error)
setTimeout(async () => { await this.dropOldQuests() }, (10 * 60 * 1000))
}
static async dropOldQuests() {
winston.verbose('Auto-deleting quests that more than 1 day old.')
const oneDayAgo = new Date()
oneDayAgo.setDate(oneDayAgo.getDate() + 1)
const oldestTimestamp = Math.floor(oneDayAgo / 1000)
await this.db.all('DELETE FROM quests WHERE createdAt < ?', oldestTimestamp)
}
}
| Add automated, timed removal of quests | Add automated, timed removal of quests
| JavaScript | mit | tinnvec/stonebot,tinnvec/stonebot | ---
+++
@@ -8,5 +8,17 @@
await this.db
.run('CREATE TABLE IF NOT EXISTS villagers (guildId INTEGER, userId INTEGER, bnetServer TEXT, bnetId TEXT, PRIMARY KEY(guildId, userId, bnetServer))')
.catch(winston.error)
+ await this.db
+ .run('CREATE TABLE IF NOT EXISTS quests (guildId INTEGER, userId INTEGER, bnetServer TEXT, bnetId TEXT, createdAt INTEGER, PRIMARY KEY(guildId, userId, bnetServer))')
+ .catch(winston.error)
+ setTimeout(async () => { await this.dropOldQuests() }, (10 * 60 * 1000))
+ }
+
+ static async dropOldQuests() {
+ winston.verbose('Auto-deleting quests that more than 1 day old.')
+ const oneDayAgo = new Date()
+ oneDayAgo.setDate(oneDayAgo.getDate() + 1)
+ const oldestTimestamp = Math.floor(oneDayAgo / 1000)
+ await this.db.all('DELETE FROM quests WHERE createdAt < ?', oldestTimestamp)
}
} |
55c074a2c627187327dd98800d9524a9e725cb95 | src/components/HomePage.js | src/components/HomePage.js | import React from 'react';
import {browserHistory} from 'react-router'
import Login from './Login';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../actions/LoginActions';
import {AUTHENTICATED, DEFAULT, ERROR, LOADING} from '../constants/loginStates'
export const HomePage = (props) => {
let onLogin = phone => {
props.actions.login(phone)
}
console.log(props.loginState)
if (props.loginState === AUTHENTICATED) {
browserHistory.push('/status')
}
return (
<div>
<Login error={props.errorMessage} onClick={onLogin}/>
</div>
);
};
function mapStateToProps(state, ownprops) {
const errorMessage = 'Login failed try again'
return {
data: state.loginReducer,
loginState: state.loginReducer.loginState,
errorMessage: state.loginReducer.loginState === ERROR ? errorMessage : null
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(HomePage); | import React from 'react';
import {browserHistory} from 'react-router'
import Login from './Login';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../actions/LoginActions';
import {AUTHENTICATED, DEFAULT, ERROR, LOADING} from '../constants/loginStates'
import CircularProgress from 'material-ui/CircularProgress';
export const HomePage = (props) => {
let onLogin = phone => {
props.actions.login(phone)
}
console.log(props.loginState)
if (props.loginState === AUTHENTICATED) {
browserHistory.push('/status')
}
return (
<div>
<div style={props.spinnerStyles}>
<CircularProgress />
</div>
<Login error={props.errorMessage} onClick={onLogin}/>
</div>
);
};
function mapStateToProps(state, ownprops) {
const errorMessage = 'Login failed try again'
return {
data: state.loginReducer,
loginState: state.loginReducer.loginState,
errorMessage: state.loginReducer.loginState === ERROR ? errorMessage : null,
spinnerStyles: {
display: state.loginReducer.loginState === LOADING ? 'block' : 'hidden'
}
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(HomePage); | Add spinner when loggin in | Add spinner when loggin in
| JavaScript | mit | nathejk/status-app,nathejk/status-app | ---
+++
@@ -5,6 +5,7 @@
import {bindActionCreators} from 'redux';
import * as actions from '../actions/LoginActions';
import {AUTHENTICATED, DEFAULT, ERROR, LOADING} from '../constants/loginStates'
+import CircularProgress from 'material-ui/CircularProgress';
export const HomePage = (props) => {
@@ -19,6 +20,9 @@
return (
<div>
+ <div style={props.spinnerStyles}>
+ <CircularProgress />
+ </div>
<Login error={props.errorMessage} onClick={onLogin}/>
</div>
);
@@ -29,8 +33,11 @@
return {
data: state.loginReducer,
loginState: state.loginReducer.loginState,
- errorMessage: state.loginReducer.loginState === ERROR ? errorMessage : null
- };
+ errorMessage: state.loginReducer.loginState === ERROR ? errorMessage : null,
+ spinnerStyles: {
+ display: state.loginReducer.loginState === LOADING ? 'block' : 'hidden'
+ }
+ }
}
function mapDispatchToProps(dispatch) { |
443c0f43039d6fd1fda9760d5fb2570f2a930ebd | packages/stockflux-watchlist/public/notificationHandler.js | packages/stockflux-watchlist/public/notificationHandler.js | /*eslint-disable-next-line no-unused-vars*/
function onNotificationMessage(message) {
document.getElementById('symbol').innerHTML = message.symbol;
document.getElementById('message').innerHTML = message.messageText;
document.getElementById('watchlist-name').innerHTML = message.watchlistName
? ' ' + message.watchlistName + ' '
: ' ';
const imageSrc = message.alreadyInWatchlist ? 'ArrowUp.png' : 'CardIcon.png';
const image = document.getElementById('icon');
image.src = imageSrc;
image.className = message.alreadyInWatchlist ? 'arrow-up' : 'card-icon';
}
| // eslint-disable-next-line no-unused-vars
function onNotificationMessage(message) {
document.getElementById('symbol').innerHTML = message.symbol;
document.getElementById('message').innerHTML = message.messageText;
document.getElementById('watchlist-name').innerHTML = message.watchlistName
? ' ' + message.watchlistName + ' '
: ' ';
const imageSrc = message.alreadyInWatchlist ? 'ArrowUp.png' : 'CardIcon.png';
const image = document.getElementById('icon');
image.src = imageSrc;
image.className = message.alreadyInWatchlist ? 'arrow-up' : 'card-icon';
}
| Change multi-line comment to single-line | Change multi-line comment to single-line
| JavaScript | mit | owennw/OpenFinD3FC,ScottLogic/bitflux-openfin,owennw/OpenFinD3FC,ScottLogic/StockFlux,ScottLogic/StockFlux,ScottLogic/bitflux-openfin | ---
+++
@@ -1,4 +1,4 @@
-/*eslint-disable-next-line no-unused-vars*/
+// eslint-disable-next-line no-unused-vars
function onNotificationMessage(message) {
document.getElementById('symbol').innerHTML = message.symbol;
document.getElementById('message').innerHTML = message.messageText; |
aa94224f57fcd86704ff01ee1c7af299a75c95f8 | lib/services/alter-items.js | lib/services/alter-items.js |
const errors = require('@feathersjs/errors');
const getItems = require('./get-items');
const replaceItems = require('./replace-items');
module.exports = function (func) {
if (!func) {
func = () => {};
}
if (typeof func !== 'function') {
throw new errors.BadRequest('Function required. (alter)');
}
return context => {
let items = getItems(context);
const isArray = Array.isArray(items);
(isArray ? items : [items]).forEach(
(item, index) => {
const result = func(item, context);
if (result != null) {
if (isArray) {
items[index] = result;
} else {
items = result;
}
}
}
);
const isDone = replaceItems(context, items);
if (!isDone || typeof isDone.then !== 'function') {
return context;
}
return isDone.then(() => context);
};
};
|
const errors = require('@feathersjs/errors');
const getItems = require('./get-items');
const replaceItems = require('./replace-items');
module.exports = function (func) {
if (!func) {
func = () => {};
}
if (typeof func !== 'function') {
throw new errors.BadRequest('Function required. (alter)');
}
return context => {
let items = getItems(context);
const isArray = Array.isArray(items);
(isArray ? items : [items]).forEach(
(item, index) => {
const result = func(item, context);
if (typeof result === 'object' && result !== null) {
if (isArray) {
items[index] = result;
} else {
items = result;
}
}
}
);
const isDone = replaceItems(context, items);
if (!isDone || typeof isDone.then !== 'function') {
return context;
}
return isDone.then(() => context);
};
};
| Improve alterItems: better null-check for the returned value | Improve alterItems: better null-check for the returned value
| JavaScript | mit | feathersjs/feathers-hooks-common | ---
+++
@@ -18,7 +18,7 @@
(isArray ? items : [items]).forEach(
(item, index) => {
const result = func(item, context);
- if (result != null) {
+ if (typeof result === 'object' && result !== null) {
if (isArray) {
items[index] = result;
} else { |
ffb497ac013b005aff799cb4523e9b772519636b | connectors/amazon-alexa.js | connectors/amazon-alexa.js | 'use strict';
Connector.playerSelector = '#d-content';
Connector.getArtistTrack = () => {
if (isPlayingLiveRadio()) {
let songTitle = $('.d-queue-info .song-title').text();
return Util.splitArtistTrack(songTitle);
}
let artist = $('#d-info-text .d-sub-text-1').text();
let track = $('#d-info-text .d-main-text').text();
return { artist, track };
};
Connector.albumSelector = '#d-info-text .d-sub-text-2';
Connector.isPlaying = () => $('#d-primary-control .play').size() === 0;
function isPlayingLiveRadio() {
return $('#d-secondary-control-left .disabled').size() === 1 &&
$('#d-secondary-control-right .disabled').size() === 1;
}
| 'use strict';
Connector.playerSelector = '#d-content';
Connector.remainingTimeSelector = '.d-np-time-display.remaining-time';
Connector.currentTimeSelector = '.d-np-time-display.elapsed-time';
Connector.getDuration = () => {
let elapsed = Util.stringToSeconds($(Connector.currentTimeSelector).text());
let remaining = -Util.stringToSeconds($(Connector.remainingTimeSelector).text());
return (remaining + elapsed);
};
Connector.getRemainingTime = () => {
let remaining = -Util.stringToSeconds($(Connector.remainingTimeSelector).text());
return remaining;
};
Connector.getArtistTrack = () => {
if (isPlayingLiveRadio()) {
let songTitle = $('.d-queue-info .song-title').text();
return Util.splitArtistTrack(songTitle);
}
let artist = $('#d-info-text .d-sub-text-1').text();
let track = $('#d-info-text .d-main-text').text();
return { artist, track };
};
Connector.albumSelector = '#d-info-text .d-sub-text-2';
Connector.isPlaying = () => {
let songProgress = $('.d-np-progress-slider .d-slider-container .d-slider-track').attr('aria-valuenow');
let duration = Connector.getDuration();
// The app doesn't update the progress bar or time remaining straight away (and starts counting down from an hour). This is a workaround to avoid detecting an incorrect duration time.
if (duration > 3600 || songProgress == 100) {
return false;
}
return $('#d-primary-control .play').size() === 0;
}
function isPlayingLiveRadio() {
return $('#d-secondary-control-left .disabled').size() === 1 &&
$('#d-secondary-control-right .disabled').size() === 1;
}
| Add duration parsing to Amazon Alexa connector | Add duration parsing to Amazon Alexa connector
| JavaScript | mit | david-sabata/web-scrobbler,carpet-berlin/web-scrobbler,david-sabata/web-scrobbler,carpet-berlin/web-scrobbler,galeksandrp/web-scrobbler,galeksandrp/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,alexesprit/web-scrobbler,inverse/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,inverse/web-scrobbler,alexesprit/web-scrobbler | ---
+++
@@ -1,6 +1,19 @@
'use strict';
Connector.playerSelector = '#d-content';
+Connector.remainingTimeSelector = '.d-np-time-display.remaining-time';
+Connector.currentTimeSelector = '.d-np-time-display.elapsed-time';
+
+Connector.getDuration = () => {
+ let elapsed = Util.stringToSeconds($(Connector.currentTimeSelector).text());
+ let remaining = -Util.stringToSeconds($(Connector.remainingTimeSelector).text());
+ return (remaining + elapsed);
+};
+
+Connector.getRemainingTime = () => {
+ let remaining = -Util.stringToSeconds($(Connector.remainingTimeSelector).text());
+ return remaining;
+};
Connector.getArtistTrack = () => {
if (isPlayingLiveRadio()) {
@@ -15,7 +28,17 @@
Connector.albumSelector = '#d-info-text .d-sub-text-2';
-Connector.isPlaying = () => $('#d-primary-control .play').size() === 0;
+Connector.isPlaying = () => {
+ let songProgress = $('.d-np-progress-slider .d-slider-container .d-slider-track').attr('aria-valuenow');
+ let duration = Connector.getDuration();
+
+ // The app doesn't update the progress bar or time remaining straight away (and starts counting down from an hour). This is a workaround to avoid detecting an incorrect duration time.
+ if (duration > 3600 || songProgress == 100) {
+ return false;
+ }
+
+ return $('#d-primary-control .play').size() === 0;
+}
function isPlayingLiveRadio() {
return $('#d-secondary-control-left .disabled').size() === 1 && |
5fbfc2f76f3365c75ab2523d7807a4f3dc89a288 | omod/src/main/webapp/resources/scripts/services/visitService.js | omod/src/main/webapp/resources/scripts/services/visitService.js | angular.module('visitService', ['ngResource', 'uicommons.common'])
.factory('Visit', function($resource) {
return $resource("/" + OPENMRS_CONTEXT_PATH + "/ws/rest/v1/visit/:uuid", {
uuid: '@uuid'
},{
query: { method:'GET', isArray:false } // OpenMRS RESTWS returns { "results": [] }
});
})
.factory('VisitService', function(Visit) {
return {
/**
* Fetches Visits
*
* @param params to search against
* @returns $promise of array of matching Visits (REST ref representation by default)
*/
getVisits: function(params) {
return Visit.query(params).$promise.then(function(res) {
return res.results;
});
},
// if visit has uuid property this will update, else it will create new
saveVisit: function(visit) {
return new Visit(visit).$save();
}
}
}); | angular.module('visitService', ['ngResource', 'uicommons.common'])
.factory('Visit', function($resource) {
return $resource("/" + OPENMRS_CONTEXT_PATH + "/ws/rest/v1/visit/:uuid", {
uuid: '@uuid'
},{
query: { method:'GET', isArray:false } // OpenMRS RESTWS returns { "results": [] }
});
})
.factory('VisitService', function(Visit, $resource) {
return {
/**
* Fetches Visits
*
* @param params to search against
* @returns $promise of array of matching Visits (REST ref representation by default)
*/
getVisits: function(params) {
return Visit.query(params).$promise.then(function(res) {
return res.results;
});
},
// if visit has uuid property this will update, else it will create new
saveVisit: function(visit) {
return new Visit(visit).$save();
},
visitAttributeResourceFor: function(visit) {
return $resource("/" + OPENMRS_CONTEXT_PATH + "/ws/rest/v1/visit/:visitUuid/attribute/:uuid", {
visitUuid: visit.uuid,
uuid: '@uuid'
},{
query: { method:'GET', isArray:false } // OpenMRS RESTWS returns { "results": [] }
});
}
}
}); | Support accessing visit/attribute sub-resource via REST | Support accessing visit/attribute sub-resource via REST
| JavaScript | mpl-2.0 | jdegraft/openmrs-module-uicommons,yadamz/first-module,yadamz/first-module,jdegraft/openmrs-module-uicommons,jdegraft/openmrs-module-uicommons,yadamz/first-module,yadamz/first-module,jdegraft/openmrs-module-uicommons | ---
+++
@@ -6,7 +6,7 @@
query: { method:'GET', isArray:false } // OpenMRS RESTWS returns { "results": [] }
});
})
- .factory('VisitService', function(Visit) {
+ .factory('VisitService', function(Visit, $resource) {
return {
@@ -25,6 +25,15 @@
// if visit has uuid property this will update, else it will create new
saveVisit: function(visit) {
return new Visit(visit).$save();
+ },
+
+ visitAttributeResourceFor: function(visit) {
+ return $resource("/" + OPENMRS_CONTEXT_PATH + "/ws/rest/v1/visit/:visitUuid/attribute/:uuid", {
+ visitUuid: visit.uuid,
+ uuid: '@uuid'
+ },{
+ query: { method:'GET', isArray:false } // OpenMRS RESTWS returns { "results": [] }
+ });
}
}
}); |
4326d2baf1350e19c87db457a1e170e73bd0a11d | src/js/streams/stream-user.js | src/js/streams/stream-user.js | YUI.add("stream-user", function(Y) {
"use strict";
var falco = Y.namespace("Falco"),
streams = Y.namespace("Falco.Streams"),
User;
User = function() {};
User.prototype = {
_create : function() {
var stream;
stream = falco.twitter.stream("user", {
with : "followings"
});
stream.on("tweet", this._tweet.bind(this));
stream.on("friends", this._friends.bind(this));
this._stream = stream;
},
_tweet : function(data) {
this.fire("tweet", {
tweet : data,
src : "user"
});
},
_friends : function(data) {
this.fire("friends", data.friends.map(function(id) {
return {
id : id
};
}));
}
};
Y.augment(User, streams.Base);
streams.User = User;
streams.user = new User();
}, "@VERSION@", {
requires : [
// YUI
"oop",
"event-custom",
// Streams
"stream-base"
]
});
| YUI.add("stream-user", function(Y) {
"use strict";
var falco = Y.namespace("Falco"),
streams = Y.namespace("Falco.Streams"),
User;
User = function() {};
User.prototype = {
_create : function() {
var stream;
stream = falco.twitter.stream("user");
stream.on("tweet", this._tweet.bind(this));
stream.on("friends", this._friends.bind(this));
this._stream = stream;
},
_tweet : function(data) {
this.fire("tweet", {
tweet : data,
src : "user"
});
},
_friends : function(data) {
this.fire("friends", data.friends.map(function(id) {
return {
id : id
};
}));
}
};
Y.augment(User, streams.Base);
streams.User = User;
streams.user = new User();
}, "@VERSION@", {
requires : [
// YUI
"oop",
"event-custom",
// Streams
"stream-base"
]
});
| Remove unnecessary param, it's the default | Remove unnecessary param, it's the default
| JavaScript | mit | tivac/falco,tivac/falco | ---
+++
@@ -11,9 +11,7 @@
_create : function() {
var stream;
- stream = falco.twitter.stream("user", {
- with : "followings"
- });
+ stream = falco.twitter.stream("user");
stream.on("tweet", this._tweet.bind(this));
stream.on("friends", this._friends.bind(this)); |
c41ba3df26018ff84e6c5e73f06c7df36e508243 | src/js/utils/ValidatorUtil.js | src/js/utils/ValidatorUtil.js | var ValidatorUtil = {
isDefined: function (value) {
return value != null && value !== '' || typeof value === 'number';
},
isEmail: function (email) {
return email != null &&
email.length > 0 &&
!/\s/.test(email) &&
/.+@.+\..+/
.test(email);
},
isEmpty: function (data) {
if (typeof data === 'number' || typeof data === 'boolean') {
return false;
}
if (typeof data === 'undefined' || data === null) {
return true;
}
if (typeof data.length !== 'undefined') {
return data.length === 0;
}
return Object.keys(data).reduce(function (memo, key) {
if (data.hasOwnProperty(key)) {
memo++;
}
return memo;
}, 0) === 0;
},
isInteger: function (value) {
const number = parseFloat(value);
return Number.isInteger(number);
},
isNumber: function (value) {
const number = parseFloat(value);
return !Number.isNaN(number) && Number.isFinite(number);
},
isNumberInRange: function (value, range = {}) {
const {min = 0, max = Number.POSITIVE_INFINITY} = range;
const number = parseFloat(value);
return !Number.isNaN(number) && number >= min && number <= max;
}
};
module.exports = ValidatorUtil;
| var ValidatorUtil = {
isDefined: function (value) {
return value != null && value !== '' || typeof value === 'number';
},
isEmail: function (email) {
return email != null &&
email.length > 0 &&
!/\s/.test(email) &&
/.+@.+\..+/
.test(email);
},
isEmpty: function (data) {
if (typeof data === 'number' || typeof data === 'boolean') {
return false;
}
if (typeof data === 'undefined' || data === null) {
return true;
}
if (typeof data.length !== 'undefined') {
return data.length === 0;
}
return Object.keys(data).reduce(function (memo, key) {
if (data.hasOwnProperty(key)) {
memo++;
}
return memo;
}, 0) === 0;
},
isInteger: function (value) {
return ValidatorUtil.isNumber(value) &&
Number.isInteger(parseFloat(value));
},
isNumber: function (value) {
const number = parseFloat(value);
return !Number.isNaN(number) && Number.isFinite(number);
},
isNumberInRange: function (value, range = {}) {
const {min = 0, max = Number.POSITIVE_INFINITY} = range;
const number = parseFloat(value);
return ValidatorUtil.isNumber(value) && number >= min && number <= max;
}
};
module.exports = ValidatorUtil;
| Use is number util to test input | Use is number util to test input
| JavaScript | apache-2.0 | dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui | ---
+++
@@ -34,9 +34,8 @@
},
isInteger: function (value) {
- const number = parseFloat(value);
-
- return Number.isInteger(number);
+ return ValidatorUtil.isNumber(value) &&
+ Number.isInteger(parseFloat(value));
},
isNumber: function (value) {
@@ -49,7 +48,7 @@
const {min = 0, max = Number.POSITIVE_INFINITY} = range;
const number = parseFloat(value);
- return !Number.isNaN(number) && number >= min && number <= max;
+ return ValidatorUtil.isNumber(value) && number >= min && number <= max;
}
};
|
b7f8dfb12f79012e5ded0b14684ad75ae7dc1821 | lib/main.js | lib/main.js | // Define keyboard shortcuts for showing and hiding a custom panel.
var { Cc, Ci } = require("chrome");
var { Hotkey } = require("hotkeys");
var panel = require("panel");
var timers = require("timers");
var data = require("self").data;
var osString = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS;
var osWarnFile;
// Load the right warning
if (osString == "Darwin") {
osWarnFile = "warnmac.html";
} else {
osWarnFile = "warn.html";
}
// Create the panel to show the warning
var myPanel = panel.Panel({
width: 300,
height: 65,
contentURL: data.url(osWarnFile),
});
// Display the warning
function showPanel() {
myPanel.show();
timers.setTimeout(function() {
myPanel.hide();
}, 2000);
}
// Handle the keypress
var showHotKey = Hotkey({
combo: "accel-q",
onPress: function() {
// We're already showing the warning
if (myPanel.isShowing) {
myPanel.hide();
Cc['@mozilla.org/toolkit/app-startup;1']
.getService(Ci.nsIAppStartup)
.quit(Ci.nsIAppStartup.eAttemptQuit)
}
// Show the warning since we didn't quit yet
showPanel();
}
});
| // Define keyboard shortcuts for showing and hiding a custom panel.
var { Cc, Ci } = require("chrome");
var { Hotkey } = require("hotkeys");
var panel = require("panel");
var timers = require("timers");
var data = require("self").data;
var runtime = require("runtime");
var osString = runtime.OS;
var osWarnFile;
// Load the right warning
if (osString === "Darwin") {
osWarnFile = "warnmac.html";
} else {
osWarnFile = "warn.html";
}
// Create the panel to show the warning
var myPanel = panel.Panel({
width: 300,
height: 65,
contentURL: data.url(osWarnFile),
});
// Display the warning
function showPanel() {
myPanel.show();
timers.setTimeout(function() {
myPanel.hide();
}, 2000);
}
// Handle the keypress
var showHotKey = Hotkey({
combo: "accel-q",
onPress: function() {
// We're already showing the warning
if (myPanel.isShowing) {
myPanel.hide();
Cc['@mozilla.org/toolkit/app-startup;1']
.getService(Ci.nsIAppStartup)
.quit(Ci.nsIAppStartup.eAttemptQuit)
}
// Show the warning since we didn't quit yet
showPanel();
}
});
| Use the interface from add-on sdk for OS | Use the interface from add-on sdk for OS
| JavaScript | mit | rhelmer/warn-before-quit,rhelmer/warn-before-quit,nigelbabu/warn-before-quit,nigelbabu/warn-before-quit | ---
+++
@@ -4,11 +4,12 @@
var panel = require("panel");
var timers = require("timers");
var data = require("self").data;
-var osString = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS;
+var runtime = require("runtime");
+var osString = runtime.OS;
var osWarnFile;
// Load the right warning
-if (osString == "Darwin") {
+if (osString === "Darwin") {
osWarnFile = "warnmac.html";
} else {
osWarnFile = "warn.html"; |
a75fef48bfb440a22fdc9605d4e677b87ebf290f | local-cli/core/Constants.js | local-cli/core/Constants.js | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
const ASSET_REGISTRY_PATH = 'react-native/Libraries/Image/AssetRegistry';
module.exports = {ASSET_REGISTRY_PATH};
| /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
const ASSET_REGISTRY_PATH = 'react-native/Libraries/Image/AssetRegistry';
const ASSET_SOURCE_RESOLVER_PATH =
'react-native/Libraries/Image/AssetSourceResolver';
module.exports = {
ASSET_REGISTRY_PATH,
ASSET_SOURCE_RESOLVER_PATH,
};
| Add code for generating remote assets | Add code for generating remote assets
Reviewed By: davidaurelio
Differential Revision: D6201839
fbshipit-source-id: 78c81eae03c6137ba9bbe33cd7aab8b87020f8d2
| JavaScript | bsd-3-clause | jevakallio/react-native,Bhullnatik/react-native,exponentjs/react-native,facebook/react-native,ptmt/react-native-macos,ptmt/react-native-macos,pandiaraj44/react-native,hoastoolshop/react-native,pandiaraj44/react-native,kesha-antonov/react-native,facebook/react-native,hammerandchisel/react-native,hoangpham95/react-native,exponentjs/react-native,kesha-antonov/react-native,janicduplessis/react-native,arthuralee/react-native,facebook/react-native,janicduplessis/react-native,arthuralee/react-native,exponent/react-native,hoastoolshop/react-native,janicduplessis/react-native,hoastoolshop/react-native,exponent/react-native,exponentjs/react-native,dikaiosune/react-native,facebook/react-native,jevakallio/react-native,pandiaraj44/react-native,jevakallio/react-native,ptmt/react-native-macos,arthuralee/react-native,exponentjs/react-native,kesha-antonov/react-native,rickbeerendonk/react-native,arthuralee/react-native,exponentjs/react-native,myntra/react-native,dikaiosune/react-native,exponent/react-native,exponentjs/react-native,kesha-antonov/react-native,exponentjs/react-native,hoastoolshop/react-native,hoangpham95/react-native,kesha-antonov/react-native,cdlewis/react-native,dikaiosune/react-native,myntra/react-native,hoangpham95/react-native,rickbeerendonk/react-native,hammerandchisel/react-native,hoastoolshop/react-native,javache/react-native,pandiaraj44/react-native,cdlewis/react-native,hoangpham95/react-native,exponent/react-native,Bhullnatik/react-native,jevakallio/react-native,ptmt/react-native-macos,facebook/react-native,myntra/react-native,exponentjs/react-native,jevakallio/react-native,kesha-antonov/react-native,janicduplessis/react-native,hoastoolshop/react-native,janicduplessis/react-native,arthuralee/react-native,myntra/react-native,dikaiosune/react-native,hoangpham95/react-native,exponent/react-native,ptmt/react-native-macos,hammerandchisel/react-native,facebook/react-native,ptmt/react-native-macos,exponent/react-native,pandiaraj44/react-native,javache/react-native,rickbeerendonk/react-native,ptmt/react-native-macos,jevakallio/react-native,pandiaraj44/react-native,pandiaraj44/react-native,ptmt/react-native-macos,cdlewis/react-native,rickbeerendonk/react-native,hammerandchisel/react-native,cdlewis/react-native,Bhullnatik/react-native,myntra/react-native,janicduplessis/react-native,dikaiosune/react-native,kesha-antonov/react-native,facebook/react-native,myntra/react-native,Bhullnatik/react-native,hoangpham95/react-native,myntra/react-native,jevakallio/react-native,facebook/react-native,hammerandchisel/react-native,jevakallio/react-native,cdlewis/react-native,hoastoolshop/react-native,rickbeerendonk/react-native,dikaiosune/react-native,rickbeerendonk/react-native,Bhullnatik/react-native,janicduplessis/react-native,exponent/react-native,kesha-antonov/react-native,cdlewis/react-native,myntra/react-native,hammerandchisel/react-native,hoangpham95/react-native,rickbeerendonk/react-native,hammerandchisel/react-native,exponent/react-native,facebook/react-native,janicduplessis/react-native,cdlewis/react-native,Bhullnatik/react-native,javache/react-native,cdlewis/react-native,javache/react-native,javache/react-native,cdlewis/react-native,Bhullnatik/react-native,rickbeerendonk/react-native,Bhullnatik/react-native,myntra/react-native,kesha-antonov/react-native,dikaiosune/react-native,javache/react-native,pandiaraj44/react-native,hoangpham95/react-native,rickbeerendonk/react-native,hammerandchisel/react-native,javache/react-native,javache/react-native,dikaiosune/react-native,hoastoolshop/react-native,jevakallio/react-native,javache/react-native | ---
+++
@@ -13,5 +13,10 @@
'use strict';
const ASSET_REGISTRY_PATH = 'react-native/Libraries/Image/AssetRegistry';
+const ASSET_SOURCE_RESOLVER_PATH =
+ 'react-native/Libraries/Image/AssetSourceResolver';
-module.exports = {ASSET_REGISTRY_PATH};
+module.exports = {
+ ASSET_REGISTRY_PATH,
+ ASSET_SOURCE_RESOLVER_PATH,
+}; |
12bfc2fdd9c1574eb37a68dc7b8fa9508b082118 | lib/vector2d.js | lib/vector2d.js | class Vector2D {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(vec) {
return new Vector2D(this.x + vec.x, this.y + vec.y);
}
multiply(factor) {
return new Vector2D(this.x * factor, this.y * factor);
}
}
Vector2D.fromPolar = function(deg, len) {
let rad = deg * (180 / Math.PI),
xf = Math.round(Math.cos(rad) * 1000) / 1000,
yf = Math.round(Math.sin(rad) * 1000) / 1000;
return new Vector2D(xf, yf).multiply(len);
};
export default function Vecor2DFactory(...args) {
return new Vector2D(...args);
};
| class Vector2D {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(vec) {
return new Vector2D(this.x + vec.x, this.y + vec.y);
}
multiply(factor) {
return new Vector2D(this.x * factor, this.y * factor);
}
length() {
return Math.sqrt(this.x * this.x, this.y * this.y);
}
angle() {
return Math.atan2(this.y, this.x) * (180 / Math.PI);
}
toPolar() {
return [this.angle(), this.length()];
}
}
Vector2D.fromPolar = function(deg, len) {
let rad = deg / (180 / Math.PI),
xf = Math.round(Math.cos(rad) * 1000) / 1000,
yf = Math.round(Math.sin(rad) * 1000) / 1000;
return new Vector2D(xf, yf).multiply(len);
};
export default function Vecor2DFactory(...args) {
return new Vector2D(...args);
};
| Add more functionality to vectors | Add more functionality to vectors
| JavaScript | mit | 190n/five.js | ---
+++
@@ -11,10 +11,22 @@
multiply(factor) {
return new Vector2D(this.x * factor, this.y * factor);
}
+
+ length() {
+ return Math.sqrt(this.x * this.x, this.y * this.y);
+ }
+
+ angle() {
+ return Math.atan2(this.y, this.x) * (180 / Math.PI);
+ }
+
+ toPolar() {
+ return [this.angle(), this.length()];
+ }
}
Vector2D.fromPolar = function(deg, len) {
- let rad = deg * (180 / Math.PI),
+ let rad = deg / (180 / Math.PI),
xf = Math.round(Math.cos(rad) * 1000) / 1000,
yf = Math.round(Math.sin(rad) * 1000) / 1000;
return new Vector2D(xf, yf).multiply(len); |
29a464500056d1b0c80e4056139931cb77dacd53 | public/fastboot-is-mobile.js | public/fastboot-is-mobile.js | /* globals define, FastBoot */
(function() {
define('ismobilejs', ['exports'], function(exports) {
'use strict';
let isMobileClass = FastBoot.require('ismobilejs');
// Change the context so that when isMobile internally sets the results of
// the user agent tests to the current scope, it doesn't use the FastBoot
// global scope, which is full of unnecessary stuff.
return { default: isMobileClass.bind(exports) };
});
})(); | /* globals define, FastBoot */
(function() {
define('ismobilejs', ['exports'], function(exports) {
'use strict';
var isMobileClass = FastBoot.require('ismobilejs');
// Change the context so that when isMobile internally sets the results of
// the user agent tests to the current scope, it doesn't use the FastBoot
// global scope, which is full of unnecessary stuff.
return { default: isMobileClass.bind(exports) };
});
})(); | Fix strict mode typo in fastboot module export | Fix strict mode typo in fastboot module export
| JavaScript | mit | sandydoo/ember-is-mobile,sandydoo/ember-is-mobile | ---
+++
@@ -3,7 +3,7 @@
define('ismobilejs', ['exports'], function(exports) {
'use strict';
- let isMobileClass = FastBoot.require('ismobilejs');
+ var isMobileClass = FastBoot.require('ismobilejs');
// Change the context so that when isMobile internally sets the results of
// the user agent tests to the current scope, it doesn't use the FastBoot
// global scope, which is full of unnecessary stuff. |
fd5ee5b257ef44549c870abc620527dda9d4a358 | src/mm-action/mm-action.js | src/mm-action/mm-action.js | /**
* @license
* Copyright (c) 2015 MediaMath Inc. All rights reserved.
* This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt
*/
Polymer({
is: "mm-action",
behaviors: [
StrandTraits.Stylable
],
properties: {
ver:{
type:String,
value:"<<version>>",
},
href: {
type: String,
value: false,
reflectToAttribute: true
},
underline: {
type: Boolean,
value: false,
reflectToAttribute: true
},
target: {
type: String,
value: "_self",
reflectToAttribute: true
},
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true
}
},
PRIMARY_ICON_COLOR: Colors.D0,
ready: function() {
// if there is an icon - colorize it:
var items = Array.prototype.slice.call(Polymer.dom(this.$.icon).getDistributedNodes());
if (items.length) {
items[0].setAttribute("primary-color", this.PRIMARY_ICON_COLOR);
}
},
updateClass: function(underline) {
var o = {};
o["action"] = true;
o["underline"] = underline;
return this.classList(o);
}
}); | /**
* @license
* Copyright (c) 2015 MediaMath Inc. All rights reserved.
* This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt
*/
(function (scope) {
scope.Action = Polymer({
is: "mm-action",
behaviors: [
StrandTraits.Stylable
],
properties: {
ver:{
type:String,
value:"<<version>>",
},
href: {
type: String,
value: false,
reflectToAttribute: true
},
underline: {
type: Boolean,
value: false,
reflectToAttribute: true
},
target: {
type: String,
value: "_self",
reflectToAttribute: true
},
disabled: {
type: Boolean,
value: false,
reflectToAttribute: true
}
},
PRIMARY_ICON_COLOR: Colors.D0,
ready: function() {
// if there is an icon - colorize it:
var items = Array.prototype.slice.call(Polymer.dom(this.$.icon).getDistributedNodes());
if (items.length) {
items[0].setAttribute("primary-color", this.PRIMARY_ICON_COLOR);
}
},
updateClass: function(underline) {
var o = {};
o["action"] = true;
o["underline"] = underline;
return this.classList(o);
}
});
})(window.Strand = window.Strand || {}); | Add correct IIF and scope | Add correct IIF and scope
| JavaScript | bsd-3-clause | sassomedia/strand,anthonykoerber/strand,shuwen/strand,dlasky/strand,shuwen/strand,sassomedia/strand,anthonykoerber/strand,dlasky/strand | ---
+++
@@ -4,55 +4,59 @@
* This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt
*/
-Polymer({
- is: "mm-action",
+(function (scope) {
- behaviors: [
- StrandTraits.Stylable
- ],
+ scope.Action = Polymer({
+ is: "mm-action",
- properties: {
- ver:{
- type:String,
- value:"<<version>>",
+ behaviors: [
+ StrandTraits.Stylable
+ ],
+
+ properties: {
+ ver:{
+ type:String,
+ value:"<<version>>",
+ },
+ href: {
+ type: String,
+ value: false,
+ reflectToAttribute: true
+ },
+ underline: {
+ type: Boolean,
+ value: false,
+ reflectToAttribute: true
+ },
+ target: {
+ type: String,
+ value: "_self",
+ reflectToAttribute: true
+ },
+ disabled: {
+ type: Boolean,
+ value: false,
+ reflectToAttribute: true
+ }
},
- href: {
- type: String,
- value: false,
- reflectToAttribute: true
+
+ PRIMARY_ICON_COLOR: Colors.D0,
+
+ ready: function() {
+ // if there is an icon - colorize it:
+ var items = Array.prototype.slice.call(Polymer.dom(this.$.icon).getDistributedNodes());
+ if (items.length) {
+ items[0].setAttribute("primary-color", this.PRIMARY_ICON_COLOR);
+ }
},
- underline: {
- type: Boolean,
- value: false,
- reflectToAttribute: true
- },
- target: {
- type: String,
- value: "_self",
- reflectToAttribute: true
- },
- disabled: {
- type: Boolean,
- value: false,
- reflectToAttribute: true
+
+ updateClass: function(underline) {
+ var o = {};
+ o["action"] = true;
+ o["underline"] = underline;
+ return this.classList(o);
}
- },
- PRIMARY_ICON_COLOR: Colors.D0,
-
- ready: function() {
- // if there is an icon - colorize it:
- var items = Array.prototype.slice.call(Polymer.dom(this.$.icon).getDistributedNodes());
- if (items.length) {
- items[0].setAttribute("primary-color", this.PRIMARY_ICON_COLOR);
- }
- },
-
- updateClass: function(underline) {
- var o = {};
- o["action"] = true;
- o["underline"] = underline;
- return this.classList(o);
- }
-
-});
+ });
+
+})(window.Strand = window.Strand || {}); |
9b44e8f5367bf24b6d5c21d35f402bc0686c1383 | src/modules/Application.js | src/modules/Application.js | class GelatoApplication extends Backbone.Model {
constructor() {
Backbone.$('body').prepend('<gelato-application></gelato-application>');
Backbone.$('gelato-application').append('<gelato-dialogs></gelato-dialogs>');
Backbone.$('gelato-application').append('<gelato-navbar></gelato-navbar>');
Backbone.$('gelato-application').append('<gelato-pages></gelato-pages>');
Backbone.$('gelato-application').append('<gelato-footer></gelato-footer>');
super(arguments);
}
getHeight() {
return Backbone.$('gelato-application').height();
}
getWidth() {
return Backbone.$('gelato-application').width();
}
isLandscape() {
return this.getWidth() > this.getHeight();
}
isPortrait() {
return this.getWidth() <= this.getHeight();
}
reload(forcedReload) {
location.reload(forcedReload);
}
}
Gelato = Gelato || {};
Gelato.Application = GelatoApplication;
| class GelatoApplication extends Backbone.View {
constructor(options) {
options = options || {};
options.tagName = 'gelato-application';
super(options);
}
render() {
$(document.body).prepend(this.el);
this.$el.append('<gelato-navbar></gelato-navbar>');
this.$el.append('<gelato-pages></gelato-pages>');
this.$el.append('<gelato-footer></gelato-footer>');
this.$el.append('<gelato-dialogs></gelato-dialogs>');
return this;
}
getHeight() {
return Backbone.$('gelato-application').height();
}
getWidth() {
return Backbone.$('gelato-application').width();
}
isLandscape() {
return this.getWidth() > this.getHeight();
}
isPortrait() {
return this.getWidth() <= this.getHeight();
}
}
Gelato = Gelato || {};
Gelato.Application = GelatoApplication;
| Make application function more like a backbone view | Make application function more like a backbone view
| JavaScript | mit | jernung/gelato,jernung/gelato,mcfarljw/gelato-framework,mcfarljw/backbone-gelato,mcfarljw/backbone-gelato,mcfarljw/gelato-framework | ---
+++
@@ -1,13 +1,20 @@
-class GelatoApplication extends Backbone.Model {
+class GelatoApplication extends Backbone.View {
- constructor() {
- Backbone.$('body').prepend('<gelato-application></gelato-application>');
- Backbone.$('gelato-application').append('<gelato-dialogs></gelato-dialogs>');
- Backbone.$('gelato-application').append('<gelato-navbar></gelato-navbar>');
- Backbone.$('gelato-application').append('<gelato-pages></gelato-pages>');
- Backbone.$('gelato-application').append('<gelato-footer></gelato-footer>');
+ constructor(options) {
+ options = options || {};
+ options.tagName = 'gelato-application';
- super(arguments);
+ super(options);
+ }
+
+ render() {
+ $(document.body).prepend(this.el);
+ this.$el.append('<gelato-navbar></gelato-navbar>');
+ this.$el.append('<gelato-pages></gelato-pages>');
+ this.$el.append('<gelato-footer></gelato-footer>');
+ this.$el.append('<gelato-dialogs></gelato-dialogs>');
+
+ return this;
}
getHeight() {
@@ -26,10 +33,6 @@
return this.getWidth() <= this.getHeight();
}
- reload(forcedReload) {
- location.reload(forcedReload);
- }
-
}
Gelato = Gelato || {}; |
cc4f209f011639d4f6888a39e71b1145e58cf5c5 | src/route/changelogs.js | src/route/changelogs.js | const router = require('express').Router();
const scraper = require('../service/scraper');
router.get('/', (req, res, next) => {
const packageName = req.query.package;
if (!packageName) {
const err = new Error('Undefined query');
err.satus = 404;
next(err);
}
scraper
.scan(packageName)
.then(result => {
const changes = result.changes;
res.json({ packageName, changes });
})
.catch(error => {
const err = new Error('Could not request info');
err.status = 404;
next(err);
});
});
module.exports = router;
| const router = require('express').Router();
const scraper = require('../service/scraper');
router.get('/:package/latest', (req, res, next) => {
const packageName = req.params.package;
if (!packageName) {
const err = new Error('Undefined query');
err.satus = 404;
next(err);
}
scraper
.scan(packageName)
.then(result => {
const changes = result.changes;
res.json({ packageName, changes });
})
.catch(error => {
const err = new Error('Could not request info');
err.status = 404;
next(err);
});
});
module.exports = router;
| Change package query from query param to path variable | Change package query from query param to path variable
| JavaScript | mit | enric-sinh/android-changelog-api | ---
+++
@@ -2,8 +2,8 @@
const scraper = require('../service/scraper');
-router.get('/', (req, res, next) => {
- const packageName = req.query.package;
+router.get('/:package/latest', (req, res, next) => {
+ const packageName = req.params.package;
if (!packageName) {
const err = new Error('Undefined query'); |
b32f0a37a944afeda9d59eb8169dbad0419c5e0e | controllers/locale.js | controllers/locale.js | /*
* @author Martin Høgh <mh@mapcentia.com>
* @copyright 2013-2018 MapCentia ApS
* @license http://www.gnu.org/licenses/#AGPL GNU AFFERO GENERAL PUBLIC LICENSE 3
*/
var express = require('express');
var router = express.Router();
router.get('/locale', function(request, response) {
var lang = request.acceptsLanguages('en', 'en-US', 'da', 'da-DK');
if (lang) {
if (lang === "en") {
lang = "en-US";
}
if (lang === "da") {
lang = "da-DK";
}
} else {
lang = "en-US";
}
lang = lang.replace("-","_");
response.set('Content-Type', 'application/javascript');
//response.send("window._vidiLocale='" + lang + "'");
response.send("var urlVars = (function getUrlVars() {var mapvars = {};var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {mapvars[key] = value;});return mapvars;})(); if (urlVars.locale !== undefined){window._vidiLocale=urlVars.locale.split('#')[0]} else {window._vidiLocale='" + lang + "'}");
});
module.exports = router; | /*
* @author Martin Høgh <mh@mapcentia.com>
* @copyright 2013-2018 MapCentia ApS
* @license http://www.gnu.org/licenses/#AGPL GNU AFFERO GENERAL PUBLIC LICENSE 3
*/
var express = require('express');
var router = express.Router();
var ipaddr = require('ipaddr.js');
router.get('/locale', function(request, response) {
var ip = ipaddr.process(request.ip).toString();
var lang = request.acceptsLanguages('en', 'en-US', 'da', 'da-DK');
if (lang) {
if (lang === "en") {
lang = "en-US";
}
if (lang === "da") {
lang = "da-DK";
}
} else {
lang = "en-US";
}
lang = lang.replace("-","_");
response.set('Content-Type', 'application/javascript');
//response.send("window._vidiLocale='" + lang + "'");
response.send("window._vidiIp = '" + ip + "'; var urlVars = (function getUrlVars() {var mapvars = {};var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {mapvars[key] = value;});return mapvars;})(); if (urlVars.locale !== undefined){window._vidiLocale=urlVars.locale.split('#')[0]} else {window._vidiLocale='" + lang + "'}");
});
module.exports = router; | Return the clients IP address | Return the clients IP address
| JavaScript | agpl-3.0 | mapcentia/vidi,mapcentia/vidi,mapcentia/vidi,mapcentia/vidi | ---
+++
@@ -6,8 +6,10 @@
var express = require('express');
var router = express.Router();
+var ipaddr = require('ipaddr.js');
router.get('/locale', function(request, response) {
+ var ip = ipaddr.process(request.ip).toString();
var lang = request.acceptsLanguages('en', 'en-US', 'da', 'da-DK');
if (lang) {
if (lang === "en") {
@@ -22,6 +24,6 @@
lang = lang.replace("-","_");
response.set('Content-Type', 'application/javascript');
//response.send("window._vidiLocale='" + lang + "'");
- response.send("var urlVars = (function getUrlVars() {var mapvars = {};var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {mapvars[key] = value;});return mapvars;})(); if (urlVars.locale !== undefined){window._vidiLocale=urlVars.locale.split('#')[0]} else {window._vidiLocale='" + lang + "'}");
+ response.send("window._vidiIp = '" + ip + "'; var urlVars = (function getUrlVars() {var mapvars = {};var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {mapvars[key] = value;});return mapvars;})(); if (urlVars.locale !== undefined){window._vidiLocale=urlVars.locale.split('#')[0]} else {window._vidiLocale='" + lang + "'}");
});
module.exports = router; |
943bc6d05065524b158ac7fc3be450126db3a558 | website/app/application/core/projects/project/provenance/wizard/show-template-details.js | website/app/application/core/projects/project/provenance/wizard/show-template-details.js | Application.Directives.directive("showTemplateDetails", showTemplateDetailsDirective);
function showTemplateDetailsDirective() {
return {
restrict: "E",
replace: true,
scope: {
template: "=template",
},
controller: "showTemplateDetailsDirectiveController",
templateUrl: "application/core/projects/project/provenance/wizard/show-template-details.html"
};
}
Application.Controllers.controller("showTemplateDetailsDirectiveController",
["$scope", showTemplateDetailsDirectiveController]);
function showTemplateDetailsDirectiveController($scope) {
}
| Application.Directives.directive("showTemplateDetails",
["RecursionHelper", showTemplateDetailsDirective]);
function showTemplateDetailsDirective(RecursionHelper) {
return {
restrict: "E",
replace: true,
scope: {
template: "=template",
},
controller: "showTemplateDetailsDirectiveController",
templateUrl: "application/core/projects/project/provenance/wizard/show-template-details.html",
compile: function(element) {
return RecursionHelper.compile(element, function(scope, iElement, iAttrs, controller, transcludeFn) {
});
}
};
}
Application.Controllers.controller("showTemplateDetailsDirectiveController",
["$scope", showTemplateDetailsDirectiveController]);
function showTemplateDetailsDirectiveController($scope) {
}
| Allow directive to be called recursively. | Allow directive to be called recursively.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -1,5 +1,6 @@
-Application.Directives.directive("showTemplateDetails", showTemplateDetailsDirective);
-function showTemplateDetailsDirective() {
+Application.Directives.directive("showTemplateDetails",
+ ["RecursionHelper", showTemplateDetailsDirective]);
+function showTemplateDetailsDirective(RecursionHelper) {
return {
restrict: "E",
replace: true,
@@ -7,11 +8,15 @@
template: "=template",
},
controller: "showTemplateDetailsDirectiveController",
- templateUrl: "application/core/projects/project/provenance/wizard/show-template-details.html"
+ templateUrl: "application/core/projects/project/provenance/wizard/show-template-details.html",
+ compile: function(element) {
+ return RecursionHelper.compile(element, function(scope, iElement, iAttrs, controller, transcludeFn) {
+ });
+ }
};
}
Application.Controllers.controller("showTemplateDetailsDirectiveController",
- ["$scope", showTemplateDetailsDirectiveController]);
+ ["$scope", showTemplateDetailsDirectiveController]);
function showTemplateDetailsDirectiveController($scope) {
} |
5ae8a55a75bef8a0af6d330842000152e2830c0e | lib/text.js | lib/text.js | exports._regExpRegExp = /^\/(.+)\/([im]?)$/;
exports._lineRegExp = /\r\n|\r|\n/;
exports.splitLines = function (text) {
var lines = [];
var match, line;
while (match = exports._lineRegExp.exec(text)) {
line = text.slice(0, match.index) + match[0];
text = text.slice(line.length);
lines.push(line);
}
lines.push(text);
return lines;
};
exports.escapeRegExp = function (text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
exports.regExpIndexOf = function(str, regex, index) {
index = index || 0;
var offset = str.slice(index).search(regex);
return (offset >= 0) ? (index + offset) : offset;
};
exports.regExpLastIndexOf = function (str, regex, index) {
if (index === 0 || index) str = str.slice(0, Math.max(0, index));
var i;
var offset = -1;
while ((i = str.search(regex)) !== -1) {
offset += i + 1;
str = str.slice(i + 1);
}
return offset;
};
| exports._regExpRegExp = /^\/(.+)\/([im]?)$/;
exports._lineRegExp = /\r\n|\r|\n/;
exports.splitLines = function (text) {
var lines = [];
var match, line;
while (match = exports._lineRegExp.exec(text)) {
line = text.slice(0, match.index) + match[0];
text = text.slice(line.length);
lines.push(line);
}
lines.push(text);
return lines;
};
exports.regExpIndexOf = function(str, regex, index) {
index = index || 0;
var offset = str.slice(index).search(regex);
return (offset >= 0) ? (index + offset) : offset;
};
exports.regExpLastIndexOf = function (str, regex, index) {
if (index === 0 || index) str = str.slice(0, Math.max(0, index));
var i;
var offset = -1;
while ((i = str.search(regex)) !== -1) {
offset += i + 1;
str = str.slice(i + 1);
}
return offset;
};
| Remove escapeRegExp in favor of lodash.escapeRegExp | Remove escapeRegExp in favor of lodash.escapeRegExp | JavaScript | mit | slap-editor/slap-util | ---
+++
@@ -11,9 +11,6 @@
}
lines.push(text);
return lines;
-};
-exports.escapeRegExp = function (text) {
- return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
exports.regExpIndexOf = function(str, regex, index) {
index = index || 0; |
2edfecbcd8b891a839e3ee36ed18d8052900d134 | src/dispatchResponse.js | src/dispatchResponse.js | /**
* @flow
*/
type ResData = {
newStates: {[key: string]: string}
};
/**
* Encode the updated states, to send to the client.
*
* @param updatedStates {StatesObject} The updated states
* @param encodeState {(string, any) => string} A function that will encode the state, of a given store, to be
* passed over an HTTP request
*
* @return {ResData} The data to respond to the client with
*/
export function encode(updatedStates: StatesObject, encodeState: EncodeStateFunc): ResData {
//TODO
return {};
}
/**
* Decode the states from the server.
*
* @param response {ResData} The response form the server
* @param decodeState {(string, string) => any} A function that will decode the state of a given store
*
* @return {StatesObject} The updated states
*/
export function decode(response: ResData, decodeState: DecodeStateFunc): StatesObject {
//TODO
return {};
} | /**
* @flow
*/
type ResData = {
newStates: {[key: string]: string}
};
/**
* Encode the updated states, to send to the client.
*
* @param updatedStates {StatesObject} The updated states
* @param encodeState {(string, any) => string} A function that will encode the state, of a given store, to be
* passed over an HTTP request
*
* @return {ResData} The data to respond to the client with
*/
export function encode(updatedStates: StatesObject, encodeState: EncodeStateFunc): ResData {
const newStates = {};
for(let storeName in updatedStates) {
const updatedState = updatedStates[storeName];
newStates[storeName] = encodeState(storeName, updatedState);
}
return { newStates };
}
/**
* Decode the states from the server.
*
* @param response {ResData} The response form the server
* @param decodeState {(string, string) => any} A function that will decode the state of a given store
*
* @return {StatesObject} The updated states
*/
export function decode(response: ResData, decodeState: DecodeStateFunc): StatesObject {
const { newStates } = response;
const updatedStates = {};
for(let storeName in newStates) {
const newState = newStates[storeName];
updatedStates[storeName] = decodeState(storeName, newState);
}
return updatedStates;
} | Implement the Response's 'encode(...)' and 'decode(...)' Functions | Implement the Response's 'encode(...)' and 'decode(...)' Functions
Implement 'encode(...)' and 'decode(...)' functions for the the response.
| JavaScript | mit | nheyn/express-isomorphic-dispatcher | ---
+++
@@ -16,8 +16,14 @@
* @return {ResData} The data to respond to the client with
*/
export function encode(updatedStates: StatesObject, encodeState: EncodeStateFunc): ResData {
- //TODO
- return {};
+ const newStates = {};
+ for(let storeName in updatedStates) {
+ const updatedState = updatedStates[storeName];
+
+ newStates[storeName] = encodeState(storeName, updatedState);
+ }
+
+ return { newStates };
}
/**
@@ -29,6 +35,13 @@
* @return {StatesObject} The updated states
*/
export function decode(response: ResData, decodeState: DecodeStateFunc): StatesObject {
- //TODO
- return {};
+ const { newStates } = response;
+ const updatedStates = {};
+ for(let storeName in newStates) {
+ const newState = newStates[storeName];
+
+ updatedStates[storeName] = decodeState(storeName, newState);
+ }
+
+ return updatedStates;
} |
0692f1a02b2dd231b40f06dce5941fdf15feecac | packages/react-cookie/src/withCookies.js | packages/react-cookie/src/withCookies.js | import React, { Component } from 'react';
import { instanceOf, func } from 'prop-types';
import Cookies from 'universal-cookie';
import hoistStatics from 'hoist-non-react-statics';
export default function withCookies(WrapperComponent) {
class Wrapper extends Component {
static displayName = `withCookies(${Component.displayName ||
Component.name})`;
static WrapperComponent = WrapperComponent;
static propTypes = {
wrappedComponentRef: func
};
static contextTypes = {
cookies: instanceOf(Cookies).isRequired
};
constructor(props, context) {
super(props);
context.cookies.addChangeListener(this.onChange);
}
componentWillUnmount() {
this.context.cookies.removeChangeListener(this.onChange);
}
onChange = () => {
this.forceUpdate();
};
render() {
const { wrappedComponentRef, ...remainingProps } = this.props;
const allCookies = this.context.cookies.getAll();
return (
<WrapperComponent
{...remainingProps}
cookies={this.context.cookies}
allCookies={allCookies}
ref={wrappedComponentRef}
/>
);
}
}
return hoistStatics(Wrapper, WrapperComponent, { WrappedComponent: true });
}
| import React, { Component } from 'react';
import { instanceOf, func } from 'prop-types';
import Cookies from 'universal-cookie';
import hoistStatics from 'hoist-non-react-statics';
export default function withCookies(WrapperComponent) {
class Wrapper extends Component {
static displayName = `withCookies(${WrapperComponent.displayName ||
WrapperComponent.name})`;
static WrapperComponent = WrapperComponent;
static propTypes = {
wrappedComponentRef: func
};
static contextTypes = {
cookies: instanceOf(Cookies).isRequired
};
constructor(props, context) {
super(props);
context.cookies.addChangeListener(this.onChange);
}
componentWillUnmount() {
this.context.cookies.removeChangeListener(this.onChange);
}
onChange = () => {
this.forceUpdate();
};
render() {
const { wrappedComponentRef, ...remainingProps } = this.props;
const allCookies = this.context.cookies.getAll();
return (
<WrapperComponent
{...remainingProps}
cookies={this.context.cookies}
allCookies={allCookies}
ref={wrappedComponentRef}
/>
);
}
}
return hoistStatics(Wrapper, WrapperComponent, { WrappedComponent: true });
}
| Fix undefined name of component | Fix undefined name of component
Fix minor misspel, `Component` is `React.Component` now, should use name of `WrapperComponent` in `displayName` | JavaScript | mit | eXon/react-cookie,reactivestack/cookies,reactivestack/cookies,reactivestack/cookies | ---
+++
@@ -5,8 +5,8 @@
export default function withCookies(WrapperComponent) {
class Wrapper extends Component {
- static displayName = `withCookies(${Component.displayName ||
- Component.name})`;
+ static displayName = `withCookies(${WrapperComponent.displayName ||
+ WrapperComponent.name})`;
static WrapperComponent = WrapperComponent;
static propTypes = { |
2800cd66ab65cc464c5ddeb1a619a2ed9e254e35 | src/update.js | src/update.js | // @flow
export default function (el: HTMLTextAreaElement, headToCursor: string, cursorToTail: ?string) {
const curr = el.value, // strA + strB1 + strC
next = headToCursor + (cursorToTail || ''), // strA + strB2 + strC
activeElement = document.activeElement;
// Calculate length of strA and strC
let aLength = 0,
cLength = 0;
while (aLength < curr.length && aLength < next.length && curr[aLength] === next[aLength]) { aLength++; }
while (curr[curr.length - cLength - 1] === next[next.length - cLength - 1]) { cLength++; }
aLength = Math.min(aLength, Math.min(curr.length, next.length) - cLength);
// Select strB1
el.setSelectionRange(aLength, curr.length - cLength);
// Get strB2
const strB2 = next.substring(aLength, next.length - cLength);
// Replace strB1 with strB2
el.focus();
if (!document.execCommand('insertText', false, strB2)) {
// Document.execCommand returns false if the command is not supported.
// Firefox and IE returns false in this case.
el.value = next;
}
// Move cursor to the end of headToCursor
el.setSelectionRange(headToCursor.length, headToCursor.length);
activeElement && activeElement.focus();
return el;
}
| // @flow
export default function (el: HTMLTextAreaElement, headToCursor: string, cursorToTail: ?string) {
const curr = el.value, // strA + strB1 + strC
next = headToCursor + (cursorToTail || ''), // strA + strB2 + strC
activeElement = document.activeElement;
// Calculate length of strA and strC
let aLength = 0,
cLength = 0;
while (aLength < curr.length && aLength < next.length && curr[aLength] === next[aLength]) { aLength++; }
while (curr.length - cLength - 1 >= 0 && next.length - cLength - 1 >= 0 && curr[curr.length - cLength - 1] === next[next.length - cLength - 1]) { cLength++; }
aLength = Math.min(aLength, Math.min(curr.length, next.length) - cLength);
// Select strB1
el.setSelectionRange(aLength, curr.length - cLength);
// Get strB2
const strB2 = next.substring(aLength, next.length - cLength);
// Replace strB1 with strB2
el.focus();
if (!document.execCommand('insertText', false, strB2)) {
// Document.execCommand returns false if the command is not supported.
// Firefox and IE returns false in this case.
el.value = next;
}
// Move cursor to the end of headToCursor
el.setSelectionRange(headToCursor.length, headToCursor.length);
activeElement && activeElement.focus();
return el;
}
| Fix a second infinite loop | Fix a second infinite loop | JavaScript | mit | yuku-t/undate,yuku-t/undate | ---
+++
@@ -9,7 +9,7 @@
let aLength = 0,
cLength = 0;
while (aLength < curr.length && aLength < next.length && curr[aLength] === next[aLength]) { aLength++; }
- while (curr[curr.length - cLength - 1] === next[next.length - cLength - 1]) { cLength++; }
+ while (curr.length - cLength - 1 >= 0 && next.length - cLength - 1 >= 0 && curr[curr.length - cLength - 1] === next[next.length - cLength - 1]) { cLength++; }
aLength = Math.min(aLength, Math.min(curr.length, next.length) - cLength);
// Select strB1 |
ea89c8e3f4068f775cca71dbfd6c2d8410addecb | lib/assets/javascripts/cartodb/new_common/url_shortener.js | lib/assets/javascripts/cartodb/new_common/url_shortener.js | var $ = require('jquery');
var LocalStorage = require('./local_storage');
var LOGIN = 'vizzuality';
var KEY = 'R_de188fd61320cb55d359b2fecd3dad4b';
var UrlShortener = function() {
this.localStorage = new LocalStorage('cartodb_urls');
};
UrlShortener.prototype.fetch = function(originalUrl, callbacks) {
var cachedUrl = this.localStorage.search(originalUrl);
if (cachedUrl) {
return callbacks.success(cachedUrl);
}
var self = this;
$.ajax({
url: 'https://api-ssl.bitly.com/v3/shorten?longUrl=' + encodeURIComponent(originalUrl) + '&login=' + LOGIN + '&apiKey=' + KEY,
type: 'GET',
async: false,
dataType: 'jsonp',
success: function(res) {
if (res && res.data && res.data.url) {
var shortURL = res.data.url;
var d = {};
d[originalUrl] = shortURL;
self.localStorage.add(d);
callbacks.success(shortURL);
} else {
callbacks.error(originalUrl);
}
},
error: function() {
callbacks.error(originalUrl);
}
});
};
module.exports = UrlShortener;
| var $ = require('jquery');
var LocalStorage = require('./local_storage');
var LOGIN = 'vizzuality';
var KEY = 'R_de188fd61320cb55d359b2fecd3dad4b';
var UrlShortener = function() {
this.localStorage = new LocalStorage('cartodb_urls2'); // to not clash with old local storage cache, they're incompatible
};
UrlShortener.prototype.fetch = function(originalUrl, callbacks) {
var cachedUrl = this.localStorage.search(originalUrl);
if (cachedUrl) {
return callbacks.success(cachedUrl);
}
var self = this;
$.ajax({
url: 'https://api-ssl.bitly.com/v3/shorten?longUrl=' + encodeURIComponent(originalUrl) + '&login=' + LOGIN + '&apiKey=' + KEY,
type: 'GET',
async: false,
dataType: 'jsonp',
success: function(res) {
if (res && res.data && res.data.url) {
var shortURL = res.data.url;
var d = {};
d[originalUrl] = shortURL;
self.localStorage.add(d);
callbacks.success(shortURL);
} else {
callbacks.error(originalUrl);
}
},
error: function() {
callbacks.error(originalUrl);
}
});
};
module.exports = UrlShortener;
| Change key used for url shortener | Change key used for url shortener
Incompatible with old keys, so do not use same key
| JavaScript | bsd-3-clause | thorncp/cartodb,UCL-ShippingGroup/cartodb-1,thorncp/cartodb,DigitalCoder/cartodb,codeandtheory/cartodb,DigitalCoder/cartodb,nyimbi/cartodb,nuxcode/cartodb,UCL-ShippingGroup/cartodb-1,DigitalCoder/cartodb,codeandtheory/cartodb,nuxcode/cartodb,CartoDB/cartodb,bloomberg/cartodb,future-analytics/cartodb,nyimbi/cartodb,codeandtheory/cartodb,nyimbi/cartodb,dbirchak/cartodb,splashblot/dronedb,CartoDB/cartodb,bloomberg/cartodb,CartoDB/cartodb,bloomberg/cartodb,raquel-ucl/cartodb,dbirchak/cartodb,dbirchak/cartodb,raquel-ucl/cartodb,future-analytics/cartodb,raquel-ucl/cartodb,raquel-ucl/cartodb,UCL-ShippingGroup/cartodb-1,nyimbi/cartodb,future-analytics/cartodb,nuxcode/cartodb,UCL-ShippingGroup/cartodb-1,bloomberg/cartodb,codeandtheory/cartodb,codeandtheory/cartodb,splashblot/dronedb,thorncp/cartodb,splashblot/dronedb,DigitalCoder/cartodb,CartoDB/cartodb,UCL-ShippingGroup/cartodb-1,DigitalCoder/cartodb,dbirchak/cartodb,dbirchak/cartodb,thorncp/cartodb,future-analytics/cartodb,CartoDB/cartodb,nuxcode/cartodb,thorncp/cartodb,raquel-ucl/cartodb,nuxcode/cartodb,nyimbi/cartodb,splashblot/dronedb,bloomberg/cartodb,splashblot/dronedb,future-analytics/cartodb | ---
+++
@@ -5,7 +5,7 @@
var KEY = 'R_de188fd61320cb55d359b2fecd3dad4b';
var UrlShortener = function() {
- this.localStorage = new LocalStorage('cartodb_urls');
+ this.localStorage = new LocalStorage('cartodb_urls2'); // to not clash with old local storage cache, they're incompatible
};
UrlShortener.prototype.fetch = function(originalUrl, callbacks) { |
3b3de3a210fe69cd4e95f0c218801992cab0c88c | src/store/student-store.js | src/store/student-store.js | import { Store } from 'consus-core/flux';
import CartStore from './cart-store';
let student = null;
class StudentStore extends Store{
hasOverdueItems(items){
return items.some(element => {
return element.timestamp <= new Date().getTime();
});
}
getStudent() {
return student;
}
}
const store = new StudentStore();
store.registerHandler('STUDENT_FOUND', data => {
student = {
//NOTE: this data is tentative
id : data.id,
name: data.name,
items: data.items,
hasOverdueItem: store.hasOverdueItems(data.items)
};
store.emitChange();
});
store.registerHandler('CLEAR_ALL_DATA', () => {
student = null;
});
store.registerHandler('CHECKOUT_SUCCESS', () => {
student.items = student.items.concat(CartStore.getItems());
store.emitChange();
});
store.registerHandler('CHECKIN_SUCCESS', data => {
let index = student.items.findIndex(element => {
return element.address === data.itemAddress;
});
student.items.splice(index, 1);
store.emitChange();
});
export default store;
| import { Store } from 'consus-core/flux';
import CartStore from './cart-store';
import { searchStudent } from '../lib/api-client';
let student = null;
class StudentStore extends Store{
hasOverdueItems(items){
return items.some(element => {
return element.timestamp <= new Date().getTime();
});
}
getStudent() {
return student;
}
}
const store = new StudentStore();
store.registerHandler('STUDENT_FOUND', data => {
student = {
//NOTE: this data is tentative
id : data.id,
name: data.name,
items: data.items,
hasOverdueItem: store.hasOverdueItems(data.items)
};
store.emitChange();
});
store.registerHandler('CLEAR_ALL_DATA', () => {
student = null;
});
store.registerHandler('CHECKOUT_SUCCESS', () => {
/*API call made from store to update student from server
after checkout completes, then the store will emit change when
student is found.*/
searchStudent(student.id);
});
store.registerHandler('CHECKIN_SUCCESS', data => {
let index = student.items.findIndex(element => {
return element.address === data.itemAddress;
});
student.items.splice(index, 1);
store.emitChange();
});
export default store;
| Update student from server after checkout completes | Update student from server after checkout completes
| JavaScript | unlicense | TheFourFifths/consus-client,TheFourFifths/consus-client | ---
+++
@@ -1,5 +1,6 @@
import { Store } from 'consus-core/flux';
import CartStore from './cart-store';
+import { searchStudent } from '../lib/api-client';
let student = null;
@@ -33,8 +34,10 @@
});
store.registerHandler('CHECKOUT_SUCCESS', () => {
- student.items = student.items.concat(CartStore.getItems());
- store.emitChange();
+ /*API call made from store to update student from server
+ after checkout completes, then the store will emit change when
+ student is found.*/
+ searchStudent(student.id);
});
store.registerHandler('CHECKIN_SUCCESS', data => { |
0be67d85e1d203b41d1dddded41f8d634e01a44f | packages/truffle-contract/statuserror.js | packages/truffle-contract/statuserror.js | var TruffleError = require("truffle-error");
var inherits = require("util").inherits;
var defaultGas = 90000;
var web3 = require("web3");
inherits(StatusError, TruffleError);
function StatusError(args, tx, receipt) {
var message;
var gasLimit = parseInt(args.gas) || defaultGas;
if(receipt.gasUsed === gasLimit){
message = "Transaction: " + tx + " exited with an error (status 0 - invalid opcode).\n" +
"Please check that the transaction:\n" +
" - satisfies all conditions set by Solidity `assert` statements.\n" +
" - has enough gas to execute all internal Solidity function calls.\n";
} else {
message = "Transaction: " + tx + " exited with an error (status 0 - revert).\n" +
"Please check that the transaction:\n" +
" - satisfies all conditions set by Solidity `require` statements.\n" +
" - does not trigger a Solidity `revert` statement.\n";
}
StatusError.super_.call(this, message);
this.tx = tx;
this.receipt = receipt;
}
module.exports = StatusError; | var TruffleError = require("truffle-error");
var inherits = require("util").inherits;
var web3 = require("web3");
inherits(StatusError, TruffleError);
var defaultGas = 90000;
function StatusError(args, tx, receipt) {
var message;
var gasLimit = parseInt(args.gas) || defaultGas;
if(receipt.gasUsed === gasLimit){
message = "Transaction: " + tx + " exited with an error (status 0 - invalid opcode).\n" +
"Please check that the transaction:\n" +
" - satisfies all conditions set by Solidity `assert` statements.\n" +
" - has enough gas to execute all internal Solidity function calls.\n";
} else {
message = "Transaction: " + tx + " exited with an error (status 0 - revert).\n" +
"Please check that the transaction:\n" +
" - satisfies all conditions set by Solidity `require` statements.\n" +
" - does not trigger a Solidity `revert` statement.\n";
}
StatusError.super_.call(this, message);
this.tx = tx;
this.receipt = receipt;
}
module.exports = StatusError; | Move errant variable away from require block | Move errant variable away from require block
| JavaScript | mit | ConsenSys/truffle | ---
+++
@@ -1,9 +1,10 @@
var TruffleError = require("truffle-error");
var inherits = require("util").inherits;
-var defaultGas = 90000;
var web3 = require("web3");
inherits(StatusError, TruffleError);
+
+var defaultGas = 90000;
function StatusError(args, tx, receipt) {
var message; |
88540362b4b676d68a2b5db474b9cb1bd7316aa3 | packages/motion/src/cli/index.js | packages/motion/src/cli/index.js | #!/usr/bin/env node
'use strict'
import commander from 'commander'
const parameters = require('minimist')(process.argv.slice(2))
const command = parameters['_'][0]
const validCommands = ['new', 'build', 'update', 'init']
// TODO: Check for updates
// Note: This is a trick to make multiple commander commands work with single executables
process.argv = process.argv.slice(0, 2).concat(process.argv.slice(3))
if (!command || command === 'run') {
require('./motion-run')
} else if (validCommands.indexOf(command) !== -1) {
require(`./motion-${command}`)
} else {
console.error(`
Usage:
motion run your motion app
motion new [name] [template] start a new app
motion build build for production
motion update update motion
motion init add a motion config to an existing app (temporary, awaiting https://github.com/motion/motion/issues/339)
`.trim())
process.exit(1)
}
| #!/usr/bin/env node
'use strict'
const command = process.argv[2] || ''
const validCommands = ['new', 'build', 'update', 'init']
// TODO: Check for updates
// Note: This is a trick to make multiple commander commands work with single executables
process.argv = process.argv.slice(0, 2).concat(process.argv.slice(3))
let showHelp = command === '--help'
if (!showHelp && (!command || command === 'run')) {
require('./motion-run')
} else if (!showHelp && validCommands.indexOf(command) !== -1) {
require(`./motion-${command}`)
} else {
console.error(`
Usage:
motion alias for 'motion run'
motion run run your motion app
motion new [name] [template] start a new app
motion build build for production
motion update update motion
motion init add a motion config to an existing app (temporary, awaiting https://github.com/motion/motion/issues/339)
`.trim())
process.exit(1)
}
| Enhance the main cli entry file | :art: Enhance the main cli entry file
| JavaScript | mpl-2.0 | flintjs/flint,flintjs/flint,motion/motion,flintjs/flint,motion/motion | ---
+++
@@ -1,10 +1,7 @@
#!/usr/bin/env node
'use strict'
-
-import commander from 'commander'
-const parameters = require('minimist')(process.argv.slice(2))
-const command = parameters['_'][0]
+const command = process.argv[2] || ''
const validCommands = ['new', 'build', 'update', 'init']
// TODO: Check for updates
@@ -12,14 +9,17 @@
// Note: This is a trick to make multiple commander commands work with single executables
process.argv = process.argv.slice(0, 2).concat(process.argv.slice(3))
-if (!command || command === 'run') {
+let showHelp = command === '--help'
+
+if (!showHelp && (!command || command === 'run')) {
require('./motion-run')
-} else if (validCommands.indexOf(command) !== -1) {
+} else if (!showHelp && validCommands.indexOf(command) !== -1) {
require(`./motion-${command}`)
} else {
console.error(`
Usage:
- motion run your motion app
+ motion alias for 'motion run'
+ motion run run your motion app
motion new [name] [template] start a new app
motion build build for production
motion update update motion |
8486a37ca95cc2c211ec6a66b618e986e3d7dec6 | server/server.js | server/server.js | const
express = require('express'),
bodyParser = require('body-parser');
const
{mongoose} = require('./db/mongoose'),
dbHandler = require('./db/dbHandler');
let app = express();
let port = porcess.env.PORT || 3000;
app.use(bodyParser.json());
app.route('/todos')
.get((req, res) => {
dbHandler.findTodos().then((value) => {
res.send({
todos: value.data
});
}).catch((err) => {
console.error('There was an error fetching the todos.', err);
res.status(err.code).send({message: err.message});
});
})
.post((req, res) => {
dbHandler.saveTodo(req.body.text).then((value) => {
res.send(value.data);
}).catch((err) => {
console.error('There was an error saving the todo.', err);
res.status(err.code).send({message: err.message});
});
});
app.route('/todos/:id')
.get((req, res) => {
dbHandler.findTodo(req.params.id).then((value) => {
res.send({
todo: value.data
});
}).catch((err) => {
console.error('There was an error fetching the todo.', err);
res.status(err.code).send({message: err.message});
})
})
app.listen(port, () => {
console.log(`Started up at port ${port}`);
});
module.exports = {app};
| const
express = require('express'),
bodyParser = require('body-parser');
const
{mongoose} = require('./db/mongoose'),
dbHandler = require('./db/dbHandler');
let app = express();
let port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.route('/todos')
.get((req, res) => {
dbHandler.findTodos().then((value) => {
res.send({
todos: value.data
});
}).catch((err) => {
console.error('There was an error fetching the todos.', err);
res.status(err.code).send({message: err.message});
});
})
.post((req, res) => {
dbHandler.saveTodo(req.body.text).then((value) => {
res.send(value.data);
}).catch((err) => {
console.error('There was an error saving the todo.', err);
res.status(err.code).send({message: err.message});
});
});
app.route('/todos/:id')
.get((req, res) => {
dbHandler.findTodo(req.params.id).then((value) => {
res.send({
todo: value.data
});
}).catch((err) => {
console.error('There was an error fetching the todo.', err);
res.status(err.code).send({message: err.message});
})
})
app.listen(port, () => {
console.log(`Started up at port ${port}`);
});
module.exports = {app};
| Fix a typo setting the port | Fix a typo setting the port
| JavaScript | mit | daniellara/smooky-todoes | ---
+++
@@ -7,7 +7,7 @@
dbHandler = require('./db/dbHandler');
let app = express();
-let port = porcess.env.PORT || 3000;
+let port = process.env.PORT || 3000;
app.use(bodyParser.json());
|
75a7442f43aeaa63727ba09c892cb7b4f5e4f1c5 | test/api/scenarios.spec.js | test/api/scenarios.spec.js | import { API } from 'api';
import Scenarios from 'api/scenarios';
describe('scenarios', () => {
afterEach(() => {
API.clearStorage();
});
it('should have currentScenario be set to "MockedRequests"', () => {
expect(Scenarios.currentScenario).toBe('MockedRequests');
});
it('should get 0 scenarios', () => {
expect(Scenarios.scenarios.length).toBe(0);
});
it('should add a scenario', () => {
expect(Scenarios.scenarios.length).toBe(0);
Scenarios.addScenario('test scenario');
expect(Scenarios.scenarios.length).toBe(1);
expect(Scenarios.scenarios[0].name).toBe('test scenario');
});
});
| import { API } from 'api';
import Scenarios from 'api/scenarios';
describe('scenarios', () => {
afterEach(() => {
API.clearStorage();
});
it('should have currentScenario be set to "MockedRequests"', () => {
expect(Scenarios.currentScenario).toBe('MockedRequests');
});
it('should get 0 scenarios', () => {
expect(Scenarios.scenarios.length).toBe(0);
});
it('should add a scenario', () => {
expect(Scenarios.scenarios.length).toBe(0);
Scenarios.addScenario('test scenario');
expect(Scenarios.scenarios.length).toBe(1);
expect(Scenarios.scenarios[0].name).toBe('test scenario');
});
it('should set the current scenario', () => {
Scenarios.addScenario('test scenario');
Scenarios.setCurrentScenario(Scenarios.scenarios[0].id);
expect(Scenarios.currentScenario).toBe(Scenarios.scenarios[0].id);
});
it('should get a scenario by id', () => {
Scenarios.addScenario('test scenario');
let scenario = Scenarios.getById(Scenarios.scenarios[0].id);
expect(scenario).toBe(Scenarios.scenarios[0]);
});
it('should get a scenario by name', () => {
Scenarios.addScenario('test scenario');
let scenario = Scenarios.getByName('test scenario');
expect(scenario).toBe(Scenarios.scenarios[0]);
});
it('should duplicate a scenario', () => {
Scenarios.addScenario('test scenario');
expect(Scenarios.scenarios.length).toBe(1);
Scenarios.duplicateScenario(Scenarios.scenarios[0].id);
expect(Scenarios.getByName('test scenario copy')).toBeDefined();
expect(Scenarios.scenarios.length).toBe(2);
});
it('should rename a scenario', () => {
Scenarios.addScenario('test scenario');
expect(Scenarios.scenarios[0].name).toBe('test scenario');
Scenarios.renameScenario(Scenarios.scenarios[0].id, 'renamed scenario');
expect(Scenarios.scenarios[0].name).toBe('renamed scenario');
});
it('should remove a scenario', () => {
expect(Scenarios.scenarios.length).toBe(0);
Scenarios.addScenario('test scenario');
expect(Scenarios.scenarios.length).toBe(1);
Scenarios.removeScenario(Scenarios.scenarios[0].id);
expect(Scenarios.scenarios.length).toBe(0);
});
});
| Add additional scenarios test cases | Add additional scenarios test cases
| JavaScript | mit | 500tech/bdsm,500tech/mimic,500tech/mimic,500tech/bdsm | ---
+++
@@ -24,4 +24,53 @@
expect(Scenarios.scenarios[0].name).toBe('test scenario');
});
+ it('should set the current scenario', () => {
+ Scenarios.addScenario('test scenario');
+
+ Scenarios.setCurrentScenario(Scenarios.scenarios[0].id);
+ expect(Scenarios.currentScenario).toBe(Scenarios.scenarios[0].id);
+ });
+
+ it('should get a scenario by id', () => {
+ Scenarios.addScenario('test scenario');
+
+ let scenario = Scenarios.getById(Scenarios.scenarios[0].id);
+ expect(scenario).toBe(Scenarios.scenarios[0]);
+ });
+
+ it('should get a scenario by name', () => {
+ Scenarios.addScenario('test scenario');
+
+ let scenario = Scenarios.getByName('test scenario');
+ expect(scenario).toBe(Scenarios.scenarios[0]);
+ });
+
+ it('should duplicate a scenario', () => {
+ Scenarios.addScenario('test scenario');
+
+ expect(Scenarios.scenarios.length).toBe(1);
+ Scenarios.duplicateScenario(Scenarios.scenarios[0].id);
+
+ expect(Scenarios.getByName('test scenario copy')).toBeDefined();
+ expect(Scenarios.scenarios.length).toBe(2);
+ });
+
+ it('should rename a scenario', () => {
+ Scenarios.addScenario('test scenario');
+ expect(Scenarios.scenarios[0].name).toBe('test scenario');
+
+ Scenarios.renameScenario(Scenarios.scenarios[0].id, 'renamed scenario');
+ expect(Scenarios.scenarios[0].name).toBe('renamed scenario');
+ });
+
+ it('should remove a scenario', () => {
+ expect(Scenarios.scenarios.length).toBe(0);
+
+ Scenarios.addScenario('test scenario');
+ expect(Scenarios.scenarios.length).toBe(1);
+
+ Scenarios.removeScenario(Scenarios.scenarios[0].id);
+ expect(Scenarios.scenarios.length).toBe(0);
+ });
+
}); |
17bc27925e2b02d4910cd6598af4bcbda7e4d8f0 | src/tasks/watchBuild.js | src/tasks/watchBuild.js | /*
* Copyright 2014 Workiva, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = function(gulp, options, subtasks) {
var taskname = 'watch:build';
gulp.desc(taskname, 'Watch source files for changes and rebuild');
var fn = function(done) {
gulp.watch(options.glob.all, {
cwd: options.path.src
}, ['build']);
};
gulp.task(taskname, ['build'], fn);
};
| /*
* Copyright 2014 Workiva, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = function(gulp, options, subtasks) {
var taskname = 'watch:build';
gulp.desc(taskname, 'Watch source files for changes and rebuild');
var fn = function(done) {
gulp.watch([
options.path.src + options.glob.all,
options.path.styles + options.glob.all
], ['build']);
};
gulp.task(taskname, ['build'], fn);
};
| Add styles to watched directories for watch:build/watch | Add styles to watched directories for watch:build/watch
| JavaScript | apache-2.0 | robertbaker/wGulp,Workiva/wGulp,Workiva/wGulp,jimhotchkin-wf/wGulp,jimhotchkin-wf/wGulp,robertbaker/wGulp,robertbaker/wGulp,jimhotchkin-wf/wGulp,Workiva/wGulp | ---
+++
@@ -21,9 +21,10 @@
gulp.desc(taskname, 'Watch source files for changes and rebuild');
var fn = function(done) {
- gulp.watch(options.glob.all, {
- cwd: options.path.src
- }, ['build']);
+ gulp.watch([
+ options.path.src + options.glob.all,
+ options.path.styles + options.glob.all
+ ], ['build']);
};
gulp.task(taskname, ['build'], fn);
}; |
e5159760eea2faff47cc88518f5b4c3317b6b4ec | src/utils/gulp/gulp-tasks-linters.js | src/utils/gulp/gulp-tasks-linters.js | var path = require('path');
var eslint = require('gulp-eslint');
var merge = require('lodash/object/merge');
var shelljs = require('shelljs');
function failLintBuild() {
process.exit(1);
}
function scssLintExists() {
return shelljs.which('scss-lint');
}
module.exports = function(gulp, options) {
var scssLintPath = path.resolve(__dirname, 'scss-lint.yml');
var esLintPath = path.resolve(__dirname, 'eslintrc');
var customEslint = options.customEslintPath ?
require(options.customEslintPath) : {};
gulp.task('scsslint', function() {
if (options.scsslint) {
if (scssLintExists()) {
var scsslint = require('gulp-scss-lint');
return gulp.src(options.scssAssets || []).pipe(scsslint({
'config': scssLintPath
})).pipe(scsslint.failReporter()).on('error', failLintBuild);
} else {
console.error('[scsslint] scsslint skipped!');
console.error('[scsslint] scss-lint is not installed. Please install ruby and the ruby gem scss-lint.');
}
}
});
gulp.task('jslint', function() {
var eslintRules = merge({
configFile: esLintPath
}, customEslint);
return gulp.src(options.jsAssets || [])
.pipe(eslint(eslintRules))
.pipe(eslint.formatEach())
.pipe(eslint.failOnError());
});
};
| var path = require('path');
var eslint = require('gulp-eslint');
var merge = require('lodash/object/merge');
var shelljs = require('shelljs');
function scssLintExists() {
return shelljs.which('scss-lint');
}
module.exports = function(gulp, options) {
var scssLintPath = path.resolve(__dirname, 'scss-lint.yml');
var esLintPath = path.resolve(__dirname, 'eslintrc');
var customEslint = options.customEslintPath ?
require(options.customEslintPath) : {};
gulp.task('scsslint', function() {
if (options.scsslint) {
if (scssLintExists()) {
var scsslint = require('gulp-scss-lint');
return gulp.src(options.scssAssets || []).pipe(scsslint({
'config': scssLintPath
})).pipe(scsslint.failReporter());
} else {
console.error('[scsslint] scsslint skipped!');
console.error('[scsslint] scss-lint is not installed. Please install ruby and the ruby gem scss-lint.');
}
}
});
gulp.task('jslint', function() {
var eslintRules = merge({
configFile: esLintPath
}, customEslint);
return gulp.src(options.jsAssets || [])
.pipe(eslint(eslintRules))
.pipe(eslint.formatEach())
.pipe(eslint.failOnError());
});
};
| Print all scsslint errors before existing. | Print all scsslint errors before existing.
| JavaScript | apache-2.0 | samogami/grommet,codeswan/grommet,phuson/grommet,HewlettPackard/grommet,davrodpin/grommet,HewlettPackard/grommet,samogami/grommet,Dinesh-Ramakrishnan/grommet,primozs/grommet,marlonpp/grommet-old,nanndoj/grommet,kylebyerly-hp/grommet,davrodpin/grommet,nickjvm/grommet,HewlettPackard/grommet,marlonpp/grommet-old,codeswan/grommet,linde12/grommet,primozs/grommet,grommet/grommet,grommet/grommet,nickjvm/grommet,Dinesh-Ramakrishnan/grommet,grommet/grommet,phuson/grommet,nanndoj/grommet | ---
+++
@@ -2,10 +2,6 @@
var eslint = require('gulp-eslint');
var merge = require('lodash/object/merge');
var shelljs = require('shelljs');
-
-function failLintBuild() {
- process.exit(1);
-}
function scssLintExists() {
return shelljs.which('scss-lint');
@@ -24,7 +20,7 @@
var scsslint = require('gulp-scss-lint');
return gulp.src(options.scssAssets || []).pipe(scsslint({
'config': scssLintPath
- })).pipe(scsslint.failReporter()).on('error', failLintBuild);
+ })).pipe(scsslint.failReporter());
} else {
console.error('[scsslint] scsslint skipped!');
console.error('[scsslint] scss-lint is not installed. Please install ruby and the ruby gem scss-lint.'); |
b5af356f623429c5472f968ad2a84da9b599a7c4 | test/setup.js | test/setup.js | import 'babel-polyfill'
import fs from 'fs'
import path from 'path'
import jsdom from 'jsdom'
import dotenv from 'dotenv'
import chai, { expect } from 'chai'
import chaiImmutable from 'chai-immutable'
import sinon from 'sinon'
import sinonChai from 'sinon-chai'
import chaiSaga from './support/saga_helpers'
chai.use(chaiSaga)
chai.use(chaiImmutable)
chai.use(sinonChai)
dotenv.load()
global.ENV = require('../env')
global.chai = chai
global.expect = expect
global.sinon = sinon
if (!global.document) {
const html = fs.readFileSync(path.join(__dirname, '../public/template.html'), 'utf-8')
const exposedProperties = ['document', 'navigator', 'window']
global.document = jsdom.jsdom(html)
global.window = document.defaultView
global.navigator = { userAgent: 'node.js' }
global.URL = { createObjectURL: input => input }
const enums = [
...Object.keys(document.defaultView),
...['Image'],
]
enums.forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property)
global[property] = document.defaultView[property]
}
})
}
| import 'babel-polyfill'
import fs from 'fs'
import path from 'path'
import jsdom from 'jsdom'
import dotenv from 'dotenv'
import chai, { expect } from 'chai'
import chaiImmutable from 'chai-immutable'
import sinon from 'sinon'
import sinonChai from 'sinon-chai'
import chaiSaga from './support/saga_helpers'
chai.use(chaiSaga)
chai.use(chaiImmutable)
chai.use(sinonChai)
dotenv.load()
global.ENV = require('../env')
global.chai = chai
global.expect = expect
global.sinon = sinon
if (!global.document) {
const html = fs.readFileSync(path.join(__dirname, '../public/template.html'), 'utf-8')
const exposedProperties = ['document', 'navigator', 'window']
global.document = jsdom.jsdom(html)
global.window = document.defaultView
global.navigator = { userAgent: 'node.js' }
global.URL = { createObjectURL: input => input }
const enums = [
...Object.keys(document.defaultView),
...['Image'],
]
enums.forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property)
global[property] = document.defaultView[property]
}
})
}
// this is a polyfill to get enquire.js to work in a headless
// environment. it is required by react-slick for carousels
window.matchMedia = window.matchMedia || function () {
return {
matches: false,
addListener: () => {},
removeListener: () => {},
}
}
| Add a polyfill for matchMedia to get tests to run | Add a polyfill for matchMedia to get tests to run
| JavaScript | mit | ello/webapp,ello/webapp,ello/webapp | ---
+++
@@ -42,3 +42,13 @@
})
}
+// this is a polyfill to get enquire.js to work in a headless
+// environment. it is required by react-slick for carousels
+window.matchMedia = window.matchMedia || function () {
+ return {
+ matches: false,
+ addListener: () => {},
+ removeListener: () => {},
+ }
+}
+ |
9752da995a819fad7859f0bce13f1370bfda9f7b | server/routes/user-routes.js | server/routes/user-routes.js | var bcrypt = require('bcryptjs');
var router = require('express').Router();
var User = require('../models/user');
router.post('/', function(req, res) {
var salt = bcrypt.genSaltSync(10);
var user = new User({
username: req.body.user.username,
name: req.body.user.name,
password_digest: bcrypt.hashSync(req.body.user.password, salt)
});
user.save().then(function(userData) {
res.json({
message: 'Thanks for signing up!',
user: userData
});
},
function(err) {
console.log(err);
});
});
module.exports = router;
| var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
var router = require('express').Router();
var User = require('../models/user');
router.post('/', function(req, res) {
var salt = bcrypt.genSaltSync(10);
var user = new User({
username: req.body.user.username,
name: req.body.user.name,
password_digest: bcrypt.hashSync(req.body.user.password, salt)
});
user.save().then(function(userData) {
var token = jwt.sign(
userData._id,
process.env.JWT_SECRET,
{ expiresIn: 24 * 60 * 60 });
res.json({
message: 'Thanks for signing up!',
user: userData,
auth_token: token
});
},
function(err) {
console.log(err);
});
});
module.exports = router;
| Include auth token in sign up response. | Include auth token in sign up response.
| JavaScript | mit | FretlessJS-2016-03/notely,FretlessJS-2016-03/notely | ---
+++
@@ -1,4 +1,5 @@
var bcrypt = require('bcryptjs');
+var jwt = require('jsonwebtoken');
var router = require('express').Router();
var User = require('../models/user');
@@ -12,9 +13,14 @@
});
user.save().then(function(userData) {
+ var token = jwt.sign(
+ userData._id,
+ process.env.JWT_SECRET,
+ { expiresIn: 24 * 60 * 60 });
res.json({
message: 'Thanks for signing up!',
- user: userData
+ user: userData,
+ auth_token: token
});
},
function(err) { |
a707369a96aa892764775146c0ca081c9b95c712 | routes/front.js | routes/front.js | var express = require('express');
var router = express.Router();
router.get('/token', function (req, res) {
res.redirect('/');
});
router.get('/*', function (req, res, next) {
res.render('user/dashboard', { layout: 'user', title: 'Busy' });
});
module.exports = router;
| var express = require('express');
var router = express.Router();
router.get('/*', function (req, res, next) {
res.render('user/dashboard', { layout: 'user', title: 'Busy' });
});
module.exports = router;
| Remove token endPoint; need to redeploy. | Remove token endPoint; need to redeploy.
| JavaScript | mit | Sekhmet/busy,busyorg/busy,ryanbaer/busy,Sekhmet/busy,busyorg/busy,ryanbaer/busy | ---
+++
@@ -1,9 +1,5 @@
var express = require('express');
var router = express.Router();
-
-router.get('/token', function (req, res) {
- res.redirect('/');
-});
router.get('/*', function (req, res, next) {
res.render('user/dashboard', { layout: 'user', title: 'Busy' }); |
a115c44bcc17d6e6956d9d07030c2bb79c8a8f42 | ssr-express/demo/app.js | ssr-express/demo/app.js | /**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const express = require('express');
const path = require('path');
const app = express();
const AmpSsrMiddleware = require('../index.js');
const ampSsr = require('amp-toolbox-ssr');
// Setup the middleware and pass the ampSsr instance that will perform the transformations.
const ampSsrMiddleware = AmpSsrMiddleware.create({ampSsr: ampSsr});
// It's important that the ampSsrMiddleware is added *before* the static middleware.
// This allows the middleware to intercept the page rendered by static and transform it.
app.use(ampSsrMiddleware);
const staticMiddleware = express.static(path.join(__dirname, '/public'));
app.use(staticMiddleware);
const DEFAULT_PORT = 3000;
const port = process.env.PORT || DEFAULT_PORT;
app.listen(port, () => {
console.log('Example app listening on port 3000!');
});
| /**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const express = require('express');
const path = require('path');
const app = express();
const AmpSsrMiddleware = require('../index.js');
// It's important that the ampSsrMiddleware is added *before* the static middleware.
// This allows the middleware to intercept the page rendered by static and transform it.
app.use(AmpSsrMiddleware.create());
const staticMiddleware = express.static(path.join(__dirname, '/public'));
app.use(staticMiddleware);
const DEFAULT_PORT = 3000;
const port = process.env.PORT || DEFAULT_PORT;
app.listen(port, () => {
console.log('Example app listening on port 3000!');
});
| Remove amp-ssr component from demo | Remove amp-ssr component from demo
Change-Id: I39067fd6e71f28a5365b447824280b7c4f71a01d
| JavaScript | apache-2.0 | ampproject/amp-toolbox,google/amp-toolbox,google/amp-toolbox,ampproject/amp-toolbox,google/amp-toolbox,ampproject/amp-toolbox,ampproject/amp-toolbox | ---
+++
@@ -19,14 +19,10 @@
const path = require('path');
const app = express();
const AmpSsrMiddleware = require('../index.js');
-const ampSsr = require('amp-toolbox-ssr');
-
-// Setup the middleware and pass the ampSsr instance that will perform the transformations.
-const ampSsrMiddleware = AmpSsrMiddleware.create({ampSsr: ampSsr});
// It's important that the ampSsrMiddleware is added *before* the static middleware.
// This allows the middleware to intercept the page rendered by static and transform it.
-app.use(ampSsrMiddleware);
+app.use(AmpSsrMiddleware.create());
const staticMiddleware = express.static(path.join(__dirname, '/public'));
app.use(staticMiddleware); |
99a416385af062898d0709b64493dcb8859e9e27 | src/e2e-tests/basic.e2e.js | src/e2e-tests/basic.e2e.js | var assert = require('assert');
describe("Basic Test", function(){
it("Loads the basic demo page and sends values to server", function(){
browser.url('http://localhost:7888/src/e2e-tests/basic-demo-page?auto-activate-glasswing')
browser.waitUntil(function () {
var a = browser.execute(function(){
return window.a
}).value
return a == 25;
}, 20000, 'expected a to be set to 25 by the page')
browser.waitUntil(function () {
var a = browser.execute(function(){
return window.__jscb.recordedValueBuffer.length
}).value
console.log("length", a)
return a == 0;
}, 20000, 'expected values to be sent to server and value buffer to be reset');
})
it("Shows simple.js in the Glasswing file listing", function(){
browser.url('http://localhost:9500')
var fileLinksTable = $(".file-links")
fileLinksTable.waitForExist(5000)
var jsFilePath = "http://localhost:7888/src/e2e-tests/basic-demo-page/basic-demo.js"
assert(fileLinksTable.getText().indexOf(jsFilePath) !== -1)
})
})
}) | var assert = require('assert');
function assertContains(string, containedValue){
assert(string.indexOf(containedValue) !== -1)
}
describe("Basic Test", function(){
it("Loads the basic demo page and sends values to server", function(){
browser.url('http://localhost:7888/src/e2e-tests/basic-demo-page?auto-activate-glasswing')
browser.waitUntil(function () {
var a = browser.execute(function(){
return window.a
}).value
return a == 25;
}, 20000, 'expected a to be set to 25 by the page')
browser.waitUntil(function () {
var a = browser.execute(function(){
return window.__jscb.recordedValueBuffer.length
}).value
console.log("length", a)
return a == 0;
}, 20000, 'expected values to be sent to server and value buffer to be reset');
})
it("Shows simple.js in the Glasswing file listing", function(){
browser.url('http://localhost:9500')
var fileLinksTable = $(".file-links")
fileLinksTable.waitForExist(5000)
var jsFilePath = "http://localhost:7888/src/e2e-tests/basic-demo-page/basic-demo.js"
assertContains(fileLinksTable.getText(), jsFilePath)
})
it("Shows annotated source", function(){
browser.click(".file-links a");
var monacoEditor = $(".monaco-editor")
monacoEditor.waitForExist(10000)
assertContains(monacoEditor.getText(), "function square")
}).timeout(100000)
}) | Check annotated source code renders. | Check annotated source code renders.
| JavaScript | mit | mattzeunert/glasswing,mattzeunert/glasswing,mattzeunert/glasswing | ---
+++
@@ -1,4 +1,8 @@
var assert = require('assert');
+
+function assertContains(string, containedValue){
+ assert(string.indexOf(containedValue) !== -1)
+}
describe("Basic Test", function(){
it("Loads the basic demo page and sends values to server", function(){
@@ -22,7 +26,12 @@
var fileLinksTable = $(".file-links")
fileLinksTable.waitForExist(5000)
var jsFilePath = "http://localhost:7888/src/e2e-tests/basic-demo-page/basic-demo.js"
- assert(fileLinksTable.getText().indexOf(jsFilePath) !== -1)
+ assertContains(fileLinksTable.getText(), jsFilePath)
})
- })
+ it("Shows annotated source", function(){
+ browser.click(".file-links a");
+ var monacoEditor = $(".monaco-editor")
+ monacoEditor.waitForExist(10000)
+ assertContains(monacoEditor.getText(), "function square")
+ }).timeout(100000)
}) |
b4ab5d7ff3556f9a40c425afaa4dab5601b37027 | models/paste.js | models/paste.js | const mongoose = require('mongoose');
const shortid = require('shortid');
const paste = new mongoose.Schema({
_id: { type: String, default: shortid.generate },
paste: { type: String },
expiresAt: { type: Date, expires: 0, default: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7) }
}, {
timestamps: true
});
module.exports = mongoose.model('Paste', paste);
| const mongoose = require('mongoose');
const shortid = require('shortid');
const paste = new mongoose.Schema({
_id: { type: String, default: shortid.generate },
paste: { type: String },
expiresAt: { type: Date, expires: 0 }
}, {
timestamps: true
});
module.exports = mongoose.model('Paste', paste);
| Remove default expiry on model | Remove default expiry on model
| JavaScript | mit | JoeBiellik/paste,JoeBiellik/paste | ---
+++
@@ -4,7 +4,7 @@
const paste = new mongoose.Schema({
_id: { type: String, default: shortid.generate },
paste: { type: String },
- expiresAt: { type: Date, expires: 0, default: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7) }
+ expiresAt: { type: Date, expires: 0 }
}, {
timestamps: true
}); |
0f3369a02a6386d8bfb895de09faa9b1c168715d | src/app/components/msp/common/consent-modal/i18n/data/en/index.js | src/app/components/msp/common/consent-modal/i18n/data/en/index.js | module.exports = {
title: 'Information collection notice',
body: 'The information in this application is collected by the Ministry of Health under section 26(a) of the Freedom of Information and Protection of Privacy Act and will be used to determine eligibility for provincial health care benefits in BC and administer Premium Assistance. Should you have any questions about the collection of this personal information please <a href="http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents-contact-us" target="_blank">contact Health Insurance of BC</a> <i class="fa fa-external-link" aria-hidden="true"></i>.',
agreeLabel: 'I have read and understand the information above and would like to continue to apply for MSP',
continueButton: 'Continue'
}
| module.exports = {
title: 'Information collection notice',
body: '<p>The data you enter on this form is saved locally to the computer or device you are using. The data will be deleted when you close the web browser you are using or after your submit your application.</p><p>The information in this application is collected by the Ministry of Health under section 26(a) of the Freedom of Information and Protection of Privacy Act and will be used to determine eligibility for provincial health care benefits in BC and administer Premium Assistance. Should you have any questions about the collection of this personal information please <a href="http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents-contact-us" target="_blank">contact Health Insurance of BC</a> <i class="fa fa-external-link" aria-hidden="true"></i>.</p>',
agreeLabel: 'I have read and understand the information above and would like to continue to apply for MSP',
continueButton: 'Continue'
}
| Add info re: data saving | Add info re: data saving | JavaScript | apache-2.0 | bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP | ---
+++
@@ -1,6 +1,6 @@
module.exports = {
title: 'Information collection notice',
- body: 'The information in this application is collected by the Ministry of Health under section 26(a) of the Freedom of Information and Protection of Privacy Act and will be used to determine eligibility for provincial health care benefits in BC and administer Premium Assistance. Should you have any questions about the collection of this personal information please <a href="http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents-contact-us" target="_blank">contact Health Insurance of BC</a> <i class="fa fa-external-link" aria-hidden="true"></i>.',
+ body: '<p>The data you enter on this form is saved locally to the computer or device you are using. The data will be deleted when you close the web browser you are using or after your submit your application.</p><p>The information in this application is collected by the Ministry of Health under section 26(a) of the Freedom of Information and Protection of Privacy Act and will be used to determine eligibility for provincial health care benefits in BC and administer Premium Assistance. Should you have any questions about the collection of this personal information please <a href="http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents-contact-us" target="_blank">contact Health Insurance of BC</a> <i class="fa fa-external-link" aria-hidden="true"></i>.</p>',
agreeLabel: 'I have read and understand the information above and would like to continue to apply for MSP',
continueButton: 'Continue'
|
e2bff214c4773626816d3f58d19a2a84451c333d | src/astring_plugin/index.js | src/astring_plugin/index.js | import astring from 'astring';
// Create a custom generator that inherits from Astring's default generator
const customGenerator = Object.assign({}, astring.defaultGenerator, {
Literal(node, state) {
if (node.raw != null) {
const first = node.raw.charAt(0);
const last = node.raw.charAt(node.raw.length - 1);
if ((first === 12300 && last === 12301) // 「」
|| (first === 8216 && last === 8217)) { // ‘’
state.output.write(`'${node.raw.slice(1, node.raw.length - 1)}'`);
}
if ((first === 12302 && last === 12303) // 『』
|| (first === 8220 && last === 8221)) { // “”
state.output.write(`"${node.raw.slice(1, node.raw.length - 1)}"`);
}
if ((first === 34 && last === 34)
|| (first === 39 && last === 39)) { // "" or ''
state.output.write(node.raw);
} else { // HaLang-specific string literals
state.output.write(node.value);
}
} else if (node.regex != null) {
this.RegExpLiteral(node, state);
} else {
state.output.write(JSON.stringify(node.value));
}
},
});
export default customGenerator;
| import astring from 'astring';
// Create a custom generator that inherits from Astring's default generator
const customGenerator = Object.assign({}, astring.defaultGenerator, {
Literal(node, state) {
if (node.raw != null) {
const first = node.raw.charAt(0).charCodeAt();
const last = node.raw.charAt(node.raw.length - 1).charCodeAt();
if ((first === 12300 && last === 12301) // 「」
|| (first === 8216 && last === 8217)) { // ‘’
state.output.write(`'${node.raw.slice(1, node.raw.length - 1)}'`);
} else if ((first === 12302 && last === 12303) // 『』
|| (first === 8220 && last === 8221)) { // “”
state.output.write(`"${node.raw.slice(1, node.raw.length - 1)}"`);
} else if ((first === 34 && last === 34)
|| (first === 39 && last === 39)) { // "" or ''
state.output.write(node.raw);
} else { // HaLang-specific string literals
state.output.write(node.value);
}
} else if (node.regex != null) {
this.RegExpLiteral(node, state);
} else {
state.output.write(JSON.stringify(node.value));
}
},
});
export default customGenerator;
| Fix the bug hidden in astring plugin | Fix the bug hidden in astring plugin
| JavaScript | mit | laosb/hatp | ---
+++
@@ -4,17 +4,16 @@
const customGenerator = Object.assign({}, astring.defaultGenerator, {
Literal(node, state) {
if (node.raw != null) {
- const first = node.raw.charAt(0);
- const last = node.raw.charAt(node.raw.length - 1);
+ const first = node.raw.charAt(0).charCodeAt();
+ const last = node.raw.charAt(node.raw.length - 1).charCodeAt();
+
if ((first === 12300 && last === 12301) // 「」
|| (first === 8216 && last === 8217)) { // ‘’
state.output.write(`'${node.raw.slice(1, node.raw.length - 1)}'`);
- }
- if ((first === 12302 && last === 12303) // 『』
+ } else if ((first === 12302 && last === 12303) // 『』
|| (first === 8220 && last === 8221)) { // “”
state.output.write(`"${node.raw.slice(1, node.raw.length - 1)}"`);
- }
- if ((first === 34 && last === 34)
+ } else if ((first === 34 && last === 34)
|| (first === 39 && last === 39)) { // "" or ''
state.output.write(node.raw);
} else { // HaLang-specific string literals |
8a5185e85c1f6206ed59256b2a6c2e996af96a6b | tools/bundle-deploy.js | tools/bundle-deploy.js | const { execSync } = require('child_process');
const path = require('path');
execSync(`
git config user.email "andrey.a.gubanov@gmail.com" &&
git config user.name "Andrey Gubanov (his digital copy)" &&
git clone -b gh-pages https://$GH_TOKEN@github.com/matreshkajs/matreshka-router.git &&
npm run bundle &&
cd bundle &&
git add . &&
git commit --allow-empty -m $npm_package_version &&
git push https://$GH_TOKEN@github.com/matreshkajs/matreshka-router.git gh-pages
`, {
cwd: path.resolve(__dirname, '..')
});
| const { execSync } = require('child_process');
const path = require('path');
execSync(`
git config user.email "andrey.a.gubanov@gmail.com" &&
git config user.name "Andrey Gubanov (his digital copy)" &&
git clone -b gh-pages https://$GH_TOKEN@github.com/matreshkajs/matreshka-router.git bundle &&
npm run bundle &&
cd bundle &&
git add . &&
git commit --allow-empty -m $npm_package_version &&
git push https://$GH_TOKEN@github.com/matreshkajs/matreshka-router.git gh-pages
`, {
cwd: path.resolve(__dirname, '..')
});
| Clone bundle repo tu bundle folder | fix: Clone bundle repo tu bundle folder
| JavaScript | mit | matreshkajs/matreshka-router,finom/matreshka_router | ---
+++
@@ -4,7 +4,7 @@
execSync(`
git config user.email "andrey.a.gubanov@gmail.com" &&
git config user.name "Andrey Gubanov (his digital copy)" &&
- git clone -b gh-pages https://$GH_TOKEN@github.com/matreshkajs/matreshka-router.git &&
+ git clone -b gh-pages https://$GH_TOKEN@github.com/matreshkajs/matreshka-router.git bundle &&
npm run bundle &&
cd bundle &&
git add . && |
fc31a6711da30682e208cc257b567c136fe9a6b5 | client/src/entrypoints/snippets/snippet-chooser-modal.js | client/src/entrypoints/snippets/snippet-chooser-modal.js | import $ from 'jquery';
window.SNIPPET_CHOOSER_MODAL_ONLOAD_HANDLERS = {
choose: function (modal) {
function ajaxifyLinks(context) {
$('a.snippet-choice', modal.body).on('click', function () {
modal.loadUrl(this.href);
return false;
});
$('.pagination a', context).on('click', function () {
loadResults(this.href);
return false;
});
}
var searchForm$ = $('form.snippet-search', modal.body);
var searchUrl = searchForm$.attr('action');
var request;
function search() {
loadResults(searchUrl, searchForm$.serialize());
return false;
}
function loadResults(url, data) {
var opts = {
url: url,
success: function (resultsData, status) {
request = null;
$('#search-results').html(resultsData);
ajaxifyLinks($('#search-results'));
},
error: function () {
request = null;
},
};
if (data) {
opts.data = data;
}
request = $.ajax(opts);
}
$('form.snippet-search', modal.body).on('submit', search);
$('#snippet-chooser-locale', modal.body).on('change', search);
$('#id_q').on('input', function () {
if (request) {
request.abort();
}
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(search, 200);
$(this).data('timer', wait);
});
ajaxifyLinks(modal.body);
},
chosen: function (modal, jsonData) {
modal.respond('snippetChosen', jsonData.result);
modal.close();
},
};
| import $ from 'jquery';
import { SearchController } from '../../includes/chooserModal';
window.SNIPPET_CHOOSER_MODAL_ONLOAD_HANDLERS = {
choose: function (modal) {
function ajaxifyLinks(context) {
$('a.snippet-choice', modal.body).on('click', function () {
modal.loadUrl(this.href);
return false;
});
$('.pagination a', context).on('click', function () {
searchController.fetchResults(this.href);
return false;
});
}
const searchController = new SearchController({
form: $('form.snippet-search', modal.body),
resultsContainerSelector: '#search-results',
onLoadResults: (context) => {
ajaxifyLinks(context);
},
});
searchController.attachSearchInput('#id_q');
searchController.attachSearchFilter('#snippet-chooser-locale');
ajaxifyLinks(modal.body);
},
chosen: function (modal, jsonData) {
modal.respond('snippetChosen', jsonData.result);
modal.close();
},
};
| Use SearchController on snippet chooser modal | Use SearchController on snippet chooser modal
| JavaScript | bsd-3-clause | wagtail/wagtail,wagtail/wagtail,rsalmaso/wagtail,wagtail/wagtail,thenewguy/wagtail,thenewguy/wagtail,zerolab/wagtail,rsalmaso/wagtail,wagtail/wagtail,rsalmaso/wagtail,thenewguy/wagtail,zerolab/wagtail,thenewguy/wagtail,rsalmaso/wagtail,zerolab/wagtail,zerolab/wagtail,wagtail/wagtail,rsalmaso/wagtail,thenewguy/wagtail,zerolab/wagtail | ---
+++
@@ -1,4 +1,5 @@
import $ from 'jquery';
+import { SearchController } from '../../includes/chooserModal';
window.SNIPPET_CHOOSER_MODAL_ONLOAD_HANDLERS = {
choose: function (modal) {
@@ -9,49 +10,20 @@
});
$('.pagination a', context).on('click', function () {
- loadResults(this.href);
+ searchController.fetchResults(this.href);
return false;
});
}
- var searchForm$ = $('form.snippet-search', modal.body);
- var searchUrl = searchForm$.attr('action');
- var request;
-
- function search() {
- loadResults(searchUrl, searchForm$.serialize());
- return false;
- }
-
- function loadResults(url, data) {
- var opts = {
- url: url,
- success: function (resultsData, status) {
- request = null;
- $('#search-results').html(resultsData);
- ajaxifyLinks($('#search-results'));
- },
- error: function () {
- request = null;
- },
- };
- if (data) {
- opts.data = data;
- }
- request = $.ajax(opts);
- }
-
- $('form.snippet-search', modal.body).on('submit', search);
- $('#snippet-chooser-locale', modal.body).on('change', search);
-
- $('#id_q').on('input', function () {
- if (request) {
- request.abort();
- }
- clearTimeout($.data(this, 'timer'));
- var wait = setTimeout(search, 200);
- $(this).data('timer', wait);
+ const searchController = new SearchController({
+ form: $('form.snippet-search', modal.body),
+ resultsContainerSelector: '#search-results',
+ onLoadResults: (context) => {
+ ajaxifyLinks(context);
+ },
});
+ searchController.attachSearchInput('#id_q');
+ searchController.attachSearchFilter('#snippet-chooser-locale');
ajaxifyLinks(modal.body);
}, |
fc610c08cd26d108ee1e48da4b19bd8c90cf570f | app/assets/javascripts/spree/backend/solidus_paypal_braintree.js | app/assets/javascripts/spree/backend/solidus_paypal_braintree.js | //= require spree/braintree_hosted_form.js
$(function() {
var $paymentForm = $("#new_payment"),
$hostedFields = $("[data-braintree-hosted-fields]");
function onError (err) {
var msg = err.name + ": " + err.message;
show_flash("error", msg);
console.error(err);
}
// exit early if we're not looking at the New Payment form, or if no
// SolidusPaypalBraintree payment methods have been configured.
if (!$paymentForm.length || !$hostedFields.length) { return; }
$hostedFields.each(function() {
var $this = $(this),
$new = $("[name=card]", $this);
var id = $this.data("id");
var hostedFieldsInstance;
$new.on("change", function() {
var isNew = $(this).val() === "new";
function setHostedFieldsInstance(instance) {
hostedFieldsInstance = instance;
return instance;
}
if (isNew && hostedFieldsInstance === null) {
braintreeForm = new BraintreeHostedForm($paymentForm, $this, id);
braintreeForm.initializeHostedFields().
then(setHostedFieldsInstance).
then(braintreeForm.addFormHook(onError)).
fail(onError);
}
});
});
});
| //= require spree/braintree_hosted_form.js
$(function() {
var $paymentForm = $("#new_payment"),
$hostedFields = $("[data-braintree-hosted-fields]");
function onError (err) {
var msg = err.name + ": " + err.message;
show_flash("error", msg);
console.error(err);
}
// exit early if we're not looking at the New Payment form, or if no
// SolidusPaypalBraintree payment methods have been configured.
if (!$paymentForm.length || !$hostedFields.length) { return; }
$.when(
$.getScript("https://js.braintreegateway.com/web/3.9.0/js/client.min.js"),
$.getScript("https://js.braintreegateway.com/web/3.9.0/js/hosted-fields.min.js")
).done(function() {
$hostedFields.each(function() {
var $this = $(this),
$new = $("[name=card]", $this);
var id = $this.data("id");
var hostedFieldsInstance;
$new.on("change", function() {
var isNew = $(this).val() === "new";
function setHostedFieldsInstance(instance) {
hostedFieldsInstance = instance;
return instance;
}
if (isNew && hostedFieldsInstance === null) {
braintreeForm = new BraintreeHostedForm($paymentForm, $container, id);
braintreeForm.initializeHostedFields().
then(setHostedFieldsInstance).
then(braintreeForm.addFormHook(onError)).
fail(onError);
}
});
});
});
});
| Load the braintree client on demand libs in admin | Load the braintree client on demand libs in admin
Like in frontend we load the braintree client libs on demand and then initialize the hosted fields.
| JavaScript | bsd-3-clause | solidusio/solidus_paypal_braintree,solidusio/solidus_paypal_braintree,solidusio/solidus_paypal_braintree,solidusio/solidus_paypal_braintree | ---
+++
@@ -14,29 +14,34 @@
// SolidusPaypalBraintree payment methods have been configured.
if (!$paymentForm.length || !$hostedFields.length) { return; }
- $hostedFields.each(function() {
- var $this = $(this),
- $new = $("[name=card]", $this);
+ $.when(
+ $.getScript("https://js.braintreegateway.com/web/3.9.0/js/client.min.js"),
+ $.getScript("https://js.braintreegateway.com/web/3.9.0/js/hosted-fields.min.js")
+ ).done(function() {
+ $hostedFields.each(function() {
+ var $this = $(this),
+ $new = $("[name=card]", $this);
- var id = $this.data("id");
+ var id = $this.data("id");
- var hostedFieldsInstance;
+ var hostedFieldsInstance;
- $new.on("change", function() {
- var isNew = $(this).val() === "new";
+ $new.on("change", function() {
+ var isNew = $(this).val() === "new";
- function setHostedFieldsInstance(instance) {
- hostedFieldsInstance = instance;
- return instance;
- }
+ function setHostedFieldsInstance(instance) {
+ hostedFieldsInstance = instance;
+ return instance;
+ }
- if (isNew && hostedFieldsInstance === null) {
- braintreeForm = new BraintreeHostedForm($paymentForm, $this, id);
- braintreeForm.initializeHostedFields().
- then(setHostedFieldsInstance).
- then(braintreeForm.addFormHook(onError)).
- fail(onError);
- }
+ if (isNew && hostedFieldsInstance === null) {
+ braintreeForm = new BraintreeHostedForm($paymentForm, $container, id);
+ braintreeForm.initializeHostedFields().
+ then(setHostedFieldsInstance).
+ then(braintreeForm.addFormHook(onError)).
+ fail(onError);
+ }
+ });
});
});
}); |
5b30c625b6d59e087341259174e78b97db07eb4a | lib/nb-slug.js | lib/nb-slug.js | 'use strict';
var diacritics = require('./diacritics');
function nbSlug(name) {
var diacriticsMap = {};
for (var i = 0; i < diacritics.length; i++) {
var letters = diacritics[i].letters;
for (var j = 0; j < letters.length ; j++) {
diacriticsMap[letters[j]] = diacritics[i].base;
}
}
function removeDiacritics (str) {
return str.replace(/[^\u0000-\u007E]/g, function(a){
return diacriticsMap[a] || a;
});
}
var slug = removeDiacritics(String(name || '').trim())
.replace(/^\s\s*/, '') // Trim start
.replace(/\s\s*$/, '') // Trim end
.toLowerCase() // Camel case is bad
.replace(/[^a-z0-9_\-~!\+\s]+/g, '') // Exchange invalid chars
.replace(/[\s]+/g, '-') // Swap whitespace for single hyphen
.replace(/--/g, '-')
.replace(/--/g, '-')
.replace(/--/g, '-')
.replace(/--/g, '-')
.trim();
while (slug[slug.length - 1] === '-') {
slug = slug.slice(0, -1);
}
return slug;
}
module.exports = nbSlug;
| 'use strict';
var diacritics = require('./diacritics');
function nbSlug(name) {
var diacriticsMap = {};
for (var i = 0; i < diacritics.length; i++) {
var letters = diacritics[i].letters;
for (var j = 0; j < letters.length ; j++) {
diacriticsMap[letters[j]] = diacritics[i].base;
}
}
function removeDiacritics (str) {
return str.replace(/[^\u0000-\u007E]/g, function(a){
return diacriticsMap[a] || a;
});
}
var slug = removeDiacritics(String(name || '').trim())
.replace(/^\s\s*/, '') // Trim start
.replace(/\s\s*$/, '') // Trim end
.toLowerCase() // Camel case is bad
.replace(/[^a-z0-9\-\s]+/g, '') // Exchange invalid chars
.replace(/[\s]+/g, '-') // Swap whitespace for single hyphen
.replace(/-{2,}/g, '-') // Replace consecutive single hypens
.trim();
while (slug[slug.length - 1] === '-') {
slug = slug.slice(0, -1);
}
return slug;
}
module.exports = nbSlug;
| Remove -, !, + and ~ from the slug too | Remove -, !, + and ~ from the slug too | JavaScript | unlicense | nurimba/nb-slug,nurimba/nb-slug | ---
+++
@@ -23,12 +23,9 @@
.replace(/^\s\s*/, '') // Trim start
.replace(/\s\s*$/, '') // Trim end
.toLowerCase() // Camel case is bad
- .replace(/[^a-z0-9_\-~!\+\s]+/g, '') // Exchange invalid chars
+ .replace(/[^a-z0-9\-\s]+/g, '') // Exchange invalid chars
.replace(/[\s]+/g, '-') // Swap whitespace for single hyphen
- .replace(/--/g, '-')
- .replace(/--/g, '-')
- .replace(/--/g, '-')
- .replace(/--/g, '-')
+ .replace(/-{2,}/g, '-') // Replace consecutive single hypens
.trim();
while (slug[slug.length - 1] === '-') { |
55ab768d9fd5adf4fbefa3db2d121fdbe6c840f4 | resources/js/modules/accordion.js | resources/js/modules/accordion.js | import 'accordion/src/accordion.js';
(function() {
"use strict";
document.querySelectorAll('.accordion').forEach(function(item) {
new Accordion(item, {
onToggle: function(target){
// Only allow one accordion item open at time
target.accordion.folds.forEach(fold => {
if(fold !== target) {
fold.open = false;
}
});
// Allow the content to be shown if its open or hide it when closed
target.content.classList.toggle('hidden')
},
enabledClass: 'enabled'
});
// Hide all accordion content from the start so content inside it isn't part of the tabindex
item.querySelectorAll('.content').forEach(function(item) {
item.classList.add('hidden');
});
// Remove the role="tablist" since it is not needed
item.removeAttribute('role');
});
document.querySelectorAll('ul.accordion > li').forEach(function(item) {
// Apply the required content fold afterwards to simplify the html
item.querySelector('div').classList.add('fold');
});
})();
| import 'accordion/src/accordion.js';
(function() {
"use strict";
document.querySelectorAll('.accordion').forEach(function(item) {
new Accordion(item, {
onToggle: function(target){
// Only allow one accordion item open at time
target.accordion.folds.forEach(fold => {
if(fold !== target) {
fold.open = false;
}
});
// Allow the content to be shown if its open or hide it when closed
target.content.classList.toggle('hidden')
},
enabledClass: 'enabled'
});
// Hide all accordion content from the start so content inside it isn't part of the tabindex
item.querySelectorAll('.content').forEach(function(item) {
item.classList.add('hidden');
});
// Remove the role="tablist" since it is not needed
item.removeAttribute('role');
item.querySelectorAll('li a:first-child').forEach(function(item) {
item.setAttribute('role', 'button');
});
});
document.querySelectorAll('ul.accordion > li').forEach(function(item) {
// Apply the required content fold afterwards to simplify the html
item.querySelector('div').classList.add('fold');
});
})();
| Set the role to button instead of tab | Set the role to button instead of tab
| JavaScript | mit | waynestate/base-site,waynestate/base-site | ---
+++
@@ -26,6 +26,10 @@
// Remove the role="tablist" since it is not needed
item.removeAttribute('role');
+
+ item.querySelectorAll('li a:first-child').forEach(function(item) {
+ item.setAttribute('role', 'button');
+ });
});
document.querySelectorAll('ul.accordion > li').forEach(function(item) { |
2a8170bd4f0ed6fad4dcd8441c2e8d162fbc4431 | simple-todos.js | simple-todos.js | if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: [
{ text: "This is task 1" },
{ text: "This is task 2" },
{ text: "This is task 3" }
]
});
}
| Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: function () {
return Tasks.find({});
}
});
}
| Make tasks a MongoDB collection. | Make tasks a MongoDB collection.
| JavaScript | mit | chooie/meteor-todo | ---
+++
@@ -1,10 +1,10 @@
+Tasks = new Mongo.Collection("tasks");
+
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
- tasks: [
- { text: "This is task 1" },
- { text: "This is task 2" },
- { text: "This is task 3" }
- ]
+ tasks: function () {
+ return Tasks.find({});
+ }
});
} |
c5ca7c86331bb349c4bd3ccd7d5c12cdce0fa924 | utils/getOutputPath.js | utils/getOutputPath.js | const path = require('path');
const getOptions = require('./getOptions');
module.exports = (options, jestRootDir) => {
// Override outputName and outputDirectory with outputFile if outputFile is defined
let output = options.outputFile;
if (!output) {
// Set output to use new outputDirectory and fallback on original output
const outputName = (options.uniqueOutputName === 'true') ? getOptions.getUniqueOutputName() : options.outputName
output = path.join(options.outputDirectory, outputName);
}
const finalOutput = getOptions.replaceRootDirInOutput(jestRootDir, output);
return finalOutput;
};
| const path = require('path');
const getOptions = require('./getOptions');
module.exports = (options, jestRootDir) => {
// Override outputName and outputDirectory with outputFile if outputFile is defined
let output = options.outputFile;
if (!output) {
// Set output to use new outputDirectory and fallback on original output
const outputName = (options.uniqueOutputName === 'true') ? getOptions.getUniqueOutputName() : options.outputName
output = getOptions.replaceRootDirInOutput(jestRootDir, options.outputDirectory);
const finalOutput = path.join(output, outputName);
return finalOutput;
}
const finalOutput = getOptions.replaceRootDirInOutput(jestRootDir, output);
return finalOutput;
};
| Replace <rootDir> prior to path.join(). | Replace <rootDir> prior to path.join().
This allows outputDirectory to be formatted like <rootDir>/../some/dir. In that case, path.join() assumes the .. cancels out the <rootDir>, which seems entirely reasonable. Unfortunately, it means the final value is some/dir, and that ends up rooted at process.cwd(), which doesn't always match <rootDir>.
Handling the <rootDir> replacement first allevaites this problem.
| JavaScript | apache-2.0 | palmerj3/jest-junit | ---
+++
@@ -7,7 +7,9 @@
if (!output) {
// Set output to use new outputDirectory and fallback on original output
const outputName = (options.uniqueOutputName === 'true') ? getOptions.getUniqueOutputName() : options.outputName
- output = path.join(options.outputDirectory, outputName);
+ output = getOptions.replaceRootDirInOutput(jestRootDir, options.outputDirectory);
+ const finalOutput = path.join(output, outputName);
+ return finalOutput;
}
const finalOutput = getOptions.replaceRootDirInOutput(jestRootDir, output); |
39b2bb6cf1148bb0c63d19b52473c46e77c5c212 | src/components/SSOLanding.js | src/components/SSOLanding.js | import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import Link from 'react-router-dom/Link';
import queryString from 'query-string';
const SSOLanding = (props) => {
const search = props.location.search;
if (!search) {
return <div>No search string</div>;
}
const query = queryString.parse(search);
const token = query['sso-token'];
if (!token) {
return <div>No <tt>sso-token</tt> query parameter</div>;
}
props.stripes.setToken(token);
return (
<div>
<p>Logged in with: token <tt>{token}</tt></p>
<p><Link to="/">continue</Link></p>
</div>
);
};
SSOLanding.propTypes = {
location: PropTypes.shape({
search: PropTypes.string,
}).isRequired,
stripes: PropTypes.shape({
setToken: PropTypes.func.isRequired,
}).isRequired,
};
export default withRouter(SSOLanding);
| import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import Link from 'react-router-dom/Link';
import queryString from 'query-string';
const SSOLanding = (props) => {
const search = props.location.search;
if (!search) {
return <div>No search string</div>;
}
const query = queryString.parse(search);
const token = query['ssoToken'];
if (!token) {
return <div>No <tt>ssoToken</tt> query parameter</div>;
}
props.stripes.setToken(token);
return (
<div>
<p>Logged in with: token <tt>{token}</tt></p>
<p><Link to="/">continue</Link></p>
</div>
);
};
SSOLanding.propTypes = {
location: PropTypes.shape({
search: PropTypes.string,
}).isRequired,
stripes: PropTypes.shape({
setToken: PropTypes.func.isRequired,
}).isRequired,
};
export default withRouter(SSOLanding);
| Change name of SSO token parameter from sso-token to ssoToken | Change name of SSO token parameter from sso-token to ssoToken
This makes is consistent with the cookie-name that I am about to
implement. The spec for cookies says hyphens are OK in the name, but
not everyone's experience agrees: see
https://stackoverflow.com/a/27235182
Modifies STCOR-20; relates to STCOR-38.
| JavaScript | apache-2.0 | folio-org/stripes-core,folio-org/stripes-core,folio-org/stripes-core | ---
+++
@@ -10,9 +10,9 @@
return <div>No search string</div>;
}
const query = queryString.parse(search);
- const token = query['sso-token'];
+ const token = query['ssoToken'];
if (!token) {
- return <div>No <tt>sso-token</tt> query parameter</div>;
+ return <div>No <tt>ssoToken</tt> query parameter</div>;
}
props.stripes.setToken(token); |
5193f5908f8929b7908649950161d9531c04f8b1 | lib/assets/javascripts/new-dashboard/store/utils/getCARTOData.js | lib/assets/javascripts/new-dashboard/store/utils/getCARTOData.js | export default function getCARTOData () {
if (window.CartoConfig) {
return window.CartoConfig.data;
}
return {
user_data: window.user_data,
organization_notifications: window.organization_notifications
};
}
| export default function getCARTOData () {
if (window.CartoConfig) {
return window.CartoConfig.data;
}
return {
user_data: window.user_data,
organization_notifications: window.organization_notifications || []
};
}
| Set organization_notifications to [] if no notificarions are available | Set organization_notifications to [] if no notificarions are available
| JavaScript | bsd-3-clause | CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb | ---
+++
@@ -5,6 +5,6 @@
return {
user_data: window.user_data,
- organization_notifications: window.organization_notifications
+ organization_notifications: window.organization_notifications || []
};
} |
c21d52d96ec21d9a43da3467ee66364619e1e3f4 | app/containers/FlagView.js | app/containers/FlagView.js | import React from 'react';
import { connect } from 'react-redux';
import admin from '../utils/admin';
import Concept from '../components/Concept';
const FlagView = React.createClass({
componentWillMount() {
this.props.fetchFlags();
},
render() {
const { flags } = this.props;
return (
<div className="FlagView">
{flags.map((flag) =>
<div style={{ borderBottom: '1px solid #ccc' }}>
<Concept concept={flag.origin}/>
{flag.type} ({flag.value})
<Concept concept={flag.target}/>
</div>
)}
</div>
);
},
});
export default connect(
(state) => {
const { data: { flags } } = state;
return {
flags: flags.data,
};
},
{
fetchFlags: admin.actions.flags,
}
)(FlagView);
| import React from 'react';
import { connect } from 'react-redux';
import admin from '../utils/admin';
import Concept from '../components/Concept';
const FlagView = React.createClass({
componentWillMount() {
this.props.fetchFlags();
},
render() {
const { flags } = this.props;
return (
<div className="FlagView">
{flags.map((flag) =>
<div style={{ borderBottom: '1px solid #ccc' }} key={flag.id}>
<Concept concept={flag.origin}/>
{flag.type} ({flag.value})
<Concept concept={flag.target}/>
</div>
)}
</div>
);
},
});
export default connect(
(state) => {
const { data: { flags } } = state;
return {
flags: flags.data,
};
},
{
fetchFlags: admin.actions.flags,
}
)(FlagView);
| Add missing key to flags view to remove warning | Add missing key to flags view to remove warning
| JavaScript | mit | transparantnederland/relationizer,transparantnederland/relationizer,waagsociety/tnl-relationizer,transparantnederland/browser,transparantnederland/browser,waagsociety/tnl-relationizer | ---
+++
@@ -16,7 +16,7 @@
return (
<div className="FlagView">
{flags.map((flag) =>
- <div style={{ borderBottom: '1px solid #ccc' }}>
+ <div style={{ borderBottom: '1px solid #ccc' }} key={flag.id}>
<Concept concept={flag.origin}/>
{flag.type} ({flag.value})
<Concept concept={flag.target}/> |
9730bfb3db49d210d496e2289bf90154ab497612 | scripts/components/Footer.js | scripts/components/Footer.js | import { format } from 'date-fns';
import React from 'react'
import { Navigation } from './blocks/Navigation'
import styles from './Main.css'
const socialLinks = [
{
to: 'https://stackoverflow.com/story/usehotkey',
title: 'StackOverflow'
},
// {
// to: 'https://yadi.sk/d/QzyQ04br3HXrmU',
// title: 'CV'
// },
{
to: 'https://www.linkedin.com/in/igor-golopolosov-98382012a/',
title: 'LinkedIn'
},
{
to: 'https://github.com/usehotkey',
title: 'GitHub'
},
// {
// to: 'https://soundcloud.com/hotkeymusic',
// title: 'SoundCloud'
// },
]
export const Footer = () => {
return (
<footer className={styles.footer}>
<div className={styles.socialNav}>
<Navigation links={socialLinks} external />
</div>
<div>
<small>
{`Igor Golopolosov, 2016-${format(new Date(), 'YYYY')} ♥️`}
<b>igolopolosov@gmail.com</b>
</small>
</div>
</footer>
)
}
| import { format } from 'date-fns';
import React from 'react'
import { Navigation } from './blocks/Navigation'
import styles from './Main.css'
const socialLinks = [
{
to: 'https://stackoverflow.com/story/usehotkey',
title: 'StackOverflow'
},
// {
// to: 'https://yadi.sk/d/QzyQ04br3HXrmU',
// title: 'CV'
// },
{
to: 'https://www.linkedin.com/in/igor-golopolosov-98382012a/',
title: 'LinkedIn'
},
{
to: 'https://github.com/usehotkey',
title: 'GitHub'
},
// {
// to: 'https://soundcloud.com/hotkeymusic',
// title: 'SoundCloud'
// },
]
export const Footer = () => {
return (
<footer className={styles.footer}>
<div className={styles.socialNav}>
<Navigation links={socialLinks} external />
</div>
<small>
{`Igor Golopolosov, ${format(new Date(), 'YYYY')} ♥️`}
<b>igolopolosov@gmail.com</b>
</small>
</footer>
)
}
| Remove first year from footer | [change] Remove first year from footer
| JavaScript | mit | usehotkey/my-personal-page,usehotkey/my-personal-page,usehotkey/my-personal-page,usehotkey/my-personal-page | ---
+++
@@ -32,12 +32,10 @@
<div className={styles.socialNav}>
<Navigation links={socialLinks} external />
</div>
- <div>
- <small>
- {`Igor Golopolosov, 2016-${format(new Date(), 'YYYY')} ♥️`}
- <b>igolopolosov@gmail.com</b>
- </small>
- </div>
+ <small>
+ {`Igor Golopolosov, ${format(new Date(), 'YYYY')} ♥️`}
+ <b>igolopolosov@gmail.com</b>
+ </small>
</footer>
)
} |
ad207a87639cef156201b8e2a208f38c51e93c50 | src/js/math.js | src/js/math.js | import THREE from 'three';
export function randomPointOnSphere( vector = new THREE.Vector3() ) {
const theta = 2 * Math.PI * Math.random();
const u = 2 * Math.random() - 1;
const v = Math.sqrt( 1 - u * u );
return vector.set(
v * Math.cos( theta ),
v * Math.sin( theta ),
u
);
}
| import THREE from 'three';
export function randomPointOnSphere( vector = new THREE.Vector3() ) {
const theta = 2 * Math.PI * Math.random();
const u = 2 * Math.random() - 1;
const v = Math.sqrt( 1 - u * u );
return vector.set(
v * Math.cos( theta ),
v * Math.sin( theta ),
u
);
}
export function lerp( a, b, t ) {
return a + t * ( b - a );
}
export function inverseLerp( a, b, x ) {
return ( x - a ) / ( b - a );
}
export function map( x, a, b, c, d ) {
return lerp( c, d, inverseLerp( a, b, x ) );
}
| Add 1D lerp(), inverseLerp(), and map(). | Add 1D lerp(), inverseLerp(), and map().
| JavaScript | mit | razh/flying-machines,razh/flying-machines | ---
+++
@@ -11,3 +11,15 @@
u
);
}
+
+export function lerp( a, b, t ) {
+ return a + t * ( b - a );
+}
+
+export function inverseLerp( a, b, x ) {
+ return ( x - a ) / ( b - a );
+}
+
+export function map( x, a, b, c, d ) {
+ return lerp( c, d, inverseLerp( a, b, x ) );
+} |
20c0f4d04aa9581a717741bb1be7f73167e358b0 | optional.js | optional.js | module.exports = function(module, options){
try{
if(module[0] in {".":1}){
module = process.cwd() + module.substr(1);
}
return require(module);
}catch(e){
if (err.code !== "MODULE_NOT_FOUND" && options && options.rethrow) {
throw err;
}
}
return null;
};
| module.exports = function(module, options){
try{
if(module[0] in {".":1}){
module = process.cwd() + module.substr(1);
}
return require(module);
}catch(err){
if (err.code !== "MODULE_NOT_FOUND" && options && options.rethrow) {
throw err;
}
}
return null;
};
| Fix a typo (`e` -> `err`) | Fix a typo (`e` -> `err`) | JavaScript | mit | tony-o/node-optional,peerbelt/node-optional | ---
+++
@@ -4,7 +4,7 @@
module = process.cwd() + module.substr(1);
}
return require(module);
- }catch(e){
+ }catch(err){
if (err.code !== "MODULE_NOT_FOUND" && options && options.rethrow) {
throw err;
} |
e057cdfb71ccd2f7d70157ccac728736fbcad450 | tests/plugins/front-matter.js | tests/plugins/front-matter.js | import test from 'ava';
import {fromString, fromNull, fromStream} from '../helpers/pipe';
import fm from '../../lib/plugins/front-matter';
test('No Compile - null', t => {
return fromNull(fm)
.then(output => {
t.is(output, '', 'No output');
});
});
test('Error - is stream', t => {
t.throws(fromStream(fm));
});
| import test from 'ava';
import {fromString} from '../helpers/pipe';
import plugin from '../helpers/plugin';
import fm from '../../lib/plugins/front-matter';
test('Extracts Front Matter', t => {
const input = `---
foo: bar
baz:
- qux
- where
- waldo
more:
good:
stuff:
- lives: here
- and: here
---
# Hello World`;
const expectedMeta = {
foo: 'bar',
baz: [
'qux',
'where',
'waldo',
],
more: {
good: {
stuff: [
{
lives: 'here',
},
{
and: 'here',
},
],
},
},
};
const expectedBody = '# Hello World';
return fromString(input, 'markdown/hello.md', fm)
.then(output => {
expectedMeta.today = output.meta.today;
t.true(output.meta.hasOwnProperty('today'), 'Contains the time');
t.deepEqual(output.meta, expectedMeta, 'Front matter transformed in to usable object');
t.is(output.contents.toString(), expectedBody);
});
});
test('No Front Matter', t => {
const input = `# Hello World`;
const expected = '# Hello World';
return fromString(input, 'markdown/hello.md', fm)
.then(output => {
t.true(output.meta.hasOwnProperty('today'), 'Contains the time');
t.is(output.contents.toString(), expected);
});
});
plugin(fm, test);
| Add tests for actual FM | :white_check_mark: Add tests for actual FM
| JavaScript | mit | Snugug/gulp-armadillo,kellychurchill/gulp-armadillo | ---
+++
@@ -1,14 +1,64 @@
import test from 'ava';
-import {fromString, fromNull, fromStream} from '../helpers/pipe';
+import {fromString} from '../helpers/pipe';
+import plugin from '../helpers/plugin';
import fm from '../../lib/plugins/front-matter';
-test('No Compile - null', t => {
- return fromNull(fm)
+test('Extracts Front Matter', t => {
+ const input = `---
+foo: bar
+baz:
+ - qux
+ - where
+ - waldo
+more:
+ good:
+ stuff:
+ - lives: here
+ - and: here
+---
+# Hello World`;
+ const expectedMeta = {
+ foo: 'bar',
+ baz: [
+ 'qux',
+ 'where',
+ 'waldo',
+ ],
+ more: {
+ good: {
+ stuff: [
+ {
+ lives: 'here',
+ },
+ {
+ and: 'here',
+ },
+ ],
+ },
+ },
+ };
+
+ const expectedBody = '# Hello World';
+
+ return fromString(input, 'markdown/hello.md', fm)
.then(output => {
- t.is(output, '', 'No output');
+ expectedMeta.today = output.meta.today;
+
+ t.true(output.meta.hasOwnProperty('today'), 'Contains the time');
+ t.deepEqual(output.meta, expectedMeta, 'Front matter transformed in to usable object');
+ t.is(output.contents.toString(), expectedBody);
});
});
-test('Error - is stream', t => {
- t.throws(fromStream(fm));
+test('No Front Matter', t => {
+ const input = `# Hello World`;
+ const expected = '# Hello World';
+
+ return fromString(input, 'markdown/hello.md', fm)
+ .then(output => {
+ t.true(output.meta.hasOwnProperty('today'), 'Contains the time');
+ t.is(output.contents.toString(), expected);
+ });
});
+
+plugin(fm, test); |
2aec558cb2518426284b0a6bca79ab87178a5ccb | TrackedViews.js | TrackedViews.js | /**
* @flow
*/
import React, {
Component,
Text,
View,
} from 'react-native';
import {registerView, unregisterView} from './ViewTracker'
/**
* Higher-order component that turns a built-in View component into a component
* that is tracked with the key specified in the viewKey prop. If the viewKey
* prop is not specified, then no tracking is done.
*/
const createTrackedView = (ViewComponent: any) => class TrackedComponent extends Component {
componentDidMount() {
const {viewKey} = this.props;
if (viewKey) {
registerView(viewKey, this.refs.viewRef);
}
}
componentWillUnmount() {
const {viewKey} = this.props;
if (viewKey) {
unregisterView(viewKey, this.refs.viewRef);
}
}
render() {
const {viewKey, ...childProps} = this.props;
return <ViewComponent ref="viewRef" {...childProps} />
}
};
export const TrackedView = createTrackedView(View);
export const TrackedText = createTrackedView(Text); | /**
* @flow
*/
import React, {
Component,
Text,
View,
} from 'react-native';
import {registerView, unregisterView} from './ViewTracker'
/**
* Higher-order component that turns a built-in View component into a component
* that is tracked with the key specified in the viewKey prop. If the viewKey
* prop is not specified, then no tracking is done.
*/
const createTrackedView = (ViewComponent: any) => class TrackedComponent extends Component {
componentDidMount() {
const {viewKey} = this.props;
if (viewKey) {
registerView(viewKey, this.refs.viewRef);
}
}
componentWillUpdate(nextProps: any) {
const {viewKey} = this.props;
if (viewKey && !viewKey.equals(nextProps.viewKey)) {
unregisterView(viewKey, this.refs.viewRef);
}
}
componentDidUpdate(prevProps: any) {
const {viewKey} = this.props;
if (viewKey && !viewKey.equals(prevProps.viewKey)) {
registerView(viewKey, this.refs.viewRef);
}
}
componentWillUnmount() {
const {viewKey} = this.props;
if (viewKey) {
unregisterView(viewKey, this.refs.viewRef);
}
}
render() {
const {viewKey, ...childProps} = this.props;
return <ViewComponent ref="viewRef" {...childProps} />
}
};
export const TrackedView = createTrackedView(View);
export const TrackedText = createTrackedView(Text); | Fix crash when dragging definitions | Fix crash when dragging definitions
I was accidentally updating the view key for a view, and the tracked view code
couldn't handle prop changes.
| JavaScript | mit | alangpierce/LambdaCalculusPlayground,alangpierce/LambdaCalculusPlayground,alangpierce/LambdaCalculusPlayground | ---
+++
@@ -23,6 +23,20 @@
}
}
+ componentWillUpdate(nextProps: any) {
+ const {viewKey} = this.props;
+ if (viewKey && !viewKey.equals(nextProps.viewKey)) {
+ unregisterView(viewKey, this.refs.viewRef);
+ }
+ }
+
+ componentDidUpdate(prevProps: any) {
+ const {viewKey} = this.props;
+ if (viewKey && !viewKey.equals(prevProps.viewKey)) {
+ registerView(viewKey, this.refs.viewRef);
+ }
+ }
+
componentWillUnmount() {
const {viewKey} = this.props;
if (viewKey) { |
11215560382e5c0b4484019dbf8541351337f7fb | src/mixins/size.js | src/mixins/size.js | draft.mixins.size = {
// Get/set the element's width & height
size(width, height) {
return this.prop({
width: draft.types.length(width),
height: draft.types.length(height)
// depth: draft.types.length(depth)
});
}
};
| draft.mixins.size = {
// Get/set the element's width & height
size(width, height) {
return this.prop({
width: draft.types.length(width),
height: draft.types.length(height)
// depth: draft.types.length(depth)
});
},
scale(width, height) {
return this.prop({
width: this.prop('width') * width || undefined,
height: this.prop('height') * height || undefined
// depth: this.prop('depth') * depth || undefined
});
}
};
| Add scale() function for relative sizing | Add scale() function for relative sizing
| JavaScript | mit | D1SC0tech/draft.js,D1SC0tech/draft.js | ---
+++
@@ -6,5 +6,13 @@
height: draft.types.length(height)
// depth: draft.types.length(depth)
});
+ },
+
+ scale(width, height) {
+ return this.prop({
+ width: this.prop('width') * width || undefined,
+ height: this.prop('height') * height || undefined
+ // depth: this.prop('depth') * depth || undefined
+ });
}
}; |
b24cd5018185dc2ef35598a7cae863322d89c8c7 | app/scripts/fixBackground.js | app/scripts/fixBackground.js | 'use strict';
var fixBackground = function(){
var backgroundImage = document.getElementById('page-background-img');
if(window.innerHeight >= backgroundImage.height) {
backgroundImage.style.height = '100%';
backgroundImage.style.width = null;
}
if(window.innerWidth >= backgroundImage.width) {
backgroundImage.style.width = '100%';
backgroundImage.style.height = null;
}
};
window.onresize = fixBackground;
window.onload = fixBackground; | 'use strict';
var fixBackground = function(){
var backgroundImage = document.getElementById('page-background-img');
if(window.innerHeight >= backgroundImage.height) {
backgroundImage.style.height = '100%';
backgroundImage.style.width = null;
}
if(window.innerWidth >= backgroundImage.width) {
backgroundImage.style.width = '100%';
backgroundImage.style.height = null;
}
};
document.getElementById('page-background-img').ondragstart = function() { return false; };
window.onresize = fixBackground;
window.onload = fixBackground; | Disable image grab event for background | Disable image grab event for background
| JavaScript | mit | Pozo/elvira-redesign | ---
+++
@@ -11,5 +11,6 @@
backgroundImage.style.height = null;
}
};
+document.getElementById('page-background-img').ondragstart = function() { return false; };
window.onresize = fixBackground;
window.onload = fixBackground; |
31fe75787678465efcfd10dafbb9c368f72d9758 | hbs-builder.js | hbs-builder.js | define(["handlebars-compiler"], function (Handlebars) {
var buildMap = {},
templateExtension = ".hbs";
return {
// http://requirejs.org/docs/plugins.html#apiload
load: function (name, parentRequire, onload, config) {
// Get the template extension.
var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension);
// Use node.js file system module to load the template.
// Sorry, no Rhino support.
var fs = nodeRequire("fs");
var fsPath = config.dirBaseUrl + "/" + name + ext;
buildMap[name] = fs.readFileSync(fsPath).toString();
onload();
},
// http://requirejs.org/docs/plugins.html#apiwrite
write: function (pluginName, name, write) {
var compiled = Handlebars.precompile(buildMap[name]);
// Write out precompiled version of the template function as AMD
// definition.
write(
"define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" +
"return Handlebars.template(" + compiled.toString() + ");\n" +
"});\n"
);
}
};
});
| define(["handlebars-compiler"], function (Handlebars) {
var buildMap = {},
templateExtension = ".hbs";
return {
// http://requirejs.org/docs/plugins.html#apiload
load: function (name, parentRequire, onload, config) {
// Get the template extension.
var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension);
// Use node.js file system module to load the template.
// Sorry, no Rhino support.
var fs = nodeRequire("fs");
var fsPath = config.dirBaseUrl + "/" + name + ext;
buildMap[name] = fs.readFileSync(fsPath).toString();
parentRequire(["handlebars"], function () {
onload();
});
},
// http://requirejs.org/docs/plugins.html#apiwrite
write: function (pluginName, name, write) {
var compiled = Handlebars.precompile(buildMap[name]);
// Write out precompiled version of the template function as AMD
// definition.
write(
"define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" +
"return Handlebars.template(" + compiled.toString() + ");\n" +
"});\n"
);
}
};
});
| Include handlebars module in build process | Include handlebars module in build process
| JavaScript | mit | designeng/requirejs-hbs,designeng/requirejs-hbs,designeng/requirejs-hbs | ---
+++
@@ -15,7 +15,9 @@
var fs = nodeRequire("fs");
var fsPath = config.dirBaseUrl + "/" + name + ext;
buildMap[name] = fs.readFileSync(fsPath).toString();
- onload();
+ parentRequire(["handlebars"], function () {
+ onload();
+ });
},
// http://requirejs.org/docs/plugins.html#apiwrite |
695f3c5607fae90b13fe6c85ffd6412afcaff0bf | packages/react-app-rewired/index.js | packages/react-app-rewired/index.js | const babelLoaderMatcher = function(rule) {
return rule.loader && rule.loader.indexOf("/babel-loader/") != -1;
}
const getLoader = function(rules, matcher) {
var loader;
rules.some(rule => {
return loader = matcher(rule)
? rule
: getLoader(rule.use || rule.oneOf || [], matcher);
});
return loader;
};
const getBabelLoader = function(rules) {
return getLoader(rules, babelLoaderMatcher);
}
const injectBabelPlugin = function(pluginName, config) {
const loader = getBabelLoader(config.module.rules);
if (!loader) {
console.log("babel-loader not found");
return config;
}
loader.options.plugins = [pluginName].concat(loader.options.plugins || []);
return config;
};
module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
| const babelLoaderMatcher = function(rule) {
return rule.loader && rule.loader.indexOf("babel-loader/") != -1;
}
const getLoader = function(rules, matcher) {
var loader;
rules.some(rule => {
return loader = matcher(rule)
? rule
: getLoader(rule.use || rule.oneOf || [], matcher);
});
return loader;
};
const getBabelLoader = function(rules) {
return getLoader(rules, babelLoaderMatcher);
}
const injectBabelPlugin = function(pluginName, config) {
const loader = getBabelLoader(config.module.rules);
if (!loader) {
console.log("babel-loader not found");
return config;
}
loader.options.plugins = [pluginName].concat(loader.options.plugins || []);
return config;
};
module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
| Fix babelLoaderMatcher for other npm install tool | Fix babelLoaderMatcher for other npm install tool
like https://github.com/cnpm/npminstall
| JavaScript | mit | timarney/react-app-rewired,timarney/react-app-rewired | ---
+++
@@ -1,5 +1,5 @@
const babelLoaderMatcher = function(rule) {
- return rule.loader && rule.loader.indexOf("/babel-loader/") != -1;
+ return rule.loader && rule.loader.indexOf("babel-loader/") != -1;
}
const getLoader = function(rules, matcher) { |
38080adc1302b88af2c5d19d70720b53d4f464a7 | jest.config.js | jest.config.js | /* @flow */
module.exports = {
coverageDirectory: 'reports/coverage',
coveragePathIgnorePatterns: [
'/node_modules/',
'/packages/mineral-ui-icons',
'/website/'
],
moduleNameMapper: {
'.*react-docgen-loader.*': '<rootDir>/utils/emptyObject.js',
'.(md|svg)$': '<rootDir>/utils/emptyString.js'
},
setupFiles: ['raf/polyfill'],
setupTestFrameworkScriptFile: '<rootDir>/utils/setupTestFrameworkScript.js',
snapshotSerializers: [
'enzyme-to-json/serializer',
'<rootDir>/utils/snapshotSerializer'
]
};
| /* @flow */
module.exports = {
coverageDirectory: 'reports/coverage',
coveragePathIgnorePatterns: [
'/node_modules/',
'/packages/mineral-ui-icons',
'/website/'
],
moduleNameMapper: {
'.*react-docgen-loader.*': '<rootDir>/utils/emptyObject.js',
'.(md|svg)$': '<rootDir>/utils/emptyString.js'
},
setupFiles: ['raf/polyfill'],
setupTestFrameworkScriptFile: '<rootDir>/utils/setupTestFrameworkScript.js',
snapshotSerializers: [
'enzyme-to-json/serializer',
'<rootDir>/utils/snapshotSerializer'
],
testURL: 'http://localhost/'
};
| Update testURL to accommodate JSDOM update | chore(jest): Update testURL to accommodate JSDOM update
- See https://github.com/jsdom/jsdom/issues/2304
| JavaScript | apache-2.0 | mineral-ui/mineral-ui,mineral-ui/mineral-ui | ---
+++
@@ -15,5 +15,6 @@
snapshotSerializers: [
'enzyme-to-json/serializer',
'<rootDir>/utils/snapshotSerializer'
- ]
+ ],
+ testURL: 'http://localhost/'
}; |
f9b3837c53bb0572c95f2f48b6855250870ea2f1 | js/Landing.js | js/Landing.js | import React from 'react'
const Landing = React.createClass({
render () {
return (
<div className='landing'>
<h1>svideo</h1>
<input type='text' placeholder='Search' />
<a>or Browse All</a>
</div>
)
}
})
export default Landing
| import React from 'react'
import { Link } from 'react-router'
const Landing = React.createClass({
render () {
return (
<div className='landing'>
<h1>svideo</h1>
<input type='text' placeholder='Search' />
<Link to='/search'>or Browse All</Link>
</div>
)
}
})
export default Landing
| Make the "or Browse All" button a link that takes you to /search route | Make the "or Browse All" button a link that takes you to /search route
| JavaScript | mit | galaxode/ubiquitous-eureka,galaxode/ubiquitous-eureka | ---
+++
@@ -1,4 +1,5 @@
import React from 'react'
+import { Link } from 'react-router'
const Landing = React.createClass({
render () {
@@ -6,7 +7,7 @@
<div className='landing'>
<h1>svideo</h1>
<input type='text' placeholder='Search' />
- <a>or Browse All</a>
+ <Link to='/search'>or Browse All</Link>
</div>
)
} |
680debc53973355b553155bdfae857907af0a259 | app/assets/javascripts/edsn.js | app/assets/javascripts/edsn.js | var EDSN_THRESHOLD = 30;
var EdsnSwitch = (function(){
var editing;
var validBaseLoads = /^(base_load|base_load_edsn)$/;
EdsnSwitch.prototype = {
enable: function(){
if(editing){
swapEdsnBaseLoadSelectBoxes();
}
},
isEdsn: function(){
return validBaseLoads.test($(this).val());
},
cloneAndAppendProfileSelect: function(){
swapSelectBox.call(this);
}
};
function swapEdsnBaseLoadSelectBoxes(){
$("tr.base_load_edsn select.name").each(swapSelectBox);
};
function swapSelectBox(){
var technology = 'base_load'
var self = this;
var unitSelector = $(this).parents("tr").find(".units input");
var units = parseInt(unitSelector.val());
var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load");
var select = $(".hidden select." + actual).clone(true, true);
$(this).val(technology);
$(this).parent().next().html(select);
$(this).find("option[value='" + technology + "']").attr('value', actual);
$(this).val(actual);
unitSelector.off('change').on('change', swapSelectBox.bind(self));
};
function EdsnSwitch(_editing){
editing = _editing;
};
return EdsnSwitch;
})();
| var EDSN_THRESHOLD = 30;
var EdsnSwitch = (function(){
var editing;
var validBaseLoads = /^(base_load|base_load_edsn)$/;
EdsnSwitch.prototype = {
enable: function(){
if(editing){
swapEdsnBaseLoadSelectBoxes();
}
},
isEdsn: function(){
return validBaseLoads.test($(this).data('type'));
},
cloneAndAppendProfileSelect: function(){
swapSelectBox.call(this);
}
};
function swapEdsnBaseLoadSelectBoxes(){
$("tr.base_load_edsn select.name").each(swapSelectBox);
};
function swapSelectBox(){
var technology = 'base_load'
var self = this;
var unitSelector = $(this).parents("tr").find(".units input");
var units = parseInt(unitSelector.val());
var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load");
var select = $(".hidden select." + actual).clone(true, true);
$(this).val(technology);
$(this).parent().next().html(select);
$(this).find("option[value='" + technology + "']").attr('value', actual);
$(this).val(actual);
unitSelector.off('change').on('change', swapSelectBox.bind(self));
};
function EdsnSwitch(_editing){
editing = _editing;
};
return EdsnSwitch;
})();
| Use data attribute instead of val() | Use data attribute instead of val()
| JavaScript | mit | quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses | ---
+++
@@ -12,7 +12,7 @@
},
isEdsn: function(){
- return validBaseLoads.test($(this).val());
+ return validBaseLoads.test($(this).data('type'));
},
cloneAndAppendProfileSelect: function(){ |
6321dc80f757cb1d83c4c06e277e0efcba5b853a | site/remark.js | site/remark.js | const visit = require('unist-util-visit');
const { kebabCase } = require('lodash');
const IGNORES = [
'https://raw.githubusercontent.com/styleguidist/react-styleguidist/master/templates/DefaultExample.md',
'https://github.com/styleguidist/react-styleguidist/blob/master/.github/Contributing.md',
];
const REPLACEMENTS = {
'https://github.com/styleguidist/react-styleguidist': 'https://react-styleguidist.js.org/',
};
const getDocUrl = url => url.replace(/(\w+)(?:\.md)/, (_, $1) => `/${kebabCase($1)}`);
/*
* Fix links:
* GettingStarted.md -> /docs/getting-started
*/
function link() {
return ast =>
visit(ast, 'link', node => {
if (IGNORES.includes(node.url)) {
return;
}
if (REPLACEMENTS[node.url]) {
node.url = REPLACEMENTS[node.url];
} else if (node.url.endsWith('.md') || node.url.includes('.md#')) {
node.url = getDocUrl(node.url);
}
});
}
module.exports = [link];
| const visit = require('unist-util-visit');
const { kebabCase } = require('lodash');
const IGNORES = [
'https://raw.githubusercontent.com/styleguidist/react-styleguidist/master/templates/DefaultExample.md',
'https://github.com/styleguidist/react-styleguidist/blob/master/.github/Contributing.md',
];
const REPLACEMENTS = {
'https://github.com/styleguidist/react-styleguidist': 'https://react-styleguidist.js.org/',
};
const getDocUrl = url => url.replace(/(\w+)(?:\.md)/, (_, $1) => `/docs/${kebabCase($1)}`);
/*
* Fix links:
* GettingStarted.md -> /docs/getting-started
*/
function link() {
return ast =>
visit(ast, 'link', node => {
if (IGNORES.includes(node.url)) {
return;
}
if (REPLACEMENTS[node.url]) {
node.url = REPLACEMENTS[node.url];
} else if (node.url.endsWith('.md') || node.url.includes('.md#')) {
node.url = getDocUrl(node.url);
}
});
}
module.exports = [link];
| Fix links on the site, again 🦐 | docs: Fix links on the site, again 🦐
Closes #1650
| JavaScript | mit | styleguidist/react-styleguidist,sapegin/react-styleguidist,styleguidist/react-styleguidist,styleguidist/react-styleguidist,sapegin/react-styleguidist | ---
+++
@@ -9,7 +9,7 @@
'https://github.com/styleguidist/react-styleguidist': 'https://react-styleguidist.js.org/',
};
-const getDocUrl = url => url.replace(/(\w+)(?:\.md)/, (_, $1) => `/${kebabCase($1)}`);
+const getDocUrl = url => url.replace(/(\w+)(?:\.md)/, (_, $1) => `/docs/${kebabCase($1)}`);
/*
* Fix links: |
24d6b502081b81eff9ce1775002015f59ee3ccba | blueprints/component/index.js | blueprints/component/index.js | 'use strict'
module.exports = {
description: "A basic React component",
generateReplacements(args) {
let propTypes = "";
let defaultProps = "";
if(args.length) {
propTypes = "__name__.propTypes = {";
defaultProps = "\n getDefaultProps: function() {";
for(let index in args) {
let prop = args[index];
let parts = prop.split(':');
propTypes += `\n ${parts[0]}: ${this.reactPropTypeFrom(parts[1])},`;
defaultProps += `\n ${parts[0]}: ${this.reactDefaultPropFrom(parts[1])},`;
}
propTypes += "\n}\n";
defaultProps += "\n },\n";
}
return {'__proptypes__': propTypes, '__defaultprops__': defaultProps };
},
reactPropTypeFrom(prop) {
return 'React.PropTypes.' + prop;
},
reactDefaultPropFrom(prop) {
switch(prop) {
case 'number':
return '0';
case 'string':
return "''";
case 'array':
return '[]';
case 'bool':
return 'false';
case 'func':
case 'object':
case 'shape':
return 'null';
default:
throw new Error(`Unsupported propType ${prop}`);
}
}
}
| 'use strict'
module.exports = {
description: "A basic React component",
generateReplacements(args) {
let propTypes = "";
let defaultProps = "";
if(args.length) {
propTypes = "__name__.propTypes = {";
defaultProps = "\n getDefaultProps: function() {";
for(let index in args) {
let prop = args[index];
let parts = prop.split(':');
if(parts.length != 2) {
throw new Error(`Prop ${prop} is formatted incorrectly`);
}
propTypes += `\n ${parts[0]}: ${this.reactPropTypeFrom(parts[1])},`;
defaultProps += `\n ${parts[0]}: ${this.reactDefaultPropFrom(parts[1])},`;
}
propTypes += "\n}\n";
defaultProps += "\n },\n";
}
return {'__proptypes__': propTypes, '__defaultprops__': defaultProps };
},
reactPropTypeFrom(prop) {
return 'React.PropTypes.' + prop;
},
reactDefaultPropFrom(prop) {
switch(prop) {
case 'number':
return '0';
case 'string':
return "''";
case 'array':
return '[]';
case 'bool':
return 'false';
case 'func':
case 'object':
case 'shape':
return 'null';
default:
throw new Error(`Unsupported propType ${prop}`);
}
}
}
| Check for badly formatted props | Check for badly formatted props
| JavaScript | mit | reactcli/react-cli,reactcli/react-cli | ---
+++
@@ -14,6 +14,9 @@
for(let index in args) {
let prop = args[index];
let parts = prop.split(':');
+ if(parts.length != 2) {
+ throw new Error(`Prop ${prop} is formatted incorrectly`);
+ }
propTypes += `\n ${parts[0]}: ${this.reactPropTypeFrom(parts[1])},`;
defaultProps += `\n ${parts[0]}: ${this.reactDefaultPropFrom(parts[1])},`;
} |
3063e971479ca50e3e7d96d89db26688f5f74375 | hobbes/vava.js | hobbes/vava.js | var vavaClass = require('./vava/class');
var vavaMethod = require('./vava/method');
var vavaType = require('./vava/type');
exports.scope = require('./vava/scope');
// TODO automate env assembly
exports.env = {
VavaClass : vavaClass.VavaClass,
VavaMethod : vavaMethod.VavaMethod,
TypedVariable : vavaType.TypedVariable,
BooleanValue : vavaType.BooleanValue,
IntValue : vavaType.IntValue,
FloatValue : vavaType.FloatValue,
DoubleValue : vavaType.DoubleValue,
StringValue : vavaType.StringValue
}
| var utils = (typeof hobbes !== 'undefined' && hobbes.utils) || require('./utils');
var vavaClass = require('./vava/class');
var vavaMethod = require('./vava/method');
var vavaType = require('./vava/type');
exports.scope = require('./vava/scope');
exports.env = utils.merge(
vavaClass,
vavaMethod,
vavaType
);
| Add automatic assembly of env | Add automatic assembly of env
| JavaScript | mit | knuton/hobbes,knuton/hobbes,knuton/hobbes,knuton/hobbes | ---
+++
@@ -1,17 +1,13 @@
+var utils = (typeof hobbes !== 'undefined' && hobbes.utils) || require('./utils');
+
var vavaClass = require('./vava/class');
var vavaMethod = require('./vava/method');
var vavaType = require('./vava/type');
exports.scope = require('./vava/scope');
-// TODO automate env assembly
-exports.env = {
- VavaClass : vavaClass.VavaClass,
- VavaMethod : vavaMethod.VavaMethod,
- TypedVariable : vavaType.TypedVariable,
- BooleanValue : vavaType.BooleanValue,
- IntValue : vavaType.IntValue,
- FloatValue : vavaType.FloatValue,
- DoubleValue : vavaType.DoubleValue,
- StringValue : vavaType.StringValue
-}
+exports.env = utils.merge(
+ vavaClass,
+ vavaMethod,
+ vavaType
+); |
b1a4e4275743dd30a19eb7005af386596c752eb9 | src/kb/widget/legacy/helpers.js | src/kb/widget/legacy/helpers.js | /*global define*/
/*jslint browser:true,white:true*/
define([
'jquery',
'kb_common/html'
], function ($, html) {
'use strict';
// jQuery plugins that you can use to add and remove a
// loading giff to a dom element.
$.fn.rmLoading = function () {
$(this).find('.loader').remove();
};
$.fn.loading = function (text, big) {
var div = html.tag('div');
$(this).rmLoading();
// TODO: handle "big"
$(this).append(div({ class: 'loader' }, html.loading(text)));
// if (big) {
// if (text !== undefined) {
// $(this).append('<p class="text-center text-muted loader"><br>'+
// '<img src="assets/img/ajax-loader-big.gif"> '+text+'</p>');
// } else {
// $(this).append('<p class="text-center text-muted loader"><br>'+
// '<img src="assets/img/ajax-loader-big.gif"> loading...</p>');
// }
// } else {
// if (text !== 'undefined') {
// $(this).append('<p class="text-muted loader">'+
// '<img src="assets/img/ajax-loader.gif"> '+text+'</p>');
// } else {
// $(this).append('<p class="text-muted loader">'+
// '<img src="assets/img/ajax-loader.gif"> loading...</p>');
// }
//
// }
return this;
};
}); | define([
'jquery',
'kb_common/html'
], function (
$,
html
) {
'use strict';
// jQuery plugins that you can use to add and remove a
// loading giff to a dom element.
$.fn.rmLoading = function () {
$(this).find('.loader').remove();
};
$.fn.loading = function (text, big) {
var div = html.tag('div');
$(this).rmLoading();
// TODO: handle "big"
$(this).append(div({ class: 'loader' }, html.loading(text)));
return this;
};
}); | Remove commented out code that was upsetting uglify | Remove commented out code that was upsetting uglify
| JavaScript | mit | eapearson/kbase-ui-widget | ---
+++
@@ -1,9 +1,10 @@
-/*global define*/
-/*jslint browser:true,white:true*/
define([
'jquery',
'kb_common/html'
-], function ($, html) {
+], function (
+ $,
+ html
+) {
'use strict';
// jQuery plugins that you can use to add and remove a
// loading giff to a dom element.
@@ -15,24 +16,6 @@
$(this).rmLoading();
// TODO: handle "big"
$(this).append(div({ class: 'loader' }, html.loading(text)));
- // if (big) {
- // if (text !== undefined) {
- // $(this).append('<p class="text-center text-muted loader"><br>'+
- // '<img src="assets/img/ajax-loader-big.gif"> '+text+'</p>');
- // } else {
- // $(this).append('<p class="text-center text-muted loader"><br>'+
- // '<img src="assets/img/ajax-loader-big.gif"> loading...</p>');
- // }
- // } else {
- // if (text !== 'undefined') {
- // $(this).append('<p class="text-muted loader">'+
- // '<img src="assets/img/ajax-loader.gif"> '+text+'</p>');
- // } else {
- // $(this).append('<p class="text-muted loader">'+
- // '<img src="assets/img/ajax-loader.gif"> loading...</p>');
- // }
- //
- // }
return this;
};
}); |
2e99a372b401cdfb8ecaaccffd3f8546c83c7da5 | api/question.js | api/question.js | var bodyParser = require('body-parser');
var express = require('express');
var database = require('../database');
var router = express.Router();
router.get('/', function(req, res) {
database.Question.find({}, function(err, questions) {
if (err) {
res.sendStatus(500);
}
else {
res.sendStatus(200).json(questions);
}
});
});
router.put('/', bodyParser.json(), function(req, res) {
var question = new database.Question(req.body);
question.save(function(err) {
if (err) {
res.sendStatus(500);
}
else {
res.sendStatus(200);
}
});
});
module.exports = router;
| var bodyParser = require('body-parser');
var express = require('express');
var database = require('../database');
var router = express.Router();
router.get('/', function(req, res) {
database.Question.find({}, function(err, questions) {
if (err) {
res.status(500);
}
else {
res.status(200).json(questions);
}
});
});
router.put('/', bodyParser.json(), function(req, res) {
var question = new database.Question(req.body);
question.save(function(err) {
if (err) {
res.status(500);
}
else {
res.status(200);
}
});
});
module.exports = router;
| Fix error with resending response. | Fix error with resending response.
| JavaScript | apache-2.0 | skalmadka/TierUp,skalmadka/TierUp | ---
+++
@@ -7,10 +7,10 @@
router.get('/', function(req, res) {
database.Question.find({}, function(err, questions) {
if (err) {
- res.sendStatus(500);
+ res.status(500);
}
else {
- res.sendStatus(200).json(questions);
+ res.status(200).json(questions);
}
});
});
@@ -20,10 +20,10 @@
question.save(function(err) {
if (err) {
- res.sendStatus(500);
+ res.status(500);
}
else {
- res.sendStatus(200);
+ res.status(200);
}
});
}); |
33e775c0e0e025847297c138261689dd5354a7d8 | api/resolver.js | api/resolver.js | var key = require('../utils/key');
var sync = require('synchronize');
var request = require('request');
var _ = require('underscore');
// The API that returns the in-email representation.
module.exports = function(req, res) {
var url = req.query.url.trim();
// Giphy image urls are in the format:
// http://giphy.com/gifs/<seo-text>-<alphanumeric id>
var matches = url.match(/\-([a-zA-Z0-9]+)$/);
if (!matches) {
res.status(400).send('Invalid URL format');
return;
}
var id = matches[1];
var response;
try {
response = sync.await(request({
url: 'http://api.giphy.com/v1/gifs/' + encodeURIComponent(id),
qs: {
api_key: key
},
gzip: true,
json: true,
timeout: 15 * 1000
}, sync.defer()));
} catch (e) {
res.status(500).send('Error');
return;
}
var image = response.body.data.images.original;
var width = image.width > 600 ? 600 : image.width;
var html = '<p><img style="max-width:100%;" src="' + image.url + '" width="' + width + '"/></p>';
res.json({
body: html
});
};
| var key = require('../utils/key');
var sync = require('synchronize');
var request = require('request');
var _ = require('underscore');
// The API that returns the in-email representation.
module.exports = function(req, res) {
var url = req.query.url.trim();
// Giphy image urls are in the format:
// http://giphy.com/gifs/<seo-text>-<alphanumeric id>
var matches = url.match(/\-([a-zA-Z0-9]+)$/);
if (!matches) {
res.status(400).send('Invalid URL format');
return;
}
var id = matches[1];
var response;
try {
response = sync.await(request({
url: 'http://api.giphy.com/v1/gifs/' + encodeURIComponent(id),
qs: {
api_key: key
},
gzip: true,
json: true,
timeout: 15 * 1000
}, sync.defer()));
} catch (e) {
res.status(500).send('Error');
return;
}
var image = response.body.data.images.original;
var width = image.width > 600 ? 600 : image.width;
var html = '<img style="max-width:100%;" src="' + image.url + '" width="' + width + '"/>';
res.json({
body: html
});
}; | Remove paragraphs since they add unnecessary vertical padding. | Remove paragraphs since they add unnecessary vertical padding. | JavaScript | mit | kigster/wanelo-mixmax-link-resolver,kigster/wanelo-mixmax-link-resolver,mixmaxhq/giphy-example-link-resolver,germy/mixmax-metaweather | ---
+++
@@ -36,7 +36,7 @@
var image = response.body.data.images.original;
var width = image.width > 600 ? 600 : image.width;
- var html = '<p><img style="max-width:100%;" src="' + image.url + '" width="' + width + '"/></p>';
+ var html = '<img style="max-width:100%;" src="' + image.url + '" width="' + width + '"/>';
res.json({
body: html
}); |
8d27f66f4b4c61ddeb95e5107a616b937eb06dff | app/core/app.js | app/core/app.js | 'use strict';
var bowlingApp = angular.module('bowling', ['ngRoute']);
bowlingApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.otherwise({
redirectTo: '/main'
});
}]);
bowlingApp.factory("dataProvider", ['$q', function ($q) {
var dataLoaded = false;
var currentPromise = null;
return {
getData: function () {
if (currentPromise == null) {
if (!dataLoaded) {
var result = bowling.initialize({"root": "polarbowler"}, $q);
currentPromise = result.then(function (league) {
dataLoaded = true;
currentPromise = null;
return league;
});
} else {
return $q(function (resolve, reject) {
resolve(bowling.currentLeague);
});
}
}
return currentPromise;
}
}
}]); | 'use strict';
var bowlingApp = angular.module('bowling', ['ngRoute']);
bowlingApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.otherwise({
redirectTo: '/main'
});
}]);
bowlingApp.factory("dataProvider", ['$q', function ($q) {
var dataLoaded = false;
var currentPromise = null;
return {
getData: function () {
if (currentPromise == null) {
if (!dataLoaded) {
var result = bowling.initialize({"root": "testdata"}, $q);
currentPromise = result.then(function (league) {
dataLoaded = true;
currentPromise = null;
return league;
});
} else {
return $q(function (resolve, reject) {
resolve(bowling.currentLeague);
});
}
}
return currentPromise;
}
}
}]); | Change data directory back to test data. | Change data directory back to test data.
| JavaScript | mit | MeerkatLabs/bowling-visualization | ---
+++
@@ -18,7 +18,7 @@
if (currentPromise == null) {
if (!dataLoaded) {
- var result = bowling.initialize({"root": "polarbowler"}, $q);
+ var result = bowling.initialize({"root": "testdata"}, $q);
currentPromise = result.then(function (league) {
dataLoaded = true;
currentPromise = null; |
4f429972826a4a1892969f11bef49f4bae147ac3 | webpack.config.base.js | webpack.config.base.js | 'use strict'
var webpack = require('webpack')
var reactExternal = {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
}
module.exports = {
externals: {
'react': reactExternal
},
module: {
loaders: [
{ test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ }
]
},
output: {
library: 'ReduxForm',
libraryTarget: 'umd'
},
resolve: {
extensions: ['', '.js']
}
}
| 'use strict'
var webpack = require('webpack')
var reactExternal = {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
}
var reduxExternal = {
root: 'Redux',
commonjs2: 'redux',
commonjs: 'redux',
amd: 'redux'
}
var reactReduxExternal = {
root: 'ReactRedux',
commonjs2: 'react-redux',
commonjs: 'react-redux',
amd: 'react-redux'
}
module.exports = {
externals: {
'react': reactExternal,
'redux': reduxExternal,
'react-redux': reactReduxExternal
},
module: {
loaders: [
{ test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ }
]
},
output: {
library: 'ReduxForm',
libraryTarget: 'umd'
},
resolve: {
extensions: ['', '.js']
}
}
| Add Redux and React Redux as external dependencies | Add Redux and React Redux as external dependencies
| JavaScript | mit | erikras/redux-form,erikras/redux-form | ---
+++
@@ -8,9 +8,25 @@
amd: 'react'
}
+var reduxExternal = {
+ root: 'Redux',
+ commonjs2: 'redux',
+ commonjs: 'redux',
+ amd: 'redux'
+}
+
+var reactReduxExternal = {
+ root: 'ReactRedux',
+ commonjs2: 'react-redux',
+ commonjs: 'react-redux',
+ amd: 'react-redux'
+}
+
module.exports = {
externals: {
- 'react': reactExternal
+ 'react': reactExternal,
+ 'redux': reduxExternal,
+ 'react-redux': reactReduxExternal
},
module: {
loaders: [ |
849ae9172c21704c61ae6a84affdef0a309fcb4b | app/controllers/application.js | app/controllers/application.js | import Ember from 'ember';
export default Ember.Controller.extend({
sitemap: {
nodes: [
{
link: 'index',
title: 'Home',
children: null
},
{
link: null,
title: 'Admin panel',
children: [
{
link: 'suggestionTypes',
title: 'Suggestion Types',
children: null
},
{
link: 'users',
title: 'Application Users',
children: null
}
]
},
{
link: 'suggestions.new',
title: 'Добавить предложение',
children: null
}
]
}
});
| import Ember from "ember";
export default Ember.Controller.extend({
sitemap: {
nodes: [
{ link: "index", title: "Home" },
{
title: "Admin panel",
children: [
{ link: "suggestionTypes", title: "Suggestion Types" },
{ link: "users", title: "Application Users" }
]
},
{ link: "suggestions.new", title: "Добавить предложение" },
{
title: "Разное",
children: [
{ link: "geolocation", title: "Геолокация" }
]
}
]
}
});
| Add link to geolocation example into sitemap | Add link to geolocation example into sitemap
| JavaScript | mit | Flexberry/flexberry-ember-demo,Flexberry/flexberry-ember-demo,Flexberry/flexberry-ember-demo | ---
+++
@@ -1,35 +1,23 @@
-import Ember from 'ember';
+import Ember from "ember";
export default Ember.Controller.extend({
sitemap: {
nodes: [
+ { link: "index", title: "Home" },
{
- link: 'index',
- title: 'Home',
- children: null
- },
- {
- link: null,
- title: 'Admin panel',
+ title: "Admin panel",
children: [
- {
- link: 'suggestionTypes',
- title: 'Suggestion Types',
- children: null
- },
- {
- link: 'users',
- title: 'Application Users',
- children: null
- }
+ { link: "suggestionTypes", title: "Suggestion Types" },
+ { link: "users", title: "Application Users" }
]
},
+ { link: "suggestions.new", title: "Добавить предложение" },
{
- link: 'suggestions.new',
- title: 'Добавить предложение',
- children: null
+ title: "Разное",
+ children: [
+ { link: "geolocation", title: "Геолокация" }
+ ]
}
-
]
}
}); |
421aba98815a8f3d99fa78daf1d6ec9315712966 | zombie/proxy/server.js | zombie/proxy/server.js | var net = require('net');
var zombie = require('zombie');
// Defaults
var ping = 'pong'
var browser = null;
var ELEMENTS = [];
//
// Store global client states indexed by ZombieProxyClient (memory address):
//
// {
// 'CLIENTID': [X, Y]
// }
//
// ...where X is some zombie.Browser instance...
//
// ...and Y is a per-browser cache (a list) used to store NodeList results.
// Subsequent TCP API calls will reference indexes to retrieve DOM
// attributes/properties accumulated in previous browser.querySelectorAll()
// calls.
//
//
var CLIENTS = {};
//
// Simple proxy server implementation
// for proxying streamed (Javascript) content via HTTP
// to a running Zombie.js
//
// Borrowed (heavily) from the Capybara-Zombie project
// https://github.com/plataformatec/capybara-zombie
//
//
function ctx_switch(id){
if(!CLIENTS[id])
CLIENTS[id] = [new zombie.Browser(), []];
return CLIENTS[id];
}
net.createServer(function (stream){
stream.setEncoding('utf8');
stream.on('data', function (data){
eval(data);
});
}).listen(process.argv[2], function(){
console.log('Zombie.js server running on ' + process.argv[2] + '...');
});
| var net = require('net');
var Browser = require('zombie');
// Defaults
var ping = 'pong'
var browser = null;
var ELEMENTS = [];
//
// Store global client states indexed by ZombieProxyClient (memory address):
//
// {
// 'CLIENTID': [X, Y]
// }
//
// ...where X is some zombie.Browser instance...
//
// ...and Y is a per-browser cache (a list) used to store NodeList results.
// Subsequent TCP API calls will reference indexes to retrieve DOM
// attributes/properties accumulated in previous browser.querySelectorAll()
// calls.
//
//
var CLIENTS = {};
//
// Simple proxy server implementation
// for proxying streamed (Javascript) content via HTTP
// to a running Zombie.js
//
// Borrowed (heavily) from the Capybara-Zombie project
// https://github.com/plataformatec/capybara-zombie
//
//
function ctx_switch(id){
if(!CLIENTS[id])
CLIENTS[id] = [new Browser(), []];
return CLIENTS[id];
}
net.createServer(function (stream){
stream.setEncoding('utf8');
stream.on('data', function (data){
eval(data);
});
}).listen(process.argv[2], function(){
console.log('Zombie.js server running on ' + process.argv[2] + '...');
});
| Make the sever.js work with zombie 2 | Make the sever.js work with zombie 2
| JavaScript | mit | ryanpetrello/python-zombie,ryanpetrello/python-zombie | ---
+++
@@ -1,5 +1,5 @@
var net = require('net');
-var zombie = require('zombie');
+var Browser = require('zombie');
// Defaults
var ping = 'pong'
@@ -34,10 +34,9 @@
//
function ctx_switch(id){
if(!CLIENTS[id])
- CLIENTS[id] = [new zombie.Browser(), []];
+ CLIENTS[id] = [new Browser(), []];
return CLIENTS[id];
}
-
net.createServer(function (stream){
stream.setEncoding('utf8');
|
fe6247d1ade209f1ebb6ba537652569810c4d77a | lib/adapter.js | lib/adapter.js | /**
* Request adapter.
*
* @package cork
* @author Andrew Sliwinski <andrew@diy.org>
*/
/**
* Dependencies
*/
var _ = require('lodash'),
async = require('async'),
request = require('request');
/**
* Executes a task from the adapter queue.
*
* @param {Object} Task
*
* @return {Object}
*/
var execute = function (task, callback) {
request(task, function (err, response, body) {
callback(err, body);
});
}
/**
* Constructor
*/
function Adapter (args) {
var self = this;
// Setup instance
_.extend(self, args);
_.defaults(self, {
base: null,
throttle: 0
});
// Throttled request method
var limiter = _.throttle(execute, self.throttle);
// Create queue
self.queue = async.queue(function (obj, callback) {
// Assemble task
var task = Object.create(null);
_.extend(task, self, obj);
if (self.base !== null) task.uri = self.base + task.uri;
// Clean-up
delete task.base;
delete task.throttle;
// Process task through the limiter method
limiter(task, callback);
}, 1);
};
/**
* Export
*/
module.exports = Adapter;
| /**
* Request adapter.
*
* @package cork
* @author Andrew Sliwinski <andrew@diy.org>
*/
/**
* Dependencies
*/
var _ = require('lodash'),
async = require('async'),
request = require('request');
/**
* Executes a task from the adapter queue.
*
* @param {Object} Task
*
* @return {Object}
*/
var execute = function (task, callback) {
request(task, function (err, response, body) {
callback(err, body);
});
}
/**
* Constructor
*/
function Adapter (args) {
var self = this;
// Setup instance
_.extend(self, args);
_.defaults(self, {
base: null,
throttle: 0
});
// Throttle the request execution method
var limiter = _.throttle(execute, self.throttle);
// Create queue
self.queue = async.queue(function (obj, callback) {
// Assemble task
var task = Object.create(null);
_.extend(task, self, obj);
if (self.base !== null) task.uri = self.base + task.uri;
// Clean-up
delete task.queue;
delete task.base;
delete task.throttle;
// Process task through the limiter method
limiter(task, callback);
}, 1);
};
/**
* Export
*/
module.exports = Adapter;
| Remove queue object from the task | Remove queue object from the task | JavaScript | mit | thisandagain/cork | ---
+++
@@ -38,7 +38,7 @@
throttle: 0
});
- // Throttled request method
+ // Throttle the request execution method
var limiter = _.throttle(execute, self.throttle);
// Create queue
@@ -49,6 +49,7 @@
if (self.base !== null) task.uri = self.base + task.uri;
// Clean-up
+ delete task.queue;
delete task.base;
delete task.throttle;
|
fcab433c54faeffbc59d0609a6f503e3a3237d6f | lib/bemhint.js | lib/bemhint.js | /**
* The core of BEM hint
* ====================
*/
var vow = require('vow'),
_ = require('lodash'),
scan = require('./walk'),
loadRules = require('./load-rules'),
Configuration = require('./configuration'),
utils = require('./utils');
/**
* Loads the BEM entities and checks them
* @param {Object} [loadedConfig]
* @param {String} [loadedConfig.configPath]
* @param {Array} [loadedConfig.levels]
* @param {Array} [loadedCinfig.excludeFiles]
* @param {Array} targets
* @returns {Promise * Array} - the list of BEM errors
*/
module.exports = function (loadedConfig, targets) {
var config = new Configuration(loadedConfig);
return vow.all([scan(targets, config), loadRules()])
.spread(function (entities, rules) {
return vow.all(_.keys(rules).map(function (rule) {
var _rule = new rules[rule]();
return _rule.check(entities);
}));
})
.then(function (res) {
var bemErros = [];
_(res).keys().forEach(function (item) {
bemErros = bemErros.concat(res[item]);
});
return utils.sortByFullpath(bemErros);
});
};
| /**
* The core of BEM hint
* ====================
*/
var vow = require('vow'),
_ = require('lodash'),
scan = require('./walk'),
loadRules = require('./load-rules'),
Configuration = require('./configuration'),
utils = require('./utils');
/**
* Loads the BEM entities and checks them
* @param {Object} [loadedConfig]
* @param {String} [loadedConfig.configPath]
* @param {Array} [loadedConfig.levels]
* @param {Array} [loadedCinfig.excludeFiles]
* @param {Array} targets
* @returns {Promise * Array} - the list of BEM errors
*/
module.exports = function (loadedConfig, targets) {
var config = new Configuration(loadedConfig);
return vow.all([scan(targets, config), loadRules()])
.spread(function (entities, rules) {
return vow.all(_.keys(rules).map(function (rule) {
var _rule = new rules[rule](config);
return _rule.check(entities);
}));
})
.then(function (res) {
var bemErros = [];
_(res).keys().forEach(function (item) {
bemErros = bemErros.concat(res[item]);
});
return utils.sortByFullpath(bemErros);
});
};
| Add 'config' as argument to rules' constructors | Add 'config' as argument to rules' constructors
| JavaScript | mit | bemhint/bemhint,bemhint/bemhint,bem/bemhint,bem/bemhint | ---
+++
@@ -24,7 +24,7 @@
return vow.all([scan(targets, config), loadRules()])
.spread(function (entities, rules) {
return vow.all(_.keys(rules).map(function (rule) {
- var _rule = new rules[rule]();
+ var _rule = new rules[rule](config);
return _rule.check(entities);
})); |
7b6d8f66fd1c2130d10ba7013136ecc3f25d6c3b | src/main/webapp/scripts/main.js | src/main/webapp/scripts/main.js | $().ready(() => {
loadContentSection().then(() =>{
$("#loader").addClass("hide");
$("#real-body").removeClass("hide");
$("#real-body").addClass("body");
$(".keyword").click(function() {
$(this).addClass("active");
$(".base").hide(200);
$("#real-body").addClass("focus");
});
$(".close").click(function(event) {
event.stopPropagation();
$(this).parent().removeClass("active");
$(".base").show(200);
$("#real-body").removeClass("focus");
});
});
});
| $().ready(() => {
loadContentSection().then(() =>{
$("#loader").addClass("hide");
$("#real-body").removeClass("hide");
$("#real-body").addClass("body");
$(".keyword").click(function() {
$(this).addClass("active");
$(".base").hide(200);
$("#real-body").addClass("focus");
});
$(".close").click(function(event) {
event.stopPropagation();
$(this).parent().removeClass("active");
$(".base").show(200);
$("#real-body").removeClass("focus");
});
$(".active .item").click(function() {
$(".item").off("click");
const url = $(this).attr("data-url");
window.location.replace(url);
});
});
});
| Add js to perform url replacement | Add js to perform url replacement
| JavaScript | apache-2.0 | googleinterns/step36-2020,googleinterns/step36-2020,googleinterns/step36-2020 | ---
+++
@@ -16,5 +16,11 @@
$(".base").show(200);
$("#real-body").removeClass("focus");
});
+
+ $(".active .item").click(function() {
+ $(".item").off("click");
+ const url = $(this).attr("data-url");
+ window.location.replace(url);
+ });
});
}); |
2de06af9887b6941f73a6610a5485d98cf7f353f | lib/mongoat.js | lib/mongoat.js | 'use strict';
var Mongoat = require('mongodb');
var utilsHelper = require('../helpers/utils-helper');
var connect = Mongoat.MongoClient.connect;
var hooks = {
before: {},
after: {}
};
Mongoat.Collection.prototype.before = function(opName, callback) {
hooks = utilsHelper.beforeAfter('before', opName, hooks, callback);
};
Mongoat.Collection.prototype.after = function(opName, callback) {
hooks = utilsHelper.beforeAfter('after', opName, hooks, callback);
};
Mongoat.Collection.prototype.insertTo = Mongoat.Collection.prototype.insert;
Mongoat.Collection.prototype.insert = function(document, options) {
var promises = [];
var _this = this;
options = options || {};
promises = utilsHelper.promisify(hooks.before.insert, document);
return Promise.all(promises).then(function (docToInsert) {
return _this.insertTo(docToInsert[0], options).then(function (mongoObject) {
promises = [];
promises = utilsHelper.promisify(hooks.after.insert, docToInsert[0]);
Promise.all(promises);
return mongoObject;
});
});
};
module.exports = Mongoat; | 'use strict';
var Mongoat = require('mongodb');
var utilsHelper = require('../helpers/utils-helper');
var connect = Mongoat.MongoClient.connect;
var hooks = {
before: {},
after: {}
};
(function(){
var opArray = ['insert', 'update', 'remove'];
var colPrototype = Mongoat.Collection.prototype;
for (var i = 0; i < opArray.length; ++i) {
colPrototype[opArray[i] + 'Method'] = colPrototype[opArray[i]];
}
})();
Mongoat.Collection.prototype.before = function(opName, callback) {
hooks = utilsHelper.beforeAfter('before', opName, hooks, callback);
};
Mongoat.Collection.prototype.after = function(opName, callback) {
hooks = utilsHelper.beforeAfter('after', opName, hooks, callback);
};
Mongoat.Collection.prototype.insert = function(document, options) {
var promises = [];
var _this = this;
options = options || {};
promises = utilsHelper.promisify(hooks.before.insert, document);
return Promise.all(promises).then(function (docToInsert) {
return _this.insertMethod(docToInsert[0], options)
.then(function (mongoObject) {
promises = [];
promises = utilsHelper.promisify(hooks.after.insert, docToInsert[0]);
Promise.all(promises);
return mongoObject;
});
});
};
module.exports = Mongoat; | Update save methods strategy - Use anonymous function to save collection methods before overwrite | Update save methods strategy
- Use anonymous function to save collection methods before overwrite
| JavaScript | mit | dial-once/node-mongoat | ---
+++
@@ -8,6 +8,15 @@
after: {}
};
+(function(){
+ var opArray = ['insert', 'update', 'remove'];
+ var colPrototype = Mongoat.Collection.prototype;
+
+ for (var i = 0; i < opArray.length; ++i) {
+ colPrototype[opArray[i] + 'Method'] = colPrototype[opArray[i]];
+ }
+})();
+
Mongoat.Collection.prototype.before = function(opName, callback) {
hooks = utilsHelper.beforeAfter('before', opName, hooks, callback);
};
@@ -15,8 +24,6 @@
Mongoat.Collection.prototype.after = function(opName, callback) {
hooks = utilsHelper.beforeAfter('after', opName, hooks, callback);
};
-
-Mongoat.Collection.prototype.insertTo = Mongoat.Collection.prototype.insert;
Mongoat.Collection.prototype.insert = function(document, options) {
var promises = [];
@@ -26,7 +33,8 @@
promises = utilsHelper.promisify(hooks.before.insert, document);
return Promise.all(promises).then(function (docToInsert) {
- return _this.insertTo(docToInsert[0], options).then(function (mongoObject) {
+ return _this.insertMethod(docToInsert[0], options)
+ .then(function (mongoObject) {
promises = [];
promises = utilsHelper.promisify(hooks.after.insert, docToInsert[0]);
Promise.all(promises);
@@ -35,5 +43,4 @@
});
};
-
module.exports = Mongoat; |
7bb5536b35b5f1bb90fde60abeb2f6cd7e410139 | lib/version.js | lib/version.js | var clone = require('clone'),
mongoose = require('mongoose'),
ObjectId = mongoose.Schema.Types.ObjectId;
module.exports = function(schema, options) {
options = options || {};
options.collection = options.collection || 'versions';
var versionedSchema = clone(schema);
// Fix for callQueue arguments
versionedSchema.callQueue.forEach(function(queueEntry) {
var args = [];
for(var key in queueEntry[1]) {
args.push(queueEntry[1][key]);
}
queueEntry[1] = args;
});
for(var key in options) {
if (options.hasOwnProperty(key)) {
versionedSchema.set(key, options[key]);
}
}
versionedSchema.add({
refId : ObjectId,
refVersion : Number
});
// Add reference to model to original schema
schema.statics.VersionedModel = mongoose.model(options.collection, versionedSchema);
schema.pre('save', function(next) {
this.increment(); // Increment origins version
var versionedModel = new versionedSchema.statics.VersionedModel(this);
versionedModel.refVersion = this._doc.__v; // Saves current document version
versionedModel.refId = this._id; // Sets origins document id as a reference
versionedModel._id = undefined;
versionedModel.save(function(err) {
next();
});
});
};
| var clone = require('clone'),
mongoose = require('mongoose'),
ObjectId = mongoose.Schema.Types.ObjectId;
module.exports = function(schema, options) {
options = options || {};
options.collection = options.collection || 'versions';
var versionedSchema = clone(schema);
// Fix for callQueue arguments
versionedSchema.callQueue.forEach(function(queueEntry) {
var args = [];
for(var key in queueEntry[1]) {
args.push(queueEntry[1][key]);
}
queueEntry[1] = args;
});
for(var key in options) {
if (options.hasOwnProperty(key)) {
versionedSchema.set(key, options[key]);
}
}
versionedSchema.add({
refId : ObjectId,
refVersion : Number
});
// Add reference to model to original schema
schema.statics.VersionedModel = mongoose.model(options.collection, versionedSchema);
schema.pre('save', function(next) {
this.increment(); // Increment origins version
var versionedModel = new schema.statics.VersionedModel(this);
versionedModel.refVersion = this._doc.__v; // Saves current document version
versionedModel.refId = this._id; // Sets origins document id as a reference
versionedModel._id = undefined;
versionedModel.save(function(err) {
next();
});
});
};
| Fix bug accessing wrong schema instance | Fix bug accessing wrong schema instance
| JavaScript | bsd-2-clause | jeresig/mongoose-version,saintedlama/mongoose-version | ---
+++
@@ -36,7 +36,7 @@
schema.pre('save', function(next) {
this.increment(); // Increment origins version
- var versionedModel = new versionedSchema.statics.VersionedModel(this);
+ var versionedModel = new schema.statics.VersionedModel(this);
versionedModel.refVersion = this._doc.__v; // Saves current document version
versionedModel.refId = this._id; // Sets origins document id as a reference
versionedModel._id = undefined; |
c31d392e1972d6eaca952c21ba9349d30b31b012 | js/defaults.js | js/defaults.js | /* exported defaults */
/* Magic Mirror
* Config Defauls
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var defaults = {
port: 8080,
language: "en",
timeFormat: 24,
modules: [
{
module: "helloworld",
position: "upper_third",
config: {
text: "Magic Mirror V2",
classes: "large thin"
}
},
{
module: "helloworld",
position: "middle_center",
config: {
text: "Please create a config file."
}
},
{
module: "helloworld",
position: "middle_center",
config: {
text: "See README for more information.",
classes: "small dimmed"
}
},
{
module: "helloworld",
position: "bottom_bar",
config: {
text: "www.michaelteeuw.nl",
classes: "xsmall dimmed"
}
},
],
paths: {
modules: "modules",
vendor: "vendor"
},
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {module.exports = defaults;}
| /* exported defaults */
/* Magic Mirror
* Config Defauls
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var defaults = {
port: 8080,
language: "en",
timeFormat: 24,
modules: [
{
module: "helloworld",
position: "upper_third",
config: {
text: "Magic Mirror<sup>2</sup>",
classes: "large thin"
}
},
{
module: "helloworld",
position: "middle_center",
config: {
text: "Please create a config file."
}
},
{
module: "helloworld",
position: "middle_center",
config: {
text: "See README for more information.",
classes: "small dimmed"
}
},
{
module: "helloworld",
position: "bottom_bar",
config: {
text: "www.michaelteeuw.nl",
classes: "xsmall dimmed"
}
},
],
paths: {
modules: "modules",
vendor: "vendor"
},
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {module.exports = defaults;}
| Change branding on default config. | Change branding on default config.
| JavaScript | mit | kthorri/MagicMirror,enith2478/spegel,aschulz90/MagicMirror,morozgrafix/MagicMirror,morozgrafix/MagicMirror,marcroga/sMirror,aghth/MagicMirror,ShivamShrivastava/Smart-Mirror,ConnorChristie/MagicMirror,berlincount/MagicMirror,wszgxa/magic-mirror,heyheyhexi/MagicMirror,gndimitro/MagicMirror,vyazadji/MagicMirror,ryanlawler/MagicMirror,aschulz90/MagicMirror,ConnorChristie/MagicMirror,thunderseethe/MagicMirror,cmwalshWVU/smartMirror,Leniox/MagicMirror,parakrama1995/Majic-Mirror,cs499Mirror/MagicMirror,cameronediger/MagicMirror,vyazadji/MagicMirror,cmwalshWVU/smartMirror,phareim/magic-mirror,aghth/MagicMirror,kevinatown/MM,n8many/MagicMirror,prasanthsasikumar/MagicMirror,thobach/MagicMirror,JimmyBoyle/MagicMirror,wszgxa/magic-mirror,aghth/MagicMirror,NoroffNIS/MagicMirror,cameronediger/MagicMirror,n8many/MagicMirror,cameronediger/MagicMirror,heyheyhexi/MagicMirror,Rimap47/MagicMirror,thunderseethe/MagicMirror,jamessalvatore/MagicMirror,denalove/MM2,soapdx/MagicMirror,cs499Mirror/MagicMirror,kevinatown/MM,kthorri/MagicMirror,parakrama1995/Majic-Mirror,mbalfour/MagicMirror,Makerspace-IDI/magic-mirror,Devan0369/AI-Project,gndimitro/MagicMirror,Leniox/MagicMirror,kevinatown/MM,Rimap47/MagicMirror,marc-86/MagicMirror,JimmyBoyle/MagicMirror,Tyvonne/MagicMirror,berlincount/MagicMirror,n8many/MagicMirror,roramirez/MagicMirror,OniDotun123/MirrorMirror,mbalfour/MagicMirror,thunderseethe/MagicMirror,Makerspace-IDI/magic-mirror,thobach/MagicMirror,vyazadji/MagicMirror,jodybrewster/hkthon,marc-86/MagicMirror,cameronediger/MagicMirror,fullbright/MagicMirror,MichMich/MagicMirror,JimmyBoyle/MagicMirror,wszgxa/magic-mirror,prasanthsasikumar/MagicMirror,phareim/magic-mirror,heyheyhexi/MagicMirror,kthorri/MagicMirror,berlincount/MagicMirror,morozgrafix/MagicMirror,marcroga/sMirror,denalove/MM2,Makerspace-IDI/magic-mirror,huntersiniard/MagicMirror,marcroga/sMirror,OniDotun123/MirrorMirror,kevinatown/MM,MichMich/MagicMirror,soapdx/MagicMirror,cs499Mirror/MagicMirror,he3/MagicMirror,thobach/MagicMirror,skippengs/MagicMirror,enith2478/spegel,mbalfour/MagicMirror,Tyvonne/MagicMirror,MichMich/MagicMirror,Tyvonne/MagicMirror,marc-86/MagicMirror,ShivamShrivastava/Smart-Mirror,NoroffNIS/MagicMirror,fullbright/MagicMirror,NoroffNIS/MagicMirror,Devan0369/AI-Project,gndimitro/MagicMirror,skippengs/MagicMirror,n8many/MagicMirror,jamessalvatore/MagicMirror,thobach/MagicMirror,roramirez/MagicMirror,huntersiniard/MagicMirror,ryanlawler/MagicMirror,jodybrewster/hkthon,MichMich/MagicMirror,ConnorChristie/MagicMirror,he3/MagicMirror,parakrama1995/Majic-Mirror,Leniox/MagicMirror,marcroga/sMirror,roramirez/MagicMirror,prasanthsasikumar/MagicMirror,denalove/MM2,OniDotun123/MirrorMirror,huntersiniard/MagicMirror,roramirez/MagicMirror,Rimap47/MagicMirror,jamessalvatore/MagicMirror,ryanlawler/MagicMirror,cmwalshWVU/smartMirror,soapdx/MagicMirror,marc-86/MagicMirror,n8many/MagicMirror,heyheyhexi/MagicMirror,Devan0369/AI-Project,ShivamShrivastava/Smart-Mirror,Tyvonne/MagicMirror,fullbright/MagicMirror,prasanthsasikumar/MagicMirror,berlincount/MagicMirror,jodybrewster/hkthon,morozgrafix/MagicMirror,he3/MagicMirror,aschulz90/MagicMirror,phareim/magic-mirror,enith2478/spegel,skippengs/MagicMirror | ---
+++
@@ -18,7 +18,7 @@
module: "helloworld",
position: "upper_third",
config: {
- text: "Magic Mirror V2",
+ text: "Magic Mirror<sup>2</sup>",
classes: "large thin"
}
}, |
fce51a7f4c2991773fff8d8070130a726f73879a | nin/frontend/app/scripts/directives/demo.js | nin/frontend/app/scripts/directives/demo.js | function demo($interval, demo) {
return {
restrict: 'E',
template: '<div class=demo-container></div>',
link: function(scope, element) {
demo.setContainer(element[0].children[0]);
setTimeout(function() {
demo.resize();
});
scope.$watch(() => scope.main.fullscreen, function (toFullscreen){
if (toFullscreen) {
// go to fullscreen
document.body.classList.add('fullscreen');
} else {
// exit fullscreen
document.body.classList.remove('fullscreen');
}
demo.resize();
});
scope.$watch(() => scope.main.mute, function (toMute) {
if (toMute) {
demo.music.setVolume(0);
} else {
demo.music.setVolume(scope.main.volume);
}
});
scope.$watch(() => scope.main.volume, volume => {
if (scope.mute) return;
demo.music.setVolume(volume);
});
$interval(function() {
scope.main.currentFrame = demo.getCurrentFrame();
scope.main.duration = demo.music.getDuration() * 60;
}, 1000 / 60);
setTimeout(function(){
demo.start();
demo.music.pause();
demo.jumpToFrame(0);
}, 0);
}
};
}
module.exports = demo;
| function demo($interval, demo) {
return {
restrict: 'E',
template: '<div class=demo-container></div>',
link: function(scope, element) {
demo.setContainer(element[0].children[0]);
setTimeout(function() {
demo.resize();
});
scope.$watch(() => scope.main.fullscreen, function (toFullscreen){
if (toFullscreen) {
// go to fullscreen
document.body.classList.add('fullscreen');
} else {
// exit fullscreen
document.body.classList.remove('fullscreen');
}
demo.resize();
});
scope.$watch(() => scope.main.mute, function (toMute) {
if (toMute) {
demo.music.setVolume(0);
} else {
demo.music.setVolume(scope.main.volume);
}
});
scope.$watch(() => scope.main.volume, volume => {
if (scope.main.mute) return;
demo.music.setVolume(volume);
});
$interval(function() {
scope.main.currentFrame = demo.getCurrentFrame();
scope.main.duration = demo.music.getDuration() * 60;
}, 1000 / 60);
setTimeout(function(){
demo.start();
demo.music.pause();
demo.jumpToFrame(0);
}, 0);
}
};
}
module.exports = demo;
| Fix mute on initial load | Fix mute on initial load
| JavaScript | apache-2.0 | ninjadev/nin,ninjadev/nin,ninjadev/nin | ---
+++
@@ -28,7 +28,7 @@
});
scope.$watch(() => scope.main.volume, volume => {
- if (scope.mute) return;
+ if (scope.main.mute) return;
demo.music.setVolume(volume);
});
|
85afadbe75bce0fd7069224c8065d99d6a663a2f | src/adapter.js | src/adapter.js | /*
* Copyright 2014 Workiva, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(karma, System) {
// Prevent immediately starting tests.
window.__karma__.loaded = function() {};
function extractModuleName(fileName){
return fileName.replace(/\.js$/, "");
}
var promises = [];
if(!System){
throw new Error("SystemJS was not found. Please make sure you have " +
"initialized jspm via installing a dependency with jspm, " +
"or by running 'jspm dl-loader'.");
}
// Configure SystemJS baseURL
System.config({
baseURL: 'base'
});
// Load everything specified in loadFiles
karma.config.jspm.expandedFiles.map(function(modulePath){
promises.push(System.import(extractModuleName(modulePath)));
});
// Promise comes from the es6_module_loader
Promise.all(promises).then(function(){
karma.start();
});
})(window.__karma__, window.System);
| /*
* Copyright 2014 Workiva, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(karma, System) {
// Prevent immediately starting tests.
window.__karma__.loaded = function() {};
function extractModuleName(fileName){
return fileName.replace(/\.js$/, "");
}
var promises = [];
if(!System){
throw new Error("SystemJS was not found. Please make sure you have " +
"initialized jspm via installing a dependency with jspm, " +
"or by running 'jspm dl-loader'.");
}
// Configure SystemJS baseURL
System.config({
baseURL: 'base'
});
// Load everything specified in loadFiles
karma.config.jspm.expandedFiles.map(function(modulePath){
var promise = System.import(extractModuleName(modulePath))
.catch(function(e){
setTimeout(function() {
throw e;
});
});
promises.push(promise);
});
// Promise comes from the es6_module_loader
Promise.all(promises).then(function(){
karma.start();
});
})(window.__karma__, window.System);
| Add error handler to System.import promises | Add error handler to System.import promises
| JavaScript | apache-2.0 | rich-nguyen/karma-jspm | ---
+++
@@ -38,7 +38,13 @@
// Load everything specified in loadFiles
karma.config.jspm.expandedFiles.map(function(modulePath){
- promises.push(System.import(extractModuleName(modulePath)));
+ var promise = System.import(extractModuleName(modulePath))
+ .catch(function(e){
+ setTimeout(function() {
+ throw e;
+ });
+ });
+ promises.push(promise);
});
// Promise comes from the es6_module_loader |
4aa3e40ae4a9b998025a010749be69da428cb9bb | src/jupyter_contrib_nbextensions/nbextensions/hide_input_all/main.js | src/jupyter_contrib_nbextensions/nbextensions/hide_input_all/main.js | // toggle display of all code cells' inputs
define([
'jquery',
'base/js/namespace'
], function(
$,
IPython
) {
"use strict";
function set_input_visible(show) {
IPython.notebook.metadata.hide_input = !show;
if (show) $('div.input').show('slow');
else $('div.input').hide('slow');
var btn = $('#toggle_codecells');
btn.toggleClass('active', !show);
var icon = btn.find('i');
icon.toggleClass('fa-eye', show);
icon.toggleClass('fa-eye-slash', !show);
$('#toggle_codecells').attr(
'title', (show ? 'Hide' : 'Show') + ' codecell inputs');
}
function toggle() {
set_input_visible($('#toggle_codecells').hasClass('active'));
}
var load_ipython_extension = function() {
IPython.toolbar.add_buttons_group([{
id : 'toggle_codecells',
label : 'Hide codecell inputs',
icon : 'fa-eye',
callback : function() {
toggle();
setTimeout(function() { $('#toggle_codecells').blur(); }, 500);
}
}]);
set_input_visible(IPython.notebook.metadata.hide_input !== true);
};
return {
load_ipython_extension : load_ipython_extension
};
});
| // toggle display of all code cells' inputs
define([
'jquery',
'base/js/namespace',
'base/js/events'
], function(
$,
Jupyter,
events
) {
"use strict";
function set_input_visible(show) {
Jupyter.notebook.metadata.hide_input = !show;
if (show) $('div.input').show('slow');
else $('div.input').hide('slow');
var btn = $('#toggle_codecells');
btn.toggleClass('active', !show);
var icon = btn.find('i');
icon.toggleClass('fa-eye', show);
icon.toggleClass('fa-eye-slash', !show);
$('#toggle_codecells').attr(
'title', (show ? 'Hide' : 'Show') + ' codecell inputs');
}
function toggle() {
set_input_visible($('#toggle_codecells').hasClass('active'));
}
function initialize () {
set_input_visible(Jupyter.notebook.metadata.hide_input !== true);
}
var load_ipython_extension = function() {
Jupyter.toolbar.add_buttons_group([{
id : 'toggle_codecells',
label : 'Hide codecell inputs',
icon : 'fa-eye',
callback : function() {
toggle();
setTimeout(function() { $('#toggle_codecells').blur(); }, 500);
}
}]);
if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) {
// notebook_loaded.Notebook event has already happened
initialize();
}
events.on('notebook_loaded.Notebook', initialize);
};
return {
load_ipython_extension : load_ipython_extension
};
});
| Fix loading for either before or after notebook loads. | [hide_input_all] Fix loading for either before or after notebook loads.
| JavaScript | bsd-3-clause | ipython-contrib/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions | ---
+++
@@ -2,15 +2,17 @@
define([
'jquery',
- 'base/js/namespace'
+ 'base/js/namespace',
+ 'base/js/events'
], function(
$,
- IPython
+ Jupyter,
+ events
) {
"use strict";
function set_input_visible(show) {
- IPython.notebook.metadata.hide_input = !show;
+ Jupyter.notebook.metadata.hide_input = !show;
if (show) $('div.input').show('slow');
else $('div.input').hide('slow');
@@ -29,8 +31,12 @@
set_input_visible($('#toggle_codecells').hasClass('active'));
}
+ function initialize () {
+ set_input_visible(Jupyter.notebook.metadata.hide_input !== true);
+ }
+
var load_ipython_extension = function() {
- IPython.toolbar.add_buttons_group([{
+ Jupyter.toolbar.add_buttons_group([{
id : 'toggle_codecells',
label : 'Hide codecell inputs',
icon : 'fa-eye',
@@ -39,8 +45,11 @@
setTimeout(function() { $('#toggle_codecells').blur(); }, 500);
}
}]);
-
- set_input_visible(IPython.notebook.metadata.hide_input !== true);
+ if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) {
+ // notebook_loaded.Notebook event has already happened
+ initialize();
+ }
+ events.on('notebook_loaded.Notebook', initialize);
};
return { |
0c0878ac06febc05dd34f617c6a874e3a5d2ee49 | lib/node_modules/@stdlib/utils/move-property/lib/index.js | lib/node_modules/@stdlib/utils/move-property/lib/index.js | 'use strict';
/**
* FUNCTION: moveProperty( source, prop, target )
* Moves a property from one object to another object.
*
* @param {Object} source - source object
* @param {String} prop - property to move
* @param {Object} target - target object
* @returns {Boolean} boolean indicating whether operation was successful
*/
function moveProperty( source, prop, target ) {
var desc;
if ( typeof source !== 'object' || source === null ) {
throw new TypeError( 'invalid input argument. Source argument must be an object. Value: `' + source + '`.' );
}
if ( typeof target !== 'object' || target === null ) {
throw new TypeError( 'invalid input argument. Target argument must be an object. Value: `' + target + '`.' );
}
desc = Object.getOwnPropertyDescriptor( source, prop );
if ( desc === void 0 ) {
return false;
}
delete source[ prop ];
Object.defineProperty( target, prop, desc );
return true;
} // end FUNCTION moveProperty()
// EXPORTS //
module.exports = moveProperty;
| 'use strict';
/**
* FUNCTION: moveProperty( source, prop, target )
* Moves a property from one object to another object.
*
* @param {Object} source - source object
* @param {String} prop - property to move
* @param {Object} target - target object
* @returns {Boolean} boolean indicating whether operation was successful
*/
function moveProperty( source, prop, target ) {
var desc;
if ( typeof source !== 'object' || source === null ) {
throw new TypeError( 'invalid input argument. Source argument must be an object. Value: `' + source + '`.' );
}
if ( typeof target !== 'object' || target === null ) {
throw new TypeError( 'invalid input argument. Target argument must be an object. Value: `' + target + '`.' );
}
// TODO: handle case where gOPD is not supported
desc = Object.getOwnPropertyDescriptor( source, prop );
if ( desc === void 0 ) {
return false;
}
delete source[ prop ];
Object.defineProperty( target, prop, desc );
return true;
} // end FUNCTION moveProperty()
// EXPORTS //
module.exports = moveProperty;
| Add TODO for handling getOwnPropertyDescriptor support | Add TODO for handling getOwnPropertyDescriptor support
| JavaScript | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -17,6 +17,7 @@
if ( typeof target !== 'object' || target === null ) {
throw new TypeError( 'invalid input argument. Target argument must be an object. Value: `' + target + '`.' );
}
+ // TODO: handle case where gOPD is not supported
desc = Object.getOwnPropertyDescriptor( source, prop );
if ( desc === void 0 ) {
return false; |
65294019c1d29baaa548e483e93c8c55bf4bbabb | static/site.js | static/site.js | jQuery( document ).ready( function( $ ) {
// Your JavaScript goes here
jQuery('#content').fitVids();
}); | jQuery( document ).ready( function( $ ) {
// Your JavaScript goes here
jQuery('#content').fitVids({customSelector: ".fitvids-responsive-iframe"});
}); | Add .fitvids-responsive-iframe class for making iframes responsive | Add .fitvids-responsive-iframe class for making iframes responsive
| JavaScript | mit | CoderDojo/cd-theme,CoderDojo/cd-theme,CoderDojo/cd-theme,CoderDojo/cd-theme | ---
+++
@@ -1,5 +1,5 @@
jQuery( document ).ready( function( $ ) {
// Your JavaScript goes here
- jQuery('#content').fitVids();
+ jQuery('#content').fitVids({customSelector: ".fitvids-responsive-iframe"});
}); |
9af98fed472b4dabeb7c713f44c0b5b80da8fe4a | website/src/app/project/experiments/experiment/experiment.model.js | website/src/app/project/experiments/experiment/experiment.model.js | export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = 'Look at grain size as it relates to hardness';
this.aim = '';
this.done = false;
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
| export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = '';
this.aim = '';
this.status = 'in-progress';
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
| Remove hard coded experiment description. Remove done field and add status field since that is what we get from the backend. | Remove hard coded experiment description. Remove done field and add status field since that is what we get from the backend.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -37,9 +37,9 @@
constructor(name) {
this.name = name;
this.goal = '';
- this.description = 'Look at grain size as it relates to hardness';
+ this.description = '';
this.aim = '';
- this.done = false;
+ this.status = 'in-progress';
this.steps = [];
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.