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 |
|---|---|---|---|---|---|---|---|---|---|---|
2e3231317d895c8b447aedd34b07a172c02ee25e | IfPermission.js | IfPermission.js | import _ from 'lodash';
const IfPermission = props =>
(_.get(props, ['currentPerms', props.perm]) ? props.children : null);
export default IfPermission;
| import _ from 'lodash';
const IfPermission = props =>
(props.stripes.hasPerm(props.perm) ? props.children : null);
export default IfPermission;
| Use stripes-core v0.3.0 API for permissions. | Use stripes-core v0.3.0 API for permissions.
| JavaScript | apache-2.0 | folio-org/stripes-core,folio-org/stripes-core,folio-org/stripes-core | ---
+++
@@ -1,6 +1,6 @@
import _ from 'lodash';
const IfPermission = props =>
- (_.get(props, ['currentPerms', props.perm]) ? props.children : null);
+ (props.stripes.hasPerm(props.perm) ? props.children : null);
export default IfPermission; |
f0a241b408fee0c91ebfe6df492c9bd52a345bbb | katas/es8/language/async-functions/basics.js | katas/es8/language/async-functions/basics.js | // 1: async - basics
// To do: make all tests pass, leave the assert lines unchanged!
describe('`async` defines an asynchronous function', function() {
describe('can be created', () => {
it('by prefixing a function expression with `async`', function() {
const f = async function() {};
assert.equal(f instanceof AsyncFunction, true);
});
it('by prefixing a function declaration with `async`', function() {
async function f() {}
assert.equal(f instanceof AsyncFunction, true);
});
it('by prefixing an arrow function with `async`', function() {
const f = async () => {};
assert.equal(f instanceof AsyncFunction, true);
});
});
});
// Note that AsyncFunction is not a global object.
// It could be obtained by evaluating the following code.
// see also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
| // 1: async - basics
// To do: make all tests pass, leave the assert lines unchanged!
describe('`async` defines an asynchronous function', function() {
describe('can be created by putting `async` before', () => {
it('a function expression', function() {
const f = async function() {};
assert.equal(f instanceof AsyncFunction, true);
});
it('a function declaration', function() {
async function f() {}
assert.equal(f instanceof AsyncFunction, true);
});
it('an arrow function', function() {
const f = async () => {};
assert.equal(f instanceof AsyncFunction, true);
});
it('an object method', function() {
const obj = {
f: async () => void 0,
};
assert.equal(obj.f instanceof AsyncFunction, true);
});
});
});
// Note that AsyncFunction is not a global object.
// It could be obtained by evaluating the following code.
// see also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
| Add one more creation way and refactor test descriptions. | Add one more creation way and refactor test descriptions.
| JavaScript | mit | tddbin/katas,tddbin/katas,tddbin/katas | ---
+++
@@ -3,18 +3,24 @@
describe('`async` defines an asynchronous function', function() {
- describe('can be created', () => {
- it('by prefixing a function expression with `async`', function() {
+ describe('can be created by putting `async` before', () => {
+ it('a function expression', function() {
const f = async function() {};
assert.equal(f instanceof AsyncFunction, true);
});
- it('by prefixing a function declaration with `async`', function() {
+ it('a function declaration', function() {
async function f() {}
assert.equal(f instanceof AsyncFunction, true);
});
- it('by prefixing an arrow function with `async`', function() {
+ it('an arrow function', function() {
const f = async () => {};
assert.equal(f instanceof AsyncFunction, true);
+ });
+ it('an object method', function() {
+ const obj = {
+ f: async () => void 0,
+ };
+ assert.equal(obj.f instanceof AsyncFunction, true);
});
});
|
347f51a03ce50384002268f4c122caf91f4a91dc | grails-app/assets/javascripts/imms.backbone.pack.js | grails-app/assets/javascripts/imms.backbone.pack.js | // Pure backbone stuffs
//
//= require app/settings
//= require bb/underscore-min
//= require bb/backbone-min
//= require_self
var pubSub = _.extend({},Backbone.Events); //http://blog.safaribooksonline.com/2013/10/02/decoupling-backbone-applications-with-pubsub/
(function(Backbone, _, App){
App.View = Backbone.View.extend({
constructor: function(opt) {
this.key = opt.key;
this.pubSub = opt.pubSub || window.pubSub;
Backbone.View.apply(this,arguments);
},
publishEvt : function(code, data) {
App.logDebug(">>> published event = "+ code);
this.pubSub.trigger(code, _.extend({key : this.key}, data));
},
subscribeEvt : function(code, callback) {
this.listenTo(this.pubSub, code, callback ,this);
},
remove: function() {
// this.$el.remove(); // this View is not removing the $el.
this.$el.unbind(); // just unbind all event
this.stopListening();
return this;
}
});
})(Backbone, _, App);
| // Pure backbone stuffs
//
//= require app/settings
//= require bb/underscore-min
//= require bb/backbone-min
//= require_self
var pubSub = _.extend({},Backbone.Events); //http://blog.safaribooksonline.com/2013/10/02/decoupling-backbone-applications-with-pubsub/
(function(Backbone, _, App){
App.View = Backbone.View.extend({
constructor: function(opt) {
this.key = opt.key || this.key;
this.pubSub = opt.pubSub || window.pubSub;
Backbone.View.apply(this,arguments);
},
publishEvt : function(code, data) {
App.logDebug(">>> published event = "+ code);
this.pubSub.trigger(code, _.extend({key : this.key}, data));
},
subscribeEvt : function(code, callback) {
this.listenTo(this.pubSub, code, callback ,this);
},
remove: function() {
// this.$el.remove(); // this View is not removing the $el.
this.$el.unbind(); // just unbind all event
this.stopListening();
return this;
}
});
})(Backbone, _, App);
| Allow to retrieve key from instance | Allow to retrieve key from instance
| JavaScript | apache-2.0 | arief-hidayat/imms-ui-plugin,arief-hidayat/imms-ui-plugin | ---
+++
@@ -11,7 +11,7 @@
(function(Backbone, _, App){
App.View = Backbone.View.extend({
constructor: function(opt) {
- this.key = opt.key;
+ this.key = opt.key || this.key;
this.pubSub = opt.pubSub || window.pubSub;
Backbone.View.apply(this,arguments);
}, |
9b00fcb2ff19bf4b48dcccc4528c6a5ae14c409e | packages/heroku-apps/test/commands/domains/index.js | packages/heroku-apps/test/commands/domains/index.js | 'use strict';
let nock = require('nock');
let cmd = require('../../../commands/domains');
let expect = require('chai').expect;
describe('domains', function() {
beforeEach(() => cli.mockConsole());
it('shows the domains', function() {
let api = nock('https://api.heroku.com:443')
.get('/apps/myapp/domains')
.reply(200, [
{"cname": "myapp.com", "hostname": "myapp.com", "kind": "custom"},
{"cname": null, "hostname": "myapp.herokuapp.com", "kind": "heroku"},
]);
return cmd.run({app: 'myapp', flags: {}})
.then(() => expect(cli.stdout).to.equal(`=== myapp Heroku Domain
myapp.herokuapp.com
=== myapp Custom Domains
Domain Name DNS Target
βββββββββββ ββββββββββ
myapp.com myapp.com
`))
.then(() => api.done());
});
});
| 'use strict';
let nock = require('nock');
let cmd = require('../../../commands/domains');
let expect = require('chai').expect;
describe('domains', function() {
beforeEach(() => cli.mockConsole());
it('shows the domains', function() {
let api = nock('https://api.heroku.com:443')
.get('/apps/myapp/domains')
.reply(200, [
{"cname": "myapp.com", "hostname": "myapp.com", "kind": "custom"},
{"cname": null, "hostname": "myapp.herokuapp.com", "kind": "heroku"},
]);
return cmd.run({app: 'myapp', flags: {}})
.then(() => expect(cli.stdout).to.equal(`=== myapp Heroku Domain
myapp.herokuapp.com
=== myapp Custom Domains
Domain Name DNS Target
βββββββββββ ββββββββββ
myapp.com myapp.com
`))
.then(() => api.done());
});
});
| Fix domains test after pull & npm install | Fix domains test after pull & npm install
| JavaScript | isc | heroku/heroku-cli,heroku/cli,heroku/cli,heroku/cli,heroku/heroku-cli,heroku/heroku-cli,heroku/heroku-cli,heroku/cli | ---
+++
@@ -21,7 +21,7 @@
=== myapp Custom Domains
Domain Name DNS Target
βββββββββββ ββββββββββ
-myapp.com myapp.com
+myapp.com myapp.com
`))
.then(() => api.done());
}); |
1f36391615f1d79f85b43e81d030e75efd373ca1 | public/app/scripts/app.js | public/app/scripts/app.js | 'use strict';
angular.module('publicApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/users/:id', {
templateUrl: 'views/user.html',
controller: 'UsersCtrl'
})
.when('/admin', {
templateUrl: 'views/admin/settings.html',
controller: 'AdminCtrl'
})
.when('/register', {
templateUrl: 'views/register',
controller: 'RegistrationCtrl'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.when('/api/docs', {
templateUrl: 'views/api.html',
controller: 'ApiDocsCtrl'
})
.otherwise({
redirectTo: '/api/docs'
});
});
| 'use strict';
angular.module('publicApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/users/:id', {
templateUrl: 'views/users.html',
controller: 'UsersCtrl'
})
.when('/admin', {
templateUrl: 'views/admin.html',
controller: 'AdminCtrl'
})
.when('/register', {
templateUrl: 'views/register.html',
controller: 'RegistrationCtrl'
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.when('/api/docs', {
templateUrl: 'views/api.html',
controller: 'ApiDocsCtrl'
})
.when('/ripple/deposit', {
templateUrl: 'views/ripple/deposit.html',
controller: 'RippleTransactionsCtrl'
})
.when('/ripple/withdraw', {
templateUrl: 'views/ripple/withdraw.html',
controller: 'RippleTransactionsCtrl'
})
.otherwise({
redirectTo: '/users/-1'
});
});
| Add route for user ripple deposit, withdraw in angular | [FEATURE] Add route for user ripple deposit, withdraw in angular
| JavaScript | isc | whotooktwarden/gatewayd,Parkjeahwan/awegeeks,crazyquark/gatewayd,xdv/gatewayd,whotooktwarden/gatewayd,Parkjeahwan/awegeeks,xdv/gatewayd,zealord/gatewayd,crazyquark/gatewayd,zealord/gatewayd | ---
+++
@@ -9,15 +9,15 @@
.config(function ($routeProvider) {
$routeProvider
.when('/users/:id', {
- templateUrl: 'views/user.html',
+ templateUrl: 'views/users.html',
controller: 'UsersCtrl'
})
.when('/admin', {
- templateUrl: 'views/admin/settings.html',
+ templateUrl: 'views/admin.html',
controller: 'AdminCtrl'
})
.when('/register', {
- templateUrl: 'views/register',
+ templateUrl: 'views/register.html',
controller: 'RegistrationCtrl'
})
.when('/login', {
@@ -28,7 +28,15 @@
templateUrl: 'views/api.html',
controller: 'ApiDocsCtrl'
})
+ .when('/ripple/deposit', {
+ templateUrl: 'views/ripple/deposit.html',
+ controller: 'RippleTransactionsCtrl'
+ })
+ .when('/ripple/withdraw', {
+ templateUrl: 'views/ripple/withdraw.html',
+ controller: 'RippleTransactionsCtrl'
+ })
.otherwise({
- redirectTo: '/api/docs'
+ redirectTo: '/users/-1'
});
}); |
ad676e36e9756335841fa81621be35f59f95cb0a | models/product_model.js | models/product_model.js | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var ProductType = require("./producttype_model");
var Location = require("./location_model");
var ProductSchema = new Schema({
name: String,
description: String,
location_id: { type: ObjectId, ref: 'Location' },
producttype_id: { type: ObjectId, ref: 'ProductType' },
price: { type: Number, validate: function(v) { return (v > 0); }, required: true },
member_discount: { type: Number, default: 0 },
topup_size: Number,
volume: Number,
xero_account: String,
xero_code: { type: String, index: true },
xero_id: String,
payment_options: [ { type: String, validate: /stuff|space|creditcard|account/, required: true } ],
self_service: { type: Boolean, default: false, index: true },
date_created: { type: Date, default: Date.now },
recurring_cost: { type: String, validate: /once-off|monthly|annually/, default: "monthly" },
_owner_id: ObjectId,
_deleted: { type: Boolean, default: false, index: true },
});
ProductSchema.set("_perms", {
admin: "crud",
owner: "r",
user: "r",
all: "r"
});
module.exports = mongoose.model('Product', ProductSchema);
| var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var ProductType = require("./producttype_model");
var Location = require("./location_model");
var ProductSchema = new Schema({
name: String,
description: String,
location_id: { type: ObjectId, ref: 'Location' },
producttype_id: { type: ObjectId, ref: 'ProductType' },
price: { type: Number, validate: function(v) { return (v > 0); }, required: true },
member_discount: { type: Number, default: 0 },
topup_size: Number,
volume: Number,
xero_account: String,
xero_code: { type: String, index: true },
xero_id: String,
payment_options: [ { type: String, validate: /stuff|space|creditcard|account/, required: true } ],
self_service: { type: Boolean, default: false, index: true },
date_created: { type: Date, default: Date.now },
pro_rata: { type: Boolean, default: false, index: true },
_owner_id: ObjectId,
_deleted: { type: Boolean, default: false, index: true },
});
ProductSchema.set("_perms", {
admin: "crud",
owner: "r",
user: "r",
all: "r"
});
module.exports = mongoose.model('Product', ProductSchema);
| Drop recurring_cost in favour of pro_rata boolean | Drop recurring_cost in favour of pro_rata boolean
| JavaScript | mit | 10layer/jexpress,10layer/jexpress | ---
+++
@@ -20,7 +20,7 @@
payment_options: [ { type: String, validate: /stuff|space|creditcard|account/, required: true } ],
self_service: { type: Boolean, default: false, index: true },
date_created: { type: Date, default: Date.now },
- recurring_cost: { type: String, validate: /once-off|monthly|annually/, default: "monthly" },
+ pro_rata: { type: Boolean, default: false, index: true },
_owner_id: ObjectId,
_deleted: { type: Boolean, default: false, index: true },
}); |
f58d1f8d18edd74927167a9fd4336f78d64da133 | LoadPredictor/linear_regression.js | LoadPredictor/linear_regression.js | var data = []
var w0 = 1;
var w1 = 0;
var w2 = 0;
var alpha = 0.01;
module.exports = {
reportWeights : function(io) {
//setInterval(function(){
io.emit('weights', JSON.stringify({"w0": w0, "w1": w1, "w2": w2}));
//}, 100);
},
weightUpdate : function(io) {
var predict = this.predict;
var reportWeights = this.reportWeights;
setInterval(function(){
data.forEach(function(d){
var z = predict(d[0], d[1]);
w1 += alpha * (d[2] - z) * d[0];
w2 += alpha * (d[2] - z) * d[1];
w0 += alpha * (d[2] - z);
});
reportWeights(io);
}, 500);
},
addData : function(d){
data.push(d);
},
predict : function(tMinusOneYear, tMinusOneHour){
return (w1 * tMinusOneYear) + (w2 * tMinusOneHour) + w0;
}
}
| var data = []
var w0 = 1;
var w1 = 0;
var w2 = 0;
var alpha = 0.01;
module.exports = {
reportWeights : function(io) {
//setInterval(function(){
io.emit('weights', JSON.stringify({"w0": w0, "w1": w1, "w2": w2}));
//}, 100);
},
weightUpdate : function(io) {
var predict = this.predict;
var reportWeights = this.reportWeights;
setInterval(function(){
data.forEach(function(d){
var z = predict(d[0], d[1]);
w1 += alpha * (d[2] - z) * d[0];
w2 += alpha * (d[2] - z) * d[1];
w0 += alpha * (d[2] - z);
});
reportWeights(io);
}, 50);
},
addData : function(d){
data.push(d);
},
predict : function(tMinusOneYear, tMinusOneHour){
return (w1 * tMinusOneYear) + (w2 * tMinusOneHour) + w0;
}
}
| Update rate of weight update | Update rate of weight update
| JavaScript | mit | JoelHoskin/Load-Balancer,JoelHoskin/Load-Balancer,Lily418/Load-Balancer,Lily418/Load-Balancer,JoelHoskin/Load-Balancer,Lily418/Load-Balancer,JoelHoskin/Load-Balancer,Lily418/Load-Balancer | ---
+++
@@ -23,7 +23,7 @@
w0 += alpha * (d[2] - z);
});
reportWeights(io);
- }, 500);
+ }, 50);
},
addData : function(d){ |
f15eaf1ba637b0101df03d816ec995c8a07253a9 | event_manager.js | event_manager.js |
;(function(){
var binder = window.addEventListener ? 'addEventListener' : 'attachEvent'
, unbinder = window.removeEventListener ? 'removeEventListener' : 'detachEvent'
, eventPrefix = binder !== 'addEventListener' ? 'on' : '';
function bind(el, type, fn, capture) {
el[binder](eventPrefix + type, fn, capture || false);
return fn;
}
function unbind(el, type, fn, capture) {
el[unbinder](eventPrefix + type, fn, capture || false);
return fn;
}
function EventManager(el, obj) {
if (!(this instanceof EventManager)) return new EventManager(el, obj);
if (!el) throw new Error('Element missing');
// TODO make this optional (for regular event binding)
if (!obj) throw new Error('Object missing');
this.el = el;
this.obj = obj;
this.eventSubscriptionList = {};
}
EventManager.prototype.bind = function(evt, fn) {
var obj = this.obj
, el = this.el;
function cb(e) {
fn.call(obj, e);
}
this.eventSubscriptionList[evt] = cb;
bind(el, evt, cb);
return cb;
};
// TODO this needs to be able to accept method names and not just callbacks
EventManager.prototype.unbind = function(evt) {
var obj = this.obj
, el = this.el
, cb = this.eventSubscriptionList[evt];
unbind(el, evt, cb);
return cb;
};
window.EventManager = EventManager;
})();
|
;(function(){
var binder = window.addEventListener ? 'addEventListener' : 'attachEvent'
, unbinder = window.removeEventListener ? 'removeEventListener' : 'detachEvent'
, eventPrefix = binder !== 'addEventListener' ? 'on' : '';
function bind(el, type, fn, capture) {
el[binder](eventPrefix + type, fn, capture || false);
return fn;
}
function unbind(el, type, fn, capture) {
el[unbinder](eventPrefix + type, fn, capture || false);
return fn;
}
function EventManager(el, obj) {
if (!(this instanceof EventManager)) return new EventManager(el, obj);
if (!el) throw new Error('Element missing');
// TODO make this optional (for regular event binding)
if (!obj) throw new Error('Object missing');
this.el = el;
this.obj = obj;
this.eventSubscriptionList = {};
}
EventManager.prototype.bind = function(evt, fn) {
var obj = this.obj
, el = this.el
, args = [].slice.call(arguments, 2);
function cb(e) {
var a = [].slice.call(arguments).concat(args);
fn.apply(obj, a);
}
this.eventSubscriptionList[evt] = cb;
bind(el, evt, cb);
return cb;
};
// TODO this needs to be able to accept method names and not just callbacks
EventManager.prototype.unbind = function(evt) {
var obj = this.obj
, el = this.el
, cb = this.eventSubscriptionList[evt];
unbind(el, evt, cb);
};
window.EventManager = EventManager;
})();
| Support extra params on event manager | Support extra params on event manager
| JavaScript | mit | mohnish/draw,mohnish/draw | ---
+++
@@ -26,10 +26,12 @@
EventManager.prototype.bind = function(evt, fn) {
var obj = this.obj
- , el = this.el;
+ , el = this.el
+ , args = [].slice.call(arguments, 2);
function cb(e) {
- fn.call(obj, e);
+ var a = [].slice.call(arguments).concat(args);
+ fn.apply(obj, a);
}
this.eventSubscriptionList[evt] = cb;
@@ -45,7 +47,6 @@
, cb = this.eventSubscriptionList[evt];
unbind(el, evt, cb);
- return cb;
};
window.EventManager = EventManager; |
90dab6edce51252b904de8c08d520c0a76635d23 | logger.js | logger.js | /*jslint node: true */
'use strict';
var fs = require('fs');
var Logger = function() {};
var defaults = function(object, defaults) {
for (var prop in defaults) {
if (object[prop] === void 0) object[prop] = defaults[prop];
}
return object;
};
Logger.prototype.setOptions = function(options) {
this.options = defaults(options || {}, {file: __dirname + '/logger.log', consoleLog: true});
if (this.options.file) {
this.logger = fs.createWriteStream(this.options.file, { flags: 'a' });
}
},
Logger.prototype.log = function(message) {
if (message) {
if (!this.options) this.setOptions();
if (this.options.consoleLog) console.log(message);
this.logger.write(new Date() + ' ' + JSON.stringify(message) + "\n");
}
};
module.exports = new Logger();
| /*jslint node: true */
'use strict';
var fs = require('fs');
var Logger = function() {};
var defaults = function(object, defaults) {
for (var prop in defaults) {
if (object[prop] === void 0) object[prop] = defaults[prop];
}
return object;
};
Logger.prototype.setOptions = function(options) {
this.options = defaults(options || {}, {file: __dirname + '/logger.log', consoleLog: true});
if (this.options.file) {
this.logger = fs.createWriteStream(this.options.file, { flags: 'a' });
}
},
Logger.prototype.log = function(message) {
if (message) {
if (!this.options) this.setOptions();
if (this.options.consoleLog) console.log(message);
if (this.logger) this.logger.write(new Date() + ' ' + JSON.stringify(message) + "\n");
}
};
module.exports = new Logger();
| Fix issue with writing to log file when not suppose to | Fix issue with writing to log file when not suppose to
| JavaScript | mit | olekenneth/node-simplelogger | ---
+++
@@ -24,7 +24,7 @@
if (!this.options) this.setOptions();
if (this.options.consoleLog) console.log(message);
- this.logger.write(new Date() + ' ' + JSON.stringify(message) + "\n");
+ if (this.logger) this.logger.write(new Date() + ' ' + JSON.stringify(message) + "\n");
}
};
|
3c6595ff9923fe8a122ce3074842ef1e7be519d2 | Test/Siv3DTest.js | Test/Siv3DTest.js | Module.preRun = [
function ()
{
FS.mkdir('/test');
FS.mount(NODEFS, { root: '../../Test/test' }, '/test');
}
] | Module.preRun = [
function ()
{
FS.mkdir('/test');
FS.mount(NODEFS, { root: '../../Test/test' }, '/test');
FS.mkdir('/resources');
FS.mount(NODEFS, { root: './resources' }, '/resources');
}
] | Add resources folder into test environment | [Web] Add resources folder into test environment
| JavaScript | mit | Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D | ---
+++
@@ -3,5 +3,8 @@
{
FS.mkdir('/test');
FS.mount(NODEFS, { root: '../../Test/test' }, '/test');
+
+ FS.mkdir('/resources');
+ FS.mount(NODEFS, { root: './resources' }, '/resources');
}
] |
60a2b50f5c49c3c109f3f90e53897a1601bdd256 | plugins/cache_reload.js | plugins/cache_reload.js | /**
* \file cache_reload.js
* Plugin that forces a cache reload of boomerang (assuming you have server side support)
* Copyright (c) 2013, SOASTA, Inc. All rights reserved.
*/
(function() {
BOOMR = BOOMR || {};
BOOMR.plugins = BOOMR.plugins || {};
var impl = {
url: "",
initialized: false
};
BOOMR.plugins.CACHE_RELOAD = {
init: function(config) {
BOOMR.utils.pluginConfig(impl, config, "CACHE_RELOAD", ["url"]);
if(this.initalized)
return this;
BOOMR.subscribe(
"page_ready",
function() {
if(!impl.url)
return;
// we use document and not BOOMR.window.document since
// we can run inside the boomerang iframe if any
var i=document.createElement('iframe');
i.style.display="none";
i.src=impl.url;
document.body.appendChild(i);
},
null,
null
);
this.initialized = true;
return this;
},
is_complete: function() {
// we always return true since this plugin never adds anything to the beacon
return true;
}
};
}());
| /**
* \file cache_reload.js
* Plugin that forces a cache reload of boomerang (assuming you have server side support)
* Copyright (c) 2013, SOASTA, Inc. All rights reserved.
*/
(function() {
BOOMR = BOOMR || {};
BOOMR.plugins = BOOMR.plugins || {};
var impl = {
url: ""
};
BOOMR.plugins.CACHE_RELOAD = {
init: function(config) {
BOOMR.utils.pluginConfig(impl, config, "CACHE_RELOAD", ["url"]);
if(!impl.url)
return this;
// we use document and not BOOMR.window.document since
// we can run inside the boomerang iframe if any
var i=document.createElement('iframe');
i.style.display="none";
i.src=impl.url;
document.body.appendChild(i);
return this;
},
is_complete: function() {
// we always return true since this plugin never adds anything to the beacon
return true;
}
};
}());
| Load cache reload iframe as soon as we have a url | Load cache reload iframe as soon as we have a url
We should not wait for onload to fire because it might never fire.
Instead, we run the cache reload code as soon as we have a url, and
allow it to reload the user's browser cache.
| JavaScript | bsd-3-clause | lognormal/boomerang,lognormal/boomerang | ---
+++
@@ -11,33 +11,22 @@
BOOMR.plugins = BOOMR.plugins || {};
var impl = {
- url: "",
- initialized: false
+ url: ""
};
BOOMR.plugins.CACHE_RELOAD = {
init: function(config) {
BOOMR.utils.pluginConfig(impl, config, "CACHE_RELOAD", ["url"]);
- if(this.initalized)
+ if(!impl.url)
return this;
- BOOMR.subscribe(
- "page_ready",
- function() {
- if(!impl.url)
- return;
- // we use document and not BOOMR.window.document since
- // we can run inside the boomerang iframe if any
- var i=document.createElement('iframe');
- i.style.display="none";
- i.src=impl.url;
- document.body.appendChild(i);
- },
- null,
- null
- );
- this.initialized = true;
+ // we use document and not BOOMR.window.document since
+ // we can run inside the boomerang iframe if any
+ var i=document.createElement('iframe');
+ i.style.display="none";
+ i.src=impl.url;
+ document.body.appendChild(i);
return this;
}, |
e2dee2041a4c5efb0e962843562ddd3880e0dbcb | services/v4/launchpads/model.js | services/v4/launchpads/model.js | const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');
const idPlugin = require('mongoose-id');
const launchpadSchema = new mongoose.Schema({
name: {
type: String,
default: null,
},
full_name: {
type: String,
default: null,
},
status: {
type: String,
enum: ['active', 'inactive', 'unknown', 'retired', 'lost', 'under construction'],
required: true,
},
locality: {
type: String,
default: null,
},
region: {
type: String,
default: null,
},
timezone: {
type: String,
default: null,
},
latitude: {
type: Number,
default: null,
},
longitude: {
type: Number,
default: null,
},
launch_attempts: {
type: Number,
default: 0,
},
launch_successes: {
type: Number,
default: 0,
},
rockets: [{
type: mongoose.ObjectId,
ref: 'Rocket',
}],
launches: [{
type: mongoose.ObjectId,
ref: 'Launch',
}],
}, { autoCreate: true });
launchpadSchema.plugin(mongoosePaginate);
launchpadSchema.plugin(idPlugin);
const Launchpad = mongoose.model('Launchpad', launchpadSchema);
module.exports = Launchpad;
| const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');
const idPlugin = require('mongoose-id');
const launchpadSchema = new mongoose.Schema({
name: {
type: String,
default: null,
},
full_name: {
type: String,
default: null,
},
status: {
type: String,
enum: ['active', 'inactive', 'unknown', 'retired', 'lost', 'under construction'],
required: true,
},
locality: {
type: String,
default: null,
},
region: {
type: String,
default: null,
},
timezone: {
type: String,
default: null,
},
latitude: {
type: Number,
default: null,
},
longitude: {
type: Number,
default: null,
},
launch_attempts: {
type: Number,
default: 0,
},
launch_successes: {
type: Number,
default: 0,
},
rockets: [{
type: mongoose.ObjectId,
ref: 'Rocket',
}],
launches: [{
type: mongoose.ObjectId,
ref: 'Launch',
}],
details: {
type: String,
default: null,
},
}, { autoCreate: true });
launchpadSchema.plugin(mongoosePaginate);
launchpadSchema.plugin(idPlugin);
const Launchpad = mongoose.model('Launchpad', launchpadSchema);
module.exports = Launchpad;
| Add details field to launchpads | Add details field to launchpads
| JavaScript | apache-2.0 | r-spacex/SpaceX-API,r-spacex/SpaceX-API | ---
+++
@@ -52,6 +52,10 @@
type: mongoose.ObjectId,
ref: 'Launch',
}],
+ details: {
+ type: String,
+ default: null,
+ },
}, { autoCreate: true });
launchpadSchema.plugin(mongoosePaginate); |
02b1e8274d769045e8f6e49b579db478c5c8e4c1 | client/app/common/common.js | client/app/common/common.js | import angular from 'angular'
import Navbar from './navbar/navbar'
import Hero from './hero/hero'
import User from './user/user'
const commonModule = angular.module('app.common', [
Navbar.name,
Hero.name,
User.name
])
export default commonModule
| import angular from 'angular'
import Navbar from './navbar/navbar'
import User from './user/user'
const commonModule = angular.module('app.common', [
Navbar.name,
User.name
])
export default commonModule
| Remove forgotten references to Hero component | Remove forgotten references to Hero component
| JavaScript | apache-2.0 | mklinga/aprendo,mklinga/aprendo | ---
+++
@@ -1,11 +1,9 @@
import angular from 'angular'
import Navbar from './navbar/navbar'
-import Hero from './hero/hero'
import User from './user/user'
const commonModule = angular.module('app.common', [
Navbar.name,
- Hero.name,
User.name
])
|
90d2e32a34c5514a3c5b77090d16a082d512797c | src/build_parts.js | src/build_parts.js | function convertToKeyValueString(obj) {
return JSON.stringify(obj).slice(1, -1);
}
function buildParts({ id, dataLayerName = 'dataLayer', additionalEvents = {} }) {
if (id === undefined) {
throw new Error('No GTM id provided');
}
const iframe = `
<iframe src="//www.googletagmanager.com/ns.html?id=${id}"
height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
const script = `
(function(w,d,s,l,i){w[l]=w[l]||[];
w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js', ${convertToKeyValueString(additionalEvents)}});
var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','${dataLayerName}','${id}');`;
return {
iframe,
script
};
}
export default buildParts;
| function convertToKeyValueString(obj) {
return JSON.stringify(obj).slice(1, -1);
}
function buildParts({ id, dataLayerName = 'dataLayer', additionalEvents = {}, scheme = '' }) {
if (id === undefined) {
throw new Error('No GTM id provided');
}
const iframe = `
<iframe src="${scheme}//www.googletagmanager.com/ns.html?id=${id}"
height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
const script = `
(function(w,d,s,l,i){w[l]=w[l]||[];
w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js', ${convertToKeyValueString(additionalEvents)}});
var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
j.async=true;j.src='${scheme}//www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','${dataLayerName}','${id}');`;
return {
iframe,
script
};
}
export default buildParts;
| Allow scheme/protocol to be passed to script | Allow scheme/protocol to be passed to script
Googles GTM now seems to redirect any http request to https, this now causes an extra redirect which seems wasteful.
This proposal is to allow someone to pass in the scheme they desire so someone can always call https if they want.
The alternative would be to always use https hardcoded in the scripts, however i'm not sure if people want that and would prefer to keep it as it currently sits. | JavaScript | mit | holidaycheck/react-google-tag-manager | ---
+++
@@ -2,20 +2,20 @@
return JSON.stringify(obj).slice(1, -1);
}
-function buildParts({ id, dataLayerName = 'dataLayer', additionalEvents = {} }) {
+function buildParts({ id, dataLayerName = 'dataLayer', additionalEvents = {}, scheme = '' }) {
if (id === undefined) {
throw new Error('No GTM id provided');
}
const iframe = `
- <iframe src="//www.googletagmanager.com/ns.html?id=${id}"
+ <iframe src="${scheme}//www.googletagmanager.com/ns.html?id=${id}"
height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
const script = `
(function(w,d,s,l,i){w[l]=w[l]||[];
w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js', ${convertToKeyValueString(additionalEvents)}});
var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
- j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;
+ j.async=true;j.src='${scheme}//www.googletagmanager.com/gtm.js?id='+i+dl;
f.parentNode.insertBefore(j,f);
})(window,document,'script','${dataLayerName}','${id}');`;
|
6f30dabb0f786e45d1bd045557272e1bf15e9b3e | src/environment.js | src/environment.js | const minimist = require('minimist');
// prepare CLI arguments
const argv = minimist(process.argv.slice(2), {
boolean: ["dev", "debug", "d", "v", "lint", "help", "version"],
string: ["init"],
});
const cwd = process.cwd();
module.exports = {
runnerPath: `${cwd}/kabafile.js`,
modulePath: `${cwd}/node_modules/kaba`,
app: getAppEnvironment(argv),
verbose: argv.v,
arguments: argv._,
init: argv.init || null,
version: argv.version,
help: argv.help,
};
/**
*
* @param {{dev: boolean, debug: boolean, d: boolean, v: boolean, lint: boolean}} argv
*
* @return {KabaAppEnvironment}
*/
function getAppEnvironment (argv)
{
const debug = argv.dev || argv.debug || argv.d;
return {
debug: debug,
lint: argv.lint || debug,
watch: debug,
verbose: argv.v,
mode: argv.lint ? "lint" : "compile",
cliVersion: null,
};
}
| const minimist = require('minimist');
// prepare CLI arguments
const argv = minimist(process.argv.slice(2), {
boolean: ["dev", "debug", "d", "v", "lint", "help", "version"],
string: ["init"],
});
const cwd = process.cwd();
module.exports = {
runnerPath: `${cwd}/kabafile.js`,
modulePath: `${cwd}/node_modules/kaba`,
app: getAppEnvironment(argv),
verbose: argv.v,
arguments: argv._,
init: argv.init || null,
version: argv.version,
help: argv.help,
};
/**
*
* @param {{dev: boolean, debug: boolean, d: boolean, v: boolean, lint: boolean}} argv
*
* @return {KabaAppEnvironment}
*/
function getAppEnvironment (argv)
{
const env = {
debug: false,
lint: false,
watch: false,
verbose: false,
mode: "compile",
cliVersion: null,
};
if (argv.d || argv.dev)
{
env.debug = true;
env.lint = true;
env.watch = true;
}
if (argv.debug)
{
env.debug = true;
}
if (argv.v)
{
env.verbose = true;
}
if (argv.lint)
{
env.lint = true;
env.mode = "lint";
}
if (argv.debug)
{
env.debug = true;
}
return env;
}
| Fix parsing of the CLI parameters | Fix parsing of the CLI parameters
| JavaScript | bsd-3-clause | Becklyn/kaba-cli | ---
+++
@@ -30,14 +30,43 @@
*/
function getAppEnvironment (argv)
{
- const debug = argv.dev || argv.debug || argv.d;
-
- return {
- debug: debug,
- lint: argv.lint || debug,
- watch: debug,
- verbose: argv.v,
- mode: argv.lint ? "lint" : "compile",
+ const env = {
+ debug: false,
+ lint: false,
+ watch: false,
+ verbose: false,
+ mode: "compile",
cliVersion: null,
};
+
+ if (argv.d || argv.dev)
+ {
+ env.debug = true;
+ env.lint = true;
+ env.watch = true;
+ }
+
+ if (argv.debug)
+ {
+ env.debug = true;
+ }
+
+ if (argv.v)
+ {
+ env.verbose = true;
+ }
+
+ if (argv.lint)
+ {
+ env.lint = true;
+ env.mode = "lint";
+ }
+
+
+ if (argv.debug)
+ {
+ env.debug = true;
+ }
+
+ return env;
} |
611ddda8d9ec41ba2f8be3b0f4a84f7e8ea3675a | src/item-button.js | src/item-button.js | import Item from './item';
export default class ButtonItem extends Item {
constructor() {
super();
this._root
.classed('button', true)
.styles({
'background': '#FFF',
'cursor': 'pointer',
'height': '3em',
'justify-content': 'center',
'padding': '0.5em 0'
});
this._button = this._root
.append('button')
.attrs({
'tabindex': -1,
'type': 'button'
})
.styles({
'background': 'none',
'border': '1px solid transparent',
'color': 'inherit',
'cursor': 'inherit',
'line-height': '2em',
'margin': 0,
'padding': '0 0.25em'
});
this._text = this._button
.append('span')
.styles({
'position': 'relative'
});
this._padding.styles({
'display': 'none'
});
}
tabindex(value = null) {
if (value === null) {
return this._button.attr('tabindex');
}
this._button.attr('tabindex', value);
return this;
}
text(value = null) {
if (value === null) {
return this._text;
}
this._text.text(value);
return this;
}
_click() {
if (this._disabled === false && this._model) {
this._model.set(this._name, this._value);
}
}
}
| import Item from './item';
export default class ButtonItem extends Item {
constructor() {
super();
this._root
.classed('button', true)
.styles({
'background': '#FFF',
'cursor': 'pointer',
'height': '3em',
'justify-content': 'center',
'padding': '0.5em 0'
});
this._button = this._root
.append('button')
.attrs({
'tabindex': -1,
'type': 'button'
})
.styles({
'background': 'none',
'border': '1px solid transparent',
'color': 'inherit',
'cursor': 'inherit',
'line-height': '2em',
'margin': 0,
'padding': '0 0.25em'
});
this._text = this._button
.append('span')
.styles({
'position': 'relative'
});
this._padding.styles({
'display': 'none'
});
}
color(value = null) {
if (value === null) {
return this._root.style('color');
}
this._root.style('color', value);
return this;
}
tabindex(value = null) {
if (value === null) {
return this._button.attr('tabindex');
}
this._button.attr('tabindex', value);
return this;
}
text(value = null) {
if (value === null) {
return this._text;
}
this._text.text(value);
return this;
}
_click() {
if (this._disabled === false && this._model) {
this._model.set(this._name, this._value);
}
}
}
| Add color method to button item | Add color method to button item
| JavaScript | mit | scola84/node-d3-list | ---
+++
@@ -41,6 +41,15 @@
});
}
+ color(value = null) {
+ if (value === null) {
+ return this._root.style('color');
+ }
+
+ this._root.style('color', value);
+ return this;
+ }
+
tabindex(value = null) {
if (value === null) {
return this._button.attr('tabindex'); |
d363158be52071999adc68ee5d0924866df2a8cb | problems/detectPermutation/javascript/detectPermutations.js | problems/detectPermutation/javascript/detectPermutations.js | const _ = require('lodash');
const quicksort = require('../../sorting-algorithms/javascript/quickSort');
module.exports = detectPermutations;
function detectPermutations (str1, str2) {
let srtd1 = str1.split('');
let srtd2 = str2.split('');
quicksort(srtd1);
quicksort(srtd2);
return srtd1.join('') === srtd2.join('');
}
function detectPermutationsNoSorting(str1, str2) {
let str1Chars = {};
let str2Chars = {};
}
let str1 = "cdeflkjh";
let str2 = "dcefhjkl";
console.log( detectPermutations(str1, str2));
| const _ = require('lodash');
const quicksort = require('../../sorting-algorithms/javascript/quickSort');
module.exports = detectPermutations;
function detectPermutations (str1, str2) {
let srtd1 = str1.split('');
let srtd2 = str2.split('');
quicksort(srtd1);
quicksort(srtd2);
return srtd1.join('') === srtd2.join('');
}
function detectPermutationsNoSorting(str1, str2) {
let str1Chars = countChars(str1);
let str2Chars = countChars(str2);
if (Object.keys(str1Chars).length !== Object.keys(str2Chars).length) {
return false;
} else {
for (let char in str1Chars) {
if (str1Chars.hasOwnProperty(char) && str1Chars[char] !== str2Chars[char]) return false;
}
return true;
}
function countChars (str) {
let count = {};
for (let char in str) {
//initialize
count[char] = count[char] || 0;
//increment
count[char]++;
}
return count;
}
}
let str1 = "cdeflkjh";
let str2 = "dcefhjkl";
console.log( detectPermutationsNoSorting(str1, str2));
| Add no-sorting version of detect permutations. | Add no-sorting version of detect permutations.
| JavaScript | mit | philosoralphter/ToyProblems,philosoralphter/ToyProblems | ---
+++
@@ -15,14 +15,34 @@
}
function detectPermutationsNoSorting(str1, str2) {
- let str1Chars = {};
- let str2Chars = {};
+ let str1Chars = countChars(str1);
+ let str2Chars = countChars(str2);
+
+ if (Object.keys(str1Chars).length !== Object.keys(str2Chars).length) {
+ return false;
+ } else {
+ for (let char in str1Chars) {
+ if (str1Chars.hasOwnProperty(char) && str1Chars[char] !== str2Chars[char]) return false;
+ }
+ return true;
+ }
+ function countChars (str) {
+ let count = {};
+ for (let char in str) {
+ //initialize
+ count[char] = count[char] || 0;
+ //increment
+ count[char]++;
+ }
+
+ return count;
+ }
}
let str1 = "cdeflkjh";
let str2 = "dcefhjkl";
-console.log( detectPermutations(str1, str2));
+console.log( detectPermutationsNoSorting(str1, str2)); |
56794f1bf3b34503764c897aebf672e92b4f2dbb | deserializers/resource.js | deserializers/resource.js | 'use strict';
var _ = require('lodash');
var P = require('bluebird');
var humps = require('humps');
var Schemas = require('../generators/schemas');
function ResourceDeserializer(model, params) {
var schema = Schemas.schemas[model.collection.name];
function extractAttributes() {
return new P(function (resolve) {
var attributes = params.data.attributes;
attributes._id = params.data.id;
resolve(attributes);
});
}
function extractRelationships() {
return new P(function (resolve) {
var relationships = {};
_.each(schema.fields, function (field) {
if (field.reference && params.data.relationships[field.field] &&
params.data.relationships[field.field].data) {
relationships[field.field] = params.data.relationships[field.field]
.data.id;
}
});
resolve(relationships);
});
}
this.perform = function () {
return P.all([extractAttributes(), extractRelationships()])
.spread(function (attributes, relationships) {
return humps.camelizeKeys(_.extend(attributes, relationships));
});
};
}
module.exports = ResourceDeserializer;
| 'use strict';
var _ = require('lodash');
var P = require('bluebird');
var humps = require('humps');
var Schemas = require('../generators/schemas');
function ResourceDeserializer(model, params) {
var schema = Schemas.schemas[model.collection.name];
function extractAttributes() {
return new P(function (resolve) {
var attributes = params.data.attributes;
attributes._id = params.data.id;
resolve(attributes);
});
}
function extractRelationships() {
return new P(function (resolve) {
var relationships = {};
_.each(schema.fields, function (field) {
if (field.reference && params.data.relationships[field.field]) {
if (params.data.relationships[field.field].data === null) {
// Remove the relationships
relationships[field.field] = null;
} else if (params.data.relationships[field.field].data) {
// Set the relationship
relationships[field.field] = params.data.relationships[field.field]
.data.id;
} // Else ignore the relationship
}
});
resolve(relationships);
});
}
this.perform = function () {
return P.all([extractAttributes(), extractRelationships()])
.spread(function (attributes, relationships) {
return humps.camelizeKeys(_.extend(attributes, relationships));
});
};
}
module.exports = ResourceDeserializer;
| Support the set/unset of belongsTo relationship | Support the set/unset of belongsTo relationship
| JavaScript | mit | SeyZ/forest-express-mongoose | ---
+++
@@ -20,10 +20,15 @@
var relationships = {};
_.each(schema.fields, function (field) {
- if (field.reference && params.data.relationships[field.field] &&
- params.data.relationships[field.field].data) {
- relationships[field.field] = params.data.relationships[field.field]
- .data.id;
+ if (field.reference && params.data.relationships[field.field]) {
+ if (params.data.relationships[field.field].data === null) {
+ // Remove the relationships
+ relationships[field.field] = null;
+ } else if (params.data.relationships[field.field].data) {
+ // Set the relationship
+ relationships[field.field] = params.data.relationships[field.field]
+ .data.id;
+ } // Else ignore the relationship
}
});
|
6940306bc0752e25f86818ef39e4bb52024b78f8 | src/public_path.js | src/public_path.js | // NOTE: Import this file before any other files
// Overwrite path to load resources or use default one.
__webpack_public_path__ = window.__patternslib_public_path__ || window.PORTAL_URL ? window.PORTAL_URL + "/++plone++static/bundles/" : null || "/dist/"; // eslint-disable-line no-undef
| // NOTE: Import this file before any other files
// Overwrite path to load resources or use default one.
__webpack_public_path__ = window.__patternslib_public_path__ || "/dist/"; // eslint-disable-line no-undef
| Remove implementation detail of Plone path fallback to chunks directory. It is set in Products.CMFPlone.resources.browser.scripts.pt | Remove implementation detail of Plone path fallback to chunks directory. It is set in Products.CMFPlone.resources.browser.scripts.pt
| JavaScript | bsd-3-clause | plone/mockup,plone/mockup,plone/mockup | ---
+++
@@ -1,3 +1,3 @@
// NOTE: Import this file before any other files
// Overwrite path to load resources or use default one.
-__webpack_public_path__ = window.__patternslib_public_path__ || window.PORTAL_URL ? window.PORTAL_URL + "/++plone++static/bundles/" : null || "/dist/"; // eslint-disable-line no-undef
+__webpack_public_path__ = window.__patternslib_public_path__ || "/dist/"; // eslint-disable-line no-undef |
a2cf41d042b71c2b418c6c5934c30774421a0eed | src/str-replace.js | src/str-replace.js | var replaceAll = function( oldToken ) {
var configs = this;
return {
from: function( string ) {
return {
to: function( newToken ) {
var _token;
var index = -1;
if ( configs.ignoringCase ) {
_token = oldToken.toLowerCase();
while((
index = string
.toLowerCase()
.indexOf(
_token,
index >= 0 ?
index + newToken.length : 0
)
) !== -1
) {
string = string
.substring( 0, index ) +
newToken +
string.substring( index + newToken.length );
}
return string;
}
return string.split( oldToken ).join( newToken );
}
};
},
ignoreCase: function() {
return replaceAll.call({
ignoringCase: true
}, oldToken );
}
};
};
module.exports = {
all: replaceAll
};
| var replaceAll = function( oldToken ) {
var configs = this;
return {
from: function( string ) {
return {
to: function( newToken ) {
var _token;
var index = -1;
if ( configs.ignoringCase ) {
_token = oldToken.toLowerCase();
while((
index = string
.toLowerCase()
.indexOf(
_token,
index >= 0 ?
index + newToken.length : 0
)
) !== -1 ) {
string = string
.substring( 0, index ) +
newToken +
string.substring( index + newToken.length );
}
return string;
}
return string.split( oldToken ).join( newToken );
}
};
},
ignoreCase: function() {
return replaceAll.call({
ignoringCase: true
}, oldToken );
}
};
};
module.exports = {
all: replaceAll
};
| ALign with the relevant code | ALign with the relevant code
| JavaScript | mit | FagnerMartinsBrack/str-replace | ---
+++
@@ -15,9 +15,8 @@
_token,
index >= 0 ?
index + newToken.length : 0
- )
- ) !== -1
- ) {
+ )
+ ) !== -1 ) {
string = string
.substring( 0, index ) +
newToken + |
2a4bd633c5598fa1f0e11663e849ada8da19ac60 | web/client/src/Routes.js | web/client/src/Routes.js | import React from "react";
import {Router, Route, Link, browserHistory, IndexRoute} from 'react-router';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
import promiseMiddleware from 'redux-promise';
import {createStore, applyMiddleware} from 'redux';
import * as ga from 'react-ga';
import mainReducer from "./reducers/mainReducer";
import App from "./components/App";
import Home from "./components/Home";
import Farm from "./components/Farm";
// google analytics
ga.initialize('UA-75597006-1');
const logPageView = () => {
ga.pageview(this.state.location.pathname);
};
// Redux store stuff
const store = createStore(mainReducer, applyMiddleware(
thunk, promiseMiddleware
));
class Routes extends React.Component {
render () {
return (
<Provider store={store}>
<Router history={browserHistory} onUpdate={logPageView}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path=":id" component={Farm} />
</Route>
</Router>
</Provider>
);
}
}
export default Routes;
| import React from "react";
import {Router, Route, Link, browserHistory, IndexRoute} from 'react-router';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
import promiseMiddleware from 'redux-promise';
import {createStore, applyMiddleware} from 'redux';
import * as ga from 'react-ga';
import mainReducer from "./reducers/mainReducer";
import App from "./components/App";
import Home from "./components/Home";
import Farm from "./components/Farm";
// google analytics
ga.initialize('UA-75597006-1');
function logPageView () { // eslint-disable-line
ga.pageview(this.state.location.pathname);
}
// Redux store stuff
const store = createStore(mainReducer, applyMiddleware(
thunk, promiseMiddleware
));
class Routes extends React.Component {
render () {
return (
<Provider store={store}>
<Router history={browserHistory} onUpdate={logPageView}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path=":id" component={Farm} />
</Route>
</Router>
</Provider>
);
}
}
export default Routes;
| Change to function declaration so this is bound by scope | Change to function declaration so this is bound by scope
| JavaScript | apache-2.0 | nictuku/stardew-rocks,nictuku/stardew-rocks,nictuku/stardew-rocks,nictuku/stardew-rocks | ---
+++
@@ -15,9 +15,9 @@
// google analytics
ga.initialize('UA-75597006-1');
-const logPageView = () => {
+function logPageView () { // eslint-disable-line
ga.pageview(this.state.location.pathname);
-};
+}
// Redux store stuff
const store = createStore(mainReducer, applyMiddleware( |
5b397f0f08ee2d2fdff3e17a19c69be55114ee64 | server/controllers/api.js | server/controllers/api.js | /**
* Get documentation URL
*/
exports.getDocUrl = function (req, res) {
res.sendBody('Documentation for this API can be found at http://github.com/thebinarypenguin/tasty');
};
/**
* Get all bookmarks
*/
exports.getAllBookmarks = function (req, res, params) {
res.send(501, {} {message: "I'm just a stub."});
};
/**
* Create new bookmark
*/
exports.createBookmark = function (req, res, body) {
res.send(501, {} {message: "I'm just a stub."});
};
/**
* Get specified bookmark
*/
exports.getBookmark = function (req, res, id, params) {
res.send(501, {} {message: "I'm just a stub."});
};
/**
* Update specified bookmark
*/
exports.updateBookmark = function (req, res, id, body) {
res.send(501, {} {message: "I'm just a stub."});
};
/**
* Delete specified bookmark
*/
exports.deleteBookmark = function (req, res, id) {
res.send(501, {} {message: "I'm just a stub."});
};
| /**
* Get documentation URL
*/
exports.getDocUrl = function (req, res) {
res.sendBody('Documentation for this API can be found at http://github.com/thebinarypenguin/tasty');
};
/**
* Get all bookmarks
*/
exports.getAllBookmarks = function (req, res, params) {
res.send(501, {}, {message: "I'm just a stub."});
};
/**
* Create new bookmark
*/
exports.createBookmark = function (req, res, body) {
res.send(501, {}, {message: "I'm just a stub."});
};
/**
* Get specified bookmark
*/
exports.getBookmark = function (req, res, id, params) {
res.send(501, {}, {message: "I'm just a stub."});
};
/**
* Update specified bookmark
*/
exports.updateBookmark = function (req, res, id, body) {
res.send(501, {}, {message: "I'm just a stub."});
};
/**
* Delete specified bookmark
*/
exports.deleteBookmark = function (req, res, id) {
res.send(501, {}, {message: "I'm just a stub."});
};
| Add missing commas in res.send() calls | Add missing commas in res.send() calls
| JavaScript | mit | thebinarypenguin/tasty,thebinarypenguin/tasty | ---
+++
@@ -10,7 +10,7 @@
* Get all bookmarks
*/
exports.getAllBookmarks = function (req, res, params) {
- res.send(501, {} {message: "I'm just a stub."});
+ res.send(501, {}, {message: "I'm just a stub."});
};
@@ -18,7 +18,7 @@
* Create new bookmark
*/
exports.createBookmark = function (req, res, body) {
- res.send(501, {} {message: "I'm just a stub."});
+ res.send(501, {}, {message: "I'm just a stub."});
};
@@ -26,7 +26,7 @@
* Get specified bookmark
*/
exports.getBookmark = function (req, res, id, params) {
- res.send(501, {} {message: "I'm just a stub."});
+ res.send(501, {}, {message: "I'm just a stub."});
};
@@ -34,7 +34,7 @@
* Update specified bookmark
*/
exports.updateBookmark = function (req, res, id, body) {
- res.send(501, {} {message: "I'm just a stub."});
+ res.send(501, {}, {message: "I'm just a stub."});
};
@@ -42,5 +42,5 @@
* Delete specified bookmark
*/
exports.deleteBookmark = function (req, res, id) {
- res.send(501, {} {message: "I'm just a stub."});
+ res.send(501, {}, {message: "I'm just a stub."});
}; |
2b7518baa2853b40720a5f300d6412520b0f839f | server/graphql/storage.js | server/graphql/storage.js | import {Option} from 'giftbox';
const lists = {
1: {
id: 1,
name: 'work items',
items: [
{ id: 11, title: 'learn graphql basics', completed: false },
{ id: 12, title: 'master more details of graphql', completed: false }
]
},
2: {
id: 2,
name: 'house items',
items: [
{ id: 21, title: 'pick up laundry', completed: false },
{ id: 22, title: 'wash the dishes', completed: true },
{ id: 23, title: 'go to gym', completed: false }
]
}
};
function signalError(msg) { throw new Error(msg) }
const storageOps = {
findList(id) {
return lists[id] ? lists[id] : signalError(`Could not find list ${id}`);
},
markItemAsCompleted(listId, itemId) {
return Option(lists[listId]).flatMap(list => Option(list.items.find(item => item.id === itemId)))
.map(item => {
item.completed = true;
return item;
})
.getOrElse(signalError(`Could not find todo item ${itemId} on list ${listId}`))
}
};
export default storageOps; | import {Option} from 'giftbox';
const lists = {
1: {
id: 1,
name: 'work items',
items: [
{ id: 11, title: 'learn graphql basics', completed: false },
{ id: 12, title: 'master more details of graphql', completed: false }
]
},
2: {
id: 2,
name: 'house items',
items: [
{ id: 21, title: 'pick up laundry', completed: false },
{ id: 22, title: 'wash the dishes', completed: true },
{ id: 23, title: 'go to gym', completed: false }
]
}
};
function signalError(msg) {
return () => { throw new Error(msg) }
}
const storageOps = {
findList(id) {
return lists[id] ? lists[id] : signalError(`Could not find list ${id}`);
},
markItemAsCompleted(listId, itemId) {
return Option(lists[listId]).flatMap(list => Option(list.items.find(item => item.id === itemId)))
.map(item => {
item.completed = true;
return item;
})
.getOrElse(signalError(`Could not find todo item ${itemId} on list ${listId}`))
}
};
export default storageOps; | Fix signalError, it needs to be function to be "lazily" evaluated and not throw Error immediately when called | Fix signalError, it needs to be function to be "lazily" evaluated and not throw Error immediately when called
| JavaScript | mit | mostr/graphql-todos | ---
+++
@@ -20,7 +20,9 @@
}
};
-function signalError(msg) { throw new Error(msg) }
+function signalError(msg) {
+ return () => { throw new Error(msg) }
+}
const storageOps = {
|
79044879bdba3fa70abee1d2303ef3703e36c83a | entry_types/scrolled/package/src/contentElements/inlineAudio/stories.js | entry_types/scrolled/package/src/contentElements/inlineAudio/stories.js | import '../frontend';
import {storiesOfContentElement, filePermaId} from 'pageflow-scrolled/spec/support/stories';
storiesOfContentElement(module, {
typeName: 'inlineAudio',
baseConfiguration: {
id: null,
autoplay: false,
controls: false
}
});
| import '../frontend';
import {storiesOfContentElement, filePermaId} from 'pageflow-scrolled/spec/support/stories';
storiesOfContentElement(module, {
typeName: 'inlineAudio',
baseConfiguration: {
id: filePermaId('audioFiles', 'quicktime_jingle'),
autoplay: false,
controls: false
}
});
| Use audio file in inlineAudio story | Use audio file in inlineAudio story
| JavaScript | mit | tf/pageflow,codevise/pageflow,codevise/pageflow,codevise/pageflow,codevise/pageflow,tf/pageflow,tf/pageflow,tf/pageflow | ---
+++
@@ -4,7 +4,7 @@
storiesOfContentElement(module, {
typeName: 'inlineAudio',
baseConfiguration: {
- id: null,
+ id: filePermaId('audioFiles', 'quicktime_jingle'),
autoplay: false,
controls: false
} |
9e80fec1f3d502e2273143de1d4659c28b2a0726 | test/brain-test.js | test/brain-test.js | 'use strict';
var _ = require('lodash');
var Brain = require('../lib/brain');
var Configuration = require('../lib/configuration.js');
var State = require('../lib/constants/state.js');
describe('Brain', function() {
var config = null;
var brain = null;
beforeEach(function () {
var commandLine = JSON.parse("{'_':[],'mockBTC':'1EyE2nE4hf8JVjV51Veznz9t9vTFv8uRU5','mockBv':'/dev/pts/7','mockTrader':true,'mockCam':true,'mockBillDispenser':true}");
config = Configuration.loadConfig(commandLine);
brain = new Brain(config);
});
it('can be configured with default values', function() {
expect(brain).toBeDefined();
});
it('starts off in the state \'start\'', function () {
expect(brain.state).toBe(State.START);
});
it('initializes its trader correctly', function () {
var expectedTraderEvents = [State.POLL_UPDATE, 'networkDown', 'networkUp', 'dispenseUpdate', 'error', 'unpair'];
brain._initTraderEvents();
_.each(expectedTraderEvents, function(el/*, idx, list*/) { var arr = brain.trader.listeners(el); expect(arr.length).toBe(1); });
});
});
| 'use strict';
var _ = require('lodash');
var Brain = require('../lib/brain');
var Configuration = require('../lib/configuration.js');
var State = require('../lib/constants/state.js');
describe('Brain', function() {
var config = null;
var brain = null;
beforeEach(function () {
var commandLine = JSON.parse('{"_":[],"mockBTC":"1EyE2nE4hf8JVjV51Veznz9t9vTFv8uRU5","mockBv":"/dev/pts/7","mockTrader":true,"mockCam":true,"mockBillDispenser":true}');
config = Configuration.loadConfig(commandLine);
brain = new Brain(config);
});
it('can be configured with default values', function() {
expect(brain).toBeDefined();
});
it('starts off in the state \'start\'', function () {
expect(brain.state).toBe(State.START);
});
it('initializes its trader correctly', function () {
var expectedTraderEvents = [State.POLL_UPDATE, 'networkDown', 'networkUp', 'dispenseUpdate', 'error', 'unpair'];
brain._initTraderEvents();
_.each(expectedTraderEvents, function(el/*, idx, list*/) { var arr = brain.trader.listeners(el); expect(arr.length).toBe(1); });
});
});
| Use single quotes for the JSON string, double quotes for the values within it | Use single quotes for the JSON string, double quotes for the values within it
| JavaScript | unlicense | lamassu/lamassu-machine,lamassu/lamassu-machine,joshmh/lamassu-machine,bitstopco/lamassu-machine-old,evan82/lamassu-machine,joshmh/lamassu-machine,evan82/lamassu-machine,bitstopco/lamassu-machine-old,evan82/lamassu-machine,lamassu/lamassu-machine,evan82/lamassu-machine,joshmh/lamassu-machine,lamassu/lamassu-machine,bitstopco/lamassu-machine-old,bitstopco/lamassu-machine-old | ---
+++
@@ -10,7 +10,7 @@
var brain = null;
beforeEach(function () {
- var commandLine = JSON.parse("{'_':[],'mockBTC':'1EyE2nE4hf8JVjV51Veznz9t9vTFv8uRU5','mockBv':'/dev/pts/7','mockTrader':true,'mockCam':true,'mockBillDispenser':true}");
+ var commandLine = JSON.parse('{"_":[],"mockBTC":"1EyE2nE4hf8JVjV51Veznz9t9vTFv8uRU5","mockBv":"/dev/pts/7","mockTrader":true,"mockCam":true,"mockBillDispenser":true}');
config = Configuration.loadConfig(commandLine);
brain = new Brain(config); |
ade6c1e4a0b1de5e95cf10e9f80c85c2fd1d2ad1 | renderer/lib/torrent-player.js | renderer/lib/torrent-player.js | module.exports = {
isPlayable,
isVideo,
isAudio,
isPlayableTorrent
}
var path = require('path')
/**
* Determines whether a file in a torrent is audio/video we can play
*/
function isPlayable (file) {
return isVideo(file) || isAudio(file)
}
function isVideo (file) {
var ext = path.extname(file.name).toLowerCase()
return ['.mp4', '.m4v', '.webm', '.mov', '.mkv'].indexOf(ext) !== -1
}
function isAudio (file) {
var ext = path.extname(file.name).toLowerCase()
return ['.mp3', '.aac', '.ogg', '.wav'].indexOf(ext) !== -1
}
function isPlayableTorrent (torrentSummary) {
return torrentSummary.files && torrentSummary.files.some(isPlayable)
}
| module.exports = {
isPlayable,
isVideo,
isAudio,
isPlayableTorrent
}
var path = require('path')
/**
* Determines whether a file in a torrent is audio/video we can play
*/
function isPlayable (file) {
return isVideo(file) || isAudio(file)
}
function isVideo (file) {
var ext = path.extname(file.name).toLowerCase()
return ['.mp4', '.m4v', '.webm', '.mov', '.mkv', '.avi'].indexOf(ext) !== -1
}
function isAudio (file) {
var ext = path.extname(file.name).toLowerCase()
return ['.mp3', '.aac', '.ogg', '.wav', '.ac3'].indexOf(ext) !== -1
}
function isPlayableTorrent (torrentSummary) {
return torrentSummary.files && torrentSummary.files.some(isPlayable)
}
| Add more media file extensions | Add more media file extensions
| JavaScript | mit | feross/webtorrent-desktop,michaelgeorgeattard/webtorrent-desktop,yciabaud/webtorrent-desktop,feross/webtorrent-app,webtorrent/webtorrent-desktop,michaelgeorgeattard/webtorrent-desktop,feross/webtorrent-app,webtorrent/webtorrent-desktop,yciabaud/webtorrent-desktop,feross/webtorrent-desktop,michaelgeorgeattard/webtorrent-desktop,webtorrent/webtorrent-desktop,feross/webtorrent-desktop,yciabaud/webtorrent-desktop,feross/webtorrent-app | ---
+++
@@ -16,12 +16,12 @@
function isVideo (file) {
var ext = path.extname(file.name).toLowerCase()
- return ['.mp4', '.m4v', '.webm', '.mov', '.mkv'].indexOf(ext) !== -1
+ return ['.mp4', '.m4v', '.webm', '.mov', '.mkv', '.avi'].indexOf(ext) !== -1
}
function isAudio (file) {
var ext = path.extname(file.name).toLowerCase()
- return ['.mp3', '.aac', '.ogg', '.wav'].indexOf(ext) !== -1
+ return ['.mp3', '.aac', '.ogg', '.wav', '.ac3'].indexOf(ext) !== -1
}
function isPlayableTorrent (torrentSummary) { |
8041b8df6f19bf18ba7087e88637ec487da1a2e3 | test/lib/mockid.js | test/lib/mockid.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const assert = require('assert');
const querystring = require('querystring');
var MockOAuth2Client = {
generateAuthUrl: function (options) {
return this.options.url + '?' + querystring.stringify(options);
},
getToken: function (code, callback) {
callback(null, 'token');
}
};
var MockUserInfo = {
get: function (params, callback) {
// make sure the credentials get set to the expected token
if (params.auth.credentials === 'token') {
callback(null, {
/*jshint camelcase: false*/
verified_email: this.options.result.authenticated,
email: this.options.result.email
});
}
}
};
module.exports = function mockid(options) {
return {
auth: {
OAuth2: function (clientId, clientSecret, redirectUri) {
assert.ok(clientId);
assert.ok(clientSecret);
assert.ok(redirectUri);
var client = Object.create(MockOAuth2Client);
client.options = options;
return client;
}
},
oauth2: function (version) {
assert.ok(version);
var userInfo = Object.create(MockUserInfo);
userInfo.options = options;
return {
userinfo: userInfo
};
}
};
};
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const assert = require('assert');
const querystring = require('querystring');
var MockOAuth2Client = {
generateAuthUrl: function (options) {
return this.options.url + '?' + querystring.stringify(options);
},
getToken: function (code, callback) {
callback(null, 'token');
},
setCredentials: function(credentials) {
this.credentials = credentials;
}
};
var MockUserInfo = {
get: function (params, callback) {
// make sure the credentials get set to the expected token
if (params.auth.credentials === 'token') {
callback(null, {
/*jshint camelcase: false*/
verified_email: this.options.result.authenticated,
email: this.options.result.email
});
}
}
};
module.exports = function mockid(options) {
return {
auth: {
OAuth2: function (clientId, clientSecret, redirectUri) {
assert.ok(clientId);
assert.ok(clientSecret);
assert.ok(redirectUri);
var client = Object.create(MockOAuth2Client);
client.options = options;
return client;
}
},
oauth2: function (version) {
assert.ok(version);
var userInfo = Object.create(MockUserInfo);
userInfo.options = options;
return {
userinfo: userInfo
};
}
};
};
| Implement setCredentials on the mock OAuth2 client | Implement setCredentials on the mock OAuth2 client
Fixes broken unit tests.
The implementation looks kind of ridiculous, but it's not terribly different
from what Google does themselves as of 1.1.3:
https://github.com/google/google-api-nodejs-client/blob/bd356c38efc5ac460f319e4d0b005425013720cb/lib/auth/authclient.js#L33-L39
| JavaScript | mpl-2.0 | mozilla/persona-gmail-bridge,mozilla/persona-gmail-bridge | ---
+++
@@ -12,6 +12,10 @@
getToken: function (code, callback) {
callback(null, 'token');
+ },
+
+ setCredentials: function(credentials) {
+ this.credentials = credentials;
}
};
|
c6fd27aada1305fbf54e46033fdecc70c2ee86bc | app/routes/home.js | app/routes/home.js | import Ember from 'ember';
export default Ember.Route.extend({
model () {
return this.get('store').findAll('expense');
// return this.get('store').findAll('expense')
// .then(response => response.filter(expense => {
// console.log('dfa');
// return moment(expense.get('timestamp')).isBetween('2016-11-05', '2016-11-29');
// }));
}
});
| import Ember from 'ember';
import moment from 'npm:moment';
export default Ember.Route.extend({
beforeModel () {
const currentDateId = moment().format('YYYY-MM');
if (this.store.peekRecord('expenses', currentDateId) === null) {
let expensesStore = this.store.createRecord('expenses', {
id: currentDateId
});
expensesStore.save();
}
},
model () {
return this.get('store').findAll('expense');
// return this.get('store').findAll('expense')
// .then(response => response.filter(expense => {
// console.log('dfa');
// return moment(expense.get('timestamp')).isBetween('2016-11-05', '2016-11-29');
// }));
}
});
| Create store for current month if doesnt exists | feat: Create store for current month if doesnt exists
| JavaScript | mit | pe1te3son/spendings-tracker,pe1te3son/spendings-tracker | ---
+++
@@ -1,6 +1,18 @@
import Ember from 'ember';
+import moment from 'npm:moment';
export default Ember.Route.extend({
+
+ beforeModel () {
+ const currentDateId = moment().format('YYYY-MM');
+
+ if (this.store.peekRecord('expenses', currentDateId) === null) {
+ let expensesStore = this.store.createRecord('expenses', {
+ id: currentDateId
+ });
+ expensesStore.save();
+ }
+ },
model () {
return this.get('store').findAll('expense'); |
48b12c46bc2dcd425c0f0dfcd33466d12136cccd | app/utils/index.js | app/utils/index.js | function download(filename, text, click = true) {
const element = document.createElement('a');
element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
if (click) {
element.click();
}
document.body.removeChild(element);
return document
}
module.exports = { download };
| function download(filename, text, click = true) {
const element = document.createElement('a');
element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`);
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
if (click) {
element.click();
}
document.body.removeChild(element);
return document;
}
module.exports = { download };
| Return documents to make it easier to test | Return documents to make it easier to test
| JavaScript | mit | mhoffman/CatAppBrowser,mhoffman/CatAppBrowser | ---
+++
@@ -8,7 +8,7 @@
element.click();
}
document.body.removeChild(element);
- return document
+ return document;
}
module.exports = { download }; |
5ae87d670f47e10c460a52bb0adc7846aa0ebb1a | js/scrollback.js | js/scrollback.js | (function(document) {
document.addEventListener("wheel", function(e) {
if (e.shiftKey) {
if (e.deltaX > 0) {
window.history.back();
return e.preventDefault();
} else if (e.deltaX < 0) {
window.history.forward();
return e.preventDefault();
}
}
});
})(document);
| document.addEventListener("wheel", function(e) {
if (e.shiftKey && e.deltaX != 0) {
window.history.go(-Math.sign(e.deltaX));
return e.preventDefault();
}
});
| Make the code even shorter | Make the code even shorter
| JavaScript | mit | jezcope/chrome-scroll-back | ---
+++
@@ -1,15 +1,6 @@
-(function(document) {
-
- document.addEventListener("wheel", function(e) {
- if (e.shiftKey) {
- if (e.deltaX > 0) {
- window.history.back();
- return e.preventDefault();
- } else if (e.deltaX < 0) {
- window.history.forward();
- return e.preventDefault();
- }
- }
- });
-
-})(document);
+document.addEventListener("wheel", function(e) {
+ if (e.shiftKey && e.deltaX != 0) {
+ window.history.go(-Math.sign(e.deltaX));
+ return e.preventDefault();
+ }
+}); |
a9bb6ba5ccaa1a240d8939674bf11a3e0f7aa482 | website/app/application/services/watcher-service.js | website/app/application/services/watcher-service.js | Application.Services.factory('watcher',
function () {
var watcherService = {};
watcherService.watch = function (scope, variable, fn) {
scope.$watch(variable, function (newval, oldval) {
if (!newval && !oldval) {
return;
}
else if (newval == "" && oldval) {
fn(oldval);
} else {
fn(newval);
}
});
};
return watcherService;
});
| Application.Services.factory('watcher',
function () {
var watcherService = {};
watcherService.watch = function (scope, variable, fn) {
scope.$watch(variable, function (newval, oldval) {
if (!newval && !oldval) {
return;
}
else if (newval === "" && oldval) {
fn(oldval);
} else {
fn(newval);
}
});
};
return watcherService;
});
| Fix equality statement to use === rather than ==. | Fix equality statement to use === rather than ==.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -7,7 +7,7 @@
if (!newval && !oldval) {
return;
}
- else if (newval == "" && oldval) {
+ else if (newval === "" && oldval) {
fn(oldval);
} else {
fn(newval); |
ffcca5e47eafa16d271847ad0dc412265c7e279f | angular-crypto-js.js | angular-crypto-js.js | /**
* Angular crypto-js
* https://github.com/janppires/angular-crypto-js.git
**/
(function(angular, CryptoJS){
'use strict';
angular
.module('angular-crypto-js', [])
.factory('cryptoJs', [cryptoJs]);
function cryptoJs(){
return {
md5Hex : md5Hex,
sha1Hex : sha1Hex,
sha256Hex: sha256Hex,
sha224Hex: sha224Hex,
sha512Hex: sha512Hex,
sha384Hex: sha384Hex,
sha3Hex: sha3Hex,
}
function md5Hex(message){
return toHex(CryptoJS.MD5, message);
}
function sha1Hex(message){
return toHex(CryptoJS.SHA1, message);
}
function sha256Hex(message){
return toHex(CryptoJS.SHA256, message);
}
function sha224Hex(message){
return toHex(CryptoJS.SHA224, message);
}
function sha512Hex(message){
return toHex(CryptoJS.SHA512, message);
}
function sha384Hex(message){
return toHex(CryptoJS.SHA384, message);
}
function sha3Hex(message){
return toHex(CryptoJS.SHA3, message);
}
function toHex(hasher, message){
return hasher(message).toString(CryptoJS.enc.Hex);
}
}
})(window.angular, window.CryptoJS);
| /**
* Angular crypto-js
* https://github.com/janppires/angular-crypto-js.git
**/
(function(angular, CryptoJS){
'use strict';
angular
.module('angular-crypto-js', [])
.factory('ngCrypto', [ngCrypto]);
function ngCrypto(){
return {
md5Hex : md5Hex,
sha1Hex : sha1Hex,
sha256Hex: sha256Hex,
sha224Hex: sha224Hex,
sha512Hex: sha512Hex,
sha384Hex: sha384Hex,
sha3Hex: sha3Hex,
}
function md5Hex(message){
return toHex(CryptoJS.MD5, message);
}
function sha1Hex(message){
return toHex(CryptoJS.SHA1, message);
}
function sha256Hex(message){
return toHex(CryptoJS.SHA256, message);
}
function sha224Hex(message){
return toHex(CryptoJS.SHA224, message);
}
function sha512Hex(message){
return toHex(CryptoJS.SHA512, message);
}
function sha384Hex(message){
return toHex(CryptoJS.SHA384, message);
}
function sha3Hex(message){
return toHex(CryptoJS.SHA3, message);
}
function toHex(hasher, message){
return hasher(message).toString(CryptoJS.enc.Hex);
}
}
})(window.angular, window.CryptoJS);
| Update factory name to ngCrypto | Update factory name to ngCrypto | JavaScript | mit | janppires/angular-crypto-js | ---
+++
@@ -7,9 +7,9 @@
angular
.module('angular-crypto-js', [])
- .factory('cryptoJs', [cryptoJs]);
+ .factory('ngCrypto', [ngCrypto]);
- function cryptoJs(){
+ function ngCrypto(){
return {
md5Hex : md5Hex,
sha1Hex : sha1Hex, |
20cadcb89995c43ff04d67d643ae896ab2380fd2 | js/background/markdown.js | js/background/markdown.js |
var md = (function () {
// marked
var defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
// sanitizer: null,
// mangle: true, // mangling of email addresses
smartLists: false,
// silent: false, // report errors
// highlight: null,
langPrefix: 'language-', // prism
smartypants: false
// headerPrefix: '',
// renderer:
// xhtml: false // handle self closing HTML tags
}
function compile (markdown, sendResponse) {
chrome.storage.sync.get(function (sync) {
marked.setOptions(sync.options)
marked(markdown, function (err, html) {
if (err) throw err
// prism fix
html = html.replace(/language-html/g, 'language-markup')
html = html.replace(/language-js/g, 'language-javascript')
sendResponse({message: 'marked', marked: html})
})
})
}
return {
defaults: defaults,
compile: compile
}
}())
|
var md = (function () {
// marked
var defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
// sanitizer: null,
// mangle: true, // mangling of email addresses
smartLists: false,
// silent: false, // report errors
// highlight: null,
langPrefix: 'language-', // prism
smartypants: false
// headerPrefix: '',
// renderer:
// xhtml: false // handle self closing HTML tags
}
function compile (markdown, sendResponse) {
chrome.storage.sync.get(function (sync) {
marked.setOptions(sync.options)
marked(markdown, function (err, html) {
if (err) throw err
sendResponse({message: 'marked', marked: html})
})
})
}
return {
defaults: defaults,
compile: compile
}
}())
| Remove prism fix for html and js code blocks | Remove prism fix for html and js code blocks
| JavaScript | mit | simov/markdown-viewer,simov/markdown-viewer,simov/markdown-viewer | ---
+++
@@ -25,10 +25,6 @@
marked(markdown, function (err, html) {
if (err) throw err
- // prism fix
- html = html.replace(/language-html/g, 'language-markup')
- html = html.replace(/language-js/g, 'language-javascript')
-
sendResponse({message: 'marked', marked: html})
})
}) |
23d0b9e021d3635bbc3465c4adb27c45fa5b110c | js/buttons/ButtonModel.js | js/buttons/ButtonModel.js | // Copyright 2002-2014, University of Colorado Boulder
/**
* Base class for button models, which describe the behavior of buttons when users interact with them. Property values
* are set by an associated listener, see ButtonListener for details.
*/
define( function( require ) {
'use strict';
// Imports
var inherit = require( 'PHET_CORE/inherit' );
var PropertySet = require( 'AXON/PropertySet' );
function ButtonModel() {
PropertySet.call( this, {
// Property that tracks whether or not a pointer that could interact with the button is currently over the button.
over: false,
// Property that tracks whether a pointer is currently down on, a.k.a. pressing, the button.
down: false,
// Property that tracks whether or not the button is enabled.
enabled: true
}, 'buttonModel' );
// Disable some of the data collection messages to cut down on noise.
this.overProperty.setSendPhetEvents( false );
}
return inherit( PropertySet, ButtonModel );
} ); | // Copyright 2002-2014, University of Colorado Boulder
/**
* Base class for button models, which describe the behavior of buttons when users interact with them. Property values
* are set by an associated listener, see ButtonListener for details.
*/
define( function( require ) {
'use strict';
// Imports
var inherit = require( 'PHET_CORE/inherit' );
var PropertySet = require( 'AXON/PropertySet' );
function ButtonModel() {
PropertySet.call( this, {
// Property that tracks whether or not a pointer that could interact with the button is currently over the button.
over: false,
// Property that tracks whether a pointer is currently down on, a.k.a. pressing, the button.
down: false,
// Property that tracks whether or not the button is enabled.
enabled: true
}, 'buttonModel' );
}
return inherit( PropertySet, ButtonModel );
} ); | Send all arch events for now | Send all arch events for now
| JavaScript | mit | phetsims/sun,phetsims/sun,phetsims/sun | ---
+++
@@ -24,9 +24,6 @@
// Property that tracks whether or not the button is enabled.
enabled: true
}, 'buttonModel' );
-
- // Disable some of the data collection messages to cut down on noise.
- this.overProperty.setSendPhetEvents( false );
}
return inherit( PropertySet, ButtonModel ); |
d75b2eb07a271a6ffe1854f15fcc4838c80b8e12 | lib/assert-full-equal/report.js | lib/assert-full-equal/report.js | 'use strict';
var nodeUtils = require('util');
var REASONS = {
'values' : 'Given objects are not equal',
'types' : 'Given objects are of different types',
'prototypes' : 'Given objects has different prototypes',
'object_property_amounts' : 'Given objects has different key amounts',
'object_property_names' : 'Given objects has different key sets',
'date_timestamps' : 'Given Date objects has different timestamps',
};
function Report(context, actual, expected, reason) {
this.context = context;
this.actual = actual;
this.expected = expected;
this.reason = reason;
if (!REASONS.hasOwnProperty(this.reason)) {
throw Error('Unknown reason for the report: ' + JSON.stringify(this.reason));
}
}
Report.prototype.toString = function toString() {
var result = '',
index,
path = this.context.path,
length = path.length;
result += REASONS[this.reason];
if (length > 0) {
result += ' at ';
for (index = 0; index < length; index += 1) {
result += '[' + JSON.stringify(path[index]) + ']';
}
}
result +=
' (actual: ' + nodeUtils.inspect(this.actual) +
', expected: ' + nodeUtils.inspect(this.expected) + ')';
return result;
}
module.exports = Report;
| 'use strict';
var nodeUtils = require('util');
var REASONS = {
'values' : 'Given objects are not equal',
'types' : 'Given objects are of different types',
'prototypes' : 'Given objects has different prototypes',
'object_property_amounts' : 'Given objects has different key amounts',
'object_property_names' : 'Given objects has different key sets',
'date_timestamps' : 'Given Date objects has different timestamps',
};
function Report(context, actual, expected, reason) {
this.context = context;
this.actual = actual;
this.expected = expected;
this.reason = reason;
if (!REASONS.hasOwnProperty(this.reason)) {
throw Error('Unknown reason for the report: ' +
nodeUtils.inspect(this.reason));
}
}
Report.prototype.toString = function toString() {
var result = '',
index,
path = this.context.path,
length = path.length;
result += REASONS[this.reason];
if (length > 0) {
result += ' at ';
for (index = 0; index < length; index += 1) {
result += '[' + JSON.stringify(path[index]) + ']';
}
}
result +=
' (actual: ' + nodeUtils.inspect(this.actual) +
', expected: ' + nodeUtils.inspect(this.expected) + ')';
return result;
}
module.exports = Report;
| Use Node's `inspect` for error message formation | Use Node's `inspect` for error message formation
| JavaScript | mit | dervus/assert-paranoid-equal | ---
+++
@@ -21,7 +21,8 @@
this.reason = reason;
if (!REASONS.hasOwnProperty(this.reason)) {
- throw Error('Unknown reason for the report: ' + JSON.stringify(this.reason));
+ throw Error('Unknown reason for the report: ' +
+ nodeUtils.inspect(this.reason));
}
}
|
6a2ed6e510932edce48dddb2ff35462fb9a677bd | src/autocomplete/autocomplete.js | src/autocomplete/autocomplete.js | import {bindable, customAttribute} from 'aurelia-templating';
import {inject} from 'aurelia-dependency-injection';
import {fireEvent} from '../common/events';
@customAttribute('md-autocomplete')
@inject(Element)
export class MdAutoComplete {
input = null;
@bindable() values = {};
constructor(element) {
this.element = element;
}
attached() {
if (this.element.tagName.toLowerCase() === 'input') {
this.input = this.element;
} else if (this.element.tagName.toLowerCase() === 'md-input') {
this.input = this.element.au.controller.viewModel.input;
} else {
throw new Error('md-autocomplete must be attached to either an input or md-input element');
}
this.refresh();
}
detached() {
// remove .autocomplete-content children
$(this.input).siblings('.autocomplete-content').off('click');
$(this.input).siblings('.autocomplete-content').remove();
}
refresh() {
this.detached();
$(this.input).autocomplete({
data: this.values
});
// $('.autocomplete-content', this.element).on('click', () => {
// fireEvent(this.input, 'change');
// });
$(this.input).siblings('.autocomplete-content').on('click', () => {
fireEvent(this.input, 'change');
});
}
valuesChanged(newValue) {
this.refresh();
}
}
| import {bindable, customAttribute} from 'aurelia-templating';
import {inject} from 'aurelia-dependency-injection';
import {fireEvent} from '../common/events';
@customAttribute('md-autocomplete')
@inject(Element)
export class MdAutoComplete {
input = null;
@bindable() values = {};
@bindable() minLength = 1;
@bindable() limit = 20;
constructor(element) {
this.element = element;
}
attached() {
if (this.element.tagName.toLowerCase() === 'input') {
this.input = this.element;
} else if (this.element.tagName.toLowerCase() === 'md-input') {
this.input = this.element.au.controller.viewModel.input;
} else {
throw new Error('md-autocomplete must be attached to either an input or md-input element');
}
this.refresh();
}
detached() {
// remove .autocomplete-content children
$(this.input).siblings('.autocomplete-content').off('click');
$(this.input).siblings('.autocomplete-content').remove();
}
refresh() {
this.detached();
$(this.input).autocomplete({
data: this.values,
minLength: this.minLength,
limit: this.limit
});
// $('.autocomplete-content', this.element).on('click', () => {
// fireEvent(this.input, 'change');
// });
$(this.input).siblings('.autocomplete-content').on('click', () => {
fireEvent(this.input, 'change');
});
}
valuesChanged(newValue) {
this.refresh();
}
}
| Add support for minLength and limit in AutoComplete | Add support for minLength and limit in AutoComplete | JavaScript | mit | aurelia-ui-toolkits/aurelia-materialize-bridge,aurelia-ui-toolkits/aurelia-materialize-bridge,aurelia-ui-toolkits/aurelia-materialize-bridge | ---
+++
@@ -7,6 +7,8 @@
export class MdAutoComplete {
input = null;
@bindable() values = {};
+ @bindable() minLength = 1;
+ @bindable() limit = 20;
constructor(element) {
this.element = element;
@@ -32,7 +34,9 @@
refresh() {
this.detached();
$(this.input).autocomplete({
- data: this.values
+ data: this.values,
+ minLength: this.minLength,
+ limit: this.limit
});
// $('.autocomplete-content', this.element).on('click', () => {
// fireEvent(this.input, 'change'); |
904d671d035dbc294a1e4415191cb75492a37040 | lib/validator.js | lib/validator.js | const RateLimiter = require("rolling-rate-limiter");
const config = require('../config');
const validKeys = ['key1','key2', 'key3', 'key4', 'key5']; //TODO replace API keys in request with JWT-token?
const limiter = RateLimiter({
interval: 60*60*1000, //1 hour in miliseconds
maxInInterval: config.max_requests_per_hour
});
const validator = {
validateKey: function(req, res, next){
if(validKeys.indexOf(req.query.key)===-1){
res.status(401);
res.json({"status":"401", "message":"invalid credentials"});
return;
}
next();
},
validateRate: function(req, res, next){
const timeLeft = limiter(req.query.key);
if (timeLeft > 0) {
// limit was exceeded, action should not be allowed
// timeLeft is the number of ms until the next action will be allowed
res.status(429);
res.json({"status":"429", "message":"Request limit excceded- try after "+(timeLeft/1000)+"s"});
} else {
next();
// limit was not exceeded, action should be allowed
}
}
};
module.exports = validator; | const RateLimiter = require("rolling-rate-limiter");
const prettyMs = require('pretty-ms');
const config = require('../config');
const validKeys = ['key1','key2', 'key3', 'key4', 'key5']; //TODO replace API keys in request with JWT-token?
const limiter = RateLimiter({
interval: 60*60*1000, //1 hour in miliseconds
maxInInterval: config.max_requests_per_hour
});
const validator = {
validateKey: function(req, res, next){
if(validKeys.indexOf(req.query.key)===-1){
res.status(401);
res.json({"status":"401", "message":"invalid credentials"});
return;
}
next();
},
validateRate: function(req, res, next){
const timeLeft = limiter(req.query.key);
if (timeLeft > 0) {
// limit was exceeded, action should not be allowed
// timeLeft is the number of ms until the next action will be allowed
res.status(429);
res.json({"status":"429", "message":"Request limit excceded- try after "+prettyMs(timeLeft)});
} else {
next();
// limit was not exceeded, action should be allowed
}
}
};
module.exports = validator; | Add pretty-ms to display a friendlier error message on timeout | Add pretty-ms to display a friendlier error message on timeout
| JavaScript | mit | umasudhan/weather | ---
+++
@@ -1,5 +1,5 @@
const RateLimiter = require("rolling-rate-limiter");
-
+const prettyMs = require('pretty-ms');
const config = require('../config');
const validKeys = ['key1','key2', 'key3', 'key4', 'key5']; //TODO replace API keys in request with JWT-token?
@@ -22,7 +22,7 @@
// limit was exceeded, action should not be allowed
// timeLeft is the number of ms until the next action will be allowed
res.status(429);
- res.json({"status":"429", "message":"Request limit excceded- try after "+(timeLeft/1000)+"s"});
+ res.json({"status":"429", "message":"Request limit excceded- try after "+prettyMs(timeLeft)});
} else {
next();
// limit was not exceeded, action should be allowed |
8fd4eac5073272ca3f71cb469f402140162035b9 | chrome/common/extensions/docs/examples/apps/calculator/app/background.js | chrome/common/extensions/docs/examples/apps/calculator/app/background.js | /**
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
**/
/**
* Listens for the app launching then creates the window.
*
* @see http://developer.chrome.com/trunk/apps/app.window.html
*/
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('calculator.html', {
width: 243, minWidth: 243, maxWidth: 243,
height: 380, minHeight: 380, maxHeight: 380,
}, function (appWindow) {
var window = appWindow.contentWindow;
window.onload = function (window) {
new View(window, new Model(8));
}.bind(this, window);
});
});
| /**
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
**/
/**
* Listens for the app launching then creates the window.
*
* @see http://developer.chrome.com/trunk/apps/app.window.html
*/
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('calculator.html', {
defaultWidth: 243, minWidth: 243, maxWidth: 243,
defaultHeight: 380, minHeight: 380, maxHeight: 380,
id: 'calculator'
}, function (appWindow) {
var window = appWindow.contentWindow;
window.onload = function (window) {
new View(window, new Model(8));
}.bind(this, window);
});
});
| Make the Calculator app window remember its position. | Make the Calculator app window remember its position.
BUG=153630
Review URL: https://chromiumcodereview.appspot.com/11092091
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@162036 0039d316-1c4b-4281-b951-d872f2087c98
| JavaScript | bsd-3-clause | Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,anirudhSK/chromium,anirudhSK/chromium,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,markYoungH/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,ondra-novak/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,littlstar/chromium.src,littlstar/chromium.src,ltilve/chromium,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,jaruba/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,dednal/chromium.src,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,dednal/chromium.src,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,ondra-novak/chromium.src,patrickm/chromium.src,littlstar/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,anirudhSK/chromium,Chilledheart/chromium,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,Fireblend/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,dednal/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,timopulkkinen/BubbleFish,Just-D/chromium-1,ChromiumWebApps/chromium,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,Chilledheart/chromium,axinging/chromium-crosswalk,ltilve/chromium,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,M4sse/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,ChromiumWebApps/chromium,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,ltilve/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,ondra-novak/chromium.src,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,dushu1203/chromium.src,ltilve/chromium,patrickm/chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,patrickm/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,patrickm/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,ltilve/chromium,dednal/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,hujiajie/pa-chromium,ondra-novak/chromium.src,dushu1203/chromium.src,hujiajie/pa-chromium,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,timopulkkinen/BubbleFish,Chilledheart/chromium | ---
+++
@@ -11,8 +11,9 @@
*/
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('calculator.html', {
- width: 243, minWidth: 243, maxWidth: 243,
- height: 380, minHeight: 380, maxHeight: 380,
+ defaultWidth: 243, minWidth: 243, maxWidth: 243,
+ defaultHeight: 380, minHeight: 380, maxHeight: 380,
+ id: 'calculator'
}, function (appWindow) {
var window = appWindow.contentWindow;
window.onload = function (window) { |
e12cf258825375468cb191982b6a8cc445135e16 | app/server/server.js | app/server/server.js | #!/usr/bin/env node
var debug = require('debug')('passport-mongo');
var app = require('./app');
app.set('port', 27017);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
}); | #!/usr/bin/env node
// var debug = require('debug')('passport-mongo');
var app = require('./app');
// app.set('port', 27017);
// var server = app.listen(app.get('port'), function() {
// debug('Express server listening on port ' + server.address().port);
// });
app.listen(process.env.PORT || 3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
}); | Change port settings for heroku | Change port settings for heroku
| JavaScript | mit | KevinElberger/MtgCardApp,KevinElberger/MtgCardApp | ---
+++
@@ -1,10 +1,14 @@
#!/usr/bin/env node
-var debug = require('debug')('passport-mongo');
+// var debug = require('debug')('passport-mongo');
var app = require('./app');
-app.set('port', 27017);
+// app.set('port', 27017);
-var server = app.listen(app.get('port'), function() {
- debug('Express server listening on port ' + server.address().port);
+// var server = app.listen(app.get('port'), function() {
+// debug('Express server listening on port ' + server.address().port);
+// });
+
+app.listen(process.env.PORT || 3000, function(){
+ console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
}); |
1c206d0d367cbb4b6aa2e350ce944397bd48b988 | client/lib/i18n.js | client/lib/i18n.js | // We save the user language preference in the user profile, and use that to set
// the language reactively. If the user is not connected we use the language
// information provided by the browser, and default to english.
Tracker.autorun(() => {
const currentUser = Meteor.user();
let language;
if (currentUser) {
language = currentUser.profile && currentUser.profile.language;
} else {
language = navigator.language || navigator.userLanguage;
}
if (language) {
TAPi18n.setLanguage(language);
// XXX
const shortLanguage = language.split('-')[0];
T9n.setLanguage(shortLanguage);
}
});
| // We save the user language preference in the user profile, and use that to set
// the language reactively. If the user is not connected we use the language
// information provided by the browser, and default to english.
Tracker.autorun(() => {
const currentUser = Meteor.user();
let language;
if (currentUser) {
language = currentUser.profile && currentUser.profile.language;
} else {
language = navigator.language || navigator.userLanguage;
}
if (language) {
TAPi18n.setLanguage(language);
// For languages such as Finnish (Suomi) that are not supported by meteor-accounts-t9n,
// the following may throw an exception. On the initial run of this `autorun()` callback,
// such an exception could cause the entire app to fail to load. Therefore, we catch
// the exception and log it as an error.
try {
T9n.setLanguage(language);
} catch (e) {
console.error(e);
}
}
});
| Fix startup for clients using Finnish and Chinese. | Fix startup for clients using Finnish and Chinese.
| JavaScript | mit | wekan/wekan,mario-orlicky/wekan,wekan/wekan,oliver4u/sap-wekan,mario-orlicky/wekan,libreboard/libreboard,johnleeming/wekan,ddanssaert/wekan,johnleeming/wekan,Serubin/wekan,libreboard/libreboard,GhassenRjab/wekan,nztqa/wekan,wekan/wekan,jtickle/wekan,nztqa/wekan,nztqa/wekan,jtickle/wekan,Serubin/wekan,wekan/wekan,wekan/wekan,Serubin/wekan,oliver4u/sap-wekan,GhassenRjab/wekan,GhassenRjab/wekan,johnleeming/wekan,oliver4u/WEKAN_runpartner,oliver4u/sap-wekan,ddanssaert/wekan,mario-orlicky/wekan,jtickle/wekan,oliver4u/WEKAN_runpartner,oliver4u/WEKAN_runpartner,ddanssaert/wekan,johnleeming/wekan | ---
+++
@@ -14,8 +14,14 @@
if (language) {
TAPi18n.setLanguage(language);
- // XXX
- const shortLanguage = language.split('-')[0];
- T9n.setLanguage(shortLanguage);
+ // For languages such as Finnish (Suomi) that are not supported by meteor-accounts-t9n,
+ // the following may throw an exception. On the initial run of this `autorun()` callback,
+ // such an exception could cause the entire app to fail to load. Therefore, we catch
+ // the exception and log it as an error.
+ try {
+ T9n.setLanguage(language);
+ } catch (e) {
+ console.error(e);
+ }
}
}); |
4a23530a861c0a733521a9c3a5cc8f165de97fee | src/proj/epsg32631projection.js | src/proj/epsg32631projection.js | goog.provide('ngeo.proj.EPSG32631');
goog.require('ol.proj');
if (typeof proj4 == 'function') {
const epsg32631def = [
'+proj=utm',
'+zone=31',
'+ellps=WGS84',
'+datum=WGS84',
'+units=m',
'+no_defs'
].join(' ');
const epsg32631extent = [166021.44, 0.00, 534994.66, 9329005.18];
proj4.defs('epsg:32631', epsg32631def);
proj4.defs('EPSG:32631', epsg32631def);
ol.proj.get('epsg:32631').setExtent(epsg32631extent);
ol.proj.get('EPSG:32631').setExtent(epsg32631extent);
}
ngeo.proj.EPSG32631 = 'EPSG:32631';
| goog.provide('ngeo.proj.EPSG32631');
goog.require('ol.proj');
if (typeof proj4 == 'function') {
const epsg32631def = [
'+proj=utm',
'+zone=31',
'+ellps=WGS84',
'+datum=WGS84',
'+units=m',
'+no_defs'
].join(' ');
const epsg32631extent = [166021.44, 0.00, 534994.66, 9329005.18];
proj4.defs('EPSG:32631', epsg32631def);
ol.proj.get('EPSG:32631').setExtent(epsg32631extent);
}
ngeo.proj.EPSG32631 = 'EPSG:32631';
| Stop registering a lowercase epsg32631 projection | Stop registering a lowercase epsg32631 projection
We said it is now only uppercase.
| JavaScript | mit | adube/ngeo,Jenselme/ngeo,adube/ngeo,camptocamp/ngeo,adube/ngeo,camptocamp/ngeo,adube/ngeo,camptocamp/ngeo,camptocamp/ngeo,camptocamp/ngeo,Jenselme/ngeo,Jenselme/ngeo,Jenselme/ngeo | ---
+++
@@ -13,9 +13,7 @@
].join(' ');
const epsg32631extent = [166021.44, 0.00, 534994.66, 9329005.18];
- proj4.defs('epsg:32631', epsg32631def);
proj4.defs('EPSG:32631', epsg32631def);
- ol.proj.get('epsg:32631').setExtent(epsg32631extent);
ol.proj.get('EPSG:32631').setExtent(epsg32631extent);
}
|
67c61692571c9ab236fb44df3b5916a5b77a0b02 | modules/index.js | modules/index.js | export {
withHistory,
Route,
Switch,
Router
} from './Core'
// Accessories
export Link from './Link'
export Redirect from './Redirect'
export Prompt from './Prompt'
// High-level wrappers
export BrowserRouter from './BrowserRouter'
export HashRouter from './HashRouter'
export MemoryRouter from './MemoryRouter'
export ServerRouter from './ServerRouter'
| export {
matchPath,
withHistory,
Route,
Switch,
Router
} from './Core'
// Accessories
export Link from './Link'
export Redirect from './Redirect'
export Prompt from './Prompt'
// High-level wrappers
export BrowserRouter from './BrowserRouter'
export HashRouter from './HashRouter'
export MemoryRouter from './MemoryRouter'
export ServerRouter from './ServerRouter'
| Add matchPath to top-level exports | Add matchPath to top-level exports
| JavaScript | mit | asaf/react-router,OpenGov/react-router,ReactTraining/react-router,rackt/react-router,OpenGov/react-router,rafrex/react-router,rafrex/react-router,reactjs/react-router,d-oliveros/react-router,rackt/react-router,d-oliveros/react-router,reactjs/react-router,OpenGov/react-router,goblortikus/react-router,goblortikus/react-router,OpenGov/react-router,DelvarWorld/react-router,DelvarWorld/react-router,asaf/react-router,asaf/react-router,goblortikus/react-router,ReactTraining/react-router,ReactTraining/react-router,goblortikus/react-router,ReactTraining/react-router | ---
+++
@@ -1,4 +1,5 @@
export {
+ matchPath,
withHistory,
Route,
Switch, |
8488da0e96cf30bf7f064a13292b2e0a5d03c5b8 | js/VerticalCheckBoxGroup.js | js/VerticalCheckBoxGroup.js | //Render a simple vertical check box group, where the buttons all have the same sizes
//TODO: not ready for use in simulations, it will need further development & discussion first.
define( function( require ) {
"use strict";
var Path = require( 'SCENERY/nodes/Path' );
var CheckBox = require( 'SUN/CheckBox' );
var VBox = require( 'SCENERY/nodes/VBox' );
var Shape = require( 'KITE/Shape' );
var inherit = require( 'PHET_CORE/inherit' );
function VerticalCheckBoxGroup( items, options ) {
options = options || {};
var width = 0;
for ( var i = 0; i < items.length; i++ ) {
width = Math.max( width, items[i].content.width );
}
var children = [];
for ( i = 0; i < items.length; i++ ) {
//Add an invisible strut to each content to make the widths match
var content = new Path( {shape: Shape.rect( 0, 0, width, 0 ), children: [items[i].content]} );
children.push( new CheckBox( content, items[i].property ) );
}
options.children = children;
VBox.call( this, options );
}
inherit( VerticalCheckBoxGroup, VBox );
return VerticalCheckBoxGroup;
} ); | //Render a simple vertical check box group, where the buttons all have the same sizes
//TODO: not ready for use in simulations, it will need further development & discussion first.
define( function( require ) {
"use strict";
var Path = require( 'SCENERY/nodes/Path' );
var CheckBox = require( 'SUN/CheckBox' );
var VBox = require( 'SCENERY/nodes/VBox' );
var Shape = require( 'KITE/Shape' );
var inherit = require( 'PHET_CORE/inherit' );
/**
* Main constructor.
*
* @param items an array of {content, property}
* @param options
* @constructor
*/
function VerticalCheckBoxGroup( items, options ) {
options = options || {};
var width = 0;
for ( var i = 0; i < items.length; i++ ) {
width = Math.max( width, items[i].content.width );
}
var children = [];
for ( i = 0; i < items.length; i++ ) {
//Add an invisible strut to each content to make the widths match
var content = new Path( {shape: Shape.rect( 0, 0, width, 0 ), children: [items[i].content]} );
children.push( new CheckBox( content, items[i].property ) );
}
options.children = children;
VBox.call( this, options );
}
inherit( VerticalCheckBoxGroup, VBox );
return VerticalCheckBoxGroup;
} ); | Use vertical check box group in Tug of War tab | Use vertical check box group in Tug of War tab
| JavaScript | mit | phetsims/sun,phetsims/sun,phetsims/sun | ---
+++
@@ -9,6 +9,13 @@
var Shape = require( 'KITE/Shape' );
var inherit = require( 'PHET_CORE/inherit' );
+ /**
+ * Main constructor.
+ *
+ * @param items an array of {content, property}
+ * @param options
+ * @constructor
+ */
function VerticalCheckBoxGroup( items, options ) {
options = options || {};
|
58b783b877d56b29bd7c2075625374ee76d7720f | source/views/settings/index.js | source/views/settings/index.js | // @flow
import * as React from 'react'
import {StyleSheet, ScrollView} from 'react-native'
import {TableView} from 'react-native-tableview-simple'
import type {TopLevelViewPropsType} from '../types'
import CredentialsLoginSection from './sections/login-credentials'
import OddsAndEndsSection from './sections/odds-and-ends'
import SupportSection from './sections/support'
const styles = StyleSheet.create({
container: {
paddingVertical: 20,
},
})
export default function SettingsView(props: TopLevelViewPropsType) {
return (
<ScrollView
contentContainerStyle={styles.container}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="always"
>
<TableView>
<CredentialsLoginSection />
<SupportSection navigation={props.navigation} />
<OddsAndEndsSection navigation={props.navigation} />
</TableView>
</ScrollView>
)
}
SettingsView.navigationOptions = {
title: 'Settings',
}
| // @flow
import * as React from 'react'
import {StyleSheet, ScrollView} from 'react-native'
import {TableView} from 'react-native-tableview-simple'
import {connect} from 'react-redux'
import {type ReduxState} from '../../flux'
import type {TopLevelViewPropsType} from '../types'
import CredentialsLoginSection from './sections/login-credentials'
import OddsAndEndsSection from './sections/odds-and-ends'
import SupportSection from './sections/support'
type ReduxStateProps = {
loadEasterEggStatus: boolean,
}
const styles = StyleSheet.create({
container: {
paddingVertical: 20,
},
})
function SettingsView(props: TopLevelViewPropsType) {
return (
<ScrollView
contentContainerStyle={styles.container}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="always"
>
<TableView>
{props.loadEasterEggStatus ? <CredentialsLoginSection /> : null}
<SupportSection navigation={props.navigation} />
<OddsAndEndsSection navigation={props.navigation} />
</TableView>
</ScrollView>
)
}
SettingsView.navigationOptions = {
title: 'Settings',
}
function mapStateToProps(state) {
return {
loadEasterEggStatus: state.settings.easterEggEnabled
? state.settings.easterEggEnabled
: false,
}
}
export default connect(mapStateToProps)(SettingsView)
| Hide settigns login if oscar hasn't been tapped | Hide settigns login if oscar hasn't been tapped
| JavaScript | mit | carls-app/carls,carls-app/carls,carls-app/carls,carls-app/carls,carls-app/carls,carls-app/carls,carls-app/carls | ---
+++
@@ -3,11 +3,17 @@
import * as React from 'react'
import {StyleSheet, ScrollView} from 'react-native'
import {TableView} from 'react-native-tableview-simple'
+import {connect} from 'react-redux'
+import {type ReduxState} from '../../flux'
import type {TopLevelViewPropsType} from '../types'
import CredentialsLoginSection from './sections/login-credentials'
import OddsAndEndsSection from './sections/odds-and-ends'
import SupportSection from './sections/support'
+
+type ReduxStateProps = {
+ loadEasterEggStatus: boolean,
+}
const styles = StyleSheet.create({
container: {
@@ -15,7 +21,7 @@
},
})
-export default function SettingsView(props: TopLevelViewPropsType) {
+function SettingsView(props: TopLevelViewPropsType) {
return (
<ScrollView
contentContainerStyle={styles.container}
@@ -23,7 +29,7 @@
keyboardShouldPersistTaps="always"
>
<TableView>
- <CredentialsLoginSection />
+ {props.loadEasterEggStatus ? <CredentialsLoginSection /> : null}
<SupportSection navigation={props.navigation} />
@@ -35,3 +41,12 @@
SettingsView.navigationOptions = {
title: 'Settings',
}
+
+function mapStateToProps(state) {
+ return {
+ loadEasterEggStatus: state.settings.easterEggEnabled
+ ? state.settings.easterEggEnabled
+ : false,
+ }
+}
+export default connect(mapStateToProps)(SettingsView) |
5401f4f4c8ae6ca81cabc84a5fbd247e4b1f82ae | 2017/07.js | 2017/07.js | // Part 1
I=document.body.innerText.split`\n`,I.map(x=>x.split` `[0]).find(w=>!I.some(e=>[...e.split`>`,''][1].includes(w)))
| // Part 1
I=document.body.innerText.split`\n`,I.map(x=>x.split` `[0]).find(w=>!I.some(e=>[...e.split`>`,''][1].includes(w)))
// Part 2
P={},document.body.innerText.split`\n`.map(l=>l&&(i=l.indexOf('>'),P[l.split` `[0]]=[+l.match(/\d+/)[0],i>0?l.slice(i+2).split`, `:[]])),v=w=>P[w][1].reduce((s,x)=>s+v(x),P[w][0]),f=w=>P[w][1].find((x,_,c)=>!c.some(y=>x!=y&v(x)==v(y))),F=Object.keys(P).map(f),x=F.find(w=>w&&!f(w)),P[x][0]+v(P[F.find(w=>w&&P[w][1].includes(x))][1].find(w=>w!=x))-v(x)
| Add day 7 solution part 2 | Add day 7 solution part 2
| JavaScript | mit | yishn/adventofcode,yishn/adventofcode | ---
+++
@@ -1,2 +1,5 @@
// Part 1
I=document.body.innerText.split`\n`,I.map(x=>x.split` `[0]).find(w=>!I.some(e=>[...e.split`>`,''][1].includes(w)))
+
+// Part 2
+P={},document.body.innerText.split`\n`.map(l=>l&&(i=l.indexOf('>'),P[l.split` `[0]]=[+l.match(/\d+/)[0],i>0?l.slice(i+2).split`, `:[]])),v=w=>P[w][1].reduce((s,x)=>s+v(x),P[w][0]),f=w=>P[w][1].find((x,_,c)=>!c.some(y=>x!=y&v(x)==v(y))),F=Object.keys(P).map(f),x=F.find(w=>w&&!f(w)),P[x][0]+v(P[F.find(w=>w&&P[w][1].includes(x))][1].find(w=>w!=x))-v(x) |
6be0661e9715b39a308cb5c89fd7cf074610fa35 | lib/updateComment.js | lib/updateComment.js | const updateComment = (body, commentArr = []) => {
body = body.map((obj, index, array) => {
if (obj.type === 'Line' || obj.type === 'Block') {
commentArr.push(obj)
if (array[index + 1] === undefined) {
array[index - commentArr.length].trailingComments = commentArr
return undefined
}
if (!(array[index + 1].type === 'Line' || array[index + 1].type === 'Block')) {
array[index + 1].leadingComments = commentArr
commentArr = []
}
return undefined
}
return obj
}).filter(stmt => stmt !== undefined)
return body
}
/* Module Exports updateComment */
module.exports = updateComment
| const updateComment = (body, ast, commentArr = []) => {
body = body.map((obj, index, array) => {
if (obj.type === 'Line' || obj.type === 'Block') {
commentArr.push(obj)
if (array[index + 1] === undefined) {
if (index - commentArr.length === -1) ast.leadingComments = commentArr
else array[index - commentArr.length].trailingComments = commentArr
return undefined
}
if (!(array[index + 1].type === 'Line' || array[index + 1].type === 'Block')) {
array[index + 1].leadingComments = commentArr
commentArr = []
}
return undefined
}
return obj
}).filter(stmt => stmt !== undefined)
return body
}
/* Module Exports updateComment */
module.exports = updateComment
| Add check if the file contains only comments | Add check if the file contains only comments
| JavaScript | mit | cleanlang/clean,cleanlang/clean,cleanlang/clean | ---
+++
@@ -1,9 +1,10 @@
-const updateComment = (body, commentArr = []) => {
+const updateComment = (body, ast, commentArr = []) => {
body = body.map((obj, index, array) => {
if (obj.type === 'Line' || obj.type === 'Block') {
commentArr.push(obj)
if (array[index + 1] === undefined) {
- array[index - commentArr.length].trailingComments = commentArr
+ if (index - commentArr.length === -1) ast.leadingComments = commentArr
+ else array[index - commentArr.length].trailingComments = commentArr
return undefined
}
if (!(array[index + 1].type === 'Line' || array[index + 1].type === 'Block')) { |
703a27408398344ce53b38727ea96ee6ebd53922 | usecase/usecase-webapi-xwalk-tests/steps/Vehicle/step.js | usecase/usecase-webapi-xwalk-tests/steps/Vehicle/step.js | var step = '<font style="font-size:85%">'
+ '<p>Test Purpose: </p>'
+ '<p>Verifies the device supports tizen vehicle information and vehicle data API.</p>'
+ '<p>Test Step: </p>'
+ '<p>'
+ '<ol>'
+ '<li>'
+ 'Click the "Get vehicle" button.'
+ '</li>'
+ '</ol>'
+ '</p>'
+ '<p>Expected Result: </p>'
+ '<p>Test passes if the detected direction reflects the actual vehicle information</p>'
+ '</font>'
| var step = '<font style="font-size:85%">'
+ '<p>Test Purpose: </p>'
+ '<p>Verifies the device supports tizen vehicle information and vehicle data API.</p>'
+ '<p>Pre-condition: </p>'
+ '<p>Enable bluemonkey plugin following https://wiki.tizen.org/wiki/AMB_Bluemonkey_Plugin</p>'
+ '<p>Test Step: </p>'
+ '<p>'
+ '<ol>'
+ '<li>'
+ 'Click the "Get vehicle" button.'
+ '</li>'
+ '</ol>'
+ '</p>'
+ '<p>Expected Result: </p>'
+ '<p>Test passes if the detected direction reflects the actual vehicle information</p>'
+ '</font>'
| Update precondition for vehicle information and data | [usecase] Update precondition for vehicle information and data
| JavaScript | bsd-3-clause | ibelem/crosswalk-test-suite,yunxliu/crosswalk-test-suite,ibelem/crosswalk-test-suite,yunxliu/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,haoxli/crosswalk-test-suite,yunxliu/crosswalk-test-suite,chunywang/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,kangxu/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,BruceDai/crosswalk-test-suite,yhe39/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,jiajiax/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,pk-sam/crosswalk-test-suite,jiajiax/crosswalk-test-suite,chunywang/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,zqzhang/crosswalk-test-suite,chunywang/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,kangxu/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,ibelem/crosswalk-test-suite,haoxli/crosswalk-test-suite,pk-sam/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,kangxu/crosswalk-test-suite,Honry/crosswalk-test-suite,Honry/crosswalk-test-suite,jacky-young/crosswalk-test-suite,chunywang/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,zqzhang/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,pk-sam/crosswalk-test-suite,jacky-young/crosswalk-test-suite,yhe39/crosswalk-test-suite,pk-sam/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,Honry/crosswalk-test-suite,yunxliu/crosswalk-test-suite,Honry/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,jacky-young/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,chunywang/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,haoxli/crosswalk-test-suite,ibelem/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,BruceDai/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,haoxli/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,jiajiax/crosswalk-test-suite,zqzhang/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,yhe39/crosswalk-test-suite,yhe39/crosswalk-test-suite,haoxli/crosswalk-test-suite,BruceDai/crosswalk-test-suite,jiajiax/crosswalk-test-suite,haoxli/crosswalk-test-suite,jacky-young/crosswalk-test-suite,kangxu/crosswalk-test-suite,zqzhang/crosswalk-test-suite,ibelem/crosswalk-test-suite,yunxliu/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,kangxu/crosswalk-test-suite,pk-sam/crosswalk-test-suite,Honry/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,ibelem/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,kangxu/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,jiajiax/crosswalk-test-suite,ibelem/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,BruceDai/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,Honry/crosswalk-test-suite,XiaosongWei/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,Honry/crosswalk-test-suite,BruceDai/crosswalk-test-suite,chunywang/crosswalk-test-suite,yhe39/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,haoxli/crosswalk-test-suite,jiajiax/crosswalk-test-suite,zqzhang/crosswalk-test-suite,BruceDai/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,yunxliu/crosswalk-test-suite,jiajiax/crosswalk-test-suite,zqzhang/crosswalk-test-suite,qiuzhong/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,kangxu/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,YongseopKim/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,yunxliu/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,yunxliu/crosswalk-test-suite,yhe39/crosswalk-test-suite,pk-sam/crosswalk-test-suite,haoxli/crosswalk-test-suite,Honry/crosswalk-test-suite,ibelem/crosswalk-test-suite,zqzhang/crosswalk-test-suite,chunywang/crosswalk-test-suite,pk-sam/crosswalk-test-suite,zqzhang/crosswalk-test-suite,zhuyongyong/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,haoyunfeix/crosswalk-test-suite,yhe39/crosswalk-test-suite,jacky-young/crosswalk-test-suite,kangxu/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,crosswalk-project/crosswalk-test-suite,BruceDai/crosswalk-test-suite,JianfengXu/crosswalk-test-suite,yhe39/crosswalk-test-suite,chunywang/crosswalk-test-suite,kaixinjxq/crosswalk-test-suite,Shao-Feng/crosswalk-test-suite,jacky-young/crosswalk-test-suite,wanghongjuan/crosswalk-test-suite,BruceDai/crosswalk-test-suite | ---
+++
@@ -1,6 +1,8 @@
var step = '<font style="font-size:85%">'
+ '<p>Test Purpose: </p>'
+ '<p>Verifies the device supports tizen vehicle information and vehicle data API.</p>'
+ + '<p>Pre-condition: </p>'
+ + '<p>Enable bluemonkey plugin following https://wiki.tizen.org/wiki/AMB_Bluemonkey_Plugin</p>'
+ '<p>Test Step: </p>'
+ '<p>'
+ '<ol>' |
46cc2ba37cb5c8aa2287398a5fd3391b8338b840 | src/exportTranslations.js | src/exportTranslations.js | const siteSlug = process.argv[2];
const fs = require('fs');
import { getQuestionsStream, getAnswersStream, uninitDB } from './datastore.js';
import { decodify } from './codify.js';
const baseLang = 'en';
let sequence = Promise.resolve();
sequence = sequence.then(getQuestionsStream.bind(null, siteSlug, baseLang, { }, question => {
if (!fs.existsSync('./translations')) {
fs.mkdirSync('./translations');
}
if (!fs.existsSync(`./translations/${siteSlug}`)) {
fs.mkdirSync(`./translations/${siteSlug}`);
}
sequence = sequence.then(decodify.bind(null, question.body));
sequence = sequence.then(data => {
fs.writeFileSync(`./translations/${siteSlug}/q${question.id}.html`, data.normalizedBody);
fs.writeFileSync(`./translations/${siteSlug}/t${question.id}.html`, question.title);
});
}));
sequence = sequence.then(getAnswersStream.bind(null, siteSlug, baseLang, { }, answer => {
sequence = sequence.then(decodify.bind(null, answer.body));
sequence = sequence.then(data => {
fs.writeFileSync(`./translations/${siteSlug}/a${answer.id}.html`, data.normalizedBody);
});
}));
sequence = sequence.then(uninitDB);
sequence.catch(err => console.error(err));
| const siteSlug = process.argv[2];
const fs = require('fs');
import { getQuestionsStream, getAnswersStream, uninitDB } from './datastore.js';
import { decodify } from './codify.js';
const baseLang = 'en';
function createDirs(dir) {
let subdirs = dir.split('/').splice(1);
let path = './';
subdirs.forEach(subdir => {
path += `${subdir}/`;
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
});
}
let sequence = Promise.resolve();
sequence = sequence.then(getQuestionsStream.bind(null, siteSlug, baseLang, { }, question => {
createDirs(`./translations/export/${siteSlug}`);
sequence = sequence.then(decodify.bind(null, question.body));
sequence = sequence.then(data => {
fs.writeFileSync(`./translations/export/${siteSlug}/q${question.id}.html`, data.normalizedBody);
fs.writeFileSync(`./translations/export/${siteSlug}/t${question.id}.html`, question.title);
});
}));
sequence = sequence.then(getAnswersStream.bind(null, siteSlug, baseLang, { }, answer => {
sequence = sequence.then(decodify.bind(null, answer.body));
sequence = sequence.then(data => {
fs.writeFileSync(`./translations/${siteSlug}/a${answer.id}.html`, data.normalizedBody);
});
}));
sequence = sequence.then(uninitDB);
sequence.catch(err => console.error(err));
| Adjust dir structure for exports | Adjust dir structure for exports
| JavaScript | mpl-2.0 | bbondy/stack-view,bbondy/stack-view,bbondy/stack-view | ---
+++
@@ -4,18 +4,25 @@
import { decodify } from './codify.js';
const baseLang = 'en';
+function createDirs(dir) {
+ let subdirs = dir.split('/').splice(1);
+ let path = './';
+ subdirs.forEach(subdir => {
+ path += `${subdir}/`;
+ if (!fs.existsSync(path)) {
+ fs.mkdirSync(path);
+ }
+ });
+}
+
let sequence = Promise.resolve();
+
sequence = sequence.then(getQuestionsStream.bind(null, siteSlug, baseLang, { }, question => {
- if (!fs.existsSync('./translations')) {
- fs.mkdirSync('./translations');
- }
- if (!fs.existsSync(`./translations/${siteSlug}`)) {
- fs.mkdirSync(`./translations/${siteSlug}`);
- }
+ createDirs(`./translations/export/${siteSlug}`);
sequence = sequence.then(decodify.bind(null, question.body));
sequence = sequence.then(data => {
- fs.writeFileSync(`./translations/${siteSlug}/q${question.id}.html`, data.normalizedBody);
- fs.writeFileSync(`./translations/${siteSlug}/t${question.id}.html`, question.title);
+ fs.writeFileSync(`./translations/export/${siteSlug}/q${question.id}.html`, data.normalizedBody);
+ fs.writeFileSync(`./translations/export/${siteSlug}/t${question.id}.html`, question.title);
});
}));
|
e728d402d02b480e1d89ed63cca3ab42c4d2ef0c | src/js/directives/jade.js | src/js/directives/jade.js | /**
* JADE DIRECTIVES
*
*/
var module = angular.module('jade', []);
/**
* Jade Replace
*/
module.directive('rpJadeReplace', function($rootScope, $compile) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
scope = {parent: scope.$parent, root: $rootScope}[attrs.scope] || scope;
template = require("../../jade/" + attrs.rpJadeReplace)();
$compile(template)(scope, function (el, $scope) {
element.replaceWith(el);
});
}
};
});
| /**
* JADE DIRECTIVES
*
*/
var module = angular.module('jade', []);
/**
* Jade Replace
*/
module.directive('rpJadeReplace', ['$rootScope', '$compile', function($rootScope, $compile) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
scope = {parent: scope.$parent, root: $rootScope}[attrs.scope] || scope;
template = require("../../jade/" + attrs.rpJadeReplace)();
$compile(template)(scope, function (el, $scope) {
element.replaceWith(el);
});
}
};
}]);
| Fix non-explicit arguments. (This broke when the code was minified.) | Fix non-explicit arguments. (This broke when the code was minified.)
| JavaScript | isc | dncohen/ripple-client-desktop,MatthewPhinney/ripple-client,xdv/ripple-client-desktop,vhpoet/ripple-client-desktop,dncohen/ripple-client-desktop,yxxyun/ripple-client,MatthewPhinney/ripple-client,resilience-me/DEPRICATED_ripple-client,vhpoet/ripple-client,darkdarkdragon/ripple-client-desktop,darkdarkdragon/ripple-client-desktop,vhpoet/ripple-client,arturomc/ripple-client,ripple/ripple-client,arturomc/ripple-client,mrajvanshy/ripple-client,xdv/ripple-client,Madsn/ripple-client,darkdarkdragon/ripple-client,vhpoet/ripple-client,ripple/ripple-client,h0vhannes/ripple-client,xdv/ripple-client,h0vhannes/ripple-client,Madsn/ripple-client,wangbibo/ripple-client,arturomc/ripple-client,yongsoo/ripple-client-desktop,MatthewPhinney/ripple-client-desktop,vhpoet/ripple-client-desktop,Madsn/ripple-client,resilience-me/DEPRICATED_ripple-client,MatthewPhinney/ripple-client,yongsoo/ripple-client,yongsoo/ripple-client,yxxyun/ripple-client-desktop,h0vhannes/ripple-client,bankonme/ripple-client-desktop,darkdarkdragon/ripple-client,MatthewPhinney/ripple-client,yxxyun/ripple-client,xdv/ripple-client,xdv/ripple-client-desktop,bsteinlo/ripple-client,bankonme/ripple-client-desktop,xdv/ripple-client-desktop,h0vhannes/ripple-client,yxxyun/ripple-client,MatthewPhinney/ripple-client-desktop,thics/ripple-client-desktop,yxxyun/ripple-client-desktop,vhpoet/ripple-client,yongsoo/ripple-client-desktop,wangbibo/ripple-client,xdv/ripple-client,wangbibo/ripple-client,ripple/ripple-client-desktop,mrajvanshy/ripple-client,arturomc/ripple-client,darkdarkdragon/ripple-client,wangbibo/ripple-client,ripple/ripple-client,mrajvanshy/ripple-client,thics/ripple-client-desktop,yxxyun/ripple-client,mrajvanshy/ripple-client-desktop,yongsoo/ripple-client,Madsn/ripple-client,bsteinlo/ripple-client,darkdarkdragon/ripple-client,mrajvanshy/ripple-client-desktop,ripple/ripple-client,yongsoo/ripple-client,mrajvanshy/ripple-client,ripple/ripple-client-desktop | ---
+++
@@ -8,7 +8,7 @@
/**
* Jade Replace
*/
-module.directive('rpJadeReplace', function($rootScope, $compile) {
+module.directive('rpJadeReplace', ['$rootScope', '$compile', function($rootScope, $compile) {
return {
restrict: 'A',
scope: false,
@@ -20,4 +20,4 @@
});
}
};
-});
+}]); |
7217cb603778f2d9459ae65c21b5bf77971157dc | lib/utils/scrollParent.js | lib/utils/scrollParent.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* @fileOverview Find scroll parent
*/
exports.default = function (node) {
if (!node) {
return document.documentElement;
}
var excludeStaticParent = node.style.position === 'absolute';
var overflowRegex = /(scroll|auto)/;
var parent = node;
while (parent) {
if (!parent.parentNode) {
return node.ownerDocument || document.documentElement;
}
var style = window.getComputedStyle(parent);
var position = style.position;
var overflow = style.overflow;
var overflowX = style['overflow-x'];
var overflowY = style['overflow-y'];
if (position === 'static' && excludeStaticParent) {
parent = parent.parentNode;
continue;
}
if (overflowRegex.test(overflow) && overflowRegex.test(overflowX) && overflowRegex.test(overflowY)) {
return parent;
}
parent = parent.parentNode;
}
return node.ownerDocument || node.documentElement || document.documentElement;
}; | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* @fileOverview Find scroll parent
*/
exports.default = function (node) {
if (!node) {
return document.documentElement;
}
var excludeStaticParent = node.style.position === 'absolute';
var overflowRegex = /(scroll|auto)/;
var parent = node;
while (parent) {
if (!parent.parentNode) {
return node.ownerDocument || document.documentElement;
}
var style = window.getComputedStyle(parent);
var position = style.position;
var overflow = style.overflow;
var overflowX = style['overflow-x'];
var overflowY = style['overflow-y'];
if (position === 'static' && excludeStaticParent) {
parent = parent.parentNode;
continue;
}
if (overflowRegex.test(overflow) || overflowRegex.test(overflowX) || overflowRegex.test(overflowY)) {
return parent;
}
parent = parent.parentNode;
}
return node.ownerDocument || node.documentElement || document.documentElement;
};
| Check for any overflow scroll style on parent node. | Check for any overflow scroll style on parent node.
| JavaScript | mit | jasonslyvia/react-lazyload | ---
+++
@@ -33,7 +33,7 @@
continue;
}
- if (overflowRegex.test(overflow) && overflowRegex.test(overflowX) && overflowRegex.test(overflowY)) {
+ if (overflowRegex.test(overflow) || overflowRegex.test(overflowX) || overflowRegex.test(overflowY)) {
return parent;
}
|
b30d2456d671cc9af9a9696a4bd54c0959ff2c44 | content/confirm.js | content/confirm.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var Cc = Components.classes;
var Ci = Components.interfaces;
function getMessage(aKey) {
var bundle = document.getElementById('messages');
return bundle.getString(aKey);
}
function onLoad() {
}
function onAccept() {
}
function onCancel() {
window.close();
}
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var Cc = Components.classes;
var Ci = Components.interfaces;
function getMessage(aKey) {
var bundle = document.getElementById('messages');
return bundle.getString(aKey);
}
var gParams;
function onLoad() {
gParams = window.arguments[0];
}
function onAccept() {
gParams.confirmed = true;
window.close();
}
function onCancel() {
window.close();
}
| Define action for the accpet button | Define action for the accpet button
| JavaScript | mpl-2.0 | clear-code/tb-check-attachment-before-send,clear-code/tb-check-attachment-before-send | ---
+++
@@ -10,10 +10,15 @@
return bundle.getString(aKey);
}
+var gParams;
+
function onLoad() {
+ gParams = window.arguments[0];
}
function onAccept() {
+ gParams.confirmed = true;
+ window.close();
}
function onCancel() { |
ba3ee93d05d7cd3c1baa7d739e909b39762fb9dc | build/footer.js | build/footer.js | if (typeof define === "function" && define.amd) {
define(function() {
return jBone;
});
}
if (typeof win === "object" && typeof win.document === "object") {
win.jBone = win.$ = jBone;
}
}());
| if (typeof module === "object" && module && typeof module.exports === "object") {
// Expose jBone as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jBone;
}
// Register as a AMD module
else if (typeof define === "function" && define.amd) {
define("jbone", [], function() {
return jBone;
});
}
if (typeof win === "object" && typeof win.document === "object") {
win.jBone = win.$ = jBone;
}
}());
| Add support for node module | Add support for node module
| JavaScript | mit | kupriyanenko/jbone,npmcomponent/kupriyanenko-jbone,kupriyanenko/jbone | ---
+++
@@ -1,5 +1,13 @@
-if (typeof define === "function" && define.amd) {
- define(function() {
+if (typeof module === "object" && module && typeof module.exports === "object") {
+ // Expose jBone as module.exports in loaders that implement the Node
+ // module pattern (including browserify). Do not create the global, since
+ // the user will be storing it themselves locally, and globals are frowned
+ // upon in the Node module world.
+ module.exports = jBone;
+}
+// Register as a AMD module
+else if (typeof define === "function" && define.amd) {
+ define("jbone", [], function() {
return jBone;
});
} |
89251d5a6a09e221832572b70cc09f98dbc7989e | templates/migrations/4_users.js | templates/migrations/4_users.js | exports.up = function(knex) {
return knex.schema.createTable('users', table => {
table.increments().primary();
table.timestamps();
table.string('name');
});
};
exports.down = function(knex) {
return knex.schema.dropTable('users');
};
| exports.up = function(knex) {
return knex.schema.createTable('users', table => {
table.increments().primary();
table.timestamps();
table.string('name');
table.string('auth0_id');
});
};
exports.down = function(knex) {
return knex.schema.dropTable('users');
};
| Update user schema to take auth0_id | Update user schema to take auth0_id | JavaScript | mit | pushkin-npm/pushkin-cli,pushkin-npm/pushkin-cli,pushkin-npm/pushkin-cli | ---
+++
@@ -3,6 +3,7 @@
table.increments().primary();
table.timestamps();
table.string('name');
+ table.string('auth0_id');
});
};
|
f86da80cdf74f5d9fe2bb77d2e184f78516383fd | src/middleware/commandCheck.js | src/middleware/commandCheck.js | const chalk = require('chalk')
const logger = require('winston')
const { Permitter } = require('../core')
module.exports = {
priority: 100,
process: container => {
const { msg, isPrivate, isCommand, cache, commander, trigger, settings, admins } = container
if (!isCommand) return Promise.resolve()
const cmd = commander.get(trigger).cmd
if (!admins.includes(msg.author.id) || !cmd.options.modOnly) {
const isAllowed = Permitter.verifyMessage(cmd.permissionNode, msg, settings.permissions)
if (!isAllowed) return Promise.resolve()
}
logger.info(`${chalk.bold.magenta(
!isPrivate
? msg.guild.name
: '(in PMs)'
)} > ${chalk.bold.green(msg.author.username)}: ` +
`${chalk.bold.blue(msg.cleanContent.replace(/\n/g, ' '))}`)
cache.client.multi()
.hincrby('usage', commander.get(trigger).cmd.labels[0], 1)
.hincrby('usage', 'ALL', 1)
.exec()
return Promise.resolve(container)
}
}
| const chalk = require('chalk')
const logger = require('winston')
const { Permitter } = require('../core')
module.exports = {
priority: 100,
process: container => {
const { msg, isPrivate, isCommand, cache, commander, trigger, settings, admins } = container
if (!isCommand) return Promise.resolve()
const cmd = commander.get(trigger).cmd
if (!admins.includes(msg.author.id) || !(cmd.options.modOnly || cmd.options.adminOnly)) {
const isAllowed = Permitter.verifyMessage(cmd.permissionNode, msg, settings.permissions)
if (!isAllowed) return Promise.resolve()
}
logger.info(`${chalk.bold.magenta(
!isPrivate
? msg.guild.name
: '(in PMs)'
)} > ${chalk.bold.green(msg.author.username)}: ` +
`${chalk.bold.blue(msg.cleanContent.replace(/\n/g, ' '))}`)
cache.client.multi()
.hincrby('usage', commander.get(trigger).cmd.labels[0], 1)
.hincrby('usage', 'ALL', 1)
.exec()
return Promise.resolve(container)
}
}
| Fix middleware check for admin commands | :bug: Fix middleware check for admin commands
| JavaScript | agpl-3.0 | pyraxo/haru | ---
+++
@@ -9,7 +9,7 @@
const { msg, isPrivate, isCommand, cache, commander, trigger, settings, admins } = container
if (!isCommand) return Promise.resolve()
const cmd = commander.get(trigger).cmd
- if (!admins.includes(msg.author.id) || !cmd.options.modOnly) {
+ if (!admins.includes(msg.author.id) || !(cmd.options.modOnly || cmd.options.adminOnly)) {
const isAllowed = Permitter.verifyMessage(cmd.permissionNode, msg, settings.permissions)
if (!isAllowed) return Promise.resolve()
} |
ae530367b59848c2259bf50e85e087634dab9bb1 | dist_chrome/content-script.js | dist_chrome/content-script.js | (function() {
"use strict";
window.addEventListener('message', function(event) {
if (event.data === 'debugger-client') {
var port = event.ports[0];
listenToPort(port);
} else if (event.data.type) {
chrome.extension.sendMessage(event.data);
}
});
function listenToPort(port) {
port.addEventListener('message', function(event) {
chrome.extension.sendMessage(event.data);
});
chrome.extension.onMessage.addListener(function(message) {
if (message.from === 'devtools') {
port.postMessage(message);
}
});
port.start();
}
// let ember-debug know that content script has executed
document.documentElement.dataset.emberExtension = 1;
// Allow older versions of Ember (< 1.4) to detect the extension.
if (document.body) {
document.body.dataset.emberExtension = 1;
}
// clear a possible previous Ember icon
chrome.extension.sendMessage({ type: 'resetEmberIcon' });
// inject JS into the page to check for an app on domready
var script = document.createElement('script');
script.type = "text/javascript";
script.src = chrome.extension.getURL("in-page-script.js");
if (document.body) document.body.appendChild(script);
}());
| (function() {
"use strict";
window.addEventListener('message', function(event) {
if (event.data === 'debugger-client') {
var port = event.ports[0];
listenToPort(port);
} else if (event.data.type) {
chrome.extension.sendMessage(event.data);
}
});
function listenToPort(port) {
port.addEventListener('message', function(event) {
chrome.extension.sendMessage(event.data);
});
chrome.extension.onMessage.addListener(function(message) {
if (message.from === 'devtools') {
port.postMessage(message);
}
});
port.start();
}
// let ember-debug know that content script has executed
document.documentElement.dataset.emberExtension = 1;
// clear a possible previous Ember icon
chrome.extension.sendMessage({ type: 'resetEmberIcon' });
// inject JS into the page to check for an app on domready
var script = document.createElement('script');
script.type = "text/javascript";
script.src = chrome.extension.getURL("in-page-script.js");
if (document.body) document.body.appendChild(script);
}());
| Stop adding data-ember-extension to body | Stop adding data-ember-extension to body
| JavaScript | mit | teddyzeenny/ember-extension,NikkiDreams/ember-inspector,emberjs/ember-inspector,vvscode/js--ember-inspector,knownasilya/ember-inspector,jryans/ember-inspector,dsturley/ember-inspector,chrisgame/ember-inspector,teddyzeenny/ember-extension,teddyzeenny/ember-inspector,maheshsenni/ember-inspector,sivakumar-kailasam/ember-inspector,pete-the-pete/ember-inspector,karthiick/ember-inspector,NikkiDreams/ember-inspector,sly7-7/ember-inspector,sivakumar-kailasam/ember-inspector,jayphelps/ember-inspector,cibernox/ember-inspector,emberjs/ember-inspector,aceofspades/ember-inspector,chrisgame/ember-inspector,dsturley/ember-inspector,jayphelps/ember-inspector,sly7-7/ember-inspector,Patsy-issa/ember-inspector,Patsy-issa/ember-inspector,karthiick/ember-inspector,cibernox/ember-inspector,vvscode/js--ember-inspector,aceofspades/ember-inspector,knownasilya/ember-inspector,teddyzeenny/ember-inspector,rwjblue/ember-inspector,jryans/ember-inspector,maheshsenni/ember-inspector,pete-the-pete/ember-inspector | ---
+++
@@ -28,10 +28,6 @@
// let ember-debug know that content script has executed
document.documentElement.dataset.emberExtension = 1;
- // Allow older versions of Ember (< 1.4) to detect the extension.
- if (document.body) {
- document.body.dataset.emberExtension = 1;
- }
// clear a possible previous Ember icon
chrome.extension.sendMessage({ type: 'resetEmberIcon' }); |
3f8a23d785e1036fe65315938a0dee9bb8a77eba | modules/fullwidth.js | modules/fullwidth.js | module.exports = {
commands: {
fullwidth: {
help: 'οΌ£ο½ο½
ο½ο½ο½
ο½γο½ο½γο½ο½
ο½ο½ο½ο½
ο½ο½ο½',
aliases: [ 'vw', 'fw' ],
command: function (bot, msg) {
let codePoints = Array.prototype.map.call(msg.body, (c) => c.codePointAt(0))
codePoints = codePoints.map((c) => {
if (c >= 33 && c <= 126) return c - 33 + 0xFF01
return c
})
return String.fromCodePoint(...codePoints)
}
}
}
}
| module.exports = {
commands: {
fullwidth: {
help: 'οΌ£ο½ο½
ο½ο½ο½
ο½γο½ο½γο½ο½
ο½ο½ο½ο½
ο½ο½ο½',
aliases: [ 'vw', 'fw' ],
command: function (bot, msg) {
let codePoints = Array.prototype.map.call(msg.body, (c) => c.codePointAt(0))
codePoints = codePoints.map((c) => {
if (c >= 33 && c <= 126) return c - 33 + 0xFF01
if (c == 32) return 0x3000
return c
})
return String.fromCodePoint(...codePoints)
}
}
}
}
| Convert spaces to U+3000 (ideographic space) | Convert spaces to U+3000 (ideographic space) | JavaScript | isc | zuzakistan/civilservant,zuzakistan/civilservant | ---
+++
@@ -7,6 +7,7 @@
let codePoints = Array.prototype.map.call(msg.body, (c) => c.codePointAt(0))
codePoints = codePoints.map((c) => {
if (c >= 33 && c <= 126) return c - 33 + 0xFF01
+ if (c == 32) return 0x3000
return c
})
return String.fromCodePoint(...codePoints) |
00690d2d264841a73a6728efc77dd3defe095fe0 | docs/src/@primer/gatsby-theme-doctocat/components/live-preview-wrapper.js | docs/src/@primer/gatsby-theme-doctocat/components/live-preview-wrapper.js | import React from 'react'
import primerStyles from '!!raw-loader!postcss-loader!../../../../../src/index.scss'
function LivePreviewWrapper({children}) {
return (
<>
<style>{primerStyles}</style>
<link rel="stylesheet" href="https://github.com/site/assets/styleguide.css" />
<div className="p-3">{children}</div>
</>
)
}
export default LivePreviewWrapper
| import React from 'react'
import primerStyles from '!!raw-loader!postcss-loader!../../../../../src/index.scss'
function LivePreviewWrapper({children}) {
return (
<>
<link rel="stylesheet" href="https://github.com/site/assets/styleguide.css" />
<style>{primerStyles}</style>
<div className="p-3">{children}</div>
</>
)
}
export default LivePreviewWrapper
| Switch source order for `styleguide.css` | Switch source order for `styleguide.css` | JavaScript | mit | primer/primer,primer/primer,primer/primer-css,primer/primer-css,primer/primer,primer/primer-css | ---
+++
@@ -4,8 +4,8 @@
function LivePreviewWrapper({children}) {
return (
<>
+ <link rel="stylesheet" href="https://github.com/site/assets/styleguide.css" />
<style>{primerStyles}</style>
- <link rel="stylesheet" href="https://github.com/site/assets/styleguide.css" />
<div className="p-3">{children}</div>
</>
) |
6cfb39df1495d209966f216c6d4838b1bcfd7559 | assets/js/cv.js | assets/js/cv.js | $(document).ready(function () {
// Send GA event when user scrolls to the bottom of the page, which we interpret as them reading the content
// on the page.
(function(){
var triggered = false;
$(window).scroll(function () {
if (($(window).scrollTop() >= $(document).height() - $(window).height() - 10) && !triggered) {
triggered = true;
ga('send', 'event', 'Page', 'Scroll', 'Bottom');
}
});
})();
// Scroll to top button
var back_to_top_button = $('.btn.back-to-top');
// Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
back_to_top_button.fadeIn();
} else {
back_to_top_button.fadeOut();
}
});
// Click event to scroll to top
back_to_top_button.click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
| $(document).ready(function () {
// Scroll to top button
var back_to_top_button = $('.btn.back-to-top');
// Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
back_to_top_button.fadeIn();
} else {
back_to_top_button.fadeOut();
}
});
// Click event to scroll to top
back_to_top_button.click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
| Remove GA event from CV | Remove GA event from CV
| JavaScript | mit | MasterRoot24/masterroot24.github.io,MasterRoot24/masterroot24.github.io,MasterRoot24/masterroot24.github.io | ---
+++
@@ -1,17 +1,4 @@
$(document).ready(function () {
-
- // Send GA event when user scrolls to the bottom of the page, which we interpret as them reading the content
- // on the page.
- (function(){
- var triggered = false;
- $(window).scroll(function () {
- if (($(window).scrollTop() >= $(document).height() - $(window).height() - 10) && !triggered) {
- triggered = true;
- ga('send', 'event', 'Page', 'Scroll', 'Bottom');
- }
- });
- })();
-
// Scroll to top button
var back_to_top_button = $('.btn.back-to-top');
@@ -29,5 +16,4 @@
$('html, body').animate({scrollTop : 0},800);
return false;
});
-
}); |
30d0019b24834e89de7e20345939f6a5db852951 | imports/client/components/main-layout/user-navigation/header-dashboard.js | imports/client/components/main-layout/user-navigation/header-dashboard.js | import React from 'react';
import { Link } from 'react-router';
class HeaderDashboard extends React.Component {
shouldComponentUpdate(nextProps, nextState, nextContext) {
const { location: key, currentUser } = this.context;
return key !== nextContext.location.key || currentUser !== nextContext.currentUser;
}
_signUpView() {
return (
<div className="header-sign-up">
<Link to="/sign-up" className="header-sign-up-button button red ">Sign Up</Link>
</div>
);
}
_userView() {
const dashboardLinks = [
'dashboard',
'cart',
'messages',
'notifications',
];
const style = {
width: `${(100 / dashboardLinks.length)}%`,
};
return (
<div className="header-dashboard">
<span className="header-primary-divider header-dashboard-divider"></span>
{
dashboardLinks.map((link, i) => {
const className = `icon icon-${link}`;
return (
<span key={i} className="header-dashboard-item" style={style}>
<Link to={`/${link}`} className={className} />
</span>
);
})
}
</div>
);
}
render() {
const view = this.context.currentUser ? this._userView() : this._signUpView();
return view;
}
}
HeaderDashboard.contextTypes = {
location: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.object,
};
export default HeaderDashboard;
| import React from 'react';
import { Link } from 'react-router';
class HeaderDashboard extends React.Component {
shouldComponentUpdate(nextProps, nextState, nextContext) {
const { location: key, currentUser } = this.context;
return key !== nextContext.location.key || currentUser !== nextContext.currentUser;
}
_signUpView() {
return (
<div className="header-sign-up">
<Link to="/sign-up" className="header-sign-up-button button red ">Sign Up</Link>
</div>
);
}
_userView() {
const dashboardLinks = [
'messages',
'notifications',
];
return (
<div className="header-dashboard">
<span className="header-primary-divider header-dashboard-divider"></span>
{
dashboardLinks.map((link, i) => {
const className = `icon icon-${link}`;
return (
<span key={i} className="header-dashboard-item">
<Link to={`/${link}`} className={className} />
</span>
);
})
}
<Link to="/post" className="header-post-button button red ">New Post</Link>
</div>
);
}
render() {
const view = this.context.currentUser ? this._userView() : this._signUpView();
return view;
}
}
HeaderDashboard.contextTypes = {
location: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.object,
};
export default HeaderDashboard;
| Replace header dashboard links with new post button | Replace header dashboard links with new post button
| JavaScript | apache-2.0 | evancorl/skate-scenes,evancorl/skate-scenes,evancorl/portfolio,evancorl/portfolio,evancorl/portfolio,evancorl/skate-scenes | ---
+++
@@ -18,14 +18,9 @@
_userView() {
const dashboardLinks = [
- 'dashboard',
- 'cart',
'messages',
'notifications',
];
- const style = {
- width: `${(100 / dashboardLinks.length)}%`,
- };
return (
<div className="header-dashboard">
@@ -35,12 +30,13 @@
const className = `icon icon-${link}`;
return (
- <span key={i} className="header-dashboard-item" style={style}>
+ <span key={i} className="header-dashboard-item">
<Link to={`/${link}`} className={className} />
</span>
);
})
}
+ <Link to="/post" className="header-post-button button red ">New Post</Link>
</div>
);
} |
5bd66d4f6c3bbda62f52d2e7dc0001a567741e85 | src/utils/code_mirror_setup.js | src/utils/code_mirror_setup.js | import CodeMirror from "codemirror"
import _ from "underscore"
require("codemirror/addon/mode/multiplex")
require("codemirror/addon/edit/trailingspace")
// Load modes
_.each([
"gfm",
"javascript",
"ruby",
"coffeescript",
"css",
"sass",
"stylus",
"yaml"
], mode => require(`codemirror/mode/${mode}/${mode}`))
CodeMirror.defineMode("frontmatter_markdown", (config) => {
return CodeMirror.multiplexingMode(
CodeMirror.getMode(config, "text/x-gfm"),
{
open : /^\b.+\b: .*|^---$/,
close : /^---$/,
mode : CodeMirror.getMode(config, "text/x-yaml"),
parseDelimiters : true
}
)
})
export default CodeMirror
| import CodeMirror from "codemirror"
import _ from "underscore"
require("codemirror/addon/mode/multiplex")
require("codemirror/addon/edit/trailingspace")
// Load modes
_.each([
"gfm",
"javascript",
"ruby",
"coffeescript",
"css",
"sass",
"stylus",
"yaml"
], mode => require(`codemirror/mode/${mode}/${mode}`))
CodeMirror.defineMode("frontmatter_markdown", (config) => {
return CodeMirror.multiplexingMode(
CodeMirror.getMode(config, "text/x-gfm"),
{
open : "---",
close : "---",
mode : CodeMirror.getMode(config, "text/x-yaml"),
delimStyle : "front-matter-delim"
}
)
})
export default CodeMirror
| Revert to simple tokens for front-matter multiplex | Revert to simple tokens for front-matter multiplex
| JavaScript | mit | doryphores/down-quark,doryphores/down-quark | ---
+++
@@ -20,10 +20,10 @@
return CodeMirror.multiplexingMode(
CodeMirror.getMode(config, "text/x-gfm"),
{
- open : /^\b.+\b: .*|^---$/,
- close : /^---$/,
- mode : CodeMirror.getMode(config, "text/x-yaml"),
- parseDelimiters : true
+ open : "---",
+ close : "---",
+ mode : CodeMirror.getMode(config, "text/x-yaml"),
+ delimStyle : "front-matter-delim"
}
)
}) |
9d524748e5ab9773b7960fcbd6f52afa6bfd457b | config/config.js | config/config.js | var path = require('path');
var rootPath = path.normalize(__dirname + '/../');
module.exports = {
development: {
rootPath: rootPath,
dbConn: 'mongodb://localhost:27017/fileuploadsystem',
uploadsPath: path.normalize(rootPath + '/uploads/'),
port: process.env.PORT || 1234
}
} | var path = require('path');
var rootPath = path.normalize(__dirname + '/../');
module.exports = {
development: {
rootPath: rootPath,
// dbConn: 'mongodb://localhost:27017/fileuploadsystem',
dbConn: 'mongodb://fileuploadsys:qweqwe@ds033831.mongolab.com:33831/fileuploadsystem',
uploadsPath: path.normalize(rootPath + '/uploads/'),
port: process.env.PORT || 1234
}
} | Change conn str to use mongolab db | Change conn str to use mongolab db
| JavaScript | mit | georgiwe/FileUploadSystem | ---
+++
@@ -4,7 +4,8 @@
module.exports = {
development: {
rootPath: rootPath,
- dbConn: 'mongodb://localhost:27017/fileuploadsystem',
+ // dbConn: 'mongodb://localhost:27017/fileuploadsystem',
+ dbConn: 'mongodb://fileuploadsys:qweqwe@ds033831.mongolab.com:33831/fileuploadsystem',
uploadsPath: path.normalize(rootPath + '/uploads/'),
port: process.env.PORT || 1234
} |
d108bdc4cc7e1ae8bb7c25c80987eb8d0afefb0e | polygerrit-ui/app/elements/plugins/gr-endpoint-param/gr-endpoint-param.js | polygerrit-ui/app/elements/plugins/gr-endpoint-param/gr-endpoint-param.js | /**
* @license
* Copyright (C) 2017 The Android Open Source Project
*
* 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() {
'use strict';
Polymer({
is: 'gr-endpoint-param',
_legacyUndefinedCheck: true,
properties: {
name: String,
value: {
type: Object,
notify: true,
},
},
});
})();
| /**
* @license
* Copyright (C) 2017 The Android Open Source Project
*
* 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() {
'use strict';
Polymer({
is: 'gr-endpoint-param',
_legacyUndefinedCheck: true,
properties: {
name: String,
value: {
type: Object,
notify: true,
observer: '_valueChanged',
},
},
_valueChanged(newValue, oldValue) {
/* In polymer 2 the following change was made:
"Property change notifications (property-changed events) aren't fired when
the value changes as a result of a binding from the host"
(see https://polymer-library.polymer-project.org/2.0/docs/about_20).
To workaround this problem, we fire the event from the observer.
In some cases this fire the event twice, but our code is
ready for it.
*/
const detail = {
value: newValue,
};
this.dispatchEvent(new CustomEvent('value-changed', {detail}));
},
});
})();
| Fix problem with {property}-changed event | Fix problem with {property}-changed event
In polymer 2 the following change was made:
Property change notifications (property-changed events) aren't fired when
the value changes as a result of a binding from the host
(see https://polymer-library.polymer-project.org/2.0/docs/about_20).
The polymer team suggested to use observer instead of {property}-changed
event.
Bug: Issue 11316
Change-Id: I12d1860d3ee836724c111605725d806687ec2141
| JavaScript | apache-2.0 | GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit | ---
+++
@@ -25,7 +25,23 @@
value: {
type: Object,
notify: true,
+ observer: '_valueChanged',
},
+ },
+
+ _valueChanged(newValue, oldValue) {
+ /* In polymer 2 the following change was made:
+ "Property change notifications (property-changed events) aren't fired when
+ the value changes as a result of a binding from the host"
+ (see https://polymer-library.polymer-project.org/2.0/docs/about_20).
+ To workaround this problem, we fire the event from the observer.
+ In some cases this fire the event twice, but our code is
+ ready for it.
+ */
+ const detail = {
+ value: newValue,
+ };
+ this.dispatchEvent(new CustomEvent('value-changed', {detail}));
},
});
})(); |
16e5e6f977a38b1d02044bea72046fbe4d3e8c95 | lib/resources/Invoices.js | lib/resources/Invoices.js | 'use strict';
const StripeResource = require('../StripeResource');
const stripeMethod = StripeResource.method;
module.exports = StripeResource.extend({
path: 'invoices',
includeBasic: ['create', 'del', 'list', 'retrieve', 'update'],
finalizeInvoice: stripeMethod({
method: 'POST',
path: '{id}/finalize',
}),
listLineItems: stripeMethod({
method: 'GET',
path: '{id}/lines',
}),
listUpcomingLineItems: stripeMethod({
method: 'GET',
path: 'upcoming/lines',
}),
markUncollectible: stripeMethod({
method: 'POST',
path: '{id}/mark_uncollectible',
}),
pay: stripeMethod({
method: 'POST',
path: '{id}/pay',
}),
retrieveUpcoming: stripeMethod({
method: 'GET',
path: 'upcoming',
}),
sendInvoice: stripeMethod({
method: 'POST',
path: '{id}/send',
}),
voidInvoice: stripeMethod({
method: 'POST',
path: '{id}/void',
}),
});
| 'use strict';
const StripeResource = require('../StripeResource');
const stripeMethod = StripeResource.method;
module.exports = StripeResource.extend({
path: 'invoices',
includeBasic: ['create', 'del', 'list', 'retrieve', 'update'],
finalizeInvoice: stripeMethod({
method: 'POST',
path: '{id}/finalize',
}),
listLineItems: stripeMethod({
method: 'GET',
path: '{id}/lines',
methodType: 'list',
}),
listUpcomingLineItems: stripeMethod({
method: 'GET',
path: 'upcoming/lines',
methodType: 'list',
}),
markUncollectible: stripeMethod({
method: 'POST',
path: '{id}/mark_uncollectible',
}),
pay: stripeMethod({
method: 'POST',
path: '{id}/pay',
}),
retrieveUpcoming: stripeMethod({
method: 'GET',
path: 'upcoming',
}),
sendInvoice: stripeMethod({
method: 'POST',
path: '{id}/send',
}),
voidInvoice: stripeMethod({
method: 'POST',
path: '{id}/void',
}),
});
| Make autopagination functions work for listLineItems and listUpcomingLineItems | Make autopagination functions work for listLineItems and listUpcomingLineItems
| JavaScript | mit | stripe/stripe-node,stripe/stripe-node | ---
+++
@@ -16,11 +16,13 @@
listLineItems: stripeMethod({
method: 'GET',
path: '{id}/lines',
+ methodType: 'list',
}),
listUpcomingLineItems: stripeMethod({
method: 'GET',
path: 'upcoming/lines',
+ methodType: 'list',
}),
markUncollectible: stripeMethod({ |
a0c5179d4c68e169d6deae210aec415db84fa161 | examples/example-1.js | examples/example-1.js | #!/usr/bin/env node
let lib = require('../index'),
Point2D = lib.Point2D,
Intersection = lib.Intersection;
let circle = {
cx: new Point2D(0, 0),
r: 50,
};
let rectangle = {
p1: new Point2D(0, 0),
p2: new Point2D(60, 30)
};
let result = Intersection.intersectCircleRectangle(
circle.cx, circle.r,
rectangle.p1, rectangle.p2
);
console.log(result);
| #!/usr/bin/env node
let lib = require('../index'),
Point2D = lib.Point2D,
Intersection = lib.Intersection;
let circle = {
center: new Point2D(0, 0),
radius: 50,
};
let rectangle = {
topLeft: new Point2D(0, 0),
bottomRight: new Point2D(60, 30)
};
let result = Intersection.intersectCircleRectangle(
circle.center, circle.radius,
rectangle.topLeft, rectangle.bottomRight
);
console.log(result);
| Fix property names in example | Fix property names in example
Some of them were incorrect and others were not very descriptive. This updates the example to match what we have in the README file.
| JavaScript | bsd-3-clause | thelonious/kld-intersections,thelonious/kld-intersections,thelonious/kld-intersections | ---
+++
@@ -5,18 +5,18 @@
Intersection = lib.Intersection;
let circle = {
- cx: new Point2D(0, 0),
- r: 50,
+ center: new Point2D(0, 0),
+ radius: 50,
};
let rectangle = {
- p1: new Point2D(0, 0),
- p2: new Point2D(60, 30)
+ topLeft: new Point2D(0, 0),
+ bottomRight: new Point2D(60, 30)
};
let result = Intersection.intersectCircleRectangle(
- circle.cx, circle.r,
- rectangle.p1, rectangle.p2
+ circle.center, circle.radius,
+ rectangle.topLeft, rectangle.bottomRight
);
console.log(result); |
fe6bb263e461b810d36fa7492e1d437dc52287e5 | migrations/0000-create-user.js | migrations/0000-create-user.js | 'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
usernamee: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Users');
}
};
| 'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
username: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Users');
}
};
| Fix a typo caused error | Fix a typo caused error
| JavaScript | mit | nowhere-cloud/node-api-gate | ---
+++
@@ -8,7 +8,7 @@
primaryKey: true,
type: Sequelize.INTEGER
},
- usernamee: {
+ username: {
type: Sequelize.STRING
},
password: { |
40d335f2cad4f73df28a6401ae1f7917072758dc | scripts/mem-test-with-levels.js | scripts/mem-test-with-levels.js |
require('babel-register');
const RG = require('../client/src/battles');
const RGTest = require('../tests/roguetest');
const fact = new RG.Factory.Base();
const levels = [];
for (let i = 0; i < 1000; i++) {
const level = fact.createLevel('arena', 100, 100);
levels.push(JSON.stringify(level.toJSON()));
if (i % 50 === 0) {
RGTest.printMemUsage(`${i} levels created`);
}
}
console.log(`Created ${levels.length} levels OK`);
RGTest.printMemUsage('END OF TEST');
|
require('babel-register');
const RG = require('../client/src/battles');
const RGTest = require('../tests/roguetest');
const fact = new RG.Factory.Base();
const levels = [];
let selectCase = 0;
if (process.argv.length > 2) {
selectCase = parseInt(process.argv[2], 10);
}
for (let i = 0; i < 1000; i++) {
const level = fact.createLevel('arena', 100, 100);
// Case 1: Pure Map.Level object
if (selectCase === 0) {levels.push(level);}
// Case 2: Serialized Map.Level object
if (selectCase === 1) {levels.push(level.toJSON());}
// Case 3: JSON stringified
if (selectCase === 2) {levels.push(JSON.stringify(level));}
if (i % 50 === 0) {
RGTest.printMemUsage(`${i} levels created`);
}
}
console.log(`Created ${levels.length} levels OK`);
RGTest.printMemUsage('END OF TEST');
| Test case can be now given from command line. | Test case can be now given from command line.
| JavaScript | mit | tpoikela/battles,tpoikela/battles,tpoikela/battles,tpoikela/battles,tpoikela/battles | ---
+++
@@ -1,7 +1,6 @@
require('babel-register');
-
const RG = require('../client/src/battles');
const RGTest = require('../tests/roguetest');
@@ -10,9 +9,20 @@
const levels = [];
+let selectCase = 0;
+if (process.argv.length > 2) {
+ selectCase = parseInt(process.argv[2], 10);
+}
+
+
for (let i = 0; i < 1000; i++) {
const level = fact.createLevel('arena', 100, 100);
- levels.push(JSON.stringify(level.toJSON()));
+ // Case 1: Pure Map.Level object
+ if (selectCase === 0) {levels.push(level);}
+ // Case 2: Serialized Map.Level object
+ if (selectCase === 1) {levels.push(level.toJSON());}
+ // Case 3: JSON stringified
+ if (selectCase === 2) {levels.push(JSON.stringify(level));}
if (i % 50 === 0) {
RGTest.printMemUsage(`${i} levels created`);
} |
4857a10de605839440a9a259a848612b53efe79c | packages/@sanity/webpack-loader/src/multiFulfillerHandler.js | packages/@sanity/webpack-loader/src/multiFulfillerHandler.js | 'use strict'
const banner = [
'/**',
' * Sanity role: ROLE_NAME',
' * ',
' * Sanity plugin loader multi-fulfiller wrapper',
' * Imports all fulfillers, then exports them as an array',
' */'
]
module.exports = function multiFulfillerHandler(opts, callback) {
const fulfillers = opts.roles.fulfilled[opts.role]
const result = banner
.concat(fulfillers.map((fulfiller, i) =>
`import fulfiller${i} from '${fulfiller.path}'`
))
.concat(['\nmodule.exports = ['])
.concat(fulfillers.map((__, i) => ` fulfiller${i}`).join(',\n'))
.concat([']\n'])
.join('\n')
.replace(/ROLE_NAME/g, opts.role)
callback(null, result)
}
| 'use strict'
const banner = [
'/**',
' * Sanity role: ROLE_NAME',
' * ',
' * Sanity plugin loader multi-fulfiller wrapper',
' * Imports all fulfillers, then exports them as an array',
' */'
]
const normalizer = [
'function normalize(mod) {',
' return mod && mod.__esModule ? mod["default"] : mod',
'}', ''
]
module.exports = function multiFulfillerHandler(opts, callback) {
const fulfillers = opts.roles.fulfilled[opts.role]
const result = banner
.concat(normalizer)
.concat(['\nmodule.exports = ['])
.concat(fulfillers.map(
(fulfiller, i) => ` require('${fulfiller.path}')`
).join(',\n'))
.concat(['].map(normalize)\n'])
.join('\n')
.replace(/ROLE_NAME/g, opts.role)
callback(null, result)
}
| Use node require over imports to skip the need for babel compiling | Use node require over imports to skip the need for babel compiling
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -9,16 +9,22 @@
' */'
]
+const normalizer = [
+ 'function normalize(mod) {',
+ ' return mod && mod.__esModule ? mod["default"] : mod',
+ '}', ''
+]
+
module.exports = function multiFulfillerHandler(opts, callback) {
const fulfillers = opts.roles.fulfilled[opts.role]
const result = banner
- .concat(fulfillers.map((fulfiller, i) =>
- `import fulfiller${i} from '${fulfiller.path}'`
- ))
+ .concat(normalizer)
.concat(['\nmodule.exports = ['])
- .concat(fulfillers.map((__, i) => ` fulfiller${i}`).join(',\n'))
- .concat([']\n'])
+ .concat(fulfillers.map(
+ (fulfiller, i) => ` require('${fulfiller.path}')`
+ ).join(',\n'))
+ .concat(['].map(normalize)\n'])
.join('\n')
.replace(/ROLE_NAME/g, opts.role)
|
f52de73995018b521786154b04c9995551a65dd7 | source/_js/modules/sign-up.js | source/_js/modules/sign-up.js | define([
'libs/bean',
'libs/bonzo',
'libs/qwery'
], function(
bean,
bonzo,
qwery
) {
var defaultValue = bonzo(qwery('.sign-up__input')).attr('value');
return {
init: function() {
this.bindEvents();
},
bindEvents: function() {
bean.on(document.body, 'focusin', '.sign-up__input', function(e) {
this.focusIn();
}.bind(this));
bean.on(document.body, 'focusout', '.sign-up__input', function(e) {
this.focusOut();
}.bind(this));
},
focusIn: function() {
bonzo(qwery('.sign-up__input')).addClass('is-focused');
if (bonzo(qwery('.sign-up__input')).attr('value') === defaultValue) {
bonzo(qwery('.sign-up__input')).attr('value', '');
}
},
focusOut: function() {
bonzo(qwery('.sign-up__input')).removeClass("is-focused");
if (bonzo(qwery('.sign-up__input')).attr('value') === '') {
bonzo(qwery('.sign-up__input')).attr('value', defaultValue);
}
}
}
}); | define([
'libs/bean',
'libs/bonzo',
'libs/qwery'
], function(
bean,
bonzo,
qwery
) {
var defaultValue = bonzo(qwery('.sign-up__input')).attr('value');
return {
init: function() {
this.bindEvents();
},
bindEvents: function() {
document.getElementsByClassName("sign-up__input")[0].onfocus = function () {
this.focusIn();
}.bind(this);
document.getElementsByClassName("sign-up__input")[0].onblur = function () {
this.focusOut();
}.bind(this);
},
focusIn: function() {
bonzo(qwery('.sign-up__input')).addClass('is-focused');
if (bonzo(qwery('.sign-up__input')).attr('value') === defaultValue) {
bonzo(qwery('.sign-up__input')).attr('value', '');
}
},
focusOut: function() {
bonzo(qwery('.sign-up__input')).removeClass("is-focused");
if (bonzo(qwery('.sign-up__input')).attr('value') === '') {
bonzo(qwery('.sign-up__input')).attr('value', defaultValue);
}
}
}
}); | Fix focus events for Firefox | Fix focus events for Firefox
| JavaScript | mit | sammorrisdesign/Monthly-mix,sammorrisdesign/Monthly-mix,sammorrisdesign/Monthly-mix | ---
+++
@@ -16,12 +16,12 @@
},
bindEvents: function() {
- bean.on(document.body, 'focusin', '.sign-up__input', function(e) {
+ document.getElementsByClassName("sign-up__input")[0].onfocus = function () {
this.focusIn();
- }.bind(this));
- bean.on(document.body, 'focusout', '.sign-up__input', function(e) {
+ }.bind(this);
+ document.getElementsByClassName("sign-up__input")[0].onblur = function () {
this.focusOut();
- }.bind(this));
+ }.bind(this);
},
focusIn: function() { |
96760d99ac0cd49384f624cfe85a104655fe00e5 | src/events/createOnDragStart.js | src/events/createOnDragStart.js | export const dataKey = 'value'
const createOnDragStart =
(name, value) =>
event => {
event.dataTransfer.setData(dataKey, value)
}
export default createOnDragStart
| export const dataKey = 'text'
const createOnDragStart =
(name, value) =>
event => {
event.dataTransfer.setData(dataKey, value)
}
export default createOnDragStart
| Change drag dataKey to 'text' | Change drag dataKey to 'text'
Bumped into https://github.com/erikras/redux-form/issues/1088 and the solution to stop these errors (and to unbreak drag and drop on IE) is to just change the dataKey to 'text.
The [stack overflow question](http://stackoverflow.com/questions/26213011/html5-dragdrop-issue-in-internet-explorer-datatransfer-property-access-not-pos) mentioned in the referenced issue suggests this as well FWIW. | JavaScript | mit | erikras/redux-form,erikras/redux-form | ---
+++
@@ -1,4 +1,4 @@
-export const dataKey = 'value'
+export const dataKey = 'text'
const createOnDragStart =
(name, value) =>
event => { |
55a818b10e50942c684db80f983a395ea2890bbd | redef/patron-client/src/frontend/components/SearchFilters.js | redef/patron-client/src/frontend/components/SearchFilters.js | import React, { PropTypes } from 'react'
import SearchFilter from './SearchFilter'
import Labels from '../constants/Labels'
export default React.createClass({
propTypes: {
filters: PropTypes.array.isRequired,
locationQuery: PropTypes.object.isRequired,
setFilter: PropTypes.func.isRequired
},
getDefaultProps () {
return {
filters: []
}
},
renderEmpty () {
return <div data-automation-id='empty'></div>
},
render () {
let groupedFilters = {}
if (this.props.locationQuery.query && this.props.filters) {
this.props.filters.forEach(filter => {
groupedFilters[ filter.aggregation ] = groupedFilters[ filter.aggregation ] || []
groupedFilters[ filter.aggregation ].push(filter)
})
return (
<aside className='col filters'>
<h3>Avgrens sΓΈket ditt</h3>
<div data-automation-id='search_filters'>
{Object.keys(groupedFilters).map(aggregation => {
let filtersByAggregation = groupedFilters[ aggregation ]
return (
<SearchFilter
key={aggregation}
title={Labels[aggregation]}
aggregation={aggregation}
filters={filtersByAggregation}
locationQuery={this.props.locationQuery}
setFilter={this.props.setFilter}/>
)
})}
</div>
</aside>
)
} else {
return this.renderEmpty()
}
}
})
| import React, { PropTypes } from 'react'
import SearchFilter from './SearchFilter'
import Labels from '../constants/Labels'
export default React.createClass({
propTypes: {
filters: PropTypes.array.isRequired,
locationQuery: PropTypes.object.isRequired,
setFilter: PropTypes.func.isRequired
},
getDefaultProps () {
return {
filters: []
}
},
renderEmpty () {
return <div data-automation-id='empty'></div>
},
render () {
let groupedFilters = {}
if (this.props.locationQuery.query && this.props.filters) {
this.props.filters.forEach(filter => {
groupedFilters[ filter.aggregation ] = groupedFilters[ filter.aggregation ] || []
groupedFilters[ filter.aggregation ].push(filter)
})
return (
<aside className='col filters'>
<h3>Avgrens sΓΈket ditt</h3>
<div data-automation-id='search_filters'>
{Object.keys(groupedFilters).map(aggregation => {
let filtersByAggregation = groupedFilters[ aggregation ]
return (
<SearchFilter
key={aggregation}
title={Labels[aggregation] || aggregation}
aggregation={aggregation}
filters={filtersByAggregation}
locationQuery={this.props.locationQuery}
setFilter={this.props.setFilter}/>
)
})}
</div>
</aside>
)
} else {
return this.renderEmpty()
}
}
})
| Add fallback on filter names | Patron-client: Add fallback on filter names
| JavaScript | mit | digibib/ls.ext,digibib/ls.ext,digibib/ls.ext,digibib/ls.ext | ---
+++
@@ -34,7 +34,7 @@
return (
<SearchFilter
key={aggregation}
- title={Labels[aggregation]}
+ title={Labels[aggregation] || aggregation}
aggregation={aggregation}
filters={filtersByAggregation}
locationQuery={this.props.locationQuery} |
6cc25b6d16cb0aad4a1bded14bb754bc4fc476f6 | addons/notes/src/index.js | addons/notes/src/index.js | import addons, { makeDecorator } from '@storybook/addons';
import marked from 'marked';
function renderMarkdown(text, options) {
marked.setOptions({ ...marked.defaults, options });
return marked(text);
}
export const withNotes = makeDecorator({
name: 'withNotes',
parameterName: 'notes',
skipIfNoParametersOrOptions: true,
allowDeprecatedUsage: true,
wrapper: (getStory, context, { options, parameters }) => {
const channel = addons.getChannel();
const storyOptions = parameters || options;
const { text, markdown, markdownOptions } =
typeof storyOptions === 'string' ? { text: storyOptions } : storyOptions;
if (!text && !markdown) {
throw new Error('You must set of one of `text` or `markdown` on the `notes` parameter');
}
channel.emit('storybook/notes/add_notes', text || renderMarkdown(markdown, markdownOptions));
return getStory(context);
},
});
export const withMarkdownNotes = (text, options) =>
withNotes({
markdown: text,
markdownOptions: options,
});
| import addons, { makeDecorator } from '@storybook/addons';
import marked from 'marked';
function renderMarkdown(text, options) {
return marked(text, { ...marked.defaults, ...options });
}
export const withNotes = makeDecorator({
name: 'withNotes',
parameterName: 'notes',
skipIfNoParametersOrOptions: true,
allowDeprecatedUsage: true,
wrapper: (getStory, context, { options, parameters }) => {
const channel = addons.getChannel();
const storyOptions = parameters || options;
const { text, markdown, markdownOptions } =
typeof storyOptions === 'string' ? { text: storyOptions } : storyOptions;
if (!text && !markdown) {
throw new Error('You must set of one of `text` or `markdown` on the `notes` parameter');
}
channel.emit('storybook/notes/add_notes', text || renderMarkdown(markdown, markdownOptions));
return getStory(context);
},
});
export const withMarkdownNotes = (text, options) =>
withNotes({
markdown: text,
markdownOptions: options,
});
| Fix how markdownOptions are passed to marked | Fix how markdownOptions are passed to marked
Previously, the options have been passed as property "options" within the actual options object, which is ignored by marked.
Also, using the parameter of marked instead of setOptions to avoid global state. | JavaScript | mit | storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook | ---
+++
@@ -2,8 +2,7 @@
import marked from 'marked';
function renderMarkdown(text, options) {
- marked.setOptions({ ...marked.defaults, options });
- return marked(text);
+ return marked(text, { ...marked.defaults, ...options });
}
export const withNotes = makeDecorator({ |
517554f05446ecc9f9c3dd850293cdeb5b5a87ea | app/lib/database/index.js | app/lib/database/index.js | var cradle = require('cradle');
var applyDesignDocuments = require('./design-documents');
var couchLocation = process.env.COUCHDB || process.env.CLOUDANT_URL;
var couch = new(cradle.Connection)(couchLocation, 5984, {
cache: true,
raw: false
});
var db = couch.database('emergencybadges');
db.setup = function (callback) {
db.exists(function (err, exists) {
if (err) {
console.log('error', err);
} else if (exists) {
console.log('Database exists.');
if (typeof callback === 'function') callback();
} else {
console.log('Database does not exist. Creating.');
db.create(function (err, res) {
if (!err) {
applyDesignDocuments(db);
if (typeof callback === 'function') callback();
}
});
}
});
};
db.updateDesignDocuments = function (callback) {
applyDesignDocuments(db);
if (typeof callback === 'function') callback();
};
module.exports = db; | var cradle = require('cradle');
var applyDesignDocuments = require('./design-documents');
var couchLocation = process.env.CLOUDANT_URL || process.env.COUCHDB || 'http://localhost';
var couch = new(cradle.Connection)(couchLocation, 5984, {
cache: true,
raw: false
});
var db = couch.database('emergencybadges');
db.setup = function (callback) {
db.exists(function (err, exists) {
if (err) {
console.log('error', err);
} else if (exists) {
console.log('Database exists.');
if (typeof callback === 'function') callback();
} else {
console.log('Database does not exist. Creating.');
db.create(function (err, res) {
if (!err) {
applyDesignDocuments(db);
if (typeof callback === 'function') callback();
}
});
}
});
};
db.updateDesignDocuments = function (callback) {
applyDesignDocuments(db);
if (typeof callback === 'function') callback();
};
module.exports = db; | Change order of Couch locations | Change order of Couch locations
| JavaScript | mpl-2.0 | rockawayhelp/emergencybadges,rockawayhelp/emergencybadges | ---
+++
@@ -1,7 +1,7 @@
var cradle = require('cradle');
var applyDesignDocuments = require('./design-documents');
-var couchLocation = process.env.COUCHDB || process.env.CLOUDANT_URL;
+var couchLocation = process.env.CLOUDANT_URL || process.env.COUCHDB || 'http://localhost';
var couch = new(cradle.Connection)(couchLocation, 5984, {
cache: true,
raw: false |
fee19fd577b5b43fb94a2b9729981441c2e0bd8d | app/models/task-detail.js | app/models/task-detail.js | import DS from "ember-data";
export default DS.Model.extend( {
body: DS.attr("string"),
solution: DS.attr("string"),
thread: DS.belongsTo("thread", { async: true }),
modules: DS.hasMany("module"),
best_scores: DS.hasMany("user-score"), // Top 5
comment: DS.belongsTo("thread", { async: true }),
achievements: DS.hasMany("achievements", { async: true })
});
| import DS from "ember-data";
export default DS.Model.extend( {
body: DS.attr("string"),
solution: DS.attr("string"),
thread: DS.belongsTo("thread"),
modules: DS.hasMany("module"),
best_scores: DS.hasMany("user-score"), // Top 5
comment: DS.belongsTo("thread"),
achievements: DS.hasMany("achievements", { async: true })
});
| Make comment and task thread included | Make comment and task thread included
| JavaScript | mit | fi-ksi/web-frontend,fi-ksi/web-frontend,fi-ksi/web-frontend | ---
+++
@@ -3,11 +3,11 @@
export default DS.Model.extend( {
body: DS.attr("string"),
solution: DS.attr("string"),
- thread: DS.belongsTo("thread", { async: true }),
+ thread: DS.belongsTo("thread"),
modules: DS.hasMany("module"),
best_scores: DS.hasMany("user-score"), // Top 5
- comment: DS.belongsTo("thread", { async: true }),
+ comment: DS.belongsTo("thread"),
achievements: DS.hasMany("achievements", { async: true })
}); |
3db52d56f46609c7c658eeca8032a3142a89f79f | packages/version/index.js | packages/version/index.js | const fs = require('fs');
const path = require('path');
let version;
module.exports = () => {
if (!version) {
version = `v${require(path.join(process.cwd(), 'package.json')).version}`;
try {
version += '-' + fs.readFileSync(path.join(process.cwd(), 'REVISION'), 'utf-8');
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
}
return version;
};
| const fs = require('fs');
const path = require('path');
let version;
module.exports = () => {
if (!version) {
version = `v${require(path.join(process.cwd(), 'package.json')).version}`;
try {
version += '-' + fs.readFileSync(path.join(process.cwd(), 'REVISION'), 'utf-8').trim();
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
}
return version;
};
| Trim revision string in version package | Trim revision string in version package
| JavaScript | mit | maxdome/maxdome-node,maxdome/maxdome-node | ---
+++
@@ -6,7 +6,7 @@
if (!version) {
version = `v${require(path.join(process.cwd(), 'package.json')).version}`;
try {
- version += '-' + fs.readFileSync(path.join(process.cwd(), 'REVISION'), 'utf-8');
+ version += '-' + fs.readFileSync(path.join(process.cwd(), 'REVISION'), 'utf-8').trim();
} catch (e) {
if (e.code !== 'ENOENT') {
throw e; |
94ebc193a331c50a9c4648fcf6024eb807cb4a4f | config/karma-e2e.conf.js | config/karma-e2e.conf.js | // base path, that will be used to resolve files and exclude
basePath = '../';
// list of files / patterns to load in the browser
files = [
ANGULAR_SCENARIO,
ANGULAR_SCENARIO_ADAPTER,
'test/e2e/*.spec.js'
];
// list of files to exclude
exclude = [];
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters = ['progress'];
// web server port
port = 9877;
// cli runner port
runnerPort = 9101;
// enable / disable colors in the output (reporters and logs)
colors = true;
urlRoot = '/__karma/';
proxies = {
'/': 'http://localhost:3000/'
};
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = false;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = true; | // base path, that will be used to resolve files and exclude
basePath = '../';
// list of files / patterns to load in the browser
files = [
ANGULAR_SCENARIO,
ANGULAR_SCENARIO_ADAPTER,
'test/e2e/*.spec.js'
];
// list of files to exclude
exclude = [];
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters = ['progress'];
// web server port
port = 9877;
// cli runner port
runnerPort = 9101;
// enable / disable colors in the output (reporters and logs)
colors = true;
urlRoot = '/__karma/';
proxies = {
'/': 'http://localhost:3000/'
};
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = false;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['PhantomJS'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = true;
| Migrate to PhantomJS for testing in travis | Migrate to PhantomJS for testing in travis
| JavaScript | mit | qloo/angular-prevent-default,jackvsworld/angular-prevent-default,minddistrict/angular-prevent-default,jackvsworld/angular-prevent-default | ---
+++
@@ -55,7 +55,7 @@
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
-browsers = ['Chrome'];
+browsers = ['PhantomJS'];
// If browser does not capture in given timeout [ms], kill it |
b963eb61d7cfb35b992ee6b094800eadd207f752 | src/main/webapp/resources/js/pages/projects/samples/index.js | src/main/webapp/resources/js/pages/projects/samples/index.js | import React from "react";
import { render } from "react-dom";
import ProjectSamples from "./components/ProjectSamples";
import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import { Provider } from "react-redux";
import { samplesApi } from "../../../apis/projects/samples";
import { associatedProjectsApi } from "../../../apis/projects/associated-projects";
import samplesReducer from "../redux/samplesSlice";
import userReducer from "../redux/userSlice";
import { projectApi } from "../../../apis/projects/project";
export const store = configureStore({
reducer: {
user: userReducer,
samples: samplesReducer,
[projectApi.reducerPath]: projectApi.reducer,
[samplesApi.reducerPath]: samplesApi.reducer,
[associatedProjectsApi.reducerPath]: associatedProjectsApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(
samplesApi.middleware,
associatedProjectsApi.middleware
),
devTools: process.env.NODE_ENV !== "production",
});
setupListeners(store.dispatch);
render(
<Provider store={store}>
<ProjectSamples />
</Provider>,
document.getElementById("root")
);
| import React from "react";
import { render } from "react-dom";
import ProjectSamples from "./components/ProjectSamples";
import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import { Provider } from "react-redux";
import { samplesApi } from "../../../apis/projects/samples";
import { associatedProjectsApi } from "../../../apis/projects/associated-projects";
import samplesReducer from "../redux/samplesSlice";
import { projectApi } from "../../../apis/projects/project";
export const store = configureStore({
reducer: {
samples: samplesReducer,
[projectApi.reducerPath]: projectApi.reducer,
[samplesApi.reducerPath]: samplesApi.reducer,
[associatedProjectsApi.reducerPath]: associatedProjectsApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(
samplesApi.middleware,
associatedProjectsApi.middleware
),
devTools: process.env.NODE_ENV !== "production",
});
setupListeners(store.dispatch);
render(
<Provider store={store}>
<ProjectSamples />
</Provider>,
document.getElementById("root")
);
| Remove user slice since since not used | Remove user slice since since not used
| JavaScript | apache-2.0 | phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida | ---
+++
@@ -7,12 +7,10 @@
import { samplesApi } from "../../../apis/projects/samples";
import { associatedProjectsApi } from "../../../apis/projects/associated-projects";
import samplesReducer from "../redux/samplesSlice";
-import userReducer from "../redux/userSlice";
import { projectApi } from "../../../apis/projects/project";
export const store = configureStore({
reducer: {
- user: userReducer,
samples: samplesReducer,
[projectApi.reducerPath]: projectApi.reducer,
[samplesApi.reducerPath]: samplesApi.reducer, |
ffc2fc89e92c4e53756d7ceae34c0c881d0bbbd0 | models/xeroaccount_model.js | models/xeroaccount_model.js | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var Location = require('./location_model');
var XeroAccountSchema = new Schema({
location_id: { type: ObjectId, ref: 'Location' },
consumer_key: String,
consumer_secret: String
});
XeroAccountSchema.set("_perms", {
super_user: "crud",
admin: "r",
all: ""
});
module.exports = mongoose.model('XeroAccount', XeroAccountSchema); | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var Location = require('./location_model');
var XeroAccountSchema = new Schema({
location_id: { type: ObjectId, ref: 'Location' },
consumer_key: String,
consumer_secret: String
});
XeroAccountSchema.set("_perms", {
super_user: "crud",
admin: "r",
user: "r",
all: ""
});
module.exports = mongoose.model('XeroAccount', XeroAccountSchema); | Allow users to read xeroaccount for booking | Allow users to read xeroaccount for booking
| JavaScript | mit | 10layer/jexpress,10layer/jexpress | ---
+++
@@ -13,6 +13,7 @@
XeroAccountSchema.set("_perms", {
super_user: "crud",
admin: "r",
+ user: "r",
all: ""
});
|
c8f35e508b1584f39a9812c1c49349114b2bfcbf | src/components/FloorplanUI.js | src/components/FloorplanUI.js | // @flow
import React from 'react';
import styled from 'styled-components';
const Wrapper = styled.div`
position: absolute;
display: flex;
flex-direction: column;
justify-content: center;
top: 0;
left: 0;
padding: 8px;
`;
const ZoomButton = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 40px;
height: 40px;
border-radius: 50%;
background-color: #ccc;
border: 1px solid #000000;
cursor: pointer;
text-align: center;
margin: 0 0 8px 0;
`;
type Props = {
zoomIn: (val: number) => void,
zoomOut: (val: number) => void,
}
export default class FloorplanUI extends React.Component {
props: Props;
render() {
return (
<Wrapper>
<ZoomButton onClick={() => this.props.zoomIn(0.5)}>+</ZoomButton>
<ZoomButton onClick={() => this.props.zoomOut(0.5)}>-</ZoomButton>
</Wrapper>
);
}
}
| // @flow
import React from 'react';
import styled from 'styled-components';
const ZoomButtons = styled.div`
position: absolute;
display: flex;
flex-direction: column;
justify-content: center;
top: 0;
left: 0;
padding: 8px;
`;
const ZoomButton = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 40px;
height: 40px;
border-radius: 50%;
background-color: #ccc;
border: 1px solid #000000;
cursor: pointer;
text-align: center;
margin: 0 0 8px 0;
`;
const Tooltip = styled.div`
position: absolute;
display: flex;
justify-content: center;
left: ${props => props.x}px;
top: ${props => props.y}px;
background-color: #000000;
color: #ffffff;
padding: 8px;
border-radius: 4px;
opacity: 0.8;
`;
type Props = {
zoomIn: (val: number) => void,
zoomOut: (val: number) => void,
}
export default class FloorplanUI extends React.Component {
props: Props;
render() {
return (
<div>
<ZoomButtons>
<ZoomButton onClick={() => this.props.zoomIn(0.5)}>+</ZoomButton>
<ZoomButton onClick={() => this.props.zoomOut(0.5)}>-</ZoomButton>
</ZoomButtons>
<Tooltip x={400} y={300}>
{"Zergov | C-30"}
</Tooltip>
</div>
);
}
}
| Add tooltip mockup and ui component | Add tooltip mockup and ui component
| JavaScript | unknown | lanets/floorplan-2,lanets/floorplanets,lanets/floorplan-2,lanets/floorplanets,lanets/floorplan-2,lanets/floorplanets | ---
+++
@@ -3,7 +3,7 @@
import styled from 'styled-components';
-const Wrapper = styled.div`
+const ZoomButtons = styled.div`
position: absolute;
display: flex;
flex-direction: column;
@@ -27,6 +27,19 @@
margin: 0 0 8px 0;
`;
+const Tooltip = styled.div`
+ position: absolute;
+ display: flex;
+ justify-content: center;
+ left: ${props => props.x}px;
+ top: ${props => props.y}px;
+ background-color: #000000;
+ color: #ffffff;
+ padding: 8px;
+ border-radius: 4px;
+ opacity: 0.8;
+`;
+
type Props = {
zoomIn: (val: number) => void,
@@ -39,10 +52,15 @@
render() {
return (
- <Wrapper>
- <ZoomButton onClick={() => this.props.zoomIn(0.5)}>+</ZoomButton>
- <ZoomButton onClick={() => this.props.zoomOut(0.5)}>-</ZoomButton>
- </Wrapper>
+ <div>
+ <ZoomButtons>
+ <ZoomButton onClick={() => this.props.zoomIn(0.5)}>+</ZoomButton>
+ <ZoomButton onClick={() => this.props.zoomOut(0.5)}>-</ZoomButton>
+ </ZoomButtons>
+ <Tooltip x={400} y={300}>
+ {"Zergov | C-30"}
+ </Tooltip>
+ </div>
);
}
} |
ae6bc681638ab96f274ae083cedcf6d86d42c3dd | src/core/reducers/keyboard.js | src/core/reducers/keyboard.js | import { KEYBINDING_UPDATE } from 'core/actions/types';
import { defaultCommands } from './defaults';
export default function keyboardConfigReducer(
state = defaultCommands,
action,
) {
if (action.type !== KEYBINDING_UPDATE || !(command in state)) {
return state;
}
const { command, keyBinding } = action.payload;
const newCommand = Object.assign({}, state[command], { command: keyBinding });
return Object.assign(
{},
state,
{ [command]: newCommand },
);
}
| import { KEYBINDING_UPDATE, KEYBINDING_DEFAULT_RESET } from 'core/actions/types';
import { defaultCommands } from './defaults';
export default function keyboardConfigReducer(
state = defaultCommands,
action,
) {
const { type } = action;
switch (type) {
case KEYBINDING_UPDATE: {
const { command, keyBinding } = action.payload;
return Object.assign(
{},
state,
{ [command]: Object.assign({}, state[command], { command: keyBinding }) },
);
}
case KEYBINDING_DEFAULT_RESET:
return defaultCommands;
default:
return state;
}
}
| Use switch-case for handling actions | Use switch-case for handling actions
| JavaScript | mit | reblws/tab-search,reblws/tab-search | ---
+++
@@ -1,18 +1,23 @@
-import { KEYBINDING_UPDATE } from 'core/actions/types';
+import { KEYBINDING_UPDATE, KEYBINDING_DEFAULT_RESET } from 'core/actions/types';
import { defaultCommands } from './defaults';
export default function keyboardConfigReducer(
state = defaultCommands,
action,
) {
- if (action.type !== KEYBINDING_UPDATE || !(command in state)) {
- return state;
+ const { type } = action;
+ switch (type) {
+ case KEYBINDING_UPDATE: {
+ const { command, keyBinding } = action.payload;
+ return Object.assign(
+ {},
+ state,
+ { [command]: Object.assign({}, state[command], { command: keyBinding }) },
+ );
+ }
+ case KEYBINDING_DEFAULT_RESET:
+ return defaultCommands;
+ default:
+ return state;
}
- const { command, keyBinding } = action.payload;
- const newCommand = Object.assign({}, state[command], { command: keyBinding });
- return Object.assign(
- {},
- state,
- { [command]: newCommand },
- );
} |
174750770ae42a0b4ae1969c5ac2be5e7364bf0e | bin/vwp.js | bin/vwp.js | const Path = require('path')
const action = process.argv[2]
var args = process.argv.slice(3)
var env, bin
switch (action) {
case 'build':
bin = 'webpack'
env = 'production'
break
case 'dist':
case 'stats':
bin = 'webpack'
env = 'production'
args.push('-p')
break
case 'dev':
case 'start':
bin = 'webpack-dev-server'
env = 'development'
args.push('--hot')
break
case '--version':
case '-v':
console.log(require('../package.json').version)
process.exit(1)
return
default:
console.log('missing command: build, dev or dist')
process.exit(1)
}
var cmd = []
if (!process.env.NODE_ENV) {
cmd.push(`NODE_ENV=${env}`) // add NODE_ENV only if not already defined
}
cmd.push(require.resolve(`.bin/${bin}`))
cmd.push('--config')
cmd.push(Path.resolve(__dirname, '../webpackfile.js'))
cmd.push('--progress')
if (action === 'stats') {
cmd.push('--profile', '--json')
} else if (bin === 'webpack') {
cmd.push('--hide-modules') // webpack-dev-server does not have hide-modules
}
cmd.push(...args)
console.log(cmd.join(' '))
| const Path = require('path')
const action = process.argv[2]
var args = process.argv.slice(3)
var env, bin
switch (action) {
case 'build':
bin = 'webpack'
env = 'production'
break
case 'dist':
case 'stats':
bin = 'webpack'
env = 'production'
args.push('-p')
break
case 'dev':
case 'start':
bin = 'webpack-dev-server'
env = 'development'
args.push('--hot')
break
case '--version':
case '-v':
console.log(require('../package.json').version)
process.exit(1)
return
default:
console.log('missing command: build, dev, dist or stats')
process.exit(1)
}
var cmd = []
if (!process.env.NODE_ENV) {
cmd.push(`NODE_ENV=${env}`) // add NODE_ENV only if not already defined
}
cmd.push(require.resolve(`.bin/${bin}`))
cmd.push('--config')
cmd.push(Path.resolve(__dirname, '../webpackfile.js'))
cmd.push('--progress')
if (action === 'stats') {
cmd.push('--profile', '--json')
} else if (bin === 'webpack') {
cmd.push('--hide-modules') // webpack-dev-server does not have hide-modules
}
cmd.push(...args)
console.log(cmd.join(' '))
| Add stats command to help | Add stats command to help
| JavaScript | mit | neves/vwp,neves/vwp | ---
+++
@@ -31,7 +31,7 @@
return
default:
- console.log('missing command: build, dev or dist')
+ console.log('missing command: build, dev, dist or stats')
process.exit(1)
}
|
0dc2b1f648a0d7fe74a8c2bc15da318b1a63e048 | server/methods/users.js | server/methods/users.js | Meteor.methods({
'addFirstUserToAdminRole': function () {
/*
Look for existing users and set initial user as admin
*/
// Count registered users
var userCount = Meteor.users().count();
// If there is only one user
if (userCount === 1) {
// Get the only user
var user = Meteor.users.findOne();
// Get the user's roles
var userRoles = Roles.getRolesForUser(user);
// Define the admin role
// TODO: refactor this to take the role name as input parameter
// TODO: create role if it doesnt exist
var adminRole = 'admin';
// Check if current user is admin
var userIsAdmin = _.contains(userRoles, adminRole);
// If user is not admin
if (!userIsAdmin) {
// Add user to admin role
Roles.addUsersToRoles(userId, ['admin']);
console.log("Added first user as admin.");
} else {
console.log("First user already has admin role.")
}
}
}
});
| Meteor.methods({
'addFirstUserToAdminRole': function (adminRole) {
/*
Look for existing users and set initial user as admin
*/
// Set default admin role if none provided
var adminRole = adminRole || 'admin';
// Create admin role if not existing
Meteor.call('createRoleIfNotExisting', adminRole);
// Count registered users
var userCount = Meteor.users().count();
// If there is only one user
if (userCount === 1) {
// Get the only user
var user = Meteor.users.findOne();
// Get the user's roles
var userRoles = Roles.getRolesForUser(user);
// Check if current user is admin
var userIsAdmin = _.contains(userRoles, adminRole);
// If user is not admin
if (!userIsAdmin) {
// Add user to admin role
Roles.addUsersToRoles(userId, [adminRole]);
console.log("Added first user as admin.");
} else {
console.log("First user already has admin role.")
}
}
}
});
| Allow adminRole argument; create role if needed | Allow adminRole argument; create role if needed
| JavaScript | mit | brylie/meteor-first-user-admin | ---
+++
@@ -1,8 +1,14 @@
Meteor.methods({
- 'addFirstUserToAdminRole': function () {
+ 'addFirstUserToAdminRole': function (adminRole) {
/*
Look for existing users and set initial user as admin
*/
+
+ // Set default admin role if none provided
+ var adminRole = adminRole || 'admin';
+
+ // Create admin role if not existing
+ Meteor.call('createRoleIfNotExisting', adminRole);
// Count registered users
var userCount = Meteor.users().count();
@@ -15,18 +21,13 @@
// Get the user's roles
var userRoles = Roles.getRolesForUser(user);
- // Define the admin role
- // TODO: refactor this to take the role name as input parameter
- // TODO: create role if it doesnt exist
- var adminRole = 'admin';
-
// Check if current user is admin
var userIsAdmin = _.contains(userRoles, adminRole);
// If user is not admin
if (!userIsAdmin) {
// Add user to admin role
- Roles.addUsersToRoles(userId, ['admin']);
+ Roles.addUsersToRoles(userId, [adminRole]);
console.log("Added first user as admin.");
} else {
console.log("First user already has admin role.") |
04a43ec149c38f5acc013237899cfbe6822af91a | iscan/static/iscan/env.js | iscan/static/iscan/env.js | (function (window) {
window.__env = window.__env || {};
if (window.location.port) {
window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/';
}
else {
window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + '/';
}
window.__env.apiUrl = window.__env.hostUrl + 'api/';
window.__env.intontationUrl = window.__env.hostUrl + 'intonation/';
window.__env.annotatorUrl = window.__env.hostUrl + 'annotator/api/';
window.__env.baseUrl = '/';
window.__env.siteName = 'ISCAN';
window.__env.enableDebug = true;
}(this));
| (function (window) {
window.__env = window.__env || {};
if (window.location.port) {
window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + window.location.pathname;
}
else {
window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + '/';
}
window.__env.apiUrl = window.__env.hostUrl + 'api/';
window.__env.intontationUrl = window.__env.hostUrl + 'intonation/';
window.__env.annotatorUrl = window.__env.hostUrl + 'annotator/api/';
window.__env.baseUrl = '/';
window.__env.siteName = 'ISCAN';
window.__env.enableDebug = true;
}(this));
| Fix for pathnames other than "/" | Fix for pathnames other than "/"
| JavaScript | mit | MontrealCorpusTools/polyglot-server,MontrealCorpusTools/polyglot-server,MontrealCorpusTools/polyglot-server,MontrealCorpusTools/polyglot-server | ---
+++
@@ -1,7 +1,7 @@
(function (window) {
window.__env = window.__env || {};
if (window.location.port) {
- window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/';
+ window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + window.location.pathname;
}
else {
window.__env.hostUrl = window.location.protocol + '//' + window.location.hostname + '/'; |
cc0c2a5263509b9c32b2e58962545034ede91ef6 | public/javascript/Body.js | public/javascript/Body.js | import Vector from "./Vector.js";
import * as constants from "./constants";
import * as pointUtils from "./pointUtils";
import * as movementUtils from "./movementUtils";
let initNum = 0;
export default class Body {
constructor(game, center, options = {}) {
this.game = game;
this.center = center;
this.isAlive = true;
this.type = "body";
this.id = initNum;
this.mass = constants.EarthMass / 100;
this.radius = this.mass / constants.EarthMass * constants.EarthRadius;
this.speed = options.initialSpeed;
initNum++;
}
update(timeSinceUpdate) {
const affectingObjects = this.game.attractors.concat(this.game.deflectors);
let { acceleration, delta } = movementUtils.moveObject(this,
timeSinceUpdate,
affectingObjects);
let min = 255;
let max = 360;
let hue = Math.min(acceleration / max, 1) * (max - min) + min;
this.color = `hsl(${hue}, 100%, 70%)`;
this.isAlive = !pointUtils.willCollide(this, delta, affectingObjects);
}
} | import Vector from "./Vector.js";
import * as constants from "./constants";
import * as pointUtils from "./pointUtils";
import * as movementUtils from "./movementUtils";
let initNum = 0;
export default class Body {
constructor(game, center, options = {}) {
this.game = game;
this.center = center;
this.isAlive = true;
this.type = "body";
this.id = initNum;
this.mass = constants.EarthMass / 100;
this.radius = this.mass / constants.EarthMass * constants.EarthRadius;
this.speed = options.initialSpeed || new Vector(
7000,
Math.PI,
"m/s"
);
initNum++;
}
update(timeSinceUpdate) {
const affectingObjects = this.game.attractors.concat(this.game.deflectors);
let { acceleration, delta } = movementUtils.moveObject(this,
timeSinceUpdate,
affectingObjects);
let min = 255;
let max = 360;
let hue = Math.min(acceleration / max, 1) * (max - min) + min;
this.color = `hsl(${hue}, 100%, 70%)`;
this.isAlive = !pointUtils.willCollide(this, delta, affectingObjects);
}
} | Fix everything breaking when a body is created without an initialSpeed | Fix everything breaking when a body is created without an initialSpeed
| JavaScript | mit | Mark-Simulacrum/gravity-simulator,Mark-Simulacrum/gravity-simulator | ---
+++
@@ -17,7 +17,11 @@
this.mass = constants.EarthMass / 100;
this.radius = this.mass / constants.EarthMass * constants.EarthRadius;
- this.speed = options.initialSpeed;
+ this.speed = options.initialSpeed || new Vector(
+ 7000,
+ Math.PI,
+ "m/s"
+ );
initNum++;
} |
613a39031fc6322f04cf6730bbc09d9b984d313f | controllers/settings/general.js | controllers/settings/general.js | var SettingsGeneralController = Ember.ObjectController.extend({
isDatedPermalinks: function (key, value) {
// setter
if (arguments.length > 1) {
this.set('permalinks', value ? '/:year/:month/:day/:slug/' : '/:slug/');
}
// getter
var slugForm = this.get('permalinks');
return slugForm !== '/:slug/';
}.property('permalinks'),
themes: function () {
return this.get('availableThemes').reduce(function (themes, t) {
var theme = {};
theme.name = t.name;
theme.label = t.package ? t.package.name + ' - ' + t.package.version : t.name;
theme.package = t.package;
theme.active = !!t.active;
themes.push(theme);
return themes;
}, []);
}.property('availableThemes').readOnly(),
actions: {
save: function () {
var self = this;
return this.get('model').save().then(function (model) {
self.notifications.closePassive();
self.notifications.showSuccess('Settings successfully saved.');
return model;
}).catch(function (errors) {
self.notifications.closePassive();
self.notifications.showErrors(errors);
});
},
}
});
export default SettingsGeneralController;
| var SettingsGeneralController = Ember.ObjectController.extend({
isDatedPermalinks: function (key, value) {
// setter
if (arguments.length > 1) {
this.set('permalinks', value ? '/:year/:month/:day/:slug/' : '/:slug/');
}
// getter
var slugForm = this.get('permalinks');
return slugForm !== '/:slug/';
}.property('permalinks'),
themes: function () {
return this.get('availableThemes').reduce(function (themes, t) {
var theme = {};
theme.name = t.name;
theme.label = t.package ? t.package.name + ' - ' + t.package.version : t.name;
theme.package = t.package;
theme.active = !!t.active;
themes.push(theme);
return themes;
}, []);
}.property().readOnly(),
actions: {
save: function () {
var self = this;
return this.get('model').save().then(function (model) {
self.notifications.closePassive();
self.notifications.showSuccess('Settings successfully saved.');
return model;
}).catch(function (errors) {
self.notifications.closePassive();
self.notifications.showErrors(errors);
});
},
}
});
export default SettingsGeneralController;
| Fix active theme selector. Add validation to API. | Fix active theme selector. Add validation to API.
Closes #3226
- Remove dependent property from the computed content property
that is used to build the active theme selector.
- Add validation to the Settings model so that it rejects
attempts to set an activeTheme that is not installed.
| JavaScript | mit | dbalders/Ghost-Admin,airycanon/Ghost-Admin,JohnONolan/Ghost-Admin,airycanon/Ghost-Admin,TryGhost/Ghost-Admin,kevinansfield/Ghost-Admin,JohnONolan/Ghost-Admin,acburdine/Ghost-Admin,acburdine/Ghost-Admin,dbalders/Ghost-Admin,kevinansfield/Ghost-Admin,TryGhost/Ghost-Admin | ---
+++
@@ -24,7 +24,7 @@
return themes;
}, []);
- }.property('availableThemes').readOnly(),
+ }.property().readOnly(),
actions: {
save: function () { |
f42add059011861b4db0d49c6d328619f70038bc | public/js/teleprompter.js | public/js/teleprompter.js | $(document).ready(function () {
$('textarea').focus();
$('form').on('submit', function (event) {
event.preventDefault();
var text = $('textarea').val();
var y = 0;
if (text == '') {
text = 'You should probably enter some text next time.'
}
$('header a').addClass('dark');
$('body').css('background-color', '#090919');
$('#container').html('<div id="teleprompt_screen">' + text + '</div>')
scrollText(y);
function scrollText(y) {
setTimeout(function () {
var newY = y;
var height = $('#teleprompt_screen').height();
if (newY > -1 * height - 150) {
newY -= 1;
$('#teleprompt_screen').css('top', newY);
scrollText(newY);
}
}, 30);
};
});
// get the height of the screen
// move the text up the screen by changing the top CSS
}); | $(document).ready(function () {
$('textarea').focus();
$('form').on('submit', function (event) {
event.preventDefault();
var text = $('textarea').val();
var y = 0;
if (text.replace(/^\s+|\s+$/g, '') == '') {
text = 'You should probably enter some text next time.'
}
$('header a').addClass('dark');
$('body').css('background-color', '#090919');
$('#container').html('<div id="teleprompt_screen">' + text + '</div>')
scrollText(y);
function scrollText(y) {
setTimeout(function () {
var newY = y;
var height = $('#teleprompt_screen').height();
if (newY > -1 * height - 150) {
newY -= 1;
$('#teleprompt_screen').css('top', newY);
scrollText(newY);
}
}, 30);
};
});
// get the height of the screen
// move the text up the screen by changing the top CSS
}); | Expand check for empty strings | Expand check for empty strings
| JavaScript | mit | jendewalt/jennifer_dewalt,cgvarela/jennifer_dewalt,cgvarela/jennifer_dewalt,altairn5/jennifer_dewalt,Jessieca/jennifer_dewalt,Jessieca/jennifer_dewalt,Jessieca/jennifer_dewalt,altairn5/jennifer_dewalt,jendewalt/jennifer_dewalt,altairn5/jennifer_dewalt,jendewalt/jennifer_dewalt,cgvarela/jennifer_dewalt | ---
+++
@@ -7,7 +7,7 @@
var text = $('textarea').val();
var y = 0;
- if (text == '') {
+ if (text.replace(/^\s+|\s+$/g, '') == '') {
text = 'You should probably enter some text next time.'
}
|
4760d6baeba25706dc6268af3f64e97a7c009dab | steps/ast-builders/templates/node-def-cjs.js | steps/ast-builders/templates/node-def-cjs.js | var node = nodeDefinitions(
function(globalId, ast) {
var gid = fromGlobalId(globalId);
var fieldKind = gid.id.match(/^[0-9]+$/) ? 'IntValue' : 'StringValue';
var override = { arguments: [{ name: { value: 'id' }, value: { value: id, kind: fieldKind } }] };
return getEntityResolver(gid.type)(null, {}, ast, override);
},
function(data) {
return data.__type;
}
);
var nodeInterface = node.nodeInterface;
var nodeField = node.nodeField;
| var node = nodeDefinitions(
function(globalId, ast) {
var gid = fromGlobalId(globalId);
var fieldKind = gid.id.match(/^[0-9]+$/) ? 'IntValue' : 'StringValue';
var override = { arguments: [{ name: { value: 'id' }, value: { value: gid.id, kind: fieldKind } }] };
return getEntityResolver(gid.type)(null, {}, ast, override);
},
function(data) {
return data.__type;
}
);
var nodeInterface = node.nodeInterface;
var nodeField = node.nodeField;
| Fix error in node definition code | Fix error in node definition code
| JavaScript | mit | rexxars/sql-to-graphql,rexxars/sql-to-graphql,vaffel/sql-to-graphql,vaffel/sql-to-graphql | ---
+++
@@ -2,7 +2,7 @@
function(globalId, ast) {
var gid = fromGlobalId(globalId);
var fieldKind = gid.id.match(/^[0-9]+$/) ? 'IntValue' : 'StringValue';
- var override = { arguments: [{ name: { value: 'id' }, value: { value: id, kind: fieldKind } }] };
+ var override = { arguments: [{ name: { value: 'id' }, value: { value: gid.id, kind: fieldKind } }] };
return getEntityResolver(gid.type)(null, {}, ast, override);
},
function(data) { |
a429e6a5d3af7a847000a36fee67da3423dc8c8e | rollup.config.js | rollup.config.js | import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
export default {
entry: 'src/index.js',
plugins: [
commonjs(),
resolve({
customResolveOptions: {
moduleDirectory: 'node_modules',
}
}),
babel({
exclude: 'node_modules/**'
})
],
external: ['knockout', 'react', 'prop-types', 'create-react-class'],
globals: {
knockout: 'ko',
react: 'React',
'prop-types': 'PropTypes',
'create-react-class': 'createReactClass'
},
moduleName: 'komx-react',
targets: [
{ dest: 'dist/komx-react.umd.js', format: 'umd' },
{ dest: 'dist/komx-react.es.js', format: 'es' }
],
};
| import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
export default {
entry: 'src/index.js',
plugins: [
commonjs(),
resolve({
customResolveOptions: {
moduleDirectory: 'node_modules',
}
}),
babel({
exclude: 'node_modules/**'
})
],
external: ['knockout', 'react'],
globals: {
knockout: 'ko',
react: 'React'
},
moduleName: 'komx-react',
targets: [
{ dest: 'dist/komx-react.umd.js', format: 'umd' },
{ dest: 'dist/komx-react.es.js', format: 'es' }
],
};
| Remove prop-types and create-react-class as externals. | Remove prop-types and create-react-class as externals.
| JavaScript | mit | ConrabOpto/komx-react | ---
+++
@@ -15,12 +15,10 @@
exclude: 'node_modules/**'
})
],
- external: ['knockout', 'react', 'prop-types', 'create-react-class'],
+ external: ['knockout', 'react'],
globals: {
knockout: 'ko',
- react: 'React',
- 'prop-types': 'PropTypes',
- 'create-react-class': 'createReactClass'
+ react: 'React'
},
moduleName: 'komx-react',
targets: [ |
7e932c5804173f5de76995d900c67d9b53a62194 | frontend/src/constants/database.js | frontend/src/constants/database.js | /**
* This file specifies the database collection and field names.
*/
export const COLLECTION_TRIPS = 'trips';
export const TRIPS_TITLE = 'title';
export const TRIPS_DESCRIPTION = 'description';
export const TRIPS_DESTINATION = 'destination';
export const TRIPS_START_DATE = 'start_date';
export const TRIPS_END_DATE = 'end_date';
export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr';
export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr';
export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr';
export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp';
/**
* NOTE: The following constant corresponds to the general collaborator field in
* {@link_RawTripData} and is not an actual field in a trip document.
*/
export const RAW_COLLAB_EMAILS = 'collaboratorEmails';
export const COLLECTION_ACTIVITIES = 'activities';
export const ACTIVITIES_START_TIME = 'start_time';
export const ACTIVITIES_END_TIME = 'end_time';
export const ACTIVITIES_START_TZ = 'start_tz';
export const ACTIVITIES_END_TZ = 'end_tz';
export const ACTIVITIES_TITLE = 'title';
export const ACTIVITIES_DESCRIPTION = 'description';
export const ACTIVITIES_START_COUNTRY = 'start_country';
export const ACTIVITIES_END_COUNTRY = 'end_country';
| /**
* This file specifies the database collection and field names.
*/
export const COLLECTION_TRIPS = 'trips';
export const TRIPS_TITLE = 'title';
export const TRIPS_DESCRIPTION = 'description';
export const TRIPS_DESTINATION = 'destination';
export const TRIPS_START_DATE = 'start_date';
export const TRIPS_END_DATE = 'end_date';
export const TRIPS_ACCEPTED_COLLABS = 'accepted_collaborator_uid_arr';
export const TRIPS_PENDING_COLLABS = 'pending_collaborator_uid_arr';
export const TRIPS_REJECTED_COLLABS = 'rejected_collaborator_uid_arr';
export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp';
/**
* NOTE: The following constant corresponds to the general collaborator field in
* {@link RawTripData} and is not an actual field in a trip document.
*/
export const RAW_COLLAB_EMAILS = 'collaboratorEmails';
export const COLLECTION_ACTIVITIES = 'activities';
export const ACTIVITIES_START_TIME = 'start_time';
export const ACTIVITIES_END_TIME = 'end_time';
export const ACTIVITIES_START_TZ = 'start_tz';
export const ACTIVITIES_END_TZ = 'end_tz';
export const ACTIVITIES_TITLE = 'title';
export const ACTIVITIES_DESCRIPTION = 'description';
export const ACTIVITIES_START_COUNTRY = 'start_country';
export const ACTIVITIES_END_COUNTRY = 'end_country';
| Replace accidental _ with space in JSDoc link. | Replace accidental _ with space in JSDoc link.
| JavaScript | apache-2.0 | googleinterns/SLURP,googleinterns/SLURP,googleinterns/SLURP | ---
+++
@@ -13,7 +13,7 @@
export const TRIPS_UPDATE_TIMESTAMP = 'update_timestamp';
/**
* NOTE: The following constant corresponds to the general collaborator field in
- * {@link_RawTripData} and is not an actual field in a trip document.
+ * {@link RawTripData} and is not an actual field in a trip document.
*/
export const RAW_COLLAB_EMAILS = 'collaboratorEmails';
|
498880103fa05d9422ec377dc9f2bb85e557240c | scripts/ayuda.js | scripts/ayuda.js | document.getElementById("ayuda").setAttribute("aria-current", "page");
function prueba() {
alert("prueba");
}
var aside = document.getElementById("complementario");
var button = document.createElement("BUTTON");
var text = document.createTextNode("Prueba");
button.appendChild(text);
aside.appendChild(button);
button.addEventListener("click", prueba());
| document.getElementById("ayuda").setAttribute("aria-current", "page");
function prueba() {
alert("prueba");
}
var aside = document.getElementById("complementario");
var button = document.createElement("BUTTON");
var text = document.createTextNode("Prueba");
button.appendChild(text);
aside.appendChild(button);
button.addEventListener("click", prueba);
| Update script, hope fixed now | Update script, hope fixed now
| JavaScript | mit | nvdaes/nvdaes.github.io,nvdaes/nvdaes.github.io | ---
+++
@@ -9,4 +9,4 @@
var text = document.createTextNode("Prueba");
button.appendChild(text);
aside.appendChild(button);
-button.addEventListener("click", prueba());
+button.addEventListener("click", prueba); |
0ee382387ff83da0c740dbc05c1a567b4f60cde1 | server/server.js | server/server.js | import express from 'express';
import logger from 'morgan';
import validator from 'express-validator';
import bodyParser from 'body-parser';
import verifyToken from './middlewares/auth';
import valueChecker from './middlewares/valueChecker';
import router from './routes/router';
const app = express();
const port = process.env.PORT || 8000;
app.use(logger('dev'));
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(validator());
app.use('/api/v1', verifyToken);
app.use(valueChecker);
app.use(router);
app.use('*', (req, res) => res.redirect(302, '/'));
app.listen(port);
export default app;
| import express from 'express';
import logger from 'morgan';
import validator from 'express-validator';
import bodyParser from 'body-parser';
import verifyToken from './middlewares/verifyToken';
import valueChecker from './middlewares/valueChecker';
import router from './routes/router';
const app = express();
const port = process.env.PORT || 8000;
app.use(logger('dev'));
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(validator());
app.use('/api/v1', verifyToken);
app.use(valueChecker);
app.use(router);
app.use('*', (req, res) => res.redirect(302, '/'));
app.listen(port);
export default app;
| Modify the imported module filename | Modify the imported module filename
| JavaScript | mit | vynessa/dman,vynessa/dman | ---
+++
@@ -2,7 +2,7 @@
import logger from 'morgan';
import validator from 'express-validator';
import bodyParser from 'body-parser';
-import verifyToken from './middlewares/auth';
+import verifyToken from './middlewares/verifyToken';
import valueChecker from './middlewares/valueChecker';
import router from './routes/router';
|
d07c941ae1b443a83e76ded60167ddb80f37c0ed | nodejs/lib/meta_user_manager.js | nodejs/lib/meta_user_manager.js | var wompt = require('./includes');
function MetaUserManager(){
this.meta_users = {};
this.expirer = new wompt.Expirer(this.meta_users,{
keep_if: function(mu){
return mu.clients.count > 0;
},
time_attribute:'touched'
});
}
var p = MetaUserManager.prototype;
p.get = function(id){
return this.meta_users[id];
}
p.set = function(id, mu){
this.meta_users[id] = mu;
}
module.exports = MetaUserManager;
| var wompt = require('./includes');
function MetaUserManager(){
this.meta_users = {};
this.expirer = new wompt.Expirer(this.meta_users,{
keep_if: function(mu){
return mu.clients.count > 0;
},
time_attribute:'touched'
});
}
var p = MetaUserManager.prototype;
p.get = function getMU(id){
return this.meta_users[id];
}
// Get a MU by ID or call the provided function and pass the "set" function
// which is the same as like this.set()
// returns the existing MU or the created one.
p.getOrCreate = function getOrCreateMU(id, create){
var result, self = this;
function set(id, object){
result = self.set(id, object);
}
return self.get(id) || (create(set) || result);
}
p.set = function setMU(id, mu){
return this.meta_users[id] = mu;
}
module.exports = MetaUserManager;
| Add a simple getOrCreate() function to MetaUserManager and add names to it's anonymous functions | Add a simple getOrCreate() function to MetaUserManager
and add names to it's anonymous functions
| JavaScript | mit | Wompt/wompt.com,Wompt/wompt.com,iFixit/wompt.com,iFixit/wompt.com,iFixit/wompt.com,iFixit/wompt.com,Wompt/wompt.com | ---
+++
@@ -2,6 +2,7 @@
function MetaUserManager(){
this.meta_users = {};
+
this.expirer = new wompt.Expirer(this.meta_users,{
keep_if: function(mu){
return mu.clients.count > 0;
@@ -11,12 +12,24 @@
}
var p = MetaUserManager.prototype;
-p.get = function(id){
+p.get = function getMU(id){
return this.meta_users[id];
}
-p.set = function(id, mu){
- this.meta_users[id] = mu;
+// Get a MU by ID or call the provided function and pass the "set" function
+// which is the same as like this.set()
+// returns the existing MU or the created one.
+p.getOrCreate = function getOrCreateMU(id, create){
+ var result, self = this;
+
+ function set(id, object){
+ result = self.set(id, object);
+ }
+
+ return self.get(id) || (create(set) || result);
}
+p.set = function setMU(id, mu){
+ return this.meta_users[id] = mu;
+}
module.exports = MetaUserManager; |
b38cae7323a77cb488f4404df0885eb2c5f44c99 | test/algorithms/sorting/testInsertionSort.js | test/algorithms/sorting/testInsertionSort.js | /* eslint-env mocha */
const InsertionSort = require('../../../src').Algorithms.Sorting.InsertionSort;
const assert = require('assert');
describe('Insertion Sort', () => {
it('should have no data when empty initialization', () => {
const inst = new InsertionSort();
assert.equal(inst.size, 0);
assert.deepEqual(inst.unsortedList, []);
assert.deepEqual(inst.sortedList, []);
});
it('should sort the array', () => {
const inst = new InsertionSort([2, 1, 3, 4]);
assert.equal(inst.size, 4);
assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]);
assert.deepEqual(inst.sortedList, [1, 2, 3, 4]);
assert.equal(inst.toString(), '1, 2, 3, 4');
});
});
| /* eslint-env mocha */
const InsertionSort = require('../../../src').Algorithms.Sorting.InsertionSort;
const assert = require('assert');
describe('Insertion Sort', () => {
it('should have no data when empty initialization', () => {
const inst = new InsertionSort();
assert.equal(inst.size, 0);
assert.deepEqual(inst.unsortedList, []);
assert.deepEqual(inst.sortedList, []);
});
it('should sort the array', () => {
const inst = new InsertionSort([2, 1, 3, 4]);
assert.equal(inst.size, 4);
assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]);
assert.deepEqual(inst.sortedList, [1, 2, 3, 4]);
assert.equal(inst.toString(), '1, 2, 3, 4');
});
it('should sort the array in ascending order with few equal vals', () => {
const inst = new InsertionSort([2, 1, 3, 4, 2], (a, b) => a < b);
assert.equal(inst.size, 5);
assert.deepEqual(inst.unsortedList, [2, 1, 3, 4, 2]);
assert.deepEqual(inst.sortedList, [1, 2, 2, 3, 4]);
assert.equal(inst.toString(), '1, 2, 2, 3, 4');
});
});
| Test Insertion Sort: Test for sorting in ascending order with equal values | Test Insertion Sort: Test for sorting in ascending order with equal values
| JavaScript | mit | ManrajGrover/algorithms-js | ---
+++
@@ -19,4 +19,13 @@
assert.equal(inst.toString(), '1, 2, 3, 4');
});
+ it('should sort the array in ascending order with few equal vals', () => {
+ const inst = new InsertionSort([2, 1, 3, 4, 2], (a, b) => a < b);
+ assert.equal(inst.size, 5);
+
+ assert.deepEqual(inst.unsortedList, [2, 1, 3, 4, 2]);
+ assert.deepEqual(inst.sortedList, [1, 2, 2, 3, 4]);
+ assert.equal(inst.toString(), '1, 2, 2, 3, 4');
+ });
+
}); |
4699f68746a15d9cf39cac307ee3609fcdf6031d | test/fixture/event-handlers-with-callback.js | test/fixture/event-handlers-with-callback.js | /* eslint-env mocha */
'use strict'
const chai = require('chai')
chai.should()
let result = ''
module.exports = function () {
this.registerHandler('BeforeFeatures', function (features, cb) {
result += features.length
cb()
})
this.registerHandler('BeforeFeature', function (feature, cb) {
result += feature.getName()
cb()
})
this.registerHandler('BeforeScenario', function (scenario, cb) {
result += scenario.getName()
cb()
})
this.registerHandler('BeforeStep', function (step, cb) {
this.click('#before-step')
result += step.getName()
cb()
})
this.registerHandler('AfterStep', function (step, cb) {
result += step.getName()
cb()
})
this.registerHandler('AfterScenario', function (scenario, cb) {
result += scenario.getName()
cb()
})
this.registerHandler('AfterFeature', function (feature, cb) {
result += feature.getName()
cb()
})
this.registerHandler('AfterFeatures', function (features, cb) {
result += features.length
if (process.send) process.send(result)
cb()
})
}
| /* eslint-env mocha */
'use strict'
const chai = require('chai')
chai.should()
let result = ''
module.exports = function () {
this.registerHandler('BeforeFeatures', function (features, cb) {
result += features.length
cb()
})
this.registerHandler('BeforeFeature', function (feature, cb) {
result += feature.getName()
cb()
})
this.registerHandler('BeforeScenario', function (scenario, cb) {
result += scenario.getName()
cb()
})
this.registerHandler('BeforeStep', function (step, cb) {
result += step.getName()
cb()
})
this.registerHandler('AfterStep', function (step, cb) {
result += step.getName()
cb()
})
this.registerHandler('AfterScenario', function (scenario, cb) {
result += scenario.getName()
cb()
})
this.registerHandler('AfterFeature', function (feature, cb) {
result += feature.getName()
cb()
})
this.registerHandler('AfterFeatures', function (features, cb) {
result += features.length
if (process.send) process.send(result)
cb()
})
}
| Fix event handler test with callback | test: Fix event handler test with callback
| JavaScript | mit | mucsi96/nightwatch-cucumber,mucsi96/nightwatch-cucumber | ---
+++
@@ -23,7 +23,6 @@
})
this.registerHandler('BeforeStep', function (step, cb) {
- this.click('#before-step')
result += step.getName()
cb()
}) |
650cec3f0c9de203f7afd1e5763f6b3f8b700dc8 | resources/public/js/monitor.js | resources/public/js/monitor.js | var columns = 3
var itemPadding = 10
function widthGiven(itemCount) {
return window.innerWidth / Math.min(columns, itemCount) - itemPadding
}
function heightGiven(itemCount) {
return window.innerHeight / Math.ceil(itemCount / columns) - itemPadding
}
function styleListItems() {
var itemCount = $('li').size()
$('.outerContainer')
.height(heightGiven(itemCount))
.width(widthGiven(itemCount))
scaleFontToContainerSize()
}
function scaleFontToContainerSize() {
$(".outerContainer").fitText(1.75)
}
function grabLatestData() {
$.getJSON("/projects").then(function(data){
$('#projects').empty()
data.body.forEach(function(project){
var buildStatus = project.lastBuildStatus
if(buildStatus !== "Success"){
$('#projects').append("<li><div class=outerContainer><div class=innerContainer>" +
project.name + "</div></div></li>")
}
})
styleListItems()
})
}
grabLatestData(); // run immediately
setInterval(grabLatestData, 5000); | var columns = 3
var itemPadding = 10
function numberOfColumns() {
var buildStatusCount = $('li').size()
return Math.min(columns, $('li').size())
}
function numberOfRows() {
var buildStatusCount = $('li').size()
return Math.ceil(buildStatusCount / columns)
}
function buildStatusWidth() {
return window.innerWidth / numberOfColumns() - itemPadding
}
function buildStatusHeight() {
return window.innerHeight / numberOfRows() - itemPadding
}
function styleListItems() {
$('.outerContainer').height(buildStatusHeight()).width(buildStatusWidth())
scaleFontToContainerSize()
}
function scaleFontToContainerSize() {
$(".outerContainer").fitText(1.75)
}
function addBuildStatusToScreen(project) {
var buildStatus = project.lastBuildStatus
if(buildStatus !== "Success"){
$('#projects').append("<li><div class=outerContainer><div class=innerContainer>" +
project.name + "</div></div></li>")
}
}
function addListItems(data) {
$('#projects').empty()
data.body.forEach(addBuildStatusToScreen)
}
function updateBuildMonitor() {
$.getJSON("/projects").then(function(data){
addListItems(data)
styleListItems()
})
}
updateBuildMonitor() // run immediately
setInterval(updateBuildMonitor, 5000) | Refactor Javascript now concepts are understood | Refactor Javascript now concepts are understood
| JavaScript | epl-1.0 | darrenhaken/nevergreen,cburgmer/nevergreen,build-canaries/nevergreen,antoniou/nevergreen-standalone,cburgmer/nevergreen,darrenhaken/nevergreen,antoniou/nevergreen-standalone,build-canaries/nevergreen,build-canaries/nevergreen,darrenhaken/nevergreen,build-canaries/nevergreen,antoniou/nevergreen-standalone,cburgmer/nevergreen | ---
+++
@@ -1,20 +1,26 @@
var columns = 3
var itemPadding = 10
-function widthGiven(itemCount) {
- return window.innerWidth / Math.min(columns, itemCount) - itemPadding
+function numberOfColumns() {
+ var buildStatusCount = $('li').size()
+ return Math.min(columns, $('li').size())
}
-function heightGiven(itemCount) {
- return window.innerHeight / Math.ceil(itemCount / columns) - itemPadding
+function numberOfRows() {
+ var buildStatusCount = $('li').size()
+ return Math.ceil(buildStatusCount / columns)
+}
+
+function buildStatusWidth() {
+ return window.innerWidth / numberOfColumns() - itemPadding
+}
+
+function buildStatusHeight() {
+ return window.innerHeight / numberOfRows() - itemPadding
}
function styleListItems() {
- var itemCount = $('li').size()
- $('.outerContainer')
- .height(heightGiven(itemCount))
- .width(widthGiven(itemCount))
-
+ $('.outerContainer').height(buildStatusHeight()).width(buildStatusWidth())
scaleFontToContainerSize()
}
@@ -22,21 +28,25 @@
$(".outerContainer").fitText(1.75)
}
-function grabLatestData() {
+function addBuildStatusToScreen(project) {
+ var buildStatus = project.lastBuildStatus
+ if(buildStatus !== "Success"){
+ $('#projects').append("<li><div class=outerContainer><div class=innerContainer>" +
+ project.name + "</div></div></li>")
+ }
+}
+
+function addListItems(data) {
+ $('#projects').empty()
+ data.body.forEach(addBuildStatusToScreen)
+}
+
+function updateBuildMonitor() {
$.getJSON("/projects").then(function(data){
- $('#projects').empty()
-
- data.body.forEach(function(project){
- var buildStatus = project.lastBuildStatus
- if(buildStatus !== "Success"){
- $('#projects').append("<li><div class=outerContainer><div class=innerContainer>" +
- project.name + "</div></div></li>")
- }
- })
-
+ addListItems(data)
styleListItems()
})
}
-grabLatestData(); // run immediately
-setInterval(grabLatestData, 5000);
+updateBuildMonitor() // run immediately
+setInterval(updateBuildMonitor, 5000) |
57b7b3d47d0f0950dc4c0f478eb280d134b1c692 | public/javascripts/ga.js | public/javascripts/ga.js | (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-10687369-9', 'cloudcv.io');
ga('send', 'pageview'); | (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-10687369-8', 'cloudcv.io');
ga('send', 'pageview'); | Update google analytics tracking code | Update google analytics tracking code
| JavaScript | bsd-3-clause | BloodAxe/CloudCV,BloodAxe/CloudCV | ---
+++
@@ -3,5 +3,5 @@
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
- ga('create', 'UA-10687369-9', 'cloudcv.io');
+ ga('create', 'UA-10687369-8', 'cloudcv.io');
ga('send', 'pageview'); |
adeda7aacfccccd94e43be6e42cce1db67513080 | bin/cmd.js | bin/cmd.js | #!/usr/bin/env node
var readJson = require('read-package-json');
var minimist = require('minimist');
var path = require('path');
var url = require('url');
var shields = require('../');
var argv = minimist(process.argv.slice(2), {
alias: {
v: 'version'
}
});
if (argv.version) {
console.log(require('../package.json').version);
return;
}
// no args
if (!argv._.length) {
var usage = [
'Shield generator for your current project.',
'',
'Usage:',
' shields [travis] [gemnasium]'
];
console.log(usage.join('\n'));
return;
}
var p = path.resolve('./package.json');
readJson(p, function(error, pkg) {
if (error) {
throw error;
}
var slug = url.parse(pkg.repository.url).path.slice(1);
var links = [''];
argv._.forEach(function(service) {
var shield = shields(slug, service);
var status = service === 'travis' ? 'Build' : 'Dependency';
console.log('[![' + status + ' Status][' + service + '-svg]][' + service + ']');
links.push(' [' + service + ']: ' + shield.link);
links.push(' [' + service + '-svg]: ' + shield.svg);
});
console.log(links.join('\n'));
}); | #!/usr/bin/env node
var readJson = require('read-package-json');
var minimist = require('minimist');
var path = require('path');
var url = require('url');
var shields = require('../');
var argv = minimist(process.argv.slice(2), {
alias: {
v: 'version'
}
});
if (argv.version) {
console.log(require('../package.json').version);
return;
}
// no args
if (!argv._.length) {
var usage = [
'Shield generator for your current project.',
'',
'Usage:',
' shields [travis] [gemnasium]',
' shields -v | --version',
'',
'Options:',
' -v --version Show version'
];
console.log(usage.join('\n'));
return;
}
var p = path.resolve('./package.json');
readJson(p, function(error, pkg) {
if (error) {
throw error;
}
var slug = url.parse(pkg.repository.url).path.slice(1);
var links = [''];
argv._.forEach(function(service) {
var shield = shields(slug, service);
var status = service === 'travis' ? 'Build' : 'Dependency';
console.log('[![' + status + ' Status][' + service + '-svg]][' + service + ']');
links.push(' [' + service + ']: ' + shield.link);
links.push(' [' + service + '-svg]: ' + shield.svg);
});
console.log(links.join('\n'));
}); | Add version flag to usage info | Add version flag to usage info
Closes #8
| JavaScript | mit | KenanY/shields | ---
+++
@@ -24,7 +24,11 @@
'Shield generator for your current project.',
'',
'Usage:',
- ' shields [travis] [gemnasium]'
+ ' shields [travis] [gemnasium]',
+ ' shields -v | --version',
+ '',
+ 'Options:',
+ ' -v --version Show version'
];
console.log(usage.join('\n')); |
d6f1706e7c0b242167b6bfaace6aceee54987324 | app/app.js | app/app.js | var express = require('express');
module.exports = exports = function (options) {
var BasicAuth = require('./middleware/auth/basic');
var TradesRouter = require('./routers/trades');
var UserRouter = require('./routers/user');
var UsersRouter = require('./routers/users');
var LabelsRouter = require('./routers/labels');
var app = express();
app.use(BasicAuth({ users: options.users }));
app.use(UserRouter({ users: options.users }));
app.use(UsersRouter({ users: options.users }));
app.use(TradesRouter({ trades: options.trades }));
app.use(LabelsRouter({ labels: options.labels }));
app.all('*', function (req, res, next) {
next(new Error('not_found'));
});
app.use(function(err, req, res, next) {
res.send(500, { error: 'something' });
});
return app;
};
| var express = require('express');
module.exports = exports = function (options) {
var BasicAuth = require('./middleware/auth/basic');
var TradesRouter = require('./routers/trades');
var UserRouter = require('./routers/user');
var UsersRouter = require('./routers/users');
var LabelsRouter = require('./routers/labels');
var app = express();
app.use(BasicAuth({ users: options.users }));
app.use(UserRouter({ users: options.users }));
app.use(UsersRouter({ users: options.users }));
app.use(TradesRouter({ trades: options.trades }));
app.use(LabelsRouter({ labels: options.labels }));
app.all('*', function (req, res, next) {
next(new Error('not_found'));
});
app.use(function(err, req, res, next) {
res.send(500, { error: err.message });
});
return app;
};
| Return error message on HTTP 500 | Return error message on HTTP 500
| JavaScript | mit | davidknezic/bitcoin-trade-guard-backend | ---
+++
@@ -22,7 +22,7 @@
});
app.use(function(err, req, res, next) {
- res.send(500, { error: 'something' });
+ res.send(500, { error: err.message });
});
return app; |
d382b1d0cac8b071432e88bebca3e8fd636b31dd | backend.js | backend.js | //Dear source-code readers, pay no attention to these global variables
var APP_ID = 'YtKfTS2Zo8ELUk63LzB0';
var APP_CODE = 'SB1wcsUEGzLA3SRHJJ7CPw';
// Reference to the root of the Firebase database
var database = new Firebase("https://brilliant-torch-6592.firebaseio.com/");
$("#upload").click(function() {
var name = $("#nameInput").val();
var text = $("#messageInput").val();
if (name.length != 0 && text.length != 0) { // Don't upload if there's no information in the textboxes
console.log(name.length);
console.log(text.length);
database.push({name: name, text: text});
database.on('child_added', function(update) {
console.log("Callback function: New data has been added to the database");
});
}else {
console.log("Please input values into the textbox");
}
});
console.log('LOADED BACKEND'); | //Dear source-code readers, pay no attention to these global variables
var APP_ID = 'YtKfTS2Zo8ELUk63LzB0';
var APP_CODE = 'SB1wcsUEGzLA3SRHJJ7CPw';
// Reference to the root of the Firebase database
var database = new Firebase("https://battleshiphere.firebaseio.com/");
$("#upload").click(function() {
var name = $("#nameInput").val();
var text = $("#messageInput").val();
if (name.length != 0 && text.length != 0) { // Don't upload if there's no information in the textboxes
console.log(name.length);
console.log(text.length);
database.push({name: name, text: text});
database.on('child_added', function(update) {
console.log("Callback function: New data has been added to the database");
});
}else {
console.log("Please input values into the textbox");
}
});
console.log('LOADED BACKEND'); | Change Database with a more fitting name | Change Database with a more fitting name
| JavaScript | mit | vingkan/conquiz,vingkan/conquiz | ---
+++
@@ -3,7 +3,7 @@
var APP_CODE = 'SB1wcsUEGzLA3SRHJJ7CPw';
// Reference to the root of the Firebase database
-var database = new Firebase("https://brilliant-torch-6592.firebaseio.com/");
+var database = new Firebase("https://battleshiphere.firebaseio.com/");
$("#upload").click(function() {
var name = $("#nameInput").val();
@@ -24,4 +24,6 @@
});
+
+
console.log('LOADED BACKEND'); |
512fac75c3b4809b159f639476a98c0253a47013 | bin/cmd.js | bin/cmd.js | #!/usr/bin/env node
/*
* mochify.js
*
* Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
*
* @license MIT
*/
'use strict';
var mochify = require('../lib/mochify');
var args = require('../lib/args');
var opts = args(process.argv.slice(2));
var _ = opts._.length
? opts._.join(' ')
: null;
function error() {
if (!opts.watch) {
process.nextTick(function () {
process.exit(1);
});
}
}
mochify(_, opts)
.on('error', error)
.bundle(function (err) {
if (err) {
error();
}
});
| #!/usr/bin/env node
/*
* mochify.js
*
* Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
*
* @license MIT
*/
'use strict';
var mochify = require('../lib/mochify');
var args = require('../lib/args');
var opts = args(process.argv.slice(2));
var _ = opts._.length
? opts._.join(' ')
: null;
function error() {
if (!opts.watch) {
process.nextTick(function () {
process.exit(1);
});
}
}
mochify(_, opts)
.on('error', error)
.bundle();
| Remove obsolete error handling callback | Remove obsolete error handling callback
| JavaScript | mit | Swaagie/mochify.js,mantoni/mochify.js,jhytonen/mochify.js,mantoni/mochify.js,Heng-xiu/mochify.js,boneskull/mochify.js,mantoni/mochify.js,Heng-xiu/mochify.js,Swaagie/mochify.js,jhytonen/mochify.js,boneskull/mochify.js | ---
+++
@@ -26,8 +26,4 @@
mochify(_, opts)
.on('error', error)
- .bundle(function (err) {
- if (err) {
- error();
- }
- });
+ .bundle(); |
4c117ffd1c4ead3e4eccddade8419c8801c01e03 | src/factories.js | src/factories.js | import React from "react"
import Form from "./components/form.js"
import Input from "./components/input.js"
import Submit from "./components/submit.js"
import FormErrorList from "./components/form_error_list.js"
import Fieldset from "./components/fieldset.js"
export const form = React.createFactory(Form)
export const input = React.createFactory(Input)
export const submit = React.createFactory(Submit)
export const formErrorList = React.createFactory(FormErrorList)
export const fieldset = React.createFactory(Fieldset)
| import React from "react"
import Form from "./components/form.js"
import Input from "./components/input.js"
import Submit from "./components/submit.js"
import FormErrorList from "./components/form_error_list.js"
import Fieldset from "./components/fieldset.js"
import FieldsetText from "./components/fieldset_text.js"
export const form = React.createFactory(Form)
export const input = React.createFactory(Input)
export const submit = React.createFactory(Submit)
export const formErrorList = React.createFactory(FormErrorList)
export const fieldset = React.createFactory(Fieldset)
export const fieldsetText = React.createFactory(FieldsetText)
| Add Fieldset Text Factory For DSL | Add Fieldset Text Factory For DSL
| JavaScript | mit | TouchBistro/frig,frig-js/frig,frig-js/frig,TouchBistro/frig | ---
+++
@@ -4,9 +4,11 @@
import Submit from "./components/submit.js"
import FormErrorList from "./components/form_error_list.js"
import Fieldset from "./components/fieldset.js"
+import FieldsetText from "./components/fieldset_text.js"
export const form = React.createFactory(Form)
export const input = React.createFactory(Input)
export const submit = React.createFactory(Submit)
export const formErrorList = React.createFactory(FormErrorList)
export const fieldset = React.createFactory(Fieldset)
+export const fieldsetText = React.createFactory(FieldsetText) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.