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 |
|---|---|---|---|---|---|---|---|---|---|---|
aa1677defe0e68126efb362a1184310b5cd5cb93 | lib/util/wrap.js | lib/util/wrap.js | /*
var args = ['jar', 'username', 'password']
raw function login (jar, username, password)
exported function login ()
check number of arguments if necessary
options object: login(arguments[0])
individual arguments:
for each argument add to an options array corresponding with argument order
login(options)
*/
// Includes
var options = require('../options.js');
// Define
var defaults = {
'jar': options.jar
};
function appendDefaults (opt, argumentList) {
for (var index in defaults) {
if (!opt[index] && argumentList.indexOf(index) > -1) {
opt[index] = defaults[index];
}
}
return opt;
}
exports.wrapExport = function (wrapFunction, argumentList) {
if (argumentList.length > 0) {
return function () {
var options = {};
if (arguments.length > 0) {
if (typeof arguments[0] === 'object') {
options = arguments[0];
} else {
for (var i = 0; i <= arguments.length; i++) {
options[argumentList[i]] = arguments[i];
}
}
}
return wrapFunction(options);
};
} else {
return wrapFunction;
}
};
| /*
var args = ['jar', 'username', 'password']
raw function login (jar, username, password)
exported function login ()
check number of arguments if necessary
options object: login(arguments[0])
individual arguments:
for each argument add to an options array corresponding with argument order
login(options)
*/
// Includes
var options = require('../options.js');
// Define
var defaults = {
'jar': options.jar
};
function appendDefaults (opt, argumentList) {
for (var index in defaults) {
if (!opt[index] && argumentList.indexOf(index) > -1) {
opt[index] = defaults[index];
}
}
return opt;
}
exports.wrapExport = function (wrapFunction, argumentList) {
if (argumentList.length > 0) {
return function () {
var options = {};
if (arguments.length > 0) {
var first = arguments[0];
if (arguments.length === 1 && (argumentList.length !== 1 || (first instanceof Object && first[argumentList[0]]))) {
options = first;
} else {
for (var i = 0; i <= arguments.length; i++) {
options[argumentList[i]] = arguments[i];
}
}
}
return wrapFunction(options);
};
} else {
return wrapFunction;
}
};
| Fix for multiple usage types | Fix for multiple usage types
Argument list/Actual parameters
| JavaScript | mit | sentanos/roblox-js,FroastJ/roblox-js,OnlyTwentyCharacters/roblox-js | ---
+++
@@ -32,8 +32,9 @@
return function () {
var options = {};
if (arguments.length > 0) {
- if (typeof arguments[0] === 'object') {
- options = arguments[0];
+ var first = arguments[0];
+ if (arguments.length === 1 && (argumentList.length !== 1 || (first instanceof Object && first[argumentList[0]]))) {
+ options = first;
} else {
for (var i = 0; i <= arguments.length; i++) {
options[argumentList[i]] = arguments[i]; |
079e9063578db0363413deba7314a74238025873 | src/AppBundle/Resources/js/userCard.js | src/AppBundle/Resources/js/userCard.js | $(document).ready(function () {
//var route = Routing.generate('seen_userCardication', { id: {{ userCard.id }} });
var $content = $('.userCardContent');
var array = {};
$('.userCardBlock').hide();
$('.userCardButton').click(function(){
$('.userCardBlock').toggle("ease-in");
});
});
| $(document).ready(function () {
//var route = Routing.generate('seen_userCardication', { id: {{ userCard.id }} });
var $content = $('.userCardContent');
var array = {};
$('.userCardBlock').hide();
$('.userCardButton').click(function(e){
e.preventDefault();
$('.userCardBlock').toggle("ease-in");
});
});
| Fix bug from previous merge conflict | Fix bug from previous merge conflict
| JavaScript | unlicense | ariescdi/documentio,ariescdi/documentio | ---
+++
@@ -6,7 +6,8 @@
$('.userCardBlock').hide();
- $('.userCardButton').click(function(){
+ $('.userCardButton').click(function(e){
+ e.preventDefault();
$('.userCardBlock').toggle("ease-in");
});
|
0ee36fe6aa1911214d87bb5ca85f34a62f150580 | frontend/test/unit/specs/Hello.spec.js | frontend/test/unit/specs/Hello.spec.js | // import Vue from 'vue'
// import Hello from '@/components/Hello'
describe('this test runner', () => {
it('needs at least one test', () => {
expect(true).to.equal(true)
})
})
// describe('Hello.vue', () => {
// it('should render correct contents', () => {
// const Constructor = Vue.extend(Hello)
// const vm = new Constructor().$mount()
// expect(vm.$el.querySelector('.hello h1').textContent)
// .to.equal('Welcome to Your Vue.js App')
// })
// })
| describe('this test runner', () => {
it('needs at least one test', () => {
expect(true).to.equal(true)
})
})
| Remove comments in test file | Remove comments in test file
| JavaScript | mit | code-for-nashville/parcel,code-for-nashville/parcel,code-for-nashville/parcel | ---
+++
@@ -1,17 +1,5 @@
-// import Vue from 'vue'
-// import Hello from '@/components/Hello'
-
describe('this test runner', () => {
it('needs at least one test', () => {
expect(true).to.equal(true)
})
})
-
-// describe('Hello.vue', () => {
- // it('should render correct contents', () => {
- // const Constructor = Vue.extend(Hello)
- // const vm = new Constructor().$mount()
- // expect(vm.$el.querySelector('.hello h1').textContent)
- // .to.equal('Welcome to Your Vue.js App')
- // })
-// }) |
a72154e507b42bcd12feaabbea9602eb6c64d1a4 | src/configure/webpack/plugins/images.js | src/configure/webpack/plugins/images.js | export default {
name: 'webpack-images',
configure () {
return {
module: {
loaders: [
{
test: /\.(png|jpg|gif)$/,
loader: 'url-loader?limit=8192&name=[name]-[hash].[ext]'
}
]
}
}
}
}
| export default {
name: 'webpack-images',
configure () {
return {
module: {
loaders: [
{
test: /\.(png|jpg|jpeg|gif)$/,
loader: 'url-loader?limit=8192&name=[name]-[hash].[ext]'
}
]
}
}
}
}
| Add jpeg file extension loading support | Add jpeg file extension loading support | JavaScript | mit | saguijs/sagui,saguijs/sagui | ---
+++
@@ -5,7 +5,7 @@
module: {
loaders: [
{
- test: /\.(png|jpg|gif)$/,
+ test: /\.(png|jpg|jpeg|gif)$/,
loader: 'url-loader?limit=8192&name=[name]-[hash].[ext]'
}
] |
aa968b2abf4171ea0b07a6a543d4c5631024346e | runcheerp.js | runcheerp.js | /*
* Run the code contained in the file manager, by compiling everything and
* executing the main class, then display the result.
*/
/* global FileManager */
function runCodeCheerp() {
// Get the main class's actual name..
// drop the .java extension
var mainFile = FileManager.getMainFile().name;
var mainName = mainFile.replace(/\.[^/.]+$/, "");
// Get the file's package name
var pkgReg = /package\s+([\w\.]+)\s*;/;
var packageName = pkgReg.exec(FileManager.getMainFile().contents);
// Add the package name to the class's name
if (packageName === null || packageName.length < 2) {
packageName = ["package", "default"];
}
// Prepare the request to run the code
// Set up the request body for a compile-run request
var body = {
version: 1,
compile: {
version: 1,
mainClass: packageName[1] + "." + mainName,
mainFile: mainFile,
sourceFiles: []
},
data: {
version: 1,
dataFiles: []
},
"test-type": "run"
};
var root = FileManager.getRootFolder();
// Add the files in the global file manager to the request body.
addAllSourceFiles(root, body.compile.sourceFiles, true);
// Add data files to the request
addAllDataFiles(root, body.data.dataFiles);
let newWindow = window.open('./cheerpjConsole.html');
newWindow.compileData = body;
} | /*
* Run the code contained in the file manager, by compiling everything and
* executing the main class, then display the result.
*/
/* global FileManager */
function runCodeCheerp() {
// Get the main class's actual name..
// drop the .java extension
var mainName = FileManager.getMainFile().name.replace(/\.[^/.]+$/, "");
// Get the file's package name
var pkgReg = /package\s+([\w\.]+)\s*;/;
var packageName = pkgReg.exec(FileManager.getMainFile().contents);
// Add the package name to the class's name
if (packageName === null || packageName.length < 2) {
packageName = ["package", "default"];
}
// Prepare the request to run the code
// Set up the request body for a compile-run request
var body = {
version: 1,
compile: {
version: 1,
mainClass: packageName[1] + "." + mainName,
mainFile: mainName,
sourceFiles: []
},
data: {
version: 1,
dataFiles: []
},
"test-type": "run"
};
var root = FileManager.getRootFolder();
// Add the files in the global file manager to the request body.
addAllSourceFiles(root, body.compile.sourceFiles, true);
// Add data files to the request
addAllDataFiles(root, body.data.dataFiles);
let newWindow = window.open('./cheerpjConsole.html');
newWindow.compileData = body;
} | Revert "keep .java on mainFile" | Revert "keep .java on mainFile"
| JavaScript | mit | mrbdahlem/MyCode.run,mrbdahlem/MyCode.run | ---
+++
@@ -7,9 +7,7 @@
function runCodeCheerp() {
// Get the main class's actual name..
// drop the .java extension
- var mainFile = FileManager.getMainFile().name;
- var mainName = mainFile.replace(/\.[^/.]+$/, "");
-
+ var mainName = FileManager.getMainFile().name.replace(/\.[^/.]+$/, "");
// Get the file's package name
var pkgReg = /package\s+([\w\.]+)\s*;/;
var packageName = pkgReg.exec(FileManager.getMainFile().contents);
@@ -25,7 +23,7 @@
compile: {
version: 1,
mainClass: packageName[1] + "." + mainName,
- mainFile: mainFile,
+ mainFile: mainName,
sourceFiles: []
},
data: { |
40d0ad7a897cff8ff1aa60a22f74ee120e9f4bc6 | src/answer_generators/mdbg/generator.js | src/answer_generators/mdbg/generator.js | function generateResults
(
recognitionResults,
q,
context
)
{
var resultList = recognitionResults['com.solveforall.recognition.lang.chinese.Chinese'];
if (!resultList)
{
return null;
}
return [{
label: 'MDBG',
uri: 'http://www.mdbg.net/chindict/mobile.php?mwddw=' + resultList[0].traditional + '&handler=DecomposeWord',
iconUrl: 'http://www.mdbg.net/favicon.ico'
}];
}
| /*jslint continue: true, devel: true, evil: true, indent: 2, plusplus: true, rhino: true, unparam: true, vars: true, white: true */
function generateResults(recognitionResults, q, context) {
'use strict';
var resultList = recognitionResults['com.solveforall.recognition.lang.chinese.Chinese'];
if (!resultList) {
return null;
}
var word = resultList[0].traditional;
return [{
label: 'MDBG',
iconUrl: 'http://www.mdbg.net/favicon.ico',
uri: 'http://www.mdbg.net/chindict/mobile.php?mwddw=' + encodeURIComponent(word) + '&handler=DecomposeWord',
embeddable: true,
summaryHtml: 'Lookup ' + _(word).escapeHTML() + ' on MDBG'
}];
}
| Add summaryHtml and embeddable: true flag to MDBG Answer Generator | Add summaryHtml and embeddable: true flag to MDBG Answer Generator
| JavaScript | apache-2.0 | jtsay362/solveforall-example-plugins,jtsay362/solveforall-example-plugins | ---
+++
@@ -1,21 +1,20 @@
-function generateResults
-(
- recognitionResults,
- q,
- context
-)
-{
+/*jslint continue: true, devel: true, evil: true, indent: 2, plusplus: true, rhino: true, unparam: true, vars: true, white: true */
+function generateResults(recognitionResults, q, context) {
+ 'use strict';
+
var resultList = recognitionResults['com.solveforall.recognition.lang.chinese.Chinese'];
- if (!resultList)
- {
+ if (!resultList) {
return null;
}
+ var word = resultList[0].traditional;
return [{
label: 'MDBG',
- uri: 'http://www.mdbg.net/chindict/mobile.php?mwddw=' + resultList[0].traditional + '&handler=DecomposeWord',
- iconUrl: 'http://www.mdbg.net/favicon.ico'
+ iconUrl: 'http://www.mdbg.net/favicon.ico',
+ uri: 'http://www.mdbg.net/chindict/mobile.php?mwddw=' + encodeURIComponent(word) + '&handler=DecomposeWord',
+ embeddable: true,
+ summaryHtml: 'Lookup ' + _(word).escapeHTML() + ' on MDBG'
}];
}
|
4ee5af4f741025379c648461f40f3943251dbd84 | migrations/20150824191630-add-users.js | migrations/20150824191630-add-users.js | var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.createTable('users', {
id: {
type: 'int',
primaryKey: true,
unsigned: true,
notNull: true,
autoIncrement: true,
length: 10
},
username: {
type: 'string',
unique: true,
notNull: true
},
password: {
type: 'string',
notNull: true
}
}, callback);
};
exports.down = function(db, callback) {
db.dropTable('users', callback);
};
| var dbm = global.dbm || require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.createTable('users', {
id: {
type: 'int',
primaryKey: true,
unsigned: true,
notNull: true,
autoIncrement: true
},
username: {
type: 'string',
unique: true,
notNull: true
},
password: {
type: 'string',
notNull: true
}
}, callback);
};
exports.down = function(db, callback) {
db.dropTable('users', callback);
};
| Fix to the users migration. | Fix to the users migration.
| JavaScript | mit | meddle0x53/react-koa-gulp-postgres-passport-example,meddle0x53/react-webpack-koa-postgres-passport-example,meddle0x53/react-webpack-koa-postgres-passport-example,meddle0x53/react-koa-gulp-postgres-passport-example | ---
+++
@@ -8,17 +8,16 @@
primaryKey: true,
unsigned: true,
notNull: true,
- autoIncrement: true,
- length: 10
+ autoIncrement: true
},
username: {
type: 'string',
unique: true,
- notNull: true
+ notNull: true
},
password: {
type: 'string',
- notNull: true
+ notNull: true
}
}, callback);
}; |
ac8c692c45e343eda9a576fb40f29317be92bf52 | src/common/config/defaultPreferences.js | src/common/config/defaultPreferences.js | // Copyright (c) 2015-2016 Yuya Ochiai
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
/**
* Default user preferences. End-users can change these parameters by editing config.json
* @param {number} version - Scheme version. (Not application version)
*/
const defaultPreferences = {
version: 1,
teams: [],
showTrayIcon: false,
trayIconTheme: 'light',
minimizeToTray: false,
notifications: {
flashWindow: 0,
bounceIcon: false,
bounceIconType: 'informational',
},
showUnreadBadge: true,
useSpellChecker: true,
enableHardwareAcceleration: true,
autostart: false,
};
export default defaultPreferences;
| // Copyright (c) 2015-2016 Yuya Ochiai
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
/**
* Default user preferences. End-users can change these parameters by editing config.json
* @param {number} version - Scheme version. (Not application version)
*/
const defaultPreferences = {
version: 1,
teams: [],
showTrayIcon: false,
trayIconTheme: 'light',
minimizeToTray: false,
notifications: {
flashWindow: 0,
bounceIcon: false,
bounceIconType: 'informational',
},
showUnreadBadge: true,
useSpellChecker: true,
enableHardwareAcceleration: true,
autostart: true,
};
export default defaultPreferences;
| Set "app start on login" preference to default on | Set "app start on login" preference to default on
| JavaScript | apache-2.0 | mattermost/desktop,yuya-oc/electron-mattermost,yuya-oc/electron-mattermost,mattermost/desktop,yuya-oc/electron-mattermost,mattermost/desktop,mattermost/desktop,yuya-oc/desktop,yuya-oc/desktop,mattermost/desktop,yuya-oc/desktop | ---
+++
@@ -20,7 +20,7 @@
showUnreadBadge: true,
useSpellChecker: true,
enableHardwareAcceleration: true,
- autostart: false,
+ autostart: true,
};
export default defaultPreferences; |
c0e375921363a2581a5b3819078e01fe172b560d | src/js/components/NewPageHeaderTabs.js | src/js/components/NewPageHeaderTabs.js | import classNames from 'classnames/dedupe';
import {Link} from 'react-router';
import React from 'react';
class PageHeaderTabs extends React.Component {
render() {
let {props: {tabs}} = this;
let tabElements = tabs.map(function (tab, index) {
let {isActive} = tab;
let classes = classNames('tab-item', {active: isActive});
let linkClasses = classNames('tab-item-label', {active: isActive});
return (
<li className={classes} key={index}>
<Link className={linkClasses} to={tab.routePath}>
<span className="tab-item-label-text">
{tab.label}
</span>
</Link>
</li>
);
});
return (
<ul className="menu-tabbed flush-bottom">
{tabElements}
</ul>
);
}
}
PageHeaderTabs.defaultProps = {
tabs: []
};
PageHeaderTabs.propTypes = {
tabs: React.PropTypes.arrayOf(
React.PropTypes.shape({
isActive: React.PropTypes.bool,
label: React.PropTypes.node.isRequired,
routePath: React.PropTypes.string.isRequired
})
)
};
module.exports = PageHeaderTabs;
| import classNames from 'classnames/dedupe';
import {Link} from 'react-router';
import React from 'react';
class PageHeaderTabs extends React.Component {
render() {
let {props: {tabs}} = this;
let tabElements = tabs.map(function (tab, index) {
let {isActive, callback} = tab;
let classes = classNames('menu-tabbed-item', {active: isActive});
let linkClasses = classNames('menu-tabbed-item-label', {active: isActive});
let innerLinkSpan = <span className="menu-tabbed-item-label-text">{tab.label}</span>;
return (
<li className={classes} key={index}>
<Link className={linkClasses} to={tab.routePath}>
<span className="tab-item-label-text">
{tab.label}
</span>
</Link>
</li>
);
});
return (
<div className="page-header-navigation">
<ul className="menu-tabbed">
{tabElements}
</ul>
</div>
);
}
}
PageHeaderTabs.defaultProps = {
tabs: []
};
PageHeaderTabs.propTypes = {
tabs: React.PropTypes.arrayOf(
React.PropTypes.shape({
isActive: React.PropTypes.bool,
label: React.PropTypes.node.isRequired,
routePath: React.PropTypes.string.isRequired
})
)
};
module.exports = PageHeaderTabs;
| Update styles in page header tabs to match latest canvas | Update styles in page header tabs to match latest canvas
| JavaScript | apache-2.0 | dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui | ---
+++
@@ -7,10 +7,11 @@
let {props: {tabs}} = this;
let tabElements = tabs.map(function (tab, index) {
- let {isActive} = tab;
- let classes = classNames('tab-item', {active: isActive});
- let linkClasses = classNames('tab-item-label', {active: isActive});
+ let {isActive, callback} = tab;
+ let classes = classNames('menu-tabbed-item', {active: isActive});
+ let linkClasses = classNames('menu-tabbed-item-label', {active: isActive});
+ let innerLinkSpan = <span className="menu-tabbed-item-label-text">{tab.label}</span>;
return (
<li className={classes} key={index}>
<Link className={linkClasses} to={tab.routePath}>
@@ -23,9 +24,11 @@
});
return (
- <ul className="menu-tabbed flush-bottom">
- {tabElements}
- </ul>
+ <div className="page-header-navigation">
+ <ul className="menu-tabbed">
+ {tabElements}
+ </ul>
+ </div>
);
}
} |
1fb5dd1b4ea489bb3de3942352480bced07e5938 | src/qux.js | src/qux.js | var Qux = (function () {
'use strict';
function Qux () {
this.events = {};
}
var uid = -1;
Qux.prototype.publish = function (ev, data) {
if (typeof this.events[ev] === 'undefined') {
return false;
}
var q = this.events[ev];
var len = q.length;
for (var i = 0; i < len; i++) {
q[i].fn(ev, data);
}
return true;
};
Qux.prototype.subscribe = function (ev, fn) {
// if event not already registered, add it
if (typeof this.events[ev] === 'undefined') {
this.events[ev] = [];
}
var token = ++uid;
this.events[ev].push({
token: token,
fn: fn
});
};
Qux.prototype.unsubscribe = function (token) {
for (var e in this.events) {
var q = this.events[e];
for (var i = 0; i < q.length; i++) {
if (q[i].token === token) {
q.splice(i, 1);
}
}
}
};
return Qux;
})();
| /* jshint node: true */
(function () {
'use strict';
var root = this;
var uid = -1;
function Qux () {
this.topics = {};
}
Qux.prototype.publish = function (topic, data) {
if (typeof this.topics[topic] === 'undefined') {
return false;
}
var queue = this.topics[topic];
var len = queue.length;
for (var i = 0; i < len; i++) {
queue[i].cb(data);
}
return true;
};
Qux.prototype.subscribe = function (topic, cb) {
var token = ++uid;
// if event not already registered, add it
if (typeof this.topics[topic] === 'undefined') {
this.topics[topic] = [];
}
this.topics[topic].push({
token: token,
cb: cb
});
return token;
};
Qux.prototype.unsubscribe = function (token) {
for (var topic in this.topics) {
var queue = this.topics[topic];
for (var i = 0; i < queue.length; i++) {
if (queue[i].token === token) {
queue.splice(i, 1);
return true;
}
}
}
return false;
};
if (typeof module !== 'undefined' &&
typeof module.exports !== 'undefined') {
module.exports = Qux;
}
else {
root.Qux = Qux;
}
}).call(this);
| Create a module or a global object depending on context | Create a module or a global object depending on context
| JavaScript | mit | ultranaut/qux | ---
+++
@@ -1,51 +1,75 @@
-var Qux = (function () {
+/* jshint node: true */
+
+(function () {
'use strict';
+ var root = this;
+ var uid = -1;
+
function Qux () {
- this.events = {};
+ this.topics = {};
}
- var uid = -1;
-
- Qux.prototype.publish = function (ev, data) {
- if (typeof this.events[ev] === 'undefined') {
+ Qux.prototype.publish = function (topic, data) {
+ if (typeof this.topics[topic] === 'undefined') {
return false;
}
- var q = this.events[ev];
- var len = q.length;
+ var queue = this.topics[topic];
+ var len = queue.length;
for (var i = 0; i < len; i++) {
- q[i].fn(ev, data);
+ queue[i].cb(data);
}
return true;
};
- Qux.prototype.subscribe = function (ev, fn) {
+ Qux.prototype.subscribe = function (topic, cb) {
+ var token = ++uid;
+
// if event not already registered, add it
- if (typeof this.events[ev] === 'undefined') {
- this.events[ev] = [];
+ if (typeof this.topics[topic] === 'undefined') {
+ this.topics[topic] = [];
}
- var token = ++uid;
+ this.topics[topic].push({
+ token: token,
+ cb: cb
+ });
- this.events[ev].push({
- token: token,
- fn: fn
- });
+ return token;
};
Qux.prototype.unsubscribe = function (token) {
- for (var e in this.events) {
- var q = this.events[e];
- for (var i = 0; i < q.length; i++) {
- if (q[i].token === token) {
- q.splice(i, 1);
+ for (var topic in this.topics) {
+ var queue = this.topics[topic];
+ for (var i = 0; i < queue.length; i++) {
+ if (queue[i].token === token) {
+ queue.splice(i, 1);
+ return true;
}
}
}
+ return false;
};
- return Qux;
-})();
+ if (typeof module !== 'undefined' &&
+ typeof module.exports !== 'undefined') {
+ module.exports = Qux;
+ }
+ else {
+ root.Qux = Qux;
+ }
+}).call(this);
+
+
+
+
+
+
+
+
+
+
+ |
b1e6b991bf2f84730fa731a24654a455baf9cd46 | modules/intentManager.js | modules/intentManager.js | var CONTEXT_URI = process.env.CONTEXT_URI;
var _ = require('underscore');
var IntentManager = function () {
};
IntentManager.prototype.process = function (intent, req, res) {
var redirect = function (url) {
console.log("And CONTEXT URI IS ->", CONTEXT_URI);
res.redirect(CONTEXT_URI + url + "?username=" + req.session.oneselfUsername);
};
if (_.isEmpty(intent)) {
res.redirect("/dashboard");
} else {
var intentName = intent.name;
var intentData = intent.data;
console.log("intentName -#-#->", intentName);
if (intentName === "website_signup") {
res.redirect("http://1self.co/confirmation.html");
} else if (intentName === "chart.comment") {
res.redirect(intentData.url);
} else {
redirect("/dashboard");
}
}
};
module.exports = new IntentManager();
| var CONTEXT_URI = process.env.CONTEXT_URI;
var _ = require('underscore');
var IntentManager = function () {
};
IntentManager.prototype.process = function (intent, req, res) {
var redirect = function (url) {
console.log("And CONTEXT URI IS ->", CONTEXT_URI);
res.redirect(CONTEXT_URI + url + "?username=" + req.session.oneselfUsername);
};
if (_.isEmpty(intent)) {
res.redirect("/dashboard");
} else {
var intentName = intent.name;
var intentData = intent.data;
console.log("intentName -#-#->", intentName);
if (intentName === "website_signup") {
res.redirect("http://www-staging.1self.co/confirmation.html");
} else if (intentName === "chart.comment") {
res.redirect(intentData.url);
} else {
redirect("/dashboard");
}
}
};
module.exports = new IntentManager();
| Use staging for confirmation while testing | Use staging for confirmation while testing
| JavaScript | agpl-3.0 | maximilianhp/api,1self/api,maximilianhp/api,1self/api,maximilianhp/api,1self/api,1self/api | ---
+++
@@ -21,7 +21,7 @@
console.log("intentName -#-#->", intentName);
if (intentName === "website_signup") {
- res.redirect("http://1self.co/confirmation.html");
+ res.redirect("http://www-staging.1self.co/confirmation.html");
} else if (intentName === "chart.comment") {
res.redirect(intentData.url);
} else { |
33a3ba258d43af45e24370eaea2589aaae67f400 | lib/display-message.js | lib/display-message.js | var DisplayLeaderboard = require('./display-leaderboard');
const $ = require('jquery');
function DisplayMessage(){
this.element = $('#post-game');
}
DisplayMessage.prototype.showWinMessage = function(){
var div = this.element;
div.empty()
.show()
.append(`<h1>You Win!</h1>
<p>Click to play the next level.</p>`
);
div.on('click', function(){
div.hide();
});
};
DisplayMessage.prototype.showHighScoreMessage = function(game, leaderboard){
var div = this.element;
div.empty()
.show()
.append(`<h1>High Score!</h1>
<p>Name:</p>
<input class='input'></input>
<button id="high-submit-button">Submit</button>`
);
div.unbind('click').on('click', 'button', function() {
var input = $('.input').val();
game.getName(input, leaderboard);
if(leaderboard.name === 'Level Random'){
new DisplayLeaderboard(leaderboard);
}
div.hide();
});
};
DisplayMessage.prototype.showScore = function(score){
$('#score').empty().append(this.scoreElement(score));
};
DisplayMessage.prototype.scoreElement = function(score){
return '<h1>Score: ' + score + '</h1>';
};
module.exports = DisplayMessage;
| var DisplayLeaderboard = require('./display-leaderboard');
const templates = require('./message-templates');
const $ = require('jquery');
function DisplayMessage(){
this.element = $('#post-game');
}
DisplayMessage.prototype.showBoardMessage = function(template) {
var div = this.element;
div.empty()
.show()
.append(template);
};
DisplayMessage.prototype.showWinMessage = function(){
var div = this.element;
div.empty()
.show()
.append(`<h1>You Win!</h1>
<p>Click to play the next level.</p>`
);
div.on('click', function(){
div.hide();
});
};
DisplayMessage.prototype.showHighScoreMessage = function(game, leaderboard){
this.showBoardMessage(templates.highScoreWin);
div.unbind('click').on('click', 'button', function() {
var input = $('.input').val();
game.getName(input, leaderboard);
if(leaderboard.name === 'Level Random'){
new DisplayLeaderboard(leaderboard);
}
div.hide();
});
};
DisplayMessage.prototype.showScore = function(score){
$('#score').empty().append(this.scoreElement(score));
};
DisplayMessage.prototype.scoreElement = function(score){
return '<h1>Score: ' + score + '</h1>';
};
module.exports = DisplayMessage;
| Add generic full board display message method | Add generic full board display message method
Currently used successfully by high score win
| JavaScript | mit | plato721/lights-out,plato721/lights-out | ---
+++
@@ -1,9 +1,17 @@
var DisplayLeaderboard = require('./display-leaderboard');
+const templates = require('./message-templates');
const $ = require('jquery');
function DisplayMessage(){
this.element = $('#post-game');
}
+
+DisplayMessage.prototype.showBoardMessage = function(template) {
+ var div = this.element;
+ div.empty()
+ .show()
+ .append(template);
+};
DisplayMessage.prototype.showWinMessage = function(){
var div = this.element;
@@ -18,14 +26,7 @@
};
DisplayMessage.prototype.showHighScoreMessage = function(game, leaderboard){
- var div = this.element;
- div.empty()
- .show()
- .append(`<h1>High Score!</h1>
- <p>Name:</p>
- <input class='input'></input>
- <button id="high-submit-button">Submit</button>`
- );
+ this.showBoardMessage(templates.highScoreWin);
div.unbind('click').on('click', 'button', function() {
var input = $('.input').val();
game.getName(input, leaderboard); |
7958aeaebae2e082e4b38bbde1196ea2689c92cc | lib/stats/got-wrong.js | lib/stats/got-wrong.js | module.exports = function (stackName, id) {
if (typeof id === 'string') {
id = this.idByFront(stackName, id)
}
this.stacks[stackName][id].wrong += 1
}
| var copy = require('../copy.js')
module.exports = function (stack, id) {
var newStack = copy(stack)
if (typeof id === 'undefined') {
// stack is not a stack - it's just a card, so update the card's wrong key
newStack.wrong += 1
}
else {
newStack[id].wrong += 1
}
return newStack
}
| Make f.gotWrong() work with actual arrays | Make f.gotWrong() work with actual arrays
| JavaScript | isc | jamescostian/flashcardz | ---
+++
@@ -1,6 +1,12 @@
-module.exports = function (stackName, id) {
- if (typeof id === 'string') {
- id = this.idByFront(stackName, id)
+var copy = require('../copy.js')
+module.exports = function (stack, id) {
+ var newStack = copy(stack)
+ if (typeof id === 'undefined') {
+ // stack is not a stack - it's just a card, so update the card's wrong key
+ newStack.wrong += 1
}
- this.stacks[stackName][id].wrong += 1
+ else {
+ newStack[id].wrong += 1
+ }
+ return newStack
} |
3375cd1c123c1748a60aa99a642d9c6e662e65e1 | examples/native/hello/__tests__/App.js | examples/native/hello/__tests__/App.js | import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<App />
);
});
| /* eslint-env jest */
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<App />
);
});
| Fix lint for react-native example | Fix lint for react-native example
| JavaScript | mit | pH200/cycle-react | ---
+++
@@ -1,3 +1,4 @@
+/* eslint-env jest */
import 'react-native';
import React from 'react';
import App from '../App'; |
b9f1d530476f25baf38feeac29634be6a3b74a89 | plugins/slack.js | plugins/slack.js | const LifeforcePlugin = require("../utils/LifeforcePlugin.js");
class SlackBot extends LifeforcePlugin {
constructor(restifyserver, logger, name) {
super(restifyserver, logger, name);
this.apiMap = [
{
path: "/api/slack/log",
type: "post",
handler: handleSlackPush
}
];
const SlackBot = require('slackbots');
this.bot = new SlackBot({
token: this.config.slack.token,
name: 'kabuildbot'
});
}
}
function handleSlackPush(req, res, next) {
if (req.body) {
var payload = req.body + "";
this.bot.postMessageToChannel('general', payload, {
icon_emoji: ':robot_face:'
});
// send a message to the chat acknowledging receipt of their message
res.send(200, { error: false });
} else {
res.send(400, { error: true, msg: "No request body" });
}
}
module.exports = SlackBot; | const LifeforcePlugin = require("../utils/LifeforcePlugin.js");
class SlackBot extends LifeforcePlugin {
constructor(restifyserver, logger, name) {
super(restifyserver, logger, name);
this.apiMap = [
{
path: "/api/slack/log",
type: "post",
handler: handleSlackPush
},
{
path: "/api/slack/deploy",
type: "post",
handler: handleSlackPushDeploy
}
];
const SlackBot = require('slackbots');
this.bot = new SlackBot({
token: this.config.slack.token,
name: 'kabuildbot'
});
}
}
function handleSlackPush(req, res, next) {
if (req.body) {
var payload = req.body + "";
this.bot.postMessageToChannel('general', payload, {
icon_emoji: ':robot_face:'
});
// send a message to the chat acknowledging receipt of their message
res.send(200, { error: false });
} else {
res.send(400, { error: true, msg: "No request body" });
}
}
function handleSlackPushDeploy(req, res, next) {
if (req.body) {
var payload = req.body + "";
this.bot.postMessageToChannel('deployment', payload, {
icon_emoji: ':robot_face:'
});
// send a message to the chat acknowledging receipt of their message
res.send(200, { error: false });
} else {
res.send(400, { error: true, msg: "No request body" });
}
}
module.exports = SlackBot;
| Add a new channel for deployment logging | Add a new channel for deployment logging | JavaScript | mit | repkam09/repka-lifeforce,repkam09/repka-lifeforce,repkam09/repka-lifeforce | ---
+++
@@ -8,6 +8,11 @@
path: "/api/slack/log",
type: "post",
handler: handleSlackPush
+ },
+ {
+ path: "/api/slack/deploy",
+ type: "post",
+ handler: handleSlackPushDeploy
}
];
@@ -34,4 +39,19 @@
}
}
+function handleSlackPushDeploy(req, res, next) {
+ if (req.body) {
+ var payload = req.body + "";
+
+ this.bot.postMessageToChannel('deployment', payload, {
+ icon_emoji: ':robot_face:'
+ });
+
+ // send a message to the chat acknowledging receipt of their message
+ res.send(200, { error: false });
+ } else {
+ res.send(400, { error: true, msg: "No request body" });
+ }
+}
+
module.exports = SlackBot; |
6dafca6cf94bf82053d9218998f5cf960659f98b | samples/factorial/run.js | samples/factorial/run.js |
var cobs = require('../..'),
fs = require('fs');
var runtime = {
display: function() {
var result = '';
if (arguments && arguments.length)
for (var k = 0; k < arguments.length; k++)
if (arguments[k])
result += arguments[k].toString();
console.log(result);
}
}
function runFile(filename) {
var text = fs.readFileSync(filename).toString();
var parser = new cobs.Parser(text);
var program = parser.parseProgram();
cobs.run(program.command.compile(program), runtime, program);
};
process.argv.forEach(function(val) {
if (val.slice(-5) == ".cobs" || val.slice(-4) == ".cob")
runFile(val);
});
|
var cobs = require('../..'),
fs = require('fs');
var runtime = {
display: function() {
var result = '';
if (arguments && arguments.length)
for (var k = 0; k < arguments.length; k++)
if (arguments[k])
result += arguments[k].toString();
console.log(result);
}
}
function runFile(filename) {
cobs.compileProgramFile(filename).run(runtime);
};
process.argv.forEach(function(val) {
if (val.slice(-4) == ".cob")
runFile(val);
});
| Refactor factorial sample to use compileProgramFile | Refactor factorial sample to use compileProgramFile
| JavaScript | mit | ajlopez/CobolScript | ---
+++
@@ -15,14 +15,11 @@
}
function runFile(filename) {
- var text = fs.readFileSync(filename).toString();
- var parser = new cobs.Parser(text);
- var program = parser.parseProgram();
- cobs.run(program.command.compile(program), runtime, program);
+ cobs.compileProgramFile(filename).run(runtime);
};
process.argv.forEach(function(val) {
- if (val.slice(-5) == ".cobs" || val.slice(-4) == ".cob")
+ if (val.slice(-4) == ".cob")
runFile(val);
});
|
cb5581744dc7503b29b52996c741723552e89c7f | test/test.ssh-config.js | test/test.ssh-config.js | 'use strict'
var expect = require('expect.js')
var fs = require('fs')
var path = require('path')
var sshConfig = require('..')
describe('ssh-config', function() {
var fixture = fs.readFileSync(path.join(__dirname, 'fixture/config'), 'utf-8')
var config = sshConfig.parse(fixture)
it('.parse ssh config text into object', function() {
expect(config.ControlMaster).to.equal('auto')
expect(config.length).to.equal(4)
expect(config[0]).to.eql({
Host: 'tahoe1',
HostName: 'tahoe1.com',
Compression: 'yes'
})
})
it('.query ssh config by host', function() {
var opts = config.query('tahoe2')
expect(opts.User).to.equal('nil')
expect(opts.IdentityFile).to.equal('~/.ssh/id_rsa')
// the first obtained parameter value will be used. So there's no way to
// override parameter values.
expect(opts.ServerAliveInterval).to.eql(80)
opts = config.query('tahoe1')
expect(opts.User).to.equal('nil')
expect(opts.ForwardAgent).to.equal('true')
expect(opts.Compression).to.equal('yes')
})
it('.stringify the parsed object back to string', function() {
expect(fixture).to.contain(sshConfig.stringify(config))
})
})
| 'use strict'
var expect = require('expect.js')
var fs = require('fs')
var path = require('path')
var sshConfig = require('..')
describe('ssh-config', function() {
var fixture = fs.readFileSync(path.join(__dirname, 'fixture/config'), 'utf-8')
.replace(/\r\n/g, '\n')
var config = sshConfig.parse(fixture)
it('.parse ssh config text into object', function() {
expect(config.ControlMaster).to.equal('auto')
expect(config.length).to.equal(4)
expect(config[0]).to.eql({
Host: 'tahoe1',
HostName: 'tahoe1.com',
Compression: 'yes'
})
})
it('.query ssh config by host', function() {
var opts = config.query('tahoe2')
expect(opts.User).to.equal('nil')
expect(opts.IdentityFile).to.equal('~/.ssh/id_rsa')
// the first obtained parameter value will be used. So there's no way to
// override parameter values.
expect(opts.ServerAliveInterval).to.eql(80)
opts = config.query('tahoe1')
expect(opts.User).to.equal('nil')
expect(opts.ForwardAgent).to.equal('true')
expect(opts.Compression).to.equal('yes')
})
it('.stringify the parsed object back to string', function() {
expect(fixture).to.contain(sshConfig.stringify(config))
})
})
| Make sure the line endings are consistent | Make sure the line endings are consistent
'\n' is the one we prefer. fixes #3
| JavaScript | mit | dotnil/ssh-config | ---
+++
@@ -8,6 +8,7 @@
describe('ssh-config', function() {
var fixture = fs.readFileSync(path.join(__dirname, 'fixture/config'), 'utf-8')
+ .replace(/\r\n/g, '\n')
var config = sshConfig.parse(fixture)
it('.parse ssh config text into object', function() { |
f853cacdb9479d302e30e59c2e190b77f9a81cc0 | src/scripts/components/colour/Colour.js | src/scripts/components/colour/Colour.js | import React from 'react';
import Colours from '../../modules/colours';
const Colour = (props) => {
var colour = props.colour;
if (props.format === 'rgb') {
var rgb = Colours.hexToRgb(colour.substring(1, 7));
colour = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
}
return (
<h2 className='colours__hex copy' data-clipboard-text={colour}>{colour}</h2>
);
};
export default Colour;
| import React from 'react';
import Colours from '../../modules/colours';
const Colour = (props) => {
var colour = props.colour;
if (props.format === 'rgb') {
var rgb = Colours.hexToRgb(colour.substring(1, 7));
colour = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
}
return (
<h2 className='colours__hex'>
<span className='copy' data-clipboard-text={colour}>{colour}</span>
</h2>
);
};
export default Colour;
| Make only the colour code the copy region instead of entire row | Make only the colour code the copy region instead of entire row
| JavaScript | mit | arkon/ColourNTP,arkon/ColourNTP | ---
+++
@@ -12,7 +12,9 @@
}
return (
- <h2 className='colours__hex copy' data-clipboard-text={colour}>{colour}</h2>
+ <h2 className='colours__hex'>
+ <span className='copy' data-clipboard-text={colour}>{colour}</span>
+ </h2>
);
};
|
6d5ab9cfe13a7f6126e8eb15d1b31a33bea75923 | server/worldGenerator.js | server/worldGenerator.js | 'use strict';
const rethinkDB = require('rethinkdb');
const program = require('commander');
const log = require('./log');
var worldDB = 'labyrinth';
if (require.main === module) {
program
.version('0.0.1')
.option('-p, --port <n>', 'Port for RethinkDB, default is 28015', parseInt, {isDefault: 28015})
.option('-t, --test <n>', 'Create n Corals', parseInt)
.parse(process.argv);
rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) {
if (err) throw err;
rethinkDB
.dbCreate(worldDB)
.run(conn, (err, res) => {
if (err) {
log.error(`The world is exist. `
+ `If you really want create a new world, `
+ `delete the database "${worldDB}".`);
throw err;
}
});
});
}
| 'use strict';
const rethinkDB = require('rethinkdb');
const program = require('commander');
const log = require('./log');
var worldDB = 'labyrinth';
if (require.main === module) {
program
.version('0.0.1')
.option('-n, --dbname', 'Name of world database')
.option('-p, --port <n>', 'Port for RethinkDB, default is 28015', parseInt, {isDefault: 28015})
.option('-t, --test <n>', 'Create n Corals', parseInt)
.parse(process.argv);
rethinkDB.connect( {host: 'localhost', port: program.port}, function(err, conn) {
if (err) throw err;
rethinkDB
.dbCreate(program.dbname)
.run(conn, (err, res) => {
if (err) {
log.error(`The world is exist. `
+ `If you really want create a new world, `
+ `delete the database "${program.dbname}".`);
throw err;
}
});
});
}
| Add color log in the world generator | Add color log in the world generator
| JavaScript | mit | nobus/Labyrinth,nobus/Labyrinth | ---
+++
@@ -10,20 +10,21 @@
if (require.main === module) {
program
.version('0.0.1')
+ .option('-n, --dbname', 'Name of world database')
.option('-p, --port <n>', 'Port for RethinkDB, default is 28015', parseInt, {isDefault: 28015})
.option('-t, --test <n>', 'Create n Corals', parseInt)
.parse(process.argv);
- rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) {
+ rethinkDB.connect( {host: 'localhost', port: program.port}, function(err, conn) {
if (err) throw err;
rethinkDB
- .dbCreate(worldDB)
+ .dbCreate(program.dbname)
.run(conn, (err, res) => {
if (err) {
log.error(`The world is exist. `
+ `If you really want create a new world, `
- + `delete the database "${worldDB}".`);
+ + `delete the database "${program.dbname}".`);
throw err;
} |
9ee199d4d6e08e8a2c7b12fee4c0b1b62dc5bc37 | docker/generate-dockerfile.js | docker/generate-dockerfile.js | #!/usr/bin/env node
var fs = require('fs');
var version = JSON.parse(fs.readFileSync("./package.json")).version;
var tag = "truecar/gluestick:" + version;
var dockerfile = [
"# DO NOT MODIFY",
"# This file is automatically generated. You can copy this file and add a",
"# Dockerfile to the root of the project if you would like to use a custom",
"# docker setup.",
"FROM " + tag,
"",
"ADD . /app",
"",
"RUN npm install",
"RUN gluestick build",
""
];
fs.writeFile("./templates/new/src/config/.Dockerfile", dockerfile.join("\n"));
| #!/usr/bin/env node
var fs = require('fs');
var version = JSON.parse(fs.readFileSync("./package.json")).version;
var tag = "truecar/gluestick:" + version;
var dockerfile = [
"# DO NOT MODIFY",
"# This file is automatically generated. You can copy this file and add a",
"# Dockerfile to the root of the project if you would like to use a custom",
"# docker setup.",
"FROM " + tag,
"",
"ADD . /app",
"",
"RUN npm install",
""
];
fs.writeFile("./templates/new/src/config/.Dockerfile", dockerfile.join("\n"));
| Remove build option from generated docker file | Remove build option from generated docker file
| JavaScript | mit | TrueCar/gluestick,TrueCar/gluestick,TrueCar/gluestick | ---
+++
@@ -15,7 +15,6 @@
"ADD . /app",
"",
"RUN npm install",
- "RUN gluestick build",
""
];
|
c429bbab8a4ac3d9d637af8bc8cb10759ea65f5a | scripts/buildexamples.js | scripts/buildexamples.js | var childProcess = require('child_process');
var fs = require('fs');
process.chdir('examples');
childProcess.execSync('npm install', { stdio: 'inherit' });
childProcess.execSync('npm run update', { stdio: 'inherit' });
process.chdir('..');
// Build all of the example folders.
dirs = fs.readdirSync('examples');
var cmd;
for (var i = 0; i < dirs.length; i++) {
if (dirs[i].indexOf('.') !== -1) {
continue;
}
if (dirs[i].indexOf('node_modules') !== -1) {
continue;
}
console.log('Building: ' + dirs[i] + '...');
process.chdir('examples/' + dirs[i]);
childProcess.execSync('npm run build', { stdio: 'inherit' });
process.chdir('../..');
}
| var childProcess = require('child_process');
var fs = require('fs');
process.chdir('examples');
childProcess.execSync('npm install', { stdio: 'inherit' });
childProcess.execSync('npm run update', { stdio: 'inherit' });
process.chdir('..');
// Build all of the example folders.
dirs = fs.readdirSync('examples');
var cmd;
for (var i = 0; i < dirs.length; i++) {
if (dirs[i].indexOf('.') !== -1) {
continue;
}
if (dirs[i].indexOf('node_modules') !== -1) {
continue;
}
console.log('\n***********\nBuilding: ' + dirs[i] + '...');
process.chdir('examples/' + dirs[i]);
childProcess.execSync('npm run build', { stdio: 'inherit' });
process.chdir('../..');
}
console.log('\n********\nDone!');
| Make examples build more verbose | Make examples build more verbose
| JavaScript | bsd-3-clause | jupyter/jupyter-js-notebook,jupyter/jupyter-js-notebook,blink1073/jupyter-js-notebook,jupyter/jupyter-js-notebook,blink1073/jupyter-js-notebook,blink1073/jupyter-js-notebook,blink1073/jupyter-js-notebook,jupyter/jupyter-js-notebook,blink1073/jupyter-js-notebook,jupyter/jupyter-js-notebook | ---
+++
@@ -17,8 +17,10 @@
if (dirs[i].indexOf('node_modules') !== -1) {
continue;
}
- console.log('Building: ' + dirs[i] + '...');
+ console.log('\n***********\nBuilding: ' + dirs[i] + '...');
process.chdir('examples/' + dirs[i]);
childProcess.execSync('npm run build', { stdio: 'inherit' });
process.chdir('../..');
+
}
+console.log('\n********\nDone!'); |
03278cc191d9dea00ad8406a3e57c6c05f82eec0 | lib/http/middleware/body-size-limiter.js | lib/http/middleware/body-size-limiter.js | var log = require('util/log');
function attachMiddleware(maxSize) {
return function bodyDecoder(req, res, next) {
var cl, bodyLen = 0;
req.buffer = '';
cl = req.headers['content-length'];
if (cl) {
cl = parseInt(cl, 10);
if (cl >= maxSize) {
log.info('Denying client for too large content length');
res.writeHead(413, {Connection: 'close'});
res.end();
}
}
function onData(chunk) {
req.buffer += chunk;
bodyLen += chunk.length;
if (bodyLen >= maxSize) {
log.info('Denying client for body too large');
res.writeHead(413, {Connection: 'close'});
res.end();
req.removeListener('data', onData);
}
}
req.setEncoding('utf8');
req.on('data', onData);
req.on('end', next);
};
}
exports.attachMiddleware = attachMiddleware;
| var sprintf = require('sprintf').sprintf;
var log = require('util/log');
var MAX_BUFFER_SIZE = 10 * 1024 * 1024;
function attachMiddleware(maxSize) {
if (maxSize > MAX_BUFFER_SIZE) {
throw new Error(sprintf('Buffering more then %d bytes of data in memory is a bad idea',
MAX_BUFFER_SIZE));
}
return function bodyDecoder(req, res, next) {
var cl, bodyLen = 0;
req.buffer = '';
cl = req.headers['content-length'];
if (cl) {
cl = parseInt(cl, 10);
if (cl >= maxSize) {
log.info('Denying client for too large content length');
res.writeHead(413, {Connection: 'close'});
res.end();
}
}
function onData(chunk) {
req.buffer += chunk;
bodyLen += chunk.length;
if (bodyLen >= maxSize) {
log.info('Denying client for body too large');
res.writeHead(413, {Connection: 'close'});
res.end();
req.removeListener('data', onData);
}
}
req.setEncoding('utf8');
req.on('data', onData);
req.on('end', next);
};
}
exports.attachMiddleware = attachMiddleware;
| Throw an error if someon wants to buffer too much data in memory. | Throw an error if someon wants to buffer too much data in memory.
| JavaScript | apache-2.0 | cloudkick/cast,cloudkick/cast,cloudkick/cast,cloudkick/cast | ---
+++
@@ -1,6 +1,15 @@
+var sprintf = require('sprintf').sprintf;
+
var log = require('util/log');
+var MAX_BUFFER_SIZE = 10 * 1024 * 1024;
+
function attachMiddleware(maxSize) {
+ if (maxSize > MAX_BUFFER_SIZE) {
+ throw new Error(sprintf('Buffering more then %d bytes of data in memory is a bad idea',
+ MAX_BUFFER_SIZE));
+ }
+
return function bodyDecoder(req, res, next) {
var cl, bodyLen = 0;
req.buffer = ''; |
be765c9052ebd6d38663d13bf1468fc0fa6201ad | cli.js | cli.js | #!/usr/bin/env node
'use strict'
var meow = require('meow')
var hacktoberFest = require('./main.js')
const cli = meow({
flags: {
year: {
type: 'number',
alias: 'y',
default: 0,
},
help: {
type: 'boolean',
alias: 'h',
},
},
})
if (cli.flags.help) {
cli.showHelp(0)
}
hacktoberFest
.getHacktoberfestStats(cli.input[0], cli.flags.year)
.then((stats) => {
console.log(stats)
})
.catch((error) => {
console.error(error.message)
process.exit(1)
})
| #!/usr/bin/env node
'use strict'
var meow = require('meow')
var hacktoberFest = require('./main.js')
const cli = meow(`
Usage:
$ npx hacktoberfeststats <username from GitHub>
Options
--help, -h Get this beautiful help panel
--year, -y Specify the year you want to get stats from. Useful if you want to retrieve historic data from previous hacktoberfest events.
Examples
$ npx hacktoberfeststats MatejMecka --year 2019
`,{
flags: {
year: {
type: 'number',
alias: 'y',
default: 0,
},
help: {
type: 'boolean',
alias: 'h',
},
},
})
if (cli.flags.help) {
cli.showHelp(0)
}
hacktoberFest
.getHacktoberfestStats(cli.input[0], cli.flags.year)
.then((stats) => {
console.log(stats)
})
.catch((error) => {
console.error(error.message)
process.exit(1)
})
| Add help text for the --help command | Add help text for the --help command | JavaScript | mit | MatejMecka/HacktoberfestStats | ---
+++
@@ -4,7 +4,18 @@
var meow = require('meow')
var hacktoberFest = require('./main.js')
-const cli = meow({
+const cli = meow(`
+ Usage:
+ $ npx hacktoberfeststats <username from GitHub>
+
+ Options
+ --help, -h Get this beautiful help panel
+ --year, -y Specify the year you want to get stats from. Useful if you want to retrieve historic data from previous hacktoberfest events.
+
+ Examples
+ $ npx hacktoberfeststats MatejMecka --year 2019
+
+`,{
flags: {
year: {
type: 'number', |
a526c4307dddb6b54521e4adbfed7dab596b313f | static/default/ckeditor/coorgConfig.js | static/default/ckeditor/coorgConfig.js | CKEDITOR.editorConfig = function( config )
{
config.toolbar = 'Full';
config.toolbar_Full =
[
['Styles', '-', 'Bold','Italic', 'Underline','Strike', '-', 'NumberedList','BulletedList', '-', 'Link', 'Unlink', 'Image', '-', 'Undo', 'Redo', '-', 'Find', 'Replace', 'SelectAll']
];
config.toolbar_Lite =
[
['Bold','Italic', 'Underline','Strike', '-', 'NumberedList','BulletedList', '-', 'Link', 'Unlink']
];
config.resize_enabled = false;
config.toolbarCanCollapse = false;
config.stylesSet = 'coorg:coorgStyles.js';
config.removePlugins = 'elementspath';
};
| CKEDITOR.editorConfig = function( config )
{
config.toolbar = 'Full';
config.toolbar_Full =
[
['Styles', '-', 'Bold','Italic', 'Underline','Strike', '-', 'NumberedList','BulletedList', '-', 'Link', 'Unlink', 'Image', '-', 'Undo', 'Redo', '-', 'Find', 'Replace', 'SelectAll']
];
config.toolbar_Lite =
[
['Bold','Italic', 'Underline','Strike', '-', 'NumberedList','BulletedList', '-', 'Link', 'Unlink']
];
config.resize_enabled = false;
config.toolbarCanCollapse = false;
config.stylesSet = 'coorg:coorgStyles.js';
config.removePlugins = 'elementspath,scayt';
config.disableNativeSpellchecker = false;
// If we choose to enable scayt again, we have to set our own language...
// config.scayt_sLang = COORGLANG;
};
| Fix the spellchecker nastyness in the rteditor | Fix the spellchecker nastyness in the rteditor | JavaScript | agpl-3.0 | nathansamson/CoOrg,nathansamson/CoOrg,nathansamson/CoOrg | ---
+++
@@ -15,6 +15,10 @@
config.resize_enabled = false;
config.toolbarCanCollapse = false;
config.stylesSet = 'coorg:coorgStyles.js';
- config.removePlugins = 'elementspath';
+ config.removePlugins = 'elementspath,scayt';
+ config.disableNativeSpellchecker = false;
+
+ // If we choose to enable scayt again, we have to set our own language...
+ // config.scayt_sLang = COORGLANG;
};
|
c2dfec82e9d5a3157c9c82de5e74407fc584d94d | examples/navigation/epics/searchUsers.js | examples/navigation/epics/searchUsers.js | import { Observable } from 'rxjs/Observable';
import { LOCATION_CHANGE } from 'react-router-redux';
import { ajax } from 'rxjs/observable/dom/ajax';
import * as ActionTypes from '../actionTypes';
export default function searchUsers(action$) {
const searchIntents$ = action$.ofType(LOCATION_CHANGE)
.filter(({ payload }) =>
payload.pathname === '/' && !!payload.query.q
);
return Observable.merge(
searchIntents$.map(() => ({
type: ActionTypes.SEARCHED_USERS
})),
searchIntents$
.switchMap(({ payload: { query: { q } } }) =>
Observable.timer(800) // debouncing
.takeUntil(action$.ofType(ActionTypes.CLEARED_RESULTS))
.mergeMapTo(ajax.getJSON(`https://api.github.com/search/users?q=${q}`))
.map(res => ({
type: ActionTypes.RECEIVED_USERS,
payload: {
users: res.items
}
}))
)
);
};
| import { Observable } from 'rxjs/Observable';
import { LOCATION_CHANGE } from 'react-router-redux';
import { ajax } from 'rxjs/observable/dom/ajax';
import * as ActionTypes from '../actionTypes';
export default function searchUsers(action$) {
const searchIntents$ = action$.ofType(LOCATION_CHANGE)
.filter(({ payload }) =>
payload.pathname === '/' && !!payload.query.q
)
.map(action => action.payload.query.q);
return Observable.merge(
searchIntents$.map(() => ({
type: ActionTypes.SEARCHED_USERS
})),
searchIntents$
.switchMap(q =>
Observable.timer(800) // debouncing
.takeUntil(action$.ofType(ActionTypes.CLEARED_RESULTS))
.mergeMapTo(
ajax.getJSON(`https://api.github.com/search/users?q=${q}`)
)
.map(res => ({
type: ActionTypes.RECEIVED_USERS,
payload: {
users: res.items
}
}))
)
);
};
| Make searchIntents be a stream of queries | chore(cleanup): Make searchIntents be a stream of queries
| JavaScript | mit | redux-observable/redux-observable,blesh/redux-observable,jesinity/redux-observable,redux-observable/redux-observable,jesinity/redux-observable,redux-observable/redux-observable,jesinity/redux-observable,blesh/redux-observable | ---
+++
@@ -7,16 +7,19 @@
const searchIntents$ = action$.ofType(LOCATION_CHANGE)
.filter(({ payload }) =>
payload.pathname === '/' && !!payload.query.q
- );
+ )
+ .map(action => action.payload.query.q);
return Observable.merge(
searchIntents$.map(() => ({
type: ActionTypes.SEARCHED_USERS
})),
searchIntents$
- .switchMap(({ payload: { query: { q } } }) =>
+ .switchMap(q =>
Observable.timer(800) // debouncing
.takeUntil(action$.ofType(ActionTypes.CLEARED_RESULTS))
- .mergeMapTo(ajax.getJSON(`https://api.github.com/search/users?q=${q}`))
+ .mergeMapTo(
+ ajax.getJSON(`https://api.github.com/search/users?q=${q}`)
+ )
.map(res => ({
type: ActionTypes.RECEIVED_USERS,
payload: { |
e30e1eef1f324382992e8164c78bdb093100a890 | test/helpers/citySuggestionFormatter.js | test/helpers/citySuggestionFormatter.js | import { assert } from 'chai';
import citySuggestionFormatter from 'helpers/citySuggestionFormatter';
describe('citySuggestionFormatter', () => {
context('for a suggestion without name', () => {
const suggestion = { zips: [12345, 67890] };
it('returns an empty string', () => {
const actual = citySuggestionFormatter(suggestion);
const expected = '';
assert.equal(actual, expected);
});
});
context('for a suggestion without zips', () => {
const suggestion = { name: 'City-Ville' };
it('returns an empty string', () => {
const actual = citySuggestionFormatter(suggestion);
const expected = '';
assert.equal(actual, expected);
});
});
context('for a suggestion with name and zips', () => {
const suggestion = {
name: 'City-Ville',
zips: [12345, 67890]
};
it('returns the name joined with the first zip', () => {
const actual = citySuggestionFormatter(suggestion);
const expected = 'City-Ville - 12345';
assert.equal(actual, expected);
});
});
});
| import { assert } from 'chai';
import citySuggestionFormatter from 'helpers/citySuggestionFormatter';
describe('citySuggestionFormatter', () => {
context('for a null suggestion', () => {
const suggestion = null;
it('returns an empty string', () => {
const actual = citySuggestionFormatter(suggestion);
const expected = '';
assert.equal(actual, expected);
});
});
context('for a suggestion without name', () => {
const suggestion = { zips: [12345, 67890] };
it('returns an empty string', () => {
const actual = citySuggestionFormatter(suggestion);
const expected = '';
assert.equal(actual, expected);
});
});
context('for a suggestion without zips', () => {
const suggestion = { name: 'City-Ville' };
it('returns an empty string', () => {
const actual = citySuggestionFormatter(suggestion);
const expected = '';
assert.equal(actual, expected);
});
});
context('for a suggestion with name and zips', () => {
const suggestion = {
name: 'City-Ville',
zips: [12345, 67890]
};
it('returns the name joined with the first zip', () => {
const actual = citySuggestionFormatter(suggestion);
const expected = 'City-Ville - 12345';
assert.equal(actual, expected);
});
});
});
| Update tests for handling null city suggestion | Update tests for handling null city suggestion
| JavaScript | apache-2.0 | iris-dni/iris-frontend,iris-dni/iris-frontend,iris-dni/iris-frontend | ---
+++
@@ -2,6 +2,17 @@
import citySuggestionFormatter from 'helpers/citySuggestionFormatter';
describe('citySuggestionFormatter', () => {
+ context('for a null suggestion', () => {
+ const suggestion = null;
+
+ it('returns an empty string', () => {
+ const actual = citySuggestionFormatter(suggestion);
+ const expected = '';
+
+ assert.equal(actual, expected);
+ });
+ });
+
context('for a suggestion without name', () => {
const suggestion = { zips: [12345, 67890] };
|
cd54817b284878f7f23f82454558af1d4c84ff0a | features/step_definitions/electionSteps.js | features/step_definitions/electionSteps.js | var chai = require('chai');
var Bluebird = require('bluebird');
var chaiAsPromised = require('chai-as-promised');
var localStorageService = require('../local-storage-service');
var expect = chai.expect;
chai.use(chaiAsPromised);
module.exports = function() {
this.Given(/^There is an (in)?active election$/, function(arg, callback) {
var active = arg !== 'in';
this.election.active = active;
this.election.save(callback);
});
this.Then(/^I see an active election$/, function(callback) {
var title = element(by.css('.election-info > h2'));
var description = element(by.css('.election-info > p'));
var alternatives = element.all(by.repeater('alternative in activeElection.alternatives'));
Bluebird.all([
expect(title.getText()).to.eventually.equal(this.election.title.toUpperCase()),
expect(description.getText()).to.eventually.equal(this.election.description),
expect(alternatives.count()).to.eventually.equal(1),
expect(alternatives.first().getText()).to.eventually.contain(this.alternative.description.toUpperCase())
]).nodeify(callback);
});
this.Given(/^I have voted on the election$/, function(callback) {
callback.pending();
});
};
| var chai = require('chai');
var Bluebird = require('bluebird');
var chaiAsPromised = require('chai-as-promised');
var expect = chai.expect;
chai.use(chaiAsPromised);
module.exports = function() {
this.Given(/^There is an (in)?active election$/, function(arg, callback) {
var active = arg !== 'in';
this.election.active = active;
this.election.save(callback);
});
this.Then(/^I see an active election$/, function(callback) {
var title = element(by.css('.election-info > h2'));
var description = element(by.css('.election-info > p'));
var alternatives = element.all(by.repeater('alternative in activeElection.alternatives'));
Bluebird.all([
expect(title.getText()).to.eventually.equal(this.election.title.toUpperCase()),
expect(description.getText()).to.eventually.equal(this.election.description),
expect(alternatives.count()).to.eventually.equal(1),
expect(alternatives.first().getText()).to.eventually.contain(this.alternative.description.toUpperCase())
]).nodeify(callback);
});
this.Given(/^I have voted on the election$/, function(callback) {
browser.get('/election');
var alternatives = element.all(by.repeater('alternative in activeElection.alternatives'));
var alternative = alternatives.first();
var button = element(by.css('button'));
alternative.click();
button.click();
button.click();
callback();
});
};
| Add step for voting on elections | Add step for voting on elections
| JavaScript | mit | webkom/vote,webkom/vote,webkom/vote,webkom/vote | ---
+++
@@ -1,7 +1,6 @@
var chai = require('chai');
var Bluebird = require('bluebird');
var chaiAsPromised = require('chai-as-promised');
-var localStorageService = require('../local-storage-service');
var expect = chai.expect;
chai.use(chaiAsPromised);
@@ -18,7 +17,6 @@
var description = element(by.css('.election-info > p'));
var alternatives = element.all(by.repeater('alternative in activeElection.alternatives'));
-
Bluebird.all([
expect(title.getText()).to.eventually.equal(this.election.title.toUpperCase()),
expect(description.getText()).to.eventually.equal(this.election.description),
@@ -28,7 +26,15 @@
});
this.Given(/^I have voted on the election$/, function(callback) {
- callback.pending();
+ browser.get('/election');
+ var alternatives = element.all(by.repeater('alternative in activeElection.alternatives'));
+ var alternative = alternatives.first();
+ var button = element(by.css('button'));
+
+ alternative.click();
+ button.click();
+ button.click();
+ callback();
});
}; |
cf96d6eb1814efa7330b71432920b928c0191bb6 | app.js | app.js | var express = require('express'), app = express(), swig = require('swig');
var bodyParser = require('body-parser');
var https = require('https'), config = require('./config');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/pages');
app.set('view cache', false);
swig.setDefaults({ cache: false });
app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.get('/', function(req, res) {
res.render('index', { 'foo': 'hi' });
});
app.post('/hook', function(req, res) {
if (req.body && req.body.after) {
console.log("checking: " + req.body.after);
var request = https.request({ 'host': 'api.github.com',
'path': '/repos/' + config.repoURL + '/status/' + req.body.after,
'method': 'POST'});
request.write(JSON.stringify({ 'state': 'pending' }));
request.end();
}
res.end();
});
app.listen(2345);
| var express = require('express'), app = express(), swig = require('swig');
var bodyParser = require('body-parser');
var https = require('https'), config = require('./config');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/pages');
app.set('view cache', false);
swig.setDefaults({ cache: false });
app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.get('/', function(req, res) {
res.render('index', { 'foo': 'hi' });
});
app.post('/hook', function(req, res) {
if (req.body && req.body.after) {
console.log("checking: " + req.body.after);
var request = https.request({ 'host': 'api.github.com',
'path': '/repos/' + config.repoURL + '/status/' + req.body.after + '?access_token=' + config.githubToken,
'method': 'POST'});
request.write(JSON.stringify({ 'state': 'pending' }));
request.end();
}
res.end();
});
app.listen(2345);
| Add access token to path URL | Add access token to path URL
| JavaScript | mit | iveysaur/PiCi | ---
+++
@@ -22,7 +22,7 @@
if (req.body && req.body.after) {
console.log("checking: " + req.body.after);
var request = https.request({ 'host': 'api.github.com',
- 'path': '/repos/' + config.repoURL + '/status/' + req.body.after,
+ 'path': '/repos/' + config.repoURL + '/status/' + req.body.after + '?access_token=' + config.githubToken,
'method': 'POST'});
request.write(JSON.stringify({ 'state': 'pending' }));
request.end(); |
7a0e7e56f7d70974c0c906085c884b76aac9bf3e | app.js | app.js | var Slack = require('slack-node');
apiToken = process.env.SLACK_TOKEN;
slack = new Slack(apiToken);
var channel = process.argv[2] ? "#"+process.argv[2] : '#kollegorna-ivan';
console.log(channel);
var postMessage = function (message) {
var icon_url = 'https://raw.githubusercontent.com/kollegorna/weatherbot/master/bot.jpg';
slack.api(
'chat.postMessage',
{ text: message, channel: channel, username: 'weatherbot', icon_url: icon_url },
function () {
console.log("Message sent to " + channel + ": " + message);
}
);
};
var weather = require('./weather');
weather.postWeatherMessages(postMessage);
| var Slack = require('slack-node');
apiToken = process.env.SLACK_TOKEN;
slack = new Slack(apiToken);
var channel = process.argv[2] ? "#"+process.argv[2] : '#kollegorna-ivan';
console.log(channel);
var postMessage = function (message) {
var icon_url = 'https://cdn.rawgit.com/kollegorna/weatherbot/master/bot.jpg';
slack.api(
'chat.postMessage',
{ text: message, channel: channel, username: 'weatherbot', icon_url: icon_url },
function () {
console.log("Message sent to " + channel + ": " + message);
}
);
};
var weather = require('./weather');
weather.postWeatherMessages(postMessage);
| Use Rawgit for the icon | Use Rawgit for the icon
| JavaScript | mit | kollegorna/weatherbot | ---
+++
@@ -7,7 +7,7 @@
console.log(channel);
var postMessage = function (message) {
- var icon_url = 'https://raw.githubusercontent.com/kollegorna/weatherbot/master/bot.jpg';
+ var icon_url = 'https://cdn.rawgit.com/kollegorna/weatherbot/master/bot.jpg';
slack.api(
'chat.postMessage',
{ text: message, channel: channel, username: 'weatherbot', icon_url: icon_url }, |
e01a9f024cf9a060c1fdf8a6f97e392bf5bf2414 | validators/forgotten.js | validators/forgotten.js | var ForgotValidator = Ember.Object.create({
check: function (model) {
var data = model.getProperties('email'),
validationErrors = [];
if (!validator.isEmail(data.email)) {
validationErrors.push({
message: 'Invalid Email'
});
}
return validationErrors;
}
});
export default ForgotValidator;
| var ForgotValidator = Ember.Object.create({
check: function (model) {
var data = model.getProperties('email'),
validationErrors = [];
if (!validator.isEmail(data.email)) {
validationErrors.push({
message: 'Invalid email address'
});
}
return validationErrors;
}
});
export default ForgotValidator;
| Update validation to match server error. | Update validation to match server error.
When a using the forgottenRoute if you enter an incorrectly formatted
email address you would see the error message 'Invalid Email', however
if you entered an email address that was correctly formatted but missing
the error message would be 'Invalid email address'.
This fixes the discrepancy.
| JavaScript | mit | kevinansfield/Ghost-Admin,dbalders/Ghost-Admin,TryGhost/Ghost-Admin,airycanon/Ghost-Admin,kevinansfield/Ghost-Admin,acburdine/Ghost-Admin,dbalders/Ghost-Admin,TryGhost/Ghost-Admin,airycanon/Ghost-Admin,acburdine/Ghost-Admin,JohnONolan/Ghost-Admin,JohnONolan/Ghost-Admin | ---
+++
@@ -5,7 +5,7 @@
if (!validator.isEmail(data.email)) {
validationErrors.push({
- message: 'Invalid Email'
+ message: 'Invalid email address'
});
}
|
2f2c6b69381473552c09f85823f245e9dc5eead9 | chrome/content/overlay.js | chrome/content/overlay.js | function startup() {
var myPanel = document.getElementById("my-panel");
myPanel.label = "Tor Enabled";
myPanel.style.color = "green";
}
function onClickHandler(event) {
switch(event.which) {
case 1:
alert("Torbutton for Thunderbird is currently enabled and is helping protect your anonymity.\n" +
"\nTo disable Torbutton, go to Tools > Add-ons.");
break;
}
}
window.addEventListener("load", startup, false);
| function startup() {
// Set the time zone to UTC.
var env = Components.classes["@mozilla.org/process/environment;1"].
getService(Components.interfaces.nsIEnvironment);
env.set('TZ', 'UTC');
var myPanel = document.getElementById("my-panel");
myPanel.label = "Tor Enabled";
myPanel.style.color = "green";
}
function onClickHandler(event) {
switch(event.which) {
case 1:
alert("Torbutton for Thunderbird is currently enabled and is helping protect your anonymity.\n" +
"\nTo disable Torbutton, go to Tools > Add-ons.");
break;
}
}
window.addEventListener("load", startup, false);
| Set time zone to UTC to prevent time zone leak | Set time zone to UTC to prevent time zone leak
| JavaScript | bsd-2-clause | DigiThinkIT/TorBirdy,ioerror/torbirdy,viggyprabhu/torbirdy,kartikm/torbirdy,DigiThinkIT/TorBirdy,infertux/torbirdy,u451f/torbirdy,u451f/torbirdy,kartikm/torbirdy,viggyprabhu/torbirdy,ioerror/torbirdy,infertux/torbirdy | ---
+++
@@ -1,4 +1,9 @@
function startup() {
+ // Set the time zone to UTC.
+ var env = Components.classes["@mozilla.org/process/environment;1"].
+ getService(Components.interfaces.nsIEnvironment);
+ env.set('TZ', 'UTC');
+
var myPanel = document.getElementById("my-panel");
myPanel.label = "Tor Enabled";
myPanel.style.color = "green"; |
13dae0065fa4b26ef2e8d445ba28bf7f48b00b67 | app/root.js | app/root.js | import React from 'react';
import { createStore, combineReducers, compose } from 'redux';
import { provide } from 'react-redux';
import * as reducers from './_reducers';
import { devTools, persistState } from 'redux-devtools';
import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';
import { Router } from 'react-router';
import BrowserHistory from 'react-router/lib/BrowserHistory';
import routes from './routes';
import LiveData from './_data/LiveData';
const finalCreateStore = compose(
devTools(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)),
createStore
);
const reducer = combineReducers(reducers);
const store = finalCreateStore(reducer);
function openDevTools() {
const win = window.open(null, 'redux-devtools', 'menubar=no,location=no,resizable=yes,scrollbars=no,status=no');
win.location.reload();
setTimeout(() => {
React.render(
<DebugPanel top right bottom left >
<DevTools store={store} monitor={LogMonitor} />
</DebugPanel>
, win.document.body);
}, 10);
}
@provide(store)
export default class Root extends React.Component {
render() {
const history = new BrowserHistory();
const liveData = new LiveData(store);
openDevTools();
liveData.init();
return (
<div>
<Router history={history} children={routes}/>
</div>
);
}
}
| import React from 'react';
import { createStore, combineReducers, compose } from 'redux';
import { Provider } from 'react-redux';
import * as reducers from './_reducers';
import { devTools, persistState } from 'redux-devtools';
import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';
import { Router } from 'react-router';
import BrowserHistory from 'react-router/lib/BrowserHistory';
import routes from './routes';
import LiveData from './_data/LiveData';
const finalCreateStore = compose(
devTools(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
)(createStore);
const reducer = combineReducers(reducers);
const store = finalCreateStore(reducer);
function openDevTools() {
const win = window.open(null, 'redux-devtools', 'menubar=no,location=no,resizable=yes,scrollbars=no,status=no');
win.location.reload();
setTimeout(() => {
React.render(
<DebugPanel top right bottom left >
<DevTools store={store} monitor={LogMonitor} />
</DebugPanel>
, win.document.body);
}, 10);
}
export default class Root extends React.Component {
render() {
const history = new BrowserHistory();
const liveData = new LiveData(store);
openDevTools();
liveData.init();
return (
<Provider store={store}>
{() => <Router history={history} children={routes}/>}
</Provider>
);
}
}
| Update redux to version 2.0 | Update redux to version 2.0
| JavaScript | mit | binary-com/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,qingweibinary/binary-next-gen,nuruddeensalihu/binary-next-gen,qingweibinary/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen,qingweibinary/binary-next-gen | ---
+++
@@ -1,6 +1,6 @@
import React from 'react';
import { createStore, combineReducers, compose } from 'redux';
-import { provide } from 'react-redux';
+import { Provider } from 'react-redux';
import * as reducers from './_reducers';
import { devTools, persistState } from 'redux-devtools';
import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react';
@@ -10,10 +10,9 @@
import LiveData from './_data/LiveData';
const finalCreateStore = compose(
- devTools(),
- persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)),
- createStore
-);
+ devTools(),
+ persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
+)(createStore);
const reducer = combineReducers(reducers);
const store = finalCreateStore(reducer);
@@ -31,7 +30,6 @@
}, 10);
}
-@provide(store)
export default class Root extends React.Component {
render() {
const history = new BrowserHistory();
@@ -39,9 +37,9 @@
openDevTools();
liveData.init();
return (
- <div>
- <Router history={history} children={routes}/>
- </div>
+ <Provider store={store}>
+ {() => <Router history={history} children={routes}/>}
+ </Provider>
);
}
} |
1c9c2763e16d9c176fab4a45616dbc8d4e5c02ac | app/adapters/employee.js | app/adapters/employee.js | import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'api',
// /**
// Get all employees from API
// @method download
// @return {Promise} resolves to `RecordArray`
// */
// findAll() {
// const empArray = {
// "employee": [
// {
// "id": 1,
// "externalId": 1,
// "firstName": "John",
// "lastName": "Owen",
// "position": "UI Developer",
// "team": "Mobile Team",
// "startDate": "12.05.2016",
// "birthDay": "05.08.1986"
// },
// {
// "id": 2,
// "externalId": 2,
// "firstName": "Michael",
// "lastName": "Carrick",
// "position": "UI Developer",
// "team": "Mobile Team",
// "startDate": "12.05.2016",
// "birthDay": "05.08.1986"
// },
// {
// "id": 3,
// "externalId": 3,
// "firstName": "David",
// "lastName": "Bradley",
// "position": "UI Developer",
// "team": "Mobile Team",
// "startDate": "12.05.2016",
// "birthDay": "05.08.1986"
// }
// ]
// };
// return empArray;
// },
findAll() {
const url = 'http://q1q1.eu/employees/employees/list';
return this.ajax(url);
}
});
| import DS from 'ember-data';
export default DS.RESTAdapter.extend({
// namespace: 'api',
host: 'http://q1q1.eu/employees/employees/list'
});
| Update adapter and default Ember calls | Update adapter and default Ember calls
| JavaScript | mit | msm-app-devs/intranet-app,msm-app-devs/intranet-app | ---
+++
@@ -1,55 +1,6 @@
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
- namespace: 'api',
-
- // /**
- // Get all employees from API
- // @method download
- // @return {Promise} resolves to `RecordArray`
- // */
- // findAll() {
- // const empArray = {
- // "employee": [
- // {
- // "id": 1,
- // "externalId": 1,
- // "firstName": "John",
- // "lastName": "Owen",
- // "position": "UI Developer",
- // "team": "Mobile Team",
- // "startDate": "12.05.2016",
- // "birthDay": "05.08.1986"
- // },
- // {
- // "id": 2,
- // "externalId": 2,
- // "firstName": "Michael",
- // "lastName": "Carrick",
- // "position": "UI Developer",
- // "team": "Mobile Team",
- // "startDate": "12.05.2016",
- // "birthDay": "05.08.1986"
- // },
- // {
- // "id": 3,
- // "externalId": 3,
- // "firstName": "David",
- // "lastName": "Bradley",
- // "position": "UI Developer",
- // "team": "Mobile Team",
- // "startDate": "12.05.2016",
- // "birthDay": "05.08.1986"
- // }
- // ]
- // };
-
- // return empArray;
- // },
-
- findAll() {
- const url = 'http://q1q1.eu/employees/employees/list';
-
- return this.ajax(url);
- }
+ // namespace: 'api',
+ host: 'http://q1q1.eu/employees/employees/list'
}); |
2679bf719318c6eeacbdf4fc8726f6129ebcda52 | repositories/ReleaseNotesRepository.js | repositories/ReleaseNotesRepository.js | 'use strict';
const BaseRepository = require('@gfcc/mongo-tenant-repository/BaseRepository');
class ReleaseNotesRepository extends BaseRepository {
getSchemaDefinition() {
const MixedType = this.getSchemaTypes().Mixed;
return {
scope: { type: String, 'default': 'global', required: true },
name: { type: String, required: true },
ownerAccountId: String,
title: String,
description: String,
releases: [{
version: String,
date: Date,
title: String,
description: String,
added: [MixedType],
removed: [MixedType],
changed: [MixedType],
improved: [MixedType],
deprecated: [MixedType],
fixed: [MixedType],
secured: [MixedType],
}]
};
}
applySchemaPlugins(schema) {
super.applySchemaPlugins(schema);
schema.index({ scope: 1, name: 1 }, { unique: true });
return this;
}
findOneByScopeAndName(scope, name, callback) {
this.findOne({
scope: scope,
name: name
}, callback);
return this;
}
findAllByScope(scope, callback) {
this.find({
scope: scope
}, callback);
return this;
}
}
module.exports = ReleaseNotesRepository;
| 'use strict';
const BaseRepository = require('@gfcc/mongo-tenant-repository/BaseRepository');
class ReleaseNotesRepository extends BaseRepository {
getSchemaDefinition() {
const MixedType = this.getSchemaTypes().Mixed;
return {
scope: { type: String, 'default': 'global', required: true },
name: { type: String, required: true },
ownerAccountId: String,
title: String,
description: String,
releases: [{
version: String,
date: Date,
title: String,
description: String,
added: [MixedType],
removed: [MixedType],
changed: [MixedType],
improved: [MixedType],
deprecated: [MixedType],
fixed: [MixedType],
secured: [MixedType],
}]
};
}
applySchemaPlugins(schema) {
super.applySchemaPlugins(schema);
schema.index({ scope: 1, name: 1 }, { unique: true });
return this;
}
findOneByScopeAndName(scope, name, callback) {
this.findOne({
scope: scope,
name: name
}, callback);
return this;
}
findAllByScope(scope, callback) {
this.find({
scope: scope
}, callback);
return this;
}
/**
* Retrieve a list of the nth newest release notes.
*
* @param {number} count
* @param {function} callback
*/
findNewest(count, callback) {
this.findList({}, {
limit: count,
sort: {
createdAt: -1
}
}, (err, releaseNotesList) => {
if (err) {
return void callback(err);
}
return void callback(null, releaseNotesList.items);
});
}
}
module.exports = ReleaseNotesRepository;
| Add support for retrieving a list of the latest release notes entries. | Add support for retrieving a list of the latest release notes entries.
| JavaScript | mit | release-notes/release-notes-hub,release-notes/release-notes-hub | ---
+++
@@ -53,6 +53,27 @@
return this;
}
+
+ /**
+ * Retrieve a list of the nth newest release notes.
+ *
+ * @param {number} count
+ * @param {function} callback
+ */
+ findNewest(count, callback) {
+ this.findList({}, {
+ limit: count,
+ sort: {
+ createdAt: -1
+ }
+ }, (err, releaseNotesList) => {
+ if (err) {
+ return void callback(err);
+ }
+
+ return void callback(null, releaseNotesList.items);
+ });
+ }
}
module.exports = ReleaseNotesRepository; |
82fa80d83d69ef63d7f1642234d88c75b8d026c6 | .prettierrc.js | .prettierrc.js | // This file is here, in part, so that users whose code editors are
// set to automatically format files with Prettier have a config to detect.
// Many users only run Prettier when a config is present, so this file makes
// sure one can be detected, even though we aren't doing anything with it.
module.exports = {
...require( '@wordpress/prettier-config' ),
};
| /**
* Provides API functions to create a datastore for notifications.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.
*/
// This file is here, in part, so that users whose code editors are
// set to automatically format files with Prettier have a config to detect.
// Many users only run Prettier when a config is present, so this file makes
// sure one can be detected, even though we aren't doing anything with it.
module.exports = {
...require( '@wordpress/prettier-config' ),
};
| Add header to Prettier RC file. | Add header to Prettier RC file.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -1,3 +1,21 @@
+/**
+ * Provides API functions to create a datastore for notifications.
+ *
+ * Site Kit by Google, Copyright 2021 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://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.
+ */
+
// This file is here, in part, so that users whose code editors are
// set to automatically format files with Prettier have a config to detect.
// Many users only run Prettier when a config is present, so this file makes |
2ae2e456c3cdfce40640e8b6827b43c733e09393 | input/composites/_observable.js | input/composites/_observable.js | 'use strict';
var noop = require('es5-ext/function/noop')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
, DOMInput = require('../_composite')
, getPrototypeOf = Object.getPrototypeOf
, getInputValue = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'inputValue').get
, Input;
module.exports = Input = function (document, type/*, options*/) {
var options = arguments[2], fn, proto;
this.type = type;
options = this._resolveOptions(options);
options.dbOptions = Object(options.dbOptions);
proto = options.dbOptions;
fn = proto._value_;
while ((fn !== undefined) && (typeof fn !== 'function')) {
proto = getPrototypeOf(proto);
fn = proto._value_;
}
this.getValue = callable(fn);
DOMInput.call(this, document, type, options);
};
Input.prototype = Object.create(DOMInput.prototype, {
constructor: d(Input),
name: d.gs(noop, noop),
inputValue: d.gs(function () {
var state = getInputValue.call(this);
return this.getValue.call(state);
}, noop)
});
| 'use strict';
var last = require('es5-ext/array/#/last')
, noop = require('es5-ext/function/noop')
, mapKeys = require('es5-ext/object/map-keys')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
, splitId = require('dbjs/_setup/unserialize/id')
, DOMInput = require('../_composite')
, getPrototypeOf = Object.getPrototypeOf
, getInputValue = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'inputValue').get
, mapKey = function (id) { return last.call(splitId(id)); }
, Input;
module.exports = Input = function (document, type/*, options*/) {
var options = arguments[2], fn, proto;
this.type = type;
options = this._resolveOptions(options);
options.dbOptions = Object(options.dbOptions);
proto = options.dbOptions;
fn = proto._value_;
while ((fn !== undefined) && (typeof fn !== 'function')) {
proto = getPrototypeOf(proto);
fn = proto._value_;
}
this.getValue = callable(fn);
DOMInput.call(this, document, type, options);
};
Input.prototype = Object.create(DOMInput.prototype, {
constructor: d(Input),
name: d.gs(noop, noop),
inputValue: d.gs(function () {
var state = mapKeys(getInputValue.call(this), mapKey);
return this.getValue.call(state);
}, noop)
});
| Fix resolution of value in composites | Fix resolution of value in composites
| JavaScript | mit | medikoo/dbjs-dom | ---
+++
@@ -1,12 +1,16 @@
'use strict';
-var noop = require('es5-ext/function/noop')
+var last = require('es5-ext/array/#/last')
+ , noop = require('es5-ext/function/noop')
+ , mapKeys = require('es5-ext/object/map-keys')
, callable = require('es5-ext/object/valid-callable')
, d = require('d')
+ , splitId = require('dbjs/_setup/unserialize/id')
, DOMInput = require('../_composite')
, getPrototypeOf = Object.getPrototypeOf
, getInputValue = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'inputValue').get
+ , mapKey = function (id) { return last.call(splitId(id)); }
, Input;
module.exports = Input = function (document, type/*, options*/) {
@@ -28,7 +32,7 @@
constructor: d(Input),
name: d.gs(noop, noop),
inputValue: d.gs(function () {
- var state = getInputValue.call(this);
+ var state = mapKeys(getInputValue.call(this), mapKey);
return this.getValue.call(state);
}, noop)
}); |
343eb4ac8db46106418cb60d820d6ec33990e07e | source/main/menus/osx.js | source/main/menus/osx.js | export const osxMenu = (app, window, openAbout) => (
[{
label: 'Daedalus',
submenu: [{
label: 'About',
click() {
openAbout();
},
}, {
label: 'Quit',
accelerator: 'Command+Q',
click: () => app.quit()
}]
}, {
label: 'Edit',
submenu: [{
label: 'Undo',
accelerator: 'Command+Z',
selector: 'undo:'
}, {
label: 'Redo',
accelerator: 'Shift+Command+Z',
selector: 'redo:'
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: 'Command+X',
selector: 'cut:'
}, {
label: 'Copy',
accelerator: 'Command+C',
selector: 'copy:'
}, {
label: 'Paste',
accelerator: 'Command+V',
selector: 'paste:'
}, {
label: 'Select All',
accelerator: 'Command+A',
selector: 'selectAll:'
}]
}, {
label: 'View',
submenu: [
{
label: 'Reload',
accelerator: 'Command+R',
click: () => window.webContents.reload()
},
{
label: 'Toggle Full Screen',
accelerator: 'Ctrl+Command+F',
click: () => window.setFullScreen(!window.isFullScreen())
},
{
label: 'Toggle Developer Tools',
accelerator: 'Alt+Command+I',
click: () => window.toggleDevTools()
}
]
}]
);
| export const osxMenu = (app, window, openAbout) => (
[{
label: 'Daedalus',
submenu: [{
label: 'About',
click() {
openAbout();
},
}, {
label: 'Quit',
accelerator: 'Command+Q',
click: () => app.quit()
}]
}, {
label: 'Edit',
submenu: [{
label: 'Undo',
accelerator: 'Command+Z',
role: 'undo'
}, {
label: 'Redo',
accelerator: 'Shift+Command+Z',
role: 'redo'
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: 'Command+X',
role: 'cut'
}, {
label: 'Copy',
accelerator: 'Command+C',
role: 'copy'
}, {
label: 'Paste',
accelerator: 'Command+V',
role: 'paste'
}, {
label: 'Select All',
accelerator: 'Command+A',
role: 'selectall'
}]
}, {
label: 'View',
submenu: [
{
label: 'Reload',
accelerator: 'Command+R',
click: () => window.webContents.reload()
},
{
label: 'Toggle Full Screen',
accelerator: 'Ctrl+Command+F',
click: () => window.setFullScreen(!window.isFullScreen())
},
{
label: 'Toggle Developer Tools',
accelerator: 'Alt+Command+I',
click: () => window.toggleDevTools()
}
]
}]
);
| Use role instead of selector in macOS menu | [DDW-160] Use role instead of selector in macOS menu
| 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 | ---
+++
@@ -16,29 +16,29 @@
submenu: [{
label: 'Undo',
accelerator: 'Command+Z',
- selector: 'undo:'
+ role: 'undo'
}, {
label: 'Redo',
accelerator: 'Shift+Command+Z',
- selector: 'redo:'
+ role: 'redo'
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: 'Command+X',
- selector: 'cut:'
+ role: 'cut'
}, {
label: 'Copy',
accelerator: 'Command+C',
- selector: 'copy:'
+ role: 'copy'
}, {
label: 'Paste',
accelerator: 'Command+V',
- selector: 'paste:'
+ role: 'paste'
}, {
label: 'Select All',
accelerator: 'Command+A',
- selector: 'selectAll:'
+ role: 'selectall'
}]
}, {
label: 'View', |
dcc5abe8709cf7ec9dfd0a30ed187d79b801e9a1 | extension/src/json-viewer/check-if-json.js | extension/src/json-viewer/check-if-json.js | var extractJSON = require('./extract-json');
function getPreWithSource() {
var childNodes = document.body.childNodes;
var pre = childNodes[0];
if (childNodes.length === 1 && pre.tagName === "PRE") return pre
return null
}
function isJSON(jsonStr) {
var str = jsonStr;
if (!str || str.length === 0) return false
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '')
return (/^[\],:{}\s]*$/).test(str)
}
function isJSONP(jsonStr) {
return isJSON(extractJSON(jsonStr));
}
function checkIfJson(sucessCallback, element) {
var pre = element || getPreWithSource();
if (pre !== null &&
pre !== undefined &&
(isJSON(pre.textContent) || isJSONP(pre.textContent))) {
sucessCallback(pre);
}
}
module.exports = checkIfJson;
| var extractJSON = require('./extract-json');
function getPreWithSource() {
var childNodes = document.body.childNodes;
if (childNodes.length === 1) {
var childNode = childNodes[0];
if (childNode.nodeName === "PRE") {
return childNode;
} else if (childNode.nodeName === "#text") { // if Content-Type is text/html
var pre = document.createElement("pre");
pre.textContent = childNode.textContent;
document.body.removeChild(childNode);
document.body.appendChild(pre);
return pre;
}
}
return null
}
function isJSON(jsonStr) {
var str = jsonStr;
if (!str || str.length === 0) return false
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '')
return (/^[\],:{}\s]*$/).test(str)
}
function isJSONP(jsonStr) {
return isJSON(extractJSON(jsonStr));
}
function checkIfJson(sucessCallback, element) {
var pre = element || getPreWithSource();
if (pre !== null &&
pre !== undefined &&
(isJSON(pre.textContent) || isJSONP(pre.textContent))) {
sucessCallback(pre);
}
}
module.exports = checkIfJson;
| Make it work if the content-type is text/html | Make it work if the content-type is text/html
| JavaScript | mit | tulios/json-viewer,tulios/json-viewer | ---
+++
@@ -2,29 +2,44 @@
function getPreWithSource() {
var childNodes = document.body.childNodes;
- var pre = childNodes[0];
- if (childNodes.length === 1 && pre.tagName === "PRE") return pre
+
+ if (childNodes.length === 1) {
+
+ var childNode = childNodes[0];
+
+ if (childNode.nodeName === "PRE") {
+ return childNode;
+ } else if (childNode.nodeName === "#text") { // if Content-Type is text/html
+ var pre = document.createElement("pre");
+ pre.textContent = childNode.textContent;
+ document.body.removeChild(childNode);
+ document.body.appendChild(pre);
+ return pre;
+ }
+
+ }
+
return null
}
function isJSON(jsonStr) {
- var str = jsonStr;
- if (!str || str.length === 0) return false
- str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
- str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
- str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '')
- return (/^[\],:{}\s]*$/).test(str)
- }
+ var str = jsonStr;
+ if (!str || str.length === 0) return false
+ str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
+ str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
+ str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '')
+ return (/^[\],:{}\s]*$/).test(str)
+}
- function isJSONP(jsonStr) {
- return isJSON(extractJSON(jsonStr));
- }
+function isJSONP(jsonStr) {
+ return isJSON(extractJSON(jsonStr));
+}
function checkIfJson(sucessCallback, element) {
var pre = element || getPreWithSource();
if (pre !== null &&
- pre !== undefined &&
- (isJSON(pre.textContent) || isJSONP(pre.textContent))) {
+ pre !== undefined &&
+ (isJSON(pre.textContent) || isJSONP(pre.textContent))) {
sucessCallback(pre);
}
} |
d0797bff3ff553a701f775e1925e576563690ae7 | addon/services/portal.js | addon/services/portal.js | import Service from 'ember-service';
import { scheduleOnce } from 'ember-runloop';
import Ember from 'ember';
const ADDED_QUEUE = Ember.A();
const REMOVED_QUEUE = Ember.A();
export default Service.extend({
portals: null,
init() {
this._super(...arguments);
this.set("portals", {});
},
itemsFor(name) {
const portals = this.get("portals");
let items = portals[name];
if (!items) {
items = Ember.A();
portals[name] = items;
}
return items;
},
addPortalContent(name, component) {
if (this.addToQueueInReverse()) {
ADDED_QUEUE.unshift({ name, component });
} else {
ADDED_QUEUE.push({ name, component });
}
scheduleOnce("afterRender", this, this.flushPortalContent);
},
// run after render to avoid warning that items were modified on didInsertElement hook
flushPortalContent() {
ADDED_QUEUE.forEach(({name, component}) => {
this.itemsFor(name).pushObject(component);
});
ADDED_QUEUE.clear();
REMOVED_QUEUE.forEach(({name, component}) => {
this.itemsFor(name).removeObject(component);
});
REMOVED_QUEUE.clear();
},
removePortalContent(name, component) {
REMOVED_QUEUE.push({name, component});
scheduleOnce("afterRender", this, this.flushPortalContent);
},
// prior to 1.13.x components are inserted in reverse order
addToQueueInReverse() {
const [maj, min] = Ember.VERSION.split('.').map(i => parseInt(i, null));
return maj === 1 && min < 13;
}
});
| import Service from 'ember-service';
import { scheduleOnce } from 'ember-runloop';
import Ember from 'ember';
const ADDED_QUEUE = Ember.A();
const REMOVED_QUEUE = Ember.A();
export default Service.extend({
portals: null,
init() {
this._super(...arguments);
this.set("portals", {});
},
itemsFor(name) {
const portals = this.get("portals");
let items = portals[name];
if (!items) {
items = Ember.A();
portals[name] = items;
}
return items;
},
addPortalContent(name, component) {
scheduleOnce("afterRender", this, this.flushPortalContent);
},
// run after render to avoid warning that items were modified on didInsertElement hook
flushPortalContent() {
ADDED_QUEUE.forEach(({name, component}) => {
this.itemsFor(name).pushObject(component);
});
ADDED_QUEUE.clear();
REMOVED_QUEUE.forEach(({name, component}) => {
this.itemsFor(name).removeObject(component);
});
REMOVED_QUEUE.clear();
},
removePortalContent(name, component) {
REMOVED_QUEUE.push({name, component});
scheduleOnce("afterRender", this, this.flushPortalContent);
}
});
| Remove support for Ember 1.13.x | Remove support for Ember 1.13.x | JavaScript | mit | minutebase/ember-portal,minutebase/ember-portal | ---
+++
@@ -24,12 +24,6 @@
},
addPortalContent(name, component) {
- if (this.addToQueueInReverse()) {
- ADDED_QUEUE.unshift({ name, component });
- } else {
- ADDED_QUEUE.push({ name, component });
- }
-
scheduleOnce("afterRender", this, this.flushPortalContent);
},
@@ -49,11 +43,5 @@
removePortalContent(name, component) {
REMOVED_QUEUE.push({name, component});
scheduleOnce("afterRender", this, this.flushPortalContent);
- },
-
- // prior to 1.13.x components are inserted in reverse order
- addToQueueInReverse() {
- const [maj, min] = Ember.VERSION.split('.').map(i => parseInt(i, null));
- return maj === 1 && min < 13;
}
}); |
a6971d097a2362f091a598a4b0443f3f76ddf443 | app/beautification.js | app/beautification.js | const $ = require('jquery');
fateBus.subscribe(module, 'fate.init', function() {
GM_addStyle(GM_getResourceText('fateOfAllFoolsCSS'));
});
// Remove the subclass icons
fateBus.subscribe(module, 'fate.refresh', function() {
$('[title~="Subclass"]').parents('.store-row').siblings('.title:contains(Weapons)').siblings('.store-row:eq(0)').attr('style', 'display:none');
});
// Remove the "Weapons" title bar
fateBus.subscribe(module, 'fate.refresh', function() {
$('[title~="Subclass"]').parents('.store-row').siblings('.title:contains(Weapons)').attr('style', 'display:none');
});
| const $ = require('jquery');
fateBus.subscribe(module, 'fate.init', function() {
GM_addStyle(GM_getResourceText('fateOfAllFoolsCSS'));
});
// Remove the subclass icons
fateBus.subscribe(module, 'fate.refresh', function() {
// AFAIK this is a serial number that shouldn't change between versions...?
$('.bucket-3284755031').parents('.store-row').attr('style', 'display:none');
});
// Remove the "Weapons" title bar
fateBus.subscribe(module, 'fate.refresh', function() {
$('.inventory-title:contains("Weapons")').attr('style', 'display:none');
});
| Remove the weapons section title and the subclass icons | Remove the weapons section title and the subclass icons
| JavaScript | mit | rslifka/fate_of_all_fools,rslifka/fate_of_all_fools | ---
+++
@@ -6,10 +6,11 @@
// Remove the subclass icons
fateBus.subscribe(module, 'fate.refresh', function() {
- $('[title~="Subclass"]').parents('.store-row').siblings('.title:contains(Weapons)').siblings('.store-row:eq(0)').attr('style', 'display:none');
+ // AFAIK this is a serial number that shouldn't change between versions...?
+ $('.bucket-3284755031').parents('.store-row').attr('style', 'display:none');
});
// Remove the "Weapons" title bar
fateBus.subscribe(module, 'fate.refresh', function() {
- $('[title~="Subclass"]').parents('.store-row').siblings('.title:contains(Weapons)').attr('style', 'display:none');
+ $('.inventory-title:contains("Weapons")').attr('style', 'display:none');
}); |
a75fc69d414f94a2ebf1d5762a1e5f5c4e6fe43f | commands/help_commands.js | commands/help_commands.js |
module.exports = {
help: (message, config) => {
const p = config.prefix;
message.channel.send(
`\`\`\`diff
++ MUSIC COMMANDS ++
${p}play URL - Plays a song at a YouTube URL.
${p}stop - Interrupts the current song.
${p}queue - Says the current queue.
${p}pleasestop - Clears the queue and interrupts the current song.
${p}clearqueue - Clears the queue.
${p}volume - Displays the volume.
${p}volumeshift n - Shifts the volume by n%. (Negative numbers can be used to decrease volume).
++ TESTING COMMANDS ++
${p}ping - Says "pong."
${p}echo text - Repeats whatever text is given.
++ RANDOMNESS COMMANDS ++
${p}coin - Says heads or tails.
${p}dice n - Says a random number between 1 and n. 6 is the default.
${p}factcheck fact - Uses advanced neural networks and quantum bubble extrapolation to calculate a fact's veracity. If no fact is provided, it will give a more general statement about the command user.
++ MISC. COMMANDS ++
${p}effify text - Effifies some text.
\`\`\``);
},
};
|
module.exports = {
help: (message, config) => {
const p = config.prefix;
message.channel.send(
`\`\`\`diff
++ MUSIC COMMANDS ++
${p}play URL - Plays a song at a YouTube URL.
${p}stop - Interrupts the current song.
${p}queue - Says the current queue.
${p}clearqueue - Clears the queue.
${p}pleasestop - Clears the queue and interrupts the current song.
${p}togglepause - Pauses (or resumes) the current stream.
${p}volume - Displays the volume.
${p}volumeshift n - Shifts the volume by n%. (Negative numbers can be used to decrease volume).
++ TESTING COMMANDS ++
${p}ping - Says "pong."
${p}echo text - Repeats whatever text is given.
++ RANDOMNESS COMMANDS ++
${p}coin - Says heads or tails.
${p}dice n - Says a random number between 1 and n. 6 is the default.
${p}factcheck fact - Uses advanced neural networks and quantum bubble extrapolation to calculate a fact's veracity. If no fact is provided, it will give a more general statement about the command user.
++ MISC. COMMANDS ++
${p}effify text - Effifies some text.
\`\`\``);
},
};
| Add togglepause command documentation and change command order | Add togglepause command documentation and change command order
| JavaScript | mit | Rafer45/soup | ---
+++
@@ -8,8 +8,9 @@
${p}play URL - Plays a song at a YouTube URL.
${p}stop - Interrupts the current song.
${p}queue - Says the current queue.
+${p}clearqueue - Clears the queue.
${p}pleasestop - Clears the queue and interrupts the current song.
-${p}clearqueue - Clears the queue.
+${p}togglepause - Pauses (or resumes) the current stream.
${p}volume - Displays the volume.
${p}volumeshift n - Shifts the volume by n%. (Negative numbers can be used to decrease volume).
|
1ece057bddc68153a3e1d5984f513497aa476d27 | app/controllers/index.js | app/controllers/index.js | // Opening the first window and controller
Alloy.Globals.openWindow(Alloy.Globals.menuOptions[0]);
// From the slide-menu widget trigger this event to open every menu section
Ti.App.addEventListener('openSection', function(option) {
if (option.first) {
Alloy.Globals.navcontroller.home();
} else {
Alloy.Globals.openWindow(option);
}
Ti.App.fireEvent('toggleSlide'); // this one is to close the slide menu
});
Ti.App.addEventListener('goToHome', function() {
Alloy.Globals.navcontroller.home();
});
| // Opening the first window and controller
Alloy.Globals.openWindow(Alloy.Globals.menuOptions[0]);
// From the slide-menu widget trigger this event to open every menu section
Ti.App.addEventListener('openSection', function(option) {
Ti.App.fireEvent('toggleSlide'); // this one is to close the slide menu
if (option.first) {
Alloy.Globals.navcontroller.home();
} else {
Alloy.Globals.openWindow(option);
}
});
Ti.App.addEventListener('goToHome', function() {
Alloy.Globals.navcontroller.home();
});
| Fix the duplicated toggleSlide event | Fix the duplicated toggleSlide event
| JavaScript | apache-2.0 | dotCMS/dotcms-mobile-app,dotCMS/dotcms-mobile-app | ---
+++
@@ -3,12 +3,13 @@
// From the slide-menu widget trigger this event to open every menu section
Ti.App.addEventListener('openSection', function(option) {
+ Ti.App.fireEvent('toggleSlide'); // this one is to close the slide menu
+
if (option.first) {
Alloy.Globals.navcontroller.home();
} else {
Alloy.Globals.openWindow(option);
}
- Ti.App.fireEvent('toggleSlide'); // this one is to close the slide menu
});
Ti.App.addEventListener('goToHome', function() { |
9a25d927548fe618d2e0f4b7294185c61fe8bf7a | app/js/controllers.js | app/js/controllers.js | 'use strict';
/* Controllers */
var cvAppControllers = angular.module('cvAppControllers', []);
cvAppControllers.controller('HomeController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
cvAppControllers.controller('AboutController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
/*
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
*/ | 'use strict';
/* Controllers */
var cvAppControllers = angular.module('cvAppControllers', []);
cvAppControllers.controller('HomeController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
/*
cvAppControllers.controller('AboutController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
*/
/*
phonecatApp.controller('PhoneListCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
}]);
*/ | Add correct tutorial controller (commented) | Add correct tutorial controller (commented)
| JavaScript | mit | RegularSvensson/cvApp,RegularSvensson/cvApp | ---
+++
@@ -8,17 +8,20 @@
$scope.name = 'Elias';
}]);
+
+
+/*
cvAppControllers.controller('AboutController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
-
+*/
/*
-phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
- $http.get('phones/phones.json').success(function(data) {
- $scope.phones = data;
- });
-
- $scope.orderProp = 'age';
-});
+phonecatApp.controller('PhoneListCtrl', ['$scope', '$http',
+ function ($scope, $http) {
+ $http.get('phones/phones.json').success(function(data) {
+ $scope.phones = data;
+ });
+ $scope.orderProp = 'age';
+ }]);
*/ |
19c3a5c0232f140b00cad1261c0d40823e003d87 | ghost/admin/routes/settings/users/index.js | ghost/admin/routes/settings/users/index.js | import AuthenticatedRoute from 'ghost/routes/authenticated';
import PaginationRouteMixin from 'ghost/mixins/pagination-route';
import styleBody from 'ghost/mixins/style-body';
var paginationSettings,
UsersIndexRoute;
paginationSettings = {
page: 1,
limit: 20,
status: 'active'
};
UsersIndexRoute = AuthenticatedRoute.extend(styleBody, PaginationRouteMixin, {
classNames: ['settings-view-users'],
setupController: function (controller, model) {
this._super(controller, model);
this.setupPagination(paginationSettings);
},
model: function () {
var self = this;
return self.store.find('user', {limit: 'all', status: 'invited'}).then(function () {
return self.store.find('user', 'me').then(function (currentUser) {
if (currentUser.get('isEditor')) {
// Editors only see authors in the list
paginationSettings.role = 'Author';
}
return self.store.filter('user', paginationSettings, function (user) {
if (currentUser.get('isEditor')) {
return user.get('isAuthor');
}
return true;
});
});
});
},
actions: {
reload: function () {
this.refresh();
}
}
});
export default UsersIndexRoute;
| import AuthenticatedRoute from 'ghost/routes/authenticated';
import PaginationRouteMixin from 'ghost/mixins/pagination-route';
import styleBody from 'ghost/mixins/style-body';
var paginationSettings,
UsersIndexRoute;
paginationSettings = {
page: 1,
limit: 20,
status: 'active'
};
UsersIndexRoute = AuthenticatedRoute.extend(styleBody, PaginationRouteMixin, {
classNames: ['settings-view-users'],
setupController: function (controller, model) {
this._super(controller, model);
this.setupPagination(paginationSettings);
},
model: function () {
var self = this;
return self.store.find('user', {limit: 'all', status: 'invited'}).then(function () {
return self.store.find('user', 'me').then(function (currentUser) {
if (currentUser.get('isEditor')) {
// Editors only see authors in the list
paginationSettings.role = 'Author';
}
return self.store.filter('user', paginationSettings, function (user) {
if (currentUser.get('isEditor')) {
return user.get('isAuthor') || user === currentUser;
}
return true;
});
});
});
},
actions: {
reload: function () {
this.refresh();
}
}
});
export default UsersIndexRoute;
| Add self to list of filtered users for editors | Add self to list of filtered users for editors
Closes #4412
| JavaScript | mit | TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost | ---
+++
@@ -31,7 +31,7 @@
return self.store.filter('user', paginationSettings, function (user) {
if (currentUser.get('isEditor')) {
- return user.get('isAuthor');
+ return user.get('isAuthor') || user === currentUser;
}
return true;
}); |
27cad60ff3ec93e202e54fb1831a3254f70c3753 | app/routes.js | app/routes.js | module.exports = {
bind : function (app) {
app.get('/', function (req, res) {
res.render('index');
});
// demo URL - essentially describing what the URL structure could be
app.get('/property/PL20_7HE/25_UNDERWAYS_YELVERTON', function (req, res) {
res.render('property-page/demo/index');
});
}
};
| module.exports = {
bind : function (app) {
app.get('/', function (req, res) {
res.render('index');
});
// demo URL - essentially describing what the URL structure could be
app.get('/property/PL20_7HE/25_UNDERWAYS_YELVERTON', function (req, res) {
res.render('property-page/demo/index');
});
// Prepopulate email field in Create account screen (v7)
app.get('/digital-register/journeys/v7/create-account', function(req, res) {
res.render('digital-register/journeys/v7/create-account', {'email' : req.query.email});
});
}
};
| Add a route to carry email address into next form page | Add a route to carry email address into next form page
| JavaScript | mit | LandRegistry/property-page-html-prototypes,LandRegistry/property-page-html-prototypes | ---
+++
@@ -10,5 +10,10 @@
res.render('property-page/demo/index');
});
+ // Prepopulate email field in Create account screen (v7)
+ app.get('/digital-register/journeys/v7/create-account', function(req, res) {
+ res.render('digital-register/journeys/v7/create-account', {'email' : req.query.email});
+ });
+
}
}; |
515ed2eec3ee0549baae9883a66b7247ef5d482b | lib/compatipede.js | lib/compatipede.js | "use strict";
let jobModel, campaignModel, tabSequence, serialExecutor, args,
JobModel = require('./models/job'),
CampaignModel = require('./models/campaign'),
TabSequence = require('./tabSequence'),
SerialExecutor = require('./serialExecutor'),
logger = require('./logger')('compatipede'),
async = require('async');
module.exports = function(argv) {
let dbSettings = {
host : argv.couchdbHost,
port : argv.couchdbPort,
auth : {
username : argv.couchdbUser,
password : argv.couchdbPassword
}
};
args = argv;
jobModel = new JobModel(dbSettings, argv.jobsDb);
campaignModel = new CampaignModel(dbSettings, argv.campaignDb);
tabSequence = new TabSequence(argv.masterUrl);
serialExecutor = new SerialExecutor(argv.processId, jobModel,
campaignModel, tabSequence);
jobModel.once('ready', ready);
campaignModel.once('ready', ready);
};
let readyCnt = 0;
function ready() {
readyCnt += 1;
if(readyCnt !== 2) {
return;
}
execute();
}
function execute() {
async.series([
// require('./githubDispatcher').bind(null, args),
serialExecutor.loop.bind(serialExecutor)
], (error) => {
if(error) {
logger.error('execute', 'Failed to do loop', error);
throw error;
}
process.exit(0);
});
}
| "use strict";
let jobModel, campaignModel, tabSequence, serialExecutor, args,
JobModel = require('./models/job'),
CampaignModel = require('./models/campaign'),
TabSequence = require('./tabSequence'),
SerialExecutor = require('./serialExecutor'),
logger = require('./logger')('compatipede'),
async = require('async');
module.exports = function(argv) {
let dbSettings = {
host : argv.couchdbHost,
port : argv.couchdbPort,
auth : {
username : argv.couchdbUser,
password : argv.couchdbPassword
}
};
args = argv;
jobModel = new JobModel(dbSettings, argv.jobsDb);
campaignModel = new CampaignModel(dbSettings, argv.campaignDb);
tabSequence = new TabSequence(argv.masterUrl);
serialExecutor = new SerialExecutor(argv.processId, jobModel,
campaignModel, tabSequence);
jobModel.once('ready', ready);
campaignModel.once('ready', ready);
};
let readyCnt = 0;
function ready() {
readyCnt += 1;
if(readyCnt !== 2) {
return;
}
execute();
}
function execute() {
async.series([
require('./githubDispatcher').bind(null, args),
serialExecutor.loop.bind(serialExecutor)
], (error) => {
if(error) {
logger.error('execute', 'Failed to do loop', error);
throw error;
}
process.exit(0);
});
}
| Fix - read github issues | Fix - read github issues
| JavaScript | mpl-2.0 | mozilla/compatipede,mozilla/compatipede,mozilla/compatipede | ---
+++
@@ -44,7 +44,7 @@
function execute() {
async.series([
- // require('./githubDispatcher').bind(null, args),
+ require('./githubDispatcher').bind(null, args),
serialExecutor.loop.bind(serialExecutor)
], (error) => {
if(error) { |
7545e8064f5bcd05dfeefa446abe4529a4720cb6 | src/index.js | src/index.js | import titleScreen from 'titlescreen';
import Scene from 'scene';
import state from 'state';
import loop from 'loop';
import { updateInputs } from 'controls';
import { render } from 'ui';
import { clear } from 'pura/canvas/tuple';
import Atarify from 'shader';
Scene(titleScreen);
loop((dt) => {
clear();
state.logic && state.logic();
render(dt);
Atarify();
updateInputs();
});
| import titleScreen from 'titlescreen';
import Scene from 'scene';
import state from 'state';
import loop from 'loop';
import { updateInputs } from 'controls';
import { render } from 'ui';
import { clear } from 'pura/canvas/tuple';
Scene(titleScreen);
loop((dt) => {
clear();
state.logic && state.logic();
render(dt);
updateInputs();
});
| Remove Atari shader until it can be optimized. | Remove Atari shader until it can be optimized.
| JavaScript | mit | HyphnKnight/js13k-2017,HyphnKnight/js13k-2017 | ---
+++
@@ -5,7 +5,6 @@
import { updateInputs } from 'controls';
import { render } from 'ui';
import { clear } from 'pura/canvas/tuple';
-import Atarify from 'shader';
Scene(titleScreen);
@@ -13,6 +12,5 @@
clear();
state.logic && state.logic();
render(dt);
- Atarify();
updateInputs();
}); |
26776afeb2568ea1a930b3d7d30141015c28aa57 | localization/jquery-ui-timepicker-ru.js | localization/jquery-ui-timepicker-ru.js | /* Russian translation for the jQuery Timepicker Addon */
/* Written by Trent Richardson */
(function($) {
$.timepicker.regional['ru'] = {
timeOnlyTitle: 'Выберите время',
timeText: 'Время',
hourText: 'Часы',
minuteText: 'Минуты',
secondText: 'Секунды',
millisecText: 'Миллисекунды',
timezoneText: 'Время зоны',
currentText: 'Теперь',
closeText: 'Закрыть',
timeFormat: 'hh:mm tt',
amNames: ['AM', 'A'],
pmNames: ['PM', 'P'],
ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['ru']);
})(jQuery);
| /* Russian translation for the jQuery Timepicker Addon */
/* Written by Trent Richardson */
(function($) {
$.timepicker.regional['ru'] = {
timeOnlyTitle: 'Выберите время',
timeText: 'Время',
hourText: 'Часы',
minuteText: 'Минуты',
secondText: 'Секунды',
millisecText: 'Миллисекунды',
timezoneText: 'Часовой пояс',
currentText: 'Сейчас',
closeText: 'Закрыть',
timeFormat: 'hh:mm tt',
amNames: ['AM', 'A'],
pmNames: ['PM', 'P'],
ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['ru']);
})(jQuery);
| Update Russian translation by Sanek | Update Russian translation by Sanek
| JavaScript | mit | nicofrand/jQuery-Timepicker-Addon,ssyang0102/jQuery-Timepicker-Addon,trentrichardson/jQuery-Timepicker-Addon,gaissa/jQuery-Timepicker-Addon,ristovskiv/jQuery-Timepicker-Addon,ssyang0102/jQuery-Timepicker-Addon,nicofrand/jQuery-Timepicker-Addon,Youraiseme/jQuery-Timepicker-Addon,brenosilver/jQuery-Timepicker-Addon,brenosilver/jQuery-Timepicker-Addon,Youraiseme/jQuery-Timepicker-Addon,pyonnuka/jQuery-Timepicker-Addon,Jaspersoft/jQuery-Timepicker-Addon,pyonnuka/jQuery-Timepicker-Addon,ristovskiv/jQuery-Timepicker-Addon,Jaspersoft/jQuery-Timepicker-Addon,gaissa/jQuery-Timepicker-Addon,trentrichardson/jQuery-Timepicker-Addon | ---
+++
@@ -8,8 +8,8 @@
minuteText: 'Минуты',
secondText: 'Секунды',
millisecText: 'Миллисекунды',
- timezoneText: 'Время зоны',
- currentText: 'Теперь',
+ timezoneText: 'Часовой пояс',
+ currentText: 'Сейчас',
closeText: 'Закрыть',
timeFormat: 'hh:mm tt',
amNames: ['AM', 'A'], |
420d98ab2e5120c45fd9a39f92308268fd04b92d | app/services/fastboot.js | app/services/fastboot.js | import Ember from "ember";
let alias = Ember.computed.alias;
let computed = Ember.computed;
export default Ember.Service.extend({
cookies: alias('_fastbootInfo.cookies'),
headers: alias('_fastbootInfo.headers'),
host: computed(function() {
return this._fastbootInfo.host();
})
});
| import Ember from "ember";
let alias = Ember.computed.alias;
let computed = Ember.computed;
export default Ember.Service.extend({
cookies: alias('_fastbootInfo.cookies'),
headers: alias('_fastbootInfo.headers'),
host: computed(function() {
return this._fastbootInfo.host();
}),
isFastboot: computed(function() {
return typeof window.document === 'undefined';
})
});
| Add isFastboot property to service | Add isFastboot property to service
| JavaScript | mit | habdelra/ember-cli-fastboot,rwjblue/ember-cli-fastboot,josemarluedke/ember-cli-fastboot,kratiahuja/ember-cli-fastboot,kratiahuja/ember-cli-fastboot,ember-fastboot/ember-cli-fastboot,josemarluedke/ember-cli-fastboot,habdelra/ember-cli-fastboot,ember-fastboot/ember-cli-fastboot,tildeio/ember-cli-fastboot,rwjblue/ember-cli-fastboot,tildeio/ember-cli-fastboot | ---
+++
@@ -8,5 +8,8 @@
headers: alias('_fastbootInfo.headers'),
host: computed(function() {
return this._fastbootInfo.host();
+ }),
+ isFastboot: computed(function() {
+ return typeof window.document === 'undefined';
})
}); |
d8cfee019a1e987e1278eec3141733bf5903d896 | src/index.js | src/index.js | var express = require('express');
var app = express();
var cors = require('cors')
var Notes = require('./domain/Notes');
var notes = new Notes();
var Users = require('./domain/Users');
var users = new Users();
/* enable cors */
app.use(cors({
"credentials": true,
"origin": true
}));
/* inject test data */
var TestData = require('./TestData');
TestData(notes, users);
/* HAL Api */
var halApi = require('./api/HalApi');
app.use('/api/hal', halApi(notes, users));
/* HTML Api */
var htmlApi = require('./api/HtmlApi');
app.use('/api/html', htmlApi(notes, users));
app.set('views', __dirname + '/api/html');
app.set('view engine', 'twig');
app.set('twig options', {
strict_variables: false
});
/* Redirect all other Users to github */
app.get('/', function(req, res) {
res.statusCode = 302;
res.setHeader('Location', '/api/html');
res.end();
});
app.get('/robots.txt', function(req, res) {
res.setHeader('Content-Type', 'text/plain');
res.send([
'User-Agent: *',
'Allow: /'
].join("\n"));
});
module.exports = app; | var express = require('express');
var app = express();
var cors = require('cors')
var Notes = require('./domain/Notes');
var notes = new Notes();
var Users = require('./domain/Users');
var users = new Users();
/* enable cors */
app.use(cors({
"credentials": true,
"origin": true,
"methods": ["GET","HEAD","PUT","PATCH","POST","DELETE", "OPTIONS"]
}));
/* inject test data */
var TestData = require('./TestData');
TestData(notes, users);
/* HAL Api */
var halApi = require('./api/HalApi');
app.use('/api/hal', halApi(notes, users));
/* HTML Api */
var htmlApi = require('./api/HtmlApi');
app.use('/api/html', htmlApi(notes, users));
app.set('views', __dirname + '/api/html');
app.set('view engine', 'twig');
app.set('twig options', {
strict_variables: false
});
/* Redirect all other Users to github */
app.get('/', function(req, res) {
res.statusCode = 302;
res.setHeader('Location', '/api/html');
res.end();
});
app.get('/robots.txt', function(req, res) {
res.setHeader('Content-Type', 'text/plain');
res.send([
'User-Agent: *',
'Allow: /'
].join("\n"));
});
module.exports = app; | Allow all methods as allowed methods for CORS | Allow all methods as allowed methods for CORS
| JavaScript | mit | DracoBlue/hateoas-notes,DracoBlue/hateoas-notes | ---
+++
@@ -11,7 +11,8 @@
app.use(cors({
"credentials": true,
- "origin": true
+ "origin": true,
+ "methods": ["GET","HEAD","PUT","PATCH","POST","DELETE", "OPTIONS"]
}));
/* inject test data */ |
dbd401be6bae38cf3590891b5a71f4c71c23cfdb | src/components/Header.js | src/components/Header.js | "use strict";
import React, { Component } from 'react';
// Bootstrap
import { Grid, Row, Col, Navbar, NavItem, Nav } from 'react-bootstrap';
export default class Header extends Component {
render() {
return(
<Navbar inverse fixedTop>
<Navbar.Header>
<Navbar.Brand>
<img src='/assets/img/nyc-logo.png' />
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} href="#">Back To Top</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
| "use strict";
import React, { Component } from 'react';
// Bootstrap
import { Grid, Row, Col, Navbar, NavItem, Nav } from 'react-bootstrap';
export default class Header extends Component {
render() {
return(
<Navbar inverse fixedTop>
<Navbar.Header>
<Navbar.Brand>
<img src='http://localhost:8081/assets/img/nyc-logo.png' />
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} href="#">Back To Top</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
| Fix link to nyc logo with temporary pointer to webpack-dev-server | Fix link to nyc logo with temporary pointer to webpack-dev-server
| JavaScript | mit | codeforamerica/nyc-january-project,codeforamerica/nyc-january-project | ---
+++
@@ -11,7 +11,7 @@
<Navbar inverse fixedTop>
<Navbar.Header>
<Navbar.Brand>
- <img src='/assets/img/nyc-logo.png' />
+ <img src='http://localhost:8081/assets/img/nyc-logo.png' />
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header> |
a3b6923b20154acd28f2df99a01a08416074194a | src/formatter.js | src/formatter.js | 'use strict';
module.exports = function (err, data, pkgPath) {
if (err) {
return 'Debug output: ' + JSON.stringify(Buffer.isBuffer(data) ? data.toString() : data) + '\n' + err;
}
var pipeWrap = function (items) {
return '|' + items.join('|') + '|';
};
var rows = [];
rows.push( pipeWrap( ['Name', 'Installed', 'Patched', 'Include Path', 'More Info'] ) );
data.forEach( function (finding) {
rows.push(
pipeWrap(
[finding.module, finding.version, finding.patched_versions === '<0.0.0' ? 'None' : finding.patched_versions, finding.path.join(' > '), finding.advisory]
)
);
});
return rows.join('\n');
};
| 'use strict';
module.exports = function (err, data, pkgPath) {
if (err) {
return 'Debug output: ' + JSON.stringify(Buffer.isBuffer(data) ? data.toString() : data) + '\n' + err;
}
var pipeWrap = function (items) {
return '|' + items.join('|') + '|';
};
var rows = [];
rows.push( pipeWrap( ['Name', 'Installed', 'Patched', 'Include Path', 'More Info'] ) );
rows.push( pipeWrap( ['--', '--', '--', '--', '--'] ) );
data.forEach( function (finding) {
rows.push(
pipeWrap(
[finding.module, finding.version, finding.patched_versions === '<0.0.0' ? 'None' : finding.patched_versions, finding.path.join(' > '), finding.advisory]
)
);
});
return rows.join('\n');
};
| Make header and actual header | Make header and actual header
| JavaScript | apache-2.0 | dap/nsp-formatter-remarkup | ---
+++
@@ -11,6 +11,7 @@
var rows = [];
rows.push( pipeWrap( ['Name', 'Installed', 'Patched', 'Include Path', 'More Info'] ) );
+ rows.push( pipeWrap( ['--', '--', '--', '--', '--'] ) );
data.forEach( function (finding) {
rows.push( |
b7178d0e2b5afda361e5c713cca2853a91b2a711 | src/commands/commands.js | src/commands/commands.js | 'use strict';
// This is a very simple interface
// Used to fire up gulp task in your local project
var runner = require('../utils/runner'),
cb = require('../utils/callback'),
argv = require('minimist')(process.argv.slice(2));
var commands = function(options) {
var command = argv._[0] || options.parent.rawArgs[2];
switch( command ) {
case 'serve':
runner(cb, 'serve');
break;
case 'build':
runner(cb, 'release');
break;
default:
runner(cb, 'default');
}
};
module.exports = commands;
| 'use strict';
// This is a very simple interface
// Used to fire up gulp task in your local project
var runner = require('../utils/runner'),
cb = require('../utils/callback'),
argv = require('minimist')(process.argv.slice(2));
var commands = function(options) {
var command = argv._[0] || options.parent.rawArgs[2];
switch( command ) {
case 'serve':
case 's':
runner(cb, 'serve');
break;
case 'build':
case 'b':
runner(cb, 'release');
break;
default:
runner(cb, 'default');
}
};
module.exports = commands;
| Fix switch removing regex and adding alias for serve and build | Fix switch removing regex and adding alias for serve and build
| JavaScript | mit | mattma/ember-rocks,mattma/ember-rocks,mattma/ember-rocks | ---
+++
@@ -10,9 +10,11 @@
var command = argv._[0] || options.parent.rawArgs[2];
switch( command ) {
case 'serve':
+ case 's':
runner(cb, 'serve');
break;
case 'build':
+ case 'b':
runner(cb, 'release');
break;
default: |
5565536bc06325e341c5e028ea68581fa56ea9b1 | src/js/update.js | src/js/update.js | export default function update( scene, dt, callback ) {
scene.traverse( object => {
if ( object.update ) {
object.update( dt, scene );
}
if ( callback ) {
callback( object );
}
});
}
| export default function update( scene, dt, callback ) {
scene.traverse( object => {
if ( object.update ) {
object.update( dt, scene );
}
if ( callback ) {
callback( object );
}
});
}
export function lateUpdate( scene, callback ) {
scene.traverse( object => {
if ( object.lateUpdate ) {
object.lateUpdate( scene );
}
if ( callback ) {
callback( object );
}
});
}
| Add lateUpdate() scene traversal function. | Add lateUpdate() scene traversal function.
| JavaScript | mit | razh/flying-machines,razh/flying-machines | ---
+++
@@ -9,3 +9,15 @@
}
});
}
+
+export function lateUpdate( scene, callback ) {
+ scene.traverse( object => {
+ if ( object.lateUpdate ) {
+ object.lateUpdate( scene );
+ }
+
+ if ( callback ) {
+ callback( object );
+ }
+ });
+} |
3c625f29e98160e6c0c047e348caac8c102c0e94 | src/rules.js | src/rules.js | /**
* Rule to apply.
*
* @typedef {Object} Rule
* @property {string} message - Rule message to be shown on violation.
* @property {RuleChecker} check - Function that checks for violations.
*/
/**
* Rule checker function.
*
* @callback RuleChecker
* @arg {Comment} comment - Comment to check.
* @arg {function(Position)} report - Callback to report if rule is violated.
*/
/**
* List of rules to apply.
*
* @type {Rule[]}
*/
module.exports = [
{
name: 'unconventional-whitespace',
message: 'Unconventional whitespace (only spaces and newlines allowed).',
check: require('./rules/whitespace').unconventionalWhitespace
},
{
name: 'spaces-in-a-row',
message: 'Several spaces in a row between words.',
check: require('./rules/whitespace').spacesInARow
},
{
name: 'indentation',
message: 'Unexpected indentation.',
check: require('./rules/whitespace').indentation
},
];
| /**
* Rule to apply.
*
* @typedef {Object} Rule
* @property {string} name - Rule name, must be url-safe (@see RFC 3986, section 2.3).
* @property {string} message - Rule message to be shown on violation.
* @property {RuleChecker} check - Function that checks for violations.
*/
/**
* Rule checker function.
*
* @callback RuleChecker
* @arg {Comment} comment - Comment to check.
* @arg {function(Position)} report - Callback to report if rule is violated.
*/
/**
* List of rules to apply.
*
* @type {Rule[]}
*/
module.exports = [
{
name: 'unconventional-whitespace',
message: 'Unconventional whitespace (only spaces and newlines allowed).',
check: require('./rules/whitespace').unconventionalWhitespace
},
{
name: 'spaces-in-a-row',
message: 'Several spaces in a row between words.',
check: require('./rules/whitespace').spacesInARow
},
{
name: 'indentation',
message: 'Unexpected indentation.',
check: require('./rules/whitespace').indentation
},
];
| Add name property to the Rule description | Add name property to the Rule description
| JavaScript | mit | eush77/js-comment-check | ---
+++
@@ -2,6 +2,7 @@
* Rule to apply.
*
* @typedef {Object} Rule
+ * @property {string} name - Rule name, must be url-safe (@see RFC 3986, section 2.3).
* @property {string} message - Rule message to be shown on violation.
* @property {RuleChecker} check - Function that checks for violations.
*/ |
16475e372a2dbcd5aef35bd7c13ac4c439f943ad | src/scene.js | src/scene.js | import addable from 'flockn/addable';
import Base from 'flockn/base';
import GameObject from 'flockn/gameobject';
import renderable from 'flockn/renderable';
import updateable from 'flockn/updateable';
// A `Scene` instance is a layer for `GameObject` instances.
// Any number of game objects can be added to a scene. Only one scene should be visible at the same time, depending
// on what was set in the `activeScene` property of a `Game` instance.
class Scene extends Base {
constructor(descriptor) {
super('Scene', descriptor);
// Mix in `renderable` and `updateable`
renderable.call(this);
updateable.call(this);
}
addGameObject() {
// Allow game objects to be added to scenes
this.queue.push(addable(GameObject, this.children).apply(this, arguments));
}
// Scenes can be defined and are stored on the object itself
static define(name, factory) {
Scene.store[name] = factory;
}
}
export default Scene;
| import Base from 'flockn/base';
import GameObject from 'flockn/gameobject';
import {addable, renderable, updateable} from 'flockn/mixins';
// A `Scene` instance is a layer for `GameObject` instances.
// Any number of game objects can be added to a scene. Only one scene should be visible at the same time, depending
// on what was set in the `activeScene` property of a `Game` instance.
class Scene extends Base {
constructor(descriptor) {
super('Scene', descriptor);
// Mix in `renderable` and `updateable`
renderable.call(this);
updateable.call(this);
}
addGameObject() {
// Allow game objects to be added to scenes
this.queue.push(addable(GameObject, this.children).apply(this, arguments));
}
// Scenes can be defined and are stored on the object itself
static define(name, factory) {
Scene.store[name] = factory;
}
}
export default Scene;
| Use new mixin structure in game module | Use new mixin structure in game module
| JavaScript | mit | freezedev/flockn,freezedev/flockn | ---
+++
@@ -1,8 +1,7 @@
-import addable from 'flockn/addable';
import Base from 'flockn/base';
import GameObject from 'flockn/gameobject';
-import renderable from 'flockn/renderable';
-import updateable from 'flockn/updateable';
+
+import {addable, renderable, updateable} from 'flockn/mixins';
// A `Scene` instance is a layer for `GameObject` instances.
// Any number of game objects can be added to a scene. Only one scene should be visible at the same time, depending |
63e6c40710e0f1d0b2d2713ea06a179b68ba3467 | src/utils.js | src/utils.js | export function getInterfaceLanguage() {
if (!!navigator && !!navigator.language) {
return navigator.language;
} else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) {
return navigator.languages[0];
} else if (!!navigator && !!navigator.userLanguage) {
return navigator.userLanguage;
} else if (!!navigator && !!navigator.browserLanguage) {
return navigator.browserLanguage;
}
return 'en-US';
}
export function validateTranslationKeys(translationKeys) {
const reservedNames = [
'_interfaceLanguage',
'_language',
'_defaultLanguage',
'_defaultLanguageFirstLevelKeys',
'_props',
];
translationKeys.forEach(key => {
if (reservedNames.indexOf(key) !== -1) {
throw new Error(`${key} cannot be used as a key. It is a reserved word.`);
}
});
} | export function getInterfaceLanguage() {
const defaultLang = 'en-US';
// Check if it's running on server side
if (typeof window === 'undefined') {
return defaultLang;
}
if (!!navigator && !!navigator.language) {
return navigator.language;
} else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) {
return navigator.languages[0];
} else if (!!navigator && !!navigator.userLanguage) {
return navigator.userLanguage;
} else if (!!navigator && !!navigator.browserLanguage) {
return navigator.browserLanguage;
}
return defaultLang;
}
export function validateTranslationKeys(translationKeys) {
const reservedNames = [
'_interfaceLanguage',
'_language',
'_defaultLanguage',
'_defaultLanguageFirstLevelKeys',
'_props',
];
translationKeys.forEach(key => {
if (reservedNames.indexOf(key) !== -1) {
throw new Error(`${key} cannot be used as a key. It is a reserved word.`);
}
});
}
| Fix server side error on navigator object | Fix server side error on navigator object
| JavaScript | mit | stefalda/react-localization | ---
+++
@@ -1,4 +1,11 @@
export function getInterfaceLanguage() {
+ const defaultLang = 'en-US';
+
+ // Check if it's running on server side
+ if (typeof window === 'undefined') {
+ return defaultLang;
+ }
+
if (!!navigator && !!navigator.language) {
return navigator.language;
} else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) {
@@ -8,7 +15,7 @@
} else if (!!navigator && !!navigator.browserLanguage) {
return navigator.browserLanguage;
}
- return 'en-US';
+ return defaultLang;
}
export function validateTranslationKeys(translationKeys) { |
e99015cfacc675982f6be0e814eb1c1a650a15b5 | lib/client/error_reporters/window_error.js | lib/client/error_reporters/window_error.js | var prevWindowOnError = window.onerror;
window.onerror = function(message, url, line, stack) {
var now = Date.now();
stack = stack || 'window@'+url+':'+line+':0';
Kadira.sendErrors([{
appId : Kadira.options.appId,
name : 'Error: ' + message,
source : 'client',
startTime : now,
type : 'window.onerror',
info : getBrowserInfo(),
stack : [{at: now, events: [], stack: stack}],
}]);
if(prevWindowOnError && typeof prevWindowOnError === 'function') {
prevWindowOnError(message, url, line);
}
}
| var prevWindowOnError = window.onerror;
window.onerror = function(message, url, line, stack) {
var now = Date.now();
if(typeof stack !== 'object') {
// if there's a fourth argument it must be the column number
var colNumber = stack || 0;
stack = 'window@'+url+':'+line+':'+colNumber;
}
// stacktrace.js takes an exception as input
var mockException = {stack: stack};
stack = getNormalizedStacktrace(mockException);
Kadira.sendErrors([{
appId : Kadira.options.appId,
name : 'Error: ' + message,
source : 'client',
startTime : now,
type : 'window.onerror',
info : getBrowserInfo(),
stack : [{at: now, events: [], stack: stack}],
}]);
if(prevWindowOnError && typeof prevWindowOnError === 'function') {
prevWindowOnError(message, url, line);
}
}
| Check if fourth argument is an object and normalize with stacktrace.js | Check if fourth argument is an object and normalize with stacktrace.js
| JavaScript | mit | chatr/kadira,meteorhacks/kadira | ---
+++
@@ -1,7 +1,17 @@
var prevWindowOnError = window.onerror;
window.onerror = function(message, url, line, stack) {
var now = Date.now();
- stack = stack || 'window@'+url+':'+line+':0';
+
+ if(typeof stack !== 'object') {
+ // if there's a fourth argument it must be the column number
+ var colNumber = stack || 0;
+ stack = 'window@'+url+':'+line+':'+colNumber;
+ }
+
+ // stacktrace.js takes an exception as input
+ var mockException = {stack: stack};
+ stack = getNormalizedStacktrace(mockException);
+
Kadira.sendErrors([{
appId : Kadira.options.appId,
name : 'Error: ' + message, |
fa6fcde46903d797a20f54dd88f3a880f4b98025 | cfgov/unprocessed/js/routes/sheer.js | cfgov/unprocessed/js/routes/sheer.js | /* ==========================================================================
Common scripts that are used on old sheer templates
These should be removed as templates are moved to wagtail
========================================================================== */
'use strict';
// List of modules often used.
var FilterableListControls = require( '../organisms/FilterableListControls' );
var Expandable = require( '../molecules/Expandable' );
var filterableListDom = document.querySelectorAll( '.o-filterable-list-controls' );
var filterableListControls;
if ( filterableListDom ) {
for ( var i = 0, len = filterableListDom.length; i < len; i++ ) {
filterableListControls = new FilterableListControls( document.body )
filterableListControls.init();
}
}
var expandableDom = document.querySelectorAll( '.content_main .m-expandable' );
var expandable;
if ( expandableDom ) {
for ( var i = 0, len = expandableDom.length; i < len; i++ ) {
expandable = new Expandable( expandableDom[i] );
expandable.init();
}
}
| /* ==========================================================================
Common scripts that are used on old sheer templates
These should be removed as templates are moved to wagtail
========================================================================== */
'use strict';
// List of modules often used.
var FilterableListControls = require( '../organisms/FilterableListControls' );
var Expandable = require( '../molecules/Expandable' );
var filterableListDom = document.querySelectorAll( '.o-filterable-list-controls' );
var filterableListControls;
if ( filterableListDom ) {
for ( var i = 0, len = filterableListDom.length; i < len; i++ ) {
filterableListControls = new FilterableListControls( document.body )
filterableListControls.init();
}
}
var expandableDom = document.querySelectorAll( '.content .m-expandable' );
var expandable;
if ( expandableDom ) {
for ( var i = 0, len = expandableDom.length; i < len; i++ ) {
expandable = new Expandable( expandableDom[i] );
expandable.init();
}
}
| Fix for In This Section expandable | Fix for In This Section expandable
| JavaScript | cc0-1.0 | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh | ---
+++
@@ -18,7 +18,7 @@
}
}
-var expandableDom = document.querySelectorAll( '.content_main .m-expandable' );
+var expandableDom = document.querySelectorAll( '.content .m-expandable' );
var expandable;
if ( expandableDom ) {
for ( var i = 0, len = expandableDom.length; i < len; i++ ) { |
b09bcd37195c694314ab0e35a0cbad8b3570694f | src/containers/Canvas.js | src/containers/Canvas.js |
import { connect } from 'react-redux'
import Canvas from '../components/Canvas'
function mapStateToProps(state) {
return {
image: state.inputImage
}
}
function mapDispatchToProps() {
return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(Canvas)
|
import { connect } from 'react-redux'
import Canvas from '../components/Canvas'
function mapStateToProps(state) {
return {
image: state.inputImage.image
}
}
function mapDispatchToProps() {
return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(Canvas)
| Update for size in props | Update for size in props | JavaScript | mit | bikevit2008/Interface,bikevit2008/Interface | ---
+++
@@ -5,7 +5,7 @@
function mapStateToProps(state) {
return {
- image: state.inputImage
+ image: state.inputImage.image
}
}
|
d9bc92ed679094e984fcb76331c104dd407187f3 | src/utils/CSS.js | src/utils/CSS.js | import CleanCSS from 'clean-css';
export default {
// Validate against common CSS vulnerabilities.
raiseOnUnsafeCSS: (css = '', foundInName = '\'not provided\'') => {
css = new CleanCSS({
shorthandCompacting: false
}).minify(css).styles;
if (css.match(/-moz-binding/i)) {
throw new Error(`Unsafe CSS found in ${foundInName}: "-moz-binding"`);
} else if (css.match(/expression/i)) {
throw new Error(`Unsafe CSS found in ${foundInName}: "expression"`);
} else if (css.match(/<\/style>/i)) {
throw new Error(`Unsafe CSS found in ${foundInName}: "<\/style>"`);
}
return css;
}
};
| import CleanCSS from 'clean-css';
export default {
// Validate against common CSS vulnerabilities.
raiseOnUnsafeCSS: (css = '', foundInName = '\'not provided\'') => {
css = new CleanCSS({
shorthandCompacting: false
}).minify(css).styles;
if (css.match(/-moz-binding/i)) {
throw new Error(`Unsafe CSS found in ${foundInName}: "-moz-binding"`);
} else if (css.match(/expression/i)) {
throw new Error(`Unsafe CSS found in ${foundInName}: "expression"`);
}
return css;
}
};
| Remove checks for closing style tag since clean-css is already taking care of it | refactor(css): Remove checks for closing style tag since clean-css is already taking care of it
| JavaScript | mit | revivek/oy,oysterbooks/oy | ---
+++
@@ -11,8 +11,6 @@
throw new Error(`Unsafe CSS found in ${foundInName}: "-moz-binding"`);
} else if (css.match(/expression/i)) {
throw new Error(`Unsafe CSS found in ${foundInName}: "expression"`);
- } else if (css.match(/<\/style>/i)) {
- throw new Error(`Unsafe CSS found in ${foundInName}: "<\/style>"`);
}
return css;
} |
41cea4b65d284b91db9949e951058512fe93204e | lib/actions/update-version.js | lib/actions/update-version.js | 'use babel';
import UpdateVersionView from '../views/UpdateVersionView';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
import addProgressNotification from '../add-progress-notification';
import getPackageVersion from '../yarn/get-package-version';
export default async function (projectFolderPath) {
const view = new UpdateVersionView((versionSpecifier) => {
if (!versionSpecifier || versionSpecifier.length === 0) {
return;
}
let progress;
const options = {
onStart: () => {
progress = addProgressNotification('Updating package version...');
},
};
yarnExec(
projectFolderPath,
'version',
['--new-version', versionSpecifier],
options,
)
.then((success) => {
progress.dismiss();
if (!success) {
atom.notifications.addError(
'An error occurred updating package version. See output for more information.',
);
return null;
}
return getPackageVersion(projectFolderPath);
})
.then((newVersion) => {
if (!newVersion) {
return;
}
atom.notifications.addSuccess(
`Updated package version to ${newVersion}`,
);
})
.catch(reportError);
});
view.attach();
}
| 'use babel';
import UpdateVersionView from '../views/UpdateVersionView';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
import getPackageVersion from '../yarn/get-package-version';
export default async function (projectFolderPath) {
const view = new UpdateVersionView((versionSpecifier) => {
if (!versionSpecifier || versionSpecifier.length === 0) {
return;
}
yarnExec(projectFolderPath, 'version', ['--new-version', versionSpecifier])
.then((success) => {
if (!success) {
atom.notifications.addError(
'An error occurred updating package version. See output for more information.',
);
return null;
}
return getPackageVersion(projectFolderPath);
})
.then((newVersion) => {
if (!newVersion) {
return;
}
atom.notifications.addSuccess(
`Updated package version to ${newVersion}`,
);
})
.catch(reportError);
});
view.attach();
}
| Remove progress notification from update version command | Remove progress notification from update version command
| JavaScript | mit | cbovis/atom-yarn | ---
+++
@@ -3,7 +3,6 @@
import UpdateVersionView from '../views/UpdateVersionView';
import yarnExec from '../yarn/exec';
import reportError from '../report-error';
-import addProgressNotification from '../add-progress-notification';
import getPackageVersion from '../yarn/get-package-version';
export default async function (projectFolderPath) {
@@ -12,23 +11,8 @@
return;
}
- let progress;
-
- const options = {
- onStart: () => {
- progress = addProgressNotification('Updating package version...');
- },
- };
-
- yarnExec(
- projectFolderPath,
- 'version',
- ['--new-version', versionSpecifier],
- options,
- )
+ yarnExec(projectFolderPath, 'version', ['--new-version', versionSpecifier])
.then((success) => {
- progress.dismiss();
-
if (!success) {
atom.notifications.addError(
'An error occurred updating package version. See output for more information.', |
caf0160788138473f3936139b1b32a25b174842b | problems/arrays/index.js | problems/arrays/index.js | var path = require('path');
var getFile = require('../../get-file');
var run = require('../../run-solution');
exports.problem = getFile(path.join(__dirname, 'problem.md'));
exports.solution = getFile(path.join(__dirname, 'solution.md'));
exports.verify = function (args, cb) {
run(args[0], function (err, result) {
var expected = "[ 'tomato sauce', 'cheese', 'pepperoni' ]\n";
if (result.replace('"', "'") === expected) cb(true);
else cb(false);
});
}; | var path = require('path');
var getFile = require('../../get-file');
var run = require('../../run-solution');
exports.problem = getFile(path.join(__dirname, 'problem.md'));
exports.solution = getFile(path.join(__dirname, 'solution.md'));
exports.verify = function (args, cb) {
run(args[0], function (err, result) {
var expected = "[ 'tomato sauce', 'cheese', 'pepperoni' ]\n";
if (result && result.replace('"', "'") === expected) cb(true);
else cb(false);
});
}; | Fix arrays verify step: do not fail if empty string or boolean passed in | Fix arrays verify step: do not fail if empty string or boolean passed in
| JavaScript | mit | ledsun/javascripting,soujiro27/javascripting,marocchino/javascripting,CLAV1ER/javascripting,ubergrafik/javascripting,aijiekj/javascripting,LindsayElia/javascripting,victorperin/javascripting,he11yeah/javascripting,jaredhensley/javascripting,claudiopro/javascripting,thenaughtychild/javascripting,RichardLitt/javascripting,liyuqi/javascripting,samilokan/javascripting,montogeek/javascripting,gcbeyond/javascripting,nodeschool-no/javascripting,michaelgrilo/javascripting,sethvincent/javascripting,MatthewDiana/javascripting,ymote/javascripting,Aalisha/javascripting,NgaNguyenDuy/javascripting,braday/javascripting,barberboy/javascripting,d9magai/javascripting,agrimm/javascripting,ipelekhan/javascripting,a0viedo/javascripting,SomeoneWeird/javascripting | ---
+++
@@ -9,7 +9,7 @@
exports.verify = function (args, cb) {
run(args[0], function (err, result) {
var expected = "[ 'tomato sauce', 'cheese', 'pepperoni' ]\n";
- if (result.replace('"', "'") === expected) cb(true);
+ if (result && result.replace('"', "'") === expected) cb(true);
else cb(false);
});
}; |
240778d13942a54c0fc0df2b6cc388f84c568922 | src/main/webapp/components/directives/clusterListFilters-directive/clusterListFilters-directive.js | src/main/webapp/components/directives/clusterListFilters-directive/clusterListFilters-directive.js | /**
* @author Jose A. Dianes <jdianes@ebi.ac.uk>
*
* The prc-cluster-list-filters directive allows us to reuse a spectra visualisations using SpeckTackle.
*
*/
var clusterListFiltersDirective = angular.module('prideClusterApp.clusterListFiltersDirective', [])
clusterListFiltersDirective.directive('prcClusterListFilters', function() {
return {
restrict: 'E',
scope: {
},
controller: "ClusterListFiltersCtrl",
templateUrl: 'components/directives/clusterListFilters-directive/clusterListFilters-directive.html'
};
});
clusterListFiltersDirective.controller('ClusterListFiltersCtrl', ['$scope', '$routeParams', '$location',
function($scope, $routeParams, $location) {
function updateState(view) {
// Set location (URL)
$location.path(view);
$location.search({
q:$routeParams.q,
page:$routeParams.page,
size:$routeParams.size
});
}
// attach filter-submit function
$scope.listSubmit = function() {
updateState("/list");
}
$scope.chartSubmit = function() {
updateState("/chart");
}
}
]);
| /**
* @author Jose A. Dianes <jdianes@ebi.ac.uk>
*
* The prc-cluster-list-filters directive allows us to reuse a spectra visualisations using SpeckTackle.
*
*/
var clusterListFiltersDirective = angular.module('prideClusterApp.clusterListFiltersDirective', [])
clusterListFiltersDirective.directive('prcClusterListFilters', function() {
return {
restrict: 'E',
scope: {
},
controller: "ClusterListFiltersCtrl",
templateUrl: 'components/directives/clusterListFilters-directive/clusterListFilters-directive.html'
};
});
clusterListFiltersDirective.controller('ClusterListFiltersCtrl', ['$scope', '$routeParams', '$location',
function($scope, $routeParams, $location) {
function updateState(view) {
// Set location (URL)
$location.path(view);
$location.search({
q:$routeParams.q,
page:$routeParams.page,
size:$routeParams.size
});
}
// attach filter-submit function
$scope.listSubmit = function() {
updateState("list");
}
$scope.chartSubmit = function() {
updateState("chart");
}
}
]);
| Solve navigation problem when you are in list view and pres the button to come back to view (before it was to home) | Solve navigation problem when you are in list view and pres the button to come back to view (before it was to home)
| JavaScript | apache-2.0 | PRIDE-Cluster/cluster-web-app,PRIDE-Cluster/cluster-web-app | ---
+++
@@ -33,11 +33,11 @@
// attach filter-submit function
$scope.listSubmit = function() {
- updateState("/list");
+ updateState("list");
}
$scope.chartSubmit = function() {
- updateState("/chart");
+ updateState("chart");
}
} |
bc414ecb41fce5ace259166ed366763f007f88b4 | src/http-configurable.js | src/http-configurable.js | 'use strict';
var _ = require('lodash');
var httpConfigurable = {};
httpConfigurable.initHttpConfigurable = function() {
this.thenApplies = [];
this.headers = {};
};
httpConfigurable.header = function(headerKey, headerValue) {
this.headers[headerKey] = headerValue;
return this;
};
httpConfigurable.contentType = function(mimeType) {
return this.header('Content-Type', mimeType);
};
httpConfigurable.accept = function(mimeType) {
return this.header('Accept', mimeType);
};
httpConfigurable.thenApply = function(onFulfilled, onRejected, onProgress) {
var applies = {
onFulfilled: onFulfilled,
onRejected: onRejected,
onProgress: onProgress
};
this.thenApplies.push(applies);
return this;
};
httpConfigurable.mergeThenApplies = function(_thenApplies) {
_.extend(this.thenApplies, _thenApplies);
};
module.exports = httpConfigurable;
| 'use strict';
var _ = require('lodash');
var httpConfigurable = {};
httpConfigurable.initHttpConfigurable = function() {
this.thenApplies = [];
this.headers = {};
};
httpConfigurable.header = function(headerKey, headerValue) {
this.headers[headerKey] = headerValue;
return this;
};
httpConfigurable.contentType = function(mimeType) {
return this.header('Content-Type', mimeType);
};
httpConfigurable.accept = function(mimeType) {
return this.header('Accept', mimeType);
};
httpConfigurable.then = function(onFulfilled, onRejected, onProgress) {
var applies = {
onFulfilled: onFulfilled,
onRejected: onRejected,
onProgress: onProgress
};
this.thenApplies.push(applies);
return this;
};
httpConfigurable.thenApply = httpConfigurable.then;
httpConfigurable.mergeThenApplies = function(_thenApplies) {
_.extend(this.thenApplies, _thenApplies);
};
module.exports = httpConfigurable;
| Rename thenApply function to then | Rename thenApply function to then
| JavaScript | mit | kahnjw/endpoints | ---
+++
@@ -24,7 +24,7 @@
return this.header('Accept', mimeType);
};
-httpConfigurable.thenApply = function(onFulfilled, onRejected, onProgress) {
+httpConfigurable.then = function(onFulfilled, onRejected, onProgress) {
var applies = {
onFulfilled: onFulfilled,
onRejected: onRejected,
@@ -35,6 +35,8 @@
return this;
};
+httpConfigurable.thenApply = httpConfigurable.then;
+
httpConfigurable.mergeThenApplies = function(_thenApplies) {
_.extend(this.thenApplies, _thenApplies);
}; |
e4446707c4947f3730d7a82911097f7da16b811a | assets/js/application.js | assets/js/application.js | $(document).ready(function(){
$("#email-form").on("submit", function(e){
e.preventDefault();
console.log("HELP");
});
});
| $(document).ready(function(){
$("#email-form").on("submit", function(e){
e.preventDefault();
$(".contact-form").empty();
$(".contact-form").append(
"<div class='thanks container' style='display:none'>
<h4>Thanks for reaching out!</h4>
<p>I'll get back to you as soon as possible.</p>
</div>"
);
$(".thanks").fadeIn(2000);
});
});
| Add animation after form is submitted | Add animation after form is submitted
| JavaScript | mit | DylanLovesCoffee/DylanLovesCoffee.github.io,DylanLovesCoffee/DylanLovesCoffee.github.io | ---
+++
@@ -1,6 +1,13 @@
$(document).ready(function(){
$("#email-form").on("submit", function(e){
e.preventDefault();
- console.log("HELP");
+ $(".contact-form").empty();
+ $(".contact-form").append(
+ "<div class='thanks container' style='display:none'>
+ <h4>Thanks for reaching out!</h4>
+ <p>I'll get back to you as soon as possible.</p>
+ </div>"
+ );
+ $(".thanks").fadeIn(2000);
});
}); |
049dd10b45d01f1e9b794342dad4335e84019745 | app/services/facebook.js | app/services/facebook.js | 'use strict';
const request = require('request-promise');
const config = require('../../config');
const scraper = require('./scraper');
module.exports = {
getFirstMessagingEntry: (body) => {
const val = body.object == 'page' &&
body.entry &&
Array.isArray(body.entry) &&
body.entry.length > 0 &&
body.entry[0] &&
body.entry[0].id == config.Facebook.pageId &&
body.entry[0].messaging &&
Array.isArray(body.entry[0].messaging) &&
body.entry[0].messaging.length > 0 &&
body.entry[0].messaging[0]
;
return val || null;
},
sendTextMessage: (sender, text) => {
const url = text;
const metadata = scraper(url);
return metadata.metadata().then((meta) => {
let messageData = {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements: [
{
title: 'Test',
image_url: meta.image,
subtitle: 'test',
buttons: []
}
]
}
}
};
console.log(messageData);
return request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: config.Facebook.pageToken},
method: 'POST',
body: {
recipient: {id: sender},
message: messageData,
},
json: true
});
});
}
};
| 'use strict';
const request = require('request-promise');
const config = require('../../config');
const scraper = require('./scraper');
module.exports = {
getFirstMessagingEntry: (body) => {
const val = body.object == 'page' &&
body.entry &&
Array.isArray(body.entry) &&
body.entry.length > 0 &&
body.entry[0] &&
body.entry[0].id == config.Facebook.pageId &&
body.entry[0].messaging &&
Array.isArray(body.entry[0].messaging) &&
body.entry[0].messaging.length > 0 &&
body.entry[0].messaging[0]
;
return val || null;
},
sendTextMessage: (sender, text) => {
const url = text;
const metadata = scraper(url);
return metadata.metadata().then((meta) => {
let messageData = {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements: [
{
title: 'Test',
image_url: meta.image,
subtitle: 'test',
buttons: [{
type: 'web_url',
url: url,
title: 'Click here'
}]
}
]
}
}
};
console.log(messageData);
return request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: config.Facebook.pageToken},
method: 'POST',
body: {
recipient: {id: sender},
message: messageData,
},
json: true
});
});
}
};
| Add button to the template | Add button to the template
| JavaScript | mit | Keeprcom/keepr-bot | ---
+++
@@ -35,7 +35,11 @@
title: 'Test',
image_url: meta.image,
subtitle: 'test',
- buttons: []
+ buttons: [{
+ type: 'web_url',
+ url: url,
+ title: 'Click here'
+ }]
}
]
} |
bd290d002d5f4090d6b5a57264d872366d7ff45c | app/mixins/validation-error-display.js | app/mixins/validation-error-display.js | import Ember from 'ember';
const { Mixin } = Ember;
export default Mixin.create({
init(){
this._super(...arguments);
this.set('showErrorsFor', []);
},
showErrorsFor: [],
actions: {
addErrorDisplayFor(field){
this.get('showErrorsFor').pushObject(field);
},
removeErrorDisplayFor(field){
this.get('showErrorsFor').removeObject(field);
},
}
});
| import Ember from 'ember';
const { Mixin } = Ember;
export default Mixin.create({
didReceiveAttrs(){
this._super(...arguments);
this.set('showErrorsFor', []);
},
showErrorsFor: [],
actions: {
addErrorDisplayFor(field){
this.get('showErrorsFor').pushObject(field);
},
removeErrorDisplayFor(field){
this.get('showErrorsFor').removeObject(field);
},
}
});
| Reset validation errors with each render | Reset validation errors with each render
If we do this in init then the errors don’t get cleared up when new
data is passed in.
| JavaScript | mit | stopfstedt/frontend,jrjohnson/frontend,stopfstedt/frontend,djvoa12/frontend,thecoolestguy/frontend,dartajax/frontend,jrjohnson/frontend,djvoa12/frontend,dartajax/frontend,ilios/frontend,gabycampagna/frontend,gabycampagna/frontend,gboushey/frontend,ilios/frontend,thecoolestguy/frontend,gboushey/frontend | ---
+++
@@ -3,8 +3,7 @@
const { Mixin } = Ember;
export default Mixin.create({
-
- init(){
+ didReceiveAttrs(){
this._super(...arguments);
this.set('showErrorsFor', []);
}, |
d3cb29aa20afd385b746a99741608ab73c8fdd4d | js/mapRequest.control.js | js/mapRequest.control.js | L.Control.MapRequest = L.Control.extend({
options: {
position: "topright"
},
initialize: function(options) {
L.setOptions(this, options);
},
onAdd: function(map) {
let self = this;
let container = L.DomUtil.create("div", "bm-map-request");
container.innerHTML = "<p>Would you like to play some other map? <a target='blank' href='https://feedback.userreport.com/2229a84e-c2fa-4427-99ab-27639f103569/'>Issue a map request.</a></p>";
L.DomEvent.disableClickPropagation(container);
L.DomEvent.disableScrollPropagation(container);
return container;
}
});
L.control.mapRequest = function(opts) {
return new L.Control.MapRequest(opts);
};
| L.Control.MapRequest = L.Control.extend({
options: {
position: "topright"
},
initialize: function(options) {
L.setOptions(this, options);
},
onAdd: function(map) {
let self = this;
let container = L.DomUtil.create("div", "bm-map-request");
container.innerHTML = "<p>Would you like to play some other map? <a target='blank' href='https://feedback.userreport.com/2229a84e-c2fa-4427-99ab-27639f103569/'>Issue a map request.</a></p>";
container.innerHTML += "<p>Chose the wrong map? <a href='/'>Choose again!</a></p>"
L.DomEvent.disableClickPropagation(container);
L.DomEvent.disableScrollPropagation(container);
return container;
}
});
L.control.mapRequest = function(opts) {
return new L.Control.MapRequest(opts);
};
| Add link to home page | Add link to home page
| JavaScript | mit | zimmicz/blind-maps,zimmicz/blind-maps | ---
+++
@@ -11,6 +11,7 @@
let self = this;
let container = L.DomUtil.create("div", "bm-map-request");
container.innerHTML = "<p>Would you like to play some other map? <a target='blank' href='https://feedback.userreport.com/2229a84e-c2fa-4427-99ab-27639f103569/'>Issue a map request.</a></p>";
+ container.innerHTML += "<p>Chose the wrong map? <a href='/'>Choose again!</a></p>"
L.DomEvent.disableClickPropagation(container);
L.DomEvent.disableScrollPropagation(container); |
f6106435674ddcc315d0ccb231849fc2346f1bdc | bin/repl.js | bin/repl.js | #!/usr/bin/env node
// Module dependencies.
var debug = require('debug')('ruche:repl');
var repl = require('repl');
var ruche = require('../lib/ruche');
var emitter = require('../lib/ruche/util/emitter');
// Start the REPL with ruche available
var prompt = repl.start({ prompt: 'ruche> ' });
prompt.context.ruche = ruche;
prompt.context.ruche.emitter = emitter;
prompt.context.help = ruche.help;
prompt.context.version = ruche.version;
prompt.context.install = ruche.install; | #!/usr/bin/env node
// Module dependencies.
var debug = require('debug')('ruche:repl');
var repl = require('repl');
var ruche = require('../lib/ruche');
var emitter = require('../lib/ruche/util/emitter');
// Start the REPL with ruche available
var prompt = repl.start({ prompt: 'ruche> ' });
prompt.context.ruche = ruche;
prompt.context.ruche.emitter = emitter;
prompt.context.help = ruche.help;
prompt.context.version = ruche.version;
prompt.context.install = ruche.install;
prompt.context.uninstall = ruche.uninstall; | Add uninstall shortcut for the REPL | Add uninstall shortcut for the REPL
In the REPL your can use uninstall(['package']) without calling ruche.uninstall
| JavaScript | mit | quentinrossetti/ruche,quentinrossetti/ruche,quentinrossetti/ruche | ---
+++
@@ -13,3 +13,4 @@
prompt.context.help = ruche.help;
prompt.context.version = ruche.version;
prompt.context.install = ruche.install;
+prompt.context.uninstall = ruche.uninstall; |
6965394bf537894af57dca01ae1862b06ec2aeb5 | app/facebook/facebook.js | app/facebook/facebook.js | 'use strict';
angular.module('ngSocial.facebook', ['ngRoute','ngFacebook'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/facebook', {
templateUrl: 'facebook/facebook.html',
controller: 'FacebookCtrl'
});
}])
.config( function( $facebookProvider ) {
$facebookProvider.setAppId('450853485276464');
$facebookProvider.setPermissions("email","public_profile","user_posts","publish_actions","user_photos");
})
.run( function( $rootScope ) {
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
})
.controller('FacebookCtrl', ['$scope', '$facebook', function($scope,$facebook) {
console.log('hello!');
$scope.isLoggedIn = false;
$scope.login = function(){
$facebook.login().then(function(){
console.log('Logged in...');
});
}
}]); | 'use strict';
angular.module('ngSocial.facebook', ['ngRoute','ngFacebook'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/facebook', {
templateUrl: 'facebook/facebook.html',
controller: 'FacebookCtrl'
});
}])
.config( function( $facebookProvider ) {
$facebookProvider.setAppId('450853485276464');
$facebookProvider.setPermissions("email","public_profile","user_posts","publish_actions","user_photos");
})
.run( function( $rootScope ) {
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
})
.controller('FacebookCtrl', ['$scope', '$facebook', function($scope,$facebook) {
aler.log('hello!');
$scope.isLoggedIn = false;
$scope.login = function(){
$facebook.login().then(function(){
console.log('Logged in...');
});
}
}]); | Add Facebook login test 3 | Add Facebook login test 3
| JavaScript | mit | PohrebniakOleskandr/ng-facebook-app,PohrebniakOleskandr/ng-facebook-app | ---
+++
@@ -26,7 +26,7 @@
.controller('FacebookCtrl', ['$scope', '$facebook', function($scope,$facebook) {
- console.log('hello!');
+ aler.log('hello!');
$scope.isLoggedIn = false;
$scope.login = function(){
$facebook.login().then(function(){ |
e71e27febb0cfbf5830e8c271ad036d5e6483221 | gulpfile.js | gulpfile.js | var gulp = require('gulp'),
jshint = require('gulp-jshint'),
stylish = require('jshint-stylish'),
connect = require('gulp-connect');
//CHANGE IF NEEDED
var conf = {
app_cwd:'../webapp/',
port:8080
};
// test JS
gulp.task('test_js', function(){
return gulp.src(['js/**/*.js'], { cwd: conf.app_cwd })
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter(stylish));
});
// SERVER TASKS
gulp.task('connect', function() {
connect.server({
root: conf.app_cwd,
livereload: true,
port:conf.port
});
});
gulp.task('html', function () {
gulp.src(['**/*.html'], { cwd: conf.app_cwd })
.pipe(connect.reload());
});
gulp.task('watch', function () {
gulp.watch([conf.app_cwd+'**/*.css',
conf.app_cwd+'**/*.js',
conf.app_cwd+'/**/*.html'], ['html', 'test_js']);
});
// development server
gulp.task('server', ['connect', 'watch']);
// default task
gulp.task('default', ['server']); | var gulp = require('gulp'),
jshint = require('gulp-jshint'),
stylish = require('jshint-stylish'),
connect = require('gulp-connect');
//CHANGE IF NEEDED
var conf = {
app_cwd:'../webapp/',
port:8080
};
// test JS
gulp.task('test_js', function(){
return gulp.src(['**/*.js'], { cwd: conf.app_cwd })
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter(stylish));
});
// SERVER TASKS
gulp.task('connect', function() {
connect.server({
root: conf.app_cwd,
livereload: true,
port:conf.port
});
});
gulp.task('html', function () {
gulp.src(['**/*.html'], { cwd: conf.app_cwd })
.pipe(connect.reload());
});
gulp.task('watch', function () {
gulp.watch([conf.app_cwd+'**/*.css',
conf.app_cwd+'**/*.js',
conf.app_cwd+'/**/*.html'], ['html', 'test_js']);
});
// development server
gulp.task('server', ['connect', 'watch']);
// default task
gulp.task('default', ['server']);
| Update jshint path to include all children | Update jshint path to include all children | JavaScript | mit | jjelosua/lrserver | ---
+++
@@ -11,7 +11,7 @@
// test JS
gulp.task('test_js', function(){
- return gulp.src(['js/**/*.js'], { cwd: conf.app_cwd })
+ return gulp.src(['**/*.js'], { cwd: conf.app_cwd })
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter(stylish)); |
6578f709efd78252e6cf444979979d5423f26592 | Animable.js | Animable.js | /**
* Animable.js
*
* https://github.com/JWhile/Animable.js
*
* Animable.js
*/
(function(){ // namespace
// class Animation
function Animation(from, to, time, update)
{
this.from = from; // :int
this.diff = to - from; // :int
this.last = from; // :int
this.start = Date.now(); // :long
this.time = time; // :int
this.update = update; // :function
}
// function next(long now):void
Animation.prototype.next = function(now)
{
var n = (now - this.start) / this.time * this.diff + this.from;
if(n !== this.last)
{
this.last = n;
this.update(n);
}
};
})();
| /**
* Animable.js
*
* https://github.com/JWhile/Animable.js
*
* Animable.js
*/
(function(){ // namespace
// class Animation
function Animation(from, to, time, update)
{
this.from = from; // :int
this.diff = to - from; // :int
this.last = from; // :int
this.start = Date.now(); // :long
this.time = time; // :int
this.update = update; // :function
}
// function next(long now):void
Animation.prototype.next = function(now)
{
var n = (now - this.start) / this.time * this.diff + this.from;
if(n !== this.last)
{
this.last = n;
this.update(n);
}
};
var animations = []; // :Array<Animation>
var next = function()
{
newFrame(next);
for(var i = 0; i < animations.length; ++i)
{
animations[i].next();
}
};
})();
| Add function next() & var animations | Add function next() & var animations
| JavaScript | mit | Julow/Animable.js | ---
+++
@@ -34,4 +34,16 @@
}
};
+var animations = []; // :Array<Animation>
+
+var next = function()
+{
+ newFrame(next);
+
+ for(var i = 0; i < animations.length; ++i)
+ {
+ animations[i].next();
+ }
+};
+
})(); |
dad356b7830185f7c18d8a3357a66d522062d96b | gulpfile.js | gulpfile.js | 'use strict'
var gulp = require('gulp')
var del = require('del')
var rename = require('gulp-rename')
var transpiler = require('./lib/transpilation/transpiler.js')
// Config for paths
var paths = {
assets: 'app/assets/',
assets_scss: 'app/assets/scss/',
dist: 'dist/',
templates: 'app/templates/',
npm: 'node_modules/',
prototype_scss: 'node_modules/@gemmaleigh/prototype-scss-refactor/**/*.scss' // This can be removed later
}
// Setup tasks
// Copy prototype-scss-refactor into app/assets/scss
// This step can be removed later once these files exist here
gulp.task('copy:prototype-scss-refactor', function () {
gulp.src(paths.prototype_scss)
.pipe(gulp.dest(paths.assets_scss))
})
gulp.task('clean', function () {
return del([paths.dist + '*'])
})
gulp.task('transpile:erb', function () {
var templateLanguage = 'erb'
return gulp.src(paths.templates + 'govuk_template.html')
.pipe(transpiler(templateLanguage))
.pipe(rename({extname: '.html.' + templateLanguage}))
.pipe(gulp.dest(paths.dist))
})
gulp.task('transpile:handlebars', function () {
var templateLanguage = 'handlebars'
return gulp.src(paths.templates + 'govuk_template.html')
.pipe(transpiler(templateLanguage))
.pipe(rename({extname: '.html.' + templateLanguage}))
.pipe(gulp.dest(paths.dist))
})
| 'use strict'
var gulp = require('gulp')
var del = require('del')
var rename = require('gulp-rename')
var transpiler = require('./lib/transpilation/transpiler.js')
// Config for paths
var paths = {
assets: 'app/assets/',
assets_scss: 'app/assets/scss/',
dist: 'dist/',
templates: 'app/templates/',
npm: 'node_modules/',
prototype_scss: 'node_modules/@gemmaleigh/prototype-scss-refactor/**/*.scss' // This can be removed later
}
var transpileRunner = function (templateLanguage) {
return gulp.src(paths.templates + 'govuk_template.html')
.pipe(transpiler(templateLanguage))
.pipe(rename({extname: '.html.' + templateLanguage}))
.pipe(gulp.dest(paths.dist))
}
// Setup tasks
// Copy prototype-scss-refactor into app/assets/scss
// This step can be removed later once these files exist here
gulp.task('copy:prototype-scss-refactor', function () {
gulp.src(paths.prototype_scss)
.pipe(gulp.dest(paths.assets_scss))
})
gulp.task('clean', function () {
return del([paths.dist + '*'])
})
gulp.task('transpile', ['transpile:erb', 'transpile:handlebars'])
gulp.task('transpile:erb', transpileRunner.bind(null, 'erb'))
gulp.task('transpile:handlebars', transpileRunner.bind(null, 'handlebars'))
| Add a generic gulp transpile task | Add a generic gulp transpile task
We can refactor the shared code between different transpilation recipes out into a separate function. | JavaScript | mit | alphagov/govuk_frontend_alpha,alphagov/govuk_frontend_alpha,alphagov/govuk_frontend_alpha | ---
+++
@@ -15,6 +15,13 @@
prototype_scss: 'node_modules/@gemmaleigh/prototype-scss-refactor/**/*.scss' // This can be removed later
}
+var transpileRunner = function (templateLanguage) {
+ return gulp.src(paths.templates + 'govuk_template.html')
+ .pipe(transpiler(templateLanguage))
+ .pipe(rename({extname: '.html.' + templateLanguage}))
+ .pipe(gulp.dest(paths.dist))
+}
+
// Setup tasks
// Copy prototype-scss-refactor into app/assets/scss
// This step can be removed later once these files exist here
@@ -27,18 +34,6 @@
return del([paths.dist + '*'])
})
-gulp.task('transpile:erb', function () {
- var templateLanguage = 'erb'
- return gulp.src(paths.templates + 'govuk_template.html')
- .pipe(transpiler(templateLanguage))
- .pipe(rename({extname: '.html.' + templateLanguage}))
- .pipe(gulp.dest(paths.dist))
-})
-
-gulp.task('transpile:handlebars', function () {
- var templateLanguage = 'handlebars'
- return gulp.src(paths.templates + 'govuk_template.html')
- .pipe(transpiler(templateLanguage))
- .pipe(rename({extname: '.html.' + templateLanguage}))
- .pipe(gulp.dest(paths.dist))
-})
+gulp.task('transpile', ['transpile:erb', 'transpile:handlebars'])
+gulp.task('transpile:erb', transpileRunner.bind(null, 'erb'))
+gulp.task('transpile:handlebars', transpileRunner.bind(null, 'handlebars')) |
16890f9fefee884bf3fe0f4d4250312fc955481e | app/routes/scientific.js | app/routes/scientific.js | import koaRouter from 'koa-router';
import Scientific from '../controllers/scientific';
import cache from '../controllers/helper/cache';
import check from '../controllers/helper/check';
import share from '../controllers/helper/share';
const router = koaRouter({
prefix: '/scientific'
});
router.get(
'/:login/statistic',
share.githubEnable(),
cache.get('user-statistic', {
params: ['login']
}),
Scientific.getUserStatistic,
cache.set()
);
router.get(
'/:login/predictions',
share.githubEnable(),
cache.get('user-predictions', {
params: ['login']
}),
Scientific.getUserPredictions,
cache.set()
);
router.delete(
'/:login/predictions',
share.githubEnable(),
check.body('fullName'),
Scientific.removePrediction,
cache.del()
);
router.put(
'/:login/predictions',
share.githubEnable(),
check.body('fullName', 'liked'),
Scientific.putPredictionFeedback,
cache.del()
);
module.exports = router;
| import koaRouter from 'koa-router';
import Scientific from '../controllers/scientific';
import cache from '../controllers/helper/cache';
import check from '../controllers/helper/check';
import share from '../controllers/helper/share';
const router = koaRouter({
prefix: '/scientific'
});
router.get(
'/:login/statistic',
share.githubEnable(),
cache.get('github-starred-statistic', {
params: ['login']
}),
Scientific.getUserStatistic,
cache.set({
expire: 86400 // 24 hours
})
);
router.get(
'/:login/predictions',
share.githubEnable(),
cache.get('github-repositories-predictions', {
params: ['login']
}),
Scientific.getUserPredictions,
cache.set()
);
router.delete(
'/:login/predictions',
share.githubEnable(),
check.body('fullName'),
Scientific.removePrediction,
cache.del()
);
router.put(
'/:login/predictions',
share.githubEnable(),
check.body('fullName', 'liked'),
Scientific.putPredictionFeedback,
cache.del()
);
module.exports = router;
| Change cache key and expire time | WHAT: Change cache key and expire time
WHY:
* XXXXX
HOW:
* NOTHING TO SAY
| JavaScript | apache-2.0 | ecmadao/hacknical,ecmadao/hacknical,ecmadao/hacknical | ---
+++
@@ -11,17 +11,19 @@
router.get(
'/:login/statistic',
share.githubEnable(),
- cache.get('user-statistic', {
+ cache.get('github-starred-statistic', {
params: ['login']
}),
Scientific.getUserStatistic,
- cache.set()
+ cache.set({
+ expire: 86400 // 24 hours
+ })
);
router.get(
'/:login/predictions',
share.githubEnable(),
- cache.get('user-predictions', {
+ cache.get('github-repositories-predictions', {
params: ['login']
}),
Scientific.getUserPredictions, |
2fef9706c7770d63debdd996d8c8a82cf7b7045d | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp'),
browserify = require('browserify'),
transform = require('vinyl-transform'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
jasmine = require('gulp-jasmine');
gulp.task('default', ['build', 'watch']);
gulp.task('watch', function () {
gulp.watch('./src/js/**/*.js', ['test']);
gulp.watch('./spec/**/*.js', ['test']);
});
gulp.task('build', ['javascript']);
gulp.task('javascript', function () {
var browserified = transform(function (filename) {
var b = browserify({ entries: filename, debug: true });
return b.bundle();
});
return gulp.src('./src/js/bowler.js')
.pipe(browserified)
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/js'));
});
gulp.task('test', ['javascript'], function () {
return gulp.src('./spec/**/*.js')
.pipe(jasmine());
});
| 'use strict';
var gulp = require('gulp'),
browserify = require('browserify'),
transform = require('vinyl-transform'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
jasmine = require('gulp-jasmine'),
sass = require('gulp-sass');
gulp.task('default', ['build', 'watch']);
gulp.task('watch', function () {
gulp.watch('./src/js/**/*.js', ['test']);
gulp.watch('./spec/**/*.js', ['test']);
gulp.watch('./src/scss/**/*.scss', ['css']);
});
gulp.task('build', ['javascript', 'css']);
gulp.task('css', function () {
gulp.src('./src/css/bowler.scss')
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/css'));
});
gulp.task('javascript', function () {
var browserified = transform(function (filename) {
var b = browserify({ entries: filename, debug: true });
return b.bundle();
});
return gulp.src('./src/js/bowler.js')
.pipe(browserified)
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(uglify())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/js'));
});
gulp.task('test', ['javascript'], function () {
return gulp.src('./spec/**/*.js')
.pipe(jasmine());
});
| Add gulp task for compiling CSS Also add watcher for SCSS compilation | Add gulp task for compiling CSS
Also add watcher for SCSS compilation
| JavaScript | mit | rowanoulton/bowler,rowanoulton/bowler | ---
+++
@@ -5,16 +5,26 @@
transform = require('vinyl-transform'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
- jasmine = require('gulp-jasmine');
+ jasmine = require('gulp-jasmine'),
+ sass = require('gulp-sass');
gulp.task('default', ['build', 'watch']);
gulp.task('watch', function () {
gulp.watch('./src/js/**/*.js', ['test']);
gulp.watch('./spec/**/*.js', ['test']);
+ gulp.watch('./src/scss/**/*.scss', ['css']);
});
-gulp.task('build', ['javascript']);
+gulp.task('build', ['javascript', 'css']);
+
+gulp.task('css', function () {
+ gulp.src('./src/css/bowler.scss')
+ .pipe(sourcemaps.init())
+ .pipe(sass())
+ .pipe(sourcemaps.write('./'))
+ .pipe(gulp.dest('./dist/css'));
+});
gulp.task('javascript', function () {
var browserified = transform(function (filename) { |
5061680bda0211a43cb55ffad69a1a74255fe189 | app/components/canvas-link/component.js | app/components/canvas-link/component.js | import Ember from 'ember';
import Qs from 'qs';
const { computed } = Ember;
export default Ember.Component.extend({
tagName: '',
parsedURL: computed('url', function() {
const link = document.createElement('a');
link.href = this.get('url');
return link;
}),
id: computed('parsedURL', function() {
return this.get('parsedURL.pathname')
.split('/')
.reject(part => !part)
.get('lastObject');
}),
blockID: computed.readOnly('query.block'),
filter: computed.readOnly('query.filter'),
query: computed('parsedURL', function() {
return Qs.parse(this.get('parsedURL.search').slice(1));
})
});
| import Ember from 'ember';
import Qs from 'qs';
const { computed } = Ember;
export default Ember.Component.extend({
tagName: '',
parsedURL: computed('url', function() {
const link = document.createElement('a');
link.href = this.get('url');
return link;
}),
id: computed('parsedURL', function() {
return this.get('parsedURL.pathname')
.split('/')
.reject(part => !part)
.get('lastObject');
}),
blockID: computed.oneWay('query.block'),
filter: computed.oneWay('query.filter'),
query: computed('parsedURL', function() {
return Qs.parse(this.get('parsedURL.search').slice(1));
})
});
| Use onewWay instead of readOnly | Use onewWay instead of readOnly
| JavaScript | apache-2.0 | usecanvas/web-v2,usecanvas/web-v2,usecanvas/web-v2 | ---
+++
@@ -19,8 +19,8 @@
.get('lastObject');
}),
- blockID: computed.readOnly('query.block'),
- filter: computed.readOnly('query.filter'),
+ blockID: computed.oneWay('query.block'),
+ filter: computed.oneWay('query.filter'),
query: computed('parsedURL', function() {
return Qs.parse(this.get('parsedURL.search').slice(1)); |
bdf0b35e53d019c87cca81a86709c17e47bbfc40 | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var ts = require('gulp-typescript');
var tslint = require('gulp-tslint');
var jade = require('gulp-jade');
var plato = require('gulp-plato');
var espower = require('gulp-espower');
var karma = require('karma').server;
gulp.task('jade', function () {
return gulp.src('./src/views/*.jade')
.pipe(jade())
.pipe(gulp.dest('./dist/'));
});
gulp.task('typescript', function () {
return gulp.src('./src/scripts/**/*.ts')
.pipe(tslint())
.pipe(tslint.report('verbose'))
.pipe(ts({
declarationFiles: true,
target: 'es5'
})
.pipe(gulp.dest('./dist/scripts/')));
});
gulp.task('plato', function () {
return gulp.src('./dist/scripts/*.js')
.pipe(plato('./report', {
jshint: {
options: {
strict: true
}
},
complexity: {
trycatch: true
}
}));
});
gulp.task('test', function (done) {
gulp.src('./test/scripts/*.js')
.pipe(espower())
.pipe(gulp.dest('./test/scripts/espower'));
return karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done);
});
gulp.task('default', function () {
});
| var gulp = require('gulp');
var ts = require('gulp-typescript');
var tslint = require('gulp-tslint');
var jade = require('gulp-jade');
var plato = require('gulp-plato');
var espower = require('gulp-espower');
var karma = require('karma').server;
gulp.task('jade', function () {
return gulp.src('./src/views/*.jade')
.pipe(jade())
.pipe(gulp.dest('./dist/'));
});
gulp.task('typescript', function () {
return gulp.src('./src/scripts/**/*.ts')
.pipe(tslint())
.pipe(tslint.report('verbose'))
.pipe(ts({
declarationFiles: true,
target: 'es5'
})
.pipe(gulp.dest('./dist/scripts/')));
});
// Generate complexity analysis reports
gulp.task('analyze', function () {
return gulp.src('./dist/scripts/*.js')
.pipe(plato('./report', {
jshint: {
options: {
strict: true
}
},
complexity: {
trycatch: true
}
}));
});
gulp.task('test', function (done) {
gulp.src('./test/scripts/*.js')
.pipe(espower())
.pipe(gulp.dest('./test/scripts/espower'));
return karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done);
});
gulp.task('default', function () {
});
| Change task name (plato -> analyze) | Change task name (plato -> analyze)
| JavaScript | mit | kubosho/simple-music-player | ---
+++
@@ -23,7 +23,8 @@
.pipe(gulp.dest('./dist/scripts/')));
});
-gulp.task('plato', function () {
+// Generate complexity analysis reports
+gulp.task('analyze', function () {
return gulp.src('./dist/scripts/*.js')
.pipe(plato('./report', {
jshint: { |
eaf9e457368afef6f9cf9186c04e7db4191a067f | gulpfile.js | gulpfile.js | const gulp = require('gulp'),
sass = require('gulp-sass'),
babel = require('gulp-babel'),
sourcemaps = require('gulp-sourcemaps'),
gls = require('gulp-live-server'),
server = gls.new('index.js');
gulp.task( 'es6', () => {
return gulp.src( 'src/**/*.js' )
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015'],
compact: true
}))
.pipe(sourcemaps.write('.'))
.pipe( gulp.dest( 'public' ) );
});
gulp.task( 'sass', () => {
return gulp.src( 'src/**/*.scss' )
.pipe(sourcemaps.init())
.pipe( sass({
outputStyle: 'compressed'
}).on( 'error', sass.logError ) )
.pipe(sourcemaps.write('.'))
.pipe( gulp.dest('public') );
});
gulp.task( 'watch', () => {
function notifyServer(file) {
server.notify.apply( server, [file] );
}
server.start();
gulp.watch( 'src/index.html', notifyServer );
gulp.watch( 'src/*.scss', ['sass'], notifyServer );
gulp.watch( 'src/*.js', ['es6'], notifyServer );
gulp.watch( 'index.js', server.start.bind(server) );
});
gulp.task( 'default', ['es6', 'sass', 'watch'] );
| const gulp = require('gulp'),
sass = require('gulp-sass'),
babel = require('gulp-babel'),
sourcemaps = require('gulp-sourcemaps'),
gls = require('gulp-live-server'),
server = gls.new('index.js');
gulp.task( 'js', () => {
return gulp.src( 'src/**/*.js' )
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015'],
compact: true
}))
.pipe(sourcemaps.write('.'))
.pipe( gulp.dest( 'public' ) );
});
gulp.task( 'scss', () => {
return gulp.src( 'src/**/*.scss' )
.pipe(sourcemaps.init())
.pipe( sass({
outputStyle: 'compressed'
}).on( 'error', sass.logError ) )
.pipe(sourcemaps.write('.'))
.pipe( gulp.dest('public') );
});
gulp.task( 'watch', () => {
server.start();
function notifyServer(file) {
var ext = file.path.split('.').pop();
if(ext == 'scss' || ext == 'js') {
gulp.run( ext );
}
server.notify.apply( server, [file] );
}
gulp.watch('src/index.html', notifyServer);
gulp.watch('src/*.scss', notifyServer);
gulp.watch('src/*.js', notifyServer);
gulp.watch('index.js', function() {
server.start.bind(server)()
});
});
gulp.task( 'default', ['js', 'scss', 'watch'] );
| Make live reloading work again | Make live reloading work again
| JavaScript | mit | leo/editor,leo/editor | ---
+++
@@ -5,7 +5,7 @@
gls = require('gulp-live-server'),
server = gls.new('index.js');
-gulp.task( 'es6', () => {
+gulp.task( 'js', () => {
return gulp.src( 'src/**/*.js' )
@@ -20,7 +20,7 @@
});
-gulp.task( 'sass', () => {
+gulp.task( 'scss', () => {
return gulp.src( 'src/**/*.scss' )
@@ -36,18 +36,28 @@
gulp.task( 'watch', () => {
+ server.start();
+
function notifyServer(file) {
+
+ var ext = file.path.split('.').pop();
+
+ if(ext == 'scss' || ext == 'js') {
+ gulp.run( ext );
+ }
+
server.notify.apply( server, [file] );
+
}
- server.start();
+ gulp.watch('src/index.html', notifyServer);
+ gulp.watch('src/*.scss', notifyServer);
+ gulp.watch('src/*.js', notifyServer);
- gulp.watch( 'src/index.html', notifyServer );
- gulp.watch( 'src/*.scss', ['sass'], notifyServer );
- gulp.watch( 'src/*.js', ['es6'], notifyServer );
-
- gulp.watch( 'index.js', server.start.bind(server) );
+ gulp.watch('index.js', function() {
+ server.start.bind(server)()
+ });
});
-gulp.task( 'default', ['es6', 'sass', 'watch'] );
+gulp.task( 'default', ['js', 'scss', 'watch'] ); |
f98ee7c3bade64f6ae84b0093bea8697d90642e6 | lib/plugin/message/widget/messageWidget.js | lib/plugin/message/widget/messageWidget.js | "use strict";
const Widget = require('../../layout/widget');
const merge = require('../../../util/merge');
const {coroutine: co} = require('bluebird');
class MessageWidget extends Widget {
init(context) {
return co(function*(self, superInit){
yield superInit.call(self, context);
merge(self.data, {
content: self.context.volatile.message.commit(),
});
})(this, super.init);
}
}
MessageWidget.id = 'Message.MessageWidget';
// TODO: Translate.
MessageWidget.title = 'Message Box';
MessageWidget.description = 'This is where system messages will be shown to the user.';
module.exports = MessageWidget;
| "use strict";
const Widget = require('../../layout/widget');
const merge = require('../../../util/merge');
const {coroutine: co} = require('bluebird');
class MessageWidget extends Widget {
init(context, data) {
return co(function*(self, superInit){
yield superInit.call(self, context, data);
merge(self.data, {
content: self.context.volatile.message.commit(),
});
})(this, super.init);
}
}
MessageWidget.id = 'Message.MessageWidget';
// TODO: Translate.
MessageWidget.title = 'Message Box';
MessageWidget.description = 'This is where system messages will be shown to the user.';
module.exports = MessageWidget;
| Update MessageWidget init() for consistency | Update MessageWidget init() for consistency
| JavaScript | mit | coreyp1/defiant,coreyp1/defiant | ---
+++
@@ -5,9 +5,9 @@
const {coroutine: co} = require('bluebird');
class MessageWidget extends Widget {
- init(context) {
+ init(context, data) {
return co(function*(self, superInit){
- yield superInit.call(self, context);
+ yield superInit.call(self, context, data);
merge(self.data, {
content: self.context.volatile.message.commit(),
}); |
cf2ce1d06c9f4a199686ec98e6a66e03bcb99076 | src/label-group/index.js | src/label-group/index.js | import { PropTypes } from 'react';
import { BEM } from 'rebem';
import Label from '#label-group/label';
import Control from '#label-group/control';
function renderChildren(props) {
const label = Label({ labelText: props.labelText, key: 'label' });
const control = Control({ key: 'control' }, props.children);
if (props.controlPosition === 'right') {
return [ label, control ];
}
return [ control, label ];
}
export default function LabelGroup({ mods, mix, ...props }) {
return BEM(
{
...props,
block: 'label-group',
mods: {
...mods,
'control-position': props.controlPosition
},
mix
},
...renderChildren(props)
);
}
LabelGroup.propTypes = {
controlPosition: PropTypes.oneOf([ 'left', 'right' ]),
labelText: PropTypes.string
};
LabelGroup.defaultProps = {
controlPosition: 'right'
};
| import { PropTypes } from 'react';
import { BEM } from 'rebem';
import Label from '#label-group/label';
import Control from '#label-group/control';
function renderChildren(props) {
const label = Label({ labelText: props.labelText, key: 'label' });
const control = Control({ key: 'control' }, props.children);
if (props.controlPosition === 'right') {
return [ label, control ];
}
return [ control, label ];
}
export default function LabelGroup({ mods, mix, ...props }) {
return BEM(
{
...props,
block: 'label-group',
mods: {
...mods,
'control-position': props.controlPosition
},
mix,
tag: 'label'
},
...renderChildren(props)
);
}
LabelGroup.propTypes = {
controlPosition: PropTypes.oneOf([ 'left', 'right' ]),
labelText: PropTypes.string
};
LabelGroup.defaultProps = {
controlPosition: 'right'
};
| Revert ":heavy_check_mark: fix label-group having label tag instead of div" | Revert ":heavy_check_mark: fix label-group having label tag instead of div"
This reverts commit 0d029074a1eaccb792d6895fd1e892f80e33f3f7.
| JavaScript | mit | rebem/core-components,rebem/core-components | ---
+++
@@ -24,7 +24,8 @@
...mods,
'control-position': props.controlPosition
},
- mix
+ mix,
+ tag: 'label'
},
...renderChildren(props)
); |
f49f71082ce7a9eaa5991a8f29bdb5a2f6679e53 | article/static/article/js/social.js | article/static/article/js/social.js | $(function(){
var socialBar = $('.social[data-url]');
$.get('https://graph.facebook.com/?id=' + socialBar.data('url'), function(data) {
$('.facebook .count', socialBar).html(data['shares']);
})
.fail(function() {
$('.facebook .count', socialBar).html('0');
});
$.getJSON('https://urls.api.twitter.com/1/urls/count.json?callback=?', {'url': socialBar.data('url')}, function(data) {
$('.twitter .count', socialBar).html(data['count']);
})
.fail(function() {
$('.twitter .count', socialBar).html('0');
});
if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
// Mobile device.
$(".hidden.whatsapp").removeClass("hidden")
}
});
| $(function(){
if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
// Mobile device.
$(".hidden.whatsapp").removeClass("hidden")
}
});
| Remove the URL count numbers now that twitter stopped reporting them. | Remove the URL count numbers now that twitter stopped reporting them.
| JavaScript | bsd-3-clause | PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari | ---
+++
@@ -1,17 +1,4 @@
$(function(){
- var socialBar = $('.social[data-url]');
- $.get('https://graph.facebook.com/?id=' + socialBar.data('url'), function(data) {
- $('.facebook .count', socialBar).html(data['shares']);
- })
- .fail(function() {
- $('.facebook .count', socialBar).html('0');
- });
- $.getJSON('https://urls.api.twitter.com/1/urls/count.json?callback=?', {'url': socialBar.data('url')}, function(data) {
- $('.twitter .count', socialBar).html(data['count']);
- })
- .fail(function() {
- $('.twitter .count', socialBar).html('0');
- });
if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
// Mobile device.
$(".hidden.whatsapp").removeClass("hidden") |
9dd87cff473f1d7328f9ac2e5a9ff4ee211f05fe | benchmark/define-a-funciton-with-this.js | benchmark/define-a-funciton-with-this.js | 'use strict'
suite('define a function with inherited this', function () {
bench('function statement', function () {
var self = this
var a = function () {
self
return '1'
}
a();
})
bench('() =>', function () {
var a = () => {
this
return '1'
}
a();
})
})
| 'use strict'
suite('define a function with inherited this', function () {
bench('function statement with self = this', function () {
var self = this
var a = function () {
self
return '1'
}
a();
})
bench('function statement with bind', function () {
var a = function () {
this
return '1'
}.bind(this);
a();
})
bench('arrow function () =>', function () {
var a = () => {
this
return '1'
}
a();
})
})
| Add a bind() bench to compare perf gain | Add a bind() bench to compare perf gain
| JavaScript | mit | DavidCai1993/ES6-benchmark | ---
+++
@@ -1,6 +1,6 @@
'use strict'
suite('define a function with inherited this', function () {
- bench('function statement', function () {
+ bench('function statement with self = this', function () {
var self = this
var a = function () {
self
@@ -9,8 +9,16 @@
a();
})
+ bench('function statement with bind', function () {
+ var a = function () {
+ this
+ return '1'
+ }.bind(this);
- bench('() =>', function () {
+ a();
+ })
+
+ bench('arrow function () =>', function () {
var a = () => {
this
return '1' |
c398ca8bc4f0624f41166c949e2eefb180ad4d1d | sashimi-webapp/src/database/stringManipulation.js | sashimi-webapp/src/database/stringManipulation.js |
export default function stringManipulation() {
this.stringConcat = function stringConcat(...stringToConcat) {
return stringToConcat.join('');
};
this.stringDateTime00Format = function stringDateTime00Format(dateTimeNumber) {
if (typeof dateTimeNumber == 'number') {
if (dateTimeNumber < 10) {
return this.stringConcat('0', dateTimeNumber);
}
}
return dateTimeNumber;
};
this.replaceAll = function replaceAll(string, stringToReplace, replacement) {
return string.replace(new RegExp(stringToReplace, 'g'), replacement);
};
this.getPreviousPath = function getPreviousPath(fullPath, lastFolderName) {
const lengthOfExtraCurrentFolder = lastFolderName.length + 1; // extra slash
return fullPath.substring(0, fullPath.length - lengthOfExtraCurrentFolder);
};
}
|
export default function stringManipulation() {
this.stringConcat = function stringConcat(...stringToConcat) {
return stringToConcat.join('');
};
this.stringDateTime00Format = function stringDateTime00Format(dateTimeNumber) {
if (typeof dateTimeNumber == 'number') {
if (dateTimeNumber < 10) {
return this.stringConcat('0', dateTimeNumber);
}
}
return dateTimeNumber;
};
};
this.getPreviousPath = function getPreviousPath(fullPath, lastFolderName) {
const lengthOfExtraCurrentFolder = lastFolderName.length + 1; // extra slash
return fullPath.substring(0, fullPath.length - lengthOfExtraCurrentFolder);
};
}
| Remove function replaceAll in stringManipulator.js | Remove function replaceAll in stringManipulator.js
not used anymore
| JavaScript | mit | nus-mtp/sashimi-note,nus-mtp/sashimi-note,nus-mtp/sashimi-note | ---
+++
@@ -13,8 +13,6 @@
return dateTimeNumber;
};
- this.replaceAll = function replaceAll(string, stringToReplace, replacement) {
- return string.replace(new RegExp(stringToReplace, 'g'), replacement);
};
this.getPreviousPath = function getPreviousPath(fullPath, lastFolderName) { |
d14798e805d1f525be323fa31bfaeb4c6d7df513 | client/api.js | client/api.js | import request from 'superagent'
module.exports = {
getWeather
}
function getWeather() {
request
.get(`http://api.openweathermap.org/data/2.5/weather?=${city}&units=metric&APPID=fc04e2e516b1de4348fb0323f981a1d9`)
.set('Accept', 'application/json')
.end((err, res) => {
if(err) {
callback(err.message)
return
}
const weather = res.body
callback(null, weather)
})
}
| import request from 'superagent'
module.exports = {
getWeather,
get3DForecast
}
function getWeather () {
request
.get(`http://api.openweathermap.org/data/2.5/weather?=${city}&units=metric&APPID=fc04e2e516b1de4348fb0323f981a1d9`)
.set('Accept', 'application/json')
.end((err, res) => {
if(err) {
callback(err.message)
return
}
const weather = res.body
callback(null, weather)
})
}
function get3DForecast () {
request
.get(`api.openweathermap.org/data/2.5/forecast/daily?q=${city}&units=metric&cnt=3&APPID=fc04e2e516b1de4348fb0323f981a1d9`)
.set('Accept', 'application/json')
.end((err, res) => {
if(err) {
callback(err.message)
return
}
const weather = res.body
callback(null, weather)
})
}
| Add get 3 days weather API call | Add get 3 days weather API call
| JavaScript | mit | daffron/WeatherApp,daffron/WeatherApp | ---
+++
@@ -1,10 +1,11 @@
import request from 'superagent'
module.exports = {
- getWeather
+ getWeather,
+ get3DForecast
}
-function getWeather() {
+function getWeather () {
request
.get(`http://api.openweathermap.org/data/2.5/weather?=${city}&units=metric&APPID=fc04e2e516b1de4348fb0323f981a1d9`)
.set('Accept', 'application/json')
@@ -17,3 +18,18 @@
callback(null, weather)
})
}
+
+function get3DForecast () {
+ request
+ .get(`api.openweathermap.org/data/2.5/forecast/daily?q=${city}&units=metric&cnt=3&APPID=fc04e2e516b1de4348fb0323f981a1d9`)
+ .set('Accept', 'application/json')
+ .end((err, res) => {
+ if(err) {
+ callback(err.message)
+ return
+ }
+ const weather = res.body
+ callback(null, weather)
+ })
+
+} |
767bb7c95cb0462264b75f062a7049267079636c | assets/js/application.js | assets/js/application.js | $(document).ready(function(){
$("#email-form").on("submit", function(e){
e.preventDefault();
$(".contact-form").empty();
$(".contact-form").append(
"<div class='thanks container' style='display:none'>
<h4>Thanks for reaching out!</h4>
<p>I'll get back to you as soon as possible.</p>
</div>"
);
$(".thanks").fadeIn(2000);
});
});
| $(document).ready(function(){
$("#email-form").on("submit", function(e){
e.preventDefault();
$(".contact-form").empty();
$(".contact-form").append("<div class='thanks container' style='display:none'><h4>Thanks for reaching out!</h4><p>I'll get back to you as soon as possible.</p></div>");
$(".thanks").fadeIn(2000);
});
});
| Debug jquery error after form submission | Debug jquery error after form submission
| JavaScript | mit | DylanLovesCoffee/DylanLovesCoffee.github.io,DylanLovesCoffee/DylanLovesCoffee.github.io | ---
+++
@@ -2,12 +2,7 @@
$("#email-form").on("submit", function(e){
e.preventDefault();
$(".contact-form").empty();
- $(".contact-form").append(
- "<div class='thanks container' style='display:none'>
- <h4>Thanks for reaching out!</h4>
- <p>I'll get back to you as soon as possible.</p>
- </div>"
- );
+ $(".contact-form").append("<div class='thanks container' style='display:none'><h4>Thanks for reaching out!</h4><p>I'll get back to you as soon as possible.</p></div>");
$(".thanks").fadeIn(2000);
});
}); |
d1ab9788c66379f5f56bdaa125cb14913930c796 | gulpfile.js | gulpfile.js | var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var sass = require("gulp-sass");
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");
gulp.task("sass", function() {
gulp.src("./sass/**/*.sass")
.pipe(sourcemaps.init())
.pipe(sass({outputStyle: "compressed"}))
.pipe(sourcemaps.write())
.pipe(gulp.dest("./dist"));
});
gulp.task("js", function() {
// Scripts for the front page
gulp.src("js/home/*.js")
.pipe(sourcemaps.init())
.pipe(concat("home.js"))
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest("./dist"));
// Scrips for the "email sent" page
gulp.src("js/emailsent/*.js")
.pipe(sourcemaps.init())
.pipe(concat("emailsent.js"))
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest("./dist"));
});
gulp.task("watch", function() {
gulp.watch("./sass/**/*.sass", ["sass"]);
});
gulp.task("default", ["watch"]);
| var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var sass = require("gulp-sass");
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");
gulp.task("sass", function() {
gulp.src("./sass/**/*.sass")
.pipe(sourcemaps.init())
.pipe(sass({outputStyle: "compressed"}))
.pipe(sourcemaps.write())
.pipe(gulp.dest("./dist"));
});
gulp.task("js", function() {
// Build all the scripts from a directory into a file.
function buildScriptsForPage(dir, path) {
gulp.src(dir+"/*.js")
.pipe(sourcemaps.init())
.pipe(concat(path))
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest("./dist"));
}
// Scripts for the front page
buildScriptsForPage("js/home", "home.js");
// Scrips for the "email sent" page
buildScriptsForPage("js/emailsent", "emailsent.js");
});
gulp.task("watch", function() {
gulp.watch("./sass/**/*.sass", ["sass"]);
});
gulp.task("default", ["watch"]);
| Refactor JS building into a function | Refactor JS building into a function
| JavaScript | mit | controversial/controversial.io,controversial/controversial.io,controversial/controversial.io | ---
+++
@@ -17,21 +17,20 @@
});
gulp.task("js", function() {
+ // Build all the scripts from a directory into a file.
+ function buildScriptsForPage(dir, path) {
+ gulp.src(dir+"/*.js")
+ .pipe(sourcemaps.init())
+ .pipe(concat(path))
+ .pipe(uglify())
+ .pipe(sourcemaps.write())
+ .pipe(gulp.dest("./dist"));
+ }
+
// Scripts for the front page
- gulp.src("js/home/*.js")
- .pipe(sourcemaps.init())
- .pipe(concat("home.js"))
- .pipe(uglify())
- .pipe(sourcemaps.write())
- .pipe(gulp.dest("./dist"));
-
+ buildScriptsForPage("js/home", "home.js");
// Scrips for the "email sent" page
- gulp.src("js/emailsent/*.js")
- .pipe(sourcemaps.init())
- .pipe(concat("emailsent.js"))
- .pipe(uglify())
- .pipe(sourcemaps.write())
- .pipe(gulp.dest("./dist"));
+ buildScriptsForPage("js/emailsent", "emailsent.js");
});
gulp.task("watch", function() { |
7bfd1dc5edc4338a2f84b3beb7ebbb50765030ca | broccoli/to-named-amd.js | broccoli/to-named-amd.js | const Babel = require('broccoli-babel-transpiler');
const resolveModuleSource = require('amd-name-resolver').moduleResolve;
const enifed = require('./transforms/transform-define');
const injectNodeGlobals = require('./transforms/inject-node-globals');
module.exports = function processModulesOnly(tree, strict = false) {
let transformOptions = { noInterop: true };
// These options need to be exclusive for some reason, even the key existing
// on the options hash causes issues.
if (strict) {
transformOptions.strict = true;
} else {
transformOptions.loose = true;
}
let options = {
sourceMap: true,
plugins: [
// ensures `@glimmer/compiler` requiring `crypto` works properly
// in both browser and node-land
injectNodeGlobals,
['module-resolver', { resolvePath: resolveModuleSource }],
['transform-es2015-modules-amd', transformOptions],
enifed,
],
moduleIds: true,
};
return new Babel(tree, options);
};
| const Babel = require('broccoli-babel-transpiler');
const { resolveRelativeModulePath } = require('ember-cli-babel/lib/relative-module-paths');
const enifed = require('./transforms/transform-define');
const injectNodeGlobals = require('./transforms/inject-node-globals');
module.exports = function processModulesOnly(tree, strict = false) {
let transformOptions = { noInterop: true };
// These options need to be exclusive for some reason, even the key existing
// on the options hash causes issues.
if (strict) {
transformOptions.strict = true;
} else {
transformOptions.loose = true;
}
let options = {
sourceMap: true,
plugins: [
// ensures `@glimmer/compiler` requiring `crypto` works properly
// in both browser and node-land
injectNodeGlobals,
['module-resolver', { resolvePath: resolveRelativeModulePath }],
['transform-es2015-modules-amd', transformOptions],
enifed,
],
moduleIds: true,
};
return new Babel(tree, options);
};
| Use `ember-cli-babel` to resolve module paths | Use `ember-cli-babel` to resolve module paths
| JavaScript | mit | intercom/ember.js,asakusuma/ember.js,emberjs/ember.js,stefanpenner/ember.js,elwayman02/ember.js,GavinJoyce/ember.js,stefanpenner/ember.js,intercom/ember.js,GavinJoyce/ember.js,emberjs/ember.js,bekzod/ember.js,stefanpenner/ember.js,givanse/ember.js,sandstrom/ember.js,bekzod/ember.js,mfeckie/ember.js,knownasilya/ember.js,mixonic/ember.js,fpauser/ember.js,givanse/ember.js,tildeio/ember.js,qaiken/ember.js,jaswilli/ember.js,jaswilli/ember.js,bekzod/ember.js,emberjs/ember.js,knownasilya/ember.js,tildeio/ember.js,mfeckie/ember.js,knownasilya/ember.js,kellyselden/ember.js,cibernox/ember.js,mixonic/ember.js,bekzod/ember.js,sly7-7/ember.js,cibernox/ember.js,givanse/ember.js,miguelcobain/ember.js,qaiken/ember.js,miguelcobain/ember.js,qaiken/ember.js,jaswilli/ember.js,asakusuma/ember.js,jaswilli/ember.js,miguelcobain/ember.js,cibernox/ember.js,kellyselden/ember.js,fpauser/ember.js,fpauser/ember.js,GavinJoyce/ember.js,asakusuma/ember.js,Turbo87/ember.js,elwayman02/ember.js,intercom/ember.js,mfeckie/ember.js,fpauser/ember.js,sandstrom/ember.js,sly7-7/ember.js,kellyselden/ember.js,Turbo87/ember.js,mixonic/ember.js,GavinJoyce/ember.js,miguelcobain/ember.js,intercom/ember.js,elwayman02/ember.js,Turbo87/ember.js,kellyselden/ember.js,sandstrom/ember.js,tildeio/ember.js,Turbo87/ember.js,givanse/ember.js,qaiken/ember.js,mfeckie/ember.js,asakusuma/ember.js,cibernox/ember.js,elwayman02/ember.js,sly7-7/ember.js | ---
+++
@@ -1,5 +1,5 @@
const Babel = require('broccoli-babel-transpiler');
-const resolveModuleSource = require('amd-name-resolver').moduleResolve;
+const { resolveRelativeModulePath } = require('ember-cli-babel/lib/relative-module-paths');
const enifed = require('./transforms/transform-define');
const injectNodeGlobals = require('./transforms/inject-node-globals');
@@ -20,7 +20,7 @@
// ensures `@glimmer/compiler` requiring `crypto` works properly
// in both browser and node-land
injectNodeGlobals,
- ['module-resolver', { resolvePath: resolveModuleSource }],
+ ['module-resolver', { resolvePath: resolveRelativeModulePath }],
['transform-es2015-modules-amd', transformOptions],
enifed,
], |
36bd61c044f52b0dfc6f90fc04c7148ad3cc1772 | server/models/server-logs.js | server/models/server-logs.js | import mongoose from 'mongoose'
const LogSchema = new mongoose.Schema({
mission_id: String,
created_at: Date,
logs: [{
time: Number,
text: String,
level: Number
}]
}, {
collection: 'serverlogs'
})
LogSchema.virtual('world').get(function () {
return this.mission_id.split('///')[0]
})
LogSchema.virtual('name').get(function () {
return this.mission_id.split('///')[1]
})
exports.schema = LogSchema
| import mongoose from 'mongoose'
const LogSchema = new mongoose.Schema({
mission_id: String,
created_at: Date,
logs: [{
time: Number,
text: String,
level: { type: Number, default: 0 }
}]
}, {
collection: 'serverlogs'
})
LogSchema.virtual('world').get(function () {
return this.mission_id.split('///')[0]
})
LogSchema.virtual('name').get(function () {
return this.mission_id.split('///')[1]
})
exports.schema = LogSchema
| Add default to log level | Add default to log level
| JavaScript | isc | fparma/fparma-web,fparma/fparma-web | ---
+++
@@ -6,7 +6,7 @@
logs: [{
time: Number,
text: String,
- level: Number
+ level: { type: Number, default: 0 }
}]
}, {
collection: 'serverlogs' |
59373060d8d65384f6b78e5acf18a3ebff543045 | _setup/utils/resolve-static-triggers.js | _setup/utils/resolve-static-triggers.js | 'use strict';
var resolve = require('esniff/accessed-properties')('this')
, memoize = require('memoizee/plain')
, ignored = require('./meta-property-names')
, re = new RegExp('^\\s*function\\s*(?:[\\0-\'\\)-\\uffff]+)*\\s*\\(\\s*' +
'(_observe)?[\\/*\\s]*\\)\\s*\\{([\\0-\\uffff]*)\\}\\s*$')
, isFn = RegExp.prototype.test.bind(/^\s*\(/);
module.exports = memoize(function (fn) {
var body = String(fn).match(re)[2], shift = 0;
resolve(body).forEach(function (data) {
var name = data.name, start;
if (name[0] === '_') return;
if (ignored[name]) return;
if (isFn(body.slice(data.end + shift))) return;
start = data.start - 5 + shift;
body = body.slice(0, start) + '_observe(this._get(\'' + name + '\'))' +
body.slice(data.end + shift);
shift += 18;
});
if (!shift) return fn;
return new Function('_observe', body);
});
| 'use strict';
var resolve = require('esniff/accessed-properties')('this')
, memoize = require('memoizee/plain')
, ignored = require('./meta-property-names')
, re = new RegExp('^\\s*function\\s*(?:[\\0-\'\\)-\\uffff]+)*\\s*\\(\\s*' +
'(_observe)?[\\/*\\s]*\\)\\s*\\{([\\0-\\uffff]*)\\}\\s*$')
, isFn = RegExp.prototype.test.bind(/^\s*\(/);
module.exports = memoize(function (fn) {
var body = String(fn).match(re)[2], shift = 0;
resolve(body).forEach(function (data) {
var name = data.name, start;
if (name[0] === '_') return;
if (ignored[name]) return;
if (isFn(body.slice(data.end + shift))) return;
start = data.start - 5 + shift;
body = body.slice(0, start) + '_observe(this._get(\'' + name + '\'))' +
body.slice(data.end + shift);
shift += 18;
});
if (!shift) return fn;
body = 'try {\n' + body +
'\n;} catch (e) { throw new Error("Dbjs getter error:\\n\\n" + e.stack + ' +
'"\\n\\nGetter Body:\\n' + JSON.stringify(body).slice(1) + '); }';
return new Function('_observe', body);
});
| Introduce better error reporting for getter errors | Introduce better error reporting for getter errors
| JavaScript | mit | medikoo/dbjs | ---
+++
@@ -21,5 +21,8 @@
shift += 18;
});
if (!shift) return fn;
+ body = 'try {\n' + body +
+ '\n;} catch (e) { throw new Error("Dbjs getter error:\\n\\n" + e.stack + ' +
+ '"\\n\\nGetter Body:\\n' + JSON.stringify(body).slice(1) + '); }';
return new Function('_observe', body);
}); |
a63c1c34a4996462c867cb0b3201370a4eac62fd | lib/api/utils/headers.js | lib/api/utils/headers.js | export function getHeadersObject(headers = []) {
return Array.from(headers).reduce((result, item) => {
result[item[0]] = item[1];
return result
}, {});
}
function getContentType(type) {
switch (type) {
case 'html':
return 'text/html';
case 'xml':
return 'text/xml';
case 'json':
return 'application/json';
case 'text':
return 'text/plain'
}
}
export function getHeaderPreset(preset) {
return {
pragma: 'no-cache',
'content-type': `${getContentType(preset)}; charset=utf-8`,
'cache-control': 'no-cache',
expires: -1
}
}
| export function getHeadersObject(headers = []) {
return Array.from(headers).reduce((result, item) => {
result[item[0]] = item[1];
return result
}, {});
}
function getContentType(type = '') {
switch (type.toLowerCase()) {
case 'html':
return 'text/html';
case 'xml':
return 'text/xml';
case 'json':
return 'application/json';
case 'text':
return 'text/plain'
}
}
export function getHeaderPreset(preset) {
return {
pragma: 'no-cache',
'content-type': `${getContentType(preset)}; charset=utf-8`,
'cache-control': 'no-cache',
expires: -1
}
}
| Fix get header preset not resolving correctly | Fix get header preset not resolving correctly
| JavaScript | mit | 500tech/mimic,500tech/bdsm,500tech/mimic,500tech/bdsm | ---
+++
@@ -5,8 +5,8 @@
}, {});
}
-function getContentType(type) {
- switch (type) {
+function getContentType(type = '') {
+ switch (type.toLowerCase()) {
case 'html':
return 'text/html';
|
f00bddb04bef8c8859a8f40a40f6025b7389fb5e | cli/main.js | cli/main.js | #!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
const options = {
save: true,
saveIncludedFiles: false,
errorCallback: function(e) {
console.log(e.stack || e)
}
}
if (parameters[0] === 'go') {
UCompiler.compile(process.cwd(), options, parameters[1] || null).then(function(result) {
if (!result.status) {
process.exit(1)
}
}, function(e) {
errorCallback(e)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
UCompiler.watch(
process.cwd(),
options,
parameters[1] ?
parameters[1]
.split(',')
.map(function(_) { return _.trim()})
.filter(function(_) { return _}) : parameters[1]
).catch(errorCallback)
}
| #!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
const options = {
save: true,
saveIncludedFiles: false,
errorCallback: function(e) {
console.log(e.stack || e)
}
}
if (parameters[0] === 'go') {
UCompiler.compile(process.cwd(), options, parameters[1] || null).then(function(result) {
if (!result.status) {
process.exit(1)
}
}, function(e) {
options.errorCallback(e)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
UCompiler.watch(
process.cwd(),
options,
parameters[1] ?
parameters[1]
.split(',')
.map(function(_) { return _.trim()})
.filter(function(_) { return _}) : parameters[1]
).catch(options.errorCallback)
}
| Fix a typo in cli | :bug: Fix a typo in cli
| JavaScript | mit | steelbrain/UCompiler | ---
+++
@@ -25,7 +25,7 @@
process.exit(1)
}
}, function(e) {
- errorCallback(e)
+ options.errorCallback(e)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
@@ -37,5 +37,5 @@
.split(',')
.map(function(_) { return _.trim()})
.filter(function(_) { return _}) : parameters[1]
- ).catch(errorCallback)
+ ).catch(options.errorCallback)
} |
978a0a5cebbb7b4267acdea9fde6799fab1e4f27 | cli/main.js | cli/main.js | #!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
if (parameters[0] === 'go') {
UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) {
console.error(e)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
if (!parameters[1]) {
console.error('You must specify a path to watch')
process.exit(1)
}
UCompiler.watch(parameters[1])
}
| #!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
if (parameters[0] === 'go') {
UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}, function(e) {
console.error(e)
}).then(function(result) {
if (!result.status) {
process.exit(1)
}
})
} else if (parameters[0] === 'watch') {
if (!parameters[1]) {
console.error('You must specify a path to watch')
process.exit(1)
}
UCompiler.watch(parameters[1], {}, function(e) {
console.error(e)
})
}
| Use the new compile and watch API in cli | :new: Use the new compile and watch API in cli
| JavaScript | mit | steelbrain/UCompiler | ---
+++
@@ -13,14 +13,19 @@
}
if (parameters[0] === 'go') {
- UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) {
+ UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}, function(e) {
console.error(e)
- process.exit(1)
+ }).then(function(result) {
+ if (!result.status) {
+ process.exit(1)
+ }
})
} else if (parameters[0] === 'watch') {
if (!parameters[1]) {
console.error('You must specify a path to watch')
process.exit(1)
}
- UCompiler.watch(parameters[1])
+ UCompiler.watch(parameters[1], {}, function(e) {
+ console.error(e)
+ })
} |
970c7d526fcd4a755c9eda41b144c017459d2d37 | node/test/index.js | node/test/index.js | import request from 'supertest';
import test from 'tape';
import app from '../server';
test('Should leftpad correctly', t => {
request(app)
.get('?str=paddin%27%20oswalt&len=68&ch=@')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, `@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@paddin' oswalt`)
t.end();
});
});
test('Should handle missing paddable string correctly', t => {
request(app)
.get('?len=68&ch=@')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, `@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@`)
t.end();
});
});
| import request from 'supertest';
import test from 'tape';
import app from '../server';
test('Should leftpad correctly', t => {
request(app)
.get('?str=paddin%27%20oswalt&len=68&ch=@')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, `@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@paddin' oswalt`)
t.end();
});
});
test('Should handle missing paddable string correctly', t => {
request(app)
.get('?len=68&ch=@')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, `@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@`)
t.end();
});
});
test('Should handle no parameters', t => {
request(app)
.get('/')
.expect(200)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) throw err;
t.equal(res.body.str, '')
t.end();
});
});
| Add test for no parameters | Add test for no parameters
| JavaScript | mit | melonmanchan/left-pad-services,melonmanchan/left-pad-services,melonmanchan/left-pad-services,melonmanchan/left-pad-services,melonmanchan/left-pad-services,melonmanchan/left-pad-services,melonmanchan/left-pad-services,melonmanchan/left-pad-services | ---
+++
@@ -26,3 +26,15 @@
t.end();
});
});
+
+test('Should handle no parameters', t => {
+ request(app)
+ .get('/')
+ .expect(200)
+ .expect('Content-Type', /json/)
+ .end((err, res) => {
+ if (err) throw err;
+ t.equal(res.body.str, '')
+ t.end();
+ });
+}); |
6aa071a484b2a5215dfb38fff831e80c98bbd7a8 | source/javascript/utilities/array2d.js | source/javascript/utilities/array2d.js | define(function() {
var Array2d = function () {
this._columns = {};
};
Array2d.prototype.get = function(location) {
var row = this._columns[location.x];
if (row)
return row[location.y];
};
Array2d.prototype.set = function (location, value) {
var row = this._columns[location.x] || (this._columns[location.x] = {});
if (row[location.y])
return false;
row[location.y] = value;
return true;
};
Array2d.prototype.each = function (callback, context) {
var context = context || this;
var columns;
Object.keys(this._columns).forEach(function (outerKey) {
columns = this._columns[key];
Object.keys(columns).forEach(function (innerKey) {
callback.call(context, outerKey, innerKey, columns[innerKey]);
}, this);
}, this);
};
Array2d.prototype.clear = function (location) {
var row = this._columns[location.x];
if (!row)
return false;
var value = row[location.y];
if (value) {
delete row[location.y];
return value;
}
return false;
};
return Array2d;
});
| define(function() {
var Array2d = function () {
this._columns = {};
};
Array2d.prototype.get = function(location) {
var row = this._columns[location.x];
if (row)
return row[location.y];
};
Array2d.prototype.set = function (location, value) {
var row = this._columns[location.x] || (this._columns[location.x] = {});
if (row[location.y])
return false;
row[location.y] = value;
return true;
};
Array2d.prototype.each = function (callback, context) {
var context = context || this;
var columns;
Object.keys(this._columns).forEach(function (outerKey) {
columns = this._columns[outerKey];
Object.keys(columns).forEach(function (innerKey) {
callback.call(context, outerKey, innerKey, columns[innerKey]);
}, this);
}, this);
};
Array2d.prototype.clear = function (location) {
var row = this._columns[location.x];
if (!row)
return false;
var value = row[location.y];
if (value) {
delete row[location.y];
return value;
}
return false;
};
return Array2d;
});
| Fix incorrect variable name in Array2d.each. | Fix incorrect variable name in Array2d.each.
| JavaScript | mit | stuartkeith/webaudiosequencer,stuartkeith/webaudiosequencer | ---
+++
@@ -26,7 +26,7 @@
var columns;
Object.keys(this._columns).forEach(function (outerKey) {
- columns = this._columns[key];
+ columns = this._columns[outerKey];
Object.keys(columns).forEach(function (innerKey) {
callback.call(context, outerKey, innerKey, columns[innerKey]); |
5fe08eb28dd74144261d4b3c2d730b80b383cb49 | src/foam/swift/SwiftLib.js | src/foam/swift/SwiftLib.js | /**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.LIB({
name: 'foam.swift',
methods: [
function stringify(v) {
var type = foam.typeOf(v);
if ( type == foam.Number || type == foam.Boolean ) {
return `${v}`;
} else if ( type == foam.String ) {
return `"${v
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
}"`;
} else if ( type == foam.Array ) {
return `[${v.map(foam.swift.stringify).join(',')}]`;
} else if ( type == foam.Function ) {
// Unable to convert functions.
return 'nil';
} else {
console.log('Encountered unexpected type while converitng value to string:', v);
debugger;
}
},
],
});
| /**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.LIB({
name: 'foam.swift',
methods: [
function stringify(v) {
var type = foam.typeOf(v);
if ( type == foam.Number || type == foam.Boolean ) {
return `${v}`;
} else if ( type == foam.String ) {
return `"${v
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
}"`;
} else if ( type == foam.Array ) {
return `[${v.map(foam.swift.stringify).join(',')}]`;
} else if ( type == foam.Function ) {
// Unable to convert functions.
return 'nil';
} else if ( type == foam.core.FObject ) {
// TODO: Should be able to serialize an FObject to swift.
return 'nil';
} else {
console.log('Encountered unexpected type while converitng value to string:', v);
debugger;
}
},
],
});
| Handle FObejcts in foam.swift.stringify during generation. | Handle FObejcts in foam.swift.stringify during generation.
| JavaScript | apache-2.0 | foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2 | ---
+++
@@ -23,6 +23,9 @@
} else if ( type == foam.Function ) {
// Unable to convert functions.
return 'nil';
+ } else if ( type == foam.core.FObject ) {
+ // TODO: Should be able to serialize an FObject to swift.
+ return 'nil';
} else {
console.log('Encountered unexpected type while converitng value to string:', v);
debugger; |
4e058681e9fe932ca67390845ff785a4cb82707f | source/views/help/wifi-tools.js | source/views/help/wifi-tools.js | // @flow
import deviceInfo from 'react-native-device-info'
import networkInfo from 'react-native-network-info'
import pkg from '../../../package.json'
export const getIpAddress = (): Promise<?string> =>
new Promise(resolve => {
try {
networkInfo.getIPAddress(resolve)
} catch (err) {
resolve(null)
}
})
export const getPosition = (args: any = {}): Promise<Object> =>
new Promise(resolve => {
navigator.geolocation.getCurrentPosition(resolve, () => resolve({}), {
...args,
enableHighAccuracy: true,
maximumAge: 1000 /*ms*/,
timeout: 5000 /*ms*/,
})
})
export const collectData = async () => ({
id: deviceInfo.getUniqueID(),
brand: deviceInfo.getBrand(),
model: deviceInfo.getModel(),
deviceKind: deviceInfo.getDeviceId(),
os: deviceInfo.getSystemName(),
osVersion: deviceInfo.getSystemVersion(),
appVersion: deviceInfo.getReadableVersion(),
jsVersion: pkg.version,
ua: deviceInfo.getUserAgent(),
ip: await getIpAddress(),
dateRecorded: new Date().toJSON(),
})
export const reportToServer = (url: string, data: Object) =>
fetch(url, {method: 'POST', body: JSON.stringify(data)})
| // @flow
import deviceInfo from 'react-native-device-info'
import networkInfo from 'react-native-network-info'
import pkg from '../../../package.json'
export const getIpAddress = (): Promise<?string> =>
new Promise(resolve => {
try {
networkInfo.getIPAddress(resolve)
} catch (err) {
resolve(null)
}
})
export const getPosition = (args: any = {}): Promise<Object> =>
new Promise(resolve => {
navigator.geolocation.getCurrentPosition(resolve, () => resolve({}))
})
export const collectData = async () => ({
id: deviceInfo.getUniqueID(),
brand: deviceInfo.getBrand(),
model: deviceInfo.getModel(),
deviceKind: deviceInfo.getDeviceId(),
os: deviceInfo.getSystemName(),
osVersion: deviceInfo.getSystemVersion(),
appVersion: deviceInfo.getReadableVersion(),
jsVersion: pkg.version,
ua: deviceInfo.getUserAgent(),
ip: await getIpAddress(),
dateRecorded: new Date().toJSON(),
})
export const reportToServer = (url: string, data: Object) =>
fetch(url, {method: 'POST', body: JSON.stringify(data)})
| Remove third argument from geolocation.getCurrentPosition call | Remove third argument from geolocation.getCurrentPosition call
This third argument is known to cause issues on Android devices,
especially with overly greedy values of maximumAge and timeout.
| JavaScript | agpl-3.0 | StoDevX/AAO-React-Native,carls-app/carls,StoDevX/AAO-React-Native,carls-app/carls,carls-app/carls,StoDevX/AAO-React-Native,carls-app/carls,carls-app/carls,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,carls-app/carls,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,carls-app/carls | ---
+++
@@ -15,12 +15,7 @@
export const getPosition = (args: any = {}): Promise<Object> =>
new Promise(resolve => {
- navigator.geolocation.getCurrentPosition(resolve, () => resolve({}), {
- ...args,
- enableHighAccuracy: true,
- maximumAge: 1000 /*ms*/,
- timeout: 5000 /*ms*/,
- })
+ navigator.geolocation.getCurrentPosition(resolve, () => resolve({}))
})
export const collectData = async () => ({ |
95667ef98ed9b20846b36f9dbf5f3ccbfb461d83 | react/features/base/participants/components/styles.js | react/features/base/participants/components/styles.js | import { createStyleSheet } from '../../styles';
/**
* The style of the avatar and participant view UI (components).
*/
export const styles = createStyleSheet({
/**
* Avatar style.
*/
avatar: {
alignSelf: 'center',
// FIXME I don't understand how a 100 border radius of a 50x50 square
// results in a circle.
borderRadius: 100,
flex: 1,
height: 50,
width: 50
},
/**
* ParticipantView style.
*/
participantView: {
alignItems: 'stretch',
flex: 1
}
});
| import { createStyleSheet } from '../../styles';
/**
* The style of the avatar and participant view UI (components).
*/
export const styles = createStyleSheet({
/**
* Avatar style.
*/
avatar: {
flex: 1,
width: '100%'
},
/**
* ParticipantView style.
*/
participantView: {
alignItems: 'stretch',
flex: 1
}
});
| Revert "[RN] Use rounded avatars in the film strip" | Revert "[RN] Use rounded avatars in the film strip"
This reverts commit 739298c7826ea6109b8a2632d54c8d867f7d03cc.
| JavaScript | apache-2.0 | jitsi/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,bgrozev/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,bgrozev/jitsi-meet,bgrozev/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet | ---
+++
@@ -8,14 +8,8 @@
* Avatar style.
*/
avatar: {
- alignSelf: 'center',
-
- // FIXME I don't understand how a 100 border radius of a 50x50 square
- // results in a circle.
- borderRadius: 100,
flex: 1,
- height: 50,
- width: 50
+ width: '100%'
},
/** |
a19b61fc92e7ac82b114a593699ea7625767e6c7 | treadmill.js | treadmill.js | /**
* treadmill.js
* Copyright © 2015 Johnie Hjelm
*/
var Treadmill = Treadmill || {};
Treadmill.run = function() {
window.onscroll = function() {
if ((window.innerHeight + window.scrollY) >= ((document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight)) {
window.scrollTo(0,0);
}
};
};
| /**
* treadmill.js
* Copyright © 2015 Johnie Hjelm
*/
'use strict';
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
exports.Treadmill = factory();
} else {
root.Treadmill = factory();
}
}(this, function () {
return {
/**
* Attach function to window.onscroll and run Treadmill.
*/
run: function () {
window.onscroll = function() {
if ((window.innerHeight + window.scrollY) >= ((document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight)) {
window.scrollTo(0, 0);
}
};
}
};
}));
| Add support for AMD, CommonJS and global export | Add support for AMD, CommonJS and global export
:smile: | JavaScript | mit | johnie/treadmill.js | ---
+++
@@ -2,12 +2,31 @@
* treadmill.js
* Copyright © 2015 Johnie Hjelm
*/
-var Treadmill = Treadmill || {};
-Treadmill.run = function() {
- window.onscroll = function() {
- if ((window.innerHeight + window.scrollY) >= ((document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight)) {
- window.scrollTo(0,0);
+'use strict';
+
+(function (root, factory) {
+ if (typeof define === 'function' && define.amd) {
+ define([], factory);
+ } else if (typeof exports === 'object') {
+ exports.Treadmill = factory();
+ } else {
+ root.Treadmill = factory();
+ }
+}(this, function () {
+ return {
+
+ /**
+ * Attach function to window.onscroll and run Treadmill.
+ */
+
+ run: function () {
+ window.onscroll = function() {
+ if ((window.innerHeight + window.scrollY) >= ((document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight)) {
+ window.scrollTo(0, 0);
+ }
+ };
}
+
};
-};
+})); |
fac9120da2029a9d893c1e69d679adc3f0f455fe | download.js | download.js | const AWS = require('aws-sdk')
const fs = require('fs-extra')
const config = require('config')
const aws = config.aws
AWS.config = new AWS.Config(aws)
const s3 = new AWS.S3()
const today = new Date().toISOString().slice(0, 10)
const params = {
Bucket: config.tamarac_bucket,
Delimiter: '/',
Prefix: `${today}/`
}
s3.listObjects(params, (err, data) => {
if (err) {
throw err
}
data.Contents.forEach(content => {
const fileParams = { Bucket: config.tamarac_bucket, Key: content.Key }
const path = `./scripts/${content.Key}`
fs.ensureFile(path, err => {
if (err) {
throw err
}
const file = fs.createWriteStream(path)
s3.getObject(fileParams)
.on('httpData', chunk => file.write(chunk))
.on('httpDone', () => file.end())
.send()
})
})
})
| const AWS = require('aws-sdk')
const fs = require('fs-extra')
const config = require('config')
const aws = config.aws
AWS.config = new AWS.Config(aws)
const s3 = new AWS.S3()
const today = process.argv[2] || new Date().toISOString().slice(0, 10)
const params = {
Bucket: config.tamarac_bucket,
Delimiter: '/',
Prefix: `${today}/`
}
s3.listObjects(params, (err, data) => {
if (err) {
throw err
}
data.Contents.forEach(content => {
const fileParams = { Bucket: config.tamarac_bucket, Key: content.Key }
const path = `./scripts/${content.Key}`
fs.ensureFile(path, err => {
if (err) {
throw err
}
const file = fs.createWriteStream(path)
s3.getObject(fileParams)
.on('httpData', chunk => file.write(chunk))
.on('httpDone', () => file.end())
.send()
})
})
})
| Allow prefix to be passed as argument | Allow prefix to be passed as argument | JavaScript | mit | kakamg0/download-today-s3 | ---
+++
@@ -6,7 +6,7 @@
AWS.config = new AWS.Config(aws)
const s3 = new AWS.S3()
-const today = new Date().toISOString().slice(0, 10)
+const today = process.argv[2] || new Date().toISOString().slice(0, 10)
const params = {
Bucket: config.tamarac_bucket, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.