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 |
|---|---|---|---|---|---|---|---|---|---|---|
29f8fd3db9258d891cb421f9658bb521fd7aa298 | examples/directory/ipClient.js | examples/directory/ipClient.js | // Fake service (makes a tether)
/* jshint node: true */
(function () {
"use strict";
var runtime = require("quark_node_runtime.js");
var ipify = require("./ipify");
function Consumer() {};
Consumer.prototype.consume = function (ip) {
console.log("IP is " + ip);
process.exit();
};
var m = new ipify.MyExternalIP(runtime, new Consumer());
runtime.launch();
})();
| // Fake service (makes a tether)
/* jshint node: true */
(function () {
"use strict";
var runtime = require("quark_node_runtime.js");
var ipify = require("./ipify");
function Consumer() {}
Consumer.prototype.consume = function (ip) {
console.log("IP is " + ip);
process.exit();
};
var m = new ipify.MyExternalIP(runtime, new Consumer());
runtime.launch();
})();
| Fix typo in JS client example | Fix typo in JS client example | JavaScript | apache-2.0 | datawire/quark,datawire/datawire-connect,datawire/quark,datawire/datawire-connect,datawire/datawire-connect,datawire/quark,datawire/datawire-connect,bozzzzo/quark,bozzzzo/quark,bozzzzo/quark,datawire/quark,datawire/quark,bozzzzo/quark,datawire/quark | ---
+++
@@ -7,7 +7,7 @@
var runtime = require("quark_node_runtime.js");
var ipify = require("./ipify");
- function Consumer() {};
+ function Consumer() {}
Consumer.prototype.consume = function (ip) {
console.log("IP is " + ip);
process.exit(); |
276aeaa74bf7f014e5ca77f0178b81b75c0cd1bb | lib/utility/create-subcompany-with-admin.js | lib/utility/create-subcompany-with-admin.js | 'use strict';
var async = require('async');
/**
* Create a new user and move it to a new subcompany.
* The new user will be the first admin of the subcompany.
* @param {Object} subcompany Informations of the subcompany
* @param {Object} newAdmin User info of the admin to create.
* @param {Function} cb(err, subcompany, admin)
*/
module.exports = function createSubcompanyWithAdmin(subcompany, newAdmin, finalCb) {
newAdmin.is_admin = true;
var self = this;
async.waterfall([
// Create the admin user who will be named admin of the new subcompany
function createAdmin(cb) {
self.postUser(newAdmin, cb);
},
function extractId(res, cb) {
cb(null, res.body);
},
function createSubcompany(admin, cb) {
subcompany.user = admin.id;
self.postSubcompany(subcompany, function(err, res) {
cb(err, res.body, admin);
});
},
], finalCb);
};
| 'use strict';
var async = require('async');
/**
* Create a new user and move it to a new subcompany.
* The new user will be the first admin of the subcompany.
* @param {Object} subcompany Informations of the subcompany
* @param {Object} newAdmin User info of the admin to create.
* @param {Function} cb(err, subcompany, admin)
*/
module.exports = function createSubcompanyWithAdmin(subcompany, newAdmin, finalCb) {
// Force set is_admin to false, for security reason: if the call to createSubcompany were to fail for any reasons,
// we won't be left with an admin user in our parent company.
newAdmin.is_admin = false;
var self = this;
async.waterfall([
// Create the admin user who will be named admin of the new subcompany
function createAdmin(cb) {
self.postUser(newAdmin, cb);
},
function extractId(res, cb) {
cb(null, res.body);
},
function createSubcompany(admin, cb) {
subcompany.user = admin.id;
self.postSubcompany(subcompany, function(err, res) {
cb(err, res.body, admin);
});
},
], finalCb);
};
| Fix potential security flaw in createSubcompany() | Fix potential security flaw in createSubcompany()
| JavaScript | mit | AnyFetch/anyfetch.js,AnyFetch/anyfetch.js | ---
+++
@@ -10,7 +10,9 @@
* @param {Function} cb(err, subcompany, admin)
*/
module.exports = function createSubcompanyWithAdmin(subcompany, newAdmin, finalCb) {
- newAdmin.is_admin = true;
+ // Force set is_admin to false, for security reason: if the call to createSubcompany were to fail for any reasons,
+ // we won't be left with an admin user in our parent company.
+ newAdmin.is_admin = false;
var self = this;
async.waterfall([ |
adf7c42b48cbcf6e98871b529faeadf80a8cf4e0 | app/assets/javascripts/modal.js | app/assets/javascripts/modal.js | $(function() {
$("#modal-1").on("change", function() {
if ($(this).is(":checked")) {
$("body").addClass("modal-open");
} else {
$("body").removeClass("modal-open");
}
});
$(".modal-fade-screen, .modal-close").on("click", function() {
$(".modal-state:checked").prop("checked", false).change();
});
$(".modal-inner").on("click", function(e) {
e.stopPropagation();
});
});
| function modal () {
$("#modal-1").on("change", function() {
if ($(this).is(":checked")) {
$("body").addClass("modal-open");
} else {
$("body").removeClass("modal-open");
}
});
$(".modal-fade-screen, .modal-close").on("click", function() {
$(".modal-state:checked").prop("checked", false).change();
});
$(".modal-inner").on("click", function(e) {
e.stopPropagation();
});
});
| Rewrite js as stand alone function | Rewrite js as stand alone function
| JavaScript | mit | costolo/chain,costolo/chain,costolo/chain | ---
+++
@@ -1,4 +1,4 @@
-$(function() {
+function modal () {
$("#modal-1").on("change", function() {
if ($(this).is(":checked")) {
$("body").addClass("modal-open"); |
35fde281c9aab34e68b1fca42ce87490ed126f65 | defaults/preferences/prefs.js | defaults/preferences/prefs.js | pref("extensions.FolderPaneSwitcher.logging.console","Warn");
pref("extensions.FolderPaneSwitcher.logging.dump","Warn");
pref("extensions.FolderPaneSwitcher.arrows",true);
pref("extensions.FolderPaneSwitcher.delay",2000);
pref("extensions.FolderPaneSwitcher.dropDelay",1000);
// https://developer.mozilla.org/en/Localizing_extension_descriptions
pref("extensions.FolderPaneSwitcher@kamens.us.description", "chrome://FolderPaneSwitcher/locale/overlay.properties");
| pref("extensions.FolderPaneSwitcher.logging.console","Warn");
pref("extensions.FolderPaneSwitcher.logging.dump","Warn");
pref("extensions.FolderPaneSwitcher.arrows",true);
pref("extensions.FolderPaneSwitcher.delay",1000);
pref("extensions.FolderPaneSwitcher.dropDelay",1000);
// https://developer.mozilla.org/en/Localizing_extension_descriptions
pref("extensions.FolderPaneSwitcher@kamens.us.description", "chrome://FolderPaneSwitcher/locale/overlay.properties");
| Reduce delay to 1 second; 2 is too long. | Reduce delay to 1 second; 2 is too long.
| JavaScript | mpl-2.0 | jikamens/folder-pane-view-switcher | ---
+++
@@ -1,7 +1,7 @@
pref("extensions.FolderPaneSwitcher.logging.console","Warn");
pref("extensions.FolderPaneSwitcher.logging.dump","Warn");
pref("extensions.FolderPaneSwitcher.arrows",true);
-pref("extensions.FolderPaneSwitcher.delay",2000);
+pref("extensions.FolderPaneSwitcher.delay",1000);
pref("extensions.FolderPaneSwitcher.dropDelay",1000);
// https://developer.mozilla.org/en/Localizing_extension_descriptions
pref("extensions.FolderPaneSwitcher@kamens.us.description", "chrome://FolderPaneSwitcher/locale/overlay.properties"); |
1338a1193f5f6cd672474e20d558ba7f0c734152 | ui/features/files/index.js | ui/features/files/index.js | /*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import router from './router'
import {monitorLtiMessages} from '@canvas/lti/jquery/messages'
router.start()
monitorLtiMessages()
| /*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import router from './router'
import {monitorLtiMessages} from '@canvas/lti/jquery/messages'
import ready from '@instructure/ready'
ready(() => {
router.start()
monitorLtiMessages()
})
| Fix flakey selenium specs for files | Fix flakey selenium specs for files
This change causes the files UI to wait
for all DOM content to be loaded before
initializing the router and listening
for LTI messages
flag=none
Test Plan:
Navigate to /courses/:id/files and verify
the Files UI loads and functions as before
Change-Id: Iee3b5579db889f455353184fd6c39a2716d42003
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/280800
Reviewed-by: Ahmad Amireh <a53a33601b8dd9d06ae9e50f1f30fbe957aba866@instructure.com>
QA-Review: Ahmad Amireh <a53a33601b8dd9d06ae9e50f1f30fbe957aba866@instructure.com>
Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com>
Product-Review: Weston Dransfield <e9203059795dc94e28a8831c65eb7869e818825e@instructure.com>
| JavaScript | agpl-3.0 | sfu/canvas-lms,sfu/canvas-lms,sfu/canvas-lms,sfu/canvas-lms,sfu/canvas-lms,sfu/canvas-lms,sfu/canvas-lms | ---
+++
@@ -18,6 +18,9 @@
import router from './router'
import {monitorLtiMessages} from '@canvas/lti/jquery/messages'
+import ready from '@instructure/ready'
-router.start()
-monitorLtiMessages()
+ready(() => {
+ router.start()
+ monitorLtiMessages()
+}) |
3b7f28f66875cd41dfd546764c23d5cf567285d9 | feature-detects/css-nthchild.js | feature-detects/css-nthchild.js | // nth-child pseudo selector
Modernizr.addTest('nthchild', function(){
return Modernizr.testStyles("#modernizr div {width:1px} #modernizr div:nth-child(2n) {width:2px;}", function (elem) {
var elems = elem.getElementsByTagName("div"),
test = true;
for (i=0; i<5; i++) {
test = test && elems[i].offsetWidth == i%2+1;
}
return test;
}, 5);
}); | // nth-child pseudo selector
Modernizr.addTest('nthchild', function(){
return Modernizr.testStyles('#modernizr div {width:1px} #modernizr div:nth-child(2n) {width:2px;}', function (elem) {
var elems = elem.getElementsByTagName('div'),
test = true;
for (var i=0; i<5; i++) {
test = test && elems[i].offsetWidth == i%2+1;
}
return test;
}, 5);
});
| Fix indent, single-quotes and leaking i | Fix indent, single-quotes and leaking i | JavaScript | mit | Modernizr/Modernizr,Modernizr/Modernizr | ---
+++
@@ -1,13 +1,15 @@
// nth-child pseudo selector
Modernizr.addTest('nthchild', function(){
- return Modernizr.testStyles("#modernizr div {width:1px} #modernizr div:nth-child(2n) {width:2px;}", function (elem) {
- var elems = elem.getElementsByTagName("div"),
- test = true;
- for (i=0; i<5; i++) {
- test = test && elems[i].offsetWidth == i%2+1;
- }
- return test;
- }, 5);
+ return Modernizr.testStyles('#modernizr div {width:1px} #modernizr div:nth-child(2n) {width:2px;}', function (elem) {
+ var elems = elem.getElementsByTagName('div'),
+ test = true;
+
+ for (var i=0; i<5; i++) {
+ test = test && elems[i].offsetWidth == i%2+1;
+ }
+
+ return test;
+ }, 5);
}); |
3a3ba3f254f9dc0e5b5e01b5c9a0dbeef84efb85 | server/chat.js | server/chat.js | var Chat = function() {
//this.members = {};
//this.messages = [];
this.state = this.buildState();
this.colors = [
'red',
'blue',
'green'
]
}
Chat.prototype.buildState = function() {
var newState = {members: {}, messages: [], member_count: 0};
return newState;
}
Chat.prototype.addMessage = function(conn, message) {
var message = {
user_id: conn.id,
message: message,
color: this.getMemberColor( conn.id )
};
this.state.messages.push( message );
return message;
}
Chat.prototype.addMember = function(conn, username) {
this.state.member_count += 1;
var member = {
id: conn.id,
username: username,
status: 'connected',
color: this.colors.shift()
};
this.state.members[conn.id] = member;
return member;
}
Chat.prototype.getMemberColor = function(id) {
return this.state.members[id].color;
}
Chat.prototype.getState = function(){
return this.state;
}
exports.Chat = Chat;
| var Chat = function() {
//this.members = {};
//this.messages = [];
this.state = this.buildState();
this.colors = [
'red',
'blue',
'green'
]
}
Chat.prototype.buildState = function() {
var newState = {members: {}, messages: [], member_count: 0};
return newState;
}
Chat.prototype.addMessage = function(conn, message) {
var message = {
user_id: conn.id,
message: this.replaceUrls(message),
color: this.getMemberColor( conn.id )
};
this.state.messages.push( message );
return message;
}
Chat.prototype.addMember = function(conn, username) {
this.state.member_count += 1;
var member = {
id: conn.id,
username: username,
status: 'connected',
color: this.colors.shift()
};
this.state.members[conn.id] = member;
return member;
}
Chat.prototype.getMemberColor = function(id) {
return this.state.members[id].color;
}
Chat.prototype.getState = function(){
return this.state;
}
Chat.prototype.replaceUrls = function(message) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return message.replace(exp,"<a target='_blank' href='$1'>$1</a>");
}
exports.Chat = Chat;
| Add replace urls text to replace urls with proper links | Add replace urls text to replace urls with proper links
| JavaScript | unlicense | mcramm/LiveChat,mcramm/LiveChat | ---
+++
@@ -17,7 +17,7 @@
Chat.prototype.addMessage = function(conn, message) {
var message = {
user_id: conn.id,
- message: message,
+ message: this.replaceUrls(message),
color: this.getMemberColor( conn.id )
};
@@ -48,4 +48,9 @@
return this.state;
}
+Chat.prototype.replaceUrls = function(message) {
+ var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
+ return message.replace(exp,"<a target='_blank' href='$1'>$1</a>");
+}
+
exports.Chat = Chat; |
100476c4c6a0c7530b5bf711287aced1d2b46611 | src/console-logger.js | src/console-logger.js | define([
'aux/has-property'
], function (hasProperty) {
/**
* Using the browsers console logging options, allowing to use console.error if accessible otherwise fallsback to
* console.log (again if accessible).
*
* @exports console-logger
*
* @requires module:has-property
*
* @param {*} message Message to log out
* @param {String} type What logging system to use error, log (defaults to log).
*/
function logger (message, type) {
type = type || 'log';
if (hasProperty(window, 'console.' + type)) {
console[type](message);
} else if (hasProperty(window, 'console.log')) {
console.log(message);
}
}
return logger;
});
| define([
'aux/is-defined'
], function (isDefined) {
/**
* Using the browsers console logging options, allowing to use console.error if accessible otherwise fallsback to
* console.log (again if accessible).
*
* @exports console-logger
*
* @requires module:is-defined
*
* @param {*} message Message to log out
* @param {String} type What logging system to use error, log (defaults to log).
*/
function logger (message, type) {
var console = window.console;
type = type || 'log';
if (isDefined(console[type], 'function')) {
console[type](message);
} else if (isDefined(console.log, 'function')) {
console.log(message);
}
}
return logger;
});
| Use is defined to check is a function not has property | Use is defined to check is a function not has property
| JavaScript | mit | rockabox/Auxilium.js | ---
+++
@@ -1,23 +1,24 @@
define([
- 'aux/has-property'
-], function (hasProperty) {
+ 'aux/is-defined'
+], function (isDefined) {
/**
* Using the browsers console logging options, allowing to use console.error if accessible otherwise fallsback to
* console.log (again if accessible).
*
* @exports console-logger
*
- * @requires module:has-property
+ * @requires module:is-defined
*
* @param {*} message Message to log out
* @param {String} type What logging system to use error, log (defaults to log).
*/
function logger (message, type) {
+ var console = window.console;
type = type || 'log';
- if (hasProperty(window, 'console.' + type)) {
+ if (isDefined(console[type], 'function')) {
console[type](message);
- } else if (hasProperty(window, 'console.log')) {
+ } else if (isDefined(console.log, 'function')) {
console.log(message);
}
} |
f0543ec50fea760d243cdf0b3d3b15f9a2c8adcd | src/core/transform.js | src/core/transform.js | import pluck from './pluck';
import {
noop,
mixin,
observable,
insertCss,
emptyTemplate,
computedAll,
pureComputedAll
} from '../util/';
const modulePolyfill = {
constructor: noop,
defaults: {},
template: emptyTemplate
};
// Transform transiton component module to native component module
//
// @param {Object} module Transiton component module
// @return {Object} Native component module
function transform(module) {
const {
name,
constructor,
defaults,
props,
mixins,
methods,
computed,
pureComputed,
style,
template
} = Object.assign({}, modulePolyfill, module);
insertCss(module.style);
Object.assign(constructor.prototype, methods);
return {
viewModel: {
createViewModel(params, componentInfo) {
componentInfo.name = name;
const opts = Object.assign(
{},
defaults,
ko.toJS(params),
pluck(componentInfo.element)
);
const vm = new constructor(opts, componentInfo);
props && Object.assign(vm, observable(opts, props));
mixins && mixin(vm, opts, mixins);
computed && computedAll(vm, computed);
pureComputed && pureComputedAll(vm, pureComputed);
vm.$opts = opts;
vm.$defaults = defaults;
vm.$info = vm.componentInfo = componentInfo;
delete vm.$opts['$raw'];
delete vm.$defaults['$raw'];
return vm;
}
},
synchronous: true,
template
};
}
export default transform;
| import pluck from './pluck';
import {
noop,
mixin,
observable,
insertCss,
emptyTemplate,
computedAll,
pureComputedAll
} from '../util/';
const modulePolyfill = {
defaults: {},
template: emptyTemplate
};
// Transform transiton component module to native component module
//
// @param {Object} module Transiton component module
// @return {Object} Native component module
function transform(module) {
const {
name,
constructor,
defaults,
props,
mixins,
methods,
computed,
pureComputed,
style,
template
} = Object.assign({
constructor: function() {}
}, modulePolyfill, module);
insertCss(module.style);
Object.assign(constructor.prototype, methods);
return {
viewModel: {
createViewModel(params, componentInfo) {
componentInfo.name = name;
const opts = Object.assign(
{},
defaults,
ko.toJS(params),
pluck(componentInfo.element)
);
const vm = new constructor(opts, componentInfo);
props && Object.assign(vm, observable(opts, props));
mixins && mixin(vm, opts, mixins);
computed && computedAll(vm, computed);
pureComputed && pureComputedAll(vm, pureComputed);
vm.$opts = opts;
vm.$defaults = defaults;
vm.$info = vm.componentInfo = componentInfo;
delete vm.$opts['$raw'];
delete vm.$defaults['$raw'];
return vm;
}
},
synchronous: true,
template
};
}
export default transform;
| Fix constructor shared between components | Fix constructor shared between components
| JavaScript | mit | baza-fe/knockout.register | ---
+++
@@ -10,7 +10,6 @@
} from '../util/';
const modulePolyfill = {
- constructor: noop,
defaults: {},
template: emptyTemplate
};
@@ -31,7 +30,9 @@
pureComputed,
style,
template
- } = Object.assign({}, modulePolyfill, module);
+ } = Object.assign({
+ constructor: function() {}
+ }, modulePolyfill, module);
insertCss(module.style);
Object.assign(constructor.prototype, methods);
@@ -54,7 +55,6 @@
computed && computedAll(vm, computed);
pureComputed && pureComputedAll(vm, pureComputed);
-
vm.$opts = opts;
vm.$defaults = defaults;
vm.$info = vm.componentInfo = componentInfo; |
994b65315cc7c678f3b8bae26a3956fb0ae4c5b6 | card-renderer/webpack.config.js | card-renderer/webpack.config.js | const path = require("path");
const webpack = require("webpack");
var MINIFY = new webpack.optimize.UglifyJsPlugin({minimize: true});
module.exports = {
name: "sunwell-card-renderer",
target: "node",
entry: {
sunwell: path.join(__dirname, "sunwell-card-renderer.js"),
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "sunwell-card-renderer.js",
},
resolve: {
extensions: [".webpack.js", ".web.js", ".ts", ".js", ".node"],
},
node: {
"fs": "empty",
},
module: {
loaders: [
{
test: /\.ts$/,
loaders: [
"ts-loader",
],
}, {
test: /\.node$/,
loaders: ["node-loader"],
}
],
},
plugins: [/*MINIFY*/], // ES6 unsupported by uglifyjs
};
| const path = require("path");
const webpack = require("webpack");
var MINIFY = new webpack.optimize.UglifyJsPlugin({minimize: true});
module.exports = {
name: "sunwell-card-renderer",
target: "node",
entry: {
sunwell: path.join(__dirname, "sunwell-card-renderer.js"),
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "sunwell-card-renderer.js",
},
resolve: {
extensions: [".webpack.js", ".web.js", ".ts", ".js", ".node"],
},
node: {
"__dirname": false,
"__filename": false,
"fs": "empty",
},
module: {
loaders: [
{
test: /\.ts$/,
loaders: [
"ts-loader",
],
}, {
test: /\.node$/,
loaders: ["node-loader"],
}
],
},
plugins: [/*MINIFY*/], // ES6 unsupported by uglifyjs
};
| Fix __dirname and __filename in sunwell-card-renderer | Fix __dirname and __filename in sunwell-card-renderer
References webpack/webpack#1599
| JavaScript | mit | HearthSim/Sunwell,HearthSim/Sunwell,Paratron/sunwell,HearthSim/Sunwell | ---
+++
@@ -18,6 +18,8 @@
extensions: [".webpack.js", ".web.js", ".ts", ".js", ".node"],
},
node: {
+ "__dirname": false,
+ "__filename": false,
"fs": "empty",
},
module: { |
5eb95b5fd34979a8d2e3d5dfe3a912d41d81fdc4 | lib/ember-qunit/test-wrapper.js | lib/ember-qunit/test-wrapper.js | import Ember from 'ember';
import { getContext } from 'ember-test-helpers';
export default function testWrapper(testName, callback, qunit) {
function wrapper(assert) {
var context = getContext();
var result = callback.call(context, assert);
function failTestOnPromiseRejection(reason) {
var message;
if (reason instanceof Error) {
message = reason.stack;
if (reason.message && message.indexOf(reason.message) < 0) {
// PhantomJS has a `stack` that does not contain the actual
// exception message.
message = Ember.inspect(reason) + "\n" + message;
}
} else {
message = Ember.inspect(reason);
}
ok(false, message);
}
Ember.run(function(){
QUnit.stop();
Ember.RSVP.Promise.resolve(result)['catch'](failTestOnPromiseRejection)['finally'](QUnit.start);
});
}
qunit(testName, wrapper);
}
| import Ember from 'ember';
import { getContext } from 'ember-test-helpers';
export default function testWrapper(testName, callback, qunit) {
function wrapper() {
var context = getContext();
var result = callback.apply(context, arguments);
function failTestOnPromiseRejection(reason) {
var message;
if (reason instanceof Error) {
message = reason.stack;
if (reason.message && message.indexOf(reason.message) < 0) {
// PhantomJS has a `stack` that does not contain the actual
// exception message.
message = Ember.inspect(reason) + "\n" + message;
}
} else {
message = Ember.inspect(reason);
}
ok(false, message);
}
Ember.run(function(){
QUnit.stop();
Ember.RSVP.Promise.resolve(result)['catch'](failTestOnPromiseRejection)['finally'](QUnit.start);
});
}
qunit(testName, wrapper);
}
| Change test wrapper callback from `call` to `apply` | Change test wrapper callback from `call` to `apply`
| JavaScript | mit | rwjblue/ember-qunit,OrKoN/ember-qunit,emberjs/ember-qunit,OrKoN/ember-qunit,rwjblue/ember-qunit,OrKoN/ember-qunit,emberjs/ember-qunit | ---
+++
@@ -2,10 +2,10 @@
import { getContext } from 'ember-test-helpers';
export default function testWrapper(testName, callback, qunit) {
- function wrapper(assert) {
+ function wrapper() {
var context = getContext();
- var result = callback.call(context, assert);
+ var result = callback.apply(context, arguments);
function failTestOnPromiseRejection(reason) {
var message; |
2b57827c7b8c552c7e84bc8b1ad44d54baab894b | app/javascript/components/Events/PerformanceCompetition/Show/Maps/RoundMap/CompetitorsList/CompetitorResult/ExitAltitude.js | app/javascript/components/Events/PerformanceCompetition/Show/Maps/RoundMap/CompetitorsList/CompetitorResult/ExitAltitude.js | import React from 'react'
import PropTypes from 'prop-types'
import { useI18n } from 'components/TranslationsProvider'
const maxAltitude = 3353
const minAltitude = 3200
const ExitAltitude = ({ altitude }) => {
const { t } = useI18n()
if (!altitude) return null
const showWarning = altitude < minAltitude || altitude > maxAltitude
return (
<span>
Exit: {altitude}m
{showWarning && (
<>
<i className="fas fa-exclamation-triangle text-warning" />
</>
)} {t('units.m')}
</span>
)
}
ExitAltitude.propTypes = {
altitude: PropTypes.number
}
ExitAltitude.defaultProps = {
altitude: undefined
}
export default ExitAltitude
| import React from 'react'
import PropTypes from 'prop-types'
import { useI18n } from 'components/TranslationsProvider'
const maxAltitude = 3353
const minAltitude = 3200
const ExitAltitude = ({ altitude }) => {
const { t } = useI18n()
if (!altitude) return null
const showWarning = altitude < minAltitude || altitude > maxAltitude
return (
<span>
Exit: {altitude} {t('units.m')}
{showWarning && (
<>
<i className="fas fa-exclamation-triangle text-warning" />
</>
)}
</span>
)
}
ExitAltitude.propTypes = {
altitude: PropTypes.number
}
ExitAltitude.defaultProps = {
altitude: undefined
}
export default ExitAltitude
| Fix exit altitude units placement | Fix exit altitude units placement
| JavaScript | agpl-3.0 | skyderby/skyderby,skyderby/skyderby,skyderby/skyderby,skyderby/skyderby,skyderby/skyderby | ---
+++
@@ -14,13 +14,13 @@
return (
<span>
- Exit: {altitude}m
+ Exit: {altitude} {t('units.m')}
{showWarning && (
<>
<i className="fas fa-exclamation-triangle text-warning" />
</>
- )} {t('units.m')}
+ )}
</span>
)
} |
7a95e0e019d30775933440add700b8a2822828cb | server.js | server.js | // server.js
/**IMPORT**/
var express = require('express');
var url = require('url');
var inject_pipe = require('./inject-pipe.js');
/** SET **/
var app = express();
/**FUNCTION**/
function sendViewMiddleware(req, res, next) { //send .html
res.sendHtml = function(html) {
return res.sendFile(__dirname + "/" + html);
}
next();
}
app.use(sendViewMiddleware);
/**GET**/
app.get('/', function (req, res) { //主页
console.log("[SERVER][GET] /");
res.sendHtml('index.html');
});
app.get('/pipe', function (req, res) { //pipe
console.log("[SERVER][GET] /pipe");
var params = url.parse(req.url,true).query;
console.log(params);
var href = params['href']
inject_pipe.pipe(href,function(html){
res.send(html);
});
});
/**启动服务器**/
var server = app.listen(10000, function () {
var host = server.address().address
var port = server.address().port
console.log("Sever Start @ http://%s:%s", host, port)
}); //于指定端口启动服务器
| // server.js
/**IMPORT**/
var express = require('express');
var url = require('url');
var inject_piper = require('./inject-piper.js');
/** SET **/
var app = express();
/**FUNCTION**/
function sendViewMiddleware(req, res, next) { //send .html
res.sendHtml = function(html) {
return res.sendFile(__dirname + "/" + html);
}
next();
}
app.use(sendViewMiddleware);
/**GET**/
app.get('/', function (req, res) { //主页
console.log("[SERVER][GET] /");
res.sendHtml('index.html');
});
app.get('/pipe', function (req, res) { //pipe
console.log("[SERVER][GET] /pipe");
var params = url.parse(req.url,true).query;
if (params.length>0){
console.log(params);
var href = params['href']
inject_piper.pipe(href,function(html){
res.send(html);
});
}else{
res.sendHtml('index.html');
}
});
/**启动服务器**/
var server = app.listen(10000, function () {
var host = server.address().address
var port = server.address().port
console.log("Sever Start @ http://%s:%s", host, port)
}); //于指定端口启动服务器
| Fix page /pipe 's error. | Fix page /pipe 's error. | JavaScript | mit | Pingze-github/inject-piper,Pingze-github/inject-piper | ---
+++
@@ -3,7 +3,7 @@
/**IMPORT**/
var express = require('express');
var url = require('url');
-var inject_pipe = require('./inject-pipe.js');
+var inject_piper = require('./inject-piper.js');
/** SET **/
var app = express();
@@ -26,11 +26,15 @@
app.get('/pipe', function (req, res) { //pipe
console.log("[SERVER][GET] /pipe");
var params = url.parse(req.url,true).query;
- console.log(params);
- var href = params['href']
- inject_pipe.pipe(href,function(html){
- res.send(html);
- });
+ if (params.length>0){
+ console.log(params);
+ var href = params['href']
+ inject_piper.pipe(href,function(html){
+ res.send(html);
+ });
+ }else{
+ res.sendHtml('index.html');
+ }
});
/**启动服务器**/ |
63593527222d7316a3078a4a4bc93a4f008cc3b5 | server.js | server.js | var path = require("path");
var express = require("express");
var webpack = require("webpack");
var config = Object.assign({}, require("./webpack.docs.config"));
config.devtool = "cheap-module-eval-source-map";
config.entry.unshift("webpack-hot-middleware/client");
config.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
);
var app = express();
var compiler = webpack(config);
app.use(require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require("webpack-hot-middleware")(compiler));
app.use(express.static("docs"));
app.listen(8080, "localhost", function(err) {
if (err) {
console.log(err);
return;
}
console.log("Listening at http://localhost:8080");
});
| var path = require("path");
var express = require("express");
var webpack = require("webpack");
var merge = require("lodash/object/merge");
var config = merge({}, require("./webpack.docs.config"));
config.devtool = "cheap-module-eval-source-map";
config.entry.unshift("webpack-hot-middleware/client");
config.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
);
var app = express();
var compiler = webpack(config);
app.use(require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require("webpack-hot-middleware")(compiler));
app.use(express.static("docs"));
app.listen(8080, "localhost", function(err) {
if (err) {
console.log(err);
return;
}
console.log("Listening at http://localhost:8080");
});
| Remove Object.assign for node v0.12 compatibility | Remove Object.assign for node v0.12 compatibility
| JavaScript | mit | marketplacer/react-datepicker,mitchrosu/react-datepicker,flexport/react-datepicker,lmenus/react-datepicker,sss0791/react-datepicker,lmenus/react-datepicker,BrunoAlcides/react-datepicker,BrunoAlcides/react-datepicker,bekerov/react-datepicker-roco,Hacker0x01/react-datepicker,bekerov/react-datepicker-roco,marketplacer/react-datepicker,lmenus/react-datepicker,BrunoAlcides/react-datepicker,Hacker0x01/react-datepicker,flexport/react-datepicker,Hacker0x01/react-datepicker,bekerov/react-datepicker-roco,mitchrosu/react-datepicker,marketplacer/react-datepicker,flexport/react-datepicker,mitchrosu/react-datepicker | ---
+++
@@ -1,7 +1,8 @@
var path = require("path");
var express = require("express");
var webpack = require("webpack");
-var config = Object.assign({}, require("./webpack.docs.config"));
+var merge = require("lodash/object/merge");
+var config = merge({}, require("./webpack.docs.config"));
config.devtool = "cheap-module-eval-source-map";
config.entry.unshift("webpack-hot-middleware/client"); |
d0d4c04949e0310f2040032afc8ec90648757dd9 | server.js | server.js | var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express()
, port = process.env.PORT || 5000;
app.use(express.static(__dirname + '/'));
var server = http.createServer(app);
server.listen(port);
console.log('http server listening on %d', port);
var mapper = require('./server/mapper.js');
var wss = new WebSocketServer({server: server});
console.log('websocket server created');
wss.on('connection', function(ws) {
function newClient() {
var numberOfUpdatesMade = 0;
function getEmailsAndUpdateClients() {
numberOfUpdatesMade ++;
if (numberOfUpdatesMade < 20) {
console.log('checking for updates (' + numberOfUpdatesMade + ')');
var currentData = mapper.readEmail(function(emailData, changes) {
if(changes || numberOfUpdatesMade === 1) {
console.log('CHANGES!');
ws.send(JSON.stringify(emailData), function() { });
} else {
console.log('no changes');
}
});
}
}
getEmailsAndUpdateClients();
var id = setInterval(getEmailsAndUpdateClients, 5000);
return id;
}
var clientId = newClient();
console.log('websocket connection open');
ws.on('close', function() {
console.log('websocket connection close');
clearInterval(clientId);
});
});
| var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express()
, port = process.env.PORT || 5000;
app.use(express.static(__dirname + '/'));
var server = http.createServer(app);
server.listen(port);
console.log('http server listening on %d', port);
var mapper = require('./server/mapper.js');
var wss = new WebSocketServer({server: server});
console.log('websocket server created');
wss.on('connection', function(ws) {
function newClient() {
var numberOfUpdatesMade = 0;
function getEmailsAndUpdateClients() {
numberOfUpdatesMade ++;
if (numberOfUpdatesMade < 20) {
console.log('checking for updates (' + numberOfUpdatesMade + ')');
var currentData = mapper.readEmail(function(emailData, changes) {
if(changes || numberOfUpdatesMade <= 2) {
console.log('CHANGES!');
ws.send(JSON.stringify(emailData), function() { });
} else {
console.log('no changes');
}
});
}
}
getEmailsAndUpdateClients();
var id = setInterval(getEmailsAndUpdateClients, 5000);
return id;
}
var clientId = newClient();
console.log('websocket connection open');
ws.on('close', function() {
console.log('websocket connection close');
clearInterval(clientId);
});
});
| Make sure client gets update after a refresh | Make sure client gets update after a refresh
| JavaScript | mit | artwise/artwise,artwise/artwise,birgitta410/monart,birgitta410/monart,birgitta410/monart,artwise/artwise | ---
+++
@@ -28,7 +28,7 @@
if (numberOfUpdatesMade < 20) {
console.log('checking for updates (' + numberOfUpdatesMade + ')');
var currentData = mapper.readEmail(function(emailData, changes) {
- if(changes || numberOfUpdatesMade === 1) {
+ if(changes || numberOfUpdatesMade <= 2) {
console.log('CHANGES!');
ws.send(JSON.stringify(emailData), function() { });
} else { |
8a18760db14efdb66fa11492214ce39fe7f1cd31 | angular/rollup-config.js | angular/rollup-config.js | import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
export default {
entry: 'src/main-aot.js',
dest: 'dist/build.js', // output a single application bundle
sourceMap: false,
format: 'iife',
onwarn: function(warning) {
// Skip certain warnings
// should intercept ... but doesn't in some rollup versions
if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }
// console.warn everything else
console.warn( warning.message );
},
plugins: [
nodeResolve({jsnext: true, module: true}),
commonjs({
include: 'node_modules/rxjs/**',
}),
uglify()
]
};
| import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
export default {
entry: 'src/main-aot.js',
dest: 'dist/build.js', // output a single application bundle
sourceMap: false,
format: 'iife',
onwarn: function(warning) {
// Skip certain warnings
// should intercept ... but doesn't in some rollup versions
if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }
// console.warn everything else
console.warn( warning.message );
},
plugins: [
nodeResolve({jsnext: true, module: true}),
commonjs({
include: [
'node_modules/rxjs/**',
'node_modules/ng-lazyload-image/**'
]
}),
uglify()
]
};
| Fix rollup for lazy load image | Fix rollup for lazy load image
| JavaScript | mit | waxe/waxe-image,waxe/waxe-image,waxe/waxe-image,waxe/waxe-image,waxe/waxe-image | ---
+++
@@ -19,7 +19,10 @@
plugins: [
nodeResolve({jsnext: true, module: true}),
commonjs({
- include: 'node_modules/rxjs/**',
+ include: [
+ 'node_modules/rxjs/**',
+ 'node_modules/ng-lazyload-image/**'
+ ]
}),
uglify()
] |
70fd5dd1b056544b6dd0177f31aa6c06537fa2da | server/scoring.js | server/scoring.js | // TODO: should the baseScore be stored, and updated at vote time?
// This interface should change and become more OO, this'll do for now
var Scoring = {
// re-run the scoring algorithm on a single object
updateObject: function(object) {
if(isNaN(object.score)){
object.score=0;
}
// just count the number of votes for now
var baseScore = object.votes;
// now multiply by 'age' exponentiated
// FIXME: timezones <-- set by server or is getTime() ok?
var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000);
object.score = baseScore * Math.pow(ageInHours + 2, -0.1375);
},
// rerun all the scoring -- TODO: should we check to see if the score has
// changed before saving?
updateScores: function() {
Posts.find().forEach(function(post) {
Scoring.updateObject(post);
Posts.update(post._id, {$set: {score: post.score}});
});
Comments.find().forEach(function(comment) {
Scoring.updateObject(comment);
Comments.update(comment._id, {$set: {score: comment.score}});
});
}
}
Meteor.Cron = new Cron();
Meteor.Cron.addJob(1, function() {
Scoring.updateScores();
}) | // TODO: should the baseScore be stored, and updated at vote time?
// This interface should change and become more OO, this'll do for now
var Scoring = {
// re-run the scoring algorithm on a single object
updateObject: function(object) {
if(isNaN(object.score)){
object.score=0;
}
// just count the number of votes for now
var baseScore = object.votes;
// now multiply by 'age' exponentiated
// FIXME: timezones <-- set by server or is getTime() ok?
var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000);
object.score = baseScore * Math.pow(ageInHours + 2, -0.1375);
},
// rerun all the scoring -- TODO: should we check to see if the score has
// changed before saving?
updateScores: function() {
Posts.find().forEach(function(post) {
Scoring.updateObject(post);
Posts.update(post._id, {$set: {score: post.score}});
});
Comments.find().forEach(function(comment) {
Scoring.updateObject(comment);
Comments.update(comment._id, {$set: {score: comment.score}});
});
}
}
// tick every second
Meteor.Cron = new Cron(1000);
// update scores every 10 seconds
Meteor.Cron.addJob(10, function() {
Scoring.updateScores();
}) | Change to updating every 10s | Change to updating every 10s
| JavaScript | mit | vlipco/startupcol-telescope,vlipco/startupcol-telescope | ---
+++
@@ -34,7 +34,9 @@
}
}
-Meteor.Cron = new Cron();
-Meteor.Cron.addJob(1, function() {
+// tick every second
+Meteor.Cron = new Cron(1000);
+// update scores every 10 seconds
+Meteor.Cron.addJob(10, function() {
Scoring.updateScores();
}) |
8a7fa7bf822b1827c0ca4dbe4b60659c971e4b0e | javascript_client/sync/__tests__/generateClientTest.js | javascript_client/sync/__tests__/generateClientTest.js | var { generateClient } = require("../generateClient")
it("returns generated code", function() {
var code = generateClient({
path: "./__tests__/documents/*.graphql",
clientName: "test-client",
})
expect(code).toMatchSnapshot()
})
| var { generateClient } = require("../generateClient")
it("returns generated code", function() {
var code = generateClient({
path: "./__tests__/documents/*.graphql",
client: "test-client",
})
expect(code).toMatchSnapshot()
})
| Update specs to reflect options key change | Update specs to reflect options key change
| JavaScript | mit | nevesenin/graphql-ruby,rmosolgo/graphql-ruby,xuorig/graphql-ruby,nevesenin/graphql-ruby,nevesenin/graphql-ruby,nevesenin/graphql-ruby,rmosolgo/graphql-ruby,rmosolgo/graphql-ruby,xuorig/graphql-ruby,xuorig/graphql-ruby,rmosolgo/graphql-ruby | ---
+++
@@ -3,7 +3,7 @@
it("returns generated code", function() {
var code = generateClient({
path: "./__tests__/documents/*.graphql",
- clientName: "test-client",
+ client: "test-client",
})
expect(code).toMatchSnapshot()
}) |
0895b03d80a5ad062c823d12b52346c882d40910 | src/Collection.js | src/Collection.js | VIE.prototype.Collection = Backbone.Collection.extend({
model: VIE.prototype.Entity,
get: function(id) {
if (!this.models.length) {
return null;
}
if (this.models[0].isReference(id)) {
id = this.models[0].fromReference(id);
}
if (id == null) return null;
return this._byId[id.id != null ? id.id : id];
},
addOrUpdate: function(model) {
var collection = this;
if (_.isArray(model)) {
var entities = [];
_.each(model, function(item) {
entities.push(collection.addOrUpdate(item));
});
return entities;
}
if (!model.isEntity) {
model = new this.model(model);
}
if (!model.id) {
this.add(model);
return model;
}
if (this.get(model.id)) {
var existing = this.get(model.id);
if (model.attributes) {
return existing.set(model.attributes);
}
return existing.set(model);
}
this.add(model);
return model;
}
});
| VIE.prototype.Collection = Backbone.Collection.extend({
model: VIE.prototype.Entity,
get: function(id) {
if (!this.models.length) {
return null;
}
if (!this.models[0].isReference(id)) {
id = this.models[0].toReference(id);
}
if (id == null) return null;
return this._byId[id.id != null ? id.id : id];
},
addOrUpdate: function(model) {
var collection = this;
if (_.isArray(model)) {
var entities = [];
_.each(model, function(item) {
entities.push(collection.addOrUpdate(item));
});
return entities;
}
if (!model.isEntity) {
model = new this.model(model);
}
if (!model.id) {
this.add(model);
return model;
}
if (this.get(model.id)) {
var existing = this.get(model.id);
if (model.attributes) {
return existing.set(model.attributes);
}
return existing.set(model);
}
this.add(model);
return model;
}
});
| Put reference handling correct way around | Put reference handling correct way around
| JavaScript | mit | bergie/VIE,bergie/VIE | ---
+++
@@ -5,8 +5,8 @@
if (!this.models.length) {
return null;
}
- if (this.models[0].isReference(id)) {
- id = this.models[0].fromReference(id);
+ if (!this.models[0].isReference(id)) {
+ id = this.models[0].toReference(id);
}
if (id == null) return null;
return this._byId[id.id != null ? id.id : id]; |
61b54f4bc854b83da47680b168350d34a5e67350 | js/generator.js | js/generator.js | GAME.setConsts({
SHIT : 1
});
GAME.Generator = (function() {
var wow = false;
function generate(level) {
width = level.size[width];
height = level.size[height];
// generate tilemap full of floor
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
tilemap[i][j] = FLOOR_TILE;
}
}
// shitty generation
// every 10th tile is a wall
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
if (Math.random > 0.9) {
tilemap[i][j] = WALL_TILE;
}
}
}
return level;
}
return {
generate : generate
}
})(); | GAME.setConsts({
SHIT : 1
});
GAME.Generator = (function() {
var wow = false;
function generate(level) {
width = level.size.width;
height = level.size.height;
// generate tilemap full of floor
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
tilemap[i][j] = FLOOR_TILE;
}
}
// shitty generation
// every 10th tile is a wall
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
if (Math.random > 0.9) {
tilemap[i][j] = WALL_TILE;
}
}
}
return level;
}
return {
generate : generate
}
})(); | Use dots instead of index notation | Use dots instead of index notation
| JavaScript | mit | Hypersonic/FreezeFrame | ---
+++
@@ -7,8 +7,8 @@
var wow = false;
function generate(level) {
- width = level.size[width];
- height = level.size[height];
+ width = level.size.width;
+ height = level.size.height;
// generate tilemap full of floor
for (var i = 0; i < width; i++) { |
ac555053fea84aa2f2a364ceb1e8adf5fc41fff8 | src/actions.js | src/actions.js | import assign from 'object-assign';
import { store } from './helpers';
export const MENU_SHOW = 'REACT_CONTEXTMENU_SHOW';
export const MENU_HIDE = 'REACT_CONTEXTMENU_HIDE';
export function dispatchGlobalEvent(eventName, opts, target = window) {
// Compatibale with IE
// @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work
let event;
if (typeof window.CustomEvent === 'function') {
event = new window.CustomEvent(eventName, { detail: opts });
} else {
event = document.createEvent('Event');
event.initCustomEvent(eventName, false, true, opts);
}
if (target) {
target.dispatchEvent(event);
assign(store, opts);
}
}
export function showMenu(opts = {}, target) {
dispatchGlobalEvent(MENU_SHOW, assign({}, opts, {type: MENU_SHOW}), target);
}
export function hideMenu(opts = {}, target) {
dispatchGlobalEvent(MENU_HIDE, assign({}, opts, {type: MENU_HIDE}), target);
}
| import assign from 'object-assign';
import { store } from './helpers';
export const MENU_SHOW = 'REACT_CONTEXTMENU_SHOW';
export const MENU_HIDE = 'REACT_CONTEXTMENU_HIDE';
export function dispatchGlobalEvent(eventName, opts, target = window) {
// Compatibale with IE
// @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work
let event;
if (typeof window.CustomEvent === 'function') {
event = new window.CustomEvent(eventName, { detail: opts });
} else {
event = document.createEvent('CustomEvent');
event.initCustomEvent(eventName, false, true, opts);
}
if (target) {
target.dispatchEvent(event);
assign(store, opts);
}
}
export function showMenu(opts = {}, target) {
dispatchGlobalEvent(MENU_SHOW, assign({}, opts, {type: MENU_SHOW}), target);
}
export function hideMenu(opts = {}, target) {
dispatchGlobalEvent(MENU_HIDE, assign({}, opts, {type: MENU_HIDE}), target);
}
| Fix for IE11 custom event | Fix for IE11 custom event
| JavaScript | mit | codeart1st/react-contextmenu,danbovey/react-contextmenu,vkbansal/react-contextmenu,danbovey/react-contextmenu,codeart1st/react-contextmenu,vkbansal/react-contextmenu | ---
+++
@@ -14,7 +14,7 @@
if (typeof window.CustomEvent === 'function') {
event = new window.CustomEvent(eventName, { detail: opts });
} else {
- event = document.createEvent('Event');
+ event = document.createEvent('CustomEvent');
event.initCustomEvent(eventName, false, true, opts);
}
|
92360f00fb7dc4188b85bab20dd1e0149aae2f67 | Resources/public/js/admin.js | Resources/public/js/admin.js | /**
* Created by mkurc1 on 15/06/16.
*/
| (function ($) {
$(function () {
hideTranslationTabForOneLanguage();
});
function hideTranslationTabForOneLanguage() {
$('ul.a2lix_translationsLocales').each(function() {
console.log($(this).children('li').size());
if ($(this).children('li').size() < 2) {
$(this).hide();
}
});
}
})(jQuery); | Hide translation tab for available one language | Hide translation tab for available one language
| JavaScript | mit | mkurc1/PurethinkCMSBundle,mkurc1/PurethinkCMSBundle | ---
+++
@@ -1,3 +1,16 @@
-/**
- * Created by mkurc1 on 15/06/16.
- */
+(function ($) {
+
+ $(function () {
+ hideTranslationTabForOneLanguage();
+ });
+
+ function hideTranslationTabForOneLanguage() {
+ $('ul.a2lix_translationsLocales').each(function() {
+ console.log($(this).children('li').size());
+ if ($(this).children('li').size() < 2) {
+ $(this).hide();
+ }
+ });
+ }
+
+})(jQuery); |
192cfe18d70b241e6b3dc7091f7b568cfff03784 | scripts/FriendlyEats.Data.js | scripts/FriendlyEats.Data.js | /**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
FriendlyEats.prototype.addRestaurant = function(data) {
/*
TODO: Implement adding a document
*/
};
FriendlyEats.prototype.getAllRestaurants = function(render) {
/*
TODO: Retrieve list of restaurants
*/
};
FriendlyEats.prototype.getDocumentsInQuery = function(query, render) {
/*
TODO: Render all documents in the provided query
*/
};
FriendlyEats.prototype.getRestaurant = function(id) {
/*
TODO: Retrieve a single restaurant
*/
};
FriendlyEats.prototype.getFilteredRestaurants = function(filters, render) {
/*
TODO: Retrieve filtered list of restaurants
*/
};
FriendlyEats.prototype.addRating = function(restaurantID, rating) {
/*
TODO: Retrieve add a rating to a restaurant
*/
}; | /**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
FriendlyEats.prototype.addRestaurant = function(data) {
/*
TODO: Implement adding a document
*/
};
FriendlyEats.prototype.getAllRestaurants = function(renderer) {
/*
TODO: Retrieve list of restaurants
*/
};
FriendlyEats.prototype.getDocumentsInQuery = function(query, renderer) {
/*
TODO: Render all documents in the provided query
*/
};
FriendlyEats.prototype.getRestaurant = function(id) {
/*
TODO: Retrieve a single restaurant
*/
};
FriendlyEats.prototype.getFilteredRestaurants = function(filters, render) {
/*
TODO: Retrieve filtered list of restaurants
*/
};
FriendlyEats.prototype.addRating = function(restaurantID, rating) {
/*
TODO: Retrieve add a rating to a restaurant
*/
}; | Fix few code to match the doc | Fix few code to match the doc
| JavaScript | apache-2.0 | firebase/friendlyeats-web,firebase/friendlyeats-web,firebase/friendlyeats-web | ---
+++
@@ -21,13 +21,13 @@
*/
};
-FriendlyEats.prototype.getAllRestaurants = function(render) {
+FriendlyEats.prototype.getAllRestaurants = function(renderer) {
/*
TODO: Retrieve list of restaurants
*/
};
-FriendlyEats.prototype.getDocumentsInQuery = function(query, render) {
+FriendlyEats.prototype.getDocumentsInQuery = function(query, renderer) {
/*
TODO: Render all documents in the provided query
*/ |
e5c6984044d4db25901cf5a9798437d591e02011 | src/main/resources/archetype-resources/src/main/webapp/js/app/controllers.js | src/main/resources/archetype-resources/src/main/webapp/js/app/controllers.js | #set( $prefix=$className.toLowerCase())
#set( $symbol_dollar = '$' )
'use strict';
function ${className}ListController($scope, $location, ${className}) {
$scope.${prefix}s = ${className}.query();
$scope.goto${className}NewPage = function () {
${symbol_dollar}location.path("/${prefix}/new")
};
$scope.delete${className} = function (${prefix}) {
${prefix}.$delete({'id':${prefix}.id}, function () {
$location.path('/');
});
};
}
function ${className}DetailController($scope, $routeParams, $location, ${className}) {
$scope.${prefix} = ${className}.get({id:$routeParams.id}, function (${prefix}) {
});
$scope.goto${className}ListPage = function () {
$location.path("/")
};
}
function ${className}NewController($scope, $location, ${className}) {
$scope.submit = function () {
${className}.save($scope.$prefix, function ($prefix) {
$location.path('/');
});
};
$scope.gotoTodoListPage = function () {
$location.path("/")
};
}
| #set( $prefix=$className.toLowerCase())
#set( $symbol_dollar = '$' )
'use strict';
function ${className}ListController($scope, $location, ${className}) {
$scope.${prefix}s = ${className}.query();
$scope.goto${className}NewPage = function () {
${symbol_dollar}location.path("/${prefix}/new");
};
$scope.delete${className} = function (${prefix}) {
${prefix}.$delete({'id':${prefix}.id}, function () {
$location.path('/');
});
};
}
function ${className}DetailController($scope, $routeParams, $location, ${className}) {
$scope.${prefix} = ${className}.get({id:$routeParams.id}, function (${prefix}) {
});
$scope.goto${className}ListPage = function () {
$location.path("/");
};
}
function ${className}NewController($scope, $location, ${className}) {
$scope.submit = function () {
${className}.save($scope.$prefix, function ($prefix) {
$location.path('/');
});
};
$scope.gotoTodoListPage = function () {
$location.path("/");
};
}
| Fix warning in eclipse (missing ;) | Fix warning in eclipse (missing ;) | JavaScript | apache-2.0 | cheleb/spring-angular-archetype,cheleb/spring-angular-archetype | ---
+++
@@ -5,7 +5,7 @@
function ${className}ListController($scope, $location, ${className}) {
$scope.${prefix}s = ${className}.query();
$scope.goto${className}NewPage = function () {
- ${symbol_dollar}location.path("/${prefix}/new")
+ ${symbol_dollar}location.path("/${prefix}/new");
};
$scope.delete${className} = function (${prefix}) {
${prefix}.$delete({'id':${prefix}.id}, function () {
@@ -18,7 +18,7 @@
$scope.${prefix} = ${className}.get({id:$routeParams.id}, function (${prefix}) {
});
$scope.goto${className}ListPage = function () {
- $location.path("/")
+ $location.path("/");
};
}
@@ -29,6 +29,6 @@
});
};
$scope.gotoTodoListPage = function () {
- $location.path("/")
+ $location.path("/");
};
} |
7fa582863903a91465c066ae66b826d79053f5d9 | src/flash/util.js | src/flash/util.js | function descAccessor(get, set) {
return {
get: get,
set: set,
configurable: true,
enumerable: true
};
}
function descConst(val) {
return {
value: val,
configurable: true,
enumerable: true
};
}
function descMethod(func) {
return descProperty(func);
}
function descProperty(val) {
return {
value: val,
writable: true,
configurable: true,
enumerable: true
};
}
function illegalOperation() {
throw Error('Illegal Operation');
}
| function descAccessor(get, set) {
return {
get: get,
set: set,
configurable: true,
enumerable: true
};
}
function descConst(val) {
return {
value: val,
configurable: true,
enumerable: true
};
}
function descMethod(func) {
return descProp(func);
}
function descProp(val) {
return {
value: val,
writable: true,
enumerable: true
};
}
function illegalOperation() {
throw Error('Illegal Operation');
}
| Rename descProperty, make properties non-configurable by default. | Rename descProperty, make properties non-configurable by default.
| JavaScript | apache-2.0 | mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway | ---
+++
@@ -14,13 +14,12 @@
};
}
function descMethod(func) {
- return descProperty(func);
+ return descProp(func);
}
-function descProperty(val) {
+function descProp(val) {
return {
value: val,
writable: true,
- configurable: true,
enumerable: true
};
} |
d121e33e29ec436aadff03ba07fdb74d86202ccf | webpack.prod.js | webpack.prod.js | const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = merge(common, {
mode: 'production',
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
'css-loader',
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'assets/styles/main.[hash].css',
chunkFilename: 'assets/styles/[id].[hash].css',
// ignoreOrder: false,
}),
],
devtool: 'source-map',
});
| const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = merge(common, {
mode: 'production',
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'assets/styles/main.[hash].css',
chunkFilename: 'assets/styles/[id].[hash].css',
// ignoreOrder: false,
}),
],
devtool: 'source-map',
});
| Simplify webpack css module config | Simplify webpack css module config
| JavaScript | mit | benct/tomlin-web,benct/tomlin-web | ---
+++
@@ -8,12 +8,7 @@
rules: [
{
test: /\.css$/,
- use: [
- {
- loader: MiniCssExtractPlugin.loader,
- },
- 'css-loader',
- ],
+ use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
}, |
8183c08eaf0f6f2f07ff17bd2334fbf2c0d7e0e3 | js/jenkins-terminal-colors.js | js/jenkins-terminal-colors.js | $(document).ready(function() {
function transformText(text) {
text = text.replace(/\[0m/g, "</span>");
text = text.replace(/\[([0-9;]+)m/g, function (match, code, offset, string) {
return "<span class='jtc-" + code.replace(/;/g, ' jtc-') + "'>";
});
return text;
}
setInterval(function() {
$('pre').get(0).innerHTML = transformText($('pre').get(0).innerHTML);
}, 200);
});
| $(document).ready(function() {
function transformText(text) {
text = text.replace(/\[0m/g, "</span>");
text = text.replace(/\[([0-9;]+)m/g, function (match, code, offset, string) {
return "<span class='jtc-" + code.replace(/;/g, ' jtc-') + "'>";
});
return text;
}
function reformatExecute()
var pre_element = $('pre').get(0);
var original_inner_html = pre_element.innerHTML;
var reformated_inner_html = transformText(original_inner_html);
// Only update the content if it actually changed.
// The transformations in `transformText` will increase the text length if any happened.
var text_changed = (original_inner_html.length != reformated_inner_html.length);
if (text_changed) pre_element.innerHTML = reformated_inner_html;
pre_element = original_inner_html = reformated_inner_html = text_changed = undefined;
}
setInterval(reformatExecute, 200);
});
| Apply the new `innerHTML` only if the text have actually changed avoiding unnecessary HTML parses and DOM rendering | Apply the new `innerHTML` only if the text have actually changed avoiding unnecessary HTML parses and DOM rendering
| JavaScript | mit | M6Web/JenkinsTerminalColors | ---
+++
@@ -8,7 +8,18 @@
return text;
}
- setInterval(function() {
- $('pre').get(0).innerHTML = transformText($('pre').get(0).innerHTML);
- }, 200);
+ function reformatExecute()
+ var pre_element = $('pre').get(0);
+
+ var original_inner_html = pre_element.innerHTML;
+ var reformated_inner_html = transformText(original_inner_html);
+
+ // Only update the content if it actually changed.
+ // The transformations in `transformText` will increase the text length if any happened.
+ var text_changed = (original_inner_html.length != reformated_inner_html.length);
+ if (text_changed) pre_element.innerHTML = reformated_inner_html;
+
+ pre_element = original_inner_html = reformated_inner_html = text_changed = undefined;
+ }
+ setInterval(reformatExecute, 200);
}); |
7451fdad4c2e58bc89f80a6b7427cbd8ae9c604f | src/DragHandle.js | src/DragHandle.js | /* @flow */
import React from 'react';
import type {Element as ReactElement} from 'react';
import {findDOMNode} from 'react-dom';
type Props = {
onMouseDown: Function;
onTouchStart: Function;
children: ReactElement<any>;
};
export default class DragHandle extends React.Component<Props> {
componentDidMount() {
const node = findDOMNode(this);
if (!node) throw new Error('DragHandle missing element');
node.addEventListener('mousedown', this._onMouseDown);
node.addEventListener('touchstart', this._onTouchStart);
}
componentWillUnmount() {
const node = findDOMNode(this);
if (!node) throw new Error('DragHandle missing element');
node.removeEventListener('mousedown', this._onMouseDown);
node.removeEventListener('touchstart', this._onTouchStart);
}
_onMouseDown: Function = (e) => {
this.props.onMouseDown.call(null, e);
};
_onTouchStart: Function = (e) => {
this.props.onTouchStart.call(null, e);
};
render() {
return React.Children.only(this.props.children);
}
}
| /* @flow */
import React from 'react';
import type {Element as ReactElement} from 'react';
import {findDOMNode} from 'react-dom';
type Props = {
onMouseDown: Function;
onTouchStart: Function;
children: ReactElement<any>;
};
export default class DragHandle extends React.Component<Props> {
componentDidMount() {
const node = findDOMNode(this);
if (!node) throw new Error('DragHandle missing element');
node.addEventListener('mousedown', this._onMouseDown);
node.addEventListener('touchstart', this._onTouchStart);
}
componentWillUnmount() {
const node = findDOMNode(this);
if (!node) throw new Error('DragHandle missing element');
node.removeEventListener('mousedown', this._onMouseDown);
node.removeEventListener('touchstart', this._onTouchStart);
}
_onMouseDown: Function = (e) => {
this.props.onMouseDown.call(null, e);
};
_onTouchStart: Function = (e) => {
this.props.onTouchStart.call(null, e);
};
render() {
// TODO In next major version remove the need for findDOMNode by using React.cloneElement here.
// Update documentation to require that the element given to dragHandle is either
// a native DOM element or forwards its props to one.
return React.Children.only(this.props.children);
}
}
| Add TODO with plan for getting rid of findDOMNode in dragHandle | Add TODO with plan for getting rid of findDOMNode in dragHandle
| JavaScript | mit | StreakYC/react-draggable-list,StreakYC/react-draggable-list,StreakYC/react-draggable-list | ---
+++
@@ -33,6 +33,9 @@
};
render() {
+ // TODO In next major version remove the need for findDOMNode by using React.cloneElement here.
+ // Update documentation to require that the element given to dragHandle is either
+ // a native DOM element or forwards its props to one.
return React.Children.only(this.props.children);
}
} |
ace5c0e8499b98a7ebcbf4c4bb6e1e6a7d177577 | server/portal/instance/page/compute-document-status.js | server/portal/instance/page/compute-document-status.js | // const debug = require('debug')('W2:portal:instance/page/compute-document-status');
const Promise = require('bluebird');
function getParentStatus(statusConfig, persistence, entity, instance) {
return Promise.resolve()
.then(() => entity.getParentInstance(persistence, instance))
.then((parentInstances) => parentInstances.pop())
.then((parentInstance) => {
const parentStatus = parentInstance[statusConfig.property];
if (parentStatus === statusConfig.inheritance) {
return Promise.resolve()
.then(() => entity.getParentEntity(instance))
.then((parentEntity) => getParentStatus(statusConfig, persistence, parentEntity, parentInstance))
;
} else {
return parentStatus;
}
})
;
}
module.exports = (statusConfig, persistence, entity, instance) => {
const instanceStatus = instance[statusConfig.property];
return (instanceStatus === statusConfig.inheritance)
? getParentStatus(statusConfig, persistence, entity, instance)
: instanceStatus
;
};
| // const debug = require('debug')('W2:portal:instance/page/compute-document-status');
const Promise = require('bluebird');
function getParentStatus(statusConfig, persistence, entity, instance) {
return Promise.resolve()
.then(() => entity.getParentInstance(persistence, instance))
.then((parentInstances) => parentInstances.pop())
.then((parentInstance) => {
if (parentInstance) {
const parentStatus = parentInstance[statusConfig.property];
if (parentStatus === statusConfig.inheritance) {
return Promise.resolve()
.then(() => entity.getParentEntity(instance))
.then((parentEntity) => getParentStatus(statusConfig, persistence, parentEntity, parentInstance))
;
} else {
return parentStatus;
}
}
})
;
}
module.exports = (statusConfig, persistence, entity, instance) => {
const instanceStatus = instance[statusConfig.property];
return (instanceStatus === statusConfig.inheritance)
? getParentStatus(statusConfig, persistence, entity, instance)
: instanceStatus
;
};
| Handle case where Status===inherit but no parent available | Handle case where Status===inherit but no parent available
| JavaScript | mit | WarpWorks/warpjs | ---
+++
@@ -6,15 +6,17 @@
.then(() => entity.getParentInstance(persistence, instance))
.then((parentInstances) => parentInstances.pop())
.then((parentInstance) => {
- const parentStatus = parentInstance[statusConfig.property];
+ if (parentInstance) {
+ const parentStatus = parentInstance[statusConfig.property];
- if (parentStatus === statusConfig.inheritance) {
- return Promise.resolve()
- .then(() => entity.getParentEntity(instance))
- .then((parentEntity) => getParentStatus(statusConfig, persistence, parentEntity, parentInstance))
- ;
- } else {
- return parentStatus;
+ if (parentStatus === statusConfig.inheritance) {
+ return Promise.resolve()
+ .then(() => entity.getParentEntity(instance))
+ .then((parentEntity) => getParentStatus(statusConfig, persistence, parentEntity, parentInstance))
+ ;
+ } else {
+ return parentStatus;
+ }
}
})
; |
afc3475d315eacdd8404915af1aa71cd64a44cc8 | src/ReactTypeInAndOut.js | src/ReactTypeInAndOut.js | var React = require('react');
var { Repeat } = require('Immutable');
class ReactTypeInAndOut extends React.Component {
constructor (props) {
super(props);
var words = props.words;
words = words.reduce((acc, word) => {
// include empty string as start/end
word = [''].concat(word.split(''));
var forwards = word.map((lc, lIdx, lw) => {
return lw.slice(0, lIdx + 1).join('');
});
var backwards = forwards.slice(0, -1).reverse();
return acc.concat(forwards, backwards);
}, []);
this.state = {
words: words
};
}
componentDidMount () {
var words = this.state.words;
var start = 0;
var running = setInterval(() => {
this.setState({
currentWord: words[start]
});
start = (start + 1) % words.length;
}, this.props.speed);
}
render () {
var currentWord = this.state.currentWord;
return <div>{currentWord}</div>;
}
}
ReactTypeInAndOut.propTypes = {
words: React.PropTypes.arrayOf(React.PropTypes.string),
speed: React.PropTypes.number
};
ReactTypeInAndOut.defaultProps = {
speed: 200
};
export default ReactTypeInAndOut;
| var React = require('react');
var { Repeat } = require('Immutable');
class ReactTypeInAndOut extends React.Component {
constructor (props) {
super(props);
var words = props.words;
words = words.reduce((acc, word) => {
// include empty string as start/end
word = [''].concat(word.split(''));
var forwards = word.map((lc, lIdx, lw) => {
return lw.slice(0, lIdx + 1).join('');
});
var backwards = forwards.slice(0, -1).reverse();
return acc.concat(forwards, backwards);
}, []);
this.state = {
words: words
};
}
startTyping (words) {
var start = 0;
var running = setInterval(() => {
this.setState({
currentWord: words[start]
});
start = (start + 1) % words.length;
if (start === 0) {
clearInterval(running);
setTimeout(this.startTyping.bind(this, words), this.props.delayRepeat);
}
}, this.props.speed);
}
componentDidMount () {
this.startTyping(this.state.words);
}
render () {
var currentWord = this.state.currentWord;
return <div>{currentWord}</div>;
}
}
ReactTypeInAndOut.propTypes = {
words: React.PropTypes.arrayOf(React.PropTypes.string),
speed: React.PropTypes.number,
delayRepeat: React.PropTypes.number
};
ReactTypeInAndOut.defaultProps = {
speed: 200,
delayRepeat: 0
};
export default ReactTypeInAndOut;
| Add property to delay repeat | Add property to delay repeat
| JavaScript | mit | JRigotti/react-type-in-and-out,JRigotti/react-type-in-and-out | ---
+++
@@ -28,10 +28,8 @@
};
}
- componentDidMount () {
- var words = this.state.words;
+ startTyping (words) {
var start = 0;
-
var running = setInterval(() => {
this.setState({
@@ -40,7 +38,16 @@
start = (start + 1) % words.length;
+ if (start === 0) {
+ clearInterval(running);
+ setTimeout(this.startTyping.bind(this, words), this.props.delayRepeat);
+ }
+
}, this.props.speed);
+ }
+
+ componentDidMount () {
+ this.startTyping(this.state.words);
}
render () {
@@ -51,11 +58,13 @@
ReactTypeInAndOut.propTypes = {
words: React.PropTypes.arrayOf(React.PropTypes.string),
- speed: React.PropTypes.number
+ speed: React.PropTypes.number,
+ delayRepeat: React.PropTypes.number
};
ReactTypeInAndOut.defaultProps = {
- speed: 200
+ speed: 200,
+ delayRepeat: 0
};
export default ReactTypeInAndOut; |
5bd8842f58d7cbf3baa013d8bbe043386e15c7b5 | src/reducers/board.js | src/reducers/board.js | export default function board(state = {}, action) {
if (action.type === 'PLAY_TURN') {
const { location, moveId, piece } = action;
const cells = [
...state.cells.slice(0, location),
{
contents: piece,
moveId,
},
...state.cells.slice(location + 1),
];
return { ...state, cells };
}
return state
}
| export default function board(state = {}, action) {
if (action.type === 'PLAY_TURN') {
const { location, moveId, piece } = action;
return {
...state,
cells: updateCellsForTurn(state.cells, location, moveId, piece),
};
}
return state;
}
function updateCellsForTurn(cells, location, moveId, piece) {
return [
...cells.slice(0, location),
{
contents: piece,
moveId,
},
...cells.slice(location + 1),
];
}
| Split out a separate function for reducing the cells | Split out a separate function for reducing the cells
| JavaScript | mit | Greatlemer/react-gomoku-bot,Greatlemer/react-gomoku-bot | ---
+++
@@ -1,15 +1,21 @@
export default function board(state = {}, action) {
if (action.type === 'PLAY_TURN') {
const { location, moveId, piece } = action;
- const cells = [
- ...state.cells.slice(0, location),
- {
- contents: piece,
- moveId,
- },
- ...state.cells.slice(location + 1),
- ];
- return { ...state, cells };
+ return {
+ ...state,
+ cells: updateCellsForTurn(state.cells, location, moveId, piece),
+ };
}
- return state
+ return state;
}
+
+function updateCellsForTurn(cells, location, moveId, piece) {
+ return [
+ ...cells.slice(0, location),
+ {
+ contents: piece,
+ moveId,
+ },
+ ...cells.slice(location + 1),
+ ];
+} |
9d03540448a1903a37d47c9c4c6bddab32e3ad98 | source/javascripts/issue-boards.js | source/javascripts/issue-boards.js | $(function () {
var isElementOnScreen = function($el, scrollTop) {
// Get very bottom of element
var elementBottom = $el.offset().top + $el.outerHeight();
// Get very top of element
var elementTop = $el.offset().top - scrollTop;
if (elementTop <= $(window).height() && elementBottom - scrollTop >= 0) {
// Element is on-screen
return true;
} else {
// Element is not on-screen
return false;
}
}
$('.js-scroll-to').on('click', function(e) {
e.preventDefault();
var $target = $(this).attr('href');
$('body').animate({
scrollTop: $target.offset().top
});
});
// Scroll effect on steps
var $steps = $('.js-step, .js-learn-more');
var $stickyBanner = $('.js-sticky-banner');
var $tryGitlabEnterprise = $('.js-try-gitlab-ee');
$(window).on('scroll', function() {
$steps.each(function() {
var isOnScreen = isElementOnScreen($(this), ($(window).scrollTop() - 150));
if (isOnScreen && !$(this).hasClass('is-visible')) {
$(this).addClass('is-visible');
}
});
var tryOnScreen = isElementOnScreen($tryGitlabEnterprise, ($(window).scrollTop() - 150));
if (tryOnScreen && $stickyBanner.hasClass('active')) {
$stickyBanner.removeClass('active');
}
});
});
| $(function () {
var isElementOnScreen = function($el, scrollTop) {
// Get very bottom of element
var elementBottom = $el.offset().top + $el.outerHeight();
// Get very top of element
var elementTop = $el.offset().top - scrollTop;
if (elementTop <= $(window).height() && elementBottom - scrollTop >= 0) {
// Element is on-screen
return true;
} else {
// Element is not on-screen
return false;
}
}
$('.js-scroll-to').on('click', function(e) {
e.preventDefault();
var $target = $(this).attr('href');
$('body').animate({
scrollTop: $target.offset().top
});
});
// Scroll effect on steps
var $steps = $('.js-step, .js-learn-more');
var $stickyBanner = $('.js-sticky-banner');
var $tryGitlabEnterprise = $('.js-try-gitlab-ee');
$(window).on('scroll', function() {
$steps.each(function() {
var isOnScreen = isElementOnScreen($(this), ($(window).scrollTop() - 150));
if (isOnScreen && !$(this).hasClass('is-visible')) {
$(this).addClass('is-visible');
}
});
var tryOnScreen = isElementOnScreen($tryGitlabEnterprise, ($(window).scrollTop() - 50));
if (tryOnScreen && $stickyBanner.hasClass('active')) {
$stickyBanner.removeClass('active');
}
if (!tryOnScreen && !$stickyBanner.hasClass('active')) {
$stickyBanner.addClass('active');
}
});
});
| Improve the sticky banner scroll detection. | Improve the sticky banner scroll detection.
| JavaScript | mit | damianhakert/damianhakert.github.io | ---
+++
@@ -38,9 +38,13 @@
}
});
- var tryOnScreen = isElementOnScreen($tryGitlabEnterprise, ($(window).scrollTop() - 150));
+ var tryOnScreen = isElementOnScreen($tryGitlabEnterprise, ($(window).scrollTop() - 50));
if (tryOnScreen && $stickyBanner.hasClass('active')) {
$stickyBanner.removeClass('active');
}
+
+ if (!tryOnScreen && !$stickyBanner.hasClass('active')) {
+ $stickyBanner.addClass('active');
+ }
});
}); |
2d1bf46e1e821b7bc46e8050698ea4b01dacc6fe | client/src/components/Listing/AddListing/AddListingComponents/ListingTitle.js | client/src/components/Listing/AddListing/AddListingComponents/ListingTitle.js | import React from 'react';
import { Form } from 'semantic-ui-react';
export const ListingTitle = ({ title, onChange }) => {
return (
<Form.TextArea
rows="1"
className="ui center aligned grid"
label="Title"
placeholder="Insert title of job here"
name="title"
value={title}
onChange={e => onChange(e)}
/>
);
};
| import React from 'react';
import { Form } from 'semantic-ui-react';
export const ListingTitle = ({ title, onChange }) => {
return (
<Form.Field className="ui center aligned grid">
<label>Title</label>
<input
placeholder="Insert title of job here"
name="title"
value={title}
onChange={e => onChange(e)}
/>
</Form.Field>
);
};
| Change AddListing title field from textarea | Change AddListing title field from textarea
| JavaScript | mit | bwuphan/raptor-ads,wolnewitz/raptor-ads,Darkrender/raptor-ads,Velocies/raptor-ads,bwuphan/raptor-ads,wolnewitz/raptor-ads,Darkrender/raptor-ads,Velocies/raptor-ads | ---
+++
@@ -3,15 +3,15 @@
export const ListingTitle = ({ title, onChange }) => {
return (
- <Form.TextArea
- rows="1"
- className="ui center aligned grid"
- label="Title"
- placeholder="Insert title of job here"
- name="title"
- value={title}
- onChange={e => onChange(e)}
- />
+ <Form.Field className="ui center aligned grid">
+ <label>Title</label>
+ <input
+ placeholder="Insert title of job here"
+ name="title"
+ value={title}
+ onChange={e => onChange(e)}
+ />
+ </Form.Field>
);
};
|
a701a9c2735b6ed85823af6ad168455dbb29776d | src/background.js | src/background.js | import tldjs from 'tldjs'
import 'src/activity-logger/background'
import 'src/omnibar'
import { installTimeStorageKey } from 'src/imports/background'
async function openOverview() {
const [ currentTab ] = await browser.tabs.query({ active: true })
if (currentTab && currentTab.url) {
const validUrl = tldjs.isValid(currentTab.url)
if (validUrl) {
return browser.tabs.create({
url: '/overview/overview.html',
})
}
}
browser.tabs.update({
url: '/overview/overview.html',
})
}
// Open the overview when the extension's button is clicked
browser.browserAction.onClicked.addListener(() => {
openOverview()
})
browser.commands.onCommand.addListener(command => {
if (command === 'openOverview') {
openOverview()
}
})
// Store the timestamp of when the extension was installed in local storage
browser.runtime.onInstalled.addListener(details => {
if (details.reason === 'install') {
browser.storage.local.set({ [installTimeStorageKey]: Date.now() })
}
})
| import tldjs from 'tldjs'
import 'src/activity-logger/background'
import 'src/omnibar'
import { installTimeStorageKey } from 'src/imports/background'
import convertOldData from 'src/util/old-data-converter'
async function openOverview() {
const [ currentTab ] = await browser.tabs.query({ active: true })
if (currentTab && currentTab.url) {
const validUrl = tldjs.isValid(currentTab.url)
if (validUrl) {
return browser.tabs.create({
url: '/overview/overview.html',
})
}
}
browser.tabs.update({
url: '/overview/overview.html',
})
}
// Open the overview when the extension's button is clicked
browser.browserAction.onClicked.addListener(() => {
openOverview()
})
browser.commands.onCommand.addListener(command => {
if (command === 'openOverview') {
openOverview()
}
})
browser.runtime.onInstalled.addListener(details => {
// Store the timestamp of when the extension was installed in local storage
if (details.reason === 'install') {
browser.storage.local.set({ [installTimeStorageKey]: Date.now() })
}
// Attempt convert of old extension data on extension update
if (details.reason === 'update') {
await convertOldData({ setAsStubs: true, concurrency: 15 })
}
})
| Set up old data conversion on update | Set up old data conversion on update
- we'll probably remove this after the first update?
- either way, if it's left and runs a second time, it will still run fine without the data in local storage without doing anything
| JavaScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -3,6 +3,7 @@
import 'src/activity-logger/background'
import 'src/omnibar'
import { installTimeStorageKey } from 'src/imports/background'
+import convertOldData from 'src/util/old-data-converter'
async function openOverview() {
const [ currentTab ] = await browser.tabs.query({ active: true })
@@ -31,9 +32,13 @@
}
})
-// Store the timestamp of when the extension was installed in local storage
browser.runtime.onInstalled.addListener(details => {
+ // Store the timestamp of when the extension was installed in local storage
if (details.reason === 'install') {
browser.storage.local.set({ [installTimeStorageKey]: Date.now() })
}
+ // Attempt convert of old extension data on extension update
+ if (details.reason === 'update') {
+ await convertOldData({ setAsStubs: true, concurrency: 15 })
+ }
}) |
47c545f924c165434befba7134b40189891e27d3 | lib/collections/mangasData.js | lib/collections/mangasData.js | MangasData = new Mongo.Collection('mangasData');
| MangasData = new Mongo.Collection('mangasData');
Meteor.methods({
addCompleteMangas: function(serie) {
return MangasData.insert(serie);
}
});
| Add method to add a complete manga | Add method to add a complete manga
| JavaScript | mit | dexterneo/mangatek,dexterneo/mangas,dexterneo/mangas,dexterneo/mangatek | ---
+++
@@ -1 +1,7 @@
MangasData = new Mongo.Collection('mangasData');
+
+Meteor.methods({
+ addCompleteMangas: function(serie) {
+ return MangasData.insert(serie);
+ }
+}); |
704c497771fb78228577f216ee73da58376dd834 | lib/formats/json/formatter.js | lib/formats/json/formatter.js |
function JSONFormatter(){
}
/*
* Every internal data structure are JSON by nature, them
* no transformation is required
*/
JSONFormatter.prototype.format = function(payload){
return payload;
};
JSONFormatter.prototype.toString = function(payload){
return JSON.stringify(payload);
};
module.exports = JSONFormatter;
|
function JSONFormatter(){
}
/*
* Every internal data structure is JSON by nature, so
* no transformation is required
*/
JSONFormatter.prototype.format = function(payload){
return payload;
};
JSONFormatter.prototype.toString = function(payload){
return JSON.stringify(payload);
};
module.exports = JSONFormatter;
| Fix minor typo in JSONFormatter comment | Fix minor typo in JSONFormatter comment
Signed-off-by: Daniel Bevenius <ae63d1d4d7994483a3e520cafec7a829fe25c0a1@gmail.com>
| JavaScript | apache-2.0 | cloudevents/sdk-javascript,cloudevents/sdk-javascript | ---
+++
@@ -4,7 +4,7 @@
}
/*
- * Every internal data structure are JSON by nature, them
+ * Every internal data structure is JSON by nature, so
* no transformation is required
*/
JSONFormatter.prototype.format = function(payload){ |
0588e21f2bbe3ca2853770f2165bcfccd0903c57 | src/components/Header.js | src/components/Header.js | import React from 'react';
// <a /> should be a <Link /> to avoid reloading the page, but avoids having to
// wrap many tests in a <MemoryRouter />
const Header = () => (
<header>
<a href="/">ETMobile - Reduce your CO2 emissions</a>
</header>
);
export default Header;
| import React from 'react';
// <a /> should be a <Link /> to avoid reloading the page, but avoids having to
// wrap many tests in a <MemoryRouter />
const Header = () => (
<header>
<a href={process.env.PUBLIC_URL || '/'}>
ETMobile - Reduce your CO2 emissions
</a>
</header>
);
export default Header;
| Fix header link on GitHub pages | Fix header link on GitHub pages
The public URL on GH pages is /etmobile, not /.
| JavaScript | mit | quintel/etmobile,quintel/etmobile,quintel/etmobile | ---
+++
@@ -4,7 +4,9 @@
// wrap many tests in a <MemoryRouter />
const Header = () => (
<header>
- <a href="/">ETMobile - Reduce your CO2 emissions</a>
+ <a href={process.env.PUBLIC_URL || '/'}>
+ ETMobile - Reduce your CO2 emissions
+ </a>
</header>
);
|
855053e656161c5f94ad029eba48519b826334e2 | src/main/web/florence/js/functions/_checkPathParsed.js | src/main/web/florence/js/functions/_checkPathParsed.js | function checkPathParsed (uri) {
if (uri.charAt(0) !== '/') {
uri = '/' + uri;
}
var safeUrl;
var myUrl = parseURL(uri);
if (myUrl.pathname.charAt(myUrl.pathname.length-1) === '/') {
myUrl.pathname = myUrl.pathname.slice(0, -1);
safeUrl = myUrl.pathname;
}
return safeUrl;
}
| function checkPathParsed (uri) {
if (uri.charAt(0) !== '/') {
uri = '/' + uri;
}
var myUrl = parseURL(uri);
var safeUrl = myUrl.pathname;
if (safeUrl.charAt(safeUrl.length-1) === '/') {
safeUrl = safeUrl.slice(0, -1);
}
return safeUrl;
}
| Check path for safe uri | Check path for safe uri
Former-commit-id: f359bd81b4764b394025af1322575fc3b2ea3837 | JavaScript | mit | ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence | ---
+++
@@ -2,11 +2,10 @@
if (uri.charAt(0) !== '/') {
uri = '/' + uri;
}
- var safeUrl;
var myUrl = parseURL(uri);
- if (myUrl.pathname.charAt(myUrl.pathname.length-1) === '/') {
- myUrl.pathname = myUrl.pathname.slice(0, -1);
- safeUrl = myUrl.pathname;
+ var safeUrl = myUrl.pathname;
+ if (safeUrl.charAt(safeUrl.length-1) === '/') {
+ safeUrl = safeUrl.slice(0, -1);
}
return safeUrl;
} |
994b44a47c27b9dc56978b811e8a465a768f2e89 | gulpfile.js/tasks/svgSprite.js | gulpfile.js/tasks/svgSprite.js | 'use strict';
if (!config.tasks.svgSprite) {
return false;
}
const svgstore = require('gulp-svgstore');
let paths = {
src: path.join(config.root.base, config.root.src, config.tasks.svgSprite.src, getExtensions(config.tasks.svgSprite.extensions)),
dest: path.join(config.root.base, config.root.dest, config.tasks.svgSprite.dest)
};
function svgSprite() {
return gulp.src(paths.src, {since: cache.lastMtime('svgSprite')})
.pipe(plumber(handleErrors))
.pipe(rename(path => {
path.basename = 'icon-' + path.basename.toLowerCase();
}))
.pipe(cache('svgSprite'))
.pipe(imagemin())
.pipe(svgstore())
.pipe(gulp.dest(paths.dest))
.pipe(size({
title: 'SVG:',
showFiles: true
})
);
}
module.exports = svgSprite;
| 'use strict';
if (!config.tasks.svgSprite) {
return false;
}
const svgstore = require('gulp-svgstore');
let paths = {
src: path.join(config.root.base, config.root.src, config.tasks.svgSprite.src, getExtensions(config.tasks.svgSprite.extensions)),
dest: path.join(config.root.base, config.root.dest, config.tasks.svgSprite.dest)
};
function svgSprite() {
return gulp.src(paths.src, {since: cache.lastMtime('svgSprite')})
.pipe(plumber(handleErrors))
.pipe(rename(path => {
path.basename = 'icon-' + path.basename.toLowerCase();
}))
.pipe(cache('svgSprite'))
.pipe(imagemin([imagemin.svgo({plugins:[config.tasks.svgSprite.svgo]})]))
.pipe(svgstore())
.pipe(gulp.dest(paths.dest))
.pipe(size({
title: 'SVG:',
showFiles: true
})
);
}
module.exports = svgSprite;
| Add settings to svg sprite task | Add settings to svg sprite task
| JavaScript | mit | jonnitto/gulpfile.js | ---
+++
@@ -16,7 +16,7 @@
path.basename = 'icon-' + path.basename.toLowerCase();
}))
.pipe(cache('svgSprite'))
- .pipe(imagemin())
+ .pipe(imagemin([imagemin.svgo({plugins:[config.tasks.svgSprite.svgo]})]))
.pipe(svgstore())
.pipe(gulp.dest(paths.dest))
.pipe(size({ |
5ad52cf2fe5b6508ffb76da2b6c521b7bd8a0532 | app/containers/wallet/WalletReceivePage.js | app/containers/wallet/WalletReceivePage.js | // @flow
import React, { Component, PropTypes } from 'react';
import { observer } from 'mobx-react';
import WalletReceive from '../../components/wallet/WalletReceive';
@observer(['store'])
export default class WalletReceivePage extends Component {
static propTypes = {
store: PropTypes.shape({
wallet: PropTypes.object.isRequired,
})
};
render() {
const { wallet } = this.props.store;
return (
<WalletReceive walletName={wallet.name} walletAddress={wallet.address} />
);
}
}
| // @flow
import React, { Component, PropTypes } from 'react';
import { observer } from 'mobx-react';
import WalletReceive from '../../components/wallet/WalletReceive';
@observer(['store'])
export default class WalletReceivePage extends Component {
static propTypes = {
store: PropTypes.shape({
uiStore: PropTypes.shape({
selectedWallet: PropTypes.object.isRequired,
})
})
};
render() {
const { selectedWallet } = this.props.store.uiStore;
return (
<WalletReceive walletName={selectedWallet.name} walletAddress={selectedWallet.address} />
);
}
}
| Refactor wallet receive page to work with new ui store | Refactor wallet receive page to work with new ui store
| JavaScript | apache-2.0 | input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus | ---
+++
@@ -8,14 +8,16 @@
static propTypes = {
store: PropTypes.shape({
- wallet: PropTypes.object.isRequired,
+ uiStore: PropTypes.shape({
+ selectedWallet: PropTypes.object.isRequired,
+ })
})
};
render() {
- const { wallet } = this.props.store;
+ const { selectedWallet } = this.props.store.uiStore;
return (
- <WalletReceive walletName={wallet.name} walletAddress={wallet.address} />
+ <WalletReceive walletName={selectedWallet.name} walletAddress={selectedWallet.address} />
);
}
|
9d9a921c50a5dd4df1a69f7c2856559efdeb2366 | lib/validators/type/number.js | lib/validators/type/number.js | Astro.createValidator({
name: 'number',
validate: function() {
return !_.isNaN(value) && _.isNumber(value);
},
events: {
validationerror: function(e) {
var fieldName = e.data.fieldName;
e.data.message = 'The value of the "' + fieldName +
'" field has to be a number';
}
}
});
| Astro.createValidator({
name: 'number',
validate: function(fieldValue) {
return !_.isNaN(fieldValue) && _.isNumber(fieldValue);
},
events: {
validationerror: function(e) {
var fieldName = e.data.fieldName;
e.data.message = 'The value of the "' + fieldName +
'" field has to be a number';
}
}
});
| Fix lack of value variable in Number validator | Fix lack of value variable in Number validator
| JavaScript | mit | jagi/meteor-astronomy-validators,awei01/meteor-astronomy-validators | ---
+++
@@ -1,7 +1,7 @@
Astro.createValidator({
name: 'number',
- validate: function() {
- return !_.isNaN(value) && _.isNumber(value);
+ validate: function(fieldValue) {
+ return !_.isNaN(fieldValue) && _.isNumber(fieldValue);
},
events: {
validationerror: function(e) { |
4b0f85c48d6917ee00846c7c0d6753a2e13d4bd0 | lib/actions/user.js | lib/actions/user.js | 'use strict';
var shell = require('shelljs');
var nameCache = {};
var emailCache = {};
/**
* @mixin
* @alias actions/user
*/
var user = module.exports;
/**
* Git related properties
*
* The value will come from the global scope or the project scope (it'll take
* what git will use in the current context)
* @prop name {String|undefined} - Current git name
* @prop email {String|undefined} - Current git email
*/
user.git = {
get name() {
var name = nameCache[process.cwd()];
if (name) {
return name;
}
name = shell.exec('git config --get user.name', { silent: true }).output.trim();
nameCache[process.cwd()] = name;
return name;
},
get email() {
var email = emailCache[process.cwd()];
if (email) {
return email;
}
email = shell.exec('git config --get user.email', { silent: true }).output.trim();
emailCache[process.cwd()] = email;
return email;
}
};
| 'use strict';
var shell = require('shelljs');
var nameCache = {};
var emailCache = {};
/**
* @mixin
* @alias actions/user
*/
var user = module.exports;
/**
* Git related properties
*
* The value will come from the global scope or the project scope (it'll take
* what git will use in the current context)
* @prop name {String|undefined} - Current git name
* @prop email {String|undefined} - Current git email
*/
user.git = {
get name() {
var name = nameCache[process.cwd()];
if (name) {
return name;
}
if (shell.which('git')) {
name = shell.exec('git config --get user.name', { silent: true }).output.trim();
nameCache[process.cwd()] = name;
}
return name;
},
get email() {
var email = emailCache[process.cwd()];
if (email) {
return email;
}
if (shell.which('git')) {
email = shell.exec('git config --get user.email', { silent: true }).output.trim();
emailCache[process.cwd()] = email;
}
return email;
}
};
| Check for git prior to calling shell.exec | Check for git prior to calling shell.exec
| JavaScript | bsd-2-clause | yeoman/generator,andrewstuart/generator,yeoman/generator,rutaihwa/generator,yeoman/environment,JulienCabanes/generator | ---
+++
@@ -26,8 +26,10 @@
return name;
}
- name = shell.exec('git config --get user.name', { silent: true }).output.trim();
- nameCache[process.cwd()] = name;
+ if (shell.which('git')) {
+ name = shell.exec('git config --get user.name', { silent: true }).output.trim();
+ nameCache[process.cwd()] = name;
+ }
return name;
},
@@ -39,8 +41,10 @@
return email;
}
- email = shell.exec('git config --get user.email', { silent: true }).output.trim();
- emailCache[process.cwd()] = email;
+ if (shell.which('git')) {
+ email = shell.exec('git config --get user.email', { silent: true }).output.trim();
+ emailCache[process.cwd()] = email;
+ }
return email;
} |
50501773149ef91afa6e4e0e1e729b0ffe8df7bf | injectChrome.js | injectChrome.js | (function() {
const IS_LOCAL = !!(localStorage["ultratypedev"]),
URL_REMOTE = "https://rawgit.com/ultratype/UltraTypeBot/master/OUT/OUT.js",
URL_OUT = IS_LOCAL ? chrome.extension.getURL('OUT/OUT.js') : URL_REMOTE,
injectFull = () => {
window.stop();
let x = new XMLHttpRequest();
x.open('GET', window.location.href, true);
x.onload = function() {
const doc = `<script src="${URL_OUT}"></script>\n${this.responseText}`;
document.open();
document.write(doc);
document.close();
}
x.send(null);
},
injectAppend = () => {
let scr = document.createElement('script');
scr.src = URL_OUT;
if (document.head) {
document.head.appendChild(scr);
} else {
// Retry after about 100 ms
setTimeout(injectAppend, 100);
}
};
if (window.location.href.includes('nitrotype.com/race')) {
// Use full injection method on the main page
injectFull();
return;
} else {
// Slower append injection method is used
injectAppend();
}
})(); | (function() {
const IS_LOCAL = !!(localStorage["ultratypedev"]),
URL_REMOTE = "https://rawgit.com/ultratype/UltraTypeBot/master/OUT/OUT.js",
URL_OUT = IS_LOCAL ? chrome.extension.getURL('OUT/OUT.js') : URL_REMOTE,
injectFull = () => {
window.stop();
let x = new XMLHttpRequest();
x.open('GET', window.location.href, true);
x.onload = function() {
const doc = `<script src="${URL_OUT}"></script>\n${this.responseText}`;
document.open();
document.write(doc);
document.close();
}
x.send(null);
},
injectAppend = () => {
let scr = document.createElement('script');
scr.src = URL_OUT;
if (document.head) {
document.head.appendChild(scr);
} else {
// Retry after about 100 ms
setTimeout(injectAppend, 100);
}
};
/*
if (window.location.href.includes('nitrotype.com/race')) {
// Use full injection method on the main page
injectFull();
return;
} else {
// Slower append injection method is used
injectAppend();
}
*/
injectAppend();
})(); | Change injection method to append | Change injection method to append
| JavaScript | mit | ultratype/UltraTypeBot,ultratype/UltraTypeBot,ultratype/UltraTypeBot | ---
+++
@@ -24,6 +24,7 @@
setTimeout(injectAppend, 100);
}
};
+ /*
if (window.location.href.includes('nitrotype.com/race')) {
// Use full injection method on the main page
injectFull();
@@ -32,4 +33,6 @@
// Slower append injection method is used
injectAppend();
}
+ */
+ injectAppend();
})(); |
7fa799e92e2ce1490520b52bb21f1fd1f66bb413 | src/ReactFauxDOM.js | src/ReactFauxDOM.js | var Element = require('./Element')
var Window = require('./Window')
var ReactFauxDOM = {
Element: Element,
defaultView: Window,
createElement: function (nodeName) {
return new Element(nodeName)
},
compareDocumentPosition: function () {
// The selector engine tries to validate with this, but we don't care.
// 8 = DOCUMENT_POSITION_CONTAINS, so we say all nodes are in this document.
return 8
}
}
Element.prototype.ownerDocument = ReactFauxDOM
module.exports = ReactFauxDOM
| var Element = require('./Element')
var Window = require('./Window')
var ReactFauxDOM = {
Element: Element,
defaultView: Window,
createElement: function (nodeName) {
return new Element(nodeName)
},
createElementNS: function (namespace, nodeName) {
return this.createElement(nodeName)
},
compareDocumentPosition: function () {
// The selector engine tries to validate with this, but we don't care.
// 8 = DOCUMENT_POSITION_CONTAINS, so we say all nodes are in this document.
return 8
}
}
Element.prototype.ownerDocument = ReactFauxDOM
module.exports = ReactFauxDOM
| Add createElementNS, just calls createElement | Add createElementNS, just calls createElement
| JavaScript | unlicense | rmoorman/react-faux-dom,Olical/react-faux-dom | ---
+++
@@ -6,6 +6,9 @@
defaultView: Window,
createElement: function (nodeName) {
return new Element(nodeName)
+ },
+ createElementNS: function (namespace, nodeName) {
+ return this.createElement(nodeName)
},
compareDocumentPosition: function () {
// The selector engine tries to validate with this, but we don't care. |
f008633a682fb9caf85fec457ec7cf84b5301d93 | src/decorators.js | src/decorators.js | import React, {Component, PropTypes} from 'react';
import lodash from 'lodash';
export function listeningTo(storeTokens, getter) {
return decorator;
function decorator(ChildComponent) {
class ListeningContainerComponent extends Component {
static contextTypes = {
dependencyCache: PropTypes.instanceOf(Map)
}
static Original = ChildComponent
getStores() {
const {dependencyCache} = this.context;
return lodash.map(storeTokens, name => {
if (typeof this.props[name] === 'string') {
return this.props[name];
} else {
return dependencyCache.get([name]);
}
});
}
componentDidMount() {
lodash.each(this.stores, store => {
store.on('change', this.setStateFromStores);
});
}
componentWillUnmount() {
lodash.each(this.stores, store => {
store.removeListener('change', this.setStateFromStores);
});
}
constructor(props, context) {
super(props, context);
this.stores = this.getStores();
this.state = {
childProps: getter(this.props)
};
this.setStateFromStores = () => {
this.setState({
childProps: getter(this.props)
});
};
}
render() {
const {childProps} = this.state;
return <ChildComponent {...this.props} {...childProps}/>;
}
}
return ListeningContainerComponent;
}
}
| import React, {Component, PropTypes} from 'react';
import lodash from 'lodash';
export function listeningTo(storeTokens = [], getter) {
if (storeTokens.some(token => token === undefined)) {
throw new TypeError('@listeningTo cannot handle undefined tokens');
}
return decorator;
function decorator(ChildComponent) {
class ListeningContainerComponent extends Component {
static contextTypes = {
dependencyCache: PropTypes.instanceOf(Map)
}
static Original = ChildComponent
getStores() {
const {dependencyCache} = this.context;
return lodash.map(storeTokens, token => {
if (typeof token === 'string') {
return this.props[token];
} else {
if (dependencyCache.has(token)) {
return dependencyCache.get(token);
} else {
throw new RangeError(`@listeningTo cannot find ${token.name || token} in dependency cache`);
}
}
});
}
componentDidMount() {
lodash.each(this.stores, store => {
store.on('change', this.setStateFromStores);
});
}
componentWillUnmount() {
lodash.each(this.stores, store => {
store.removeListener('change', this.setStateFromStores);
});
}
constructor(props, context) {
super(props, context);
this.stores = this.getStores();
this.state = {
childProps: getter(this.props)
};
this.setStateFromStores = () => {
this.setState({
childProps: getter(this.props)
});
};
}
render() {
const {childProps} = this.state;
return <ChildComponent {...this.props} {...childProps}/>;
}
}
return ListeningContainerComponent;
}
}
| Fix token getter and improve error reporting | Fix token getter and improve error reporting
| JavaScript | mit | goodybag/tokyo | ---
+++
@@ -1,7 +1,11 @@
import React, {Component, PropTypes} from 'react';
import lodash from 'lodash';
-export function listeningTo(storeTokens, getter) {
+export function listeningTo(storeTokens = [], getter) {
+ if (storeTokens.some(token => token === undefined)) {
+ throw new TypeError('@listeningTo cannot handle undefined tokens');
+ }
+
return decorator;
function decorator(ChildComponent) {
@@ -15,11 +19,15 @@
getStores() {
const {dependencyCache} = this.context;
- return lodash.map(storeTokens, name => {
- if (typeof this.props[name] === 'string') {
- return this.props[name];
+ return lodash.map(storeTokens, token => {
+ if (typeof token === 'string') {
+ return this.props[token];
} else {
- return dependencyCache.get([name]);
+ if (dependencyCache.has(token)) {
+ return dependencyCache.get(token);
+ } else {
+ throw new RangeError(`@listeningTo cannot find ${token.name || token} in dependency cache`);
+ }
}
});
} |
37260c9dba0e4b1766374d49fc65dc948c7e9dbf | lib/node/readers.js | lib/node/readers.js | 'use strict';
var fs = require('fs')
, request = require('./request');
exports.getContentsFromFile = function(file, callback) {
fs.readFile(file, 'binary', function(err, body) {
if (err) {
return callback(err);
}
callback(err, body);
});
};
exports.getContentsFromUrl = function(url, callback) {
request({
method : 'GET',
uri : url,
encoding : null,
onComplete: callback
});
};
| 'use strict';
var fs = require('fs')
, request = require('./request');
exports.getContentsFromFile = function(file, callback) {
fs.readFile(file, function(err, body) {
if (err) {
return callback(err);
}
callback(err, body);
});
};
exports.getContentsFromUrl = function(url, callback) {
request({
method : 'GET',
uri : url,
encoding : null,
onComplete: callback
});
};
| Read files in raw buffers instead of binary strings | Read files in raw buffers instead of binary strings
| JavaScript | mit | rexxars/imboclient-js,imbo/imboclient-js,rexxars/imboclient-js,rexxars/imboclient-js,imbo/imboclient-js,imbo/imboclient-js | ---
+++
@@ -3,7 +3,7 @@
, request = require('./request');
exports.getContentsFromFile = function(file, callback) {
- fs.readFile(file, 'binary', function(err, body) {
+ fs.readFile(file, function(err, body) {
if (err) {
return callback(err);
} |
14b17d211820fe3555d7a60ad57ade904a6cef3b | C-FAR/index.js | C-FAR/index.js | /// <reference path="../typings/node/node.d.ts" />
/// <reference path="../typings/express/express.d.ts" />
/// <reference path="../typings/express-session/express-session.d.ts" />
var Express = require('express');
var config = require('./config');
var mainRouter = Express.Router();
var modules = [];
var db = require('./db');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
module.exports.router = mainRouter;
var s = session(config.session);
s.store = new RedisStore(config.sessionStore);
mainRouter.use(s);
for (var m in config.active_modules){
var mod = require(__dirname + '/' + config.active_modules[m].name);
mod.init();
mainRouter.use(config.active_modules[m].route, mod.router);
modules.push(mod);
console.log("Loaded module " + config.active_modules[m].name + ", mounted at " + config.active_modules[m].route);
}
// db.query('SET FOREIGN_KEY_CHECKS = 0')
// .then(function(){
// return db.sync({ force: true, logging: console.log });
// })
// .then(function(){
// return db.query('SET FOREIGN_KEY_CHECKS = 1')
// })
// db.sync({force: false}); // Sync database schema after loaded all the modules. | /// <reference path="../typings/node/node.d.ts" />
/// <reference path="../typings/express/express.d.ts" />
/// <reference path="../typings/express-session/express-session.d.ts" />
var Express = require('express');
var config = require('./config');
var mainRouter = Express.Router();
var modules = [];
var db = require('./db');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
module.exports.router = mainRouter;
config.session.store = new RedisStore(config.sessionStore);
var s = session(config.session);
mainRouter.use(s);
for (var m in config.active_modules){
var mod = require(__dirname + '/' + config.active_modules[m].name);
mod.init();
mainRouter.use(config.active_modules[m].route, mod.router);
modules.push(mod);
console.log("Loaded module " + config.active_modules[m].name + ", mounted at " + config.active_modules[m].route);
}
// db.query('SET FOREIGN_KEY_CHECKS = 0')
// .then(function(){
// return db.sync({ force: true, logging: console.log });
// })
// .then(function(){
// return db.query('SET FOREIGN_KEY_CHECKS = 1')
// })
// db.sync({force: false}); // Sync database schema after loaded all the modules. | Change the way to initialize session in order to suppress error message. | Change the way to initialize session in order to suppress error message.
| JavaScript | mit | tom19960222/C-FAR-Website,tom19960222/C-FAR-Website,tom19960222/C-FAR-Website,tom19960222/C-FAR-Website | ---
+++
@@ -11,8 +11,8 @@
var RedisStore = require('connect-redis')(session);
module.exports.router = mainRouter;
+config.session.store = new RedisStore(config.sessionStore);
var s = session(config.session);
-s.store = new RedisStore(config.sessionStore);
mainRouter.use(s);
for (var m in config.active_modules){ |
d8913e81b3f51ff4ddb5afc8577f02dac86cc80f | static/js/states/adminProjectCreate.js | static/js/states/adminProjectCreate.js | define(['app', 'bloodhound'], function(app, Bloodhound) {
'use strict';
return {
parent: 'admin_layout',
url: 'new/project/',
templateUrl: 'partials/admin/project-create.html',
controller: function($scope, $http, $state) {
$scope.searchRepositories = function(value) {
return $http.get('/api/0/repositories/', {
params: {
query: value
}
}).success(function(data){
var results = [];
angular.forEach(data, function(item){
results.push(item.url);
});
return results;
});
};
var bloodhound = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.url); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: '/api/0/repositories/?query=%QUERY'
});
bloodhound.initialize();
$scope.repoTypeaheadData = {
displayKey: 'url',
source: bloodhound.ttAdapter()
};
$scope.createProject = function() {
$http.post('/api/0/projects/', $scope.project)
.success(function(data){
return $state.go('admin_project_settings', {project_id: data.slug});
});
};
$scope.project = {};
}
};
});
| define(['app', 'bloodhound'], function(app, Bloodhound) {
'use strict';
return {
parent: 'admin_layout',
url: 'new/project/',
templateUrl: 'partials/admin/project-create.html',
controller: function($scope, $http, $state) {
$scope.searchRepositories = function(value) {
return $http.get('/api/0/repositories/', {
params: {
query: value
}
}).success(function(data){
var results = [];
angular.forEach(data, function(item){
results.push(item.url);
});
return results;
});
};
var bloodhound = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.url); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: '/api/0/repositories/?query=%QUERY'
});
bloodhound.initialize();
$scope.repoTypeaheadData = {
displayKey: 'url',
source: bloodhound.ttAdapter()
};
$scope.createProject = function() {
$http.post('/api/0/projects/', $scope.project)
.success(function(data){
return $state.go('admin_project_details', {project_id: data.slug});
});
};
$scope.project = {};
}
};
});
| Correct url to project details | Correct url to project details
| JavaScript | apache-2.0 | bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,dropbox/changes | ---
+++
@@ -35,7 +35,7 @@
$scope.createProject = function() {
$http.post('/api/0/projects/', $scope.project)
.success(function(data){
- return $state.go('admin_project_settings', {project_id: data.slug});
+ return $state.go('admin_project_details', {project_id: data.slug});
});
};
|
43af7dc0789f48bde2cdde2ced4e6dfa64c16746 | addon/mixins/r-button-mixin.js | addon/mixins/r-button-mixin.js | import Ember from 'ember';
import { createAttributesObject } from 'ui-library/utils/create-attributes-object';
const { Mixin, get, setProperties } = Ember;
export default Mixin.create({
classNames: ['r-btn'],
classNameBindings: [
// types
'primary:r-btn-primary',
'secondary:r-btn-secondary',
'cancel:r-btn-cancel',
// states
'loading:r-btn-loading',
// sizes
'big:r-btn-large',
'small:r-btn-small'
],
attributes: {
variant: ['primary', 'secondary', 'cancel'],
size: ['small', 'big']
},
defaults: {
variant: 'secondary',
size: 'small'
},
init() {
this._super(...arguments);
this.allowedAttributes = {
variant: ['primary', 'secondary', 'cancel'],
size: ['small', 'big']
};
this.defaults = {
variant: 'secondary',
size: 'small'
};
const allowedAttributes = get(this, 'allowedAttributes');
const defaults = get(this, 'defaults');
const suppliedAttrs = get(this, 'attrs');
const attrObj = createAttributesObject(allowedAttributes, defaults, suppliedAttrs);
setProperties(this, attrObj);
}
});
| import Ember from 'ember';
import { createAttributesObject } from 'ui-library/utils/create-attributes-object';
const { Mixin, get, setProperties } = Ember;
export default Mixin.create({
classNames: ['r-btn'],
classNameBindings: [
// types
'primary:r-btn-primary',
'secondary:r-btn-secondary',
'cancel:r-btn-cancel',
// states
'loading:r-btn-loading',
// sizes
'big:r-btn-large',
'small:r-btn-small'
],
init() {
this._super(...arguments);
this.allowedAttributes = {
variant: ['primary', 'secondary', 'cancel'],
size: ['small', 'big']
};
this.defaults = {
variant: 'secondary',
size: 'small'
};
const allowedAttributes = get(this, 'allowedAttributes');
const defaults = get(this, 'defaults');
const suppliedAttrs = get(this, 'attrs');
const attrObj = createAttributesObject(allowedAttributes, defaults, suppliedAttrs);
setProperties(this, attrObj);
}
});
| Remove attributes and defaults in favor of init implementation | Remove attributes and defaults in favor of init implementation
| JavaScript | mit | repositive/ui-library,repositive/ui-library | ---
+++
@@ -19,16 +19,6 @@
'small:r-btn-small'
],
- attributes: {
- variant: ['primary', 'secondary', 'cancel'],
- size: ['small', 'big']
- },
-
- defaults: {
- variant: 'secondary',
- size: 'small'
- },
-
init() {
this._super(...arguments);
this.allowedAttributes = { |
0adf146a26cef1ae155ab2d1b0899ffde122ee98 | test/something.js | test/something.js | var assert = require('assert');
var messageTypes = {
RESERVED : 0
}
function parseMessageType(inputBuffer){
var firstByte = inputBuffer.readUInt8(0);
var fourBitTransformation = ((0xf0 & firstByte) >> 4);
return fourBitTransformation;
}
describe('Parsing fixed header', function(){
describe('parses the Message Type', function(){
it('of Reserved', function(){
var input = new Buffer(1);
input.writeUInt8(0, 0);
var result = parseMessageType(input);
assert.equal(result, messageTypes.RESERVED);
});
});
});
| var assert = require('assert');
var messageTypes = {
RESERVED: 0,
CONNECT: 1
}
function parseMessageType(inputBuffer) {
var firstByte = inputBuffer.readUInt8(0);
var fourBitTransformation = ((0xf0 & firstByte) >> 4);
return fourBitTransformation;
}
describe('Parsing fixed header', function() {
describe('parses the Message Type', function() {
var input;
beforeEach(function() {
input = new Buffer(1);
});
it('of Reserved', function() {
input.writeUInt8(0, 0);
assert.equal(parseMessageType(input), messageTypes.RESERVED);
});
it('of CONNECT', function() {
input.writeUInt8(16, 0);
assert.equal(parseMessageType(input), messageTypes.CONNECT);
});
});
});
| Support Message Type of CONNECT | Support Message Type of CONNECT
| JavaScript | mit | REAANDREW/thingamabob,REAANDREW/thingamabob | ---
+++
@@ -1,27 +1,35 @@
var assert = require('assert');
var messageTypes = {
- RESERVED : 0
+ RESERVED: 0,
+ CONNECT: 1
}
-function parseMessageType(inputBuffer){
+function parseMessageType(inputBuffer) {
var firstByte = inputBuffer.readUInt8(0);
var fourBitTransformation = ((0xf0 & firstByte) >> 4);
return fourBitTransformation;
}
-describe('Parsing fixed header', function(){
+describe('Parsing fixed header', function() {
- describe('parses the Message Type', function(){
-
- it('of Reserved', function(){
- var input = new Buffer(1);
- input.writeUInt8(0, 0);
- var result = parseMessageType(input);
- assert.equal(result, messageTypes.RESERVED);
+ describe('parses the Message Type', function() {
+
+ var input;
+
+ beforeEach(function() {
+ input = new Buffer(1);
});
-
+ it('of Reserved', function() {
+ input.writeUInt8(0, 0);
+ assert.equal(parseMessageType(input), messageTypes.RESERVED);
+ });
+
+ it('of CONNECT', function() {
+ input.writeUInt8(16, 0);
+ assert.equal(parseMessageType(input), messageTypes.CONNECT);
+ });
});
|
3d077b057fb44519740ea4feafae022abbc19f6d | src/createActionAsync.js | src/createActionAsync.js | import {createAction} from 'redux-act'
import _defaults from 'lodash.defaults';
const defaultOption = {
request:{},
ok:{},
error:{}
}
export default function createActionAsync(description, api, options = defaultOption) {
_defaults(options, defaultOption);
let actions = {
request: createAction(`${description}_REQUEST`, options.request.payloadReducer, options.request.metaReducer),
ok: createAction(`${description}_OK`, options.ok.payloadReducer, options.ok.metaReducer),
error: createAction(`${description}_ERROR`, options.error.payloadReducer, options.error.metaReducer)
}
let actionAsync = (...args) => {
return (dispatch) => {
dispatch(actions.request(...args));
return api(...args)
.then(res => {
dispatch(actions.ok(res, ...args))
})
.catch(err => {
dispatch(actions.error(err, ...args))
if(options.rethrow) throw err;
})
}
}
actionAsync.request = actions.request;
actionAsync.ok = actions.ok;
actionAsync.error = actions.error;
return actionAsync;
};
| import {createAction} from 'redux-act'
import _defaults from 'lodash.defaults';
const defaultOption = {
request:{},
ok:{},
error:{}
}
export default function createActionAsync(description, api, options = defaultOption) {
_defaults(options, defaultOption);
let actions = {
request: createAction(`${description}_REQUEST`, options.request.payloadReducer, options.request.metaReducer),
ok: createAction(`${description}_OK`, options.ok.payloadReducer, options.ok.metaReducer),
error: createAction(`${description}_ERROR`, options.error.payloadReducer, options.error.metaReducer)
}
let actionAsync = (...args) => {
return (dispatch) => {
dispatch(actions.request(...args));
if(options.request.callback) options.request.callback(dispatch, getState, ...args)
return api(...args)
.then(res => {
dispatch(actions.ok(res, ...args))
if(options.ok.callback) options.ok.callback(dispatch, getState, res, ...args)
})
.catch(err => {
dispatch(actions.error(err, ...args))
if(options.error.callback) options.error.callback(dispatch, getState, err, ...args)
if(options.rethrow) throw err;
})
}
}
actionAsync.request = actions.request;
actionAsync.ok = actions.ok;
actionAsync.error = actions.error;
return actionAsync;
};
| Add option to provide callback for request, ok and error actions | Add option to provide callback for request, ok and error actions
The callbacks are passed dispatch and getState along with the other
arguments.
| JavaScript | apache-2.0 | FredericHeem/redux-act-async | ---
+++
@@ -18,12 +18,15 @@
let actionAsync = (...args) => {
return (dispatch) => {
dispatch(actions.request(...args));
+ if(options.request.callback) options.request.callback(dispatch, getState, ...args)
return api(...args)
.then(res => {
dispatch(actions.ok(res, ...args))
+ if(options.ok.callback) options.ok.callback(dispatch, getState, res, ...args)
})
.catch(err => {
dispatch(actions.error(err, ...args))
+ if(options.error.callback) options.error.callback(dispatch, getState, err, ...args)
if(options.rethrow) throw err;
})
} |
9af5eeb53144608d61f5e7ca5ed7854c4bed4c70 | lib/babel-config.js | lib/babel-config.js | const addExports = require('babel-plugin-add-module-exports')
const babelEnv = require('@babel/preset-env')
const flow = require('@babel/preset-flow')
const react = require('@babel/preset-react')
const reactRequire = require('babel-plugin-react-require').default
const lodash = require('babel-plugin-lodash')
const reactDisplayName = require('@babel/plugin-transform-react-display-name')
const transformRuntime = require('@babel/plugin-transform-runtime')
const classProperties = require('@babel/plugin-proposal-class-properties')
const exportFrom = require('@babel/plugin-proposal-export-namespace-from')
const browsers = require('./constants').BROWSER_SUPPORT
module.exports = function (env) {
const plugins = [
addExports,
classProperties,
exportFrom,
lodash,
reactDisplayName,
reactRequire,
transformRuntime
]
return {
plugins,
presets: [
[
babelEnv,
{
loose: false, // Loose mode breaks spread operator on `Set`s
targets: { browsers }
}
],
flow,
react
]
}
}
| const addExports = require('babel-plugin-add-module-exports')
const babelEnv = require('@babel/preset-env')
const flow = require('@babel/preset-flow')
const react = require('@babel/preset-react')
const reactRequire = require('babel-plugin-react-require').default
const lodash = require('babel-plugin-lodash')
const reactDisplayName = require('@babel/plugin-transform-react-display-name')
const classProperties = require('@babel/plugin-proposal-class-properties')
const exportFrom = require('@babel/plugin-proposal-export-namespace-from')
const browsers = require('./constants').BROWSER_SUPPORT
module.exports = function (env) {
const plugins = [
addExports,
classProperties,
exportFrom,
lodash,
reactDisplayName,
reactRequire
]
return {
plugins,
presets: [
[
babelEnv,
{
loose: false, // Loose mode breaks spread operator on `Set`s
targets: { browsers },
useBuiltIns: 'usage'
}
],
flow,
react
]
}
}
| Remove direct transform runtime requirement and turn on the userBuiltIns flag for b | refactor(babel): Remove direct transform runtime requirement and turn on the userBuiltIns flag for b
| JavaScript | mit | conveyal/mastarm,conveyal/mastarm | ---
+++
@@ -5,7 +5,6 @@
const reactRequire = require('babel-plugin-react-require').default
const lodash = require('babel-plugin-lodash')
const reactDisplayName = require('@babel/plugin-transform-react-display-name')
-const transformRuntime = require('@babel/plugin-transform-runtime')
const classProperties = require('@babel/plugin-proposal-class-properties')
const exportFrom = require('@babel/plugin-proposal-export-namespace-from')
@@ -18,8 +17,7 @@
exportFrom,
lodash,
reactDisplayName,
- reactRequire,
- transformRuntime
+ reactRequire
]
return {
@@ -29,7 +27,8 @@
babelEnv,
{
loose: false, // Loose mode breaks spread operator on `Set`s
- targets: { browsers }
+ targets: { browsers },
+ useBuiltIns: 'usage'
}
],
flow, |
a93fbc0989e3dfe8b9ad05f3180a91975969e3ce | main/preload.js | main/preload.js | 'use strict';
/**
* This file is being preloaded in Ghost Instances.
* ⚠ Remember: No jQuery! ⚠
*/
/**
* Simple timeout function checking for
* a) failed login
* b) successful loaded
*/
function checkStatus() {
var err = document.querySelector('p.main-error');
var loaded = document.querySelector('a[title="New Post"]');
if (err && ((err.childElementCount && err.childElementCount > 0) || (err.textContent && err.textContent.length > 0))) {
// Noooo, login errors!
console.log(`login-error`)
} else if (loaded) {
// Yay, successfully loaded
console.log('loaded');
} else {
setTimeout(checkStatus, 100);
}
}
setTimeout(checkStatus, 100); | 'use strict';
/**
* This file is being preloaded in Ghost Instances.
* ⚠ Remember: No jQuery! ⚠
*/
var remote = require('electron').remote;
var Menu = remote.Menu;
var template = [{
label: 'Undo',
role: 'undo'
}, {
label: 'Redo',
role: 'redo'
}, {
type: 'separator'
}, {
label: 'Cut',
role: 'cut'
}, {
label: 'Copy',
role: 'copy'
}, {
label: 'Paste',
role: 'paste'
}, {
label: 'Select All',
role: 'selectall'
}];
var editorMenu = Menu.buildFromTemplate(template);
/**
* Simple timeout function checking for
* a) failed login
* b) successful loaded
*/
function checkStatus() {
var err = document.querySelector('p.main-error');
var loaded = document.querySelector('a[title="New Post"]');
if (err && ((err.childElementCount && err.childElementCount > 0) || (err.textContent && err.textContent.length > 0))) {
// Noooo, login errors!
console.log(`login-error`)
} else if (loaded) {
// Yay, successfully loaded
console.log('loaded');
} else {
setTimeout(checkStatus, 100);
}
}
/**
* Setup the context menu
*/
function handleContextMenu(e) {
// Do nothing when there's no input nearby
if (!e.target.closest('textarea, input, [contenteditable="true"]')) {
return;
};
e.preventDefault();
e.stopPropagation();
var node = e.target;
while (node) {
if (node.nodeName.match(/^(input|textarea)$/i) || node.isContentEditable) {
editorMenu.popup(remote.getCurrentWindow());
break;
}
node = node.parentNode;
}
}
/**
* Init
*/
setTimeout(checkStatus, 100);
window.addEventListener('contextmenu', handleContextMenu);
/**
* Cleanup
*/
remote = undefined;
Menu = undefined; | Enable Ghost Instance Context Menu | :memo: Enable Ghost Instance Context Menu
- Enables the context menu in Ghost instances
| JavaScript | mit | felixrieseberg/Ghost-Desktop,felixrieseberg/Ghost-Desktop,TryGhost/Ghost-Desktop,TryGhost/Ghost-Desktop,TryGhost/Ghost-Desktop,felixrieseberg/Ghost-Desktop | ---
+++
@@ -4,6 +4,31 @@
* This file is being preloaded in Ghost Instances.
* ⚠ Remember: No jQuery! ⚠
*/
+var remote = require('electron').remote;
+var Menu = remote.Menu;
+
+var template = [{
+ label: 'Undo',
+ role: 'undo'
+}, {
+ label: 'Redo',
+ role: 'redo'
+}, {
+ type: 'separator'
+}, {
+ label: 'Cut',
+ role: 'cut'
+}, {
+ label: 'Copy',
+ role: 'copy'
+}, {
+ label: 'Paste',
+ role: 'paste'
+}, {
+ label: 'Select All',
+ role: 'selectall'
+}];
+var editorMenu = Menu.buildFromTemplate(template);
/**
* Simple timeout function checking for
@@ -13,8 +38,8 @@
function checkStatus() {
var err = document.querySelector('p.main-error');
var loaded = document.querySelector('a[title="New Post"]');
-
-
+
+
if (err && ((err.childElementCount && err.childElementCount > 0) || (err.textContent && err.textContent.length > 0))) {
// Noooo, login errors!
console.log(`login-error`)
@@ -26,4 +51,38 @@
}
}
+/**
+ * Setup the context menu
+ */
+function handleContextMenu(e) {
+ // Do nothing when there's no input nearby
+ if (!e.target.closest('textarea, input, [contenteditable="true"]')) {
+ return;
+ };
+
+ e.preventDefault();
+ e.stopPropagation();
+
+ var node = e.target;
+
+ while (node) {
+ if (node.nodeName.match(/^(input|textarea)$/i) || node.isContentEditable) {
+ editorMenu.popup(remote.getCurrentWindow());
+ break;
+ }
+
+ node = node.parentNode;
+ }
+}
+
+/**
+ * Init
+ */
setTimeout(checkStatus, 100);
+window.addEventListener('contextmenu', handleContextMenu);
+
+/**
+ * Cleanup
+ */
+remote = undefined;
+Menu = undefined; |
ef5a46d29e079b6a1cb444f2bceefa48548ecbae | client/app/app.config.js | client/app/app.config.js | 'use strict';
export default function($translateProvider, $mdIconProvider) {
'ngInject';
// put your common app configurations here
// register icons from outsides
$mdIconProvider
.icon('icon-navigate-first', 'assets/icons/navigate-first.svg', 24)
.icon('icon-navigate-last', 'assets/icons/navigate-last.svg', 24)
.icon('icon-navigate-next', 'assets/icons/navigate-next.svg', 24)
.icon('icon-navigate-previous', 'assets/icons/navigate-previous.svg', 24);
// angular-translate configuration
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '{part}/i18n/{lang}.json'
});
// tell the module what language to use by default
$translateProvider.preferredLanguage('en');
// tell the module to store the language in the cookies
$translateProvider.useCookieStorage();
$translateProvider.useSanitizeValueStrategy('sce');
}
| 'use strict';
export default function($translateProvider, $mdIconProvider) {
'ngInject';
// put your common app configurations here
// register icons from outsides
$mdIconProvider
.icon('icon-navigate-first', 'assets/icons/navigate-first.svg', 24)
.icon('icon-navigate-last', 'assets/icons/navigate-last.svg', 24)
.icon('icon-navigate-next', 'assets/icons/navigate-next.svg', 24)
.icon('icon-navigate-previous', 'assets/icons/navigate-previous.svg', 24);
// angular-translate configuration
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '{part}/i18n/{lang}.json'
});
// tell the module what language to use by default
$translateProvider.preferredLanguage('zh');
// tell the module to store the language in the cookies
$translateProvider.useCookieStorage();
$translateProvider.useSanitizeValueStrategy('sce');
}
| Change default language to zh-CN | Change default language to zh-CN
| JavaScript | mit | sunshouxing/bshm,sunshouxing/bshm,sunshouxing/bshm | ---
+++
@@ -16,7 +16,7 @@
urlTemplate: '{part}/i18n/{lang}.json'
});
// tell the module what language to use by default
- $translateProvider.preferredLanguage('en');
+ $translateProvider.preferredLanguage('zh');
// tell the module to store the language in the cookies
$translateProvider.useCookieStorage();
|
74e0a66f23462dbf8017dd0cb13f1392e337e8fb | test/test_biom.js | test/test_biom.js | /*
* biojs-io-biom
* https://github.com/iimog/biojs-io-biom
*
* Copyright (c) 2015 Markus J. Ankenbrand
* Licensed under the MIT license.
*/
// chai is an assertion library
let chai = require('chai');
// @see http://chaijs.com/api/assert/
let assert = chai.assert;
// register alternative styles
// @see http://chaijs.com/api/bdd/
chai.expect();
chai.should();
// requires your main app (specified in index.js)
import {Biom} from '../src/biojs-io-biom';
describe('biojs-io-biom module', function(){
describe('Biom object', function(){
it('should create an object', function(){
assert.equal(typeof new Biom(), "object");
});
});
});
| /*
* biojs-io-biom
* https://github.com/iimog/biojs-io-biom
*
* Copyright (c) 2015 Markus J. Ankenbrand
* Licensed under the MIT license.
*/
// chai is an assertion library
let chai = require('chai');
// @see http://chaijs.com/api/assert/
let assert = chai.assert;
// register alternative styles
// @see http://chaijs.com/api/bdd/
chai.expect();
chai.should();
// requires your main app (specified in index.js)
import {Biom} from '../src/biojs-io-biom';
describe('biojs-io-biom module', () => {
describe('Biom constructor should create an object', () => {
it('should create an object', () => {
assert.equal(typeof new Biom(), "object");
});
});
});
| Use arrow notation for anonymous test functions | Use arrow notation for anonymous test functions
| JavaScript | mit | molbiodiv/biojs-io-biom,molbiodiv/biojs-io-biom | ---
+++
@@ -20,9 +20,9 @@
// requires your main app (specified in index.js)
import {Biom} from '../src/biojs-io-biom';
-describe('biojs-io-biom module', function(){
- describe('Biom object', function(){
- it('should create an object', function(){
+describe('biojs-io-biom module', () => {
+ describe('Biom constructor should create an object', () => {
+ it('should create an object', () => {
assert.equal(typeof new Biom(), "object");
});
}); |
d703036b31a9e094beb8b1b4caa616592e7ad090 | test/test_open.js | test/test_open.js | var amok = require('../');
var test = require('tape');
test('open chrome', function(t) {
var client = amok.open('chrome', ['about:blank'], options);
client.on('ready', function() {
t.ok(client.pid);
client.kill();
});
client.on('close', function(code) {
t.equal(code, 0);
t.end();
});
});
| var amok = require('../');
var test = require('tape');
test('open chrome', function(t) {
var client = amok.open('chrome', ['about:blank']);
client.on('ready', function() {
t.ok(client.pid);
client.kill();
});
client.on('close', function(code) {
t.equal(code, 0);
t.end();
});
});
| Remove stale options from open test | Remove stale options from open test
| JavaScript | mit | stereokai/amok,stereokai/amok,stereokai/amok | ---
+++
@@ -2,7 +2,7 @@
var test = require('tape');
test('open chrome', function(t) {
- var client = amok.open('chrome', ['about:blank'], options);
+ var client = amok.open('chrome', ['about:blank']);
client.on('ready', function() {
t.ok(client.pid);
client.kill(); |
6a98011f5a726ada46e33198763896eec27e153a | jupyterlab/make-release.js | jupyterlab/make-release.js | var childProcess = require('child_process');
var fs = require('fs-extra');
var glob = require('glob');
var path = require('path');
var sortPackageJson = require('sort-package-json');
// Run a production build with Typescript source maps.
childProcess.execSync('npm run build:prod', {stdio:[0,1,2]});
// Update the package.app.json file.
var data = require('./package.json');
data['scripts']['build'] = 'webpack'
data['scripts']['watch'] = "concurrently \"webpack --watch\" \"node watch\""
data['jupyterlab']['outputDir'] = '..';
data['jupyterlab']['linkedPackages'] = {};
text = JSON.stringify(sortPackageJson(data), null, 2) + '\n';
fs.writeFileSync('./package.app.json', text);
// Update our app index file.
fs.copySync('./index.js', './index.app.js');
// Add the release metadata.
var release_data = { version: data.jupyterlab.version };
text = JSON.stringify(release_data, null, 2) + '\n';
fs.writeFileSync('./build/release_data.json', text);
| var childProcess = require('child_process');
var fs = require('fs-extra');
var glob = require('glob');
var path = require('path');
var sortPackageJson = require('sort-package-json');
// Run a production build with Typescript source maps.
childProcess.execSync('npm run build:prod', {stdio:[0,1,2]});
// Update the package.app.json file.
var data = require('./package.json');
data['scripts']['build'] = 'webpack'
data['scripts']['watch'] = 'webpack --watch'
data['jupyterlab']['outputDir'] = '..';
data['jupyterlab']['linkedPackages'] = {};
text = JSON.stringify(sortPackageJson(data), null, 2) + '\n';
fs.writeFileSync('./package.app.json', text);
// Update our app index file.
fs.copySync('./index.js', './index.app.js');
// Add the release metadata.
var release_data = { version: data.jupyterlab.version };
text = JSON.stringify(release_data, null, 2) + '\n';
fs.writeFileSync('./build/release_data.json', text);
| Revert change to watch script invocation | Revert change to watch script invocation
| JavaScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -10,7 +10,7 @@
// Update the package.app.json file.
var data = require('./package.json');
data['scripts']['build'] = 'webpack'
-data['scripts']['watch'] = "concurrently \"webpack --watch\" \"node watch\""
+data['scripts']['watch'] = 'webpack --watch'
data['jupyterlab']['outputDir'] = '..';
data['jupyterlab']['linkedPackages'] = {};
text = JSON.stringify(sortPackageJson(data), null, 2) + '\n'; |
48b85d1fb28e8a27ebe536e64c6f8036bc07b457 | src/getDomainHandlers.js | src/getDomainHandlers.js | function format (string) {
/*eslint-disable no-unused-vars*/
const [ _, action, state ] = `${ string }`.match(/(\w*)\_\d+\_(\w*)/, ' ') || []
/*eslint-enable no-unused-vars*/
return action ? `the ${ action } action's ${ state } state` : string
}
function getHandler (key, domain, type) {
let handler = domain[type]
if (handler === undefined) {
const registrations = domain.register()
if (process.env.NODE_ENV !== 'production') {
if (type in registrations && registrations[type] === undefined) {
console.warn('The handler for %s within a domain for "%s" is undefined. ' +
'Check the register method for this domain.', format(type), key)
}
}
handler = registrations[type]
}
return handler
}
export default function getDomainHandlers (domains, type) {
const handlers = []
domains.forEach(function ([key, domain]) {
let handler = getHandler(key, domain, type)
if (handler !== undefined) {
handlers.push({ key, domain, handler })
}
})
return handlers
}
| function format (string) {
/*eslint-disable no-unused-vars*/
const [ _, action, state ] = `${ string }`.match(/(\w*)\_\d+\_(\w*)/, ' ') || []
/*eslint-enable no-unused-vars*/
return action ? `the ${ action } action's ${ state } state` : string
}
function getHandler (key, domain, type) {
let handler = domain[type]
if (handler === undefined) {
const registrations = domain.register()
if (process.env.NODE_ENV !== 'production') {
if (registrations.hasOwnProperty(type) && registrations[type] === undefined) {
console.warn('The handler for %s within a domain for "%s" is undefined. ' +
'Check the register method for this domain.', format(type), key)
}
}
handler = registrations[type]
}
return handler
}
export default function getDomainHandlers (domains, type) {
const handlers = []
domains.forEach(function ([key, domain]) {
let handler = getHandler(key, domain, type)
if (handler !== undefined) {
handlers.push({ key, domain, handler })
}
})
return handlers
}
| Use hasOwnProperty instead of in keyword | Use hasOwnProperty instead of in keyword
| JavaScript | mit | leobauza/microcosm,vigetlabs/microcosm,vigetlabs/microcosm,vigetlabs/microcosm,leobauza/microcosm,leobauza/microcosm | ---
+++
@@ -13,7 +13,7 @@
const registrations = domain.register()
if (process.env.NODE_ENV !== 'production') {
- if (type in registrations && registrations[type] === undefined) {
+ if (registrations.hasOwnProperty(type) && registrations[type] === undefined) {
console.warn('The handler for %s within a domain for "%s" is undefined. ' +
'Check the register method for this domain.', format(type), key)
} |
eb5963456489290d0a770944a5a056dc2c406d61 | javascripts/application.js | javascripts/application.js | $(function() {
function randomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function newBubble () {
var radius = randomInt(10, 208);
if (event) {
var left = event.clientX;
var top = event.clientY;
}
else {
var left = randomInt(radius, $(document).width() - radius);
var top = randomInt(radius, $(document).height() - radius);
}
$("<div />").appendTo("#bubbles").css ({
'height': radius,
'left': left,
'margin-top': -radius/2,
'margin-left': -radius/2,
'top': top,
'-webkit-animation-duration': randomInt(4.2, 9.8) + 's',
'width': radius
});
}
function generateBubbles() {
newBubble();
clearInterval(timer);
timer = setInterval(generateBubbles, randomInt(252, 2542));
if ($("#bubbles > div").length > 25) {
$("#bubbles > div:first-child").remove();
}
}
var timer = setInterval(generateBubbles, 500);
$("body").click(function() {
newBubble();
});
});
| $(function() {
function randomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function newBubble () {
var radius = randomInt(10, 208);
var animationDuration = randomInt(4.2, 9.8);
if (event) {
var left = event.clientX;
var top = event.clientY;
}
else {
var left = randomInt(radius, $(document).width() - radius);
var top = randomInt(radius, $(document).height() - radius);
}
$("<div />").appendTo("#bubbles")
.css ({
'height': radius,
'left': left,
'margin-top': -radius/2,
'margin-left': -radius/2,
'top': top,
'-webkit-animation-duration': animationDuration + 's',
'width': radius
})
.delay(animationDuration * 1000)
.queue(function() {
$(this).remove();
});
}
function generateBubbles() {
newBubble();
clearInterval(timer);
timer = setInterval(generateBubbles, randomInt(252, 2542));
}
var timer = setInterval(generateBubbles, 500);
$("body").click(function() {
newBubble();
});
});
| Remove bubbles when animation is done. | Remove bubbles when animation is done.
| JavaScript | mit | ubuwaits/bokehdelic,ubuwaits/bokehdelic,ubuwaits/bokehdelic | ---
+++
@@ -5,6 +5,7 @@
function newBubble () {
var radius = randomInt(10, 208);
+ var animationDuration = randomInt(4.2, 9.8);
if (event) {
var left = event.clientX;
@@ -15,14 +16,19 @@
var top = randomInt(radius, $(document).height() - radius);
}
- $("<div />").appendTo("#bubbles").css ({
+ $("<div />").appendTo("#bubbles")
+ .css ({
'height': radius,
'left': left,
'margin-top': -radius/2,
'margin-left': -radius/2,
'top': top,
- '-webkit-animation-duration': randomInt(4.2, 9.8) + 's',
+ '-webkit-animation-duration': animationDuration + 's',
'width': radius
+ })
+ .delay(animationDuration * 1000)
+ .queue(function() {
+ $(this).remove();
});
}
@@ -31,10 +37,6 @@
clearInterval(timer);
timer = setInterval(generateBubbles, randomInt(252, 2542));
-
- if ($("#bubbles > div").length > 25) {
- $("#bubbles > div:first-child").remove();
- }
}
var timer = setInterval(generateBubbles, 500); |
35d9e5eb8f6bb8f062cf7b0387f622f799be9c9f | lib/tab-debugger.js | lib/tab-debugger.js | function _attach(tabId) {
var protocolVersion = '1.1';
return new Promise((resolve, reject) => {
chrome.debugger.attach({
tabId: tabId
}, protocolVersion, () => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message);
return;
}
resolve();
});
});
}
function _sendCommand(tabId, command, data = {}) {
return new Promise((resolve, reject) => {
chrome.debugger.sendCommand({
tabId: tabId
}, command, data, (response) => {
console.log('command', command, tabId, data);
if (response.error) {
reject(response.error);
return;
}
resolve();
});
});
}
class TabDebugger {
constructor(tabId) {
this._tabId = tabId;
}
connect() {
return _attach(this._tabId);
}
sendCommand(command, data) {
return _sendCommand(this._tabId, command, data);
}
}
export default TabDebugger; | function _attach(tabId) {
var protocolVersion = '1.1';
return new Promise((resolve, reject) => {
chrome.debugger.attach({
tabId: tabId
}, protocolVersion, () => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message);
return;
}
resolve();
});
});
}
function _sendCommand(tabId, command, data = {}) {
return new Promise((resolve, reject) => {
chrome.debugger.sendCommand({
tabId: tabId
}, command, data, (response) => {
console.log('command', command, tabId, data);
if (response.error) {
reject(response.error);
return;
}
resolve();
});
});
}
class TabDebugger {
constructor(tabId) {
var tabDebugger = this;
this._tabId = tabId;
this._attached = true;
chrome.debugger.onDetach.addListener((source, reason) => {
if(source.tabId === tabDebugger._tabId) {
tabDebugger._attached = false;
}
});
}
connect() {
var tabDebugger = this;
return _attach(this._tabId).then(() => {
tabDebugger._attached = true;
});
}
sendCommand(command, data) {
var tabDebugger = this;
if(!this._attached) {
//TODO all settings (width/height/userAgent/etc.) are cleared when we reconnect - fix that
return this.connect().then(() => {
return _sendCommand(tabDebugger._tabId, command, data);
});
}
return _sendCommand(this._tabId, command, data);
}
}
export default TabDebugger; | Reconnect tab debugger when it gets detached. | Reconnect tab debugger when it gets detached.
| JavaScript | mit | kevinSuttle/EmulatedDeviceLab,kevinSuttle/EmulatedDeviceLab,kevinSuttle/EmulatedDeviceLab | ---
+++
@@ -33,14 +33,35 @@
class TabDebugger {
constructor(tabId) {
+ var tabDebugger = this;
this._tabId = tabId;
+ this._attached = true;
+
+ chrome.debugger.onDetach.addListener((source, reason) => {
+ if(source.tabId === tabDebugger._tabId) {
+ tabDebugger._attached = false;
+ }
+ });
}
connect() {
- return _attach(this._tabId);
+ var tabDebugger = this;
+
+ return _attach(this._tabId).then(() => {
+ tabDebugger._attached = true;
+ });
}
sendCommand(command, data) {
+ var tabDebugger = this;
+
+ if(!this._attached) {
+ //TODO all settings (width/height/userAgent/etc.) are cleared when we reconnect - fix that
+ return this.connect().then(() => {
+ return _sendCommand(tabDebugger._tabId, command, data);
+ });
+ }
+
return _sendCommand(this._tabId, command, data);
}
} |
7963273521e826e98efb4dc80d94962eda16cd93 | libs/ItemFactory.js | libs/ItemFactory.js | "use strict";
var exports = module.exports = {};
exports.AbstractItem = require('../items/AbstractItem.js');
exports.WifiGuestItem = require('../items/WifiGuestItem.js');
var FritzBoxAPI = require('./FritzBoxApi.js').FritzBoxAPI;
exports.Factory = function(FRITZBoxPlatform,homebridge) {
this.platform = FRITZBoxPlatform;
this.log = this.platform.log;
this.homebridge = homebridge;
this.fritzBoxApi = new FritzBoxAPI(FRITZBoxPlatform);
};
exports.Factory.prototype.CreateAccessories = function () {
var accessoryList = [];
accessoryList.push(new exports.WifiGuestItem(this.platform,this.homebridge,this.fritzBoxApi));
return accessoryList;
}; | "use strict";
var exports = module.exports = {};
exports.AbstractItem = require('../items/AbstractItem.js');
exports.WifiGuestItem = require('../items/WifiGuestItem.js');
var FritzBoxAPI = require('./FritzBoxAPI.js').FritzBoxAPI;
exports.Factory = function(FRITZBoxPlatform,homebridge) {
this.platform = FRITZBoxPlatform;
this.log = this.platform.log;
this.homebridge = homebridge;
this.fritzBoxApi = new FritzBoxAPI(FRITZBoxPlatform);
};
exports.Factory.prototype.CreateAccessories = function () {
var accessoryList = [];
accessoryList.push(new exports.WifiGuestItem(this.platform,this.homebridge,this.fritzBoxApi));
return accessoryList;
};
| Fix case insensitive import of FritzBoxAPI.js | Fix case insensitive import of FritzBoxAPI.js
On case sensitive filesystems (e.g. when running on a Raspberry Pi), the `require` failed since the file is called `FritzBoxAPI.js` instead of `FritzBoxApi.js`. | JavaScript | apache-2.0 | tommasomarchionni/homebridge-FRITZBox | ---
+++
@@ -2,7 +2,7 @@
var exports = module.exports = {};
exports.AbstractItem = require('../items/AbstractItem.js');
exports.WifiGuestItem = require('../items/WifiGuestItem.js');
-var FritzBoxAPI = require('./FritzBoxApi.js').FritzBoxAPI;
+var FritzBoxAPI = require('./FritzBoxAPI.js').FritzBoxAPI;
exports.Factory = function(FRITZBoxPlatform,homebridge) {
this.platform = FRITZBoxPlatform; |
8f49e5e7fd94cde6463a82b6296ed906e8ef749c | wherehows-web/tests/integration/components/datasets/health/score-table-test.js | wherehows-web/tests/integration/components/datasets/health/score-table-test.js | import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | datasets/health/score-table', function(hooks) {
setupRenderingTest(hooks);
test('it renders', async function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.set('myAction', function(val) { ... });
await render(hbs`{{datasets/health/score-table}}`);
assert.equal(this.element.textContent.trim(), '');
// Template block usage:
await render(hbs`
{{#datasets/health/score-table}}
template block text
{{/datasets/health/score-table}}
`);
assert.equal(this.element.textContent.trim(), 'template block text');
});
});
| import { moduleForComponent, test } from 'ember-qunit';
import { run } from '@ember/runloop';
import hbs from 'htmlbars-inline-precompile';
import healthDetail from 'wherehows-web/mirage/fixtures/health-detail';
moduleForComponent('datasets/health/score-table', 'Integration | Component | datasets/health/score-table', {
integration: true
});
const table = '.dataset-health__score-table';
const row = `${table}__row`;
test('it renders', async function(assert) {
this.render(hbs`{{datasets/health/score-table}}`);
assert.ok(this.$(), 'Renders without errors as standalone component');
});
test('it renders the correct information', async function(assert) {
const tableData = healthDetail;
this.set('tableData', tableData);
this.render(hbs`{{datasets/health/score-table
tableData=tableData}}`);
assert.ok(this.$(), 'Still renders without errors');
assert.equal(this.$(table).length, 1, 'Renders one table');
assert.equal(this.$(row).length, tableData.length, 'Renders one row for every detail data');
});
test('it filters correctly', async function(assert) {
const tableData = healthDetail;
const numComplianceRows = tableData.reduce((sum, curr) => sum + (curr.category === 'Compliance' ? 1 : 0), 0);
this.setProperties({
tableData,
categoryFilter: 'Compliance',
severityFilter: ''
});
this.render(hbs`{{datasets/health/score-table
tableData=tableData
currentCategoryFilter=categoryFilter
currentSeverityFilter=severityFilter}}`);
assert.ok(this.$(), 'Still renders further without errors');
assert.equal(this.$(row).length, numComplianceRows, 'Show correct rows based on filter');
});
| Add tests for dataset health score table | Add tests for dataset health score table
| JavaScript | apache-2.0 | theseyi/WhereHows,alyiwang/WhereHows,alyiwang/WhereHows,linkedin/WhereHows,camelliazhang/WhereHows,theseyi/WhereHows,camelliazhang/WhereHows,linkedin/WhereHows,mars-lan/WhereHows,camelliazhang/WhereHows,linkedin/WhereHows,mars-lan/WhereHows,theseyi/WhereHows,theseyi/WhereHows,mars-lan/WhereHows,theseyi/WhereHows,mars-lan/WhereHows,camelliazhang/WhereHows,alyiwang/WhereHows,linkedin/WhereHows,alyiwang/WhereHows,theseyi/WhereHows,camelliazhang/WhereHows,mars-lan/WhereHows,linkedin/WhereHows,camelliazhang/WhereHows,alyiwang/WhereHows,alyiwang/WhereHows,mars-lan/WhereHows,linkedin/WhereHows | ---
+++
@@ -1,26 +1,48 @@
-import { module, test } from 'qunit';
-import { setupRenderingTest } from 'ember-qunit';
-import { render } from '@ember/test-helpers';
+import { moduleForComponent, test } from 'ember-qunit';
+import { run } from '@ember/runloop';
import hbs from 'htmlbars-inline-precompile';
+import healthDetail from 'wherehows-web/mirage/fixtures/health-detail';
-module('Integration | Component | datasets/health/score-table', function(hooks) {
- setupRenderingTest(hooks);
+moduleForComponent('datasets/health/score-table', 'Integration | Component | datasets/health/score-table', {
+ integration: true
+});
- test('it renders', async function(assert) {
- // Set any properties with this.set('myProperty', 'value');
- // Handle any actions with this.set('myAction', function(val) { ... });
+const table = '.dataset-health__score-table';
+const row = `${table}__row`;
- await render(hbs`{{datasets/health/score-table}}`);
+test('it renders', async function(assert) {
+ this.render(hbs`{{datasets/health/score-table}}`);
- assert.equal(this.element.textContent.trim(), '');
+ assert.ok(this.$(), 'Renders without errors as standalone component');
+});
- // Template block usage:
- await render(hbs`
- {{#datasets/health/score-table}}
- template block text
- {{/datasets/health/score-table}}
- `);
+test('it renders the correct information', async function(assert) {
+ const tableData = healthDetail;
- assert.equal(this.element.textContent.trim(), 'template block text');
+ this.set('tableData', tableData);
+ this.render(hbs`{{datasets/health/score-table
+ tableData=tableData}}`);
+
+ assert.ok(this.$(), 'Still renders without errors');
+ assert.equal(this.$(table).length, 1, 'Renders one table');
+ assert.equal(this.$(row).length, tableData.length, 'Renders one row for every detail data');
+});
+
+test('it filters correctly', async function(assert) {
+ const tableData = healthDetail;
+ const numComplianceRows = tableData.reduce((sum, curr) => sum + (curr.category === 'Compliance' ? 1 : 0), 0);
+
+ this.setProperties({
+ tableData,
+ categoryFilter: 'Compliance',
+ severityFilter: ''
});
+
+ this.render(hbs`{{datasets/health/score-table
+ tableData=tableData
+ currentCategoryFilter=categoryFilter
+ currentSeverityFilter=severityFilter}}`);
+
+ assert.ok(this.$(), 'Still renders further without errors');
+ assert.equal(this.$(row).length, numComplianceRows, 'Show correct rows based on filter');
}); |
70a6c94d67a3edd0ffaab0f3e17c31fc86689f95 | public/js/application.js | public/js/application.js | /**
* Open external links in new tabs automatically
*/
var links = document.links;
for (var i = 0; i < links.length; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
| /**
* Open external links in new tabs automatically
*/
var domReady = function(callback) {
// Enable jQuery's $(document).ready() in Vanilla Js
document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback);
};
domReady(function() {
var links = document.links;
for (var i = 0; i < links.length; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
});
| Add vanilla Js DOMContentLoaded event | Add vanilla Js DOMContentLoaded event
| JavaScript | mit | nchristiny/nchristiny.github.io,nchristiny/nchristiny.github.io,nchristiny/nchristiny.github.io | ---
+++
@@ -2,10 +2,18 @@
* Open external links in new tabs automatically
*/
-var links = document.links;
+var domReady = function(callback) {
+// Enable jQuery's $(document).ready() in Vanilla Js
+ document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback);
+};
-for (var i = 0; i < links.length; i++) {
- if (links[i].hostname != window.location.hostname) {
- links[i].target = '_blank';
+domReady(function() {
+
+ var links = document.links;
+
+ for (var i = 0; i < links.length; i++) {
+ if (links[i].hostname != window.location.hostname) {
+ links[i].target = '_blank';
+ }
}
-}
+}); |
0def13e1ebdd3bbb1dd0c072132ec4a959799857 | src/packages/examples-ext/index.js | src/packages/examples-ext/index.js | var Package = require('dgeni').Package;
/**
* @dgPackage examples-ext
* @description Extensions for the dgeni-packages/examples
*/
module.exports = new Package('examples-ext', [require('dgeni-packages/examples')])
// Add in the real processors for this package
.processor(require('./processors/exampleDependenciesBuilder'))
// add more templates location
.config(function(templateFinder) {
templateFinder.templateFolders.unshift(path.resolve(__dirname, 'templates'));
})
; | var Package = require('dgeni').Package;
var path = require('path');
/**
* @dgPackage examples-ext
* @description Extensions for the dgeni-packages/examples
*/
module.exports = new Package('examples-ext', [require('dgeni-packages/examples')])
// Add in the real processors for this package
.processor(require('./processors/exampleDependenciesBuilder'))
// add more templates location
.config(function(templateFinder) {
templateFinder.templateFolders.unshift(path.resolve(__dirname, 'templates'));
})
; | Fix for bug where path variable did not exist | Fix for bug where path variable did not exist
| JavaScript | mit | wingedfox/dgeni-alive,wingedfox/dgeni-alive | ---
+++
@@ -1,4 +1,5 @@
var Package = require('dgeni').Package;
+var path = require('path');
/**
* @dgPackage examples-ext |
14f204578b5f0d405f595dd7e2b7a73fd99aa78b | intents/help-intent-function.js | intents/help-intent-function.js | module.exports = HelpIntentFunction
// Purpose: To provide the user with more information on how to use the skill
// param (in): intent: given by Alexa, allows code to access parts of the intent request
// param (in): session: given by Alexa, allows code to access parts of the session in the Lambda request
// param (out): request: allows the user to change the response by Alexa
function HelpIntentFunction (intent, session, response) {
var begin = 'This is a skill that allows you to find jobs using themuse.com '
var useFindNewest = 'In order to find the newest job postings, please say Alexa, ask muse jobs to give me the newest job postings. '
var useLocation = 'In order to find the newest job postings by location, please say Alexa, ask muse jobs to tell me the jobs near New York City Metro Area. '
var useLevel = 'In order to find the newest job postings by location, please say Alexa, ask Muse Jobs to show jobs that are Entry Level. '
var question = 'What would you like to do ?'
var output = begin + useFindNewest + useLocation + useLevel + question
response.ask(output)
return
}
| module.exports = HelpIntentFunction
// Purpose: To provide the user with more information on how to use the skill
// param (in): intent: given by Alexa, allows code to access parts of the intent request
// param (in): session: given by Alexa, allows code to access parts of the session in the Lambda request
// param (out): request: allows the user to change the response by Alexa
function HelpIntentFunction (intent, session, response) {
var begin = 'This is a skill that allows you to find jobs using themuse.com '
var useFindNewest = 'In order to find the newest job postings, please say Alexa, ask muse jobs to give me the newest job postings. '
var useLocation = 'In order to find the newest job postings by location, please say Alexa, ask muse jobs to tell me the jobs near New York City Metro Area. '
var useLevel = 'In order to find the newest job postings by location, please say Alexa, ask Muse Jobs to show jobs that are Entry Level. '
var useCategory = 'In order to find the newest job postings by category, please say Alexa, ask Muse Jobs to tell me jobs that are in the category engineering. '
var question = 'What would you like to do ?'
var output = begin + useFindNewest + useLocation + useLevel + useCategory + question
response.ask(output)
return
}
| Update Help Intent with new Instruction | Update Help Intent with new Instruction
| JavaScript | mit | acucciniello/the-muse-jobs | ---
+++
@@ -10,8 +10,9 @@
var useFindNewest = 'In order to find the newest job postings, please say Alexa, ask muse jobs to give me the newest job postings. '
var useLocation = 'In order to find the newest job postings by location, please say Alexa, ask muse jobs to tell me the jobs near New York City Metro Area. '
var useLevel = 'In order to find the newest job postings by location, please say Alexa, ask Muse Jobs to show jobs that are Entry Level. '
+ var useCategory = 'In order to find the newest job postings by category, please say Alexa, ask Muse Jobs to tell me jobs that are in the category engineering. '
var question = 'What would you like to do ?'
- var output = begin + useFindNewest + useLocation + useLevel + question
+ var output = begin + useFindNewest + useLocation + useLevel + useCategory + question
response.ask(output)
return
} |
85ee4e2b89a5611c6c55aee3e351a2ec71d7f920 | resources/assets/components/ReviewBlock/index.js | resources/assets/components/ReviewBlock/index.js | import React from 'react';
import Tags from '../Tags';
import StatusButton from '../StatusButton';
class ReviewBlock extends React.Component {
setStatus(status) {
this.props.onUpdate(this.props.post.id, { status: status });
}
render() {
const post = this.props.post;
return (
<div>
<ul className="form-actions -inline" style={{'marginTop': 0}}>
<li><StatusButton type="accepted" label="accept" status={post.status} setStatus={this.setStatus.bind(this)}/></li>
<li><StatusButton type="rejected" label="reject" status={post.status} setStatus={this.setStatus.bind(this)}/></li>
</ul>
<ul className="form-actions -inline">
<li><button className="button delete -tertiary" onClick={e => this.props.deletePost(post['id'], e)}>Delete</button></li>
</ul>
{post.status === 'accepted' ?
<Tags id={post.id} tagged={post.tagged} onTag={this.props.onTag} />
: null}
</div>
)
}
}
export default ReviewBlock;
| import React from 'react';
import Tags from '../Tags';
import StatusButton from '../StatusButton';
class ReviewBlock extends React.Component {
setStatus(status) {
this.props.onUpdate(this.props.post.id, { status: status });
}
render() {
const post = this.props.post;
return (
<div>
<ul className="form-actions -inline" style={{'marginTop': 0}}>
<li><StatusButton type="accepted" label="accept" status={post.status} setStatus={this.setStatus.bind(this)}/></li>
<li><StatusButton type="rejected" label="reject" status={post.status} setStatus={this.setStatus.bind(this)}/></li>
</ul>
<ul className="form-actions -inline">
<li><button className="button delete -tertiary" onClick={e => this.props.deletePost(post['id'], e)}>Delete</button></li>
</ul>
{post.status === 'accepted' ?
<Tags id={post.id} tagged={post.tags} onTag={this.props.onTag} />
: null}
</div>
)
}
}
export default ReviewBlock;
| Use new 'tags' property instead of old 'tagged' property on posts | Use new 'tags' property instead of old 'tagged' property on posts
| JavaScript | mit | DoSomething/rogue,DoSomething/rogue,DoSomething/rogue | ---
+++
@@ -21,7 +21,7 @@
<li><button className="button delete -tertiary" onClick={e => this.props.deletePost(post['id'], e)}>Delete</button></li>
</ul>
{post.status === 'accepted' ?
- <Tags id={post.id} tagged={post.tagged} onTag={this.props.onTag} />
+ <Tags id={post.id} tagged={post.tags} onTag={this.props.onTag} />
: null}
</div>
) |
037f920a2b3383c088f3738a4354effb68e22829 | src/js/Helpers/dancerData.js | src/js/Helpers/dancerData.js | const makeDancer = (mass, x, y, z) => ({ mass, position: [x, y, z] });
module.export = [
makeDancer(100, -3, 4, -8),
makeDancer(200, -2, -1, -12),
makeDancer(700, 3, 2, -8),
makeDancer(1200, 1, -2, -7),
];
| const makeDancer = (mass, x, y, z) => ({ mass, position: [x, y, z] });
const dancerData = [
makeDancer(100, -3, 4, -8),
makeDancer(200, -2, -1, -12),
makeDancer(700, 3, 2, -8),
makeDancer(1200, 1, -2, -7),
];
module.exports = dancerData;
| Make dummy dancer data and export it | Make dummy dancer data and export it
| JavaScript | mit | elliotaplant/celestial-dance,elliotaplant/celestial-dance | ---
+++
@@ -1,7 +1,9 @@
const makeDancer = (mass, x, y, z) => ({ mass, position: [x, y, z] });
-module.export = [
+const dancerData = [
makeDancer(100, -3, 4, -8),
makeDancer(200, -2, -1, -12),
makeDancer(700, 3, 2, -8),
makeDancer(1200, 1, -2, -7),
];
+
+module.exports = dancerData; |
3a7b21cd0af3c37993b367a0853e3dd335e76a2d | config/express-config.js | config/express-config.js | /*
* This file exports the configuration Express.js back to the application
* so that it can be used in other parts of the product.
*/
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
exports.setup = function(app, express) {
app.set('views', 'public/views');
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'mylittlesecret' , resave: false, saveUninitialized: false }));
app.use(cookieParser());
app.use(express.static('./public'));
} | /*
* This file exports the configuration Express.js back to the application
* so that it can be used in other parts of the product.
*/
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
exports.setup = function(app, express) {
app.set('views', path.join(__dirname + '../../public/views'));
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'mylittlesecret' , resave: false, saveUninitialized: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname + '../../public')));
} | Change how the path is set for Express | Change how the path is set for Express
| JavaScript | mit | kurtbradd/facebook-music-recommender,kurtbradd/facebook-music-recommender,kurtbradd/facebook-music-recommender,kurtbradd/facebook-music-recommender | ---
+++
@@ -10,12 +10,12 @@
var session = require('express-session');
exports.setup = function(app, express) {
- app.set('views', 'public/views');
+ app.set('views', path.join(__dirname + '../../public/views'));
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({ secret: 'mylittlesecret' , resave: false, saveUninitialized: false }));
app.use(cookieParser());
- app.use(express.static('./public'));
+ app.use(express.static(path.join(__dirname + '../../public')));
} |
02ea5a0689d3d5cd1a0a11b78de50a833f09ea21 | server/app/controllers/hello-world-controller.js | server/app/controllers/hello-world-controller.js | const winston = require('winston');
/**
* Says Hello World and compute 1+1.
*
* @param req Request
* @param res Response
* @return {Promise.<void>} Nothing
*/
async function sayHelloWorld(req, res) {
const [rows] = await req.db.query('SELECT 1 + 1 AS solution');
req.db.release();
res.send(`Hello World ! Result of 1 + 1 is ${rows[0].solution}`);
winston.debug('API request to hello world:', rows[0]);
res.end();
}
module.exports = {
sayHelloWorld
};
| const winston = require('winston');
/**
* Says Hello World and compute 1+1.
*
* @param req Request
* @param res Response
* @return {Promise.<void>} Nothing
*/
async function sayHelloWorld(req, res) {
//async: declare a function which can wait for a expression with the 'await' keyword
const [rows] = await req.db.query('SELECT 1 + 1 AS solution');
// Declare const array
// await: wait for the expression
// req.db.query: execute function called query of the db object define in req object (parameter)
// When the expression after await is resolved, rows contains the return values
req.db.release();
// Release the database connection
res.send(`Hello World ! Result of 1 + 1 is ${rows[0].solution}`);
// res.send(): send the string back to the client
winston.debug('API request to hello world:', rows[0]);
// Log the API call
res.end();
// Close the response
}
// async function otherFunction(req, res) {
//some other stuff heure
// }
module.exports = {
sayHelloWorld,
/* Here you can export all functions you want to use outside the file
*/
};
| Add comments for hello word controller | Add comments for hello word controller
| JavaScript | apache-2.0 | K-Fet/K-App,K-Fet/K-App,K-Fet/K-App,K-Fet/K-App | ---
+++
@@ -8,18 +8,33 @@
* @return {Promise.<void>} Nothing
*/
async function sayHelloWorld(req, res) {
+ //async: declare a function which can wait for a expression with the 'await' keyword
const [rows] = await req.db.query('SELECT 1 + 1 AS solution');
+ // Declare const array
+ // await: wait for the expression
+ // req.db.query: execute function called query of the db object define in req object (parameter)
+ // When the expression after await is resolved, rows contains the return values
+
req.db.release();
+ // Release the database connection
res.send(`Hello World ! Result of 1 + 1 is ${rows[0].solution}`);
+ // res.send(): send the string back to the client
winston.debug('API request to hello world:', rows[0]);
+ // Log the API call
res.end();
+ // Close the response
}
+// async function otherFunction(req, res) {
+//some other stuff heure
+// }
module.exports = {
- sayHelloWorld
+ sayHelloWorld,
+ /* Here you can export all functions you want to use outside the file
+ */
};
|
574709159d2d392aef7aa4cf14413efb03438e72 | client/iFrameScripts.js | client/iFrameScripts.js | /* eslint-disable no-undef, no-unused-vars, no-native-reassign */
window.__$ = parent.$;
window.__$(function() {
var _ = parent._;
var Rx = parent.Rx;
var chai = parent.chai;
var assert = chai.assert;
var tests = parent.tests;
var common = parent.common;
var editor = common.editor.getValue();
// grab the iframe body element
var body = document.getElementsByTagName('body');
// change the context of $ so it uses the iFrame for testing
var $ = __$.proxy(__$.fn.find, __$(body));
common.runPreviewTests$ =
function runPreviewTests$({ tests = [], ...rest }) {
return Rx.Observable.from(tests)
.map(test => {
const userTest = {};
try {
/* eslint-disable no-eval */
eval(test);
/* eslint-enable no-eval */
} catch (e) {
userTest.err = e.message.split(':').shift();
} finally {
userTest.text = test
.split(',')
.pop()
.replace(/\'/g, '')
.replace(/\)/, '');
}
return userTest;
})
.toArray()
.map(tests => ({ ...rest, tests }));
};
});
| /* eslint-disable no-undef, no-unused-vars, no-native-reassign */
window.__$ = parent.$;
window.__$(function() {
var _ = parent._;
var Rx = parent.Rx;
var chai = parent.chai;
var assert = chai.assert;
var tests = parent.tests;
var common = parent.common;
var editor = common.editor.getValue();
// change the context of $ so it uses the iFrame for testing
var $ = __$.proxy(__$.fn.find, __$(document));
common.runPreviewTests$ =
function runPreviewTests$({ tests = [], ...rest }) {
return Rx.Observable.from(tests)
.map(test => {
const userTest = {};
try {
/* eslint-disable no-eval */
eval(test);
/* eslint-enable no-eval */
} catch (e) {
userTest.err = e.message.split(':').shift();
} finally {
userTest.text = test
.split(',')
.pop()
.replace(/\'/g, '')
.replace(/\)/, '');
}
return userTest;
})
.toArray()
.map(tests => ({ ...rest, tests }));
};
});
| Fix use the document as the proxy for jquery We proxy the jquery object. This lets us use the jQuery that FCC uses in the iframe. | Fix use the document as the proxy for jquery
We proxy the jquery object. This lets us use the jQuery that FCC
uses in the iframe.
Since jQuery sets the context, the main document object or DOM, at script
load, we need to create a proxy with the context of the iframe,
the document object of the iframe.
This was originally set to the body element. But not all challenges
require a body element.
| JavaScript | bsd-3-clause | Munsterberg/freecodecamp,pahosler/freecodecamp,Munsterberg/freecodecamp,BhaveshSGupta/FreeCodeCamp,tmashuang/FreeCodeCamp,matthew-t-smith/freeCodeCamp,techstonia/FreeCodeCamp,codeman869/FreeCodeCamp,BerkeleyTrue/FreeCodeCamp,MiloATH/FreeCodeCamp,TheeMattOliver/FreeCodeCamp,systimotic/FreeCodeCamp,BhaveshSGupta/FreeCodeCamp,no-stack-dub-sack/freeCodeCamp,BhaveshSGupta/FreeCodeCamp,FreeCodeCamp/FreeCodeCamp,DusanSacha/FreeCodeCamp,techstonia/FreeCodeCamp,BerkeleyTrue/FreeCodeCamp,sakthik26/FreeCodeCamp,tmashuang/FreeCodeCamp,FreeCodeCampQuito/FreeCodeCamp,FreeCodeCamp/FreeCodeCamp,matthew-t-smith/freeCodeCamp,otavioarc/freeCodeCamp,HKuz/FreeCodeCamp,HKuz/FreeCodeCamp,sakthik26/FreeCodeCamp,DusanSacha/FreeCodeCamp,BrendanSweeny/FreeCodeCamp,jonathanihm/freeCodeCamp,TheeMattOliver/FreeCodeCamp,codeman869/FreeCodeCamp,FreeCodeCampQuito/FreeCodeCamp,1111113j8Pussy420/https-github.com-raisedadead-freeCodeCamp,raisedadead/FreeCodeCamp,BrendanSweeny/FreeCodeCamp,pahosler/freecodecamp,MiloATH/FreeCodeCamp,otavioarc/freeCodeCamp,systimotic/FreeCodeCamp,raisedadead/FreeCodeCamp,no-stack-dub-sack/freeCodeCamp,jonathanihm/freeCodeCamp,1111113j8Pussy420/https-github.com-raisedadead-freeCodeCamp | ---
+++
@@ -8,10 +8,8 @@
var tests = parent.tests;
var common = parent.common;
var editor = common.editor.getValue();
- // grab the iframe body element
- var body = document.getElementsByTagName('body');
// change the context of $ so it uses the iFrame for testing
- var $ = __$.proxy(__$.fn.find, __$(body));
+ var $ = __$.proxy(__$.fn.find, __$(document));
common.runPreviewTests$ =
function runPreviewTests$({ tests = [], ...rest }) { |
ba39ade863fc0b9ed761a9c6cac2df4305e8e045 | src/js/utils/urlUtils.js | src/js/utils/urlUtils.js |
import util from './util';
/**
* @namespace
*
*/
var urlUtils = {
/***
* @param {String} url
* @type String
*/
getOrigin:function( url ){
var result = /https?:\/\/[^/]*\/?/.exec( url );
return result.length ? result[0] : null;
},
/**
* @param {HTMLElement} el
* @type Object
*/
getOriginByFrameEl:function( el ){
return util.isElement( el ) ? urlUtils.getOrigin( el.src ) : document.referrer;
}
};
export default urlUtils;
|
import util from './util';
/**
* @namespace
*
*/
var urlUtils = {
/***
* @param {String} url
* @type String
*/
getOrigin:function( url ){
var result = /https?:\/\/[^/]*\/?/.exec( url );
return result.length ? result[0] : null;
},
/**
* @param {HTMLElement} el
* @type Object
*/
getOriginByFrameEl:function( el ){
return util.isElement( el ) ? urlUtils.getOrigin( el.src ) : (document.referrer ? document.referrer : urlUtils.getOrigin(document.location.href));
}
};
export default urlUtils;
| Return current domain if the document.referrer is empty string (dynamic iframe created) | Return current domain if the document.referrer is empty string (dynamic iframe created)
| JavaScript | mit | eHanlin/frame-observer,eHanlin/frame-observer | ---
+++
@@ -22,7 +22,7 @@
*/
getOriginByFrameEl:function( el ){
- return util.isElement( el ) ? urlUtils.getOrigin( el.src ) : document.referrer;
+ return util.isElement( el ) ? urlUtils.getOrigin( el.src ) : (document.referrer ? document.referrer : urlUtils.getOrigin(document.location.href));
}
};
|
1660fb5c1c7aba4dec6709ae9b4ef3fdb88b579a | test/actions/ScreenActions.spec.js | test/actions/ScreenActions.spec.js | import setCurrentScreenAction from "src/actions/ScreenActions.js";
import { SET_CURRENT_SCREEN, MENU_SCREEN,
GAME_SCREEN} from "src/actions/ScreenActions.js";
describe("Screen Actions", () => {
it("should exist", () => {
setCurrentScreenAction.should.exist;
});
it("should be a function", () => {
setCurrentScreenAction.should.be.function;
});
it("should create action of type SET_CURRENT_SCREEN", () => {
const action = setCurrentScreenAction(MENU_SCREEN);
action.type.should.be.equal(SET_CURRENT_SCREEN);
});
it("should have parameter screen equal to function argument", () => {
const action = setCurrentScreenAction(MENU_SCREEN);
const setMenuScreenAction = {
screen: MENU_SCREEN,
type: SET_CURRENT_SCREEN
};
action.should.be.eql(setMenuScreenAction);
action = setCurrentScreenAction(GAME_SCREEN);
const setGameScreenAction = {
screen: GAME_SCREEN,
type: SET_CURRENT_SCREEN
};
action.should.be.eql(setGameScreenAction);
});
});
| import setCurrentScreenAction from "src/actions/ScreenActions.js";
import { SET_CURRENT_SCREEN, MENU_SCREEN,
GAME_SCREEN} from "src/actions/ScreenActions.js";
describe("Screen Actions", () => {
it("should exist", () => {
setCurrentScreenAction.should.exist;
});
it("should be a function", () => {
setCurrentScreenAction.should.be.function;
});
it("should create action of type SET_CURRENT_SCREEN", () => {
const action = setCurrentScreenAction(MENU_SCREEN);
action.type.should.be.equal(SET_CURRENT_SCREEN);
});
it("should have parameter screen equal to function argument", () => {
const action = setCurrentScreenAction(MENU_SCREEN);
const setMenuScreenAction = {
screen: MENU_SCREEN,
type: SET_CURRENT_SCREEN
};
action.should.be.eql(setMenuScreenAction);
});
it("should have parameter screen equal to function argument", () => {
const action = setCurrentScreenAction(GAME_SCREEN);
const setGameScreenAction = {
screen: GAME_SCREEN,
type: SET_CURRENT_SCREEN
};
action.should.be.eql(setGameScreenAction);
});
});
| Refactor split one ‘it’ block that was testing two things into two ’it blocks’ | Refactor split one ‘it’ block that was testing two things into two ’it blocks’
| JavaScript | mit | Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React | ---
+++
@@ -26,8 +26,10 @@
};
action.should.be.eql(setMenuScreenAction);
-
- action = setCurrentScreenAction(GAME_SCREEN);
+ });
+
+ it("should have parameter screen equal to function argument", () => {
+ const action = setCurrentScreenAction(GAME_SCREEN);
const setGameScreenAction = {
screen: GAME_SCREEN, |
ea39d81e578e21ce674e647e66b2e7f9a12116ef | test/llvm/helper.js | test/llvm/helper.js | var expect = require('expect.js'),
child_process = require('child_process')
function spawnSync (cmd, args, input) {
var opts = {
stdio: 'pipe',
env: process.env
}
if (input !== undefined) {
opts.input = input
}
if (args === undefined) { args = [] }
return child_process.spawnSync(cmd, args, opts)
}
function checkResult (result) {
// Print out the output streams if the status wasn't what we expected
if (result.error) {
throw result.error
}
var err = (result.stderr ? result.stderr : 'Missing STDERR').toString().trim()
if (err.length > 0) {
console.error(err)
}
// if (result.status !== 0) {
// console.log((result.stdout ? result.stdout : 'Missing STDOUT').toString())
// }
expect(result.status).to.eql(0)
return result
}
function runSync (cmd, input) {
var opts = {}
if (input !== undefined) {
opts.input = input
}
return child_process.execSync(cmd, opts)
}
module.exports = {
runSync: runSync,
spawnSync: spawnSync,
checkResult: checkResult
}
| var expect = require('expect.js'),
child_process = require('child_process')
function spawnSync (cmd, args, input) {
var opts = {
stdio: 'pipe',
env: process.env
}
if (input !== undefined) {
opts.input = input
}
if (args === undefined) { args = [] }
return child_process.spawnSync(cmd, args, opts)
}
function checkResult (result) {
// Print out the output streams if the status wasn't what we expected
if (result.error) {
throw result.error
}
var err = (result.stderr ? result.stderr : 'Missing STDERR').toString().trim()
if (err.length > 0) {
console.error(err)
}
// if (result.status !== 0) {
// console.log((result.stdout ? result.stdout : 'Missing STDOUT').toString())
// }
expect(result.status).to.eql(0)
return result
}
function runSync (cmd, input) {
var opts = {}
if (input !== undefined) {
opts.input = input
}
try {
return child_process.execSync(cmd, opts)
} catch (err) {
if (err.stdout) {
console.error(err.stdout.toString())
}
if (err.stderr) {
console.error(err.stderr.toString())
}
throw err
}
}
module.exports = {
runSync: runSync,
spawnSync: spawnSync,
checkResult: checkResult
}
| Improve logging from errors in LLVM tests | Improve logging from errors in LLVM tests
| JavaScript | bsd-3-clause | dirk/hummingbird,dirk/hummingbird,dirk/hummingbird | ---
+++
@@ -34,7 +34,17 @@
if (input !== undefined) {
opts.input = input
}
- return child_process.execSync(cmd, opts)
+ try {
+ return child_process.execSync(cmd, opts)
+ } catch (err) {
+ if (err.stdout) {
+ console.error(err.stdout.toString())
+ }
+ if (err.stderr) {
+ console.error(err.stderr.toString())
+ }
+ throw err
+ }
}
module.exports = { |
7f61ec3891bf24fdeee3a1637a0e6b3b3b9a96aa | src/js/model-list-list-tweets.js | src/js/model-list-list-tweets.js | YUI.add("model-list-list-tweets", function(Y) {
"use strict";
var tristis = Y.namespace("Tristis"),
models = Y.namespace("Tristis.Models"),
ListTweets;
ListTweets = Y.Base.create("listTweets", Y.LazyModelList, [
Y.namespace("Extensions").ModelListMore
], {
sync : function(action, options, done) {
tristis.twitter.get("lists/statuses", {
list_id : this.get("list_id"),
// TODO: configurable
include_rts : true
}, done);
}
}, {
ATTRS : {
list_id : null
}
});
models.ListTweets = ListTweets;
}, "@VERSION@", {
requires : [
// YUI
"base-build",
"lazy-model-list",
// Extensions
"extension-model-list-more"
]
});
| YUI.add("model-list-list-tweets", function(Y) {
"use strict";
var tristis = Y.namespace("Tristis"),
models = Y.namespace("Tristis.Models"),
ListTweets;
ListTweets = Y.Base.create("listTweets", Y.LazyModelList, [
Y.namespace("Extensions").ModelListMore
], {
sync : function(action, options, done) {
var args = {},
last;
if(action === "more") {
last = this.item(this.size() - 1);
if(last) {
args.since_id = last.id_str;
}
}
tristis.twitter.get("lists/statuses", Y.merge({
list_id : this.get("list_id"),
// TODO: configurable?
include_rts : true,
count : 50
}, args), done);
},
comparator : function(model) {
return Date.parse(model.created_at);
}
}, {
ATTRS : {
list_id : null
}
});
models.ListTweets = ListTweets;
}, "@VERSION@", {
requires : [
// YUI
"base-build",
"lazy-model-list",
// Extensions
"extension-model-list-more"
]
});
| Support since_id param on .more() calls | Support since_id param on .more() calls
| JavaScript | mit | tivac/falco,tivac/falco | ---
+++
@@ -10,11 +10,27 @@
Y.namespace("Extensions").ModelListMore
], {
sync : function(action, options, done) {
- tristis.twitter.get("lists/statuses", {
+ var args = {},
+ last;
+
+ if(action === "more") {
+ last = this.item(this.size() - 1);
+
+ if(last) {
+ args.since_id = last.id_str;
+ }
+ }
+
+ tristis.twitter.get("lists/statuses", Y.merge({
list_id : this.get("list_id"),
- // TODO: configurable
- include_rts : true
- }, done);
+ // TODO: configurable?
+ include_rts : true,
+ count : 50
+ }, args), done);
+ },
+
+ comparator : function(model) {
+ return Date.parse(model.created_at);
}
}, {
ATTRS : { |
a7532b5f550826d169f8aff8ad3c4e8b08a85c51 | web_modules/ws.js | web_modules/ws.js | // If there is no WebSocket, try MozWebSocket (support for some old browsers)
try {
module.exports = WebSocket
} catch(err) {
module.exports = MozWebSocket
} | // If there is no WebSocket, try MozWebSocket (support for some old browsers)
try {
module.exports = WebSocket;
} catch(err) {
module.exports = MozWebSocket;
}
// Some versions of Safari Mac 5 and Safari iOS 4 seem to support websockets,
// but can't communicate with websocketpp, which is what rippled uses.
//
// Note that we check for both the WebSocket protocol version the browser seems
// to implement as well as the user agent etc. The reason is that we want to err
// on the side of trying to connect since we don't want to accidentally disable
// a browser that would normally work fine.
var match, versionRegexp = /Version\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//;
if (
// Is browser
"object" === typeof navigator &&
"string" === typeof navigator.userAgent &&
// Is Safari
(match = versionRegexp.exec(navigator.userAgent)) &&
// And uses the old websocket protocol
2 === window.WebSocket.CLOSED
) {
// Is iOS
if (/iP(hone|od|ad)/.test(navigator.platform)) {
// Below version 5 is broken
if (+match[1] < 5) {
module.exports = void(0);
}
// Is any other Mac OS
// If you want to refactor this code, be careful, iOS user agents contain the
// string "like Mac OS X".
} else if (navigator.appVersion.indexOf("Mac") !== -1) {
// Below version 6 is broken
if (+match[1] < 6) {
module.exports = void(0);
}
}
}
| Disable ripple-lib in Safari iOS < 5 and Safari Mac < 6. | Disable ripple-lib in Safari iOS < 5 and Safari Mac < 6.
Actively disabling support for these browsers allows us to catch and report the
problem rather than trying to connect and failing for unknown reasons.
| JavaScript | isc | darkdarkdragon/ripple-lib,wilsonianb/ripple-lib,darkdarkdragon/ripple-lib,ripple/ripple-lib,darkdarkdragon/ripple-lib,wilsonianb/ripple-lib,wilsonianb/ripple-lib,ripple/ripple-lib,ripple/ripple-lib,ripple/ripple-lib | ---
+++
@@ -1,6 +1,40 @@
// If there is no WebSocket, try MozWebSocket (support for some old browsers)
try {
- module.exports = WebSocket
+ module.exports = WebSocket;
} catch(err) {
- module.exports = MozWebSocket
+ module.exports = MozWebSocket;
}
+
+// Some versions of Safari Mac 5 and Safari iOS 4 seem to support websockets,
+// but can't communicate with websocketpp, which is what rippled uses.
+//
+// Note that we check for both the WebSocket protocol version the browser seems
+// to implement as well as the user agent etc. The reason is that we want to err
+// on the side of trying to connect since we don't want to accidentally disable
+// a browser that would normally work fine.
+var match, versionRegexp = /Version\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//;
+if (
+ // Is browser
+ "object" === typeof navigator &&
+ "string" === typeof navigator.userAgent &&
+ // Is Safari
+ (match = versionRegexp.exec(navigator.userAgent)) &&
+ // And uses the old websocket protocol
+ 2 === window.WebSocket.CLOSED
+) {
+ // Is iOS
+ if (/iP(hone|od|ad)/.test(navigator.platform)) {
+ // Below version 5 is broken
+ if (+match[1] < 5) {
+ module.exports = void(0);
+ }
+ // Is any other Mac OS
+ // If you want to refactor this code, be careful, iOS user agents contain the
+ // string "like Mac OS X".
+ } else if (navigator.appVersion.indexOf("Mac") !== -1) {
+ // Below version 6 is broken
+ if (+match[1] < 6) {
+ module.exports = void(0);
+ }
+ }
+} |
b5a67aa2712934a565b35c471c7bf5eebcda44f8 | src/js/reducers/notifications.js | src/js/reducers/notifications.js | import { CLOSE_NOTIFICATION } from '../constants';
const initialState = {
isClosed: false,
notes: []
}
export default function update(state = initialState, action) {
if(action.type === CLOSE_NOTIFICATION) {
return {
isClosed: true
}
}
return state;
}
| import { CLOSE_NOTIFICATION } from '../constants';
const initialState = {
isClosed: true,
notes: []
}
export default function update(state = initialState, action) {
if(action.type === CLOSE_NOTIFICATION) {
return {
isClosed: true
}
}
return state;
}
| Hide notification about talent images | Hide notification about talent images
| JavaScript | mit | dfilipidisz/overwolf-hots-talents,dfilipidisz/overwolf-hots-talents,dfilipidisz/overfwolf-hots-talents,dfilipidisz/overfwolf-hots-talents | ---
+++
@@ -1,7 +1,7 @@
import { CLOSE_NOTIFICATION } from '../constants';
const initialState = {
- isClosed: false,
+ isClosed: true,
notes: []
}
|
7aaecc08327f14bb6db6e2951aa0aa30e65bc878 | webpack.common.js | webpack.common.js | const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: '[name].css', // '[name].[contenthash].css'
// disable: process.env.NODE_ENV === 'development'
});
module.exports = {
entry: {
app: './build/app',
worker: './build/worker'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
module: {
loaders: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.(css|scss)$/,
use: extractSass.extract({
use: [{
loader: 'css-loader'
}, {
loader: 'sass-loader'
}],
// use style-loader in development
fallback: 'style-loader'
})
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'url-loader',
options: {
limit: 10000
}
},
]
},
plugins: [
extractSass,
// new webpack.ProvidePlugin({
// $: 'jquery',
// jQuery: 'jquery'
// }),
],
};
| const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: '[name].css', // '[name].[contenthash].css'
// disable: process.env.NODE_ENV === 'development'
});
module.exports = {
entry: {
app: './build/app',
worker: './build/worker'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
module: {
loaders: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.(css|scss)$/,
use: extractSass.extract({
use: [{
loader: 'css-loader'
}, {
loader: 'sass-loader'
}],
// use style-loader in development
fallback: 'style-loader'
})
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'url-loader',
options: {
limit: 10000
}
},
]
},
plugins: [
extractSass,
// new webpack.ProvidePlugin({
// $: 'jquery',
// jQuery: 'jquery'
// }),
new CopyWebpackPlugin([
{ from: 'server' /*, to: 'server'*/ },
])
],
};
| Add server folder copy to build | Add server folder copy to build
| JavaScript | mit | e7d/speedtest,e7d/speedtest | ---
+++
@@ -1,10 +1,12 @@
const path = require('path');
const webpack = require('webpack');
+const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: '[name].css', // '[name].[contenthash].css'
// disable: process.env.NODE_ENV === 'development'
});
+
module.exports = {
entry: {
@@ -53,5 +55,8 @@
// $: 'jquery',
// jQuery: 'jquery'
// }),
+ new CopyWebpackPlugin([
+ { from: 'server' /*, to: 'server'*/ },
+ ])
],
}; |
9e6bad29283b27f56ab5c597c85dcdeef99258f9 | lib/deployment/index.js | lib/deployment/index.js | /*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = {
create_service: require('deployment/services').create_service,
get_available_instances: require('deployment/instances').get_available_instances,
realize_application_templates: require('deployment/templates').realize_application_templates
};
| /*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick licenses this file to You 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.
*/
exports.create_service = require('deployment/services').create_service;
exports.get_available_instances = require('deployment/instances').get_available_instances;
exports.realize_application_templates = require('deployment/templates').realize_application_templates;
| Use normal exports here, not messing with the modules.exports | Use normal exports here, not messing with the modules.exports
| JavaScript | apache-2.0 | cloudkick/cast,cloudkick/cast,cloudkick/cast,cloudkick/cast | ---
+++
@@ -15,8 +15,6 @@
* limitations under the License.
*/
-module.exports = {
- create_service: require('deployment/services').create_service,
- get_available_instances: require('deployment/instances').get_available_instances,
- realize_application_templates: require('deployment/templates').realize_application_templates
-};
+exports.create_service = require('deployment/services').create_service;
+exports.get_available_instances = require('deployment/instances').get_available_instances;
+exports.realize_application_templates = require('deployment/templates').realize_application_templates; |
6e7681073c45ffb3a64a495a4829cf29196a14c9 | webpack.config.js | webpack.config.js | const path = require('path');
const webpack = require('webpack');
const glob = require('glob');
const pkg = require('./package.json');
function newConfig() {
return {
resolve: {
extensions: ['.coffee']
},
module: {
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
]
},
devtool: 'source-map',
output: {
filename: '[name].js',
chunkFilename: '[id][name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.DefinePlugin({
VERSION: JSON.stringify(pkg.version)
}),
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
sourceMap: true
})
]
}
};
var client = newConfig();
client.entry = {
'client': './src/client.coffee',
'client.min': './src/client.coffee'
};
client.output.library = ['airbrakeJs', 'Client'];
var jquery = newConfig();
jquery.entry = {
'instrumentation/jquery': './src/instrumentation/jquery.coffee',
'instrumentation/jquery.min': './src/instrumentation/jquery.coffee',
}
jquery.output.library = ['airbrakeJs', 'instrumentation', 'jquery'];
module.exports = [client, jquery];
| const path = require('path');
const webpack = require('webpack');
const glob = require('glob');
const pkg = require('./package.json');
function newConfig() {
return {
resolve: {
extensions: ['.coffee']
},
module: {
rules: [
{test: /\.coffee$/, loader: 'coffee-loader'}
]
},
devtool: 'nosources-source-map',
output: {
filename: '[name].js',
chunkFilename: '[id][name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.DefinePlugin({
VERSION: JSON.stringify(pkg.version)
}),
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/,
sourceMap: true
})
]
}
};
var client = newConfig();
client.entry = {
'client': './src/client.coffee',
'client.min': './src/client.coffee'
};
client.output.library = ['airbrakeJs', 'Client'];
var jquery = newConfig();
jquery.entry = {
'instrumentation/jquery': './src/instrumentation/jquery.coffee',
'instrumentation/jquery.min': './src/instrumentation/jquery.coffee',
}
jquery.output.library = ['airbrakeJs', 'instrumentation', 'jquery'];
module.exports = [client, jquery];
| Remove sources from source maps. | Remove sources from source maps.
| JavaScript | mit | airbrake/airbrake-js,airbrake/airbrake-js,airbrake/airbrake-js | ---
+++
@@ -16,7 +16,7 @@
]
},
- devtool: 'source-map',
+ devtool: 'nosources-source-map',
output: {
filename: '[name].js', |
3aab832524fed2f63f4c179ec7202fcedd921efb | webpack.config.js | webpack.config.js | const path = require('path')
const UglifyjsPlugin = require('uglifyjs-webpack-plugin')
const BannerPlugin = require('webpack').BannerPlugin
const { name, version, author } = require('./package.json')
const banner = `${name} v${version} | (c) 2015-${(new Date()).getFullYear()} by ${author}`
module.exports = {
entry: {
'cpf': './index.js',
'cpf.min': './index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
library: 'CPF',
libraryTarget: 'umd'
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: [
'env'
]
}
}]
},
optimization: {
minimize: false
},
plugins: [
new UglifyjsPlugin({
include: /\.min\.js$/,
uglifyOptions: {
output: {
comments: false,
}
}
}),
new BannerPlugin(banner)
],
stats: {
colors: true
}
}
| const path = require('path')
const UglifyjsPlugin = require('uglifyjs-webpack-plugin')
const BannerPlugin = require('webpack').BannerPlugin
const { name, version, author } = require('./package.json')
const banner = `${name} v${version} | (c) 2015-${(new Date()).getFullYear()} by ${author}`
module.exports = {
entry: {
'cpf': './index.js',
'cpf.min': './index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
library: 'CPF',
libraryTarget: 'umd',
// To solve a problem with Webpack 4 (webpack#6522).
globalObject: `typeof self !== 'undefined' ? self : this`
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: [
'env'
]
}
}]
},
optimization: {
minimize: false
},
plugins: [
new UglifyjsPlugin({
include: /\.min\.js$/,
uglifyOptions: {
output: {
comments: false,
}
}
}),
new BannerPlugin(banner)
],
stats: {
colors: true
}
}
| Solve a problema with Webpack 4 | Solve a problema with Webpack 4
| JavaScript | mit | theuves/cpf | ---
+++
@@ -14,7 +14,10 @@
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
library: 'CPF',
- libraryTarget: 'umd'
+ libraryTarget: 'umd',
+
+ // To solve a problem with Webpack 4 (webpack#6522).
+ globalObject: `typeof self !== 'undefined' ? self : this`
},
module: {
rules: [{ |
fbdbd93956241320bc3960d350c4dd0030cc6e84 | webpack.config.js | webpack.config.js | var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./scripts/index'
],
output: {
path: __dirname + '/scripts/',
filename: 'bundle.js',
publicPath: '/scripts/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{ test: /\.jsx?$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }
]
}
};
| var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./scripts/index'
],
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/scripts/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'scripts')
}]
}
};
| Use include over exclude so npm link works | Use include over exclude so npm link works
| JavaScript | mit | talldan/hex-demo-motion,roth1002/react-hot-boilerplate,surikaterna/formr,taskworld/react-overlay-popup,IoanAlexandru/React-Redux-with-Hot-Loading-and-tcomb-forms,barock19/react-hot-boilerplate,Eol217/redux-course,OlehHappy/oleh_010-DnD_React_transhand01_bind,addi90/redux-todo,revivek/hackdays-chat-client,joshlevy89/stock-market-app,GovWizely/trade-event-search-app,joshlevy89/pinclone,Youpinadi/load-monitor,ePak/react-datepicker-csp,ViniciusAtaide/reduxchat,gaearon/react-hot-boilerplate,VictorBjelkholm/webpack-node-ipfs-api-demo,samlawrencejones/react-starter,MirekSz/tic-tac-toe-gui,paragonbliss/ReduxTut,rahulpyd/react-dnd-sort-example,alex-cory/sf-hacks-react-starter,davesnx/wpbase.com,mikeastock/LonelyKnight,buttercomponents/butter-component,g8extended/Character-Generator,thrawny/hscards,npverni/react-hot-boilerplate,happypeter/sketch-with-css,sljuka/bizflow-ui,ScholtenSeb/react-hot-boilerplate,kostya9116/expense-app,lyhoanglong/react-hot-boilerplate,chasemc67/Unlimited-Image-Compression,morgante/deceptachat,ViniciusAtaide/chatflux,IanBarkerDev/pinterest,joshlevy89/the-book-thing,gilbox/elegant-react-hot-demo,Alkamenos/friendlist,csmalin/reduxchat,ecastano/generation-take-home,saeedmahani/rt-fullscreen-search,alexravs/midgar,ghostsnstuff/byte,dindonus/react-hot-boilerplate,JulianSamarjiev/redux-friendlist,bthj/chain-reaction-board,Eol217/redux-course,kylefdoherty/ipsum-generator,szhangpitt/react-hot-es6,cpachomski/Lines,Marcoga/react-timeslider-filter,JasonStoltz/test-runner-demo,roytang121/phaser-game-demo,vicai/MusicMoodzon,cruiz07/react-hot-boilerplate,LinkedList/react-hot-boilerplate,Barakar/FriendList,seanpharvey/react-hot-boilerplate,dbatten4/chessboard-react,yanhua365/react-hot-boilerplate,hidden4003/react-hot-boilerplate,autozimu/react-hot-boilerplate,mattcav/airline-interface-prototype,Marcoga/react-dnd-test,andrevvalle/redux-lab,nahkar/react_cms,buttercomponents/butter-component-builder,anara123/udemy-react-todo-app,prathamesh-sonpatki/openlib-react,amysimmons/mememe,nadee013/react-router,hedgerh/thinkful-react-style-guide,rikukissa/knockout-reflux,alejodiazg/alejodiazg.github.io,dixitc/react-hot-boilerplate,colevoss/react-hot-boilerplate,jnwng/calendar,w01fgang/react-hot-boilerplate,betoesquivel/hackmtyaug16_LSystemsUI,bcbcb/react-hot-boilerplate,j-der/pickmeup-ui,ijones16/react-hot-boilerplate,dhrp/react-overlay-popup,yanhua365/react-hot-boilerplate,batmanimal/react-hot-boilerplate,marg51/uto,mdkalish/json_selector,txgruppi/react-hot-boilerplate,weilidai2001/react-radium-playground,ntwcklng/react-hot-boilerplate,MirekSz/tic-tac-toe-gui,AndrewZures/ixora,zeljkoX/e-learning,gonardfreeman/moviesDB,skainth/500px-React,buttercomponents/butter-component-show-header,andrevvalle/redux-lab,ftorre104/todolist-redux,SwordSoul/swordsoul.github.com,aboutscript/react-tutorial-ninputs,GovWizely/trade-event-search-app,OlehHappy/oleh_009-DnD_React_transhand01_changed-forneeds,Florenz23/wifi_signals,taskworld/react-overlay-popup,tongcx/gantt.js,buttercomponents/butter-component-builder,gonardfreeman/moviesDB,roycejewell/flux-ui-example,ZigGreen/matrix-calc--test-task,marcello3d/react-hotplate,postazure/redux-helloworld,SiAdcock/bg-prototype,hedgerh/thinkful-react-blog,tomenden/webpack-react,ncuillery/react-hot-boilerplate,atlonis/teach-react,vsuperator/todomvc-redux,mjxm/loadingscreen,phosphene/react-d3-hotload-test-demo,thisishuey/react-hot-boilerplate,ncuillery/react-hot-boilerplate,Yangani/friendlist,rahulpyd/react-dnd-sort-example,nguoihocnghe/react-workshop-basic,hidden4003/react-hot-boilerplate,alexqeo/react-redux-todos,ifunk/audiovisual-react,ijones16/react-hot-boilerplate,taymoork2/react-hot-boilerplate,bofa/demography-portal,batmanimal/react-hot-boilerplate,johatl/react-hot-boilerplate3,mdanie2/stanford-prereq-graph,weixing2014/redux-todo,OlehHappy/oleh_009-DnD_React_transhand01_changed-forneeds,bedrich/gimme-react,alphanumeric0101/pomodo-it,Narasimman/ReactTrials,alex-cory/sf-hacks-react-starter,nataly87s/follow-mouse,hedgerh/thinkful-react-blog,jptconiconde/react-happy-starter,fatrossy/color_palette,barcicki/react-hot-gulp-boilerplate,betoesquivel/hackmtyaug16_LSystemsUI,morgante/laughbot,yang-wei/resit,ohlsont/commutable-homes,VictorBjelkholm/webpack-node-ipfs-api-demo,OlehHappy/oleh_007-DnD_React_tests,davesnx/wpbase.com,blaqbern/intro-to-react,alejodiazg/alejodiazg.github.io,nadee013/react-router,lelandlee/FoodFates,skainth/500px-React,happypeter/sketch-with-css,Alkamenos/friendlist,rikukissa/dogfight-dodgers,SalvaCarsi/Geometric,blaqbern/intro-to-react,alexqeo/react-redux-todos,Marcoga/react-dnd-test,anara123/udemy-react-todo-app,OlehHappy/oleh_007-DnD_React_tests,future-ui/basics,alphanumeric0101/pomodo-it,ivmarcos/react-hot-boilerplate,AlexKVal/react-hot-boilerplate,xaiki/react-popcorn,gordon2012/friendlist,yatish27/react-hot-boilerplate,cmelion/react-hot-boilerplate,j-der/pickmeup-ui,chasemc67/Unlimited-Image-Compression,bryaneaton13/discussion-comments,jakewisse/layout-dependent-rendering,ScholtenSeb/react-hot-boilerplate,pcdv/react-explorer,dhrp/react-overlay-popup,saeedmahani/rt-fullscreen-search,eric-wood/playlist,morgante/react-starter,Yangani/friendlist,OlehHappy/oleh_011-DnD_React_Native_Box,msikma/react-hot-boilerplate,Ligerlilly/redo,cdaringe/square-dance,surikaterna/formr,meta-meta/react-synonym-game,bryaneaton13/discussion-comments,hoodwink73/react-hello-world,bthj/chain-reaction-board,gaearon/react-hot-boilerplate,nahkar/react_cms,weixing2014/react-hot-boilerplate,gilbox/elegant-react-hot-demo,nataly87s/follow-mouse,colevoss/react-hot-boilerplate,ViniciusAtaide/reduxchat,InSuperposition/react-hot-boilerplate,OlehHappy/oleh_005-DnD_Chess_React,jonboerner/flipturn,morgante/deceptachat,seanpharvey/react-hot-boilerplate,agualbbus/fibmaps,rodolfo2488/butter-component-builder,r0m4/reactWebpack,thrawny/hscards,ntwcklng/react-hot-boilerplate,ViniciusAtaide/chatflux,joshlevy89/stock-market-app,rikukissa/flappy-bird,meta-meta/react-synonym-game,mattlewis92/react-imgur,kostya9116/expense-app,danielwerthen/react-hot-boilerplate,Youpinadi/load-monitor,esoman/eli-dnd,InSuperposition/react-hot-boilerplate,natstar93/React_train_timings,nrobin24/react-sidescroller,lassecapel/friendlist-app,edwinwright/react-project,jaredbrookswhite/barebones_react_hot_loading_boilerplate,addi90/redux-todo,ePak/react-datepicker-csp,aboutscript/react-tutorial-ninputs,rikukissa/dogfight-dodgers,deluxe-pig/cloud-farmer,ransanjeev/react-hot-boilerplate,vnguyen94/react-commute,r0m4/reactWebpack,buttercomponents/butter-component-settings,debarshri/react-logger,Ehesp/react-flux-webpack-boilerplate,OlehHappy/oleh_011-DnD_React_Native_Box,ifunk/audiovisual-react,Ehesp/react-flux-webpack-boilerplate,Narasimman/ReactTrials,vnguyen94/react-commute,CatDaVinci/wiser-react-redux,SalvaCarsi/Geometric,prathamesh-sonpatki/openlib-react,znation/react-hot-boilerplate,talldan/hex-demo-motion,alexravs/midgar,masonforest/stellar.dance,future-ui/basics,rahul14m93/GenerationProject,rodfernandez/react-hot-boilerplate,cdaringe/square-dance,jxnblk/react-basscss-hot-boilerplate,dixitc/react-hot-boilerplate,cruiz07/react-hot-boilerplate,thadiggitystank/react-hot-boilerplate,morgante/deceptachat,ivmarcos/react-hot-boilerplate,Florenz23/wifi_signals,rodolfo2488/butter-component-builder,xaiki/react-popcorn,joeyfigaro/migrated,mattlewis92/react-imgur,joshlevy89/the-book-thing,thisishuey/react-hot-boilerplate,yang-wei/resit,buttercomponents/butter-component-stars,schutterp/hotreactdux-fullstack-starter,kylefdoherty/redux-todo,rikukissa/dogfight-dodgers,dvshur/react-components-inject,kylefdoherty/redux-todo,Florenz23/wifi_signals,txgruppi/react-hot-boilerplate,SiAdcock/bg-prototype,chandlera/react-hot-boilerplate,msikma/react-hot-boilerplate,samlawrencejones/react-starter,vire/resit,autozimu/react-hot-boilerplate,agualbbus/fibmaps,pcdv/react-explorer,AndrewZures/ixora,rikukissa/flappy-bird,klik1301/ex7_repos_baobal,mdanie2/stanford-prereq-graph,roth1002/react-hot-boilerplate,barcicki/react-hot-gulp-boilerplate,pebie/ecodex,hedgerh/thinkful-reflux-async,CookPete/react-hot-boilerplate,jxnblk/react-basscss-hot-boilerplate,joeyfigaro/migrated,schutterp/hotreactdux-fullstack-starter,joshlevy89/pinclone,mboperator/fractalTodoExample,jonboerner/flipturn,mjxm/loadingscreen,barock19/react-hot-boilerplate,taggartbg/connectjs2015,g8extended/Character-Generator,znation/react-hot-boilerplate,atlonis/teach-react,eduardopoleo/blog-fe,OlehHappy/oleh_005-DnD_Chess_React,AlexKVal/react-hot-boilerplate,buttercomponents/butter-component-builder,thadiggitystank/react-hot-boilerplate,nadee013/react,triqi/react-snake,yatish27/react-hot-boilerplate,weixing2014/redux-todo,eric-wood/playlist,kylefdoherty/ipsum-generator,yang-wei/resit,cpachomski/Lines,cmelion/react-hot-boilerplate,vire/resit,hedgerh/thinkful-react-hoc,OlehHappy/oleh_012-DnD_React_Native_CustomElement,Ladex/reactSVG,nadee013/react,klik1301/ex7_repos_baobal,dvshur/react-components-inject,sljuka/bizflow-ui,CatDaVinci/wiser-react-redux,vicai/MusicMoodzon,rikukissa/knockout-reflux,hidden4003/react-hot-boilerplate,hedgerh/thinkful-react-style-guide,deluxe-pig/cloud-farmer,buttercomponents/butter-component,amysimmons/mememe,OlehHappy/oleh_008-DnD_React_transhand01,fatrossy/color_palette,OlehHappy/oleh_010-DnD_React_transhand01_bind,halochou/react-playground,roycejewell/flux-ui-example,miknonny/github-notetaker,phosphene/react-d3-hotload-test-demo,ZigGreen/matrix-calc--test-task,gordon2012/friendlist,szhangpitt/react-hot-es6,IanBarkerDev/pinterest,mboperator/fractalTodoExample,pebie/ecodex,tongcx/gantt.js,chandlera/react-hot-boilerplate,taymoork2/react-hot-boilerplate,mikeastock/LonelyKnight,bcbcb/react-hot-boilerplate,nrobin24/react-sidescroller,zeljkoX/e-learning,morgante/laughbot,edwinwright/react-project,OlehHappy/oleh_006-DnD_Native_Boxes,Marcoga/react-timeslider-filter,Ligerlilly/redo,DelvarWorld/cats-react,SwordSoul/swordsoul.github.com,bofa/demography-portal,buttercomponents/butter-base-components,hedgerh/thinkful-reflux-async,debarshri/react-logger,danielwerthen/react-hot-boilerplate,DelvarWorld/cats-react,ftorre104/todolist-redux,npverni/react-hot-boilerplate,johatl/react-hot-boilerplate3,jaredbrookswhite/barebones_react_hot_loading_boilerplate,jakewisse/layout-dependent-rendering,amysimmons/a-guide-to-the-care-and-feeding-of-new-devs,weilidai2001/react-radium-playground,w01fgang/react-hot-boilerplate,marg51/uto,Barakar/FriendList,CookPete/react-hot-boilerplate,JasonStoltz/test-runner-demo,vsuperator/todomvc-redux,halochou/react-playground,IoanAlexandru/React-Redux-with-Hot-Loading-and-tcomb-forms,buttercomponents/butter-component-show-detail,masonforest/stellar.dance,dbatten4/chessboard-react,jnwng/calendar,mattcav/airline-interface-prototype,ohlsont/commutable-homes,michaelBenin/react-hot-boilerplate,JulianSamarjiev/redux-friendlist,lelandlee/FoodFates,taggartbg/connectjs2015,OlehHappy/oleh_008-DnD_React_transhand01,roytang121/phaser-game-demo,esoman/eli-dnd,michaelBenin/react-hot-boilerplate,miknonny/github-notetaker,LinkedList/react-hot-boilerplate,weixing2014/react-hot-boilerplate,paragonbliss/ReduxTut,ransanjeev/react-hot-boilerplate,ecastano/generation-take-home,vire/resit,robsquires/react-audio-examples,henryhedges/react-hot-template,csmalin/reduxchat,OlehHappy/oleh_012-DnD_React_Native_CustomElement,natstar93/React_train_timings,robsquires/react-audio-examples,bedrich/gimme-react,postazure/redux-helloworld,triqi/react-snake,bedrich/gimme-react,jptconiconde/react-happy-starter,lyhoanglong/react-hot-boilerplate,rahul14m93/GenerationProject,mdkalish/json_selector,Ladex/reactSVG,henryhedges/react-hot-template,josebalius/react-hot-boilerplate,revivek/hackdays-chat-client,josebalius/react-hot-boilerplate,tomenden/webpack-react,OlehHappy/oleh_006-DnD_Native_Boxes,hedgerh/thinkful-react-hoc,dindonus/react-hot-boilerplate,rodfernandez/react-hot-boilerplate,lassecapel/friendlist-app,hoodwink73/react-hello-world,eduardopoleo/blog-fe,nguoihocnghe/react-workshop-basic,ghostsnstuff/byte,SwordSoul/swordsoul.github.com,morgante/react-starter,amysimmons/a-guide-to-the-care-and-feeding-of-new-devs | ---
+++
@@ -1,3 +1,4 @@
+var path = require('path');
var webpack = require('webpack');
module.exports = {
@@ -8,7 +9,7 @@
'./scripts/index'
],
output: {
- path: __dirname + '/scripts/',
+ path: path.join(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/scripts/'
},
@@ -20,8 +21,10 @@
extensions: ['', '.js', '.jsx']
},
module: {
- loaders: [
- { test: /\.jsx?$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }
- ]
+ loaders: [{
+ test: /\.jsx?$/,
+ loaders: ['react-hot', 'babel'],
+ include: path.join(__dirname, 'scripts')
+ }]
}
}; |
53ce5f02d9c78307bd1022ba3326d45d0093f50e | lib/defaults.js | lib/defaults.js | module.exports = {
server: {
port: process.env.NODE_PORT || 8080
, host: null
}
};
| module.exports = {
server: {
port: process.env.PORT || 8080
, host: null
}
};
| Fix the port env variable | Fix the port env variable
| JavaScript | mit | Bloggify/Bloggify | ---
+++
@@ -1,6 +1,6 @@
module.exports = {
server: {
- port: process.env.NODE_PORT || 8080
+ port: process.env.PORT || 8080
, host: null
}
}; |
9cc1e316360b41b5d19316ee7ec6acd59dfa0b91 | webpack.config.js | webpack.config.js | const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
index: './src/js/index.js',
options: './src/js/options.js'
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
filename: '[name].bundle.js'
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
};
| const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
index: './src/js/index.js',
options: './src/js/options.js'
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
filename: '[name].bundle.js'
},
plugins: [
new webpack.ProvidePlugin({
jQuery: 'jquery' // for jquery.esarea
})
]
};
| Remove needless providing for jQuery | Remove needless providing for jQuery
| JavaScript | mit | yoshihara/tsuibami,yoshihara/tsuibami | ---
+++
@@ -13,8 +13,7 @@
},
plugins: [
new webpack.ProvidePlugin({
- $: 'jquery',
- jQuery: 'jquery'
+ jQuery: 'jquery' // for jquery.esarea
})
]
}; |
cad4c74e98e2da7a8458a173da61fcc7382891a2 | lib/stripe/handlers/customer.subscription.deleted.js | lib/stripe/handlers/customer.subscription.deleted.js | 'use strict';
var models = require('../../models');
var sessionStore = require('../../app').sessionStore;
module.exports = function (data, callbackToStripe) {
if (isCanceled(data)) {
var removeProStatus = function(customer){
sessionStore.destroyByName(customer.user);
return models.user.setProAccount(customer.user, false);
};
var sendStripe200 = callbackToStripe.bind(null, null);
models.customer.setActive(data.customer, false)
.then(removeProStatus)
//.then(removeTeamStatus)
.then(sendStripe200)
.catch(callbackToStripe);
} else {
callbackToStripe(null);
}
};
function isCanceled(obj) {
return obj.status ? obj.status === 'canceled' : isCanceled(obj.data || obj.object);
}
| 'use strict';
var models = require('../../models');
var sessionStore = require('../../app').sessionStore;
var Promise = require('rsvp').Promise;
module.exports = function (data, callbackToStripe) {
if (isCanceled(data)) {
var removeProStatus = function(customer){
sessionStore.destroyByName(customer.user);
return models.user.setProAccount(customer.user, false);
};
var sendStripe200 = callbackToStripe.bind(null, null);
models.customer.setActive(data.customer, false)
.then(removeProStatus)
//.then(removeTeamStatus)
.then(sendStripe200)
.catch(callbackToStripe);
} else {
callbackToStripe(null);
}
};
function isCanceled(obj) {
return obj.status ? obj.status === 'canceled' : isCanceled(obj.data || obj.object);
}
function removeProStatusFromDB (customer) {
return new Promise(function(reject, resolve) {
models.user.setProAccount(customer.user, false, function(err) {
if (err) {
return reject(err);
}
resolve(customer);
});
});
}
function removeProStatusFromSession (customer) {
return sessionStore.set(customer.name, false);
}
| Split the removal of pro from session and db into separate functions | Split the removal of pro from session and db into separate functions
Both now use promises keeping flow control simple and less buggy
| JavaScript | mit | arcseldon/jsbin,mlucool/jsbin,kentcdodds/jsbin,vipulnsward/jsbin,arcseldon/jsbin,blesh/jsbin,jasonsanjose/jsbin-app,yohanboniface/jsbin,knpwrs/jsbin,mingzeke/jsbin,dennishu001/jsbin,KenPowers/jsbin,Hamcha/jsbin,jasonsanjose/jsbin-app,filamentgroup/jsbin,svacha/jsbin,saikota/jsbin,pandoraui/jsbin,pandoraui/jsbin,ctide/jsbin,AverageMarcus/jsbin,carolineartz/jsbin,yohanboniface/jsbin,AverageMarcus/jsbin,yize/jsbin,ilyes14/jsbin,thsunmy/jsbin,jamez14/jsbin,jsbin/jsbin,kirjs/jsbin,thsunmy/jsbin,dennishu001/jsbin,HeroicEric/jsbin,martinvd/jsbin,mdo/jsbin,vipulnsward/jsbin,jwdallas/jsbin,IvanSanchez/jsbin,remotty/jsbin,jwdallas/jsbin,mcanthony/jsbin,fend-classroom/jsbin,svacha/jsbin,dhval/jsbin,IveWong/jsbin,minwe/jsbin,johnmichel/jsbin,yize/jsbin,mingzeke/jsbin,HeroicEric/jsbin,minwe/jsbin,juliankrispel/jsbin,juliankrispel/jsbin,jamez14/jsbin,francoisp/jsbin,francoisp/jsbin,IveWong/jsbin,martinvd/jsbin,kirjs/jsbin,IvanSanchez/jsbin,late-warrior/jsbin,nitaku/jervis,carolineartz/jsbin,roman01la/jsbin,eggheadio/jsbin,KenPowers/jsbin,late-warrior/jsbin,fgrillo21/NPA-Exam,saikota/jsbin,Hamcha/jsbin,KenPowers/jsbin,knpwrs/jsbin,simonThiele/jsbin,Freeformers/jsbin,y3sh/jsbin-fork,simonThiele/jsbin,digideskio/jsbin,kentcdodds/jsbin,peterblazejewicz/jsbin,filamentgroup/jsbin,johnmichel/jsbin,dedalik/jsbin,fgrillo21/NPA-Exam,mcanthony/jsbin,knpwrs/jsbin,eggheadio/jsbin,ctide/jsbin,jsbin/jsbin,fend-classroom/jsbin,mlucool/jsbin,ilyes14/jsbin,y3sh/jsbin-fork,peterblazejewicz/jsbin,dhval/jsbin,digideskio/jsbin,roman01la/jsbin,dedalik/jsbin,Freeformers/jsbin | ---
+++
@@ -1,6 +1,7 @@
'use strict';
var models = require('../../models');
var sessionStore = require('../../app').sessionStore;
+var Promise = require('rsvp').Promise;
module.exports = function (data, callbackToStripe) {
if (isCanceled(data)) {
@@ -26,3 +27,17 @@
function isCanceled(obj) {
return obj.status ? obj.status === 'canceled' : isCanceled(obj.data || obj.object);
}
+function removeProStatusFromDB (customer) {
+ return new Promise(function(reject, resolve) {
+ models.user.setProAccount(customer.user, false, function(err) {
+ if (err) {
+ return reject(err);
+ }
+ resolve(customer);
+ });
+ });
+}
+
+function removeProStatusFromSession (customer) {
+ return sessionStore.set(customer.name, false);
+} |
8315d48117ba9bd54bcf8c6a9012d7a0cfbc2071 | 2018/js/day8.js | 2018/js/day8.js | window.AdventOfCode.Day8 = ( input ) =>
{
input = input.split( ' ' ).map( x => +x );
let part1 = 0;
const process = () =>
{
const childrenSize = input.shift();
const metadataSize = input.shift();
let values = [];
let value = 0;
for( let i = childrenSize; i > 0; i-- )
{
values.push( process() );
}
const metadata = input.slice( 0, metadataSize );
const metadataSum = metadata.reduce( ( a, b ) => a + b, 0 );
part1 += metadataSum;
if( childrenSize > 0 )
{
for( const i of metadata )
{
value += values[ i - 1 ] || 0;
}
}
else
{
value = metadataSum;
}
input = input.slice( metadataSize );
return value;
};
const part2 = process();
return [ part1, part2 ];
};
| window.AdventOfCode.Day8 = ( input ) =>
{
input = input.split( ' ' ).map( x => +x );
let part1 = 0;
let index = 0;
const process = () =>
{
const childrenSize = input[ index++ ];
const metadataSize = input[ index++ ];
let values = [];
let value = 0;
for( let i = childrenSize; i > 0; i-- )
{
values.push( process() );
}
const metadata = input.slice( index, index += metadataSize );
const metadataSum = metadata.reduce( ( a, b ) => a + b, 0 );
part1 += metadataSum;
if( childrenSize > 0 )
{
for( const i of metadata )
{
value += values[ i - 1 ] || 0;
}
}
else
{
value = metadataSum;
}
return value;
};
const part2 = process();
return [ part1, part2 ];
};
| Use index instead of shifting data | Use index instead of shifting data
| JavaScript | unlicense | xPaw/adventofcode-solutions,xPaw/adventofcode-solutions,xPaw/adventofcode-solutions | ---
+++
@@ -3,11 +3,12 @@
input = input.split( ' ' ).map( x => +x );
let part1 = 0;
+ let index = 0;
const process = () =>
{
- const childrenSize = input.shift();
- const metadataSize = input.shift();
+ const childrenSize = input[ index++ ];
+ const metadataSize = input[ index++ ];
let values = [];
let value = 0;
@@ -16,7 +17,7 @@
values.push( process() );
}
- const metadata = input.slice( 0, metadataSize );
+ const metadata = input.slice( index, index += metadataSize );
const metadataSum = metadata.reduce( ( a, b ) => a + b, 0 );
part1 += metadataSum;
@@ -33,8 +34,6 @@
value = metadataSum;
}
- input = input.slice( metadataSize );
-
return value;
};
|
450ac4a717454ad37a72d84a133d9c2a2f1c7eae | src/utils/transpile/index.js | src/utils/transpile/index.js | import React from 'react'
import transform from './transform'
import errorBoundary from './errorBoundary'
import evalCode from './evalCode'
export const generateElement = (
{ code = '', scope = {} },
errorCallback
) => (
errorBoundary(
evalCode(
`return (${transform(code)})`,
{ ...scope, React }
),
errorCallback
)
)
export const renderElementAsync = (
{ code = '', scope = {} },
resultCallback,
errorCallback
) => {
const render = element => {
resultCallback(
errorBoundary(
element,
errorCallback
)
)
}
if (!/render\s*\(/.test(code)) {
return errorCallback(
new SyntaxError('No-Inline evaluations must call `render`.')
)
}
evalCode(
transform(code),
{ ...scope, render, React }
)
}
| import React from 'react'
import transform from './transform'
import errorBoundary from './errorBoundary'
import evalCode from './evalCode'
export const generateElement = (
{ code = '', scope = {} },
errorCallback
) => {
// NOTE: Workaround for classes, since buble doesn't allow `return` without a function
const transformed = transform(code)
.trim()
.replace(/^var \w+ =/, '')
return errorBoundary(
evalCode(
`return ${transformed}`,
{ ...scope, React }
),
errorCallback
)
}
export const renderElementAsync = (
{ code = '', scope = {} },
resultCallback,
errorCallback
) => {
const render = element => {
resultCallback(
errorBoundary(
element,
errorCallback
)
)
}
if (!/render\s*\(/.test(code)) {
return errorCallback(
new SyntaxError('No-Inline evaluations must call `render`.')
)
}
evalCode(
transform(code),
{ ...scope, render, React }
)
}
| Fix Buble classes being transpiled to variable | Fix Buble classes being transpiled to variable
| JavaScript | cc0-1.0 | philpl/react-live | ---
+++
@@ -6,15 +6,20 @@
export const generateElement = (
{ code = '', scope = {} },
errorCallback
-) => (
- errorBoundary(
+) => {
+ // NOTE: Workaround for classes, since buble doesn't allow `return` without a function
+ const transformed = transform(code)
+ .trim()
+ .replace(/^var \w+ =/, '')
+
+ return errorBoundary(
evalCode(
- `return (${transform(code)})`,
+ `return ${transformed}`,
{ ...scope, React }
),
errorCallback
)
-)
+}
export const renderElementAsync = (
{ code = '', scope = {} }, |
b3b5e8e00b24582fdebd8f4251ba9b4e4d3804f9 | webpack.dev.config.js | webpack.dev.config.js | var _ = require('lodash');
var path = require('path');
var webpack = require('webpack');
var getWebpackConfig = require('./webpack.config.js');
var devConfig = _.assign(getWebpackConfig(), {
devtool: 'eval',
output: {
path: path.join(__dirname, '/app/'),
publicPath: '/app/',
filename: '[name].js'
}
});
_.keysIn(devConfig.entry).forEach(function(key) {
var currentValue = devConfig.entry[key];
devConfig.entry[key] = currentValue.concat(
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server'
);
});
devConfig.plugins = devConfig.plugins.concat(
new webpack.DefinePlugin({
DEBUG: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
);
module.exports = devConfig; | var _ = require('lodash');
var path = require('path');
var webpack = require('webpack');
var getWebpackConfig = require('./webpack.config.js');
var devConfig = _.assign(getWebpackConfig(), {
devtool: 'eval',
output: {
path: path.join(__dirname, '/app/'),
// Specify complete path to force
// chrome/FF load the images
publicPath: 'http://localhost:3000/app/',
filename: '[name].js'
}
});
_.keysIn(devConfig.entry).forEach(function(key) {
var currentValue = devConfig.entry[key];
devConfig.entry[key] = currentValue.concat(
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server'
);
});
devConfig.plugins = devConfig.plugins.concat(
new webpack.DefinePlugin({
DEBUG: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
);
module.exports = devConfig; | Fix publicPath for assets in dev mode | Fix publicPath for assets in dev mode
| JavaScript | mit | zdenekkostal/react-infinite-list,jankopriva/react-infinite-list,zdenekkostal/react-infinite-list,crudo/react-infinite-list,crudo/react-infinite-list,jankopriva/react-infinite-list | ---
+++
@@ -8,7 +8,10 @@
output: {
path: path.join(__dirname, '/app/'),
- publicPath: '/app/',
+
+ // Specify complete path to force
+ // chrome/FF load the images
+ publicPath: 'http://localhost:3000/app/',
filename: '[name].js'
}
}); |
525c7d2f109f4e0354069bebf21857c995dd6ca7 | src/client/app/basket/basket.service.js | src/client/app/basket/basket.service.js | "use strict";
(function () {
angular
.module("conpa")
.factory("basketService", basketService);
function basketService() {
var assets = [],
service = {
getAssets: getAssets,
addAsset: addAsset
};
return service;
function getAssets() {
return assets;
}
function addAsset(item) {
var isNew;
if (!item) {
return;
}
isNew = assets.filter(function (asset) {
if (item.name === asset.name) {
return asset;
}
}).length === 0;
if (isNew) {
assets.push(item);
}
}
}
}());
| "use strict";
(function () {
angular
.module("conpa")
.factory("basketService", basketService);
function basketService() {
var assets = [],
service = {
getAssets: getAssets,
addAsset: addAsset
};
return service;
function getAssets() {
return assets;
}
function addAsset(item) {
var isNew;
if (!item) {
return;
}
isNew = assets.filter(function (asset) {
if (item.symbol === asset.symbol) {
return asset;
}
}).length === 0;
if (isNew) {
assets.push(item);
}
}
}
}());
| Fix distinct asset in the basket. | Fix distinct asset in the basket.
| JavaScript | mit | albertosantini/node-conpa,albertosantini/node-conpa | ---
+++
@@ -26,7 +26,7 @@
}
isNew = assets.filter(function (asset) {
- if (item.name === asset.name) {
+ if (item.symbol === asset.symbol) {
return asset;
}
}).length === 0; |
dd252bdfe5470dd3429004844cfd7909b254740e | src/server/webpack-dev-server.js | src/server/webpack-dev-server.js | import url from 'url'
import webpack from 'webpack'
import WebpackDevServer from 'webpack-dev-server'
import webpackDevConfig from '../../webpack.config.dev'
const publicURL = url.parse(webpackDevConfig.output.publicPath)
new WebpackDevServer(webpack(webpackDevConfig), {
historyApiFallback: true,
hot: true,
noInfo: true,
publicPath: webpackDevConfig.output.publicPath,
stats: { colors: true },
quiet: true,
}).listen(publicURL.port, publicURL.hostname, function (err) {
if (err) { console.log(err) }
console.log(`Webpack development server listening on ${webpackDevConfig.output.publicPath}`)
})
| import url from 'url'
import webpack from 'webpack'
import WebpackDevServer from 'webpack-dev-server'
import webpackDevConfig from '../../webpack.config.dev'
const publicURL = url.parse(webpackDevConfig.output.publicPath)
new WebpackDevServer(webpack(webpackDevConfig), {
historyApiFallback: true,
hot: true,
noInfo: true,
publicPath: webpackDevConfig.output.publicPath,
stats: { colors: true },
quiet: true,
}).listen(publicURL.port, publicURL.hostname, function (err) {
if (err)
return console.error(err)
console.log(`Webpack development server listening on ${webpackDevConfig.output.publicPath}`)
})
| Improve error behaviour in webpack dev server boot | Improve error behaviour in webpack dev server boot
| JavaScript | agpl-3.0 | openfisca/legislation-explorer | ---
+++
@@ -16,6 +16,8 @@
stats: { colors: true },
quiet: true,
}).listen(publicURL.port, publicURL.hostname, function (err) {
- if (err) { console.log(err) }
+ if (err)
+ return console.error(err)
+
console.log(`Webpack development server listening on ${webpackDevConfig.output.publicPath}`)
}) |
81590311253a17958945b30786b4b30674ab6ca3 | src/common/InlineEventHandlerRewrite.js | src/common/InlineEventHandlerRewrite.js |
// Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
document.addEventListener('DOMContentLoaded', function(e) {
var selectors = ['load', 'click', 'mouseover', 'mouseout', 'keydown', 'keypress', 'keyup', 'blur', 'focus'];
for(var i = 0, l = selectors.length; i < l; i++) {
var els = document.querySelectorAll('[on' + selectors[i] + ']');
for(var j = 0, k = els.length; j < k; j++) {
var fn = new Function('e', els[j].getAttribute('on' + selectors[i]));
var target = els[j];
if(selectors[i] === 'load' && els[j] === document.body) {
target = window;
}
els[j].removeAttribute('on' + selectors[i]);
target.addEventListener(selectors[i], fn, true);
}
}
}, false);
|
opera.isReady(function() {
// Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
document.addEventListener('DOMContentLoaded', function(e) {
var selectors = ['load', 'beforeunload', 'unload', 'click', 'dblclick', 'mouseover', 'mousemove',
'mousedown', 'mouseup', 'mouseout', 'keydown', 'keypress', 'keyup', 'blur', 'focus'];
for(var i = 0, l = selectors.length; i < l; i++) {
var els = document.querySelectorAll('[on' + selectors[i] + ']');
for(var j = 0, k = els.length; j < k; j++) {
var fn = new Function('e', els[j].getAttribute('on' + selectors[i]));
var target = els[j];
if(selectors[i].indexOf('load') > -1 && els[j] === document.body) {
target = window;
}
els[j].removeAttribute('on' + selectors[i]);
target.addEventListener(selectors[i], fn, true);
}
}
}, false);
});
| Add a broader set of events for inline event handler rewrite function | Add a broader set of events for inline event handler rewrite function
| JavaScript | mit | operasoftware/operaextensions.js,operasoftware/operaextensions.js,operasoftware/operaextensions.js | ---
+++
@@ -1,22 +1,27 @@
-// Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
+opera.isReady(function() {
-document.addEventListener('DOMContentLoaded', function(e) {
+ // Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
+
+ document.addEventListener('DOMContentLoaded', function(e) {
- var selectors = ['load', 'click', 'mouseover', 'mouseout', 'keydown', 'keypress', 'keyup', 'blur', 'focus'];
+ var selectors = ['load', 'beforeunload', 'unload', 'click', 'dblclick', 'mouseover', 'mousemove',
+ 'mousedown', 'mouseup', 'mouseout', 'keydown', 'keypress', 'keyup', 'blur', 'focus'];
- for(var i = 0, l = selectors.length; i < l; i++) {
- var els = document.querySelectorAll('[on' + selectors[i] + ']');
- for(var j = 0, k = els.length; j < k; j++) {
- var fn = new Function('e', els[j].getAttribute('on' + selectors[i]));
- var target = els[j];
- if(selectors[i] === 'load' && els[j] === document.body) {
- target = window;
+ for(var i = 0, l = selectors.length; i < l; i++) {
+ var els = document.querySelectorAll('[on' + selectors[i] + ']');
+ for(var j = 0, k = els.length; j < k; j++) {
+ var fn = new Function('e', els[j].getAttribute('on' + selectors[i]));
+ var target = els[j];
+ if(selectors[i].indexOf('load') > -1 && els[j] === document.body) {
+ target = window;
+ }
+
+ els[j].removeAttribute('on' + selectors[i]);
+ target.addEventListener(selectors[i], fn, true);
}
-
- els[j].removeAttribute('on' + selectors[i]);
- target.addEventListener(selectors[i], fn, true);
}
- }
-}, false);
+ }, false);
+
+}); |
936c745c97fb1dc1f4fe11d0e0fcc0078815058d | public/index.js | public/index.js | (function ($, Vue, marked) {
/* eslint-disable no-console */
'use strict';
Vue.filter('marked', marked);
new Vue({
el: '#mail-form',
data: {
busy: false,
text: '',
domain: '',
password: '',
mail: {
from: '',
to: '',
subject: '',
text: ''
}
},
methods: {
send: function () {
var that = this;
this.busy = true;
$.post('/api/v1/' + this.domain + '/send', {
password: this.password,
from: this.mail.from,
to: this.mail.to,
subject: this.mail.subject,
text: this.mail.text
}).always(function (rep) {
console.log(arguments);
that.busy = false;
that.text = (rep && rep.responseJSON && rep.responseJSON.message || JSON.stringify(rep)) || 'no response';
});
}
}
});
/* eslint-enable no-console */
})(window.$, window.Vue, window.marked);
| (function ($, Vue, marked) {
/* eslint-disable no-console */
'use strict';
Vue.filter('marked', marked);
new Vue({
el: '#mail-form',
data: {
busy: false,
text: '',
domain: '',
password: '',
mail: {
from: '',
to: '',
subject: '',
text: ''
}
},
methods: {
send: function () {
var that = this;
this.busy = true;
this.text = 'sending...';
$.post('/api/v1/' + this.domain + '/send', {
password: this.password,
from: this.mail.from,
to: this.mail.to,
subject: this.mail.subject,
text: this.mail.text
}).always(function (rep) {
console.log(arguments);
that.busy = false;
that.text = (rep && rep.responseJSON && rep.responseJSON.message || JSON.stringify(rep)) || 'no response';
});
}
}
});
/* eslint-enable no-console */
})(window.$, window.Vue, window.marked);
| Remove last message after new sending | Remove last message after new sending
| JavaScript | mit | arrowrowe/mgu,arrowrowe/mgu | ---
+++
@@ -23,6 +23,7 @@
send: function () {
var that = this;
this.busy = true;
+ this.text = 'sending...';
$.post('/api/v1/' + this.domain + '/send', {
password: this.password,
from: this.mail.from, |
c7c7d4e33e19f5541d8e1e7ec5a06ba6cfb316ec | lib/plugins/body_parser.js | lib/plugins/body_parser.js | // Copyright 2012 Mark Cavage, Inc. All rights reserved.
var jsonParser = require('./json_body_parser');
var formParser = require('./form_body_parser');
var multipartParser = require('./multipart_parser');
function bodyParser(options) {
var parseForm = formParser(options);
var parseJson = jsonParser(options);
var parseMultipart = multipartParser(options);
return function parseBody(req, res, next) {
if (req.contentLength === 0 && !req.chunked)
return next();
if (req.contentType === 'application/json') {
return parseJson(req, res, next);
} else if (req.contentType === 'application/x-www-form-urlencoded') {
return parseForm(req, res, next);
} else if (req.contentType === 'multipart/form-data') {
return parseMultipart(req, res, next);
}
return next();
};
}
module.exports = bodyParser;
| // Copyright 2012 Mark Cavage, Inc. All rights reserved.
var jsonParser = require('./json_body_parser');
var formParser = require('./form_body_parser');
var multipartParser = require('./multipart_parser');
var errors = require('../errors');
var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError;
function bodyParser(options) {
var parseForm = formParser(options);
var parseJson = jsonParser(options);
var parseMultipart = multipartParser(options);
return function parseBody(req, res, next) {
if (req.contentLength === 0 && !req.chunked)
return next();
if (req.contentType === 'application/json') {
return parseJson(req, res, next);
} else if (req.contentType === 'application/x-www-form-urlencoded') {
return parseForm(req, res, next);
} else if (req.contentType === 'multipart/form-data') {
return parseMultipart(req, res, next);
} else {
return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' + req.contentType));
}
return next();
};
}
module.exports = bodyParser;
| Add http error 415 Unsupported Media Type | Add http error 415 Unsupported Media Type
| JavaScript | mit | prasmussen/node-restify,adunkman/node-restify,chaordic/node-restify,rborn/node-restify,kevinykchan/node-restify,TheDeveloper/node-restify,jclulow/node-restify,ferhatsb/node-restify,sstur/node-restify,uWhisp/node-restify,msaffitz/node-restify | ---
+++
@@ -3,6 +3,10 @@
var jsonParser = require('./json_body_parser');
var formParser = require('./form_body_parser');
var multipartParser = require('./multipart_parser');
+
+var errors = require('../errors');
+
+var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError;
function bodyParser(options) {
@@ -21,6 +25,8 @@
return parseForm(req, res, next);
} else if (req.contentType === 'multipart/form-data') {
return parseMultipart(req, res, next);
+ } else {
+ return next(new UnsupportedMediaTypeError('Unsupported Content-Type: ' + req.contentType));
}
return next(); |
daaae39dc66738b17b34bf1e2e0a000902ddb46f | linux/registerMediaKeys.js | linux/registerMediaKeys.js | const DBus = require('dbus');
function executeMediaKey(win, key) {
win.webContents.executeJavaScript(`
window.electronConnector.emit('${key}')
`);
}
function registerBindings(win, desktopEnv, bus) {
const serviceName = `org.${desktopEnv}.SettingsDaemon`;
const objectPath = `/org/${desktopEnv}/SettingsDaemon/MediaKeys`;
const interfaceName = `org.${desktopEnv}.SettingsDaemon.MediaKeys`;
bus.getInterface(serviceName, objectPath, interfaceName, (err, iface) => {
if (err) {
// dbus is showing "Error: No introspectable" that doesn't affect the code
return;
}
iface.on('MediaPlayerKeyPressed', (n, keyName) => {
switch (keyName) {
case 'Next':
executeMediaKey(win, 'play-next');
break;
case 'Previous':
executeMediaKey(win, 'play-previous');
break;
case 'Play':
executeMediaKey(win, 'play-pause');
break;
default:
}
});
iface.GrabMediaPlayerKeys(0, interfaceName);
});
}
module.exports = (win) => {
const dbus = new DBus();
const bus = dbus.getBus('session');
registerBindings(win, 'gnome', bus);
registerBindings(win, 'mate', bus);
};
| const DBus = require('dbus');
const { ipcMain } = require('electron');
let status = 'Stopped';
ipcMain.on('win2Player', (e, args) => {
if (args[0] === 'playVideo') {
status = 'Playing';
}
});
function executeMediaKey(win, key) {
win.webContents.executeJavaScript(`
window.electronConnector.emit('${key}')
`);
}
function registerBindings(win, desktopEnv, bus) {
const serviceName = `org.${desktopEnv}.SettingsDaemon`;
const objectPath = `/org/${desktopEnv}/SettingsDaemon/MediaKeys`;
const interfaceName = `org.${desktopEnv}.SettingsDaemon.MediaKeys`;
bus.getInterface(serviceName, objectPath, interfaceName, (err, iface) => {
if (err) {
// dbus is showing "Error: No introspectable" that doesn't affect the code
return;
}
iface.on('MediaPlayerKeyPressed', (n, keyName) => {
switch (keyName) {
case 'Next':
executeMediaKey(win, 'play-next');
break;
case 'Previous':
executeMediaKey(win, 'play-previous');
break;
case 'Play':
if (status !== 'Stopped') {
executeMediaKey(win, 'play-pause');
}
break;
default:
}
});
iface.GrabMediaPlayerKeys(0, interfaceName);
});
}
module.exports = (win) => {
const dbus = new DBus();
const bus = dbus.getBus('session');
registerBindings(win, 'gnome', bus);
registerBindings(win, 'mate', bus);
};
| Fix segmentation fault on linux | Fix segmentation fault on linux
| JavaScript | mit | fcastilloec/headset-electron,fcastilloec/headset-electron,headsetapp/headset-electron,headsetapp/headset-electron,headsetapp/headset-electron,fcastilloec/headset-electron | ---
+++
@@ -1,4 +1,13 @@
const DBus = require('dbus');
+const { ipcMain } = require('electron');
+
+let status = 'Stopped';
+
+ipcMain.on('win2Player', (e, args) => {
+ if (args[0] === 'playVideo') {
+ status = 'Playing';
+ }
+});
function executeMediaKey(win, key) {
win.webContents.executeJavaScript(`
@@ -25,7 +34,9 @@
executeMediaKey(win, 'play-previous');
break;
case 'Play':
- executeMediaKey(win, 'play-pause');
+ if (status !== 'Stopped') {
+ executeMediaKey(win, 'play-pause');
+ }
break;
default:
} |
c02df73d3f827cba39a285bb440959f8e0c518e1 | makeExportsHot.js | makeExportsHot.js | 'use strict';
var isReactClassish = require('./isReactClassish'),
isReactElementish = require('./isReactElementish');
function makeExportsHot(m) {
if (isReactElementish(m.exports)) {
return false;
}
var freshExports = m.exports,
foundReactClasses = false;
if (isReactClassish(m.exports)) {
m.exports = m.makeHot(m.exports, '__MODULE_EXPORTS');
foundReactClasses = true;
}
for (var key in m.exports) {
if (freshExports.hasOwnProperty(key) &&
isReactClassish(freshExports[key])) {
if (Object.getOwnPropertyDescriptor(m.exports, key).writable) {
m.exports[key] = m.makeHot(freshExports[key], '__MODULE_EXPORTS_' + key);
foundReactClasses = true;
} else {
console.warn("Can't make class " + key + " hot reloadable due to being read-only. You can exclude files or directories (for example, /node_modules/) using 'exclude' option in loader configuration.");
}
}
}
return foundReactClasses;
}
module.exports = makeExportsHot;
| 'use strict';
var isReactClassish = require('./isReactClassish'),
isReactElementish = require('./isReactElementish');
function makeExportsHot(m) {
if (isReactElementish(m.exports)) {
return false;
}
var freshExports = m.exports,
foundReactClasses = false;
if (isReactClassish(m.exports)) {
m.exports = m.makeHot(m.exports, '__MODULE_EXPORTS');
foundReactClasses = true;
}
for (var key in m.exports) {
if (Object.prototype.hasOwnProperty.call(freshExports, key) &&
isReactClassish(freshExports[key])) {
if (Object.getOwnPropertyDescriptor(m.exports, key).writable) {
m.exports[key] = m.makeHot(freshExports[key], '__MODULE_EXPORTS_' + key);
foundReactClasses = true;
} else {
console.warn("Can't make class " + key + " hot reloadable due to being read-only. You can exclude files or directories (for example, /node_modules/) using 'exclude' option in loader configuration.");
}
}
}
return foundReactClasses;
}
module.exports = makeExportsHot;
| Fix for modules with null [[Prototype]] chain | Fix for modules with null [[Prototype]] chain
A module created in the following ways:
module.exports = Object.create(null)
module.exports = { __proto__: null }
won't have hasOwnProperty() available on it.
So it’s safer to use Object.prototype.hasOwnProperty.call(myObj, prop)
instead of myObj.hasOwnProperty(prop)
| JavaScript | mit | gaearon/react-hot-loader,gaearon/react-hot-loader | ---
+++
@@ -17,7 +17,7 @@
}
for (var key in m.exports) {
- if (freshExports.hasOwnProperty(key) &&
+ if (Object.prototype.hasOwnProperty.call(freshExports, key) &&
isReactClassish(freshExports[key])) {
if (Object.getOwnPropertyDescriptor(m.exports, key).writable) {
m.exports[key] = m.makeHot(freshExports[key], '__MODULE_EXPORTS_' + key); |
5fcfceb88f9982ad41d5877f83bd9a6287170b21 | templates/frontend/module.js | templates/frontend/module.js | /**
* @file Instantiates and configures angular modules for your module.
*/
define(['angular'], function (ng) {
'use strict';
ng.module('{{template_name}}.controllers', []);
ng.module('{{template_name}}.providers', []);
ng.module('{{template_name}}.services', []);
ng.module('{{template_name}}.factories', []);
ng.module('{{template_name}}.directives', []);
var module = ng.module('{{template_name}}', [
'cs_common',
'{{template_name}}.controllers',
'{{template_name}}.providers',
'{{template_name}}.services',
'{{template_name}}.factories',
'{{template_name}}.directives'
]);
module.config([
'$routeProvider',
'CSTemplateProvider',
function ($routeProvider, CSTemplate) {
// Set the subfolder of your module that contains all your view templates.
CSTemplate.setPath('/modules/{{template_name}}/views');
// Register any routes you need for your module.
$routeProvider
.when('/example', {
templateUrl: CSTemplate.view('{{Template}}-view'),
controller: '{{Template}}ExampleController',
public: true
});
}
]);
return module;
});
| /**
* @file Instantiates and configures angular modules for your module.
*/
define(['angular'], function (ng) {
'use strict';
ng.module('{{template_name}}.controllers', []);
ng.module('{{template_name}}.providers', []);
ng.module('{{template_name}}.services', []);
ng.module('{{template_name}}.factories', []);
ng.module('{{template_name}}.directives', []);
var module = ng.module('{{template_name}}', [
'cs_common',
'{{template_name}}.controllers',
'{{template_name}}.providers',
'{{template_name}}.services',
'{{template_name}}.factories',
'{{template_name}}.directives'
]);
module.config([
'$routeProvider',
'CSTemplateProvider',
function ($routeProvider, CSTemplate) {
// Set the subfolder of your module that contains all your view templates.
CSTemplate.setPath('/modules/{{template_name}}/views');
// Register any routes you need for your module.
$routeProvider
.when('/example', {
templateUrl: CSTemplate.view('{{Template}}-view'),
controller: '{{Template}}Controller',
public: true
});
}
]);
return module;
});
| Set a correct controller name | Set a correct controller name
| JavaScript | mit | CleverStack/cleverstack-cli,CleverStack/cleverstack-cli,GrimDerp/cleverstack-cli,GrimDerp/cleverstack-cli | ---
+++
@@ -31,7 +31,7 @@
$routeProvider
.when('/example', {
templateUrl: CSTemplate.view('{{Template}}-view'),
- controller: '{{Template}}ExampleController',
+ controller: '{{Template}}Controller',
public: true
});
} |
9277c60a9f248949b3784f80b0aa62ba7bdf8546 | src/js/effects/translateFromPosition.js | src/js/effects/translateFromPosition.js | import { SplashEffect } from "./effect.js";
import { Linear } from "../interpolation.js";
export class TranslateFromPosition extends SplashEffect {
constructor(element, options) {
super(element);
options = options || {};
this.x = options.x || 0;
this.y = options.y || 0;
this.interpolation = options.interpolation || new Linear();
}
in(value) {
let x = this.interpolation.in(value * -1 + 1) * this.x,
y = this.interpolation.in(value * -1 + 1) * this.y;
this.setStyle("left", x + "px");
this.setStyle("top", y + "px");
}
out(value) {
let x = this.interpolation.out(value) * this.x,
y = this.interpolation.out(value) * this.y;
this.setStyle("left", x + "px");
this.setStyle("top", y + "px");
}
}
| import { SplashEffect } from "./effect.js";
import { Linear } from "../interpolation.js";
export class TranslateFromPosition extends SplashEffect {
constructor(element, options) {
super(element);
options = options || {};
this.x = options.x || 0;
this.y = options.y || 0;
// Can be whatever, but the effect won't do
// anything if it isn't a valid css unit.
this.unit = options.unit || "px";
// Can be either "transform" or "position"
this.translationType = options.translationType || "transform";
this.interpolation = options.interpolation || new Linear();
}
in(value) {
this._set(
this.interpolation.in(value * -1 + 1) * this.x,
this.interpolation.in(value * -1 + 1) * this.y
);
}
out(value) {
this._set(
this.interpolation.out(value) * this.x,
this.interpolation.out(value) * this.y
);
}
_set(x, y) {
if (this.translationType = "transform") {
this.setTransform("translateX", x + this.unit);
this.setTransform("translateY", y + this.unit);
} else if (this.translationType = "position") {
this.setStyle("left", x + this.unit);
this.setStyle("top", y + this.unit);
} else {
console.error("Unknown translation type: " + this.translationType);
}
}
}
| Add units and different translation types to translate from position effect | Add units and different translation types to translate from position effect
| JavaScript | mit | magnontobi/splasher.js | ---
+++
@@ -10,20 +10,38 @@
this.x = options.x || 0;
this.y = options.y || 0;
+ // Can be whatever, but the effect won't do
+ // anything if it isn't a valid css unit.
+ this.unit = options.unit || "px";
+ // Can be either "transform" or "position"
+ this.translationType = options.translationType || "transform";
+
this.interpolation = options.interpolation || new Linear();
}
in(value) {
- let x = this.interpolation.in(value * -1 + 1) * this.x,
- y = this.interpolation.in(value * -1 + 1) * this.y;
- this.setStyle("left", x + "px");
- this.setStyle("top", y + "px");
+ this._set(
+ this.interpolation.in(value * -1 + 1) * this.x,
+ this.interpolation.in(value * -1 + 1) * this.y
+ );
}
out(value) {
- let x = this.interpolation.out(value) * this.x,
- y = this.interpolation.out(value) * this.y;
- this.setStyle("left", x + "px");
- this.setStyle("top", y + "px");
+ this._set(
+ this.interpolation.out(value) * this.x,
+ this.interpolation.out(value) * this.y
+ );
+ }
+
+ _set(x, y) {
+ if (this.translationType = "transform") {
+ this.setTransform("translateX", x + this.unit);
+ this.setTransform("translateY", y + this.unit);
+ } else if (this.translationType = "position") {
+ this.setStyle("left", x + this.unit);
+ this.setStyle("top", y + this.unit);
+ } else {
+ console.error("Unknown translation type: " + this.translationType);
+ }
}
} |
6fa17eb4e984c6a05a0eca6d0b41400b5926ff1a | test/rjsconfig.js | test/rjsconfig.js | var require = {
paths: {
"power-assert": "../build/power-assert",
expect: "../bower_components/expect/index",
"power-assert-formatter": "../bower_components/power-assert-formatter/lib/power-assert-formatter",
"qunit-tap": "../bower_components/qunit-tap/lib/qunit-tap",
qunit: "../bower_components/qunit/qunit/qunit",
mocha: "../bower_components/mocha/mocha",
empower: "../bower_components/empower/lib/empower",
esprima: "../bower_components/esprima/esprima",
requirejs: "../bower_components/requirejs/require"
},
shim: {
"power-assert": {
exports: "assert"
},
expect: {
exports: "expect"
}
}
};
| var require = {
paths: {
"power-assert": "../build/power-assert",
expect: "../bower_components/expect/index",
mocha: "../bower_components/mocha/mocha",
requirejs: "../bower_components/requirejs/require"
},
shim: {
"power-assert": {
exports: "assert"
},
expect: {
exports: "expect"
}
}
};
| Remove unused dependencies from AMD testing. | Remove unused dependencies from AMD testing.
| JavaScript | mit | twada/power-assert,falsandtru/power-assert,falsandtru/power-assert,saneyuki/power-assert,power-assert-js/power-assert,twada/power-assert,yagitoshiro/power-assert,power-assert-js/power-assert,saneyuki/power-assert,yagitoshiro/power-assert | ---
+++
@@ -2,12 +2,7 @@
paths: {
"power-assert": "../build/power-assert",
expect: "../bower_components/expect/index",
- "power-assert-formatter": "../bower_components/power-assert-formatter/lib/power-assert-formatter",
- "qunit-tap": "../bower_components/qunit-tap/lib/qunit-tap",
- qunit: "../bower_components/qunit/qunit/qunit",
mocha: "../bower_components/mocha/mocha",
- empower: "../bower_components/empower/lib/empower",
- esprima: "../bower_components/esprima/esprima",
requirejs: "../bower_components/requirejs/require"
},
shim: { |
bbdb9c6dda6ed5a7d815a64d97299dee6821d172 | src/ContentBlocks/BlockButton/BlockButton.js | src/ContentBlocks/BlockButton/BlockButton.js | /* @flow */
import React from 'react';
import Button from 'grommet/components/Button';
import Anchor from 'grommet/components/Anchor';
import type { AssetType, ButtonType } from './BlockButtonForm';
export type Props = {
label?: string,
path?: string,
href?: string,
assetType?: AssetType,
buttonType?: ButtonType,
primary?: boolean,
}
export default function BlockButton({
buttonType,
href,
path,
label,
primary,
assetType,
}: Props) {
const isPrimary = primary === 'True';
let props = { label, primary: isPrimary, target: '_blank' };
if (assetType === 'path' && path && path.indexOf('.') < 0) {
props = { ...props, path };
} else if (assetType === 'path' && path && path.indexOf('.') > -1) {
props = { ...props, href: path };
} else {
props = { ...props, href };
}
if (buttonType === 'Button') {
return (
<Button {...props} />
);
} else if (buttonType === 'Anchor') {
return (
<Anchor {...props} />
);
}
}
| /* @flow */
import React from 'react';
import Button from 'grommet/components/Button';
import Anchor from 'grommet/components/Anchor';
import type { AssetType, ButtonType } from './BlockButtonForm';
export type Props = {
label?: string,
path?: string,
href?: string,
assetType?: AssetType,
buttonType?: ButtonType,
primary?: boolean,
}
export default function BlockButton({
buttonType,
href,
path,
label,
primary,
assetType,
}: Props) {
const isPrimary = primary === 'True';
let props = { label, primary: isPrimary, target: '_blank' };
if (assetType === 'path' && path && path.indexOf('.') < 0) {
props = { ...props, path };
} else if (assetType === 'path' && path && path.indexOf('.') > -1) {
props = { ...props, href: path, target: '_blank' };
} else {
props = { ...props, href };
}
if (buttonType === 'Button') {
return (
<Button {...props} />
);
} else if (buttonType === 'Anchor') {
return (
<Anchor {...props} />
);
}
}
| Fix button block new tab bug. | Fix button block new tab bug.
| JavaScript | apache-2.0 | grommet/grommet-cms-content-blocks,grommet/grommet-cms-content-blocks | ---
+++
@@ -25,7 +25,7 @@
if (assetType === 'path' && path && path.indexOf('.') < 0) {
props = { ...props, path };
} else if (assetType === 'path' && path && path.indexOf('.') > -1) {
- props = { ...props, href: path };
+ props = { ...props, href: path, target: '_blank' };
} else {
props = { ...props, href };
} |
fb6c208e08e15575afce3c0eb1c622e45fd2796e | test/models/memory_stats_test.js | test/models/memory_stats_test.js | 'use strict';
var MemoryStats = require('../../lib/models/memory_stats')
, SQliteAdapter = require('../../lib/models/sqlite_adapter')
, chai = require('chai')
, expect = chai.expect
, chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
describe('MemoryStats', function() {
describe('.constructor', function() {
it('returns an instantiated memory stats and its schema attributes', function() {
expect(MemoryStats().schemaAttrs).to.include.members(['container_name', 'timestamp_day']);
});
it('returns an instantiated memory stats and its table name', function() {
expect(MemoryStats().tableName).to.eql('memory_stats');
});
});
after(function() {
return SQliteAdapter.deleteDB()
.then(null)
.catch(function(err) {
console.log(err.stack);
});
});
});
| 'use strict';
var MemoryStats = require('../../src/models/memory_stats')
, SQliteAdapter = require('../../src/models/sqlite_adapter')
, chai = require('chai')
, expect = chai.expect
, chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
describe('MemoryStats', function() {
describe('.constructor', function() {
it('returns an instantiated memory stats and its schema attributes', function() {
expect(MemoryStats().schemaAttrs).to.include.members(['container_name', 'timestamp_day']);
});
it('returns an instantiated memory stats and its table name', function() {
expect(MemoryStats().tableName).to.eql('memory_stats');
});
});
after(function() {
return SQliteAdapter.deleteDB()
.then(null)
.catch(function(err) {
console.log(err.stack);
});
});
});
| Fix directory path memory stats test | Fix directory path memory stats test
| JavaScript | mit | davidcunha/wharf,davidcunha/wharf | ---
+++
@@ -1,7 +1,7 @@
'use strict';
-var MemoryStats = require('../../lib/models/memory_stats')
- , SQliteAdapter = require('../../lib/models/sqlite_adapter')
+var MemoryStats = require('../../src/models/memory_stats')
+ , SQliteAdapter = require('../../src/models/sqlite_adapter')
, chai = require('chai')
, expect = chai.expect
, chaiAsPromised = require('chai-as-promised'); |
e422a6327ec552e409717f994110b4d132235ae4 | test/dummy/app/assets/javascripts/application.js | test/dummy/app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require bitcharts/application
//= require_tree .
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require bitcharts/full
//= require_tree .
| Fix JS-Include in dummy app | Fix JS-Include in dummy app
| JavaScript | mit | Lichtbit/bitcharts,Lichtbit/bitcharts,Lichtbit/bitcharts | ---
+++
@@ -10,5 +10,5 @@
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
-//= require bitcharts/application
+//= require bitcharts/full
//= require_tree . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.