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 |
|---|---|---|---|---|---|---|---|---|---|---|
6874f4dd0d08d0b3a0d227f304dd2f8a56a6f72b | js/init.js | js/init.js | "use strict";
var canvas;
var context;
$(document).ready(function(){
$("<canvas/>").attr({
id: "main_canvas", width:$(document).innerWidth()+"px", height: $(document).innerHeight()+"px"
}).css({
background: "#add8e6"
}).appendTo("#main_container");
canvas = document.getElementById("main_canvas");
context = canvas.getContext("2d");
StartMainMenu();
});
function StartMainMenu()
{
//Creating a new Menu Object
var MainMenu = new Menu("",
[],
200, 50, 200,
function(numItem)
{
if(numItem === 0)
{
StartGame();
}
});
$.getJSON("json/menu.json", function (data) {
$("body").append(buildHtml(data));
});
}
| "use strict";
var canvas;
var context;
$(document).ready(function(){
$("<canvas/>").attr({
id: "main_canvas", width:$(document).innerWidth()+"px", height: $(document).innerHeight()+"px"
}).css({
background: "#add8e6"
}).appendTo("#main_container");
canvas = document.getElementById("main_canvas");
context = canvas.getContext("2d");
StartMainMenu();
});
function StartMainMenu()
{
//Creating a new Menu Object
var MainMenu = new Menu("",
[],
200, 50, 200,
function(numItem)
{
if(numItem === 0)
{
StartGame();
}
});
//GameLoopManager.run(function(){MainMenu.Tick();});
//document.addEventListener("mousedown", function(e){MainMenu.mouseDown(e);}, false);
} | Revert "I don't think this hurts?" | Revert "I don't think this hurts?"
This reverts commit 2e7ffb040e281792a578d8d44ba922531ceff16a.
Conflicts:
js/init.js
| JavaScript | mit | 50Wliu/airplane-simulator,50Wliu/airplane-simulator | ---
+++
@@ -27,8 +27,7 @@
}
});
- $.getJSON("json/menu.json", function (data) {
- $("body").append(buildHtml(data));
- });
+ //GameLoopManager.run(function(){MainMenu.Tick();});
+ //document.addEventListener("mousedown", function(e){MainMenu.mouseDown(e);}, false);
} |
6b3df806d78639a8b4d9b593515b1850bc63afd7 | js/main.js | js/main.js | var bindEvents = function() {
smoothScroll.init();
document.querySelector('.mobile-menu-toggle').addEventListener('click', function(event) {
event.preventDefault();
document.getElementById('nav-list').classList.toggle('show');
});
}
window.onload = function() {
bindEvents();
} | var bindEvents = function() {
smoothScroll.init();
document.querySelector('.mobile-menu-toggle').addEventListener('click', function(event) {
event.preventDefault();
document.getElementById('nav-list').classList.toggle('show');
});
var nav_links = document.querySelectorAll('nav ul li');
for (var i = 0; i < nav_links.length; i++) {
nav_links[i].addEventListener('click', function(event) {
var other_active = document.querySelector('.active');
if (other_active && other_active != this) {
other_active.classList.toggle('active');
}
this.classList.toggle('active');
if (window.innerWidth < 600) {
document.getElementById('nav-list').classList.toggle('show');
}
});
}
}
window.onload = function() {
bindEvents();
} | Add eventlistener for nav links to toggle active class | Add eventlistener for nav links to toggle active class
| JavaScript | mit | jboland/genome-ui-challenge,jboland/genome-ui-challenge | ---
+++
@@ -6,6 +6,21 @@
document.getElementById('nav-list').classList.toggle('show');
});
+ var nav_links = document.querySelectorAll('nav ul li');
+
+ for (var i = 0; i < nav_links.length; i++) {
+ nav_links[i].addEventListener('click', function(event) {
+ var other_active = document.querySelector('.active');
+ if (other_active && other_active != this) {
+ other_active.classList.toggle('active');
+ }
+ this.classList.toggle('active');
+ if (window.innerWidth < 600) {
+ document.getElementById('nav-list').classList.toggle('show');
+ }
+ });
+ }
+
}
window.onload = function() { |
0977a95ee827aeb849b9d47b8e1c2ff7d0cca5e4 | lib/api.js | lib/api.js | const Prismic = require('prismic.io');
module.exports = {
getAll(apiEndpoint) {
return Prismic.api(apiEndpoint).then(api => (
api.query(null, { lang: '*' })
));
},
};
| const Prismic = require('prismic.io');
module.exports = {
getAll(apiEndpoint) {
return Prismic.api(apiEndpoint).then(api => (
api.query(null, {
lang: '*',
pageSize: 100,
})
));
},
};
| Increase pageSize to 100 (which is the current prismic.io maximum) | Increase pageSize to 100 (which is the current prismic.io maximum)
| JavaScript | mit | puhastudio/store-prismic | ---
+++
@@ -3,7 +3,10 @@
module.exports = {
getAll(apiEndpoint) {
return Prismic.api(apiEndpoint).then(api => (
- api.query(null, { lang: '*' })
+ api.query(null, {
+ lang: '*',
+ pageSize: 100,
+ })
));
},
}; |
4f32b708483a3724490b442c82c818ccd170fad6 | lib/log.js | lib/log.js | /**
* Logs which are used in 'cli.js'
*/
module.exports = {
successInsertMsg: function () {
console.log('The TOC was ' + 'successfully'.bold.green + ' inserted.');
},
successCleanMsg: function () {
console.log('The TOC was ' + 'successfully'.bold.green + ' cleaned.');
},
noTocCommentErr: function () {
console.log('A TOC generation ' + 'failed'.bold.red +
'. Can not find the HTML comment ' + '<!-- TOC -->'.bold.red + '.');
}
};
| /**
* Logs which are used in 'cli.js'
*/
module.exports = {
successInsertMsg: function () {
console.log('The TOC was ' + 'successfully'.bold.green + ' inserted.');
},
successCleanMsg: function () {
console.log('The TOC was ' + 'successfully'.bold.green + ' cleaned.');
},
noTocCommentErr: function () {
console.error('A TOC generation ' + 'failed'.bold.red +
'. Can not find the HTML comment ' + '<!-- TOC -->'.bold.red + '.');
}
};
| Write to stderr if there is not '<!-- TOC -->' comment in md | Write to stderr if there is not '<!-- TOC -->' comment in md
| JavaScript | mit | eGavr/toc-md | ---
+++
@@ -11,7 +11,7 @@
},
noTocCommentErr: function () {
- console.log('A TOC generation ' + 'failed'.bold.red +
+ console.error('A TOC generation ' + 'failed'.bold.red +
'. Can not find the HTML comment ' + '<!-- TOC -->'.bold.red + '.');
}
}; |
1a34adf4e512be4639414dc7202b97d2ee056ee3 | src/watchers/LinkSpamWatcher.js | src/watchers/LinkSpamWatcher.js | import BaseWatcher from './BaseWatcher';
/**
* This checks for people spamming links.
*/
class LinkSpamWatcher extends BaseWatcher {
constructor(bot) {
super(bot);
}
usesBypassRules = true;
/**
* The method this watcher should listen on.
*
* @type {string}
*/
method = [
'message',
'messageUpdate'
];
async action(method, message, updatedMessage) {
if (method === 'messageUpdate') {
message = updatedMessage;
}
if (
message.cleanContent.toLowerCase().indexOf('giftsofsteam.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('steamdigitalgift.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('steam.cubecode.site') !== -1 ||
message.cleanContent.toLowerCase().indexOf('hellcase.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('fatalpvp.serv.nu') !== -1
) {
const warningMessage = await message.reply(`This link is not allowed to be posted as it is a known hoax/spam/scam.`);
this.addWarningToUser(message);
message.delete();
warningMessage.delete(60000);
}
}
}
export default LinkSpamWatcher; | import BaseWatcher from './BaseWatcher';
/**
* This checks for people spamming links.
*/
class LinkSpamWatcher extends BaseWatcher {
constructor(bot) {
super(bot);
}
usesBypassRules = true;
/**
* The method this watcher should listen on.
*
* @type {string}
*/
method = [
'message',
'messageUpdate'
];
async action(method, message, updatedMessage) {
if (method === 'messageUpdate') {
message = updatedMessage;
}
if (
message.cleanContent.toLowerCase().indexOf('giftsofsteam.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('steamdigitalgift.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('steam.cubecode.site') !== -1 ||
message.cleanContent.toLowerCase().indexOf('hellcase.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('fatalpvp.serv.nu') !== -1 ||
message.cleanContent.toLowerCase().indexOf('splix.io') !== -1
) {
const warningMessage = await message.reply(`This link is not allowed to be posted as it is a known hoax/spam/scam.`);
this.addWarningToUser(message);
message.delete();
warningMessage.delete(60000);
}
}
}
export default LinkSpamWatcher; | Add splix to spam watcher | Add splix to spam watcher
| JavaScript | mit | ATLauncher/Discord-Bot | ---
+++
@@ -30,7 +30,8 @@
message.cleanContent.toLowerCase().indexOf('steamdigitalgift.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('steam.cubecode.site') !== -1 ||
message.cleanContent.toLowerCase().indexOf('hellcase.com') !== -1 ||
- message.cleanContent.toLowerCase().indexOf('fatalpvp.serv.nu') !== -1
+ message.cleanContent.toLowerCase().indexOf('fatalpvp.serv.nu') !== -1 ||
+ message.cleanContent.toLowerCase().indexOf('splix.io') !== -1
) {
const warningMessage = await message.reply(`This link is not allowed to be posted as it is a known hoax/spam/scam.`);
|
b07e598a8a64308a835fa3f32e8f4bf4ac2ba6c4 | src/utils/emoji-index.js | src/utils/emoji-index.js | import lunr from 'lunr'
import data from '../../data'
var emoticonsList = []
var index = lunr(function() {
this.pipeline.reset()
this.field('short_name', { boost: 2 })
this.field('emoticons')
this.field('name')
this.ref('id')
})
for (let emoji in data.emojis) {
let emojiData = data.emojis[emoji],
{ short_name, name, emoticons } = emojiData
for (let emoticon of emoticons) {
if (emoticonsList.indexOf(emoticon) == -1) {
emoticonsList.push(emoticon)
}
}
index.add({
id: short_name,
emoticons: emoticons,
short_name: tokenize(short_name),
name: tokenize(name),
})
}
function search(value, maxResults = 75) {
var results = null
if (value.length) {
results = index.search(tokenize(value)).map((result) =>
result.ref
)
results = results.slice(0, maxResults)
}
return results
}
function tokenize (string = '') {
if (string[0] == '-' || string[0] == '+') {
return string.split('')
}
if (/(:|;|=)-/.test(string)) {
return [string]
}
return string.split(/[-|_|\s]+/)
}
export default { search, emoticons: emoticonsList }
| import lunr from 'lunr'
import data from '../../data'
var emoticonsList = []
var index = lunr(function() {
this.pipeline.reset()
this.field('short_name', { boost: 2 })
this.field('emoticons')
this.field('name')
this.ref('id')
})
for (let emoji in data.emojis) {
let emojiData = data.emojis[emoji],
{ short_name, name, emoticons } = emojiData
for (let emoticon of emoticons) {
if (emoticonsList.indexOf(emoticon) == -1) {
emoticonsList.push(emoticon)
}
}
index.add({
id: short_name,
emoticons: emoticons,
short_name: tokenize(short_name),
name: tokenize(name),
})
}
function search(value, maxResults = 75) {
var results = null
if (value.length) {
results = index.search(tokenize(value)).map((result) =>
data.emojis[result.ref]
)
results = results.slice(0, maxResults)
}
return results
}
function tokenize (string = '') {
if (string[0] == '-' || string[0] == '+') {
return string.split('')
}
if (/(:|;|=)-/.test(string)) {
return [string]
}
return string.split(/[-|_|\s]+/)
}
export default { search, emoticons: emoticonsList }
| Return emoji object in search results | Return emoji object in search results
| JavaScript | bsd-3-clause | MarcoPolo/emoji-mart,MarcoPolo/emoji-mart | ---
+++
@@ -36,7 +36,7 @@
if (value.length) {
results = index.search(tokenize(value)).map((result) =>
- result.ref
+ data.emojis[result.ref]
)
results = results.slice(0, maxResults) |
f4ad545b2522f8009f78efa8e7f5745cf7413c08 | src/file_url_mapper.js | src/file_url_mapper.js | var path = require('path'),
fs = require('fs');
function FileUrlMapper(options) {
this.base = options.directory;
this.spa = options.spa;
}
FileUrlMapper.prototype.hasTrailingSlash = function(url) {
return url[url.length - 1] === '/';
};
FileUrlMapper.prototype.implicitIndexConversion = function(url) {
return url + 'index.html';
};
FileUrlMapper.prototype.relativeFilePath = function(url) {
return this.hasTrailingSlash(url) ? this.implicitIndexConversion(url) : url;
};
FileUrlMapper.prototype.pathFromUrl = function(url) {
if(this.spa) return path.relative(this.base, 'index.html');
return path.join(this.base, this.relativeFilePath(url));
};
FileUrlMapper.prototype.urlFromPath = function(filePath) {
return path.relative(this.base, filePath);
};
module.exports = FileUrlMapper;
| var path = require('path'),
fs = require('fs');
function FileUrlMapper(options) {
this.base = options.directory;
this.spa = options.spa;
}
FileUrlMapper.prototype.hasTrailingSlash = function(url) {
return url[url.length - 1] === '/';
};
FileUrlMapper.prototype.implicitIndexConversion = function(url) {
return url + 'index.html';
};
FileUrlMapper.prototype.relativeFilePath = function(url) {
return this.hasTrailingSlash(url) ? this.implicitIndexConversion(url) : url;
};
FileUrlMapper.prototype.pathFromUrl = function(url) {
if(this.spa) return path.join(this.base, this.relativeFilePath('index.html'));
return path.join(this.base, this.relativeFilePath(url));
};
FileUrlMapper.prototype.urlFromPath = function(filePath) {
return path.relative(this.base, filePath);
};
module.exports = FileUrlMapper;
| Fix relative paths for spa | Fix relative paths for spa
| JavaScript | mit | eth0lo/slr | ---
+++
@@ -20,7 +20,7 @@
};
FileUrlMapper.prototype.pathFromUrl = function(url) {
- if(this.spa) return path.relative(this.base, 'index.html');
+ if(this.spa) return path.join(this.base, this.relativeFilePath('index.html'));
return path.join(this.base, this.relativeFilePath(url));
}; |
c619a94990f71215640cc4aa0fa289517720ef1f | src/Our.Umbraco.Nexu.Web/App_Plugins/Nexu/controllers/related-links-app-controller.js | src/Our.Umbraco.Nexu.Web/App_Plugins/Nexu/controllers/related-links-app-controller.js | (function () {
'use strict';
function RelatedLinksAppController($scope) {
var vm = this;
vm.relations = $scope.model.viewModel;
var currentVariant = _.find($scope.content.variants, function (v) { return v.active });
if (currentVariant.language) {
vm.culture = currentVariant.language.culture;
vm.cultureRelations = _.filter(vm.relations,
function(r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() });
} else {
vm.cultureRelations = vm.relations;
}
vm.ungrouped = [];
for (var i = 0; i < vm.cultureRelations.length; i++) {
var relation = vm.cultureRelations[i];
for (var j = 0; j < relation.Properties.length; j++) {
vm.ungrouped.push({
id: relation.Id,
name: relation.Name,
propertyname: relation.Properties[j].PropertyName,
tabname: relation.Properties[j].TabName,
published: relation.IsPublished,
trashed: relation.IsTrashed
});
}
}
}
angular.module('umbraco').controller('Our.Umbraco.Nexu.Controllers.RelatedLinksAppController',
[
'$scope',
'editorState',
'localizationService',
RelatedLinksAppController
]);
})(); | (function () {
'use strict';
function RelatedLinksAppController($scope) {
var vm = this;
vm.relations = $scope.model.viewModel;
var currentVariant = _.find($scope.content.variants, function (v) { return v.active });
if (currentVariant && currentVariant.language) {
vm.culture = currentVariant.language.culture;
vm.cultureRelations = _.filter(vm.relations,
function(r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() });
} else {
vm.cultureRelations = vm.relations;
}
vm.ungrouped = [];
for (var i = 0; i < vm.cultureRelations.length; i++) {
var relation = vm.cultureRelations[i];
for (var j = 0; j < relation.Properties.length; j++) {
vm.ungrouped.push({
id: relation.Id,
name: relation.Name,
propertyname: relation.Properties[j].PropertyName,
tabname: relation.Properties[j].TabName,
published: relation.IsPublished,
trashed: relation.IsTrashed
});
}
}
}
angular.module('umbraco').controller('Our.Umbraco.Nexu.Controllers.RelatedLinksAppController',
[
'$scope',
'editorState',
'localizationService',
RelatedLinksAppController
]);
})(); | Fix error when showing content app in media section | Fix error when showing content app in media section
| JavaScript | mit | dawoe/umbraco-nexu,dawoe/umbraco-nexu,dawoe/umbraco-nexu | ---
+++
@@ -7,7 +7,7 @@
vm.relations = $scope.model.viewModel;
var currentVariant = _.find($scope.content.variants, function (v) { return v.active });
- if (currentVariant.language) {
+ if (currentVariant && currentVariant.language) {
vm.culture = currentVariant.language.culture;
vm.cultureRelations = _.filter(vm.relations,
function(r) { return r.Culture.toLowerCase() === vm.culture.toLowerCase() }); |
fa18d31b4017a42a29d3f4345a4a7ade9ef08b9f | action_queue.js | action_queue.js | (function () {
"use strict";
var ActionQueue = window.ActionQueue = function () {
var self = this instanceof ActionQueue ? this : Object.create(ActionQueue.prototype);
self._queue = [];
self._isInAction = false;
self._previousAction = undefined;
return self;
};
ActionQueue.prototype.queueNext = function () {
var self = this,
args = [];
Array.prototype.push.apply(args, arguments);
self._queue.push(args);
nextAction.call(self);
return self;
};
function nextAction (finishPrevious) {
var self = this;
if (finishPrevious) self._isInAction = false;
if (!self._isInAction && self._queue.length > 0) {
var args = self._queue.shift(),
action = args.shift();
self._isInAction = true;
self._previousAction = action;
action.apply(self, args);
}
return self;
};
ActionQueue.prototype.finishAction = function () {
var self = this;
nextAction.call(self, true);
return self;
};
})();
| (function () {
"use strict";
var ActionQueue = window.ActionQueue = function () {
var self = this instanceof ActionQueue ? this : Object.create(ActionQueue.prototype);
self._queue = [];
self._isInAction = false;
self._previousAction = undefined;
return self;
};
ActionQueue.prototype.queueNext = function () {
var self = this,
args = [];
Array.prototype.push.apply(args, arguments);
self._queue.push(args);
nextAction.call(self);
return self;
};
function nextAction (finishPrevious) {
var self = this;
if (finishPrevious) self._isInAction = false;
if (!self._isInAction && self._queue.length > 0) {
var args = self._queue.shift(),
action = args.shift();
self._isInAction = true;
self._previousAction = action;
self._callAction(function () { action.apply(self, args) });
}
return self;
};
ActionQueue.prototype._callAction = function(func) { func(); };
ActionQueue.prototype.finishAction = function () {
var self = this;
nextAction.call(self, true);
return self;
};
})();
| Move calling the action into a separate function so it can be subclassed (for async) | Move calling the action into a separate function so it can be subclassed (for async)
| JavaScript | mit | dataworker/dataworker,dataworker/dataworker,jctank88/dataworker,jctank88/dataworker | ---
+++
@@ -34,12 +34,13 @@
self._isInAction = true;
self._previousAction = action;
-
- action.apply(self, args);
+ self._callAction(function () { action.apply(self, args) });
}
return self;
};
+
+ ActionQueue.prototype._callAction = function(func) { func(); };
ActionQueue.prototype.finishAction = function () {
var self = this; |
06e19fabe77e7e91e9a439ccfe3fd524e31ab7e8 | test/end-to-end/browser/pages/BasePage.js | test/end-to-end/browser/pages/BasePage.js | /* eslint-disable class-methods-use-this */
class BasePage {
get mainHeading() { return browser.getText('h1'); }
waitForMainHeadingWithDataId(id) {
browser.waitForVisible(`[data-title="${id}"]`, 3000);
return browser.getText('h1');
}
get form() { return browser.element('.form'); }
get headerUsername() { return browser.getText('[data-header-username]'); }
submitPage() { this.form.submitForm(); }
clickContinue() {
browser.pause(3000);
browser.click('[data-continue-button]');
}
}
export default BasePage;
| /* eslint-disable class-methods-use-this */
class BasePage {
get mainHeading() { return browser.getText('h1'); }
waitForMainHeadingWithDataId(id) {
browser.waitForVisible(`[data-title="${id}"]`, 5000);
return browser.getText('h1');
}
get form() { return browser.element('.form'); }
get headerUsername() { return browser.getText('[data-header-username]'); }
submitPage() { this.form.submitForm(); }
clickContinue() { browser.click('[data-continue-button]'); }
}
export default BasePage;
| Reset timers back to default | CSRA-000: Reset timers back to default
| JavaScript | mit | noms-digital-studio/csra-app,noms-digital-studio/csra-app,noms-digital-studio/csra-app | ---
+++
@@ -3,17 +3,14 @@
get mainHeading() { return browser.getText('h1'); }
waitForMainHeadingWithDataId(id) {
- browser.waitForVisible(`[data-title="${id}"]`, 3000);
+ browser.waitForVisible(`[data-title="${id}"]`, 5000);
return browser.getText('h1');
}
get form() { return browser.element('.form'); }
get headerUsername() { return browser.getText('[data-header-username]'); }
submitPage() { this.form.submitForm(); }
- clickContinue() {
- browser.pause(3000);
- browser.click('[data-continue-button]');
- }
+ clickContinue() { browser.click('[data-continue-button]'); }
}
export default BasePage; |
b6f23e50aec4ae364db0601e3efa04b902722d13 | src/webvowl/js/elements/nodes/SetOperatorNode.js | src/webvowl/js/elements/nodes/SetOperatorNode.js | var RoundNode = require("./RoundNode");
module.exports = (function () {
var radius = 40;
var o = function (graph) {
RoundNode.apply(this, arguments);
var that = this,
superHoverHighlightingFunction = that.setHoverHighlighting,
superPostDrawActions = that.postDrawActions;
this.radius(radius);
this.setHoverHighlighting = function (enable) {
superHoverHighlightingFunction(enable);
// Highlight connected links when hovering the set operator
d3.selectAll(".link ." + that.cssClassOfNode()).classed("hovered", enable);
};
this.draw = function (element) {
that.nodeElement(element);
element.append("circle")
.attr("class", that.type())
.classed("class", true)
.classed("dashed", true)
.attr("r", that.actualRadius());
};
this.postDrawActions = function () {
superPostDrawActions();
that.textBlock().clear();
that.textBlock().addInstanceCount(that.individuals().length);
that.textBlock().setTranslation(0, 10);
};
};
o.prototype = Object.create(RoundNode.prototype);
o.prototype.constructor = o;
return o;
}());
| var RoundNode = require("./RoundNode");
module.exports = (function () {
var radius = 40;
var o = function (graph) {
RoundNode.apply(this, arguments);
var that = this,
superHoverHighlightingFunction = that.setHoverHighlighting,
superPostDrawActions = that.postDrawActions;
this.radius(radius);
this.setHoverHighlighting = function (enable) {
superHoverHighlightingFunction(enable);
// Highlight connected links when hovering the set operator
d3.selectAll(".link ." + that.cssClassOfNode()).classed("hovered", enable);
};
this.draw = function (element) {
that.nodeElement(element);
element.append("circle")
.attr("class", that.collectCssClasses().join(" "))
.classed("class", true)
.classed("dashed", true)
.attr("r", that.actualRadius());
};
this.postDrawActions = function () {
superPostDrawActions();
that.textBlock().clear();
that.textBlock().addInstanceCount(that.individuals().length);
that.textBlock().setTranslation(0, 10);
};
};
o.prototype = Object.create(RoundNode.prototype);
o.prototype.constructor = o;
return o;
}());
| Set collected css classes on set operators | Set collected css classes on set operators
| JavaScript | mit | MissLoveWu/webvowl,VisualDataWeb/WebVOWL,leshek-pawlak/WebVOWL,leshek-pawlak/WebVOWL,MissLoveWu/webvowl,VisualDataWeb/WebVOWL | ---
+++
@@ -24,7 +24,7 @@
that.nodeElement(element);
element.append("circle")
- .attr("class", that.type())
+ .attr("class", that.collectCssClasses().join(" "))
.classed("class", true)
.classed("dashed", true)
.attr("r", that.actualRadius()); |
12b15cc373b9bf19f75951845c26d2ffb3673013 | js/boot.js | js/boot.js | /*
* boot.js
* Sets up game and loads preloader assets
*/
/* Sets a global object to hold all the states of the game */
YINS = {
/* declare global variables, these will persist across different states */
score: 0,
/* Declare global colors used throughout the game
Usage example: YINS.color.purple */
color: {
purple: '#673ab7'
},
/* Text styles are available by calling: YINS.text.STYLE
for example: YINS.text.header */
text: {
header: {
font: '8vh Arial',
fill: '#f0f0f0',
align: 'center'
}
}
}
/* Constructor creates the game object */
YINS.Boot = function(game) {
console.log('%cStarting YINS..', 'color: white; background: #673ab7');
};
YINS.Boot.prototype = {
preload: function() {
// Load assets for the preloader state
},
create: function() {
YINS.game.state.start('preloader');
}
};
| /*
* boot.js
* Sets up game and loads preloader assets
*/
/* Sets a global object to hold all the states of the game */
YINS = {
/* declare global variables, these will persist across different states */
score: 0,
/* Declare global colors used throughout the game
Usage example: YINS.color.purple */
color: {
purple: '#673ab7',
purple_light: '#b39ddb'
},
/* Text styles are available by calling: YINS.text.STYLE
for example: YINS.text.header */
text: {
title: {
font: '12vh Courier New',
fill: '#404040',
align: 'center'
},
header: {
font: '8vh Arial',
fill: '#f0f0f0',
align: 'center'
}
}
}
/* Constructor creates the game object */
YINS.Boot = function(game) {
console.log('%cStarting YINS..', 'color: white; background: #673ab7');
};
YINS.Boot.prototype = {
preload: function() {
// Load assets for the preloader state
},
create: function() {
// Phaser will automatically pause if the browser tab the game is in loses focus.
// This disables that
YINS.game.stage.disableVisibilityChange = true;
YINS.game.state.start('preloader');
}
};
| Add vars & disable auto pausing | Add vars & disable auto pausing
| JavaScript | mpl-2.0 | Vogeltak/YINS,Vogeltak/YINS | ---
+++
@@ -12,12 +12,19 @@
/* Declare global colors used throughout the game
Usage example: YINS.color.purple */
color: {
- purple: '#673ab7'
+ purple: '#673ab7',
+ purple_light: '#b39ddb'
},
/* Text styles are available by calling: YINS.text.STYLE
for example: YINS.text.header */
text: {
+ title: {
+ font: '12vh Courier New',
+ fill: '#404040',
+ align: 'center'
+ },
+
header: {
font: '8vh Arial',
fill: '#f0f0f0',
@@ -38,6 +45,10 @@
},
create: function() {
+ // Phaser will automatically pause if the browser tab the game is in loses focus.
+ // This disables that
+ YINS.game.stage.disableVisibilityChange = true;
+
YINS.game.state.start('preloader');
}
}; |
7c79a82e84a5a39c3f0f1813257899198b725885 | JustRunnerChat/JustRunnerChat/ChatScripts/main.js | JustRunnerChat/JustRunnerChat/ChatScripts/main.js | /// <reference path="controller.js" />
/// <reference path="dataAccess.js" />
(function () {
var serviceRoot = "http://localhost:16502/api/";
var persister = Chat.persisters.get(serviceRoot);
var controller = Chat.controller.get(persister);
controller.loadUI("#body");
}()); | /// <reference path="controller.js" />
/// <reference path="dataAccess.js" />
(function () {
var serviceRoot = "http://roadrunnerchat.apphb.com/api/";
var persister = Chat.persisters.get(serviceRoot);
var controller = Chat.controller.get(persister);
controller.loadUI("#body");
}()); | Change service root for apphourbor. | Change service root for apphourbor.
| JavaScript | mit | VelizarIT/WebServices-TheRoadRunner,Cheeesus/WebServices-TheRoadRunner,Cheeesus/WebServices-TheRoadRunner,VelizarIT/WebServices-TheRoadRunner | ---
+++
@@ -1,7 +1,7 @@
/// <reference path="controller.js" />
/// <reference path="dataAccess.js" />
(function () {
- var serviceRoot = "http://localhost:16502/api/";
+ var serviceRoot = "http://roadrunnerchat.apphb.com/api/";
var persister = Chat.persisters.get(serviceRoot);
|
5a51300e31f8bee03a540d1fa69d8c036b52518e | js/carousel_collage.js | js/carousel_collage.js | function redistributeCollagePics()
{
var $pictures = jQuery('.carousel-panel-collage-wrapper').contents();
jQuery('.carousel-panel-collage-wrapper').parent().remove();
var $container = jQuery('#carousel-container');
var width = $container.innerWidth();
var height = $container.innerHeight();
// Calculate number of pictures per panel
var picsPerPanel = Math.floor(($pictures.length * 400 * 220) / (width * height));
var numPanels = Math.ceiling($pictures.length / picsPerPanel);
var $panels = jQuery();
for (var i = 0; i < numPanels; ++i)
{
for (var j = i * picsPerPanel; j < (i * picsPerPanel) + picsPerPanel; ++j)
{
$wrapper = jQuery('<div class="carousel-panel-collage-wrapper"></div>');
$wrapper.html($pictures.eq(j));
$panel = jQuery('<div class="carousel-panel"></div>');
$panel.append($wrapper);
$panels.append($panel);
}
}
}
jQuery(document).ready(function()
{
jQuery(window).resize(redistributeCollagePics);
}
);
| function redistributeCollagePics()
{
var $pictures = jQuery('.carousel-panel-collage-wrapper').contents();
jQuery('.carousel-panel-collage-wrapper').parent().remove();
var $container = jQuery('#carousel-container');
var width = $container.innerWidth();
var height = $container.innerHeight();
// Calculate number of pictures per panel
var picsPerPanel = Math.floor(($pictures.length * 400 * 220) / (width * height));
var numPanels = Math.ceil($pictures.length / picsPerPanel);
var $panels = jQuery();
for (var i = 0; i < numPanels; ++i)
{
for (var j = i * picsPerPanel; j < (i * picsPerPanel) + picsPerPanel; ++j)
{
$wrapper = jQuery('<div class="carousel-panel-collage-wrapper"></div>');
$wrapper.html($pictures.eq(j));
$panel = jQuery('<div class="carousel-panel"></div>');
$panel.append($wrapper);
$panels.append($panel);
}
}
}
jQuery(document).ready(function()
{
jQuery(window).resize(redistributeCollagePics);
}
);
| Fix ceiling in other file | Fix ceiling in other file
| JavaScript | agpl-3.0 | MTres19/nwortho-theme,MTres19/nwortho-theme,MTres19/nwortho-theme | ---
+++
@@ -8,7 +8,7 @@
// Calculate number of pictures per panel
var picsPerPanel = Math.floor(($pictures.length * 400 * 220) / (width * height));
- var numPanels = Math.ceiling($pictures.length / picsPerPanel);
+ var numPanels = Math.ceil($pictures.length / picsPerPanel);
var $panels = jQuery();
for (var i = 0; i < numPanels; ++i) |
f850f88053ecce99bad8d8e15d746b162d14e05f | code/media/lib_koowa/js/patch.validator.js | code/media/lib_koowa/js/patch.validator.js | /*
---
description: Monkey patching the Form.Validator to alter its behavior and extend it into doing more
requires:
- MooTools More
license: @TODO
...
*/
if(!Koowa) var Koowa = {};
(function($){
Koowa.Validator = new Class({
Extends: Form.Validator.Inline,
options: {
onShowAdvice: function(input, advice) {
advice.addEvent('click', function(){
input.focus();
});
}
}
});
})(document.id); | /*
---
description: Monkey patching the Form.Validator to alter its behavior and extend it into doing more
requires:
- MooTools More
license: @TODO
...
*/
if(!Koowa) var Koowa = {};
(function($){
Koowa.Validator = new Class({
Extends: Form.Validator.Inline,
options: {
//Needed to make the TinyMCE editor validation function properly
ignoreHidden: false,
onShowAdvice: function(input, advice) {
advice.addEvent('click', function(){
input.focus();
});
}
}
});
})(document.id); | Set ignoreHidden to false to allow TinyMCE editor validation to function properly. | Set ignoreHidden to false to allow TinyMCE editor validation to function properly.
| JavaScript | mpl-2.0 | timble/kodekit,timble/kodekit,timble/kodekit | ---
+++
@@ -20,6 +20,9 @@
Extends: Form.Validator.Inline,
options: {
+ //Needed to make the TinyMCE editor validation function properly
+ ignoreHidden: false,
+
onShowAdvice: function(input, advice) {
advice.addEvent('click', function(){
input.focus(); |
87ed8d27f466183897275d2ae96a47b0b220e3f2 | providers/from_json.js | providers/from_json.js | /*
* Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Transform = require('stream').Transform;
function FromJson() {
Transform.call(this, {
objectMode: true
});
}
require('util').inherits(FromJson, Transform);
FromJson.prototype._transform = function(chunk, encoding, done) {
try {
this.push(JSON.parse(chunk.toString()));
} catch (ex) {
console.error("Could not parse JSON:" + chunk.toString());
}
done();
}
module.exports = FromJson; | /*
* Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Transform = require('stream').Transform;
function FromJson() {
Transform.call(this, {
objectMode: true
});
}
require('util').inherits(FromJson, Transform);
FromJson.prototype._transform = function(chunk, encoding, done) {
var parsed = null;
try {
parsed = JSON.parse(chunk.toString());
} catch (ex) {
console.error("Could not parse JSON:" + chunk.toString());
}
if (parsed) {
this.push(parsed)
}
done();
}
module.exports = FromJson; | Handle just parse errors in provider | Handle just parse errors in provider
Previously all errors were reported as JSON parse errors.
| JavaScript | apache-2.0 | webmasterkai/signalk-server-node,SignalK/signalk-server-node,sbender9/signalk-server-node,sbender9/signalk-server-node,sbender9/signalk-server-node,SignalK/signalk-server-node,SignalK/signalk-server-node,webmasterkai/signalk-server-node,webmasterkai/signalk-server-node,SignalK/signalk-server-node | ---
+++
@@ -25,10 +25,14 @@
require('util').inherits(FromJson, Transform);
FromJson.prototype._transform = function(chunk, encoding, done) {
+ var parsed = null;
try {
- this.push(JSON.parse(chunk.toString()));
+ parsed = JSON.parse(chunk.toString());
} catch (ex) {
console.error("Could not parse JSON:" + chunk.toString());
+ }
+ if (parsed) {
+ this.push(parsed)
}
done();
} |
af986b41b7826615ec0c0f67d069a8096773492a | test/spec/server/controllers/api/index.js | test/spec/server/controllers/api/index.js | /*global describe:false, it:false, beforeEach:false, afterEach:false, request:false, mock:false*/
'use strict';
describe('/', function () {
it('should say "hello"', function (done) {
request(mock)
.get('/api')
.expect(200)
.expect('Content-Type', /html/)
.expect(/"name": "index"/)
.end(function (err, res) {
done(err);
});
});
});
| /*global describe:false, it:false, beforeEach:false, afterEach:false, request:false, mock:false*/
'use strict';
describe('/api', function() {
it('should say "hello"', function(done) {
request(mock)
.get('/api')
.expect(200)
.expect('Content-Type', /html/)
.expect(/"name": "index"/)
.end(function(err, res) {
done(err);
});
});
});
| Update main api endpoint tests | Update main api endpoint tests
| JavaScript | mit | LinuxBozo/18FAgileBPA,adj7388/18FAgileBPA,adj7388/18FAgileBPA,adj7388/18FAgileBPA,LinuxBozo/18FAgileBPA,LinuxBozo/18FAgileBPA | ---
+++
@@ -2,17 +2,15 @@
'use strict';
-describe('/', function () {
+describe('/api', function() {
- it('should say "hello"', function (done) {
+ it('should say "hello"', function(done) {
request(mock)
.get('/api')
.expect(200)
.expect('Content-Type', /html/)
-
- .expect(/"name": "index"/)
-
- .end(function (err, res) {
+ .expect(/"name": "index"/)
+ .end(function(err, res) {
done(err);
});
}); |
ba66599bec8c81fa1c114568d4ef659a08064617 | src/js/event/events.js | src/js/event/events.js | // When creating events, name them with all CAPS separated with underscores.
// Example: AMAZING_MAP_CREATED
//
// The value of the event should be a very short description on when the event
// is fired.
// Example: "when an awesome map was created"
export default const Events = {
}
| // When creating events, name them with all CAPS separated with underscores.
// Example: AMAZING_MAP_CREATED
//
// The value of the event should be a very short description on when the event
// is fired.
// Example: "when an awesome map was created"
export default {
}
| Fix invalid export syntax (ooops) | Fix invalid export syntax (ooops)
| JavaScript | unknown | theMagnon/DTile,MagnonGames/DTile,MagnonGames/DTile,MagnonGames/DTile,theMagnon/DTile,theMagnon/DTile | ---
+++
@@ -5,6 +5,6 @@
// is fired.
// Example: "when an awesome map was created"
-export default const Events = {
-
+export default {
+
} |
20e3fb6f5fdc8098739a797ab005d3f67e77f225 | src/renderer/lib/media-extensions.js | src/renderer/lib/media-extensions.js | const mediaExtensions = {
audio: [
'.aac', '.asf', '.flac', '.m2a', '.m4a', '.m4b', '.mp2', '.mp4',
'.mp3', '.oga', '.ogg', '.opus', '.wma', '.wav', '.wv', '.wvp'],
video: [
'.avi', '.mp4', '.m4v', '.webm', '.mov', '.mkv', 'mpg', 'mpeg',
'.ogv', '.webm', '.wmv'],
image: ['.gif', '.jpg', '.jpeg', '.png']
}
module.exports = mediaExtensions
| const mediaExtensions = {
audio: [
'.aac', 'aif', 'aiff', '.asf', '.flac', '.m2a', '.m4a', '.m4b',
'.mp2', '.mp3', '.mpc', '.oga', '.ogg', '.opus', 'spx', '.wma',
'.wav', '.wv', '.wvp'],
video: [
'.avi', '.mp4', '.m4v', '.webm', '.mov', '.mkv', 'mpg', 'mpeg',
'.ogv', '.webm', '.wmv'],
image: ['.gif', '.jpg', '.jpeg', '.png']
}
module.exports = mediaExtensions
| Add aif/aiff, spx (Speex) & mpc (Musepack) as audio file extensions. Remove clashing .mp4 extension (with video) from audio. | Add aif/aiff, spx (Speex) & mpc (Musepack) as audio file extensions.
Remove clashing .mp4 extension (with video) from audio.
| JavaScript | mit | feross/webtorrent-desktop,feross/webtorrent-desktop,feross/webtorrent-desktop,webtorrent/webtorrent-desktop,webtorrent/webtorrent-desktop,feross/webtorrent-app,feross/webtorrent-app,feross/webtorrent-app,webtorrent/webtorrent-desktop | ---
+++
@@ -1,7 +1,8 @@
const mediaExtensions = {
audio: [
- '.aac', '.asf', '.flac', '.m2a', '.m4a', '.m4b', '.mp2', '.mp4',
- '.mp3', '.oga', '.ogg', '.opus', '.wma', '.wav', '.wv', '.wvp'],
+ '.aac', 'aif', 'aiff', '.asf', '.flac', '.m2a', '.m4a', '.m4b',
+ '.mp2', '.mp3', '.mpc', '.oga', '.ogg', '.opus', 'spx', '.wma',
+ '.wav', '.wv', '.wvp'],
video: [
'.avi', '.mp4', '.m4v', '.webm', '.mov', '.mkv', 'mpg', 'mpeg',
'.ogv', '.webm', '.wmv'], |
36cab8b19d58301ac7ce16643feaf5b2579b6a2e | src/alertmessages/alertmessages.spec.js | src/alertmessages/alertmessages.spec.js | 'use strict';
describe('Directive: alertMessages', function() {
// load the directive's module
beforeEach(module('polestar'));
var element,
scope;
beforeEach(module('polestar', function($provide) {
var mock = {
alerts: [
{name: 'foo'},
{name: 'bar'}
]
};
$provide.value('Alerts', mock);
}));
beforeEach(inject(function($rootScope) {
scope = $rootScope.$new();
}));
it('should show alert messages', inject(function($compile) {
element = angular.element('<alert-messages></alert-messages>');
element = $compile(element)(scope);
scope.$digest();
expect(element.find('.alert-item').length).to.eql(2);
}));
});
| 'use strict';
describe('Directive: alertMessages', function() {
var element,
scope;
// load the directive's module
beforeEach(module('vlui', function($provide) {
// Mock the alerts service
$provide.value('Alerts', {
alerts: [
{msg: 'foo'},
{msg: 'bar'}
]
});
}));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
var $el = angular.element('<alert-messages></alert-messages>');
element = $compile($el)(scope);
scope.$digest();
}));
it('should show alert messages', function() {
expect(element.find('.alert-item').length).to.equal(2);
// Ignore the close buttons, which use an HTML entity for the close icon
element.find('a').remove();
expect(element.find('.alert-item').eq(0).text().trim()).to.equal('foo');
expect(element.find('.alert-item').eq(1).text().trim()).to.equal('bar');
});
});
| Migrate the tests for the alert service to vlui | Migrate the tests for the alert service to vlui
| JavaScript | bsd-3-clause | uwdata/vega-lite-ui,uwdata/vega-lite-ui,vega/vega-lite-ui,uwdata/vega-lite-ui,vega/vega-lite-ui,vega/vega-lite-ui | ---
+++
@@ -2,31 +2,32 @@
describe('Directive: alertMessages', function() {
- // load the directive's module
- beforeEach(module('polestar'));
-
var element,
scope;
- beforeEach(module('polestar', function($provide) {
- var mock = {
+ // load the directive's module
+ beforeEach(module('vlui', function($provide) {
+ // Mock the alerts service
+ $provide.value('Alerts', {
alerts: [
- {name: 'foo'},
- {name: 'bar'}
+ {msg: 'foo'},
+ {msg: 'bar'}
]
- };
- $provide.value('Alerts', mock);
+ });
}));
- beforeEach(inject(function($rootScope) {
+ beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
+ var $el = angular.element('<alert-messages></alert-messages>');
+ element = $compile($el)(scope);
+ scope.$digest();
}));
- it('should show alert messages', inject(function($compile) {
- element = angular.element('<alert-messages></alert-messages>');
- element = $compile(element)(scope);
- scope.$digest();
-
- expect(element.find('.alert-item').length).to.eql(2);
- }));
+ it('should show alert messages', function() {
+ expect(element.find('.alert-item').length).to.equal(2);
+ // Ignore the close buttons, which use an HTML entity for the close icon
+ element.find('a').remove();
+ expect(element.find('.alert-item').eq(0).text().trim()).to.equal('foo');
+ expect(element.find('.alert-item').eq(1).text().trim()).to.equal('bar');
+ });
}); |
4f33f1022273dfcaccd520ef6f58999373ddc871 | src/dashboard.directive.js | src/dashboard.directive.js | /**
* Mycockpit Directive
*/
(function() {
'use strict';
angular
.module('dashboard')
.directive('dashboard', ['dashboardFactory', function(dashboardFactory) {
// Width of the dashboard container
var currentWidth;
// To detet a change of column
var lastNumberColumns;
// Usually currentWidth / minWidth where max is numberMaxOfColumn
var numberOfColumnPossible;
// Width of columns in % to use in ng-style
var columnsWidth;
// Maximum number of columns
var numberMaxOfColumn;
// Thread to avoir too much event trigger during resize
var timeout;
return {
restrict: 'E',
scope: {
'id': '@',
'width': '@',
'columns': '@',
'columnsMinWidth': '@'
},
templateUrl: 'dashboard.directive.html',
controller: ['$scope', function(scope) {
var screenWidth = $( window ).width();
scope.dashboard = dashboardFactory.get(scope.id);
scope.dashboard.setOptions({
'width': scope['width'],
'columns': scope['columns'],
'columnsMinWidth': scope['columnsMinWidth']
});
scope.dashboard.refresh();
// On resize we refresh
window.addEventListener('resize', function(event) {
if ($( window ).width() !== screenWidth) {
clearTimeout(timeout);
timeout = setTimeout(function () {
scope.dashboard.refresh();
scope.$apply();
}, 150);
}
}, true);
}]
};
}]);
})();
| /**
* Mycockpit Directive
*/
(function() {
'use strict';
angular
.module('dashboard')
.directive('dashboard', ['dashboardFactory', function(dashboardFactory) {
// Width of the dashboard container
var currentWidth;
// To detet a change of column
var lastNumberColumns;
// Usually currentWidth / minWidth where max is numberMaxOfColumn
var numberOfColumnPossible;
// Width of columns in % to use in ng-style
var columnsWidth;
// Maximum number of columns
var numberMaxOfColumn;
// Thread to avoir too much event trigger during resize
var timeout;
return {
restrict: 'E',
scope: {
'id': '@',
'width': '@',
'columns': '@',
'columnsMinWidth': '@'
},
templateUrl: 'dashboard.directive.html',
controller: ['$scope', function(scope) {
currentWidth = $( window ).width();
scope.dashboard = dashboardFactory.get(scope.id);
scope.dashboard.setOptions({
'width': scope['width'],
'columns': scope['columns'],
'columnsMinWidth': scope['columnsMinWidth']
});
scope.dashboard.refresh();
// On resize we refresh
window.addEventListener('resize', function(event) {
if ($( window ).width() !== currentWidth) {
// update currentWidth with current window width
currentWidth = $( window ).width();
clearTimeout(timeout);
timeout = setTimeout(function () {
scope.dashboard.refresh();
scope.$apply();
}, 150);
}
}, true);
}]
};
}]);
})();
| Update dashboard current width when window is resized (eg: when table orientation changes). | Update dashboard current width when window is resized (eg: when table orientation changes).
| JavaScript | apache-2.0 | fluanceit/angular-dashboard,fluanceit/angular-dashboard,fluanceit/angular-dashboard | ---
+++
@@ -31,7 +31,7 @@
},
templateUrl: 'dashboard.directive.html',
controller: ['$scope', function(scope) {
- var screenWidth = $( window ).width();
+ currentWidth = $( window ).width();
scope.dashboard = dashboardFactory.get(scope.id);
@@ -46,11 +46,13 @@
// On resize we refresh
window.addEventListener('resize', function(event) {
- if ($( window ).width() !== screenWidth) {
+ if ($( window ).width() !== currentWidth) {
+ // update currentWidth with current window width
+ currentWidth = $( window ).width();
clearTimeout(timeout);
timeout = setTimeout(function () {
- scope.dashboard.refresh();
- scope.$apply();
+ scope.dashboard.refresh();
+ scope.$apply();
}, 150);
}
}, true); |
722a4c19db98955e257def819cb35431a6736328 | src/components/employee/EmployeeEdit.js | src/components/employee/EmployeeEdit.js | import React, { Component } from "react";
import { connect } from "react-redux";
import { employeeUpdate, employeeEdit, employeeEditSave } from "../../actions";
import { Card, CardSection, Button } from "../common";
import EmployeeForm from "./EmployeeForm";
class EmployeeEdit extends Component {
componentWillMount() {
this.props.employeeEdit(this.props.employee);
}
onButtonClick = () => {
const { name, phone, shift } = this.props;
this.props.employeeEditSave({
name,
phone,
shift,
uid: this.props.employee.uid
});
};
render() {
return (
<Card>
<EmployeeForm />
<CardSection>
<Button onPress={this.onButtonClick}>Save Changes</Button>
</CardSection>
</Card>
);
}
}
const mapStateToProps = state => {
const { name, phone, shift } = state.employeeForm;
return { name, phone, shift };
};
export default connect(mapStateToProps, {
employeeUpdate,
employeeEdit,
employeeEditSave
})(EmployeeEdit);
| import React, { Component } from "react";
import { connect } from "react-redux";
import Communications from "react-native-communications";
import { employeeUpdate, employeeEdit, employeeEditSave } from "../../actions";
import { Card, CardSection, Button, ConfirmDialog } from "../common";
import EmployeeForm from "./EmployeeForm";
class EmployeeEdit extends Component {
componentWillMount() {
this.props.employeeEdit(this.props.employee);
}
onButtonClick = () => {
const { name, phone, shift } = this.props;
this.props.employeeEditSave({
name,
phone,
shift,
uid: this.props.employee.uid
});
};
onTextClick = () => {
const { phone, shift } = this.props;
Communications.text(phone, `Your upcome shift is on ${shift}`);
};
onFireClick = () => {};
render() {
return (
<Card>
<EmployeeForm />
<CardSection>
<Button onPress={this.onButtonClick}>Save Changes</Button>
</CardSection>
<CardSection>
<Button onPress={this.onTextClick}>Text employee</Button>
</CardSection>
<CardSection>
<Button onPress={this.onFireClick}>Fire</Button>
</CardSection>
</Card>
);
}
}
const mapStateToProps = state => {
const { name, phone, shift } = state.employeeForm;
return { name, phone, shift };
};
export default connect(mapStateToProps, {
employeeUpdate,
employeeEdit,
employeeEditSave
})(EmployeeEdit);
| Add callback function to text button | [Employee] Add callback function to text button
This calls the native api to send some text message to the selected
employee.
Signed-off-by: Andre Loureiro <89b413c9cb95df28b97ff74e34cd65b0c0b16f96@gmail.com>
| JavaScript | mit | alvloureiro/Manager,alvloureiro/Manager,alvloureiro/Manager | ---
+++
@@ -1,7 +1,8 @@
import React, { Component } from "react";
import { connect } from "react-redux";
+import Communications from "react-native-communications";
import { employeeUpdate, employeeEdit, employeeEditSave } from "../../actions";
-import { Card, CardSection, Button } from "../common";
+import { Card, CardSection, Button, ConfirmDialog } from "../common";
import EmployeeForm from "./EmployeeForm";
class EmployeeEdit extends Component {
@@ -19,12 +20,28 @@
});
};
+ onTextClick = () => {
+ const { phone, shift } = this.props;
+ Communications.text(phone, `Your upcome shift is on ${shift}`);
+ };
+
+ onFireClick = () => {};
+
render() {
return (
<Card>
<EmployeeForm />
+
<CardSection>
<Button onPress={this.onButtonClick}>Save Changes</Button>
+ </CardSection>
+
+ <CardSection>
+ <Button onPress={this.onTextClick}>Text employee</Button>
+ </CardSection>
+
+ <CardSection>
+ <Button onPress={this.onFireClick}>Fire</Button>
</CardSection>
</Card>
); |
1f6603ae25e6dfa2636f8d7828f4456cf58ae9ac | example/controllers/football.js | example/controllers/football.js | 'use strict'
module.exports = (function(){
/**
* Import modules
*/
const footballDb = require('./../db/footballDb')
/**
* football module API
*/
return {
'leagues': leagues,
'leagueTable': leagueTable
}
/**
* football module API -- leagueTable
*/
function leagueTable(id) { // Auto parses id from query-string
return footballDb
.leagueTable(id)
.then(league => {
league.title = 'League Table'
return league
})
}
/**
* football module API -- leagues
*/
function leagues() {
return footballDb
.leagues()
.then(leagues => {
leagues = leaguesWithLinks(leagues)
return {
'title':'Leagues',
'leagues': leagues
}
})
}
/**
* Utility auxiliary function
*/
function leaguesWithLinks(leagues) {
return leagues.map(item => {
item.leagueHref = "/football/leagueTable?id=" + item.id
return item
})
}
})() | 'use strict'
module.exports = (function(){
/**
* Import modules
*/
const footballDb = require('./../db/footballDb')
/**
* football module API
*/
return {
'leagues': leagues,
'leagueTable_id': leagueTable_id
}
/**
* football module API -- leagueTable
*/
function leagueTable_id(id) { // Auto parses id from query-string
return footballDb
.leagueTable(id)
.then(league => {
league.title = 'League Table'
return league
})
}
/**
* football module API -- leagues
*/
function leagues() {
return footballDb
.leagues()
.then(leagues => {
leagues = leaguesWithLinks(leagues)
return {
'title':'Leagues',
'leagues': leagues
}
})
}
/**
* Utility auxiliary function
*/
function leaguesWithLinks(leagues) {
return leagues.map(item => {
item.leagueHref = "/football/leagueTable/" + item.id
return item
})
}
})() | Change id query parameter to route parameter | Change id query parameter to route parameter
| JavaScript | mit | CCISEL/connect-controller,CCISEL/connect-controller | ---
+++
@@ -11,12 +11,12 @@
*/
return {
'leagues': leagues,
- 'leagueTable': leagueTable
+ 'leagueTable_id': leagueTable_id
}
/**
* football module API -- leagueTable
*/
- function leagueTable(id) { // Auto parses id from query-string
+ function leagueTable_id(id) { // Auto parses id from query-string
return footballDb
.leagueTable(id)
.then(league => {
@@ -44,7 +44,7 @@
*/
function leaguesWithLinks(leagues) {
return leagues.map(item => {
- item.leagueHref = "/football/leagueTable?id=" + item.id
+ item.leagueHref = "/football/leagueTable/" + item.id
return item
})
} |
f7e7e3a7c60fcbdd99aab902fcc6484e5775905c | js/main.js | js/main.js | $(function() {
//tabs
$('ul.tabs li').click(function(){
var tab_id = $(this).attr('data-tab');
$('ul.tabs li').removeClass('current');
$('.tab-content').removeClass('current');
$(this).addClass('current');
$("#"+tab_id).addClass('current');
})
//retina
retinajs();
//sticky navigation
$("#sticker").sticky({
topSpacing: 105
}).on('sticky-end', function() {
//$("#sticker").addClass("sticky-end");
//setTimeout(function(){
// $("#sticker").removeClass("sticky-end");
//}, 1000);
});
//slider settings
$('.slick-slider').slick({
arrows: false,
infinite: true,
slidesToShow: 6,
slidesToScroll: 5,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 2,
infinite: true,
}
},
{
breakpoint: 700,
settings: {
slidesToShow: 2,
slidesToScroll: 1
}
}
]
});
$('header .next').click(function(){
$(".slick-slider").slick('slickNext');
});
});
| $(function() {
//tabs
$('ul.tabs li').click(function(){
var tab_id = $(this).attr('data-tab');
$('ul.tabs li').removeClass('current');
$('.tab-content').removeClass('current');
$(this).addClass('current');
$("#"+tab_id).addClass('current');
})
//retina
retinajs();
//sticky navigation
$("#sticker").sticky({
topSpacing: 105
}).on('sticky-end', function() {
//$("#sticker").addClass("sticky-end");
//setTimeout(function(){
// $("#sticker").removeClass("sticky-end");
//}, 1000);
});
//slider settings
$('.slick-slider').slick({
arrows: false,
infinite: true,
slidesToShow: 6,
slidesToScroll: 3,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 2,
infinite: true,
}
},
{
breakpoint: 700,
settings: {
slidesToShow: 2,
slidesToScroll: 1
}
}
]
});
$('header .next').click(function(){
$(".slick-slider").slick('slickNext');
});
});
| Change slider scroll count to 3 instead of 5 | Change slider scroll count to 3 instead of 5
| JavaScript | mit | chaddanna/d1-baseball,chaddanna/d1-baseball,chaddanna/d1-baseball | ---
+++
@@ -28,7 +28,7 @@
arrows: false,
infinite: true,
slidesToShow: 6,
- slidesToScroll: 5,
+ slidesToScroll: 3,
responsive: [
{
breakpoint: 1024, |
e47cffc722c0ae405eb2c00e2109b98b191019e1 | webpack/ts.config.js | webpack/ts.config.js | module.exports = function() {
return {
bail: true,
module: {
loaders: [
{
test: /\.ts$/,
exclude: /node_modules/,
loader: 'ts-loader',
},
],
},
resolve: {
extensions: ['', '.webpack.js','.web.js', '.js', '.ts'],
},
};
};
| module.exports = function() {
return {
bail: true,
module: {
loaders: [
{
test: /\.ts$/,
exclude: /node_modules/,
loader: 'ts-loader',
},
],
},
resolve: {
extensions: ['', '.webpack.js','.web.js', '.ts', '.js'],
},
};
};
| Resolve typescript files *before* resolving javascript files. | Resolve typescript files *before* resolving javascript files.
| JavaScript | mit | RenovoSolutions/Gulp-Typescript-Utilities | ---
+++
@@ -11,7 +11,7 @@
],
},
resolve: {
- extensions: ['', '.webpack.js','.web.js', '.js', '.ts'],
+ extensions: ['', '.webpack.js','.web.js', '.ts', '.js'],
},
};
}; |
2677136d8c46402c339207e4f5100ab09c0f4924 | backend/main.js | backend/main.js | import connect from 'connect';
import faker from 'faker';
import path from 'path';
import serveStatic from 'serve-static';
import uuid from 'node-uuid';
import {Server as WebSocketServer} from 'ws';
connect().use(serveStatic(path.join(__dirname, '../'))).listen(8080);
class ChatServer {
constructor(port) {
this.wss = new WebSocketServer({port: port});
this.wss.on('connection', this.handleConnection);
}
sendMessage = (nick, event, data) => {
const payload = JSON.stringify({
id: uuid.v4(),
nick,
event,
message: data
});
this.wss.clients.forEach(client => client.send(payload));
};
handleConnection = (ws) => {
const nick = faker.internet.userName();
this.sendMessage(nick, 'join');
ws.on('message', message => this.sendMessage(nick, 'message', message));
ws.on('close', message => this.sendMessage(nick, 'leave'));
}
}
let server = new ChatServer(6639);
process.on('SIGINT', () => {
setTimeout(process.exit, 100);
});
| import connect from 'connect';
import faker from 'faker';
import path from 'path';
import serveStatic from 'serve-static';
import uuid from 'node-uuid';
import {Server as WebSocketServer} from 'ws';
connect().use(serveStatic(path.join(__dirname, '../'))).listen(8080);
class ChatServer {
constructor(port) {
this.wss = new WebSocketServer({port});
this.wss.on('connection', this.handleConnection);
}
sendMessage = (nick, event, data) => {
const payload = JSON.stringify({
id: uuid.v4(),
nick,
event,
message: data
});
this.wss.clients.forEach(client => client.send(payload));
};
handleConnection = (ws) => {
const nick = faker.internet.userName();
this.sendMessage(nick, 'join');
ws.on('message', message => this.sendMessage(nick, 'message', message));
ws.on('close', message => this.sendMessage(nick, 'leave'));
}
}
let server = new ChatServer(6639);
process.on('SIGINT', () => {
setTimeout(process.exit, 100);
});
| Simplify object in ChatServer constructor. | Simplify object in ChatServer constructor.
| JavaScript | mit | zsiciarz/isthisachat,zsiciarz/isthisachat | ---
+++
@@ -9,7 +9,7 @@
class ChatServer {
constructor(port) {
- this.wss = new WebSocketServer({port: port});
+ this.wss = new WebSocketServer({port});
this.wss.on('connection', this.handleConnection);
}
|
acf34da2afb0fb2477e1d487c279fc6dc4c8b9f1 | src/network_manager.js | src/network_manager.js | var network = function () {
this.port = 8080;
this.ip = "127.0.0.1";
};
module.exports = new network(); | var network = function () {
this.port = process.env.PORT || 8080;
this.ip = "0.0.0.0";
};
module.exports = new network(); | Change port and ip for azure host | [Enhancement] Change port and ip for azure host
| JavaScript | mit | NikolaDimitroff/GiftOfTheSanctum,NikolaDimitroff/GiftOfTheSanctum,NikolaDimitroff/GiftOfTheSanctum | ---
+++
@@ -1,6 +1,6 @@
var network = function () {
- this.port = 8080;
- this.ip = "127.0.0.1";
+ this.port = process.env.PORT || 8080;
+ this.ip = "0.0.0.0";
};
module.exports = new network(); |
63aa47d7f16d6c1f568bd2a7af5185494ea35558 | tests/cross-context-instance.js | tests/cross-context-instance.js | let ivm = require('isolated-vm');
let isolate = new ivm.Isolate;
function makeContext() {
let context = isolate.createContextSync();
let global = context.global;
global.setSync('ivm', ivm);
isolate.compileScriptSync(`
function makeReference(ref) {
return new ivm.Reference(ref);
}
function isReference(ref) {
return ref instanceof ivm.Reference;
}
`).runSync(context);
return {
makeReference: global.getSync('makeReference'),
isReference: global.getSync('isReference'),
};
}
let context1 = makeContext();
let context2 = makeContext();
[ context1, context2 ].forEach(context => {
if (!context.isReference(new ivm.Reference({}))) {
console.log('fail1');
}
if (!context.isReference(context.makeReference(1))) {
console.log('fail2');
}
});
if (context1.isReference(context2.makeReference(1).derefInto())) {
console.log('fail3');
}
console.log('pass');
| let ivm = require('isolated-vm');
let isolate = new ivm.Isolate;
function makeContext() {
let context = isolate.createContextSync();
let global = context.global;
global.setSync('ivm', ivm);
isolate.compileScriptSync(`
function makeReference(ref) {
return new ivm.Reference(ref);
}
function isReference(ref) {
return ref instanceof ivm.Reference;
}
`).runSync(context);
return {
makeReference: global.getSync('makeReference'),
isReference: global.getSync('isReference'),
};
}
let context1 = makeContext();
let context2 = makeContext();
[ context1, context2 ].forEach(context => {
if (!context.isReference(new ivm.Reference({}))) {
console.log('fail1');
}
if (!context.isReference(context.makeReference({}))) {
console.log('fail2');
}
});
if (context1.isReference(context2.makeReference({}).derefInto())) {
console.log('fail3');
}
console.log('pass');
| Fix debug build test failure | Fix debug build test failure
Not really a bug here, v8 seems overzealous with this CHECK failure
| JavaScript | isc | laverdet/isolated-vm,laverdet/isolated-vm,laverdet/isolated-vm,laverdet/isolated-vm | ---
+++
@@ -25,11 +25,11 @@
if (!context.isReference(new ivm.Reference({}))) {
console.log('fail1');
}
- if (!context.isReference(context.makeReference(1))) {
+ if (!context.isReference(context.makeReference({}))) {
console.log('fail2');
}
});
-if (context1.isReference(context2.makeReference(1).derefInto())) {
+if (context1.isReference(context2.makeReference({}).derefInto())) {
console.log('fail3');
}
console.log('pass'); |
39e4fa236de4c9ed4053844c69e589c3b4b6af37 | lib/mongo_connect.js | lib/mongo_connect.js | 'use strict';
var logger = require('./logger'),
mongoose = require('mongoose');
// Log unexpected events.
var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error'];
events.forEach(function(event) {
mongoose.connection.on(event, function() {
logger.error('Mongo '+ event, arguments);
});
});
module.exports = function(callback) {
var config = require('api-umbrella-config').global();
// Connect to mongo using mongoose.
//
// Note: For this application, we don't particularly need an ODM like
// Mongoose, and the lower-level mongodb driver would meet our needs.
// However, when using the standalone driver, we were experiencing
// intermittent mongo connection drops in staging and production
// environments. I can't figure out how to reproduce the original issue in a
// testable way, so care should be taken if switching how mongo connects. See
// here for more details: https://github.com/NREL/api-umbrella/issues/17
mongoose.connect(config.get('mongodb.url'), config.get('mongodb.options'), callback);
};
| 'use strict';
var logger = require('./logger'),
mongoose = require('mongoose');
// Log unexpected events.
var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error'];
events.forEach(function(event) {
mongoose.connection.on(event, function(error) {
var logEvent = true;
if(event === 'disconnecting') {
mongoose.expectedCloseInProgress = true;
}
if(mongoose.expectedCloseInProgress) {
if(event === 'disconnecting' || event === 'disconnected' || event === 'close') {
logEvent = false;
}
}
if(event === 'close') {
mongoose.expectedCloseInProgress = false;
}
if(logEvent) {
logger.error('Mongo event: ' + event, error);
}
});
});
module.exports = function(callback) {
var config = require('api-umbrella-config').global();
// Connect to mongo using mongoose.
//
// Note: For this application, we don't particularly need an ODM like
// Mongoose, and the lower-level mongodb driver would meet our needs.
// However, when using the standalone driver, we were experiencing
// intermittent mongo connection drops in staging and production
// environments. I can't figure out how to reproduce the original issue in a
// testable way, so care should be taken if switching how mongo connects. See
// here for more details: https://github.com/NREL/api-umbrella/issues/17
mongoose.connect(config.get('mongodb.url'), config.get('mongodb.options'), callback);
};
| Improve mongo logging, so we only log unexpected disconnects. | Improve mongo logging, so we only log unexpected disconnects.
This cleans things up a bit so normal shutdown doesn't spew mongo
disconnect errors.
| JavaScript | mit | apinf/api-umbrella,NREL/api-umbrella-router,OdiloOrg/api-umbrella-router,NREL/api-umbrella-router,NREL/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,OdiloOrg/api-umbrella-router,NREL/api-umbrella-router,NREL/api-umbrella,NREL/api-umbrella,OdiloOrg/api-umbrella-router,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella | ---
+++
@@ -6,8 +6,26 @@
// Log unexpected events.
var events = ['disconnecting', 'disconnected', 'close', 'reconnected', 'error'];
events.forEach(function(event) {
- mongoose.connection.on(event, function() {
- logger.error('Mongo '+ event, arguments);
+ mongoose.connection.on(event, function(error) {
+ var logEvent = true;
+
+ if(event === 'disconnecting') {
+ mongoose.expectedCloseInProgress = true;
+ }
+
+ if(mongoose.expectedCloseInProgress) {
+ if(event === 'disconnecting' || event === 'disconnected' || event === 'close') {
+ logEvent = false;
+ }
+ }
+
+ if(event === 'close') {
+ mongoose.expectedCloseInProgress = false;
+ }
+
+ if(logEvent) {
+ logger.error('Mongo event: ' + event, error);
+ }
});
});
|
2945de8666055238fe2b43f60daad7aaf2279355 | lib/app.js | lib/app.js | module.exports = {
steamID: "",
steamNick: "",
steamError: "",
reconnectTries: 0,
connected: false,
away: false,
lastInvite: "",
lastChat: "",
ghostTimer: null,
users: {}, // steamID: { persona_state, player_name, game_name }
clans: {}, // chatID: { clan_name, user_count, user_live, members: { steamID: rank } }
friends: [], // [ steamID, ... ]
chats: [ "log" ],
currentChat: "log"
}; // TODO: move steam-specific keys to steam and ui-specific to UI
| module.exports = {
steamID: "",
steamNick: "",
steamError: "",
reconnectTries: 0,
connected: false,
away: false,
lastInvite: "",
lastChat: "",
ghostTimer: null,
users: {}, // steamID: { persona_state, player_name, game_name }
clans: {}, // chatID: { clan_name, user_count, user_live, members: { steamID: rank } }
friends: [], // [ steamID, ... ]
chats: [], // [ "log" | steamID | chatID, ... ]
currentChat: "log"
}; // TODO: move steam-specific keys to steam and ui-specific to UI
| Fix duplicate log chats bug | Fix duplicate log chats bug
| JavaScript | mit | rubyconn/steam-chat | ---
+++
@@ -11,6 +11,6 @@
users: {}, // steamID: { persona_state, player_name, game_name }
clans: {}, // chatID: { clan_name, user_count, user_live, members: { steamID: rank } }
friends: [], // [ steamID, ... ]
- chats: [ "log" ],
+ chats: [], // [ "log" | steamID | chatID, ... ]
currentChat: "log"
}; // TODO: move steam-specific keys to steam and ui-specific to UI |
920ab8209d85673038d04fa51a7a28593941c72a | app/errorResponse.js | app/errorResponse.js | const HTTPStatus = require('http-status-codes');
// eslint-disable-next-line no-unused-vars
function handleErrorResponse(err, req, res, next) {
const responseObject =
{
type: err.type || 'about:blank',
title:
err.message ||
HTTPStatus.getStatusText((err.statusCode || HTTPStatus.INTERNAL_SERVER_ERROR)),
status: err.statusCode || HTTPStatus.INTERNAL_SERVER_ERROR,
};
if (typeof err.detail !== 'undefined') {
responseObject.detail = err.detail;
}
res.status(responseObject.status);
res.send(responseObject);
}
module.exports = handleErrorResponse;
| const HTTPStatus = require('http-status-codes');
// eslint-disable-next-line no-unused-vars
function handleErrorResponse(err, req, res, next) {
const responseObject =
{
title:
err.message ||
HTTPStatus.getStatusText((err.statusCode || HTTPStatus.INTERNAL_SERVER_ERROR)),
status: err.statusCode || HTTPStatus.INTERNAL_SERVER_ERROR,
};
if (typeof err.detail !== 'undefined') {
responseObject.detail = err.detail;
}
res.status(responseObject.status);
res.send(responseObject);
}
module.exports = handleErrorResponse;
| Implement recommendation for json:api v1 error response | feat: Implement recommendation for json:api v1 error response
| JavaScript | mit | C3-TKO/junkan-server | ---
+++
@@ -4,7 +4,6 @@
function handleErrorResponse(err, req, res, next) {
const responseObject =
{
- type: err.type || 'about:blank',
title:
err.message ||
HTTPStatus.getStatusText((err.statusCode || HTTPStatus.INTERNAL_SERVER_ERROR)), |
40a460b2d9c707c9d532e8e155d8ea3c44af9b79 | frontend/src/components/ActiveVideoFeed.js | frontend/src/components/ActiveVideoFeed.js | import { connect } from "react-redux"
import * as trackActions from '../actions/trackActions'
import * as playlistActions from '../actions/playlistActions'
import VideoFeed from './VideoFeed'
const mapStateToProps = (state) => ({
activeFeedId: state.main.show,
items: state[state.main.show].items,
selectedId: state[state.main.show].selectedId
})
const mapDispatchToProps = (dispatch) => ({
tracks: {
onUpvote: (track) => dispatch(trackActions.upvoteTrack(track)),
onDownvote: (track) => dispatch(trackActions.downvoteTrack(track)),
onClickItem: (track) => dispatch(trackActions.setFeedNavigate(track.id))
},
playlists: {
onUpvote: (playlist) => dispatch(playlistActions.upvotePlaylist(playlist)),
onDownvote: (playlist) => dispatch(playlistActions.downvotePlaylist(playlist)),
onClickItem: (playlist) => dispatch(playlistActions.setFeedNavigate(playlist.id))
}
})
const mergeProps = (stateProps, dispatchProps, ownProps) => ({
...ownProps,
...stateProps,
...dispatchProps[stateProps.activeFeedId]
});
export default connect(
mapStateToProps,
mapDispatchToProps,
mergeProps
)(VideoFeed)
| import { connect } from "react-redux"
import _ from 'lodash'
import * as trackActions from '../actions/trackActions'
import * as playlistActions from '../actions/playlistActions'
import VideoFeed from './VideoFeed'
const mapStateToProps = (state) => ({
activeFeedId: state.main.show,
items: _.orderBy(state[state.main.show].items, ["value", "created_at"], ['desc', 'asc']),
selectedId: state[state.main.show].selectedId
})
const mapDispatchToProps = (dispatch) => ({
tracks: {
onUpvote: (track) => dispatch(trackActions.upvoteTrack(track)),
onDownvote: (track) => dispatch(trackActions.downvoteTrack(track)),
onClickItem: (track) => dispatch(trackActions.setFeedNavigate(track.id))
},
playlists: {
onUpvote: (playlist) => dispatch(playlistActions.upvotePlaylist(playlist)),
onDownvote: (playlist) => dispatch(playlistActions.downvotePlaylist(playlist)),
onClickItem: (playlist) => dispatch(playlistActions.setFeedNavigate(playlist.id))
}
})
const mergeProps = (stateProps, dispatchProps, ownProps) => ({
...ownProps,
...stateProps,
...dispatchProps[stateProps.activeFeedId]
});
export default connect(
mapStateToProps,
mapDispatchToProps,
mergeProps
)(VideoFeed)
| Sort items by votes annd created at | Sort items by votes annd created at
| JavaScript | mit | cthit/playIT-python,cthit/playIT-python,cthit/playIT-python,cthit/playIT-python | ---
+++
@@ -1,4 +1,5 @@
import { connect } from "react-redux"
+import _ from 'lodash'
import * as trackActions from '../actions/trackActions'
import * as playlistActions from '../actions/playlistActions'
@@ -8,7 +9,7 @@
const mapStateToProps = (state) => ({
activeFeedId: state.main.show,
- items: state[state.main.show].items,
+ items: _.orderBy(state[state.main.show].items, ["value", "created_at"], ['desc', 'asc']),
selectedId: state[state.main.show].selectedId
})
|
7432e639f1a5f4cd96a01df9692ae482f72889f6 | app/libs/job/show.js | app/libs/job/show.js | 'use strict';
// Load requirements
const parser = require('parse-torrent-name');
// Create promise to resolve with dataset
module.exports = function(filename) {
return new Promise((resolve, reject) => {
// Variables
let source;
// No file provided
if ( filename === undefined ) {
return reject('No filename provided');
}
// Check for tmdb key
/* istanbul ignore if */
if ( process.env.TMDB_KEY ) {
source = require('./show/tmdb')(process.env.TMDB_KEY);
} else {
source = require('./show/tvmaze')();
}
// Decode episode details from filename
let details = parser(filename);
// Check we have what we need to continue
// TODO: Replace with better validation
if ( ! details.title || ! details.season || ! details.episode ) {
return resolve({});
}
// Check for the show in cache
source.findShow(details.title).then((show) => {
return source.findEpisode(details.title, details.season, details.episode);
}).then((episode) => {
episode.type = 'show';
return resolve(episode);
}).catch((err) => {
return reject(err);
});
});
};
| 'use strict';
// Load requirements
const parser = require('parse-torrent-name');
// Load libraries
const settings = __require('libs/settings');
// Create promise to resolve with dataset
module.exports = function(filename) {
return new Promise((resolve, reject) => {
// Variables
let source;
// No file provided
if ( filename === undefined ) {
return reject('No filename provided');
}
// Check for tmdb key
/* istanbul ignore if */
if ( process.env.TMDB_KEY) {
source = require('./show/tmdb')(process.env.TMDB_KEY);
} else if ( settings.tmdb && settings.tmdb.key ) {
source = require('./show/tmdb')(settings.tmdb.key);
} else {
source = require('./show/tvmaze')();
}
// Decode episode details from filename
let details = parser(filename);
// Check we have what we need to continue
// TODO: Replace with better validation
if ( ! details.title || ! details.season || ! details.episode ) {
return resolve({});
}
// Check for the show in cache
source.findShow(details.title).then((show) => {
return source.findEpisode(details.title, details.season, details.episode);
}).then((episode) => {
episode.type = 'show';
return resolve(episode);
}).catch((err) => {
return reject(err);
});
});
};
| Add settings support for tmdb keys | Add settings support for tmdb keys
| JavaScript | apache-2.0 | transmutejs/core | ---
+++
@@ -2,6 +2,9 @@
// Load requirements
const parser = require('parse-torrent-name');
+
+// Load libraries
+const settings = __require('libs/settings');
// Create promise to resolve with dataset
module.exports = function(filename) {
@@ -17,8 +20,10 @@
// Check for tmdb key
/* istanbul ignore if */
- if ( process.env.TMDB_KEY ) {
+ if ( process.env.TMDB_KEY) {
source = require('./show/tmdb')(process.env.TMDB_KEY);
+ } else if ( settings.tmdb && settings.tmdb.key ) {
+ source = require('./show/tmdb')(settings.tmdb.key);
} else {
source = require('./show/tvmaze')();
} |
6448429f021d5babcc7d0df6742af5e271537acd | lib/create-set.test.js | lib/create-set.test.js | "use strict";
var assert = require("@sinonjs/referee").assert;
var createSet = require("./create-set");
describe("createSet", function() {
describe("when called without arguments", function() {
it("returns an empty Set", function() {
var set = createSet();
assert.isSet(set);
assert.equals(set.size, 0);
});
});
describe("when called with a non-empty Array", function() {
it("returns a Set with the same (distinct) members", function() {
var array = [0, 1, 1, 1, 1, 2, 3, 4];
var set = createSet(array);
set.forEach(function(value) {
assert.isTrue(array.includes(value));
});
});
});
describe("when called with non-Array or empty Array argument", function() {
it("throws a TypeError", function() {
var invalids = [
{},
new Date(),
new Set(),
new Map(),
null,
undefined
];
invalids.forEach(function(value) {
assert.exception(function() {
createSet(value);
}, /createSet can be called with either no arguments or an Array/);
});
});
});
});
| "use strict";
var assert = require("@sinonjs/referee").assert;
var createSet = require("./create-set");
describe("createSet", function() {
describe("when called without arguments", function() {
it("returns an empty Set", function() {
var set = createSet();
assert.isSet(set);
assert.equals(set.size, 0);
});
});
describe("when called with a non-empty Array", function() {
it("returns a Set with the same (distinct) members", function() {
var array = [0, 1, 1, 1, 1, 2, 3, 4];
var set = createSet(array);
set.forEach(function(value) {
assert.isTrue(array.indexOf(value) !== -1);
});
});
});
describe("when called with non-Array or empty Array argument", function() {
it("throws a TypeError", function() {
var invalids = [
{},
new Date(),
new Set(),
new Map(),
null,
undefined
];
invalids.forEach(function(value) {
assert.exception(function() {
createSet(value);
}, /createSet can be called with either no arguments or an Array/);
});
});
});
});
| Fix broken build in IE11 | Fix broken build in IE11
Don't use array.includes, it is not supported in IE11
| JavaScript | bsd-3-clause | busterjs/samsam | ---
+++
@@ -19,7 +19,7 @@
var set = createSet(array);
set.forEach(function(value) {
- assert.isTrue(array.includes(value));
+ assert.isTrue(array.indexOf(value) !== -1);
});
});
}); |
0e18aac64aeb5dff37e9fa93aec10e79ae7f8cbb | md2html.js | md2html.js | 'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const marked = require('marked');
const ECT = require('ect');
function md2html(filePath, cb) {
fs.readFile(filePath, 'utf8', (err, mdString) => {
if (err) {
cb(err);
return;
}
const content = marked(mdString);
const renderer = ECT({ root : __dirname });
const data = { title: filePath, content : content, dirname : __dirname };
const html = renderer.render('template.ect', data);
cb(null, html);
});
}
function toHtmlFile(mdFilePath, cb) {
md2html(mdFilePath, (err, html) => {
if (err) {
cb(err);
return;
}
const name = path.basename(mdFilePath, path.extname(mdFilePath))
const htmlPath = path.join(os.tmpdir(), name + '.html');
fs.writeFile(htmlPath, html, (err) => {
cb(err, htmlPath)
});
});
}
exports.toHtmlFile = toHtmlFile;
| 'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const marked = require('marked');
const ECT = require('ect');
function md2html(filePath, cb) {
fs.readFile(filePath, 'utf8', (err, mdString) => {
if (err) {
cb(err);
return;
}
const markedRenderer = new marked.Renderer();
markedRenderer.image = function(href, title, text) {
const imgAbsolutePath = path.resolve(path.dirname(filePath), href);
return marked.Renderer.prototype.image.call(this, imgAbsolutePath, title, text);
}
const content = marked(mdString, { renderer: markedRenderer });
const data = { title: filePath, content : content, dirname : __dirname };
const renderer = ECT({ root : __dirname });
const html = renderer.render('template.ect', data);
cb(null, html);
});
}
function toHtmlFile(mdFilePath, cb) {
md2html(mdFilePath, (err, html) => {
if (err) {
cb(err);
return;
}
const name = path.basename(mdFilePath, path.extname(mdFilePath))
const htmlPath = path.join(os.tmpdir(), name + '.html');
fs.writeFile(htmlPath, html, (err) => {
cb(err, htmlPath)
});
});
}
exports.toHtmlFile = toHtmlFile;
| Fix image file path at generated html file. | Fix image file path at generated html file.
| JavaScript | mit | fossamagna/electron-md2pdf-hands-on,fossamagna/electron-md2pdf-hands-on | ---
+++
@@ -12,9 +12,14 @@
cb(err);
return;
}
- const content = marked(mdString);
+ const markedRenderer = new marked.Renderer();
+ markedRenderer.image = function(href, title, text) {
+ const imgAbsolutePath = path.resolve(path.dirname(filePath), href);
+ return marked.Renderer.prototype.image.call(this, imgAbsolutePath, title, text);
+ }
+ const content = marked(mdString, { renderer: markedRenderer });
+ const data = { title: filePath, content : content, dirname : __dirname };
const renderer = ECT({ root : __dirname });
- const data = { title: filePath, content : content, dirname : __dirname };
const html = renderer.render('template.ect', data);
cb(null, html);
}); |
b6a20c3154eee2e347fcb08d67673c98f3a56107 | test/acceptance/features/step_definitions/common.js | test/acceptance/features/step_definitions/common.js | const { get } = require('lodash')
const { client } = require('nightwatch-cucumber')
const { When } = require('cucumber')
When(/^I (?:navigate|go|open|visit).*? `(.+)` page$/, async function (pageName) {
try {
const page = get(client.page, pageName)
await page().navigate()
} catch (error) {
throw new Error(`The page object '${pageName}' does not exist`)
}
})
| const { assign, camelCase, find, get, set } = require('lodash')
const { client } = require('nightwatch-cucumber')
const { When } = require('cucumber')
const fixtures = require('../../features/setup/fixtures')
When(/^I (?:navigate|go|open|visit).*? `(.+)` page$/, async function (pageName) {
try {
const page = get(client.page, pageName)
await page().navigate()
} catch (error) {
throw new Error(`The page object '${pageName}' does not exist`)
}
})
When(/^I (?:navigate|go|open|visit).*? `(.+)` page using `(.+)` `(.+)` fixture$/, async function (pageName, entity, fixtureName) {
const Page = get(client.page, pageName)()
const fixture = find(fixtures[entity], { name: fixtureName })
// TODO: Need to find a way to remove needing to store the item in state
const entityTypeFieldName = camelCase(entity)
set(this.state, entityTypeFieldName, assign({}, get(this.state, entityTypeFieldName), fixture))
await Page.navigate(Page.url(fixtureName))
})
| Add support for a new shared fixture step definition | Add support for a new shared fixture step definition
This creates a new step definition for navigating to fixtures directly
rather than via search.
| JavaScript | mit | uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend | ---
+++
@@ -1,6 +1,8 @@
-const { get } = require('lodash')
+const { assign, camelCase, find, get, set } = require('lodash')
const { client } = require('nightwatch-cucumber')
const { When } = require('cucumber')
+
+const fixtures = require('../../features/setup/fixtures')
When(/^I (?:navigate|go|open|visit).*? `(.+)` page$/, async function (pageName) {
try {
@@ -10,3 +12,15 @@
throw new Error(`The page object '${pageName}' does not exist`)
}
})
+
+When(/^I (?:navigate|go|open|visit).*? `(.+)` page using `(.+)` `(.+)` fixture$/, async function (pageName, entity, fixtureName) {
+ const Page = get(client.page, pageName)()
+
+ const fixture = find(fixtures[entity], { name: fixtureName })
+
+ // TODO: Need to find a way to remove needing to store the item in state
+ const entityTypeFieldName = camelCase(entity)
+ set(this.state, entityTypeFieldName, assign({}, get(this.state, entityTypeFieldName), fixture))
+
+ await Page.navigate(Page.url(fixtureName))
+}) |
afbbbee87cf24dfcbfb9c52928d7cfe68b7d4680 | node/ls.js | node/ls.js | var path = '../data/snippets';
// TODO list this folder
| var fs = require('fs');
var os = require('os');
var path = '../data/snippets';
var folders = fs.readdirSync(path);
var files = {};
folders.forEach(function (folder) {
files[folder] = fs.readdirSync(path+'/'+folder);
});
console.log(files);
| Read files with NodeJS script | Read files with NodeJS script
| JavaScript | apache-2.0 | Codeberry-Black/code-quiz,Codeberry-Black/code-quiz | ---
+++
@@ -1,3 +1,13 @@
+var fs = require('fs');
+var os = require('os');
+
var path = '../data/snippets';
-// TODO list this folder
+var folders = fs.readdirSync(path);
+var files = {};
+
+folders.forEach(function (folder) {
+ files[folder] = fs.readdirSync(path+'/'+folder);
+});
+
+console.log(files); |
4caea3daea0c05ac4b184daa61e4fdf11187c7b1 | package.js | package.js | Package.describe({
summary: "Reactive bootstrap modals for meteor",
version: "1.0.4",
git: "https://github.com/jchristman/reactive-modal.git",
name: "jchristman:reactive-modal"
});
Package.on_use(function (api) {
if(api.versionsFrom){
api.versionsFrom('METEOR@1.0');
}
api.use(['underscore', 'jquery','templating', 'reactive-var@1.0.5'], 'client');
api.add_files(['lib/reactive-modal.html', 'lib/reactive-modal.js', 'lib/ev.js'], "client");
api.export('ReactiveModal', ['client']);
});
| Package.describe({
summary: "Reactive bootstrap modals for meteor",
version: "1.0.5",
git: "https://github.com/jchristman/reactive-modal.git",
name: "jchristman:reactive-modal"
});
Package.on_use(function (api) {
if(api.versionsFrom){
api.versionsFrom('METEOR@1.0');
}
api.use(['underscore', 'jquery','templating', 'reactive-var@1.0.6'], 'client');
api.add_files(['lib/reactive-modal.html', 'lib/reactive-modal.js', 'lib/ev.js'], "client");
api.export('ReactiveModal', ['client']);
});
| Update depedencies and version number | Update depedencies and version number
| JavaScript | mit | jchristman/reactive-modal,jchristman/reactive-modal | ---
+++
@@ -1,6 +1,6 @@
Package.describe({
summary: "Reactive bootstrap modals for meteor",
- version: "1.0.4",
+ version: "1.0.5",
git: "https://github.com/jchristman/reactive-modal.git",
name: "jchristman:reactive-modal"
});
@@ -9,7 +9,7 @@
if(api.versionsFrom){
api.versionsFrom('METEOR@1.0');
}
- api.use(['underscore', 'jquery','templating', 'reactive-var@1.0.5'], 'client');
+ api.use(['underscore', 'jquery','templating', 'reactive-var@1.0.6'], 'client');
api.add_files(['lib/reactive-modal.html', 'lib/reactive-modal.js', 'lib/ev.js'], "client");
api.export('ReactiveModal', ['client']);
}); |
cb9c6e73a80b833763c5d0a6bdfb2a25d358e3f9 | app/lib/lang/index.js | app/lib/lang/index.js | 'use strict';
// Load our requirements
const i18n = require('i18n'),
path = require('path'),
logger = require('../log');
// Variables
let localeDir = path.resolve('./locales');
// Configure the localization engine
i18n.configure({
locales: require('./available-locales')(localeDir),
defaultLocale: 'en',
directory: localeDir,
syncFiles: true,
autoReload: true,
register: global,
api: {
'__': 'lang',
'__n': 'plural'
},
logDebugFn: (msg) => {
return logger.debug(msg);
},
logWarnFn: (msg) => {
return logger.warn(msg);
},
logErrorFn: (msg) => {
return logger.error(msg);
}
});
// Set the default locale
i18n.setLocale(( process.env.LANG !== undefined ? process.env.LANG : 'en' ));
// Export for future use
module.exports = i18n;
| 'use strict';
// Load our requirements
const i18n = require('i18n'),
path = require('path'),
logger = require('../log');
// Variables
let localeDir = path.resolve('./locales');
// Configure the localization engine
i18n.configure({
locales: require('./available-locales')(localeDir),
defaultLocale: 'en',
directory: localeDir,
syncFiles: true,
autoReload: true,
register: global,
api: {
'__': 'lang',
'__n': 'plural'
}
});
// Set the default locale
i18n.setLocale( process.env.LOCALE || 'en' );
// Export for future use
module.exports = i18n;
| Revert to default logger for i18n | Revert to default logger for i18n
| JavaScript | apache-2.0 | transmutejs/core | ---
+++
@@ -19,20 +19,11 @@
api: {
'__': 'lang',
'__n': 'plural'
- },
- logDebugFn: (msg) => {
- return logger.debug(msg);
- },
- logWarnFn: (msg) => {
- return logger.warn(msg);
- },
- logErrorFn: (msg) => {
- return logger.error(msg);
}
});
// Set the default locale
-i18n.setLocale(( process.env.LANG !== undefined ? process.env.LANG : 'en' ));
+i18n.setLocale( process.env.LOCALE || 'en' );
// Export for future use
module.exports = i18n; |
dd7471f84f28b222c1e085f666150b2222be6b37 | options.js | options.js | var eslint = require('eslint')
var path = require('path')
var pkg = require('./package.json')
module.exports = {
bugs: pkg.bugs.url,
cmd: 'standard',
cwd: __dirname,
eslint: eslint,
eslintConfig: {
configFile: path.join(__dirname, 'eslintrc.json')
},
formatter: 'Formatting is no longer included with standard. Install it separately: "npm install -g standard-format"',
homepage: pkg.homepage,
tagline: 'Use JavaScript Standard Style',
version: pkg.version
}
| var eslint = require('eslint')
var path = require('path')
var pkg = require('./package.json')
module.exports = {
bugs: pkg.bugs.url,
cmd: 'standard',
eslint: eslint,
eslintConfig: {
configFile: path.join(__dirname, 'eslintrc.json')
},
formatter: 'Formatting is no longer included with standard. Install it separately: "npm install -g standard-format"',
homepage: pkg.homepage,
tagline: 'Use JavaScript Standard Style',
version: pkg.version
}
| Remove cwd option to standard-engine | Remove cwd option to standard-engine
| JavaScript | mit | LinusU/standard,feross/standard,LinusU/standard,SimenB/standard,SimenB/standard,jasonpincin/standard,JedWatson/happiness,JedWatson/happiness,feross/standard,standard/standard,standard/standard | ---
+++
@@ -5,7 +5,6 @@
module.exports = {
bugs: pkg.bugs.url,
cmd: 'standard',
- cwd: __dirname,
eslint: eslint,
eslintConfig: {
configFile: path.join(__dirname, 'eslintrc.json') |
a50b46f8f50f52b6e16ef5e842e2961ae6ef6f8d | app/models/course.js | app/models/course.js | 'use strict';
import * as _ from 'lodash'
import * as React from 'react'
import * as humanize from 'humanize-plus'
var Course = React.createClass({
render() {
let title = this.props.info.type === 'Topic' ? this.props.info.name : this.props.info.title;
let summary = React.DOM.article({className: 'course'},
React.DOM.div({className: 'info-rows'},
React.DOM.h1({className: 'title'}, title),
React.DOM.span({className: 'details'},
React.DOM.span({className: 'identifier'},
React.DOM.span({className: 'department'}, this.props.info.dept),
' ', React.DOM.span({className: 'number'}, this.props.info.num),
this.props.info.sect ?
React.DOM.span({className: 'section'}, this.props.info.sect) :
''),
React.DOM.span({className: 'professors'}, humanize.oxford(this.props.info.profs)))
),
React.DOM.div({
className: 'info-button',
})
)
return summary;
}
})
export default Course
| 'use strict';
import * as _ from 'lodash'
import * as React from 'react'
import * as humanize from 'humanize-plus'
import {DragDropMixin} from '../../node_modules/react-dnd/dist/ReactDND.min'
import itemTypes from '../objects/itemTypes'
var Course = React.createClass({
mixins: [DragDropMixin],
configureDragDrop(registerType) {
registerType(itemTypes.COURSE, {
dragSource: {
beginDrag() {
return {
item: {clbid: this.props.info.clbid}
}
}
}
})
},
render() {
let title = this.props.info.type === 'Topic' ? this.props.info.name : this.props.info.title;
let summary = React.DOM.article(
Object.assign({className: 'course'}, this.dragSourceFor(itemTypes.COURSE)),
React.DOM.div({className: 'info-rows'},
React.DOM.h1({className: 'title'}, title),
React.DOM.span({className: 'details'},
React.DOM.span({className: 'identifier'},
React.DOM.span({className: 'department'}, this.props.info.dept),
' ', React.DOM.span({className: 'number'}, this.props.info.num),
this.props.info.sect ?
React.DOM.span({className: 'section'}, this.props.info.sect) :
''),
React.DOM.span({className: 'professors'}, humanize.oxford(this.props.info.profs)))
),
React.DOM.div({
className: 'info-button',
})
)
return summary;
}
})
export default Course
| Make Course draggable When dropped, it returns {clbid: <it's clbid>} | Make Course draggable
When dropped, it returns {clbid: <it's clbid>}
| JavaScript | agpl-3.0 | hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook | ---
+++
@@ -4,11 +4,30 @@
import * as React from 'react'
import * as humanize from 'humanize-plus'
+import {DragDropMixin} from '../../node_modules/react-dnd/dist/ReactDND.min'
+import itemTypes from '../objects/itemTypes'
+
var Course = React.createClass({
+ mixins: [DragDropMixin],
+
+ configureDragDrop(registerType) {
+ registerType(itemTypes.COURSE, {
+ dragSource: {
+ beginDrag() {
+ return {
+ item: {clbid: this.props.info.clbid}
+ }
+ }
+ }
+ })
+ },
+
render() {
let title = this.props.info.type === 'Topic' ? this.props.info.name : this.props.info.title;
- let summary = React.DOM.article({className: 'course'},
+ let summary = React.DOM.article(
+ Object.assign({className: 'course'}, this.dragSourceFor(itemTypes.COURSE)),
+
React.DOM.div({className: 'info-rows'},
React.DOM.h1({className: 'title'}, title),
React.DOM.span({className: 'details'}, |
12d31ec96802524deec6d3cb2b5345dd5e51a57b | app/models/ticket.js | app/models/ticket.js | //////////////////////////////
// Handles the Ticket model //
//////////////////////////////
'use strict';
module.exports = function (sequelize, DataTypes) {
var Ticket = sequelize.define('Ticket', {
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
username: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false
},
student: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
contributor: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
paid: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
paid_at: {
type: DataTypes.DATE,
},
paid_with: {
type: DataTypes.STRING(45)
},
temporarlyOut: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
}
// Association with Price
// Association with Event
// Association with Mean of Payment
}, {
underscored: true,
paranoid: true
});
return Ticket;
};
| //////////////////////////////
// Handles the Ticket model //
//////////////////////////////
'use strict';
module.exports = function (sequelize, DataTypes) {
var Ticket = sequelize.define('Ticket', {
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
username: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false
},
student: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
contributor: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
paid: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
paid_at: {
type: DataTypes.DATE,
},
paid_with: {
type: DataTypes.STRING(45)
},
temporarlyOut: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
barcode: {
type: DataTypes.STRING(13),
allowNull: false,
unique: true
}
// Association with Price
// Association with Event
// Association with Mean of Payment
}, {
underscored: true,
paranoid: true
});
return Ticket;
};
| Add barcode to Ticket db structure | Add barcode to Ticket db structure
| JavaScript | mit | buckutt/BuckUTT-pay,buckutt/BuckUTT-pay,buckutt/BuckUTT-pay | ---
+++
@@ -48,6 +48,12 @@
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
+ },
+
+ barcode: {
+ type: DataTypes.STRING(13),
+ allowNull: false,
+ unique: true
}
// Association with Price |
a0c52d88cb8836d9bc9532bbf885e91731365b8e | src/assets/dosamigos-ckeditor.widget.js | src/assets/dosamigos-ckeditor.widget.js | /**
* @copyright Copyright (c) 2012-2015 2amigOS! Consulting Group LLC
* @link http://2amigos.us
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
if (typeof dosamigos == "undefined" || !dosamigos) {
var dosamigos = {};
}
dosamigos.ckEditorWidget = (function ($) {
var pub = {
registerOnChangeHandler: function (id) {
CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () {
CKEDITOR.instances[id].updateElement();
$('#' + id).trigger('change');
return false;
});
},
registerCsrfImageUploadHandler: function () {
yii & $(document).off('click', '.cke_dialog_tabs a[title="Upload"]').on('click', '.cke_dialog_tabs a[title="Upload"]', function () {
var $forms = $('.cke_dialog_ui_input_file iframe').contents().find('form');
var csrfName = yii.getCsrfParam();
$forms.each(function () {
if (!$(this).find('input[name=' + csrfName + ']').length) {
var csrfTokenInput = $('<input/>').attr({
'type': 'hidden',
'name': csrfName
}).val(yii.getCsrfToken());
$(this).append(csrfTokenInput);
}
});
});
}
};
return pub;
})(jQuery);
| /**
* @copyright Copyright (c) 2012-2015 2amigOS! Consulting Group LLC
* @link http://2amigos.us
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*/
if (typeof dosamigos == "undefined" || !dosamigos) {
var dosamigos = {};
}
dosamigos.ckEditorWidget = (function ($) {
var pub = {
registerOnChangeHandler: function (id) {
CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () {
CKEDITOR.instances[id].updateElement();
$('#' + id).trigger('change');
return false;
});
},
registerCsrfImageUploadHandler: function () {
yii & $(document).off('click', '.cke_dialog_tabs a[id^="cke_Upload_"]').on('click', '.cke_dialog_tabs a[id^="cke_Upload_"]', function () {
var $forms = $('.cke_dialog_ui_input_file iframe').contents().find('form');
var csrfName = yii.getCsrfParam();
$forms.each(function () {
if (!$(this).find('input[name=' + csrfName + ']').length) {
var csrfTokenInput = $('<input/>').attr({
'type': 'hidden',
'name': csrfName
}).val(yii.getCsrfToken());
$(this).append(csrfTokenInput);
}
});
});
}
};
return pub;
})(jQuery);
| Fix bug when locale isn't English. | Fix bug when locale isn't English.
| JavaScript | bsd-3-clause | alexdin/yii2-ckeditor-widget,richardfan1126/yii2-ckeditor-widget,alexdin/yii2-ckeditor-widget,yangtoude/yii2-ckeditor-widget,richardfan1126/yii2-ckeditor-widget,yangtoude/yii2-ckeditor-widget,yangtoude/yii2-ckeditor-widget,richardfan1126/yii2-ckeditor-widget | ---
+++
@@ -18,7 +18,7 @@
});
},
registerCsrfImageUploadHandler: function () {
- yii & $(document).off('click', '.cke_dialog_tabs a[title="Upload"]').on('click', '.cke_dialog_tabs a[title="Upload"]', function () {
+ yii & $(document).off('click', '.cke_dialog_tabs a[id^="cke_Upload_"]').on('click', '.cke_dialog_tabs a[id^="cke_Upload_"]', function () {
var $forms = $('.cke_dialog_ui_input_file iframe').contents().find('form');
var csrfName = yii.getCsrfParam();
$forms.each(function () { |
e1e087cd2531371c9450f6e3a079a05f6d3dc5c4 | package.js | package.js | Package.describe({
summary: "meteor sql bindings for server-side calls"
});
Npm.depends({ "newrelic": "1.0.1" });
Package.on_use(function(api) {
if (api.export) api.export('newrelic', 'server');
api.add_files('newrelic_npm.js', 'server');
});
| Package.describe({
summary: "meteor sql bindings for server-side calls"
});
Npm.depends({ "newrelic": "1.3.0" });
Package.on_use(function(api) {
if (api.export) api.export('newrelic', 'server');
api.add_files('newrelic_npm.js', 'server');
});
| Update New Relic library to 1.3.0 | Update New Relic library to 1.3.0
| JavaScript | mit | andreioprisan/meteor-newrelic,mycartio/newrelic | ---
+++
@@ -2,7 +2,7 @@
summary: "meteor sql bindings for server-side calls"
});
-Npm.depends({ "newrelic": "1.0.1" });
+Npm.depends({ "newrelic": "1.3.0" });
Package.on_use(function(api) {
if (api.export) api.export('newrelic', 'server'); |
46822d801d50990efa5892ccbe79be60884a8c3d | public/sw.js | public/sw.js | this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('learn-memory').then(function(cache) {
return cache.addAll([
'/',
'/stylesheets/styles.css',
'/views/lessons-list.html',
'/views/lessons-id.html',
'/javascripts/scripts.js',
'/langs/locale-en.json'
]);
})
);
});
this.addEventListener('fetch', function(event) {
if (event.request.method !== 'GET' || /authenticated/.test(event.request.url)) {
return;
}
var get = function () {
return fetch(event.request).then(function(response) {
return caches.open('learn-memory').then(function(cache) {
cache.put(event.request, response.clone());
return response;
});
});
};
event.respondWith(
caches
.match(event.request)
.then(function(cached) {
// get the latest updates from API
if (/api/.test(event.request.url)) {
return get().catch(function () {
return cached;
});
}
// the cached value could be undefined
if (typeof cached == 'undefined') {
return get();
}
return cached;
})
.catch(get)
);
});
| this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('learn-memory-1500879945180').then(function(cache) {
return cache.addAll([
'/',
'/stylesheets/styles.css',
'/views/lessons-list.html',
'/views/lessons-id.html',
'/javascripts/scripts.js',
'/langs/locale-en.json'
]);
})
);
});
this.addEventListener('fetch', function(event) {
if (event.request.method !== 'GET' || /authenticated/.test(event.request.url)) {
return;
}
var get = function () {
return fetch(event.request).then(function(response) {
return caches.open('learn-memory').then(function(cache) {
cache.put(event.request, response.clone());
return response;
});
});
};
event.respondWith(
caches
.match(event.request)
.then(function(cached) {
// get the latest updates from API
if (/api/.test(event.request.url)) {
return get().catch(function () {
return cached;
});
}
// the cached value could be undefined
if (typeof cached == 'undefined') {
return get();
}
return cached;
})
.catch(get)
);
});
this.addEventListener('activate', function(event) {
var cacheWhitelist = ['learn-memory-1500879945180'];
event.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (cacheWhitelist.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
});
| Add a system to update service worker | Add a system to update service worker
sw.js
| JavaScript | mit | cedced19/learn-memory,cedced19/learn-memory | ---
+++
@@ -1,6 +1,6 @@
this.addEventListener('install', function(event) {
event.waitUntil(
- caches.open('learn-memory').then(function(cache) {
+ caches.open('learn-memory-1500879945180').then(function(cache) {
return cache.addAll([
'/',
'/stylesheets/styles.css',
@@ -47,3 +47,17 @@
.catch(get)
);
});
+
+this.addEventListener('activate', function(event) {
+ var cacheWhitelist = ['learn-memory-1500879945180'];
+
+ event.waitUntil(
+ caches.keys().then(function(keyList) {
+ return Promise.all(keyList.map(function(key) {
+ if (cacheWhitelist.indexOf(key) === -1) {
+ return caches.delete(key);
+ }
+ }));
+ })
+ );
+}); |
dbd69a35dfddbe8d42f147680cb196e88c127abb | app/server/player.js | app/server/player.js | class Player {
constructor({ socket }) {
// The identifier for this player, unique on a per-room level
this.id = Date.now();
// The current socket assocuat
this.socket = socket;
// The player's total number of wins across all games
this.score = 0;
}
}
module.exports = Player;
| class Player {
constructor({ socket }) {
// The identifier for this player, unique on a per-room level
this.id = Date.now();
// The current socket assocuat
this.socket = socket;
// The player's total number of wins across all games
this.score = 0;
}
toJSON() {
return {
name: this.name,
score: this.score
};
}
}
module.exports = Player;
| Fix infinite recursion on server | Fix infinite recursion on server
| JavaScript | mit | caleb531/connect-four | ---
+++
@@ -9,6 +9,13 @@
this.score = 0;
}
+ toJSON() {
+ return {
+ name: this.name,
+ score: this.score
+ };
+ }
+
}
module.exports = Player; |
9573aa16fad08be19eb0ed138d45a20af0ea3787 | options.js | options.js | function initSettings() {
var globalSettings = getGlobalSettings();
if (globalSettings['hw_accel']) {
$('hw_accel').value = globalSettings['hw_accel'];
}
}
function onForget() {
resetSiteSchemes();
loadSettingsDisplay();
update();
}
// Open all links in new tabs.
function onLinkClick() {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
(function () {
var ln = links[i];
var location = ln.href;
ln.onclick = function () {
chrome.tabs.create({active: true, url: location});
};
})();
}
}
function onHwAccel(evt) {
setGlobalSetting('hw_accel', evt.target.value);
}
function loadSettingsDisplay() {
var settings = {
'version': 1,
'schemes': JSON.parse(localStorage['siteschemes']),
'modifiers': JSON.parse(localStorage['sitemodifiers'] || '{}')
}
$('settings').value = JSON.stringify(settings, null, 4);
}
function init() {
initSettings();
$('forget').addEventListener('click', onForget, false);
$('hw_accel').addEventListener('change', onHwAccel, false);
loadSettingsDisplay();
}
window.addEventListener('load', init, false);
document.addEventListener('DOMContentLoaded', onLinkClick);
| function initSettings() {
var globalSettings = getGlobalSettings();
if (globalSettings['hw_accel']) {
$('hw_accel').value = globalSettings['hw_accel'];
}
}
function onForget() {
resetSiteSchemes();
loadSettingsDisplay();
}
// Open all links in new tabs.
function onLinkClick() {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
(function () {
var ln = links[i];
var location = ln.href;
ln.onclick = function () {
chrome.tabs.create({active: true, url: location});
};
})();
}
}
function onHwAccel(evt) {
setGlobalSetting('hw_accel', evt.target.value);
}
function loadSettingsDisplay() {
var settings = {
'version': 1,
'schemes': JSON.parse(localStorage['siteschemes']),
'modifiers': JSON.parse(localStorage['sitemodifiers'] || '{}')
}
$('settings').value = JSON.stringify(settings, null, 4);
}
function init() {
initSettings();
$('forget').addEventListener('click', onForget, false);
$('hw_accel').addEventListener('change', onHwAccel, false);
loadSettingsDisplay();
}
window.addEventListener('load', init, false);
document.addEventListener('DOMContentLoaded', onLinkClick);
| Fix error clearing site customizations | Fix error clearing site customizations
| JavaScript | bsd-2-clause | abstiles/deluminate,heyalexchoi/deluminate,heyalexchoi/deluminate,abstiles/deluminate,abstiles/deluminate | ---
+++
@@ -8,7 +8,6 @@
function onForget() {
resetSiteSchemes();
loadSettingsDisplay();
- update();
}
// Open all links in new tabs. |
f8a2b5fdd50b0a0b894c08e0c18e3a7d3b951039 | src/impure-react/connectIO.js | src/impure-react/connectIO.js |
import React from 'react'
import PropTypes from 'prop-types'
import _ from 'lodash'
import { compose, getContext, mapProps, withHandlers } from 'recompose'
export const connectIO = (handlers) => compose(
getContext({
runIO: PropTypes.func
}),
withHandlers(_.mapValues(handlers, (handler) => {
return ({ runIO, ...props }) => (...args) => {
return runIO(handler(props)(...args))
}
})),
mapProps(({ runIO, ...props }) => props)
)
export default connectIO
|
import PropTypes from 'prop-types'
import _ from 'lodash'
import { compose, getContext, mapProps, withHandlers } from 'recompose'
export const connectIO = (handlers) => compose(
getContext({
runIO: PropTypes.func
}),
withHandlers(_.mapValues(handlers, (handler) => {
return ({ runIO, ...props }) => (...args) => {
return runIO(handler(props)(...args))
}
})),
mapProps(({ runIO, ...props }) => props)
)
export default connectIO
| Remove unused reference to React | :rotating_light: Remove unused reference to React
| JavaScript | agpl-3.0 | bemusic/bemuse,bemusic/bemuse,bemusic/bemuse,bemusic/bemuse,bemusic/bemuse | ---
+++
@@ -1,5 +1,4 @@
-import React from 'react'
import PropTypes from 'prop-types'
import _ from 'lodash'
import { compose, getContext, mapProps, withHandlers } from 'recompose' |
011261eb9d8b673b6190139fa1ab8b2815c87cee | package.js | package.js | Package.describe({
summary: "Methods to create admin role and add first admin user.",
version: "0.1.0",
name: "brylie:first-admin",
git: "https://github.com/brylie/meteor-first-user-admin"
});
Package.on_use(function (api, where) {
api.versionsFrom("1.0.1");
api.use('accounts-base', ['server']);
api.use("alanning:roles@1.2.11", ['server']);
api.use("underscore", ['server']);
api.add_files('server/methods/roles.js', ['server']);
api.add_files('server/methods/users.js', ['server']);
});
| Package.describe({
summary: "Methods to create admin role and add first admin user.",
version: "0.1.1",
name: "brylie:first-admin",
git: "https://github.com/brylie/meteor-first-user-admin"
});
Package.on_use(function (api, where) {
api.versionsFrom("1.0.1");
api.use('accounts-base', ['server']);
api.use("alanning:roles@1.2.11", ['server']);
api.add_files('server/methods/roles.js', ['server']);
api.add_files('server/methods/users.js', ['server']);
});
| Remove underscore dependency; cleanup whitespace | Remove underscore dependency; cleanup whitespace
| JavaScript | mit | brylie/meteor-first-user-admin | ---
+++
@@ -1,16 +1,15 @@
Package.describe({
- summary: "Methods to create admin role and add first admin user.",
- version: "0.1.0",
- name: "brylie:first-admin",
+ summary: "Methods to create admin role and add first admin user.",
+ version: "0.1.1",
+ name: "brylie:first-admin",
git: "https://github.com/brylie/meteor-first-user-admin"
});
Package.on_use(function (api, where) {
api.versionsFrom("1.0.1");
- api.use('accounts-base', ['server']);
- api.use("alanning:roles@1.2.11", ['server']);
- api.use("underscore", ['server']);
+ api.use('accounts-base', ['server']);
+ api.use("alanning:roles@1.2.11", ['server']);
- api.add_files('server/methods/roles.js', ['server']);
- api.add_files('server/methods/users.js', ['server']);
+ api.add_files('server/methods/roles.js', ['server']);
+ api.add_files('server/methods/users.js', ['server']);
}); |
a3ae5d89bb4218700a898f7d3a203f06dc9c1398 | package.js | package.js | Package.describe({
name: 'nimblenotes:typed.js',
version: '0.0.1',
summary: 'Typed.js v1.1.1',
git: 'https://github.com/NimbleNotes/nimblenotes-packages',
documentation: 'README.md'
});
Package.onUse(function (api) {
api.versionsFrom('1.1.0.2');
api.use([
'jquery',
'nimblenotes:jquery-autosize@0.0.1'
], 'client');
api.addFiles([
'js/typed.js'
], 'client');
});
| Package.describe({
name: 'nimblenotes:typed.js',
version: '0.0.1',
summary: 'Typed.js v1.1.1',
git: 'https://github.com/NimbleNotes/nimblenotes-packages',
documentation: 'README.md'
});
Package.onUse(function (api) {
api.versionsFrom('1.1.0.2');
api.use([
'jquery',
], 'client');
api.addFiles([
'js/typed.js'
], 'client');
});
| Remove dependency on jquery autosize | Remove dependency on jquery autosize
| JavaScript | mit | NimbleNotes/typed.js,NimbleNotes/typed.js | ---
+++
@@ -11,7 +11,6 @@
api.use([
'jquery',
- 'nimblenotes:jquery-autosize@0.0.1'
], 'client');
api.addFiles([
'js/typed.js' |
ced746b51521941263720a32e547a1ef69718ccc | lib/resources/index.js | lib/resources/index.js | 'use strict';
var fs = require('fs'), files = fs.readdirSync('./lib/resources');
var resources = {}, resource, i = 0, l = files.length;
for(; i < l; i++) {
resource = files[i];
if(resource === 'index.js' ||
resource === 'resourceBase.js' ||
resource.indexOf('.js') < 0) {
continue;
}
resource = resource.replace('.js', '');
resources[resource] = require('./' + resource);
}
module.exports = resources;
| 'use strict';
var fs = require('fs'), files = fs.readdirSync(__dirname);
var resources = {}, resource, i = 0, l = files.length;
for(; i < l; i++) {
resource = files[i];
if(resource === 'index.js' ||
resource === 'resourceBase.js' ||
resource.indexOf('.js') < 0) {
continue;
}
resource = resource.replace('.js', '');
resources[resource] = require('./' + resource);
}
module.exports = resources;
| Fix resource loader file path being relative to running script. Use current directory global instead. | Fix resource loader file path being relative to running script. Use current directory global instead.
| JavaScript | mit | lob/lob-node | ---
+++
@@ -1,6 +1,6 @@
'use strict';
-var fs = require('fs'), files = fs.readdirSync('./lib/resources');
+var fs = require('fs'), files = fs.readdirSync(__dirname);
var resources = {}, resource, i = 0, l = files.length;
for(; i < l; i++) { |
a602da66da08edb7275a81d93ef648f7cfec3998 | package.js | package.js | Package.describe({
summary: "Jade template language for Meteor"
});
Package._transitional_registerBuildPlugin({
name: "compileJade",
use: [
"underscore",
"html-tools",
"spacebars-compiler",
],
sources: [
"plugin/lexer.js",
"plugin/parser.js",
"plugin/filters.js",
"plugin/compiler.js",
"plugin/handler.js",
],
npmDependencies: {
"jade": "1.1.5",
"markdown": "0.5.0",
}
});
Package.on_test(function (api) {
api.use("jade");
api.use("tinytest");
api.add_files("tests/tests.jade");
api.add_files("tests/client.js", "client");
api.add_files("tests/server.js", "server");
});
| Package.describe({
summary: "Jade template language for Meteor"
});
Package._transitional_registerBuildPlugin({
name: "compileJade",
use: [
"underscore",
"html-tools",
"spacebars-compiler",
],
sources: [
"plugin/lexer.js",
"plugin/parser.js",
"plugin/filters.js",
"plugin/compiler.js",
"plugin/handler.js",
],
npmDependencies: {
"jade": "1.2.0",
"markdown": "0.5.0",
}
});
Package.on_test(function (api) {
api.use("jade");
api.use("tinytest");
api.add_files("tests/tests.jade");
api.add_files("tests/client.js", "client");
api.add_files("tests/server.js", "server");
});
| Upgrade jade from 1.1.5 to 1.2.0 | Upgrade jade from 1.1.5 to 1.2.0
| JavaScript | mit | waitingkuo/meteor-jade,mquandalle/meteor-jade,thr0w/meteor-jade,lawrenceAIO/meteor-jade,lawrenceAIO/meteor-jade,mquandalle/meteor-jade,thr0w/meteor-jade | ---
+++
@@ -17,7 +17,7 @@
"plugin/handler.js",
],
npmDependencies: {
- "jade": "1.1.5",
+ "jade": "1.2.0",
"markdown": "0.5.0",
}
}); |
fde93a8309639645a4964e5da178b945c0a5cf35 | project/frontend/src/components/SGonksLists/ShortSGonksList/ShortSGonksRow/ShortSGonksRow.js | project/frontend/src/components/SGonksLists/ShortSGonksList/ShortSGonksRow/ShortSGonksRow.js | import React from "react";
import classes from "./ShortSGonksRow.module.css";
const ShortSGonksRow = (props) => {
console.log(props);
const getDiffIndicator = () => {
const diff =
props.datapoints[props.datapoints.length - 1] >
props.datapoints[props.datapoints.length - 2]
? "+"
: props.datapoints[props.datapoints.length - 1] <
props.datapoints[props.datapoints.length - 2]
? "-"
: "=";
const style =
diff == "+"
? { color: "green" }
: diff == "-"
? { color: "red" }
: { color: "orange" };
return (
<div className={classes.ChangeIndicator} style={style}>
{diff}
</div>
);
};
return (
<div {...props} className={classes.Row}>
{getDiffIndicator()}
<div className={classes.SearchTerm}>{props.searchterm}</div>
<div className={classes.CurrentPrice}>$t{props.currentprice}</div>
</div>
);
};
export default ShortSGonksRow;
| import React from "react";
import classes from "./ShortSGonksRow.module.css";
const ShortSGonksRow = (props) => {
console.log(props);
const getDiffIndicator = () => {
const priceDelta =
props.datapoints[props.datapoints.length - 1] -
props.datapoints[props.datapoints.length - 2];
const diff = priceDelta > 0 ? "+" : priceDelta < 0 ? "-" : "=";
const style =
diff == "+"
? { color: "green" }
: diff == "-"
? { color: "red" }
: { color: "orange" };
return (
<div className={classes.ChangeIndicator} style={style}>
{diff}
</div>
);
};
return (
<div {...props} className={classes.Row}>
{getDiffIndicator()}
<div className={classes.SearchTerm}>{props.searchterm}</div>
<div className={classes.CurrentPrice}>$t{props.currentprice}</div>
</div>
);
};
export default ShortSGonksRow;
| Update price change indicator code to be more readable | Update price change indicator code to be more readable
| JavaScript | apache-2.0 | googleinterns/sgonks,googleinterns/sgonks,googleinterns/sgonks,googleinterns/sgonks | ---
+++
@@ -4,14 +4,10 @@
const ShortSGonksRow = (props) => {
console.log(props);
const getDiffIndicator = () => {
- const diff =
- props.datapoints[props.datapoints.length - 1] >
- props.datapoints[props.datapoints.length - 2]
- ? "+"
- : props.datapoints[props.datapoints.length - 1] <
- props.datapoints[props.datapoints.length - 2]
- ? "-"
- : "=";
+ const priceDelta =
+ props.datapoints[props.datapoints.length - 1] -
+ props.datapoints[props.datapoints.length - 2];
+ const diff = priceDelta > 0 ? "+" : priceDelta < 0 ? "-" : "=";
const style =
diff == "+" |
4d1308fd6783dcd71bff9f882f36a794d29d9f14 | src/graphql/state.js | src/graphql/state.js | import localForage from 'localforage';
import { withClientState } from 'apollo-link-state';
import { DialerInfo } from './queries';
import { CONFERENCE_PHONE_NUMBER } from '../config';
let defaultPhoneNumber;
(async () => {
defaultPhoneNumber =
(await localForage.getItem('dialer/CONFERENCE_PHONE_NUMBER')) || CONFERENCE_PHONE_NUMBER;
})();
export default withClientState({
Query: {
dialer: () => ({
__typename: 'Dialer',
phoneNumber: defaultPhoneNumber,
}),
},
Mutation: {
updateDialer: (_, { input: { phoneNumber } = {} }, { cache }) => {
const currentDialerQuery = cache.readQuery({ query: DialerInfo, variables: {} });
const updatedDialer = {
...currentDialerQuery.dialer,
phoneNumber,
};
cache.writeQuery({
query: DialerInfo,
data: {
dialer: updatedDialer,
},
});
localForage.setItem('dialer/CONFERENCE_PHONE_NUMBER', phoneNumber);
return updatedDialer;
},
},
});
| import localForage from 'localforage';
import { withClientState } from 'apollo-link-state';
import { DialerInfo } from './queries';
import { CONFERENCE_PHONE_NUMBER } from '../config';
// TODO refactor after https://github.com/apollographql/apollo-link-state/issues/119 is resolved
let persistedPhoneNumber;
(async () => {
persistedPhoneNumber = await localForage.getItem('dialer/PHONE_NUMBER');
})();
export default withClientState({
Query: {
dialer: () => ({
__typename: 'Dialer',
phoneNumber: persistedPhoneNumber || CONFERENCE_PHONE_NUMBER,
}),
},
Mutation: {
updateDialer: (_, { input: { phoneNumber } = {} }, { cache }) => {
const currentDialerQuery = cache.readQuery({ query: DialerInfo, variables: {} });
const updatedDialer = {
...currentDialerQuery.dialer,
phoneNumber,
};
cache.writeQuery({
query: DialerInfo,
data: {
dialer: updatedDialer,
},
});
localForage.setItem('dialer/PHONE_NUMBER', phoneNumber);
return updatedDialer;
},
},
});
| Fix persistence in private tabs | Fix persistence in private tabs
| JavaScript | mit | callthemonline/simple-client-react,callthemonline/simple-client-react | ---
+++
@@ -3,17 +3,17 @@
import { DialerInfo } from './queries';
import { CONFERENCE_PHONE_NUMBER } from '../config';
-let defaultPhoneNumber;
+// TODO refactor after https://github.com/apollographql/apollo-link-state/issues/119 is resolved
+let persistedPhoneNumber;
(async () => {
- defaultPhoneNumber =
- (await localForage.getItem('dialer/CONFERENCE_PHONE_NUMBER')) || CONFERENCE_PHONE_NUMBER;
+ persistedPhoneNumber = await localForage.getItem('dialer/PHONE_NUMBER');
})();
export default withClientState({
Query: {
dialer: () => ({
__typename: 'Dialer',
- phoneNumber: defaultPhoneNumber,
+ phoneNumber: persistedPhoneNumber || CONFERENCE_PHONE_NUMBER,
}),
},
Mutation: {
@@ -29,7 +29,7 @@
dialer: updatedDialer,
},
});
- localForage.setItem('dialer/CONFERENCE_PHONE_NUMBER', phoneNumber);
+ localForage.setItem('dialer/PHONE_NUMBER', phoneNumber);
return updatedDialer;
},
}, |
dd96f804152f475952703605e81f8d87fd41b7b1 | product.js | product.js | var mongoose = require('mongoose');
var Category = require('./category');
var productSchema = {
name: {
type: String,
required: true
},
pictures: [{
type: String,
// pictures must start with http://
match: /^http:\/\//i
}],
price: {
amount: {
type: Number,
required: true
},
currency: {
type: String,
// only three currencies supported for now
enum: ['USD', 'EUR', 'GPB'],
required: true
}
},
category: Category.categorySchema
};
module.exports = mongoose.Schema(productSchema);
exports.productSchema = productSchema;
| var mongoose = require('mongoose');
var Category = require('./category');
var productSchema = {
name: {
type: String,
required: true
},
pictures: [{
type: String,
// pictures must start with http://
match: /^http:\/\//i
}],
price: {
amount: {
type: Number,
required: true
},
currency: {
type: String,
// only three currencies supported for now
enum: ['USD', 'EUR', 'GPB'],
required: true
}
},
category: Category.categorySchema
};
var schema = mongoose.Schema(productSchema);
var currencySymbols = {
'USD': '$',
'EUR': '€',
'GBP': '£'
}
schema.virtual('displayPrice').get(function() {
return currencySymbols[this.price.currency] + this.price.amount;
});
schema.set('toObject', { virtuals: true });
schema.set('toJSON', { virtuals: true });
module.exports = schema;
exports.productSchema = productSchema;
| Add currency symbols and displayPrice virtual | Add currency symbols and displayPrice virtual
| JavaScript | mit | kevinlmh/Retail | ---
+++
@@ -26,5 +26,20 @@
category: Category.categorySchema
};
-module.exports = mongoose.Schema(productSchema);
+var schema = mongoose.Schema(productSchema);
+
+var currencySymbols = {
+ 'USD': '$',
+ 'EUR': '€',
+ 'GBP': '£'
+}
+
+schema.virtual('displayPrice').get(function() {
+ return currencySymbols[this.price.currency] + this.price.amount;
+});
+
+schema.set('toObject', { virtuals: true });
+schema.set('toJSON', { virtuals: true });
+
+module.exports = schema;
exports.productSchema = productSchema; |
f08ea70a479182b76a14025e0daa3effaed56726 | tools/cli/dev-bundle-bin-commands.js | tools/cli/dev-bundle-bin-commands.js | // Note that this file is required before we install our Babel hooks in
// ../tool-env/install-babel.js, so we can't use ES2015+ syntax here.
var win32Extensions = {
node: ".exe",
npm: ".cmd"
};
// The dev_bundle/bin command has to come immediately after the meteor
// command, as in `meteor npm` or `meteor node`, because we don't want to
// require("./main.js") for these commands.
var devBundleBinCommand = process.argv[2];
var args = process.argv.slice(3);
function getChildProcess() {
if (! win32Extensions.hasOwnProperty(devBundleBinCommand)) {
return Promise.resolve(null);
}
var helpers = require("./dev-bundle-bin-helpers.js");
if (process.platform === "win32") {
devBundleBinCommand += win32Extensions[devBundleBinCommand];
}
return Promise.all([
helpers.getCommandPath(devBundleBinCommand),
helpers.getEnv()
]).then(function (cmdAndEnv) {
var cmd = cmdAndEnv[0];
var env = cmdAndEnv[1];
var child = require("child_process").spawn(cmd, args, {
stdio: "inherit",
env: env
});
require("./flush-buffers-on-exit-in-windows.js");
child.on("exit", function (exitCode) {
process.exit(exitCode);
});
return child;
});
}
module.exports = getChildProcess();
| // Note that this file is required before we install our Babel hooks in
// ../tool-env/install-babel.js, so we can't use ES2015+ syntax here.
var win32Extensions = {
node: ".exe",
npm: ".cmd"
};
// The dev_bundle/bin command has to come immediately after the meteor
// command, as in `meteor npm` or `meteor node`, because we don't want to
// require("./main.js") for these commands.
var devBundleBinCommand = process.argv[2];
var args = process.argv.slice(3);
function getChildProcess() {
if (! win32Extensions.hasOwnProperty(devBundleBinCommand)) {
return Promise.resolve(null);
}
var helpers = require("./dev-bundle-bin-helpers.js");
if (process.platform === "win32") {
devBundleBinCommand += win32Extensions[devBundleBinCommand];
}
return Promise.all([
helpers.getCommandPath(devBundleBinCommand),
helpers.getEnv()
]).then(function (cmdAndEnv) {
var cmd = cmdAndEnv[0];
var env = cmdAndEnv[1];
var child = require("child_process").spawn(cmd, args, {
stdio: "inherit",
env: env
});
require("./flush-buffers-on-exit-in-windows.js");
child.on("error", function (error) {
console.log(error.stack || error);
});
child.on("exit", function (exitCode) {
process.exit(exitCode);
});
return child;
});
}
module.exports = getChildProcess();
| Print stack traces from failed `meteor {node,npm}` commands. | Print stack traces from failed `meteor {node,npm}` commands.
| JavaScript | mit | Hansoft/meteor,mjmasn/meteor,mjmasn/meteor,chasertech/meteor,Hansoft/meteor,mjmasn/meteor,mjmasn/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,chasertech/meteor,chasertech/meteor,chasertech/meteor,Hansoft/meteor,mjmasn/meteor,chasertech/meteor,Hansoft/meteor,chasertech/meteor,mjmasn/meteor,chasertech/meteor,mjmasn/meteor | ---
+++
@@ -36,6 +36,10 @@
require("./flush-buffers-on-exit-in-windows.js");
+ child.on("error", function (error) {
+ console.log(error.stack || error);
+ });
+
child.on("exit", function (exitCode) {
process.exit(exitCode);
}); |
24ede76ef8112b80abba942bba29295adfb0af03 | src/visitors/minify.js | src/visitors/minify.js | import * as t from 'babel-types'
import { useMinify } from '../utils/options'
import { isStyled, isHelper } from '../utils/detectors'
const minify = (linebreak) => {
const regex = new RegExp(linebreak + '\\s*', 'g')
return (code) => code.split(regex).filter(line => line.length > 0).map((line) => {
return line.indexOf('//') === -1 ? line : line + '\n';
}).join('')
}
const minifyRaw = minify('(?:\\\\r|\\\\n|\\r|\\n)')
const minifyCooked = minify('[\\r\\n]')
export default (path, state) => {
if (useMinify(state) && (isStyled(path.node.tag, state) || isHelper(path.node.tag, state))) {
const templateLiteral = path.node.quasi
for (let element of templateLiteral.quasis) {
element.value.raw = minifyRaw(element.value.raw)
element.value.cooked = minifyCooked(element.value.cooked)
}
}
}
| import * as t from 'babel-types'
import {
useMinify,
useCSSPreprocessor
} from '../utils/options'
import { isStyled, isHelper } from '../utils/detectors'
const minify = (linebreak) => {
const regex = new RegExp(linebreak + '\\s*', 'g')
return (code) => code.split(regex).filter(line => line.length > 0).map((line) => {
return line.indexOf('//') === -1 ? line : line + '\n';
}).join('')
}
const minifyRaw = minify('(?:\\\\r|\\\\n|\\r|\\n)')
const minifyCooked = minify('[\\r\\n]')
export default (path, state) => {
if (
useMinify(state) &&
!useCSSPreprocessor(state) &&
(
isStyled(path.node.tag, state) ||
isHelper(path.node.tag, state)
)
) {
const templateLiteral = path.node.quasi
for (let element of templateLiteral.quasis) {
element.value.raw = minifyRaw(element.value.raw)
element.value.cooked = minifyCooked(element.value.cooked)
}
}
}
| Disable minificiation when preprocessing is enabled | Disable minificiation when preprocessing is enabled
| JavaScript | mit | styled-components/babel-plugin-styled-components | ---
+++
@@ -1,5 +1,8 @@
import * as t from 'babel-types'
-import { useMinify } from '../utils/options'
+import {
+ useMinify,
+ useCSSPreprocessor
+} from '../utils/options'
import { isStyled, isHelper } from '../utils/detectors'
const minify = (linebreak) => {
@@ -13,7 +16,14 @@
const minifyCooked = minify('[\\r\\n]')
export default (path, state) => {
- if (useMinify(state) && (isStyled(path.node.tag, state) || isHelper(path.node.tag, state))) {
+ if (
+ useMinify(state) &&
+ !useCSSPreprocessor(state) &&
+ (
+ isStyled(path.node.tag, state) ||
+ isHelper(path.node.tag, state)
+ )
+ ) {
const templateLiteral = path.node.quasi
for (let element of templateLiteral.quasis) {
element.value.raw = minifyRaw(element.value.raw) |
5030ce17dc5cc74477a90aa295569ee00ea0f881 | src/widgets/DataTable/utilities.js | src/widgets/DataTable/utilities.js | /* eslint-disable import/prefer-default-export */
export const getAdjustedStyle = (style, width, isLastCell) => {
if (width && isLastCell) return { ...style, flex: width, borderRightWidth: 0 };
if (width) return { ...style, flex: width };
if (isLastCell) return { ...style, borderWidth: 0 };
return style;
};
| /* eslint-disable import/prefer-default-export */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Utility method to inject properties into a provided style object.
* If width is passed, add a flex property equal to width.
* If isLastCell is passed, add a borderRightWidth: 0 property to remove
* the border for the last cell in a row.
* If neither are used, do nothing.
*
* @param {Object} style Style object to inject styles into.
* @param {Number} width Value for the flex property to inject.
* @param {Bool} isLastCell Indicator for the cell being the last in a row.
*/
export const getAdjustedStyle = (style, width, isLastCell) => {
if (width && isLastCell) return { ...style, flex: width, borderRightWidth: 0 };
if (width) return { ...style, flex: width };
if (isLastCell) return { ...style, borderWidth: 0 };
return style;
};
| Add doc string to utility method getAdjustedStyle | Add doc string to utility method getAdjustedStyle
| JavaScript | mit | sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile | ---
+++
@@ -1,4 +1,20 @@
/* eslint-disable import/prefer-default-export */
+/**
+ * mSupply Mobile
+ * Sustainable Solutions (NZ) Ltd. 2019
+ */
+
+/**
+ * Utility method to inject properties into a provided style object.
+ * If width is passed, add a flex property equal to width.
+ * If isLastCell is passed, add a borderRightWidth: 0 property to remove
+ * the border for the last cell in a row.
+ * If neither are used, do nothing.
+ *
+ * @param {Object} style Style object to inject styles into.
+ * @param {Number} width Value for the flex property to inject.
+ * @param {Bool} isLastCell Indicator for the cell being the last in a row.
+ */
export const getAdjustedStyle = (style, width, isLastCell) => {
if (width && isLastCell) return { ...style, flex: width, borderRightWidth: 0 };
if (width) return { ...style, flex: width }; |
b1bebd76b9e2d1afaaa9d8c89c4f1711bd4eb44b | app/models/calibration.js | app/models/calibration.js | var mysql = require('mysql');
var connectionParams = require('../../config/connectionParams');
function getConnection() {
var connection = mysql.createConnection(connectionParams);
return connection;
}
function Calibration(databaseRow) {
for(var propertyName in databaseRow) {
this[propertyName] = databaseRow[propertyName];
}
}
function Calibrations() {
function query(queryString, queryParams, callback) {
var connection = getConnection();
connection.connect();
connection.query(queryString, queryParams, callback);
connection.end()
}
this.findById = function(calibration_id, callback) {
// callback is (calibration, err)
// query the calibrations by id
var queryString = 'SELECT * FROM calibrations WHERE CalibrationID = ?';
query(queryString, [calibration_id], function(err, results) {
if(err) {
callback(null,err);
} else {
var calibrationResult = new Calibration(results[0]);
callback(calibrationResult);
}
});
};
this.findByFilter = function(params, callback) {
var queryString = 'SELECT * FROM calibrations WHERE minAge > ? AND maxAge < ?';
query(queryString, [params.min, params.max], function(err, results) {
if(err) {
callback(null,err);
} else {
var calibrationResults = results.map(function(result) { return new Calibration(result)});
callback(calibrationResults);
}
});
};
}
module.exports = new Calibrations(); | var mysql = require('mysql');
var connectionParams = require('../../config/connectionParams');
function getConnection() {
var connection = mysql.createConnection(connectionParams);
return connection;
}
function Calibration(databaseRow) {
for(var propertyName in databaseRow) {
this[propertyName] = databaseRow[propertyName];
}
}
function Calibrations() {
function query(queryString, queryParams, callback) {
var connection = getConnection();
connection.connect();
connection.query(queryString, queryParams, callback);
connection.end()
}
var TABLE_NAME = 'View_Calibrations';
this.findById = function(calibration_id, callback) {
// callback is (calibration, err)
// query the calibrations by id
var queryString = 'SELECT * FROM ' + TABLE_NAME + ' WHERE CalibrationID = ?';
query(queryString, [calibration_id], function(err, results) {
if(err) {
callback(null,err);
} else {
var calibrationResult = new Calibration(results[0]);
callback(calibrationResult);
}
});
};
this.findByFilter = function(params, callback) {
var queryString = 'SELECT * FROM ' + TABLE_NAME + ' WHERE minAge > ? AND maxAge < ?';
query(queryString, [params.min, params.max], function(err, results) {
if(err) {
callback(null,err);
} else {
var calibrationResults = results.map(function(result) { return new Calibration(result)});
callback(calibrationResults);
}
});
};
}
module.exports = new Calibrations(); | Move table name literal out of query | Move table name literal out of query
| JavaScript | mit | NESCent/fcdb-api,NESCent/fcdb-api | ---
+++
@@ -19,10 +19,11 @@
connection.end()
}
+ var TABLE_NAME = 'View_Calibrations';
this.findById = function(calibration_id, callback) {
// callback is (calibration, err)
// query the calibrations by id
- var queryString = 'SELECT * FROM calibrations WHERE CalibrationID = ?';
+ var queryString = 'SELECT * FROM ' + TABLE_NAME + ' WHERE CalibrationID = ?';
query(queryString, [calibration_id], function(err, results) {
if(err) {
callback(null,err);
@@ -33,7 +34,7 @@
});
};
this.findByFilter = function(params, callback) {
- var queryString = 'SELECT * FROM calibrations WHERE minAge > ? AND maxAge < ?';
+ var queryString = 'SELECT * FROM ' + TABLE_NAME + ' WHERE minAge > ? AND maxAge < ?';
query(queryString, [params.min, params.max], function(err, results) {
if(err) {
callback(null,err); |
3624060ef75b1bb59563fc0f4b92f40df918fb7c | src/App.js | src/App.js | import React, { Component } from 'react';
import './App.css';
import './index.css';
import Rowbox from './components/Rowbox';
import IconRow from './components/IconRow';
class App extends Component {
render() {
return (
<main className='container'>
<div className='row row1'>
<h1 className='nameHeader'>Fay Ray</h1>
<IconRow />
</div>
<div className='row row2'>
<Rowbox text='Is a band' number='1'/>
<Rowbox text='Has a new single' number='2'/>
</div>
<div className='row row3'>
<Rowbox text='Plays shows' number='3'/>
<Rowbox text='Takes photos' number='4'/>
<Rowbox text='Uses email' number='5'/>
</div>
</main>
);
}
}
export default App;
| import React, { Component } from 'react';
import './App.css';
import './index.css';
import Rowbox from './components/Rowbox';
import IconRow from './components/IconRow';
class App extends Component {
render() {
return (
<main className='container'>
<div className='row row1'>
<h1 className='nameHeader'>FAY RAY</h1>
<IconRow />
</div>
<div className='row row2'>
<Rowbox text='Is a band' number='1'/>
<Rowbox text='Has a new single' number='2'/>
</div>
<div className='row row3'>
<Rowbox text='Plays shows' number='3'/>
<Rowbox text='Takes photos' number='4'/>
<Rowbox text='Uses email' number='5'/>
</div>
</main>
);
}
}
export default App;
| Change band name to all caps | Change band name to all caps
| JavaScript | mit | hinzed1127/fayraysite,hinzed1127/fayraysite | ---
+++
@@ -9,7 +9,7 @@
return (
<main className='container'>
<div className='row row1'>
- <h1 className='nameHeader'>Fay Ray</h1>
+ <h1 className='nameHeader'>FAY RAY</h1>
<IconRow />
</div>
<div className='row row2'> |
213cdf62510263c1de13cc2b400489bbd90f3676 | src/innerJoin.js | src/innerJoin.js | (function () {
'use strict';
Array.prototype.innerJoin = function (arr, outer, inner, result, comparer) {
comparer = comparer || linq.EqualityComparer;
var res = [];
this.forEach(function (t) {
arr.where(function (u) {
return comparer(outer(t), inner(u));
})
.forEach(function (u) {
res.push(result(t, u));
});
});
return res;
};
}()); | (function () {
'use strict';
Array.prototype.innerJoin = function (inner, outerKeySelector, innerKeySelector, resultSelector, comparer) {
if (!inner) { throw new TypeError("inner is undefined."); }
if (!innerKeySelector) { throw new TypeError("innerKeySelector is undefined."); }
if (!outerKeySelector) { throw new TypeError("outerKeySelector is undefined."); }
resultSelector = resultSelector || function (o, i) {
return [o, i];
};
comparer = comparer || linq.EqualityComparer;
var innerKeyed = inner.select(function (e) {
return {
key: innerKeySelector(e),
element: e
};
});
return this.selectMany(function (o) {
var key = outerKeySelector(o);
return innerKeyed.where(function (i) {
return comparer(key, i.key);
})
.select(function (i) {
return i.element;
});
}, resultSelector.bind(null));
};
}());
| Validate arguments, make resultSelector optional, only apply key selectors once | Validate arguments, make resultSelector optional, only apply key selectors once
Validate arguments, make resultSelector optional, only apply key selectors once. | JavaScript | mit | joaom182/linqjs,joaom182/linqjs | ---
+++
@@ -1,20 +1,30 @@
(function () {
'use strict';
-
- Array.prototype.innerJoin = function (arr, outer, inner, result, comparer) {
+
+ Array.prototype.innerJoin = function (inner, outerKeySelector, innerKeySelector, resultSelector, comparer) {
+ if (!inner) { throw new TypeError("inner is undefined."); }
+ if (!innerKeySelector) { throw new TypeError("innerKeySelector is undefined."); }
+ if (!outerKeySelector) { throw new TypeError("outerKeySelector is undefined."); }
+
+ resultSelector = resultSelector || function (o, i) {
+ return [o, i];
+ };
comparer = comparer || linq.EqualityComparer;
- var res = [];
-
- this.forEach(function (t) {
- arr.where(function (u) {
- return comparer(outer(t), inner(u));
+ var innerKeyed = inner.select(function (e) {
+ return {
+ key: innerKeySelector(e),
+ element: e
+ };
+ });
+ return this.selectMany(function (o) {
+ var key = outerKeySelector(o);
+ return innerKeyed.where(function (i) {
+ return comparer(key, i.key);
})
- .forEach(function (u) {
- res.push(result(t, u));
+ .select(function (i) {
+ return i.element;
});
- });
-
- return res;
+ }, resultSelector.bind(null));
};
}()); |
e28b0f5e547b184ae82a6b9dfdd3bf1264671a73 | client/stores/geometry.js | client/stores/geometry.js | var account = require('./account');
exports.getInEverySystem = function (geom, callback) {
var params = {
geometry: geom,
};
$.ajax({
url: '/api/geometry',
method: 'POST', // get cannot have JSON body
data: JSON.stringify(params), // request data
contentType: 'application/json', // request data type
processData: false, // already string
dataType: 'json', // response data type
headers: { 'Authorization': 'Bearer ' + account.getToken() },
success: function (coordinates) {
return callback(null, coordinates);
},
error: function (jqxhr) {
var err = new Error(jqxhr.statusText);
err.code = jqxhr.status;
return callback(err);
},
});
};
| var request = require('./lib/request');
exports.getInEverySystem = function (geom, callback) {
return request.postJSON({
url: '/api/geometry',
data: {
geometry: geom,
},
}, callback);
};
exports.parseCoordinates = function (params, callback) {
// Parameters
// params, object with props
// coordinateSystem
// coordinatesText
// callback
// fn (err, latlng), where
// latlng
// { lat, lng } in WGS84
//
return callback(null, {
lat: 0,
lng: 0,
});
};
| Use request instead of raw jquery ajax | Use request instead of raw jquery ajax
| JavaScript | mit | axelpale/tresdb,axelpale/tresdb | ---
+++
@@ -1,26 +1,26 @@
-var account = require('./account');
+var request = require('./lib/request');
exports.getInEverySystem = function (geom, callback) {
+ return request.postJSON({
+ url: '/api/geometry',
+ data: {
+ geometry: geom,
+ },
+ }, callback);
+};
- var params = {
- geometry: geom,
- };
-
- $.ajax({
- url: '/api/geometry',
- method: 'POST', // get cannot have JSON body
- data: JSON.stringify(params), // request data
- contentType: 'application/json', // request data type
- processData: false, // already string
- dataType: 'json', // response data type
- headers: { 'Authorization': 'Bearer ' + account.getToken() },
- success: function (coordinates) {
- return callback(null, coordinates);
- },
- error: function (jqxhr) {
- var err = new Error(jqxhr.statusText);
- err.code = jqxhr.status;
- return callback(err);
- },
+exports.parseCoordinates = function (params, callback) {
+ // Parameters
+ // params, object with props
+ // coordinateSystem
+ // coordinatesText
+ // callback
+ // fn (err, latlng), where
+ // latlng
+ // { lat, lng } in WGS84
+ //
+ return callback(null, {
+ lat: 0,
+ lng: 0,
});
}; |
c247ed8bfdd6bfd0103a25254f6c7645eec63469 | backend/lib/stats/index.js | backend/lib/stats/index.js | var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var piwik = require('./piwik');
var mongodb = require('./mongodb');
function dateDaysAgo(nb_days) {
var date = new Date();
date = new Date(date.toISOString().slice(0,10));
date.setDate(date.getDate() - nb_days);
return date;
}
var nineWeeksAgo = dateDaysAgo(7 * 9);
var yesterday = dateDaysAgo(1);
var today = dateDaysAgo(0);
Promise.all([
mongodb.getDailySituationCount(nineWeeksAgo,today),
piwik.getUsageData(nineWeeksAgo, yesterday)
])
.then(function(data) { return [].concat(data[0], data[1]); })
.then(function(data) { return fs.writeFileAsync('dist/documents/stats.json', JSON.stringify(data, null, 2), 'utf-8'); })
.catch(function(error) {
console.error('error', error);
process.exitCode = 1;
})
.finally(mongodb.closeDb);
| var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var piwik = require('./piwik');
var mongodb = require('./mongodb');
function dateDaysAgo(nb_days) {
var date = new Date();
date = new Date(date.toISOString().slice(0,10));
date.setDate(date.getDate() - nb_days);
return date;
}
var nineWeeksAgo = dateDaysAgo(7 * 9);
var yesterday = dateDaysAgo(1);
var today = dateDaysAgo(0);
var relative_path = __dirname + '/../../../dist/documents/stats.json';
Promise.all([
mongodb.getDailySituationCount(nineWeeksAgo,today),
piwik.getUsageData(nineWeeksAgo, yesterday)
])
.then(function(data) { return [].concat(data[0], data[1]); })
.then(function(data) { return fs.writeFileAsync(relative_path, JSON.stringify(data, null, 2), 'utf-8'); })
.catch(function(error) {
console.error('error', error);
process.exitCode = 1;
})
.finally(mongodb.closeDb);
| Allow script run from any folder | Allow script run from any folder
| JavaScript | agpl-3.0 | sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui | ---
+++
@@ -15,12 +15,13 @@
var yesterday = dateDaysAgo(1);
var today = dateDaysAgo(0);
+var relative_path = __dirname + '/../../../dist/documents/stats.json';
Promise.all([
mongodb.getDailySituationCount(nineWeeksAgo,today),
piwik.getUsageData(nineWeeksAgo, yesterday)
])
.then(function(data) { return [].concat(data[0], data[1]); })
-.then(function(data) { return fs.writeFileAsync('dist/documents/stats.json', JSON.stringify(data, null, 2), 'utf-8'); })
+.then(function(data) { return fs.writeFileAsync(relative_path, JSON.stringify(data, null, 2), 'utf-8'); })
.catch(function(error) {
console.error('error', error);
process.exitCode = 1; |
bf81b291c493476e9d5136b9b94b2db78e37c184 | test/ringo/promise_test.js | test/ringo/promise_test.js | var assert = require("assert");
var {defer, promiseList} = require("ringo/promise");
exports.testPromiseList = function() {
var d1 = defer(), d2 = defer(), d3 = defer();
var l = promiseList(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise
l.then(function(result) {
assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
}, function(error) {
assert.fail("promiseList called error callback");
});
d2.resolve(1);
d3.resolve("error", true);
d1.resolve("ok");
};
// start the test runner if we're called directly from command line
if (require.main == module.id) {
system.exit(require('test').run(exports));
}
| var assert = require("assert");
var {defer, promises} = require("ringo/promise");
exports.testPromiseList = function() {
var d1 = defer(), d2 = defer(), d3 = defer();
var l = promises(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise
l.then(function(result) {
assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
}, function(error) {
assert.fail("promiseList called error callback");
});
d2.resolve(1);
d3.resolve("error", true);
d1.resolve("ok");
};
// start the test runner if we're called directly from command line
if (require.main == module.id) {
system.exit(require('test').run(exports));
}
| Test promises instead of promiseList. | Test promises instead of promiseList.
| JavaScript | apache-2.0 | oberhamsi/ringojs,oberhamsi/ringojs,ringo/ringojs,Transcordia/ringojs,Transcordia/ringojs,ringo/ringojs,ashwinrayaprolu1984/ringojs,ringo/ringojs,ashwinrayaprolu1984/ringojs,ashwinrayaprolu1984/ringojs,Transcordia/ringojs,ringo/ringojs,ashwinrayaprolu1984/ringojs,oberhamsi/ringojs,Transcordia/ringojs | ---
+++
@@ -1,9 +1,9 @@
var assert = require("assert");
-var {defer, promiseList} = require("ringo/promise");
+var {defer, promises} = require("ringo/promise");
exports.testPromiseList = function() {
var d1 = defer(), d2 = defer(), d3 = defer();
- var l = promiseList(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise
+ var l = promises(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise
l.then(function(result) {
assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
}, function(error) { |
13c11bbd78e2a71d6d8313f6d0985e20fa4091f5 | test/server/webhookSpec.js | test/server/webhookSpec.js | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const chai = require('chai')
const expect = chai.expect
describe('webhook', () => {
const webhook = require('../../lib/webhook')
const challenge = {
key: 'key'
}
describe('notify', () => {
it('fails when no webhook URL is provided via environment variable', () => {
expect(() => webhook.notify(challenge)).to.throw('options.uri is a required argument')
})
it('fails when supplied webhook is not a valid URL', () => {
expect(() => webhook.notify(challenge, 'localhorst')).to.throw('Invalid URI "localhorst"')
})
it('submits POST with payload to existing URL', () => {
expect(() => webhook.notify(challenge, 'http://localhost')).to.not.throw()
})
})
})
| /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const chai = require('chai')
const expect = chai.expect
describe('webhook', () => {
const webhook = require('../../lib/webhook')
const challenge = {
key: 'key'
}
describe('notify', () => {
it('fails when no webhook URL is provided via environment variable', () => {
expect(() => webhook.notify(challenge)).to.throw('options.uri is a required argument')
})
it('fails when supplied webhook is not a valid URL', () => {
expect(() => webhook.notify(challenge, 'localhorst')).to.throw('Invalid URI "localhorst"')
})
it('submits POST with payload to existing URL', () => {
expect(() => webhook.notify(challenge, 'https://webhook.site/f69013b6-c475-46ed-973f-aa07e5e573a3')).to.not.throw()
})
})
})
| Use webhook URL that should be available from anywhere | Use webhook URL that should be available from anywhere
(with working Internet connection)
| JavaScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -23,7 +23,7 @@
})
it('submits POST with payload to existing URL', () => {
- expect(() => webhook.notify(challenge, 'http://localhost')).to.not.throw()
+ expect(() => webhook.notify(challenge, 'https://webhook.site/f69013b6-c475-46ed-973f-aa07e5e573a3')).to.not.throw()
})
})
}) |
9b7fc3eb72cf15798e2decd85429ae495b74700b | client/tests/end2end/protractor-sauce.config.js | client/tests/end2end/protractor-sauce.config.js | var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER;
browser_capabilities['tags'] = [process.env.TRAVIS_BRANCH];
exports.config = {
framework: 'jasmine',
baseUrl: 'http://localhost:9000/',
troubleshoot: false,
directConnect: false,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
capabilities: browser_capabilities,
params: {
'testFileDownload': false,
'verifyFileDownload': false,
'tmpDir': '/tmp/globaleaks-download',
},
specs: specs,
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
| var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var browser_capabilities = JSON.parse(process.env.SELENIUM_BROWSER_CAPABILITIES);
browser_capabilities['name'] = 'GlobaLeaks-E2E';
browser_capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
browser_capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER;
browser_capabilities['tags'] = [process.env.TRAVIS_BRANCH];
exports.config = {
framework: 'jasmine',
baseUrl: 'http://localhost:9000/',
troubleshoot: false,
directConnect: false,
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
sauceBuild: process.env.TRAVIS_BUILD_NUMBER,
capabilities: browser_capabilities,
params: {
'testFileDownload': false,
'verifyFileDownload': false,
'tmpDir': '/tmp/globaleaks-download',
},
specs: specs,
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 360000
}
};
| Use protractor sauceBuild parameter to mass the build number to Sauce | Use protractor sauceBuild parameter to mass the build number to Sauce
| JavaScript | agpl-3.0 | vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks | ---
+++
@@ -17,6 +17,7 @@
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
+ sauceBuild: process.env.TRAVIS_BUILD_NUMBER,
capabilities: browser_capabilities,
params: { |
a4648a1b8d1641a4e48dca50ba61378d377db855 | app/scripts/timetable_builder/views/TimetableView.js | app/scripts/timetable_builder/views/TimetableView.js | define(['underscore', 'backbone.marionette', './LessonView'],
function(_, Marionette, LessonView) {
'use strict';
return Marionette.CollectionView.extend({
el: $('#timetable'),
childView: LessonView,
childViewOptions: function () {
return {
parentView: this,
timetable: this.collection
};
},
events: {
'mousemove': 'mouseMove',
'mouseleave': 'mouseLeave'
},
initialize: function() {
this.$colgroups = this.$('colgroup');
},
mouseMove: function(evt) {
if (!this.colX) {
this.colX = this.$('#mon > tr:last-child > td')
.filter(':even')
.map(function() { return $(this).offset().left; })
.get();
}
var currCol = this.$colgroups.eq(_.sortedIndex(this.colX, evt.pageX));
if (!currCol.is(this.prevCol)) {
if (this.prevCol) {
this.prevCol.removeAttr('class');
}
currCol.addClass('hover');
this.prevCol = currCol;
}
},
mouseLeave: function() {
if (this.prevCol) {
this.prevCol.removeAttr('class');
this.prevCol = false;
}
},
attachBuffer: function () {
},
attachHtml: function () {
}
});
});
| define(['underscore', 'backbone.marionette', './LessonView'],
function(_, Marionette, LessonView) {
'use strict';
return Marionette.CollectionView.extend({
el: $('#timetable'),
childView: LessonView,
childViewOptions: function () {
return {
parentView: this,
timetable: this.collection
};
},
events: {
'mousemove': 'mouseMove',
'mouseleave': 'mouseLeave'
},
ui: {
colgroups: 'colgroup'
},
initialize: function() {
},
mouseMove: function(evt) {
if (!this.colX) {
this.colX = this.$('#mon > tr:last-child > td')
.filter(':even')
.map(function() { return $(this).offset().left; })
.get();
}
var currCol = this.ui.colgroups.eq(_.sortedIndex(this.colX, evt.pageX));
if (!currCol.is(this.prevCol)) {
if (this.prevCol) {
this.prevCol.removeAttr('class');
}
currCol.addClass('hover');
this.prevCol = currCol;
}
},
mouseLeave: function() {
if (this.prevCol) {
this.prevCol.removeAttr('class');
this.prevCol = false;
}
},
attachBuffer: function () {
},
attachHtml: function () {
}
});
});
| Store colgroup in ui hash | Store colgroup in ui hash
| JavaScript | mit | zhouyichen/nusmods,chunqi/nusmods,Yunheng/nusmods,nathanajah/nusmods,chunqi/nusmods,chunqi/nusmods,nathanajah/nusmods,chunqi/nusmods,nusmodifications/nusmods,zhouyichen/nusmods,Yunheng/nusmods,mauris/nusmods,Yunheng/nusmods,zhouyichen/nusmods,nusmodifications/nusmods,mauris/nusmods,nathanajah/nusmods,nusmodifications/nusmods,mauris/nusmods,mauris/nusmods,Yunheng/nusmods,nusmodifications/nusmods,Yunheng/nusmods,nathanajah/nusmods,zhouyichen/nusmods | ---
+++
@@ -17,8 +17,11 @@
'mouseleave': 'mouseLeave'
},
+ ui: {
+ colgroups: 'colgroup'
+ },
+
initialize: function() {
- this.$colgroups = this.$('colgroup');
},
mouseMove: function(evt) {
@@ -29,7 +32,7 @@
.get();
}
- var currCol = this.$colgroups.eq(_.sortedIndex(this.colX, evt.pageX));
+ var currCol = this.ui.colgroups.eq(_.sortedIndex(this.colX, evt.pageX));
if (!currCol.is(this.prevCol)) {
if (this.prevCol) {
this.prevCol.removeAttr('class'); |
44aa937a7747147218dbc06c7d12274dfc386330 | webapp/js/scripts.js | webapp/js/scripts.js | // scripts app
var app;
(function(){
"use strict";
app = new ElecionesApp();
console.log(app);
// load mapa
$.get("img/mapaBA_SVG.txt", function(mapa){
$("#mapa_cont").html(mapa);
});
$('select#opts').change(function(e){
app.change_dropdown($(this).val());
});
})();
| // scripts app
var app;
$(function(){
"use strict";
app = new ElecionesApp();
console.log(app);
// load mapa
$.get("img/mapaBA_SVG.txt", function(mapa){
$("#mapa_cont").html(mapa);
});
$('select#opts').change(function(e){
app.change_dropdown($(this).val());
});
});
| Fix problem with anonymous function in production mode | Fix problem with anonymous function in production mode
| JavaScript | mit | lanacioncom/elecciones_2015_caba,lanacioncom/elecciones_2015_caba,lanacioncom/elecciones_2015_caba,lanacioncom/elecciones_2015_caba | ---
+++
@@ -1,6 +1,6 @@
// scripts app
var app;
-(function(){
+$(function(){
"use strict";
app = new ElecionesApp();
console.log(app);
@@ -13,4 +13,4 @@
app.change_dropdown($(this).val());
});
-})();
+}); |
d503494d18b3af9df9e27ddcc8eaa4c97914e9b8 | example/webpack.config.server.js | example/webpack.config.server.js | var api = require("./webpack.config.defaults")
.entry("./src/server.js")
// @TODO Auto-installed deps aren't in node_modules (yet),
// so let's see if this is a problem or not
.externals(/^@?\w[a-z\-0-9\./]+$/)
// .externals(...require("fs").readdirSync("./node_modules"))
.output("build/server")
.target("node")
.when("development", function(api) {
return api
.entry({
server: [
"webpack/hot/poll?1000",
"./src/server.js",
],
})
.sourcemap("source-map")
.plugin("start-server-webpack-plugin")
.plugin("webpack.BannerPlugin", {
banner: `require("source-map-support").install();`,
raw: true,
})
;
})
;
module.exports = api.getConfig();
| var api = require("./webpack.config.defaults")
.entry("./src/server.js")
.externals(/^@?\w[a-z\-0-9\./]+$/)
.output("build/server")
.target("node")
.when("development", function(api) {
return api
.entry({
server: [
"webpack/hot/poll?1000",
"./src/server.js",
],
})
.sourcemap("source-map")
.plugin("start-server-webpack-plugin")
.plugin("webpack.BannerPlugin", {
banner: `require("source-map-support").install();`,
raw: true,
})
;
})
;
module.exports = api.getConfig();
| Add comment that externals RegExp does work | Add comment that externals RegExp does work
| JavaScript | mit | ericclemmons/terse-webpack | ---
+++
@@ -1,9 +1,6 @@
var api = require("./webpack.config.defaults")
.entry("./src/server.js")
- // @TODO Auto-installed deps aren't in node_modules (yet),
- // so let's see if this is a problem or not
.externals(/^@?\w[a-z\-0-9\./]+$/)
- // .externals(...require("fs").readdirSync("./node_modules"))
.output("build/server")
.target("node")
.when("development", function(api) { |
9df18bb2e42506b765c21d76f93228dced3ca14b | tb_website/static/js/basic.js | tb_website/static/js/basic.js |
$(document).ready(function() {
$("[data-toggle=tooldesc]").data('container', 'body').tooltip({placement: 'bottom', trigger: 'manual'});
$("[data-toggle=tooltip], [data-toggle=tooltips] *").data('container', 'body').tooltip();
setInterval(function () {
$('.page-loader:visible').each(function() {
var elem = this.parentElement;
$(this).removeClass('page-loader');
$(this).addClass('page-loading');
var url = $(this).data('loader-url');
if (!url) {
$(this).remove();
console.error("No url to go to for page loader!");
}
$.get(url, function(data) {
$(elem).html(data);
$(this).remove(); // Maybe not required
});
});
}, 500);
});
|
$(document).ready(function() {
setInterval(function () {
$('.page-loader:visible').each(function() {
var elem = this.parentElement;
$(this).removeClass('page-loader');
$(this).addClass('page-loading');
var url = $(this).data('loader-url');
if (!url) {
$(this).remove();
console.error("No url to go to for page loader!");
}
$.get(url, function(data) {
$(elem).html(data);
$(this).remove(); // Maybe not required
setup_hover();
});
});
}, 500);
setup_hover();
});
function setup_hover() {
$("[data-toggle=tooldesc]").data('container', 'body').tooltip({placement: 'bottom', trigger: 'manual'});
$("[data-toggle=tooltip], [data-toggle=tooltips] *").data('container', 'body').tooltip();
}
| Fix tooltips when lazy loading | Fix tooltips when lazy loading
| JavaScript | agpl-3.0 | IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site | ---
+++
@@ -1,7 +1,5 @@
$(document).ready(function() {
- $("[data-toggle=tooldesc]").data('container', 'body').tooltip({placement: 'bottom', trigger: 'manual'});
- $("[data-toggle=tooltip], [data-toggle=tooltips] *").data('container', 'body').tooltip();
setInterval(function () {
$('.page-loader:visible').each(function() {
var elem = this.parentElement;
@@ -15,7 +13,14 @@
$.get(url, function(data) {
$(elem).html(data);
$(this).remove(); // Maybe not required
+ setup_hover();
});
});
}, 500);
+ setup_hover();
});
+
+function setup_hover() {
+ $("[data-toggle=tooldesc]").data('container', 'body').tooltip({placement: 'bottom', trigger: 'manual'});
+ $("[data-toggle=tooltip], [data-toggle=tooltips] *").data('container', 'body').tooltip();
+} |
f64fbbd2303499012ede0fdf42b6133f0bfef32d | config/regions.js | config/regions.js | 'use strict'
module.exports = [
{
name: 'auckland',
id: 1
},
{
name: 'wellington',
id: 15
},
{
name: 'waikato',
id: 14
}
]
| 'use strict'
const auckland = {
name: 'auckland',
id: 1
}
const wellington = {
name: 'wellington',
id: 15
}
const waikato = {
name: 'waikato',
id: 14
}
module.exports = [
auckland
]
| Disable cities other than AKL for testing | Disable cities other than AKL for testing
| JavaScript | mit | rowanoulton/rent | ---
+++
@@ -1,16 +1,20 @@
'use strict'
+const auckland = {
+ name: 'auckland',
+ id: 1
+}
+
+const wellington = {
+ name: 'wellington',
+ id: 15
+}
+
+const waikato = {
+ name: 'waikato',
+ id: 14
+}
+
module.exports = [
- {
- name: 'auckland',
- id: 1
- },
- {
- name: 'wellington',
- id: 15
- },
- {
- name: 'waikato',
- id: 14
- }
+ auckland
] |
08a0186506afc46443f096607a861db740b89f28 | client/src/app/app.js | client/src/app/app.js | angular.module('14all', ['ui.bootstrap','ngAnimate',
'auth',
/* Modules */
'manga','movie','serie','anime','game','book',
'14all.templates'])
.config(['RestangularProvider',function(RestangularProvider){
RestangularProvider.setRestangularFields({
id: "_id"
});
RestangularProvider.setBaseUrl('/api');
}])
.controller('AppCtrl',['$scope','$location','authService','$store',function($scope,$location,authService,$store){
// FIX SETTINGS
var tempSettings = $store.get('settings');
if(angular.isDefined(tempSettings.excludeFinished)){
$store.remove('settings');
}
// FIX SETTINGS
$scope.isLoggedIn = authService.isLoggedIn;
$scope.logout = authService.logout;
$scope.settings = $store.bind($scope,'settings',{
filter:{
stats:{
finished: false,
dropped: false
},
orderBy:{
predicate:'',
reverse:false
},
keyword:{}
}
});
$scope.orderBy = $scope.settings.filter.orderBy;
$scope.focus = {search:true};
$scope.$on("$routeChangeStart",function(event,next,current){
$scope.focus.search = false;
});
$scope.$on("$routeChangeSuccess",function(event,next,current){
$scope.focus.search = true;
});
}]);
| angular.module('14all', ['ui.bootstrap','ngAnimate',
'auth',
/* Modules */
'manga','movie','serie','anime','game','book',
'14all.templates'])
.config(['RestangularProvider',function(RestangularProvider){
RestangularProvider.setRestangularFields({
id: "_id"
});
RestangularProvider.setBaseUrl('/api');
}])
.controller('AppCtrl',['$scope','$location','authService','$store',function($scope,$location,authService,$store){
// FIX SETTINGS
var tempSettings = $store.get('settings');
if(angular.isDefined(tempSettings) && angular.isDefined(tempSettings.excludeFinished)){
$store.remove('settings');
}
// FIX SETTINGS
$scope.isLoggedIn = authService.isLoggedIn;
$scope.logout = authService.logout;
$scope.settings = $store.bind($scope,'settings',{
filter:{
stats:{
finished: false,
dropped: false
},
orderBy:{
predicate:'',
reverse:false
},
keyword:{}
}
});
$scope.orderBy = $scope.settings.filter.orderBy;
$scope.focus = {search:true};
$scope.$on("$routeChangeStart",function(event,next,current){
$scope.focus.search = false;
});
$scope.$on("$routeChangeSuccess",function(event,next,current){
$scope.focus.search = true;
});
}]);
| Fix for Cannot read property 'excludeFinished' of null | Fix for Cannot read property 'excludeFinished' of null
| JavaScript | mit | Opiskull/one4all | ---
+++
@@ -14,7 +14,7 @@
// FIX SETTINGS
var tempSettings = $store.get('settings');
- if(angular.isDefined(tempSettings.excludeFinished)){
+ if(angular.isDefined(tempSettings) && angular.isDefined(tempSettings.excludeFinished)){
$store.remove('settings');
}
// FIX SETTINGS |
efccff1832c45d68b1111da230b561ece2698e54 | test/bigtest/network/start.js | test/bigtest/network/start.js | /* eslint global-require: off, import/no-mutable-exports: off */
import merge from 'lodash/merge';
import flow from 'lodash/flow';
const environment = process.env.NODE_ENV || 'test';
let start = () => {};
if (environment !== 'production') {
const { default: Mirage, camelize } = require('@bigtest/mirage');
const { default: coreModules } = require('./index');
require('./force-fetch-polyfill');
start = (scenarioNames, options = {}) => {
const { coreScenarios = {}, baseConfig: coreConfig, ...coreOpts } = coreModules;
const { scenarios = {}, baseConfig = () => {}, ...opts } = options;
const server = new Mirage(merge({
baseConfig: flow(coreConfig, baseConfig),
environment
}, coreOpts, opts));
// mirage only loads a `default` scenario for us out of the box,
// so instead of providing all scenarios we run specific scenarios
// after the mirage server is initialized.
[].concat(scenarioNames || 'default').filter(Boolean).forEach(name => {
const key = camelize(name);
const scenario = scenarios[key] || coreScenarios[key];
if (scenario) scenario(server);
});
return server;
};
}
export default start;
| /* eslint global-require: off, import/no-mutable-exports: off */
import merge from 'lodash/merge';
import flow from 'lodash/flow';
const environment = process.env.NODE_ENV || 'test';
let start = () => {};
if (environment !== 'production') {
const { default: Mirage, camelize } = require('@bigtest/mirage');
const { default: coreModules } = require('./index');
require('./force-fetch-polyfill');
start = (scenarioNames, options = {}) => {
const { coreScenarios = {}, baseConfig: coreConfig, ...coreOpts } = coreModules;
const { scenarios = {}, baseConfig = () => {}, ...opts } = options;
const server = new Mirage(merge({
baseConfig: flow(coreConfig, baseConfig),
environment
}, coreOpts, opts));
// the default scenario is only used when not in test mode
let defaultScenario;
if (!scenarioNames && environment !== 'test') {
defaultScenario = 'default';
}
// mirage only loads a `default` scenario for us out of the box,
// so instead of providing all scenarios we run specific scenarios
// after the mirage server is initialized.
[].concat(scenarioNames || defaultScenario).filter(Boolean).forEach(name => {
const key = camelize(name);
const scenario = scenarios[key] || coreScenarios[key];
if (scenario) scenario(server);
});
return server;
};
}
export default start;
| Fix mirage to only use default scenario when not testing | Fix mirage to only use default scenario when not testing
| JavaScript | apache-2.0 | folio-org/stripes-core,folio-org/stripes-core,folio-org/stripes-core | ---
+++
@@ -20,10 +20,16 @@
environment
}, coreOpts, opts));
+ // the default scenario is only used when not in test mode
+ let defaultScenario;
+ if (!scenarioNames && environment !== 'test') {
+ defaultScenario = 'default';
+ }
+
// mirage only loads a `default` scenario for us out of the box,
// so instead of providing all scenarios we run specific scenarios
// after the mirage server is initialized.
- [].concat(scenarioNames || 'default').filter(Boolean).forEach(name => {
+ [].concat(scenarioNames || defaultScenario).filter(Boolean).forEach(name => {
const key = camelize(name);
const scenario = scenarios[key] || coreScenarios[key];
if (scenario) scenario(server); |
c15a006124e6bc5dbcbf4d1e9036391cb1b9b7d0 | usr/local/www/javascript/index/sajax.js | usr/local/www/javascript/index/sajax.js | function updateMeters()
{
x_cpu_usage(updateCPU);
x_mem_usage(updateMemory);
x_get_uptime(updateUptime);
x_get_pfstate(updateState);
window.setTimeout('updateMeters()', 1500);
}
function updateMemory(x)
{
document.getElementById("memusagemeter").value = x + '%';
document.getElementById("memwidtha").style.width = x + 'px';
document.getElementById("memwidthb").style.width = (100 - x) + 'px';
}
function updateCPU(x)
{
document.getElementById("cpumeter").value = x + '%';
document.getElementById("cpuwidtha").style.width = x + 'px';
document.getElementById("cpuwidthb").style.width = (100 - x) + 'px';
}
function updateUptime(x)
{
document.getElementById("uptime").value = x;
}
function updateState(x)
{
document.getElementById("pfstate").value = x;
}
window.setTimeout('updateMeters()', 1500); | function updateMeters()
{
x_cpu_usage(updateCPU);
x_mem_usage(updateMemory);
x_get_uptime(updateUptime);
x_get_pfstate(updateState);
window.setTimeout('updateMeters()', 10000);
}
function updateMemory(x)
{
document.getElementById("memusagemeter").value = x + '%';
document.getElementById("memwidtha").style.width = x + 'px';
document.getElementById("memwidthb").style.width = (100 - x) + 'px';
}
function updateCPU(x)
{
document.getElementById("cpumeter").value = x + '%';
document.getElementById("cpuwidtha").style.width = x + 'px';
document.getElementById("cpuwidthb").style.width = (100 - x) + 'px';
}
function updateUptime(x)
{
document.getElementById("uptime").value = x;
}
function updateState(x)
{
document.getElementById("pfstate").value = x;
}
window.setTimeout('updateMeters()', 10000); | Update time now 10 seconds. | Update time now 10 seconds.
| JavaScript | apache-2.0 | NOYB/pfsense,NOYB/pfsense,dennypage/pfsense,NewEraCracker/pfsense,NewEraCracker/pfsense,NewEraCracker/pfsense,ch1c4um/pfsense,BlackstarGroup/pfsense,pfsense/pfsense,ch1c4um/pfsense,jxmx/pfsense,phil-davis/pfsense,dennypage/pfsense,BlackstarGroup/pfsense,jxmx/pfsense,BlackstarGroup/pfsense,brunostein/pfsense,ptorsten/pfsense,BlackstarGroup/pfsense,pfsense/pfsense,pfsense/pfsense,phil-davis/pfsense,phil-davis/pfsense,ch1c4um/pfsense,pfsense/pfsense,NewEraCracker/pfsense,brunostein/pfsense,ptorsten/pfsense,ch1c4um/pfsense,dennypage/pfsense,ptorsten/pfsense,jxmx/pfsense,brunostein/pfsense,dennypage/pfsense,NOYB/pfsense,phil-davis/pfsense | ---
+++
@@ -5,7 +5,7 @@
x_get_uptime(updateUptime);
x_get_pfstate(updateState);
- window.setTimeout('updateMeters()', 1500);
+ window.setTimeout('updateMeters()', 10000);
}
function updateMemory(x)
@@ -34,4 +34,4 @@
document.getElementById("pfstate").value = x;
}
-window.setTimeout('updateMeters()', 1500);
+window.setTimeout('updateMeters()', 10000); |
9309f7a09c8d6af2b42946378bc3d4f87b888d62 | ui/src/reducers/similar.js | ui/src/reducers/similar.js | import { createReducer } from 'redux-act';
import {
queryEntities,
queryEntitySetEntities,
fetchEntity,
createEntity,
updateEntity,
deleteEntity,
} from 'actions';
import {
objectLoadStart, objectLoadError, objectLoadComplete, objectDelete, resultObjects,
} from 'reducers/util';
const initialState = {};
export default createReducer({
[querySimilar.COMPLETE]: (state, { result }) => resultObjects(state, result),
}, initialState);
| import { createReducer } from 'redux-act';
import { querySimilar } from 'actions';
import { resultObjects } from 'reducers/util';
const initialState = {};
export default createReducer({
[querySimilar.COMPLETE]: (state, { result }) => resultObjects(state, result),
}, initialState);
| Fix ESLint errors and warnings | Fix ESLint errors and warnings
| JavaScript | mit | alephdata/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph | ---
+++
@@ -1,16 +1,7 @@
import { createReducer } from 'redux-act';
-import {
- queryEntities,
- queryEntitySetEntities,
- fetchEntity,
- createEntity,
- updateEntity,
- deleteEntity,
-} from 'actions';
-import {
- objectLoadStart, objectLoadError, objectLoadComplete, objectDelete, resultObjects,
-} from 'reducers/util';
+import { querySimilar } from 'actions';
+import { resultObjects } from 'reducers/util';
const initialState = {};
|
edc416dd7695afc273032209b7d7ea67abe9e7d9 | lib/assets/javascripts/cartodb/common/dialogs/merge_datasets/column_merge/column_merge_model.js | lib/assets/javascripts/cartodb/common/dialogs/merge_datasets/column_merge/column_merge_model.js | var _ = require('underscore');
var cdb = require('cartodb.js');
var ChooseKeyColumnsModel = require('./choose_key_columns_model');
module.exports = cdb.core.Model.extend({
defaults: {
illustrationIconType: 'IllustrationIcon--alert',
icon: 'iconFont-Question',
title: 'Column join',
desc: 'Merge two datasets based on a shared value (ex. ISO codes in both datasets)',
table: undefined,
excludeColumns: []
},
initialize: function(attrs) {
if (!attrs.table) throw new Error('table is required');
if (!attrs.excludeColumns || _.isEmpty(attrs.excludeColumns)) cdb.log.error('excludeColumns was empty');
this.elder('initialize');
},
isAvailable: function() {
// Need at least one more column than the_geom to do a column merge
return _.chain(this.get('table').get('schema'))
.map(function(column) {
return column[0]; //name
})
.without(this.get('filteredColumns'))
.any(function(columnName) {
return columnName !== 'the_geom';
})
.value();
},
firstStep: function() {
return new ChooseKeyColumnsModel({
leftTable: this.get('table'),
excludeColumns: this.get('excludeColumns')
});
}
});
| var _ = require('underscore');
var cdb = require('cartodb.js');
var ChooseKeyColumnsModel = require('./choose_key_columns_model');
module.exports = cdb.core.Model.extend({
defaults: {
illustrationIconType: 'IllustrationIcon--alert',
icon: 'iconFont-Question',
title: 'Column join',
desc: 'Merge two datasets based on a shared value (ex. ISO codes in both datasets)',
table: undefined,
excludeColumns: []
},
initialize: function(attrs) {
if (!attrs.table) throw new Error('table is required');
if (!attrs.excludeColumns || _.isEmpty(attrs.excludeColumns)) cdb.log.error('excludeColumns was empty');
this.elder('initialize');
},
isAvailable: function() {
// Need at least one more column than the_geom to do a column merge
return _.chain(this.get('table').get('schema'))
.map(function(column) {
return column[0]; //name
})
.without(this.get('excludeColumns'))
.any(function(columnName) {
return columnName !== 'the_geom';
})
.value();
},
firstStep: function() {
return new ChooseKeyColumnsModel({
leftTable: this.get('table'),
excludeColumns: this.get('excludeColumns')
});
}
});
| Fix can merge check for column merge | Fix can merge check for column merge
| JavaScript | bsd-3-clause | thorncp/cartodb,bloomberg/cartodb,CartoDB/cartodb,nyimbi/cartodb,nuxcode/cartodb,codeandtheory/cartodb,nuxcode/cartodb,dbirchak/cartodb,DigitalCoder/cartodb,future-analytics/cartodb,dbirchak/cartodb,thorncp/cartodb,UCL-ShippingGroup/cartodb-1,CartoDB/cartodb,bloomberg/cartodb,splashblot/dronedb,nyimbi/cartodb,dbirchak/cartodb,dbirchak/cartodb,nuxcode/cartodb,splashblot/dronedb,UCL-ShippingGroup/cartodb-1,splashblot/dronedb,nuxcode/cartodb,bloomberg/cartodb,nuxcode/cartodb,future-analytics/cartodb,thorncp/cartodb,DigitalCoder/cartodb,UCL-ShippingGroup/cartodb-1,codeandtheory/cartodb,codeandtheory/cartodb,DigitalCoder/cartodb,bloomberg/cartodb,UCL-ShippingGroup/cartodb-1,splashblot/dronedb,nyimbi/cartodb,future-analytics/cartodb,thorncp/cartodb,splashblot/dronedb,DigitalCoder/cartodb,future-analytics/cartodb,CartoDB/cartodb,CartoDB/cartodb,bloomberg/cartodb,nyimbi/cartodb,codeandtheory/cartodb,nyimbi/cartodb,dbirchak/cartodb,future-analytics/cartodb,CartoDB/cartodb,thorncp/cartodb,codeandtheory/cartodb,DigitalCoder/cartodb,UCL-ShippingGroup/cartodb-1 | ---
+++
@@ -26,7 +26,7 @@
.map(function(column) {
return column[0]; //name
})
- .without(this.get('filteredColumns'))
+ .without(this.get('excludeColumns'))
.any(function(columnName) {
return columnName !== 'the_geom';
}) |
c83853f0d3b12bff8ad6320e4f25b475874286e8 | utils/upgrade-extracted.js | utils/upgrade-extracted.js | var async = require("async");
var mongoose = require("mongoose");
require("ukiyoe-models")(mongoose);
var ExtractedImage = mongoose.model("ExtractedImage");
mongoose.connect('mongodb://localhost/extract');
mongoose.connection.on('error', function(err) {
console.error('Connection Error:', err)
});
mongoose.connection.once('open', function() {
ExtractedImage.batchQuery({"image": null}, 1000, function(err, data, callback) {
if (err) {
console.error(err);
return;
}
if (data.done) {
console.log("DONE");
process.exit(0);
return;
}
console.log("Processing " + data.from + " to " + data.to);
async.eachLimit(data.images, 10, function(extracted, callback) {
console.log(extracted._id);
extracted.upgrade(callback);
}, function(err) {
if (err) {
console.error(err);
}
if (callback) {
callback();
}
});
});
}); | var async = require("async");
var mongoose = require("mongoose");
require("ukiyoe-models")(mongoose);
var ExtractedImage = mongoose.model("ExtractedImage");
mongoose.connect('mongodb://localhost/extract');
mongoose.connection.on('error', function(err) {
console.error('Connection Error:', err)
});
mongoose.connection.once('open', function() {
var query = {"image": null};
if (process.argv[2]) {
query.source = process.argv[2];
}
ExtractedImage.batchQuery(query, 1000, function(err, data, callback) {
if (err) {
console.error(err);
return;
}
if (data.done) {
console.log("DONE");
process.exit(0);
return;
}
console.log("Processing " + data.from + " to " + data.to);
async.eachLimit(data.images, 10, function(extracted, callback) {
console.log(extracted._id);
extracted.upgrade(callback);
}, function(err) {
if (err) {
console.error(err);
}
if (callback) {
callback();
}
});
});
}); | Make it so that you can upgrade a specific source. | Make it so that you can upgrade a specific source.
| JavaScript | mit | jeresig/ukiyoe-web | ---
+++
@@ -11,7 +11,13 @@
});
mongoose.connection.once('open', function() {
- ExtractedImage.batchQuery({"image": null}, 1000, function(err, data, callback) {
+ var query = {"image": null};
+
+ if (process.argv[2]) {
+ query.source = process.argv[2];
+ }
+
+ ExtractedImage.batchQuery(query, 1000, function(err, data, callback) {
if (err) {
console.error(err);
return; |
5834c8958f74783422d84dc96fd9d2593dd67b83 | server/server.js | server/server.js | // Load environment variables
if (process.env.NODE_ENV === 'development') {
require('dotenv').config({ path: './env/development.env' });
}
var express = require('express');
var passport = require('passport');
var util = require('./lib/utility.js');
var app = express();
// Initial Configuration, Static Assets, & View Engine Configuration
require('./config/initialize.js')(app, express);
// Authentication Middleware: Express Sessions, Passport Strategy
require('./config/auth.js')(app, express, passport);
// Pre-Authentication Routes & OAuth Requests
require('./routes/auth-routes.js')(app, passport);
//Authentication check currently commented out, uncomment line to re-activate
// app.use(util.ensureAuthenticated);
// View Routes
require('./routes/view-routes.js')(app);
// API Routes
require('./routes/api-routes.js')(app);
// Wildcard route
app.get('/*', function(req, res) {
res.redirect('/');
})
app.listen(Number(process.env.PORT), process.env.HOST, function() {
console.log('NODE_ENV: ' + process.env.NODE_ENV);
console.log(process.env.APP_NAME + ' is listening at ' + process.env.HOST + ' on port ' + process.env.PORT + '.')
}); | // Load environment variables
if (process.env.NODE_ENV === 'development') {
require('dotenv').config({ path: './env/development.env' });
}
var express = require('express');
var passport = require('passport');
var util = require('./lib/utility.js');
var app = express();
// Initial Configuration, Static Assets, & View Engine Configuration
require('./config/initialize.js')(app, express);
// Authentication Middleware: Express Sessions, Passport Strategy
require('./config/auth.js')(app, express, passport);
// Pre-Authentication Routes & OAuth Requests
require('./routes/auth-routes.js')(app, passport);
//Authentication check currently commented out, uncomment line to re-activate
app.use(util.ensureAuthenticated);
// View Routes
require('./routes/view-routes.js')(app);
// API Routes
require('./routes/api-routes.js')(app);
// Wildcard route
app.get('/*', function(req, res) {
res.redirect('/');
})
app.listen(Number(process.env.PORT), process.env.HOST, function() {
console.log('NODE_ENV: ' + process.env.NODE_ENV);
console.log(process.env.APP_NAME + ' is listening at ' + process.env.HOST + ' on port ' + process.env.PORT + '.')
}); | Put back the authentication to pass Travis CI tests | Put back the authentication to pass Travis CI tests
| JavaScript | mit | formidable-coffee/masterfully,chkakaja/sentimize,formidable-coffee/masterfully,chkakaja/sentimize | ---
+++
@@ -18,7 +18,7 @@
require('./routes/auth-routes.js')(app, passport);
//Authentication check currently commented out, uncomment line to re-activate
-// app.use(util.ensureAuthenticated);
+app.use(util.ensureAuthenticated);
// View Routes
require('./routes/view-routes.js')(app); |
0e94996de971e27054747df5784e1df5270b5b60 | ui/model/tests/patch_file_tests.js | ui/model/tests/patch_file_tests.js |
describe("PatchFile should", function() {
it("only parse positive or zero delta numbers", function() {
var file = new PatchFile();
expect(file.added).toBe(0);
expect(file.removed).toBe(0);
file.added = 10;
file.removed = 5;
expect(file.added).toBe(10);
expect(file.removed).toBe(5);
file.parseData({
num_added: -1,
num_removed: -10,
});
expect(file.added).toBe(0);
expect(file.removed).toBe(0);
file.parseData({
num_added: 8,
num_removed: 4,
});
expect(file.added).toBe(8);
expect(file.removed).toBe(4);
});
});
|
describe("PatchFile should", function() {
it("parse file extensions into syntax highlighting languages", function() {
expect(PatchFile.computeLanguage("")).toBe("");
expect(PatchFile.computeLanguage("Document.h")).toBe("cpp");
expect(PatchFile.computeLanguage("Document.cpp")).toBe("cpp");
expect(PatchFile.computeLanguage("path/test.html")).toBe("html");
expect(PatchFile.computeLanguage("dir/test.xhtml")).toBe("html");
expect(PatchFile.computeLanguage("example.js")).toBe("javascript");
expect(PatchFile.computeLanguage("this_is.file.css")).toBe("css");
expect(PatchFile.computeLanguage("image.xml")).toBe("xml");
expect(PatchFile.computeLanguage("image.svg")).toBe("xml");
expect(PatchFile.computeLanguage("horror.pl")).toBe("perl");
expect(PatchFile.computeLanguage("horror2.pm")).toBe("perl");
expect(PatchFile.computeLanguage("//./.py/horror1.cgi")).toBe("perl");
expect(PatchFile.computeLanguage("snakesonaplane.py")).toBe("python");
expect(PatchFile.computeLanguage("gems.rb")).toBe("ruby");
expect(PatchFile.computeLanguage("cocoa.mm")).toBe("objectivec");
expect(PatchFile.computeLanguage("../.file/data.json")).toBe("json");
expect(PatchFile.computeLanguage("Document.idl")).toBe("actionscript");
expect(PatchFile.computeLanguage("Document.map")).toBe("");
expect(PatchFile.computeLanguage("Document.h.")).toBe("");
expect(PatchFile.computeLanguage("Document.cpp/")).toBe("");
});
it("only parse positive or zero delta numbers", function() {
var file = new PatchFile();
expect(file.added).toBe(0);
expect(file.removed).toBe(0);
file.added = 10;
file.removed = 5;
expect(file.added).toBe(10);
expect(file.removed).toBe(5);
file.parseData({
num_added: -1,
num_removed: -10,
});
expect(file.added).toBe(0);
expect(file.removed).toBe(0);
file.parseData({
num_added: 8,
num_removed: 4,
});
expect(file.added).toBe(8);
expect(file.removed).toBe(4);
});
});
| Add a PatchFile test for parsing file extensions. | Add a PatchFile test for parsing file extensions.
| JavaScript | bsd-3-clause | esprehn/chromium-codereview,esprehn/chromium-codereview | ---
+++
@@ -1,5 +1,27 @@
describe("PatchFile should", function() {
+ it("parse file extensions into syntax highlighting languages", function() {
+ expect(PatchFile.computeLanguage("")).toBe("");
+ expect(PatchFile.computeLanguage("Document.h")).toBe("cpp");
+ expect(PatchFile.computeLanguage("Document.cpp")).toBe("cpp");
+ expect(PatchFile.computeLanguage("path/test.html")).toBe("html");
+ expect(PatchFile.computeLanguage("dir/test.xhtml")).toBe("html");
+ expect(PatchFile.computeLanguage("example.js")).toBe("javascript");
+ expect(PatchFile.computeLanguage("this_is.file.css")).toBe("css");
+ expect(PatchFile.computeLanguage("image.xml")).toBe("xml");
+ expect(PatchFile.computeLanguage("image.svg")).toBe("xml");
+ expect(PatchFile.computeLanguage("horror.pl")).toBe("perl");
+ expect(PatchFile.computeLanguage("horror2.pm")).toBe("perl");
+ expect(PatchFile.computeLanguage("//./.py/horror1.cgi")).toBe("perl");
+ expect(PatchFile.computeLanguage("snakesonaplane.py")).toBe("python");
+ expect(PatchFile.computeLanguage("gems.rb")).toBe("ruby");
+ expect(PatchFile.computeLanguage("cocoa.mm")).toBe("objectivec");
+ expect(PatchFile.computeLanguage("../.file/data.json")).toBe("json");
+ expect(PatchFile.computeLanguage("Document.idl")).toBe("actionscript");
+ expect(PatchFile.computeLanguage("Document.map")).toBe("");
+ expect(PatchFile.computeLanguage("Document.h.")).toBe("");
+ expect(PatchFile.computeLanguage("Document.cpp/")).toBe("");
+ });
it("only parse positive or zero delta numbers", function() {
var file = new PatchFile();
|
f138c95cfb0bd88b7e43683588be6dbb9122e329 | src/responses.js | src/responses.js | // Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
"use strict";
const responses = {
noAudioPlayer: "Sorry, this application does not support audio streams.",
noIntent: "Sorry, I don't understand how to do that.",
noSession: "Sorry, the session is not available.",
onError: "Sorry, an error occurred.",
onInvalidRequest: "Sorry, that request is not valid.",
onLaunch: "Welcome to the London Travel skill.",
onUnknown: "Sorry, I didn't catch that.",
onSessionEnded: "Goodbye."
};
module.exports = responses;
| // Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
"use strict";
const responses = {
noAudioPlayer: "Sorry, this application does not support audio streams.",
noIntent: "Sorry, I don't understand how to do that.",
noSession: "Sorry, the session is not available.",
onError: "Sorry, something went wrong.",
onInvalidRequest: "Sorry, that request is not valid.",
onLaunch: "Welcome to the London Travel skill.",
onUnknown: "Sorry, I didn't catch that.",
onSessionEnded: "Goodbye."
};
module.exports = responses;
| Change the default error message | Change the default error message
Make the default error message souund a bit friendlier.
| JavaScript | apache-2.0 | martincostello/alexa-london-travel | ---
+++
@@ -7,7 +7,7 @@
noAudioPlayer: "Sorry, this application does not support audio streams.",
noIntent: "Sorry, I don't understand how to do that.",
noSession: "Sorry, the session is not available.",
- onError: "Sorry, an error occurred.",
+ onError: "Sorry, something went wrong.",
onInvalidRequest: "Sorry, that request is not valid.",
onLaunch: "Welcome to the London Travel skill.",
onUnknown: "Sorry, I didn't catch that.", |
018b82dae4f564b74851c73f250e2a9f13b493b8 | chattify.js | chattify.js | function filterF(i, el) {
var pattern = /(From|To|Sent|Subject|Cc|Date):/i;
return el.textContent.match(pattern);
}
// convert From...To... blocks into one-liners
var matches = $(document).find("*").filter(filterF).get().reverse();
while (matches.length > 0) {
matches[0].remove();
matches = $(document).find("*").filter(filterF).get().reverse();
}
// remove blockquotes but preserve contents
$($("blockquote").get().reverse()).each(function(i, el) {
var contents = $(el).contents();
contents.insertAfter($(el));
$(el).remove();
});
| function filterF(i, el) {
var pattern = /(From|To|Sent|Subject|Cc|Date):/i;
return el.textContent.match(pattern);
}
// convert From...To... blocks into one-liners
var matches = $(document).find("*").filter(filterF).get().reverse();
while (matches.length > 0) {
var parent = $(matches[0]).parent();
var localMatches = parent.find("*").filter(filterF);
// insert breakpoint after either the last element of localMatches
var breakpoint = "breakpoint";
$(localMatches[localMatches.length-1]).insertAfter("<div id=" + breakpoint + "></div>");
$(localMatches[0]).nextUntil("#" + breakpoint).each(function(i, el) {
$(el).remove();
});
$(localMatches[0]).remove();
$("#" + breakpoint).remove();
matches = $(document).find("*").filter(filterF).get().reverse();
}
// remove blockquotes but preserve contents
$($("blockquote").get().reverse()).each(function(i, el) {
var contents = $(el).contents();
contents.insertAfter($(el));
$(el).remove();
});
| Remove From...To... tags including all content | Remove From...To... tags including all content
| JavaScript | mit | kubkon/email-chattifier,kubkon/email-chattifier | ---
+++
@@ -7,7 +7,18 @@
var matches = $(document).find("*").filter(filterF).get().reverse();
while (matches.length > 0) {
- matches[0].remove();
+ var parent = $(matches[0]).parent();
+ var localMatches = parent.find("*").filter(filterF);
+
+ // insert breakpoint after either the last element of localMatches
+ var breakpoint = "breakpoint";
+ $(localMatches[localMatches.length-1]).insertAfter("<div id=" + breakpoint + "></div>");
+ $(localMatches[0]).nextUntil("#" + breakpoint).each(function(i, el) {
+ $(el).remove();
+ });
+ $(localMatches[0]).remove();
+ $("#" + breakpoint).remove();
+
matches = $(document).find("*").filter(filterF).get().reverse();
}
|
3f2b4bb35d616dd548352bbdf1338ab64c1a6459 | src/index.js | src/index.js | import React from 'react';
import ReactDom from 'react-dom';
import Feedy from './Components/Feedy';
import styles from './assets/styles/reset.less';
module.exports = function({namespaceUrl, appName}={
namespaceUrl:'https://webcom.orange.com/base/feedy',
appName:'general'
}) {
$("<div id='feedy'></div>").appendTo(document.body);
ReactDom.render(
<Feedy namespaceUrl={namespaceUrl} appName={appName} />,
document.getElementById('feedy')
);
} | import React from 'react';
import ReactDom from 'react-dom';
import Feedy from './Components/Feedy';
import styles from './assets/styles/reset.less';
module.exports = function({namespaceUrl='https://webcom.orange.com/base/feedy', appName='general'}) {
$("<div id='feedy'></div>").appendTo(document.body);
ReactDom.render(
<Feedy namespaceUrl={namespaceUrl} appName={appName} />,
document.getElementById('feedy')
);
} | Initialize feedy with an empty object crashes | fix: Initialize feedy with an empty object crashes
| JavaScript | mit | webcom-components/feedy,webcom-components/feedy | ---
+++
@@ -4,10 +4,7 @@
import styles from './assets/styles/reset.less';
-module.exports = function({namespaceUrl, appName}={
- namespaceUrl:'https://webcom.orange.com/base/feedy',
- appName:'general'
-}) {
+module.exports = function({namespaceUrl='https://webcom.orange.com/base/feedy', appName='general'}) {
$("<div id='feedy'></div>").appendTo(document.body);
ReactDom.render( |
d87dd0f7cb14a07ebf93c75af60149bdee99337c | src/index.js | src/index.js | import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import marked from 'marked';
import 'normalize.css';
import prism from 'prismjs';
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import config from './config';
import './global.css';
import App from './components/App';
import registerServiceWorker from './utils/registerServiceWorker';
firebase.initializeApp(config[process.env.NODE_ENV]);
prism.languages.js = prism.languages.javascript;
marked.setOptions({
highlight(code, language) {
const grammar = prism.languages[language] || prism.languages.markup;
return prism.highlight(code, grammar);
},
langPrefix: 'language-',
});
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('app'),
);
registerServiceWorker();
| import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import marked from 'marked';
import 'normalize.css';
import prism from 'prismjs';
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import config from './config';
import './global.css';
import App from './components/App';
import { unregister } from './utils/registerServiceWorker';
unregister();
firebase.initializeApp(config[process.env.NODE_ENV]);
prism.languages.js = prism.languages.javascript;
marked.setOptions({
highlight(code, language) {
const grammar = prism.languages[language] || prism.languages.markup;
return prism.highlight(code, grammar);
},
langPrefix: 'language-',
});
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('app'),
);
| Add code to unregister the service worker for now | Add code to unregister the service worker for now
| JavaScript | mit | hoopr/codework,hoopr/codework | ---
+++
@@ -11,10 +11,11 @@
import config from './config';
import './global.css';
import App from './components/App';
-import registerServiceWorker from './utils/registerServiceWorker';
+import { unregister } from './utils/registerServiceWorker';
+
+unregister();
firebase.initializeApp(config[process.env.NODE_ENV]);
-
prism.languages.js = prism.languages.javascript;
marked.setOptions({
highlight(code, language) {
@@ -30,4 +31,3 @@
</Router>,
document.getElementById('app'),
);
-registerServiceWorker(); |
e4e1d2a3eadf4b322c744f57278d154321142217 | hooks/beforePrepare.js | hooks/beforePrepare.js | #!/usr/bin/env node
var exec = require('child_process').exec;
var fs = require('fs');
var coffee_path = 'coffee/'
if( !fs.existsSync(coffee_path)) {
fs.mkdirSync(coffee_path)
}
exec("coffee --compile --output www/js/ " + coffee_path)
| #!/usr/bin/env node
var execSync = require('child_process').execSync;
var fs = require('fs');
var coffee_path = 'coffee/'
if( !fs.existsSync(coffee_path)) {
fs.mkdirSync(coffee_path)
}
execSync("coffee --compile --output www/js/ " + coffee_path)
| Use execSync to avoid race | Use execSync to avoid race
Running coffeescript in the background means that cordova might use
stale output, depending on who is faster.
As an added bonus, throws error if coffeescript exits with a non-zero
return code. Usually, that is because of a syntax error in the
sources.
| JavaScript | mit | metova/coffee-script-cordova-plugin | ---
+++
@@ -1,6 +1,6 @@
#!/usr/bin/env node
-var exec = require('child_process').exec;
+var execSync = require('child_process').execSync;
var fs = require('fs');
var coffee_path = 'coffee/'
@@ -9,4 +9,4 @@
fs.mkdirSync(coffee_path)
}
-exec("coffee --compile --output www/js/ " + coffee_path)
+execSync("coffee --compile --output www/js/ " + coffee_path) |
f5a666047b05cbb8034aad958e0fba938769b4fb | tests/dummy/config/targets.js | tests/dummy/config/targets.js | const browsers = [
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Safari versions'
];
const isCI = !!process.env.CI;
const isProduction = process.env.EMBER_ENV === 'production';
if (isCI || isProduction) {
browsers.push('ie 11');
}
module.exports = {
browsers
};
| var browsers = [
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Safari versions'
];
var isCI = !!process.env.CI;
var isProduction = process.env.EMBER_ENV === 'production';
if (isCI || isProduction) {
browsers.push('ie 11');
}
module.exports = {
browsers
};
| Switch const to var for node 4 | Switch const to var for node 4
| JavaScript | mit | paddle8/ember-autoresize,tim-evans/ember-autoresize,tim-evans/ember-autoresize,paddle8/ember-autoresize | ---
+++
@@ -1,11 +1,11 @@
-const browsers = [
+var browsers = [
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Safari versions'
];
-const isCI = !!process.env.CI;
-const isProduction = process.env.EMBER_ENV === 'production';
+var isCI = !!process.env.CI;
+var isProduction = process.env.EMBER_ENV === 'production';
if (isCI || isProduction) {
browsers.push('ie 11'); |
8ea18ca05393c92f457f92cb0901ed6e5b42d761 | app/scripts/services/responseredirector.js | app/scripts/services/responseredirector.js | 'use strict';
/**
* @ngdoc service
* @name wavesApp.responseredirector
* @description
* # responseredirector
* Service in the wavesApp.
*/
angular.module('wavesApp')
.service('responseRedirector', ['$state', function ($state) {
function noServiceFound(response){
return response.status === 'not_found';
}
return {
redirect: function(response){
response = JSON.parse(response);
if(noServiceFound(response)){
$state.go(response.attributes.query_words[0].toLowerCase(), response);
}else{
$state.go('not_found', response);
}
}
};
}]);
| 'use strict';
/**
* @ngdoc service
* @name wavesApp.responseredirector
* @description
* # responseredirector
* Service in the wavesApp.
*/
angular.module('wavesApp')
.service('responseRedirector', ['$state', function ($state) {
function noServiceFound(response){
return response.attributes.status == 'not_found';
}
return {
redirect: function(response){
response = response.data;
if(noServiceFound(response)){
$state.go(response.attributes.query_words[0].toLowerCase(), response);
}else{
$state.go('not_found', response);
}
}
};
}]);
| FIX on response data reference. | FIX on response data reference.
| JavaScript | mit | InflectProject/waves,InflectProject/waves | ---
+++
@@ -10,12 +10,12 @@
angular.module('wavesApp')
.service('responseRedirector', ['$state', function ($state) {
function noServiceFound(response){
- return response.status === 'not_found';
+ return response.attributes.status == 'not_found';
}
return {
redirect: function(response){
- response = JSON.parse(response);
+ response = response.data;
if(noServiceFound(response)){
$state.go(response.attributes.query_words[0].toLowerCase(), response);
}else{ |
851b16ece1303a9eae5090014eae85dd2e572ef7 | skeleton/boot.js | skeleton/boot.js |
var Protos = require('../');
Protos.bootstrap(__dirname, {
// Server configuration
server: {
host: 'localhost',
port: 8080,
multiProcess: false,
stayUp: false
},
// Application environments
environments: {
default: 'development',
development: function(app) {
app.debugLog = false;
}
},
// Application events
events: {
init: function(app) {
// Load extensions in lib/
app.libExtensions();
// Load middleware
app.use('logger');
app.use('markdown');
app.use('body_parser');
app.use('cookie_parser');
app.use('static_server');
}
}
});
module.exports = protos.app; |
var Protos = require('../');
Protos.bootstrap(__dirname, {
// Server configuration
server: {
host: 'localhost',
port: 8080,
multiProcess: false,
stayUp: false
},
// Application environments
environments: {
default: 'development',
development: function(app) {
app.debugLog = false;
}
},
// Application events
events: {
init: function(app) {
// Load middleware
app.use('logger');
app.use('markdown');
app.use('body_parser');
app.use('cookie_parser');
app.use('static_server');
// Load extensions in lib/
app.libExtensions();
}
}
});
module.exports = protos.app; | Load lib extensions after loading middleware | Load lib extensions after loading middleware
| JavaScript | mit | derdesign/protos | ---
+++
@@ -23,15 +23,16 @@
events: {
init: function(app) {
- // Load extensions in lib/
- app.libExtensions();
-
// Load middleware
app.use('logger');
app.use('markdown');
app.use('body_parser');
app.use('cookie_parser');
app.use('static_server');
+
+ // Load extensions in lib/
+ app.libExtensions();
+
}
}
|
b0141005e616e171cf60731c9e751604e6370d33 | examples/js/password.js | examples/js/password.js | var doc = new jsPDF({
encryption: {
userPassword: "user",
ownerPassword: "owner",
userPermissions: ["print", "modify", "copy", "annot-forms"]
// try changing the user permissions granted
}
});
doc.setFontSize(40);
doc.text("Octonyan loves jsPDF", 35, 25);
doc.addImage("examples/images/Octonyan.jpg", "JPEG", 15, 40, 180, 180);
| var doc = new jsPDF({
// jsPDF supports encryption of PDF version 1.3.
// Version 1.3 just uses RC4 40-bit which is kown to be weak and is NOT state of the art.
// Keep in mind that it is just a minimal protection.
encryption: {
userPassword: "user",
ownerPassword: "owner",
userPermissions: ["print", "modify", "copy", "annot-forms"]
// try changing the user permissions granted
}
});
doc.setFontSize(40);
doc.text("Octonyan loves jsPDF", 35, 25);
doc.addImage("examples/images/Octonyan.jpg", "JPEG", 15, 40, 180, 180);
| Add security notice for encryption | Add security notice for encryption | JavaScript | mit | MrRio/jsPDF,MrRio/jsPDF,MrRio/jsPDF | ---
+++
@@ -1,4 +1,7 @@
var doc = new jsPDF({
+ // jsPDF supports encryption of PDF version 1.3.
+ // Version 1.3 just uses RC4 40-bit which is kown to be weak and is NOT state of the art.
+ // Keep in mind that it is just a minimal protection.
encryption: {
userPassword: "user",
ownerPassword: "owner", |
686c874a4b2b1b9e1ff246fe8ab11f0e4a8d2c3e | app/assets/javascripts/audio_controls.js | app/assets/javascripts/audio_controls.js | window.GLOBAL_ACTIONS = {
'play': function () {
wavesurfer.playPause();
},
'back': function () {
wavesurfer.skipBackward();
},
'forth': function () {
wavesurfer.skipForward();
},
'toggle-mute': function () {
wavesurfer.toggleMute();
}
};
// Bind actions to buttons and keypresses
document.addEventListener('DOMContentLoaded', function () {
document.addEventListener('keydown', function (e) {
var map = {
32: 'play', // space
37: 'back', // left
39: 'forth' // right
};
var action = map[e.keyCode];
if (action in GLOBAL_ACTIONS) {
e.preventDefault();
GLOBAL_ACTIONS[action](e);
}
});
[].forEach.call(document.querySelectorAll('[data-action]'), function (el) {
el.addEventListener('click', function (e) {
var action = e.currentTarget.dataset.action;
if (action in GLOBAL_ACTIONS) {
e.preventDefault();
GLOBAL_ACTIONS[action](e);
}
});
});
});
| window.GLOBAL_ACTIONS = {
'play': function () {
wavesurfer.playPause();
},
'back': function () {
wavesurfer.skipBackward();
},
'forth': function () {
wavesurfer.skipForward();
},
'toggle-mute': function () {
wavesurfer.toggleMute();
}
};
// Bind actions to buttons and keypresses
document.addEventListener('DOMContentLoaded', function () {
document.addEventListener('keydown', function (e) {
var map = {
32: 'play', // space
37: 'back', // left
39: 'forth' // right
};
if(e.target.nodeName.toLowerCase() === 'input'){
return;
}
var action = map[e.keyCode];
if (action in GLOBAL_ACTIONS) {
e.preventDefault();
GLOBAL_ACTIONS[action](e);
}
});
[].forEach.call(document.querySelectorAll('[data-action]'), function (el) {
el.addEventListener('click', function (e) {
var action = e.currentTarget.dataset.action;
if (action in GLOBAL_ACTIONS) {
e.preventDefault();
GLOBAL_ACTIONS[action](e);
}
});
});
});
| Disable keyboard shortcuts when editing input field | Disable keyboard shortcuts when editing input field
| JavaScript | mit | shirshendu/kine_type,shirshendu/kine_type,shirshendu/kine_type,shirshendu/kine_type | ---
+++
@@ -25,6 +25,9 @@
37: 'back', // left
39: 'forth' // right
};
+ if(e.target.nodeName.toLowerCase() === 'input'){
+ return;
+ }
var action = map[e.keyCode];
if (action in GLOBAL_ACTIONS) {
e.preventDefault(); |
a02a43f4f79ada52892eeefbc712da708eaa4ad5 | app/scripts/services/payments-service.js | app/scripts/services/payments-service.js | 'use strict';
(function() {
angular.module('ncsaas')
.service('paymentsService', ['baseServiceClass', 'ENV', '$http', paymentsService]);
function paymentsService(baseServiceClass, ENV, $http) {
/*jshint validthis: true */
var ServiceClass = baseServiceClass.extend({
init:function() {
this._super();
this.endpoint = '/paypal-payments/';
this.filterByCustomer = false;
},
approve: function(payment) {
return $http.post(ENV.apiEndpoint + 'api/paypal-payments/approve/', payment);
}
});
return new ServiceClass();
}
})();
| 'use strict';
(function() {
angular.module('ncsaas')
.service('paymentsService', ['baseServiceClass', 'ENV', '$http', paymentsService]);
function paymentsService(baseServiceClass, ENV, $http) {
/*jshint validthis: true */
var ServiceClass = baseServiceClass.extend({
init:function() {
this._super();
this.endpoint = '/paypal-payments/';
this.filterByCustomer = false;
},
approve: function(payment) {
return $http.post(ENV.apiEndpoint + 'api/paypal-payments/approve/', payment);
},
cancel: function(payment) {
return $http.post(ENV.apiEndpoint + 'api/paypal-payments/cancel/', payment);
}
});
return new ServiceClass();
}
})();
| Implement service method for payment cancellation (SAAS-1101) | Implement service method for payment cancellation (SAAS-1101)
| JavaScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -14,6 +14,9 @@
},
approve: function(payment) {
return $http.post(ENV.apiEndpoint + 'api/paypal-payments/approve/', payment);
+ },
+ cancel: function(payment) {
+ return $http.post(ENV.apiEndpoint + 'api/paypal-payments/cancel/', payment);
}
});
return new ServiceClass(); |
254f104c213282cef4bc285473cdf39e73ed80fb | db/dbconnect.js | db/dbconnect.js | var mysql = require('mysql');
// Create a database connection and export it from this file.
// You will need to connect with the user "root", no password,
// and to the database "chat".
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'foodQuest'
});
connection.connect();
module.exports.connection = connection; | var mysql = require('mysql');
// Create a database connection and export it from this file.
// You will need to connect with the user "root", no password,
// and to the database "chat".
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'foodQuest',
multipleStatements: true
});
connection.connect();
module.exports.connection = connection; | Set multipleStatements to true in mysql.createConnection object | Set multipleStatements to true in mysql.createConnection object
| JavaScript | mit | Sibilant-Siblings/sibilant-siblings,Sibilant-Siblings/sibilant-siblings | ---
+++
@@ -8,7 +8,8 @@
host: '127.0.0.1',
user: 'root',
password: '',
- database: 'foodQuest'
+ database: 'foodQuest',
+ multipleStatements: true
});
connection.connect(); |
9f3653e9b0982aaada55f17f85c9a611036edcb8 | src/app.js | src/app.js | (function (window) {
'use strict';
var hearingTest = HearingTest;
var hearing = hearingTest.init();
var app = new Vue({
el: '#hearing-test-app',
data: {
isPlaySound: false,
frequency: 1000
},
methods: {
changeFrequency: function() {
hearing.sound.frequency.value = this.frequency;
}
}
});
}(window));
| (function (window) {
'use strict';
var hearingTest = HearingTest;
var hearing = hearingTest.init();
var app = new Vue({
el: '#hearing-test-app',
data: {
isPlaySound: false,
frequency: 1000
},
methods: {
changeFrequency: function() {
hearing.sound.frequency.value = this.frequency;
},
playSound: function() {
hearingTest.playSound();
this.isPlaySound = true;
},
stopSound: function() {
hearingTest.stopSound();
this.isPlaySound = false;
}
}
});
}(window));
| Implement play and stop sound | Implement play and stop sound
| JavaScript | mit | kubosho/hearing-test-app | ---
+++
@@ -13,6 +13,16 @@
methods: {
changeFrequency: function() {
hearing.sound.frequency.value = this.frequency;
+ },
+
+ playSound: function() {
+ hearingTest.playSound();
+ this.isPlaySound = true;
+ },
+
+ stopSound: function() {
+ hearingTest.stopSound();
+ this.isPlaySound = false;
}
}
}); |
5df999836d0fdc20ec197f7ff808b6d85828a694 | src/app.js | src/app.js | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom';
import configureStore from 'redux/configureStore';
import { newGame } from 'redux/modules/game';
import { DevTools, Board } from './containers';
import './styles/app.scss';
if (module.hot) {
module.hot.accept();
}
const store = configureStore();
store.dispatch(newGame({ yourName: 'Inooid', opponentName: 'OpponentName' }));
class App extends Component {
render() {
return <Board />;
}
}
ReactDOM.render(
<Provider store={store}>
<div style={{ width: '100%', height: '100%' }}>
<App />
<DevTools />
</div>
</Provider>,
document.getElementById('app')
);
| import React, { Component } from 'react';
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom';
import configureStore from 'redux/configureStore';
import { newGame } from 'redux/modules/game';
import { DevTools, Board } from './containers';
import './styles/app.scss';
import sharedStyles from 'components/shared/styles.scss';
if (module.hot) {
module.hot.accept();
}
const store = configureStore();
store.dispatch(newGame({ yourName: 'Inooid', opponentName: 'OpponentName' }));
class App extends Component {
render() {
return <Board />;
}
}
ReactDOM.render(
<Provider store={store}>
<div className={sharedStyles.fullSize}>
<App />
<DevTools />
</div>
</Provider>,
document.getElementById('app')
);
| Remove hard coding 100% width height | Remove hard coding 100% width height
| JavaScript | mit | inooid/react-redux-card-game,inooid/react-redux-card-game | ---
+++
@@ -6,6 +6,7 @@
import { newGame } from 'redux/modules/game';
import { DevTools, Board } from './containers';
import './styles/app.scss';
+import sharedStyles from 'components/shared/styles.scss';
if (module.hot) {
module.hot.accept();
@@ -22,7 +23,7 @@
ReactDOM.render(
<Provider store={store}>
- <div style={{ width: '100%', height: '100%' }}>
+ <div className={sharedStyles.fullSize}>
<App />
<DevTools />
</div> |
4decd4229420b8a2979ef80f20e5593b070f4a55 | src/bot.js | src/bot.js | const Eris = require("eris");
const config = require("./cfg");
const intents = [
// PRIVILEGED INTENTS
"guildMembers", // For server greetings
// REGULAR INTENTS
"directMessages", // For core functionality
"guildMessages", // For bot commands and mentions
"guilds", // For core functionality
"guildVoiceStates", // For member information in the thread header
"guildMessageTyping", // For typing indicators
"directMessageTyping", // For typing indicators
// EXTRA INTENTS (from the config)
...config.extraIntents,
];
const bot = new Eris.Client(config.token, {
restMode: true,
intents: Array.from(new Set(intents)),
allowedMentions: {
everyone: false,
roles: false,
users: false,
},
});
bot.on("error", err => {
if (err.code === 1006) {
// 1006 = "Connection reset by peer"
// Eris allegedly handles this internally, so we can ignore it
return;
}
throw err;
});
/**
* @type {Eris.Client}
*/
module.exports = bot;
| const Eris = require("eris");
const config = require("./cfg");
const intents = [
// PRIVILEGED INTENTS
"guildMembers", // For server greetings
// REGULAR INTENTS
"directMessages", // For core functionality
"guildMessages", // For bot commands and mentions
"guilds", // For core functionality
"guildVoiceStates", // For member information in the thread header
"guildMessageTyping", // For typing indicators
"directMessageTyping", // For typing indicators
// EXTRA INTENTS (from the config)
...config.extraIntents,
];
const bot = new Eris.Client(config.token, {
restMode: true,
intents: Array.from(new Set(intents)),
allowedMentions: {
everyone: false,
roles: false,
users: false,
},
});
bot.on("error", err => {
if (err.code === 1006 || err.code === "ECONNRESET") {
// 1006 = "Connection reset by peer"
// ECONNRESET is similar
// Eris allegedly handles these internally, so we can ignore them
return;
}
throw err;
});
/**
* @type {Eris.Client}
*/
module.exports = bot;
| Handle ECONNRESET errors gracefully as well | Handle ECONNRESET errors gracefully as well
| JavaScript | mit | Dragory/modmailbot | ---
+++
@@ -28,9 +28,10 @@
});
bot.on("error", err => {
- if (err.code === 1006) {
+ if (err.code === 1006 || err.code === "ECONNRESET") {
// 1006 = "Connection reset by peer"
- // Eris allegedly handles this internally, so we can ignore it
+ // ECONNRESET is similar
+ // Eris allegedly handles these internally, so we can ignore them
return;
}
|
6e97d5633c676ce1865fa32b2845aa042f151dd5 | addon/utils/scales/d3-linear-scale.js | addon/utils/scales/d3-linear-scale.js | import Ember from 'ember';
import Scale from './d3-scale';
const { on, observer } = Ember;
export default Scale.extend({
init() {
this.set('scale', d3.scale.linear());
},
rangeRoundChanged: on('init', observer('rangeRound.[]', function() {
this.updateScale('rangeRound');
})),
interpolateChanged: on('init', observer('interpolate', function() {
this.updateScale('interpolate');
})),
clampChanged: on('init', observer('clamp', function() {
this.updateScale('clamp')
})),
niceChanged: on('init', observer('nice', function() {
this.updateScale('nice')
}))
});
| import Ember from 'ember';
import Scale from './d3-scale';
const { on, observer } = Ember;
export default Scale.extend({
init() {
this.set('scale', d3.scale.linear());
},
rangeRoundChanged: on('init', observer('rangeRound.[]', function() {
this.updateScale('rangeRound');
})),
interpolateChanged: on('init', observer('interpolate', function() {
this.updateScale('interpolate');
})),
clampChanged: on('init', observer('clamp', function() {
this.updateScale('clamp')
})),
niceChanged: on('init', observer('nice', function() {
let nice = this.get('nice');
if(nice) {
this.get('scale').nice();
Ember.run.next(this, 'notifyPropertyChange', 'scale');
}
})),
niceTickCountChanged: on('init', observer('niceTickCount', function() {
this.updateScale('niceTickCount', 'nice')
}))
});
| Add support for calling default nice() | Add support for calling default nice()
| JavaScript | mit | BryanHunt/ember-d3-components,BryanHunt/ember-d3-components,BryanHunt/ember-d3,BryanHunt/ember-d3 | ---
+++
@@ -21,6 +21,15 @@
})),
niceChanged: on('init', observer('nice', function() {
- this.updateScale('nice')
+ let nice = this.get('nice');
+
+ if(nice) {
+ this.get('scale').nice();
+ Ember.run.next(this, 'notifyPropertyChange', 'scale');
+ }
+ })),
+
+ niceTickCountChanged: on('init', observer('niceTickCount', function() {
+ this.updateScale('niceTickCount', 'nice')
}))
}); |
1fa196037e62c10a74f0d5fb1683270b201bd8a2 | test/testutils.js | test/testutils.js |
exports.get_config = get_config;
function get_config() {
var config = { };
try {
config = require('./config');
} catch(exception) {
config = require('./config-example');
}
return load_config(config);
}
exports.load_config = load_config;
function load_config(config) {
return load_module('config').load(config);
}
exports.load_module = load_module;
function load_module(name) {
return require((process.env.RIPPLE_LIB_COV ? '../src-cov/js/ripple/' : '../src/js/ripple/') + name);
}
| var ripple = require('../src/js/ripple');
exports.get_config = get_config;
function get_config() {
var config = { };
try {
config = require('./config');
} catch(exception) {
config = require('./config-example');
}
return load_config(config);
};
exports.load_config = load_config;
function load_config(config) {
return load_module('config').load(config);
};
exports.load_module = load_module;
function load_module(name) {
if (process.env.RIPPLE_LIB_COV) {
return require('../src-cov/js/ripple/' + name)
} else if (!ripple.hasOwnProperty(name)) {
return require('../src/js/ripple/' + name);
} else {
return require('../src/js/ripple')[name];
}
};
| Fix direct requirements for tests | Fix direct requirements for tests
| JavaScript | isc | ripple/ripple-lib,wilsonianb/ripple-lib,ripple/ripple-lib,darkdarkdragon/ripple-lib,ripple/ripple-lib,wilsonianb/ripple-lib,darkdarkdragon/ripple-lib,ripple/ripple-lib,wilsonianb/ripple-lib,darkdarkdragon/ripple-lib | ---
+++
@@ -1,3 +1,4 @@
+var ripple = require('../src/js/ripple');
exports.get_config = get_config;
@@ -9,16 +10,22 @@
config = require('./config-example');
}
return load_config(config);
-}
+};
exports.load_config = load_config;
function load_config(config) {
return load_module('config').load(config);
-}
+};
exports.load_module = load_module;
function load_module(name) {
- return require((process.env.RIPPLE_LIB_COV ? '../src-cov/js/ripple/' : '../src/js/ripple/') + name);
-}
+ if (process.env.RIPPLE_LIB_COV) {
+ return require('../src-cov/js/ripple/' + name)
+ } else if (!ripple.hasOwnProperty(name)) {
+ return require('../src/js/ripple/' + name);
+ } else {
+ return require('../src/js/ripple')[name];
+ }
+}; |
7aa447ff9aa381bc4bee5fff1f02e9625f0bbfe0 | packages/minifier-js/package.js | packages/minifier-js/package.js | Package.describe({
summary: "JavaScript minifier",
version: "2.6.1"
});
Npm.depends({
terser: "4.8.0"
});
Package.onUse(function (api) {
api.use('ecmascript');
api.use('babel-compiler');
api.mainModule('minifier.js', 'server');
api.export('meteorJsMinify');
});
Package.onTest(function (api) {
api.use('ecmascript');
api.use('tinytest');
api.use('minifier-js');
api.mainModule('minifier-tests.js', 'server');
}); | Package.describe({
summary: "JavaScript minifier",
version: "2.6.1"
});
Npm.depends({
terser: "4.8.0"
});
Package.onUse(function (api) {
api.use('ecmascript');
api.mainModule('minifier.js', 'server');
api.export('meteorJsMinify');
});
Package.onTest(function (api) {
api.use('ecmascript');
api.use('tinytest');
api.use('minifier-js');
api.mainModule('minifier-tests.js', 'server');
});
| Remove babel-compiler dependency in minifier-js | Remove babel-compiler dependency in minifier-js
| JavaScript | mit | Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor | ---
+++
@@ -9,7 +9,6 @@
Package.onUse(function (api) {
api.use('ecmascript');
- api.use('babel-compiler');
api.mainModule('minifier.js', 'server');
api.export('meteorJsMinify');
}); |
32df49502da1865eaf84ee97447137289e939a0a | src/bom/Label.js | src/bom/Label.js | /*
==================================================================================================
Lowland - JavaScript low level functions
Copyright (C) 2012 Sebatian Fastner
==================================================================================================
*/
core.Module("lowland.bom.Label", {
create : function(value, html) {
var e = document.createElement("div");
if (html) {
e.setAttribute("html", "true");
}
lowland.bom.Label.setValue(e, value);
return e;
},
getHtmlSize : function(content, style, width) {
console.log("GET HTML SIZE");
},
getTextSize : function(content, style) {
console.log("GET TEXT SIZE");
},
setValue : function(label, content) {
var html = !!label.getAttribute("html");
if (html) {
label.innerHTML = content;
} else {
label.setAttribute("text", content);
}
}
}); | /*
==================================================================================================
Lowland - JavaScript low level functions
Copyright (C) 2012 Sebatian Fastner
==================================================================================================
*/
(function(global) {
var measureElement = global.document.createElement("div");
core.bom.Style.set(measureElement, {
height: "auto",
width: "auto",
left: "-10000px",
top: "-10000px",
position: "absolute",
overflow: "visible",
display: "block"
});
var body = global.document.body;
body.insertBefore(measureElement, body.firstChild);
core.Module("lowland.bom.Label", {
create : function(value, html) {
var e = document.createElement("div");
if (html) {
e.setAttribute("html", "true");
}
lowland.bom.Label.setValue(e, value);
return e;
},
getHtmlSize : function(content, style, width) {
console.log("GET HTML SIZE");
},
getTextSize : function(content, style) {
var protectStyle = {
whiteSpace: "no-wrap",
fontFamily: style.fontFamily || "",
fontWeight: style.fontWeight || "",
fontSize: style.fontSize || "",
fontStyle: style.fontStyle || "",
lineHeight: style.lineHeight || ""
};
core.bom.Style.set(measureElement, protectStyle);
this.__setText(measureElement, content);
return lowland.bom.Element.getContentSize(measureElement);
},
setValue : function(label, content) {
var html = !!label.getAttribute("html");
if (html) {
label.innerHTML = content;
} else {
this.__setText(label, content);
}
},
__setText : function(element, content) {
if (core.Env.getValue("engine") == "trident") {
element.innerText = content;
} else {
element.textContent = content;
}
}
});
})(this); | Add calculation of text label | Add calculation of text label
| JavaScript | mit | fastner/lowland,fastner/lowland | ---
+++
@@ -5,31 +5,68 @@
==================================================================================================
*/
-core.Module("lowland.bom.Label", {
- create : function(value, html) {
- var e = document.createElement("div");
- if (html) {
- e.setAttribute("html", "true");
+(function(global) {
+
+ var measureElement = global.document.createElement("div");
+ core.bom.Style.set(measureElement, {
+ height: "auto",
+ width: "auto",
+ left: "-10000px",
+ top: "-10000px",
+ position: "absolute",
+ overflow: "visible",
+ display: "block"
+ });
+
+ var body = global.document.body;
+ body.insertBefore(measureElement, body.firstChild);
+
+ core.Module("lowland.bom.Label", {
+ create : function(value, html) {
+ var e = document.createElement("div");
+ if (html) {
+ e.setAttribute("html", "true");
+ }
+ lowland.bom.Label.setValue(e, value);
+ return e;
+ },
+
+ getHtmlSize : function(content, style, width) {
+ console.log("GET HTML SIZE");
+ },
+
+ getTextSize : function(content, style) {
+ var protectStyle = {
+ whiteSpace: "no-wrap",
+ fontFamily: style.fontFamily || "",
+ fontWeight: style.fontWeight || "",
+ fontSize: style.fontSize || "",
+ fontStyle: style.fontStyle || "",
+ lineHeight: style.lineHeight || ""
+ };
+ core.bom.Style.set(measureElement, protectStyle);
+ this.__setText(measureElement, content);
+
+ return lowland.bom.Element.getContentSize(measureElement);
+ },
+
+ setValue : function(label, content) {
+ var html = !!label.getAttribute("html");
+
+ if (html) {
+ label.innerHTML = content;
+ } else {
+ this.__setText(label, content);
+ }
+ },
+
+ __setText : function(element, content) {
+ if (core.Env.getValue("engine") == "trident") {
+ element.innerText = content;
+ } else {
+ element.textContent = content;
+ }
}
- lowland.bom.Label.setValue(e, value);
- return e;
- },
+ });
- getHtmlSize : function(content, style, width) {
- console.log("GET HTML SIZE");
- },
-
- getTextSize : function(content, style) {
- console.log("GET TEXT SIZE");
- },
-
- setValue : function(label, content) {
- var html = !!label.getAttribute("html");
-
- if (html) {
- label.innerHTML = content;
- } else {
- label.setAttribute("text", content);
- }
- }
-});
+})(this); |
e4190e9584d7635fb3b4627e9f3c300b5a5b852f | client/src/deviceTypes.js | client/src/deviceTypes.js | /**
* These are all the device types defined in Johnny-Five. These
* extend our Input objects (not elements)
*
* min - Minimum value for the device type
* max - Maximum value for the device type
* _methods - A list of deviceMethods names that apply to the device type
*/
var deviceTypes = {
Led: {
min: 0,
max: 255,
_methods: ['on', 'off'] //, 'toggle', 'brightness', 'pulse', 'fade', 'fadeIn', 'fadeOut', 'strobe', 'stop']
},
Servo: {
min: 0,
max: 180,
_methods: ['move'] //, 'center', 'sweep'
}
}
| /**
* These are all the device types defined in Johnny-Five. These
* extend our Input objects (not elements)
*
* min - Minimum value for the device type
* max - Maximum value for the device type
* _methods - A list of deviceMethods names that apply to the device type
*/
var deviceTypes = {
Led: {
min: 0,
max: 255,
_methods: ['on', 'off'] //, 'toggle', 'brightness', 'pulse', 'fade', 'fadeIn', 'fadeOut', 'strobe', 'stop']
},
Servo: {
min: 0,
max: 180,
tolerance: 1,
_lastUpdate: 0,
_methods: ['move'] //, 'center', 'sweep'
}
}
| Set default tolerans and lastupdate values | Set default tolerans and lastupdate values
| JavaScript | mit | dtex/NodebotUI,davatron5000/NodebotUI | ---
+++
@@ -15,6 +15,8 @@
Servo: {
min: 0,
max: 180,
+ tolerance: 1,
+ _lastUpdate: 0,
_methods: ['move'] //, 'center', 'sweep'
}
} |
65fe7f69a73270146fca9d21691a5393bb779adc | admin/server/api/list/legacyCreate.js | admin/server/api/list/legacyCreate.js | var keystone = require('../../../../');
module.exports = function (req, res) {
if (!keystone.security.csrf.validate(req)) {
return res.apiError(403, 'invalid csrf');
}
var item = new req.list.model();
item.getUpdateHandler(req).process(req.body, { flashErrors: false, logErrors: true }, function (err) {
if (err) {
if (err.name === 'ValidationErrors') {
return res.apiError(400, 'validation errors', err.errors);
} else {
return res.apiError(500, 'error', err);
}
}
res.json(req.list.getData(item));
});
};
| var keystone = require('../../../../');
module.exports = function (req, res) {
if (!keystone.security.csrf.validate(req)) {
return res.apiError(403, 'invalid csrf');
}
var item = new req.list.model();
item.getUpdateHandler(req).process(req.body, { flashErrors: false, logErrors: true }, function (err) {
if (err) {
if (err.name === 'ValidationError') {
return res.apiError(400, 'validation errors', err.errors);
} else {
return res.apiError(500, 'error', err);
}
}
res.json(req.list.getData(item));
});
};
| Fix validation errors not showing in the admin UI | Fix validation errors not showing in the admin UI
| JavaScript | mit | creynders/keystone,creynders/keystone | ---
+++
@@ -7,7 +7,7 @@
var item = new req.list.model();
item.getUpdateHandler(req).process(req.body, { flashErrors: false, logErrors: true }, function (err) {
if (err) {
- if (err.name === 'ValidationErrors') {
+ if (err.name === 'ValidationError') {
return res.apiError(400, 'validation errors', err.errors);
} else {
return res.apiError(500, 'error', err); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.