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 |
|---|---|---|---|---|---|---|---|---|---|---|
077242d046e3e755ff82ba4b29cce2477fd50bea | config/seneca-options.js | config/seneca-options.js | 'use strict';
var senecaOptions = {
transport: {
web: {
port: process.env.PORT || 8080
}
},
apiBaseUrl: process.env.API_BASE_URL || 'http://localhost:3000',
apiSecret: process.env.API_SECRET || ''
};
module.exports = senecaOptions;
| 'use strict';
var senecaOptions = {
transport: {
web: {
port: process.env.BADGES_SERVICE_PORT || 10305
}
},
apiBaseUrl: process.env.API_BASE_URL || 'http://localhost:8080',
apiSecret: process.env.API_SECRET || ''
};
module.exports = senecaOptions;
| Change ports and env variable names | Change ports and env variable names
| JavaScript | mit | CoderDojo/cp-badges-service,bmatthews68/cp-badges-service,CoderDojo/cp-badges-service,bmatthews68/cp-badges-service | ---
+++
@@ -3,10 +3,10 @@
var senecaOptions = {
transport: {
web: {
- port: process.env.PORT || 8080
+ port: process.env.BADGES_SERVICE_PORT || 10305
}
},
- apiBaseUrl: process.env.API_BASE_URL || 'http://localhost:3000',
+ apiBaseUrl: process.env.API_BASE_URL || 'http://localhost:8080',
apiSecret: process.env.API_SECRET || ''
};
|
1bc0febdf56a49d70f61eda1cc81f405a5ba7064 | server/theme/default/libraries/bootstrap/js/bootstrap-ckeditor-fix.js | server/theme/default/libraries/bootstrap/js/bootstrap-ckeditor-fix.js | // bootstrap-ckeditor-fix.js
// hack to fix ckeditor/bootstrap compatiability bug when ckeditor appears in a bootstrap modal dialog
//
// Include this file AFTER both jQuery and bootstrap are loaded.
$.fn.modal.Constructor.prototype.enforceFocus = function() {
modal_this = this
$(document).on('focusin.modal', function (e) {
if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length
&& !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select')
&& !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) {
modal_this.$element.focus()
}
})
}; | // bootstrap-ckeditor-fix.js
// hack to fix ckeditor/bootstrap compatiability bug when ckeditor appears in a bootstrap modal dialog
//
// Include this file AFTER both jQuery and bootstrap are loaded.
$.fn.modal.Constructor.prototype.enforceFocus = function() {
modal_this = this
$(document).on('focusin.modal', function (e) {
if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length
// add whatever conditions you need here:
&& !$(e.target.parentNode).hasClass('cke')) {
modal_this.$element.focus()
}
})
}; | Patch for CKEditor and IE11 | [cms] Patch for CKEditor and IE11 | JavaScript | agpl-3.0 | alexharrington/xibo-cms,ajiwo/xibo-cms,dasgarner/xibo-cms,gractor/xibo-cms,yashodhank/xibo-cms,jbirdkerr/xibo-cms,guruevi/xibo-cms,gractor/xibo-cms,yashodhank/xibo-cms,xibosignage/xibo-cms,PeterMis/xibo-cms,CourtneyJWhite/xibo-cms,alexharrington/xibo-cms,PeterMis/xibo-cms,CourtneyJWhite/xibo-cms,CourtneyJWhite/xibo-cms,omgapuppy/xibo-cms,taboure/xibo-cms,jbirdkerr/xibo-cms,omgapuppy/xibo-cms,gractor/xibo-cms,dasgarner/xibo-cms,ajiwo/xibo-cms,PeterMis/xibo-cms,alexharrington/xibo-cms,phongtnit/xibo-cms,dasgarner/xibo-cms,xibosignage/xibo-cms,phongtnit/xibo-cms,xibosignage/xibo-cms,alexharrington/xibo-cms,guruevi/xibo-cms,PeterMis/xibo-cms,taboure/xibo-cms,xibosignage/xibo-cms,guruevi/xibo-cms,omgapuppy/xibo-cms,alexhuang888/xibo-cms,PeterMis/xibo-cms,alexhuang888/xibo-cms,yashodhank/xibo-cms,phongtnit/xibo-cms,alexharrington/xibo-cms,taboure/xibo-cms,jbirdkerr/xibo-cms,dasgarner/xibo-cms,dasgarner/xibo-cms,xibosignage/xibo-cms,xibosignage/xibo-cms,dasgarner/xibo-cms,alexhuang888/xibo-cms,ajiwo/xibo-cms | ---
+++
@@ -7,8 +7,8 @@
modal_this = this
$(document).on('focusin.modal', function (e) {
if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length
- && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select')
- && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) {
+ // add whatever conditions you need here:
+ && !$(e.target.parentNode).hasClass('cke')) {
modal_this.$element.focus()
}
}) |
5cbd75f443a87c9a966ffe0320d8258c6691d4ba | blueprints/ember-cli-changelog/files/config/changelog.js | blueprints/ember-cli-changelog/files/config/changelog.js | // jshint node:true
// For details on each option run `ember help release`
module.exports = {
// ember style guide: https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md#commit-tagging
// angular style guide: https://github.com/angular/angular.js/blob/v1.4.8/CONTRIBUTING.md#commit
// jquery style guide: https://contribute.jquery.org/commits-and-pull-requests/#commit-guidelines
style: 'ember', // 'angular' 'jquery'
head: 'master',
base: '-last', // a branch or tag name, `-last` defaults to the version in package.json
hooks: {
/*
parser: function(commit) { return commit; }
filter: function(commit) { return true; },
groupSort: function(commits) { return { commits: commits }; },
format: function(commit) { return commit.title; },
*/
}
};
| // jshint node:true
// For details on each option run `ember help release`
module.exports = {
// ember style guide: https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md#commit-tagging
// angular style guide: https://github.com/angular/angular.js/blob/v1.4.8/CONTRIBUTING.md#commit
// jquery style guide: https://contribute.jquery.org/commits-and-pull-requests/#commit-guidelines
style: 'angular', // 'ember' 'jquery'
head: 'master',
base: '-last', // a branch or tag name, `-last` defaults to the version in package.json
hooks: {
/*
parser: function(commit) { return commit; }
filter: function(commit) { return true; },
groupSort: function(commits) { return { commits: commits }; },
format: function(commit) { return commit.title; },
*/
}
};
| Set angular as default in blueprint | Set angular as default in blueprint | JavaScript | mit | runspired/ember-cli-changelog,runspired/ember-cli-changelog | ---
+++
@@ -6,7 +6,7 @@
// ember style guide: https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md#commit-tagging
// angular style guide: https://github.com/angular/angular.js/blob/v1.4.8/CONTRIBUTING.md#commit
// jquery style guide: https://contribute.jquery.org/commits-and-pull-requests/#commit-guidelines
- style: 'ember', // 'angular' 'jquery'
+ style: 'angular', // 'ember' 'jquery'
head: 'master',
base: '-last', // a branch or tag name, `-last` defaults to the version in package.json |
d72326fe7646a6c44d08637141f7df5f7d293fb7 | src/helpers/seeder.js | src/helpers/seeder.js | #!/usr/bin/env node
const storage = require('../storage')
const fixtures = require('./fixtures')
const recipes = fixtures.createRecipes(10)
function save (recipe) {
return storage.put(recipe.id, recipe)
}
storage.connect()
.then(() => {
return Promise.all(recipes.map(recipe => save(recipe)))
})
.then(() => {
console.log('Database was successfuly seeded.\n')
})
.catch(error => {
throw error
})
| #!/usr/bin/env node
const storage = require('../storage')
const fixtures = require('./fixtures')
const recipes = fixtures.createRecipes(10)
function save (db, recipe) {
return storage.put(db, recipe.id, recipe)
}
storage.connect(process.env.NODE_ENV)
.then((db) => {
return Promise.all(recipes.map(recipe => save(db, recipe)))
})
.then(() => {
console.log('Database was successfuly seeded.\n')
})
.catch(error => {
throw error
})
| Fix issues with the seed script | Fix issues with the seed script
| JavaScript | mit | ruiquelhas/electron-recipes,ruiquelhas/electron-recipes | ---
+++
@@ -5,13 +5,13 @@
const recipes = fixtures.createRecipes(10)
-function save (recipe) {
- return storage.put(recipe.id, recipe)
+function save (db, recipe) {
+ return storage.put(db, recipe.id, recipe)
}
-storage.connect()
- .then(() => {
- return Promise.all(recipes.map(recipe => save(recipe)))
+storage.connect(process.env.NODE_ENV)
+ .then((db) => {
+ return Promise.all(recipes.map(recipe => save(db, recipe)))
})
.then(() => {
console.log('Database was successfuly seeded.\n') |
be6bc61e0be6226af1c1b6fbbee0ffbfee38248c | src/services/config/config.service.js | src/services/config/config.service.js | 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
overlay: {line: true},
scale: {useRawDomain: false}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
},
overlay: {line: true},
scale: {useRawDomain: false}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
| 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
overlay: {line: true},
scale: {useRawDomain: false}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
},
overlay: {line: true},
scale: {useRawDomain: true}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
| Bring back useRawDomain for Voyager2 | Bring back useRawDomain for Voyager2
| JavaScript | bsd-3-clause | uwdata/vega-lite-ui,vega/vega-lite-ui,uwdata/vega-lite-ui,uwdata/vega-lite-ui,vega/vega-lite-ui,vega/vega-lite-ui | ---
+++
@@ -43,7 +43,7 @@
}
},
overlay: {line: true},
- scale: {useRawDomain: false}
+ scale: {useRawDomain: true}
};
};
|
532fb8e2150c70c627d57f9f72f8232606976a4a | app/javascript/flavours/glitch/reducers/domain_lists.js | app/javascript/flavours/glitch/reducers/domain_lists.js | import {
DOMAIN_BLOCKS_FETCH_SUCCESS,
DOMAIN_BLOCKS_EXPAND_SUCCESS,
DOMAIN_UNBLOCK_SUCCESS,
} from '../actions/domain_blocks';
import { Map as ImmutableMap, OrderedSet as ImmutableOrderedSet } from 'immutable';
const initialState = ImmutableMap({
blocks: ImmutableMap(),
});
export default function domainLists(state = initialState, action) {
switch(action.type) {
case DOMAIN_BLOCKS_FETCH_SUCCESS:
return state.setIn(['blocks', 'items'], ImmutableOrderedSet(action.domains)).setIn(['blocks', 'next'], action.next);
case DOMAIN_BLOCKS_EXPAND_SUCCESS:
return state.updateIn(['blocks', 'items'], set => set.union(action.domains)).setIn(['blocks', 'next'], action.next);
case DOMAIN_UNBLOCK_SUCCESS:
return state.updateIn(['blocks', 'items'], set => set.delete(action.domain));
default:
return state;
}
};
| import {
DOMAIN_BLOCKS_FETCH_SUCCESS,
DOMAIN_BLOCKS_EXPAND_SUCCESS,
DOMAIN_UNBLOCK_SUCCESS,
} from '../actions/domain_blocks';
import { Map as ImmutableMap, OrderedSet as ImmutableOrderedSet } from 'immutable';
const initialState = ImmutableMap({
blocks: ImmutableMap({
items: ImmutableOrderedSet(),
}),
});
export default function domainLists(state = initialState, action) {
switch(action.type) {
case DOMAIN_BLOCKS_FETCH_SUCCESS:
return state.setIn(['blocks', 'items'], ImmutableOrderedSet(action.domains)).setIn(['blocks', 'next'], action.next);
case DOMAIN_BLOCKS_EXPAND_SUCCESS:
return state.updateIn(['blocks', 'items'], set => set.union(action.domains)).setIn(['blocks', 'next'], action.next);
case DOMAIN_UNBLOCK_SUCCESS:
return state.updateIn(['blocks', 'items'], set => set.delete(action.domain));
default:
return state;
}
};
| Fix error when unmuting a domain without listing muted domains first | Fix error when unmuting a domain without listing muted domains first
| JavaScript | agpl-3.0 | Kirishima21/mastodon,Kirishima21/mastodon,glitch-soc/mastodon,im-in-space/mastodon,glitch-soc/mastodon,Kirishima21/mastodon,glitch-soc/mastodon,Kirishima21/mastodon,im-in-space/mastodon,im-in-space/mastodon,im-in-space/mastodon,glitch-soc/mastodon | ---
+++
@@ -6,7 +6,9 @@
import { Map as ImmutableMap, OrderedSet as ImmutableOrderedSet } from 'immutable';
const initialState = ImmutableMap({
- blocks: ImmutableMap(),
+ blocks: ImmutableMap({
+ items: ImmutableOrderedSet(),
+ }),
});
export default function domainLists(state = initialState, action) { |
08eaac64daa1b7bb5137261967cd7c655b7dbc1f | jquery.sortBy-0.1.js | jquery.sortBy-0.1.js | /* uses schwartzian transform to sort the selected elements in-place */
(function($) {
$.fn.sortBy = function(sortfn) {
var values = [],
$self = this;
this.children().each(function(i,o) {
values.push([ $(o), sortfn($(o)) ]);
});
values.sort(function(a,b) {
return a[1] > b[1] ? 1
: a[1] == b[1] ? 0
: -1;
});
$.each(values, function(_,o) {
$self.append(o[0]);
});
};
})(jQuery);
| /* uses schwartzian transform to sort the selected elements in-place */
(function($) {
$.fn.sortBy = function(sortfn) {
var values = [],
$self = this;
values = this.children().map(function(o) {
return [ $(o), sortfn($(o)) ];
});
$.sort(values, function(a,b) {
return a[1] > b[1] ? 1
: a[1] == b[1] ? 0
: -1;
});
$.each(values, function(_,o) {
$self.append(o[0]);
});
};
})(jQuery);
| Use jQuery helpers for simplification and compat | Use jQuery helpers for simplification and compat
| JavaScript | bsd-2-clause | propcom/jquery-sortBy | ---
+++
@@ -4,11 +4,11 @@
var values = [],
$self = this;
- this.children().each(function(i,o) {
- values.push([ $(o), sortfn($(o)) ]);
+ values = this.children().map(function(o) {
+ return [ $(o), sortfn($(o)) ];
});
- values.sort(function(a,b) {
+ $.sort(values, function(a,b) {
return a[1] > b[1] ? 1
: a[1] == b[1] ? 0
: -1; |
69a349f1865e59c5751e6ec685e41b57bb1b1f9a | js-example/server.js | js-example/server.js | var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(3011, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:3000/');
});
| var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(3000, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:3000/');
});
| Update exampe with new react-filter-box version | Update exampe with new react-filter-box version
| JavaScript | mit | nhabuiduc/react-filter-box,nhabuiduc/react-filter-box,nhabuiduc/react-filter-box | ---
+++
@@ -6,7 +6,7 @@
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
-}).listen(3011, 'localhost', function (err, result) {
+}).listen(3000, 'localhost', function (err, result) {
if (err) {
return console.log(err);
} |
9494ce3faf614483079b6bfe85ae1f48e8373e22 | data/clothing.js | data/clothing.js | const request = require('request');
/**
* Function checks that a string given is string with some number of
* characters
*
* @params {string} str string value to check for validity
* @return true if the string is valid; otherwise, return false
*/
function isValidString(str) {
if ((str === undefined) || (typeof(str) !== "string") || (str.length <= 0)) {
return false;
}
return true;
}
let user = exports = module.exports = {
retrieveClothingInfo: (clothing_url) => {
return new Promise((accept, reject) => {
if (!isValidString(clothing_url)) {
return reject("No clothing_url provided");
}
const options = {
headers: {'user-agent': 'node.js'}
}
request(clothing_url, options, function (error, response, body) {
if (error || !response || response.statusCode !== 200) {
console.log(body);
return reject("Invalid clothing_url");
}
const price = body.match(/\$([\d.]+)/);
const image = body.match(/<meta[\S ]+og:image[\S ]+content="(\S+)"/);
accept({
price: price && parseFloat(price[1]),
image: image && image[1],
});
});
});
}
} | const request = require('request');
/**
* Function checks that a string given is string with some number of
* characters
*
* @params {string} str string value to check for validity
* @return true if the string is valid; otherwise, return false
*/
function isValidString(str) {
if ((str === undefined) || (typeof(str) !== "string") || (str.length <= 0)) {
return false;
}
return true;
}
let clothing = exports = module.exports = {
retrieveClothingInfo: (clothing_url) => {
return new Promise((accept, reject) => {
if (!isValidString(clothing_url)) {
return reject("No clothing_url provided");
}
const options = {
headers: {'user-agent': 'node.js'}
}
request(clothing_url, options, function (error, response, body) {
if (error || !response || response.statusCode !== 200) {
console.log(body);
return reject("Invalid clothing_url");
}
const price = body.match(/\$([\d.]+)/);
const image = body.match(/<meta[\S ]+og:image[\S ]+content="(\S+)"/);
accept({
price: price && parseFloat(price[1]),
image: image && image[1],
});
});
});
}
}
| Refactor to better define data helper | Refactor to better define data helper
| JavaScript | mit | tsangjustin/CS546-Product_Forum,tsangjustin/CS546-Product_Forum | ---
+++
@@ -14,7 +14,7 @@
return true;
}
-let user = exports = module.exports = {
+let clothing = exports = module.exports = {
retrieveClothingInfo: (clothing_url) => {
return new Promise((accept, reject) => {
if (!isValidString(clothing_url)) {
@@ -30,7 +30,7 @@
}
const price = body.match(/\$([\d.]+)/);
const image = body.match(/<meta[\S ]+og:image[\S ]+content="(\S+)"/);
-
+
accept({
price: price && parseFloat(price[1]),
image: image && image[1], |
989a705f204a2a6078475493650d30e569cdaf0d | views/js/helpers/login/loginsubmitter.js | views/js/helpers/login/loginsubmitter.js | /**
* Created by Omnius on 6/27/16.
*/
const submitForm = () => {
// TODO: Supposedly needs sanitation using ESAPI.encoder().encodeForJavascript() or some other sanitation
// mechanism on inputUsername and inputPassword
const username = $('#inputUsername').val();
const password = $('#inputPassword').val();
$.ajax({
type: 'GET',
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Basic ' + btoa(username + ':' + password));
},
url: '/auth/basic',
processData: false,
success: function(data, textStatus, jQxhr){
$('#formLogin').attr('action', '/user/welcome');
$('#formLogin').submit();
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.status === 401) {
$('#formUnauthorized').removeClass('hidden');
}
}
});
};
| /**
* Created by Omnius on 6/27/16.
*/
const submitForm = () => {
// TODO: Supposedly needs sanitation using ESAPI.encoder().encodeForJavascript() or some other sanitation
// mechanism on inputUsername and inputPassword
const username = $('#inputUsername').val();
const password = $('#inputPassword').val();
$.ajax({
type: 'GET',
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Basic ' + btoa(username + ':' + password));
},
url: '/auth/basic',
processData: false,
success: function(data, textStatus, jQxhr){
$('#formLogin').attr('action', '/user/welcome');
$('#formLogin').submit();
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.status === 401) {
$('#alertUnauthorized').removeClass('hidden');
}
}
});
};
| Fix error in element name for showing unauthorized alert using jQuery | Fix error in element name for showing unauthorized alert using jQuery
| JavaScript | mit | identityclash/hapi-login-test,identityclash/hapi-login-test | ---
+++
@@ -21,7 +21,7 @@
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.status === 401) {
- $('#formUnauthorized').removeClass('hidden');
+ $('#alertUnauthorized').removeClass('hidden');
}
}
}); |
0b36c6109e9a96403d6c779c56c1b1482df0a48f | app/assets/javascripts/vue/fluent_log.js | app/assets/javascripts/vue/fluent_log.js | (function(){
"use strict";
$(function(){
if($('#fluent-log').length === 0) return;
new Vue({
el: "#fluent-log",
paramAttributes: ["logUrl"],
data: {
"autoFetch": false,
"logs": [],
"limit": 30
},
created: function(){
this.fetchLogs();
var self = this;
var timer;
this.$watch("autoFetch", function(newValue){
if(newValue === true) {
timer = setInterval(function(){
self.fetchLogs();
var $log = $(".log", self.$el);
$log.scrollTop($log[0].scrollHeight);
}, 1000);
} else {
clearInterval(timer);
}
});
},
methods: {
fetchLogs: function() {
var self = this;
new Promise(function(resolve, reject) {
$.getJSON(self.logUrl + "?limit=" + self.limit, resolve).fail(reject);
}).then(function(logs){
self.logs = logs;
});
},
}
});
});
})();
| (function(){
"use strict";
$(function(){
if($('#fluent-log').length === 0) return;
new Vue({
el: "#fluent-log",
paramAttributes: ["logUrl"],
data: {
"autoFetch": false,
"logs": [],
"limit": 30,
"processing": false
},
created: function(){
this.fetchLogs();
var self = this;
var timer;
this.$watch("autoFetch", function(newValue){
if(newValue === true) {
timer = setInterval(function(){
self.fetchLogs();
var $log = $(".log", self.$el);
$log.scrollTop($log[0].scrollHeight);
}, 1000);
} else {
clearInterval(timer);
}
});
},
methods: {
fetchLogs: function() {
if(this.processing) return;
this.processing = true;
var self = this;
new Promise(function(resolve, reject) {
$.getJSON(self.logUrl + "?limit=" + self.limit, resolve).fail(reject);
}).then(function(logs){
self.logs = logs;
setTimeout(function(){
self.processing = false;
}, 256); // delay to reduce flicking loading icon
});
},
}
});
});
})();
| Add reaction while fetching logs | Add reaction while fetching logs
| JavaScript | apache-2.0 | fluent/fluentd-ui,mt0803/fluentd-ui,fluent/fluentd-ui,mt0803/fluentd-ui,mt0803/fluentd-ui,fluent/fluentd-ui | ---
+++
@@ -10,7 +10,8 @@
data: {
"autoFetch": false,
"logs": [],
- "limit": 30
+ "limit": 30,
+ "processing": false
},
created: function(){
@@ -33,11 +34,16 @@
methods: {
fetchLogs: function() {
+ if(this.processing) return;
+ this.processing = true;
var self = this;
new Promise(function(resolve, reject) {
$.getJSON(self.logUrl + "?limit=" + self.limit, resolve).fail(reject);
}).then(function(logs){
self.logs = logs;
+ setTimeout(function(){
+ self.processing = false;
+ }, 256); // delay to reduce flicking loading icon
});
},
} |
54b9597c9a01ed7904d0b9ed12cb46cbe211e7b8 | packages/@sanity/desk-tool/src/components/Diff.js | packages/@sanity/desk-tool/src/components/Diff.js | import PropTypes from 'prop-types'
import React from 'react'
import {diffJson} from 'diff'
import styles from './styles/Diff.css'
function getDiffStatKey(part) {
if (part.added) {
return 'added'
}
if (part.removed) {
return 'removed'
}
return 'neutral'
}
export default class Diff extends React.PureComponent {
static defaultProps = {
inputA: '',
inputB: ''
}
static propTypes = {
inputA: PropTypes.object,
inputB: PropTypes.object
}
render() {
const diff = diffJson(this.props.inputA, this.props.inputB)
return (
<pre>
{diff.map((part, index) => (
<span key={index} className={styles[getDiffStatKey(part)]}>{part.value}</span>
))}
</pre>
)
}
}
| /**
*
*
*
*
*
*
*
* HEADSUP: This is not in use, but keep for later reference
*
*
*
*
*
*
*
*/
import PropTypes from 'prop-types'
import React from 'react'
import {diffJson} from 'diff'
import styles from './styles/Diff.css'
function getDiffStatKey(part) {
if (part.added) {
return 'added'
}
if (part.removed) {
return 'removed'
}
return 'neutral'
}
export default class Diff extends React.PureComponent {
static defaultProps = {
inputA: '',
inputB: ''
}
static propTypes = {
inputA: PropTypes.object,
inputB: PropTypes.object
}
render() {
const diff = diffJson(this.props.inputA, this.props.inputB)
return (
<pre>
{diff.map((part, index) => (
<span key={index} className={styles[getDiffStatKey(part)]}>{part.value}</span>
))}
</pre>
)
}
}
| Add a note about keeping unused component for later reference | [desk-tool] Add a note about keeping unused component for later reference
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -1,3 +1,20 @@
+/**
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ * HEADSUP: This is not in use, but keep for later reference
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
import PropTypes from 'prop-types'
import React from 'react'
import {diffJson} from 'diff' |
f267bbc9e34282354997720f86f323b76ab47b1d | test/manual-tests/get-data-sources.js | test/manual-tests/get-data-sources.js | var BridgeDb = require('../index.js');
var bridgeDb1 = BridgeDb({
apiUrlStub: 'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb.php',
dataSourcesUrl:
'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb-datasources.php'
});
//*
bridgeDb1.dataSource.getAll()
.each(function(dataSource) {
console.log('Database metadata');
console.log(JSON.stringify(dataSource, null, '\t'));
});
//*/
//*
var bridgeDb2 = BridgeDb({
apiUrlStub: 'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb.php',
dataSourcesUrl:
'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb-datasources.php'
});
//*/
//*
bridgeDb2.dataSource.getAll()
.each(function(dataSource) {
console.log('Database metadata');
console.log(JSON.stringify(dataSource, null, '\t'));
});
//*/
//*
bridgeDb2.dataSource.getAll()
.each(function(dataSource) {
console.log('Database metadata');
console.log(JSON.stringify(dataSource, null, '\t'));
});
//*/
| var BridgeDb = require('../../index.js');
var bridgeDb1 = BridgeDb({
apiUrlStub: 'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb.php',
dataSourcesUrl:
'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb-datasources.php'
});
//*
bridgeDb1.dataSource.getAll()
.each(function(dataSource) {
console.log('Database metadata');
console.log(JSON.stringify(dataSource, null, '\t'));
});
//*/
//*
var bridgeDb2 = BridgeDb({
apiUrlStub: 'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb.php',
dataSourcesUrl:
'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb-datasources.php'
});
//*/
//*
bridgeDb2.dataSource.getAll()
.each(function(dataSource) {
console.log('Database metadata');
console.log(JSON.stringify(dataSource, null, '\t'));
});
//*/
//*
bridgeDb2.dataSource.getAll()
.each(function(dataSource) {
console.log('Database metadata');
console.log(JSON.stringify(dataSource, null, '\t'));
});
//*/
| Update location of bridgedb index file. | Update location of bridgedb index file.
| JavaScript | apache-2.0 | egonw/bridgedbjs | ---
+++
@@ -1,4 +1,4 @@
-var BridgeDb = require('../index.js');
+var BridgeDb = require('../../index.js');
var bridgeDb1 = BridgeDb({
apiUrlStub: 'http://pointer.ucsf.edu/d3/r/data-sources/bridgedb.php', |
9956f54a1e34d66f1d2af3a89d245b36681b4d8f | packages/@sanity/util/src/getConfig.js | packages/@sanity/util/src/getConfig.js | import path from 'path'
import get from 'lodash/get'
import merge from 'lodash/merge'
import {loadJsonSync} from './safeJson'
const defaults = {
server: {
staticPath: './static',
port: 3910,
hostname: 'localhost'
}
}
const configContainer = values => ({
get: (dotPath, defaultValue) =>
get(values, dotPath, defaultValue)
})
const getConfig = rootDir => {
const localConfig = rootDir && loadJsonSync(path.join(rootDir, 'sanity.json'))
const config = localConfig ? merge({}, defaults, localConfig) : defaults
return configContainer(config)
}
export default getConfig
| import path from 'path'
import get from 'lodash/get'
import merge from 'lodash/merge'
import {loadJsonSync} from './safeJson'
const defaults = {
server: {
staticPath: './static',
port: 3333,
hostname: 'localhost'
}
}
const configContainer = values => ({
get: (dotPath, defaultValue) =>
get(values, dotPath, defaultValue)
})
const getConfig = rootDir => {
const localConfig = rootDir && loadJsonSync(path.join(rootDir, 'sanity.json'))
const config = localConfig ? merge({}, defaults, localConfig) : defaults
return configContainer(config)
}
export default getConfig
| Change default port to 3333 | Change default port to 3333
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -6,7 +6,7 @@
const defaults = {
server: {
staticPath: './static',
- port: 3910,
+ port: 3333,
hostname: 'localhost'
}
} |
85641e0db06224488dab96f69eed31f0b2a0d4ba | tests/integration/config-ci.js | tests/integration/config-ci.js | // this file is for use in CircleCI continuous integration environment
var browserName = ['chrome', 'firefox', 'internet explorer', 'android'][process.env.CIRCLE_NODE_INDEX];
module.exports = {
seleniumServerURL: {
hostname: 'ondemand.saucelabs.com',
port: 80
},
driverCapabilities: {
'tunnel-identifier': 'circle-' + process.env.CIRCLE_BUILD_NUM + '-' + process.env.CIRCLE_NODE_INDEX,
browserName: browserName
},
tags: [ 'circle-ci', '#' + process.env.CIRCLE_BUILD_NUM ],
views: [ 'Verbose', 'SauceLabs' ],
quit: 'always', // avoid wasting 90 seconds on SauceLabs
bail: true,
build: 'CircleCI#' + process.env.CIRCLE_BUILD_NUM
}
| // this file is for use in CircleCI continuous integration environment
var capabilities = [
{browserName: 'chrome'},
{browserName: 'firefox'},
{browserName: 'internet explorer'},
{
deviceName: 'Samsung Galaxy S6 GoogleAPI Emulator',
browserName: 'Chrome',
platformName: 'Android',
platformVersion: '7.0'
}
][process.env.CIRCLE_NODE_INDEX];
module.exports = {
seleniumServerURL: {
hostname: 'ondemand.saucelabs.com',
port: 80
},
driverCapabilities: Object.assign({},
capabilities,
{'tunnel-identifier': 'circle-' + process.env.CIRCLE_BUILD_NUM + '-' + process.env.CIRCLE_NODE_INDEX}
),
tags: [ 'circle-ci', '#' + process.env.CIRCLE_BUILD_NUM ],
views: [ 'Verbose', 'SauceLabs' ],
quit: 'always', // avoid wasting 90 seconds on SauceLabs
bail: true,
build: 'CircleCI#' + process.env.CIRCLE_BUILD_NUM
}
| Use a more recent Android for integration tests | Use a more recent Android for integration tests
| JavaScript | agpl-3.0 | openfisca/legislation-explorer | ---
+++
@@ -1,16 +1,26 @@
// this file is for use in CircleCI continuous integration environment
-var browserName = ['chrome', 'firefox', 'internet explorer', 'android'][process.env.CIRCLE_NODE_INDEX];
+var capabilities = [
+ {browserName: 'chrome'},
+ {browserName: 'firefox'},
+ {browserName: 'internet explorer'},
+ {
+ deviceName: 'Samsung Galaxy S6 GoogleAPI Emulator',
+ browserName: 'Chrome',
+ platformName: 'Android',
+ platformVersion: '7.0'
+ }
+ ][process.env.CIRCLE_NODE_INDEX];
module.exports = {
seleniumServerURL: {
hostname: 'ondemand.saucelabs.com',
port: 80
},
- driverCapabilities: {
- 'tunnel-identifier': 'circle-' + process.env.CIRCLE_BUILD_NUM + '-' + process.env.CIRCLE_NODE_INDEX,
- browserName: browserName
- },
+ driverCapabilities: Object.assign({},
+ capabilities,
+ {'tunnel-identifier': 'circle-' + process.env.CIRCLE_BUILD_NUM + '-' + process.env.CIRCLE_NODE_INDEX}
+ ),
tags: [ 'circle-ci', '#' + process.env.CIRCLE_BUILD_NUM ],
views: [ 'Verbose', 'SauceLabs' ],
quit: 'always', // avoid wasting 90 seconds on SauceLabs |
2ab41ec1f71f405f7e718db2f11acbc010862b0d | packages/babel/src/transformation/transformers/internal/block-hoist.js | packages/babel/src/transformation/transformers/internal/block-hoist.js | import sortBy from "lodash/collection/sortBy";
export var metadata = {
group: "builtin-trailing"
};
/**
* [Please add a description.]
*
* Priority:
*
* - 0 We want this to be at the **very** bottom
* - 1 Default node position
* - 2 Priority over normal nodes
* - 3 We want this to be at the **very** top
*/
export var visitor = {
/**
* [Please add a description.]
*/
Block: {
exit(node) {
var hasChange = false;
for (var i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) hasChange = true;
}
if (!hasChange) return;
node.body = sortBy(node.body, function(bodyNode){
var priority = bodyNode && bodyNode._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;
// Higher priorities should move toward the top.
return -1 * priority;
});
}
}
};
| import sortBy from "lodash/collection/sortBy";
export var metadata = {
group: "builtin-trailing"
};
/**
* [Please add a description.]
*
* Priority:
*
* - 0 We want this to be at the **very** bottom
* - 1 Default node position
* - 2 Priority over normal nodes
* - 3 We want this to be at the **very** top
*/
export var visitor = {
/**
* [Please add a description.]
*/
Block: {
exit(node) {
var hasChange = false;
for (var i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) {
hasChange = true;
break;
}
}
if (!hasChange) return;
node.body = sortBy(node.body, function(bodyNode){
var priority = bodyNode && bodyNode._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;
// Higher priorities should move toward the top.
return -1 * priority;
});
}
}
};
| Break loop as soon as change detected. | Break loop as soon as change detected.
| JavaScript | mit | mcanthony/babel,aalluri-navaratan/babel,iamstarkov/babel,abdulsam/babel,thorikawa/babel,existentialism/babel,greyhwndz/babel,spicyj/babel,zorosteven/babel,sethcall/babel,rn0/babel,hzoo/babel,rn0/babel,codenamejason/babel,andrewwilkins/babel,nmn/babel,moander/babel,plemarquand/babel,guybedford/babel,VukDukic/babel,VukDukic/babel,kassens/babel,vjeux/babel,moander/babel,jchip/babel,KualiCo/babel,dustyjewett/babel-plugin-transform-es2015-modules-commonjs-ember,vipulnsward/babel,garyjN7/babel,hubli/babel,drieks/babel,VukDukic/babel,greyhwndz/babel,SaltTeam/babel,lastjune/babel,vjeux/babel,victorenator/babel,sethcall/babel,tikotzky/babel,jeffmo/babel,prathamesh-sonpatki/babel,jnuine/babel,ezbreaks/babel,cartermarino/babel,mayflower/babel,johnamiahford/babel,shuhei/babel,ramoslin02/babel,inikulin/babel,drieks/babel,james4388/babel,prathamesh-sonpatki/babel,prathamesh-sonpatki/babel,ming-codes/babel,cesarandreu/6to5,iamstarkov/babel,maurobringolf/babel,mgcrea/babel,mrtrizer/babel,chicoxyzzy/babel,PolymerLabs/babel,manukall/babel,macressler/babel,ming-codes/babel,DmitrySoshnikov/babel,ramoslin02/babel,zenparsing/babel,steveluscher/babel,KunGha/babel,e-jigsaw/babel,victorenator/babel,kaicataldo/babel,1yvT0s/babel,hzoo/babel,shuhei/babel,michaelficarra/babel,grasuxxxl/babel,fabiomcosta/babel,Victorystick/babel,mayflower/babel,chengky/babel,SaltTeam/babel,shuhei/babel,jmptrader/babel,guybedford/babel,kellyselden/babel,mgcrea/babel,Victorystick/babel,vhf/babel,cgvarela/babel,pingjiang/babel,mrapogee/babel,thorikawa/babel,kellyselden/babel,ameyms/babel,andrejkn/babel,sejoker/babel,jridgewell/babel,plemarquand/babel,CrocoDillon/babel,kpdecker/babel,douglasduteil/babel,Victorystick/babel,iamchenxin/babel,sejoker/babel,jridgewell/babel,pingjiang/babel,kaicataldo/babel,claudiopro/babel,cgvarela/babel,forivall/babel,existentialism/babel,zenlambda/babel,PolymerLabs/babel,zenlambda/babel,rn0/babel,douglasduteil/babel,plemarquand/babel,codenamejason/babel,vipulnsward/babel,james4388/babel,michaelficarra/babel,pingjiang/babel,dekelcohen/babel,CrabDude/babel,jridgewell/babel,zorosteven/babel,bcoe/babel,samwgoldman/babel,aalluri-navaratan/babel,gxr1020/babel,jeffmo/babel,Dignifiedquire/babel,inikulin/babel,antn/babel,michaelficarra/babel,ccschneidr/babel,douglasduteil/babel,Industrial/babel,abdulsam/babel,johnamiahford/babel,hulkish/babel,cesarandreu/6to5,hubli/babel,ajcrites/babybel,ianmstew/babel,jnuine/babel,gxr1020/babel,spicyj/babel,kassens/babel,Mark-Simulacrum/babel,ezbreaks/babel,rmacklin/babel,1yvT0s/babel,steveluscher/babel,lastjune/babel,bcoe/babel,kedromelon/babel,forivall/babel,kaicataldo/babel,ccschneidr/babel,inikulin/babel,sairion/babel,beni55/babel,DmitrySoshnikov/babel,chicoxyzzy/babel,benjamn/babel,sethcall/babel,PolymerLabs/babel,zenparsing/babel,cesarandreu/6to5,krasimir/babel,jackmew/babel,macressler/babel,antn/babel,sairion/babel,jmptrader/babel,ErikBaath/babel,koistya/babel,framewr/babel,hulkish/babel,kellyselden/babel,AgentME/babel,jackmew/babel,sejoker/babel,sairion/babel,Industrial/babel,jridgewell/babel,zjmiller/babel,zorosteven/babel,claudiopro/babel,Dignifiedquire/babel,jnuine/babel,rmacklin/babel,jhen0409/babel,vadzim/babel,mrapogee/babel,benjamn/babel,macressler/babel,1yvT0s/babel,moander/babel,cartermarino/babel,steveluscher/babel,ysmood/babel,ywo/babel,koistya/babel,babel/babel,SaltTeam/babel,claudiopro/babel,chengky/babel,jmptrader/babel,ianmstew/babel,iamchenxin/babel,maurobringolf/babel,manukall/babel,e-jigsaw/babel,Skillupco/babel,framewr/babel,Skillupco/babel,STRML/babel,ysmood/babel,cgvarela/babel,abdulsam/babel,ramoslin02/babel,grasuxxxl/babel,mgcrea/babel,andrejkn/babel,garyjN7/babel,Skillupco/babel,kaicataldo/babel,kedromelon/babel,dekelcohen/babel,vipulnsward/babel,vjeux/babel,fabiomcosta/babel,hzoo/babel,ywo/babel,hubli/babel,ameyms/babel,hulkish/babel,babel/babel,jackmew/babel,guybedford/babel,ezbreaks/babel,vadzim/babel,codenamejason/babel,zjmiller/babel,koistya/babel,cartermarino/babel,maurobringolf/babel,thorikawa/babel,jchip/babel,victorenator/babel,forivall/babel,ErikBaath/babel,mayflower/babel,drieks/babel,beni55/babel,ajcrites/babybel,hulkish/babel,ErikBaath/babel,hzoo/babel,Dignifiedquire/babel,lxe/babel,chengky/babel,ajcrites/babybel,nmn/babel,tikotzky/babel,mcanthony/babel,chicoxyzzy/babel,AgentME/babel,STRML/babel,lxe/babel,johnamiahford/babel,babel/babel,framewr/babel,babel/babel,aalluri-navaratan/babel,e-jigsaw/babel,chicoxyzzy/babel,existentialism/babel,lastjune/babel,ysmood/babel,mcanthony/babel,mrtrizer/babel,KunGha/babel,iamchenxin/babel,beni55/babel,ianmstew/babel,Mark-Simulacrum/babel,spicyj/babel,gxr1020/babel,jhen0409/babel,Mark-Simulacrum/babel,james4388/babel,andrewwilkins/babel,kpdecker/babel,andrejkn/babel,zenlambda/babel,KualiCo/babel,samwgoldman/babel,samwgoldman/babel,andrewwilkins/babel,CrabDude/babel,mrapogee/babel,manukall/babel,nmn/babel,zertosh/babel,jeffmo/babel,greyhwndz/babel,kedromelon/babel,CrocoDillon/babel,zertosh/babel,vhf/babel,Skillupco/babel,ming-codes/babel,kellyselden/babel,ywo/babel,grasuxxxl/babel,CrabDude/babel,krasimir/babel,KualiCo/babel | ---
+++
@@ -26,7 +26,10 @@
var hasChange = false;
for (var i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i];
- if (bodyNode && bodyNode._blockHoist != null) hasChange = true;
+ if (bodyNode && bodyNode._blockHoist != null) {
+ hasChange = true;
+ break;
+ }
}
if (!hasChange) return;
|
29bdb0a226c76279193033bf2d0e777381d2a870 | tests/test.config.circle-ci.js | tests/test.config.circle-ci.js | module.exports = {
store_url: 'http://localhost:8080',
account_user: 'test',
account_password: 'testing',
account_name: 'tester',
container_name: 'test_container',
object_name: 'test_object',
segment_container_name: 'segment_test_container',
segment_object_name: 'segment_test_object',
dlo_container_name: 'dlo_test_container',
dlo_object_name: 'dlo_test_object',
dlo_prefix: 'dlo_prefix',
slo_container_name: 'slo_test_container',
slo_object_name: 'slo_test_object'
}; | module.exports = {
store_url: 'http://localhost:8080',
account_user: 'test:tester',
account_password: 'testing',
account_name: 'AUTH_test',
container_name: 'test_container',
object_name: 'test_object',
segment_container_name: 'segment_test_container',
segment_object_name: 'segment_test_object',
dlo_container_name: 'dlo_test_container',
dlo_object_name: 'dlo_test_object',
dlo_prefix: 'dlo_prefix',
slo_container_name: 'slo_test_container',
slo_object_name: 'slo_test_object'
}; | Fix circleci test config file | Fix circleci test config file
| JavaScript | mit | Tezirg/os2 | ---
+++
@@ -1,8 +1,8 @@
module.exports = {
store_url: 'http://localhost:8080',
- account_user: 'test',
+ account_user: 'test:tester',
account_password: 'testing',
- account_name: 'tester',
+ account_name: 'AUTH_test',
container_name: 'test_container',
object_name: 'test_object',
segment_container_name: 'segment_test_container', |
94558f5dcf5ce15b7b1964dd36e1a7fa26c730fd | packages/purgecss-webpack-plugin/rollup.config.js | packages/purgecss-webpack-plugin/rollup.config.js | import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
export default {
entry: './src/index.js',
targets: [
{
dest: './lib/purgecss-webpack-plugin.es.js',
format: 'es'
},
{
dest: './lib/purgecss-webpack-plugin.js',
format: 'cjs'
}
],
plugins: [resolve(), commonjs(), babel()],
external: ['purgecss', 'webpack-sources']
}
| import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
export default {
entry: './src/index.js',
targets: [
{
dest: './lib/purgecss-webpack-plugin.es.js',
format: 'es'
},
{
dest: './lib/purgecss-webpack-plugin.js',
format: 'cjs'
}
],
plugins: [resolve(), commonjs(), babel()],
external: ['purgecss', 'webpack-sources', 'fs', 'path']
}
| Add fs & path as external | Add fs & path as external
| JavaScript | mit | FullHuman/purgecss,FullHuman/purgecss,FullHuman/purgecss,FullHuman/purgecss | ---
+++
@@ -15,5 +15,5 @@
}
],
plugins: [resolve(), commonjs(), babel()],
- external: ['purgecss', 'webpack-sources']
+ external: ['purgecss', 'webpack-sources', 'fs', 'path']
} |
2343d77cd75492c4b1bda09b4c87d406a8e3a87d | frontend/app/routes/visualize/graph.js | frontend/app/routes/visualize/graph.js | import { inject as service } from '@ember/service';
import fetch from 'fetch';
import Route from '@ember/routing/route';
import ResetScrollPositionMixin from 'frontend/mixins/reset-scroll-position';
export default Route.extend(ResetScrollPositionMixin, {
intl: service(),
session: service(),
queryParams: {
specificToUser: {
refreshModel: true
}
},
model(params) {
const host = this.store.adapterFor('summarized-statistic').get('host');
let url = new URL(`${host}/chart_data/similarities.json`);
if (params.specificToUser){
url.searchParams.append('specific_to_user', params.specificToUser);
}
return fetch(url).then(function(response) {
return response.json();
});
},
actions: {
toggleSpecificToUser(currentValue){
const switchedValue = currentValue != "true";
this.transitionTo({ queryParams: { specific_to_user: switchedValue }});
}
}
}
);
| import { inject as service } from '@ember/service';
import fetch from 'fetch';
import Route from '@ember/routing/route';
import ResetScrollPositionMixin from 'frontend/mixins/reset-scroll-position';
export default Route.extend(ResetScrollPositionMixin, {
intl: service(),
session: service(),
queryParams: {
specificToUser: {
refreshModel: true
}
},
model(params) {
const host = this.store.adapterFor('summarized-statistic').get('host');
let url = new URL(`${host}/chart_data/similarities.json`);
let headers = {};
if (this.get('session.isAuthenticated') && params.specificToUser){
url.searchParams.append('specific_to_user', params.specificToUser);
headers['Authorization'] = `Bearer ${this.get('session.data.authenticated.idToken')}`;
}
return fetch(url, {headers: headers}).then(function(response) {
return response.json();
});
},
actions: {
toggleSpecificToUser(currentValue){
const switchedValue = currentValue != "true";
this.transitionTo({ queryParams: { specific_to_user: switchedValue }});
}
}
}
);
| Send authorization tokens in `fetch` | Send authorization tokens in `fetch`
| JavaScript | mit | roschaefer/rundfunk-mitbestimmen,roschaefer/rundfunk-mitbestimmen,roschaefer/rundfunk-mitbestimmen | ---
+++
@@ -15,11 +15,13 @@
model(params) {
const host = this.store.adapterFor('summarized-statistic').get('host');
let url = new URL(`${host}/chart_data/similarities.json`);
- if (params.specificToUser){
+ let headers = {};
+ if (this.get('session.isAuthenticated') && params.specificToUser){
url.searchParams.append('specific_to_user', params.specificToUser);
+ headers['Authorization'] = `Bearer ${this.get('session.data.authenticated.idToken')}`;
}
- return fetch(url).then(function(response) {
+ return fetch(url, {headers: headers}).then(function(response) {
return response.json();
});
}, |
196b1746e17241d764f35d67d257da8b0c111a7c | public/visifile_drivers/ui_components/editorComponent.js | public/visifile_drivers/ui_components/editorComponent.js | function component( args ) {
/*
base_component_id("editorComponent")
load_once_from_file(true)
*/
//alert(JSON.stringify(args,null,2))
var uid = uuidv4()
var uid2 = uuidv4()
var mm = Vue.component(uid, {
data: function () {
return {
text: args.text,
uid2: uid2
}
},
template: `<div>
<div v-bind:id='uid2' ></div>
<hr />
<slot :text2="text"></slot>
</div>`
,
mounted: function() {
var mm = this
var editor = ace.edit( uid2, {
mode: "ace/mode/javascript",
selectionStyle: "text"
})
document.getElementById(uid2).style.width="100%"
document.getElementById(uid2).style.height="45vh"
editor.getSession().setValue(mm.text);
editor.getSession().on('change', function() {
mm.text = editor.getSession().getValue();
//alert("changed text to : " + mm.text)
});
},
methods: {
getText: function() {
return this.text
}
}
})
return {
name: uid
}
}
| function component( args ) {
/*
base_component_id("editorComponent")
load_once_from_file(true)
*/
//alert(JSON.stringify(args,null,2))
var uid = uuidv4()
var uid2 = uuidv4()
var mm = Vue.component(uid, {
data: function () {
return {
text: args.text,
uid2: uid2
}
},
template: `<div>
<div v-bind:id='uid2' ></div>
<hr />
<slot :text2="text"></slot>
</div>`
,
mounted: function() {
var mm = this
var editor = ace.edit( uid2, {
mode: "ace/mode/javascript",
selectionStyle: "text"
})
document.getElementById(uid2).style.width="100%"
document.getElementById(uid2).style.height="45vh"
editor.getSession().setValue(mm.text);
editor.getSession().setUseWorker(false);
editor.getSession().on('change', function() {
mm.text = editor.getSession().getValue();
//alert("changed text to : " + mm.text)
});
},
methods: {
getText: function() {
return this.text
}
}
})
return {
name: uid
}
}
| Disable errors in Ace Editor | Disable errors in Ace Editor
I did this as errors always seem to show in the editor and this can be very offputting for the end user
| JavaScript | mit | zubairq/AppShare,zubairq/AppShare,zubairq/yazz,zubairq/AppShare,zubairq/gosharedata,zubairq/gosharedata,zubairq/yazz,zubairq/AppShare | ---
+++
@@ -31,6 +31,8 @@
document.getElementById(uid2).style.height="45vh"
editor.getSession().setValue(mm.text);
+ editor.getSession().setUseWorker(false);
+
editor.getSession().on('change', function() {
mm.text = editor.getSession().getValue(); |
dc74ef87e18cfcb537b93dbc535788cb8893be37 | reducers/file_list.js | reducers/file_list.js | import Cookie from 'js-cookie'
import _ from 'lodash'
import { SAVE_FILE, DELETE_FILE } from '../actions/file_list_actions'
const initialState = Cookie.get('files')
const setState = () => {
const files = Cookie.get('files')
if (files) { return JSON.parse(files) }
return []
}
const saveExistingFile = (state, updatedFile) => {
let newState
if (state.length === 0) {
newState = [updatedFile]
} else {
const removeFile = _.flatten([_.slice(state, 0, updatedFile.id), _.slice(state, updatedFile.id + 1, state.length)])
newState = [...removeFile, updatedFile]
}
Cookie.set('files', newState)
return newState
}
export const fileList = (state = setState(), action) => {
switch (action.type) {
case SAVE_FILE: {
const fileId = state[action.file.id].id
if (fileId) {
return saveExistingFile(state, action.file)
}
const newState = [...state, action.file]
Cookie.set('files', newState)
return newState
}
case DELETE_FILE: {
const newState = _.flatten([_.slice(state, 0, action.id), _.slice(state, action.id + 1, state.length)])
Cookie.set('files', newState)
return newState
}
default:
return state
}
} | import Cookie from 'js-cookie'
import _ from 'lodash'
import { SAVE_FILE, DELETE_FILE } from '../actions/file_list_actions'
const initialState = Cookie.get('files')
const setState = () => {
const files = Cookie.get('files')
if (files) { return JSON.parse(files) }
return []
}
const saveExistingFile = (state, updatedFile) => {
let newState
if (state.length === 0) {
newState = [updatedFile]
} else {
const removeFile = _.flatten([_.slice(state, 0, updatedFile.id), _.slice(state, updatedFile.id + 1, state.length)])
newState = [...removeFile, updatedFile]
}
Cookie.set('files', newState)
return newState
}
export const fileList = (state = setState(), action) => {
switch (action.type) {
case SAVE_FILE: {
const file = state[action.file.id]
if (file) {
return saveExistingFile(state, action.file)
}
const newState = [...state, action.file]
Cookie.set('files', newState)
return newState
}
case DELETE_FILE: {
const newState = _.flatten([_.slice(state, 0, action.id), _.slice(state, action.id + 1, state.length)])
Cookie.set('files', newState)
return newState
}
default:
return state
}
} | Stop breaking things Raquel, this is why you need tests | Stop breaking things Raquel, this is why you need tests
| JavaScript | mit | raquelxmoss/markdown-writer,raquelxmoss/markdown-writer | ---
+++
@@ -31,9 +31,9 @@
export const fileList = (state = setState(), action) => {
switch (action.type) {
case SAVE_FILE: {
- const fileId = state[action.file.id].id
+ const file = state[action.file.id]
- if (fileId) {
+ if (file) {
return saveExistingFile(state, action.file)
}
|
1d9ec16d01ea54dabb046b1b798a64c8ae6279bd | controller/index.js | controller/index.js | var Https = require('https');
var Common = require('./common');
exports.main = {
handler: function (request, reply) {
var params = Common.getRoomParameters(request, null, null, null);
reply.view('index_template', params);
}
};
exports.turn = {
handler: function (request, reply) {
var getOptions = {
host: 'instant.io',
port: 443,
path: '/rtcConfig',
method: 'GET'
};
Https.get(getOptions, function (result) {
console.log(result.statusCode == 200);
var body = '';
result.on('data', function (data) {
body += data;
});
result.on('end', function () {
reply(body);
});
}).on('error', function (e) {
reply({
"username":"webrtc",
"password":"webrtc",
"uris":[
"stun:stun.l.google.com:19302",
"stun:stun1.l.google.com:19302",
"stun:stun2.l.google.com:19302",
"stun:stun3.l.google.com:19302",
"stun:stun4.l.google.com:19302",
"stun:stun.services.mozilla.com",
"turn:turn.anyfirewall.com:443?transport=tcp"
]
});
});
}
};
| var Https = require('https');
var Common = require('./common');
exports.main = {
handler: function (request, reply) {
var params = Common.getRoomParameters(request, null, null, null);
reply.view('index_template', params);
}
};
exports.turn = {
handler: function (request, reply) {
var getOptions = {
host: 'instant.io',
port: 443,
path: '/__rtcConfig__',
method: 'GET'
};
Https.get(getOptions, function (result) {
console.log(result.statusCode == 200);
var body = '';
result.on('data', function (data) {
body += data;
});
result.on('end', function () {
reply(body);
});
}).on('error', function (e) {
reply({
"username":"webrtc",
"password":"webrtc",
"uris":[
"stun:stun.l.google.com:19302",
"stun:stun1.l.google.com:19302",
"stun:stun2.l.google.com:19302",
"stun:stun3.l.google.com:19302",
"stun:stun4.l.google.com:19302",
"stun:stun.services.mozilla.com",
"turn:turn.anyfirewall.com:443?transport=tcp"
]
});
});
}
};
| Change turn rest api endpoint. | Change turn rest api endpoint.
| JavaScript | mit | MidEndProject/node-apprtc,MidEndProject/node-apprtc | ---
+++
@@ -14,7 +14,7 @@
var getOptions = {
host: 'instant.io',
port: 443,
- path: '/rtcConfig',
+ path: '/__rtcConfig__',
method: 'GET'
};
Https.get(getOptions, function (result) { |
96f19a3d8937b075080ad70d304ecfa4136b6ff9 | Libraries/Utilities/RCTLog.js | Libraries/Utilities/RCTLog.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const invariant = require('invariant');
const levelsMap = {
log: 'log',
info: 'info',
warn: 'warn',
error: 'error',
fatal: 'error',
};
let warningHandler: ?(Array<any>) => void = null;
const RCTLog = {
// level one of log, info, warn, error, mustfix
logIfNoNativeHook(level: string, ...args: Array<any>): void {
// We already printed in the native console, so only log here if using a js debugger
if (typeof global.nativeLoggingHook === 'undefined') {
RCTLog.logToConsole(level, ...args);
} else {
// Report native warnings to YellowBox
if (warningHandler && level === 'warn') {
warningHandler(...args);
}
}
},
// Log to console regardless of nativeLoggingHook
logToConsole(level: string, ...args: Array<any>): void {
const logFn = levelsMap[level];
invariant(
logFn,
'Level "' + level + '" not one of ' + Object.keys(levelsMap).toString(),
);
console[logFn](...args);
},
setWarningHandler(handler: typeof warningHandler): void {
warningHandler = handler;
},
};
module.exports = RCTLog;
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const invariant = require('invariant');
const levelsMap = {
log: 'log',
info: 'info',
warn: 'warn',
error: 'error',
fatal: 'error',
};
let warningHandler: ?(Array<any>) => void = null;
const RCTLog = {
// level one of log, info, warn, error, mustfix
logIfNoNativeHook(level: string, ...args: Array<any>): void {
// We already printed in the native console, so only log here if using a js debugger
if (typeof global.nativeLoggingHook === 'undefined') {
RCTLog.logToConsole(level, ...args);
} else {
// Report native warnings to LogBox
if (warningHandler && level === 'warn') {
warningHandler(...args);
}
}
},
// Log to console regardless of nativeLoggingHook
logToConsole(level: string, ...args: Array<any>): void {
const logFn = levelsMap[level];
invariant(
logFn,
'Level "' + level + '" not one of ' + Object.keys(levelsMap).toString(),
);
console[logFn](...args);
},
setWarningHandler(handler: typeof warningHandler): void {
warningHandler = handler;
},
};
module.exports = RCTLog;
| Replace YellowBox references with LogBox | Replace YellowBox references with LogBox
Summary:
This diff replaces some YellowBox references with LogBox so we can remove it.
Changelog: [Internal]
Reviewed By: motiz88
Differential Revision: D19948126
fbshipit-source-id: b26ad1b78d86a8290f7e08396e4a8314fef7a9f3
| JavaScript | bsd-3-clause | hammerandchisel/react-native,arthuralee/react-native,hoangpham95/react-native,facebook/react-native,javache/react-native,facebook/react-native,exponent/react-native,exponentjs/react-native,janicduplessis/react-native,pandiaraj44/react-native,exponent/react-native,javache/react-native,exponent/react-native,myntra/react-native,myntra/react-native,javache/react-native,hoangpham95/react-native,hoangpham95/react-native,exponent/react-native,exponent/react-native,javache/react-native,javache/react-native,hoangpham95/react-native,exponentjs/react-native,janicduplessis/react-native,hammerandchisel/react-native,exponent/react-native,exponentjs/react-native,janicduplessis/react-native,exponent/react-native,pandiaraj44/react-native,facebook/react-native,facebook/react-native,exponentjs/react-native,hoangpham95/react-native,javache/react-native,pandiaraj44/react-native,facebook/react-native,myntra/react-native,janicduplessis/react-native,janicduplessis/react-native,facebook/react-native,javache/react-native,pandiaraj44/react-native,myntra/react-native,arthuralee/react-native,hoangpham95/react-native,myntra/react-native,myntra/react-native,exponentjs/react-native,pandiaraj44/react-native,janicduplessis/react-native,exponentjs/react-native,exponent/react-native,janicduplessis/react-native,pandiaraj44/react-native,hammerandchisel/react-native,pandiaraj44/react-native,exponentjs/react-native,hammerandchisel/react-native,arthuralee/react-native,hammerandchisel/react-native,javache/react-native,pandiaraj44/react-native,myntra/react-native,facebook/react-native,hoangpham95/react-native,facebook/react-native,janicduplessis/react-native,arthuralee/react-native,myntra/react-native,myntra/react-native,hammerandchisel/react-native,exponentjs/react-native,hammerandchisel/react-native,facebook/react-native,hammerandchisel/react-native,javache/react-native,arthuralee/react-native,hoangpham95/react-native | ---
+++
@@ -29,7 +29,7 @@
if (typeof global.nativeLoggingHook === 'undefined') {
RCTLog.logToConsole(level, ...args);
} else {
- // Report native warnings to YellowBox
+ // Report native warnings to LogBox
if (warningHandler && level === 'warn') {
warningHandler(...args);
} |
c04a3b26c6b1859bf77df6a84936c95b457bf65c | src/generators/background-colors.js | src/generators/background-colors.js | const postcss = require('postcss')
const _ = require('lodash')
function findColor(colors, color) {
const colorsNormalized = _.mapKeys(colors, (value, key) => {
return _.camelCase(key)
})
return _.get(colorsNormalized, _.camelCase(color), color)
}
module.exports = function ({ colors, backgroundColors }) {
if (_.isArray(backgroundColors)) {
backgroundColors = _(backgroundColors).map(color => [color, color]).fromPairs()
}
return _(backgroundColors).toPairs().map(([className, colorName]) => {
const kebabClass = _.kebabCase(className)
return postcss.rule({
selector: `.bg-${kebabClass}`
}).append({
prop: 'background-color',
value: findColor(colors, colorName)
})
}).value()
}
| const postcss = require('postcss')
const _ = require('lodash')
function findColor(colors, color) {
const colorsNormalized = _.mapKeys(colors, (value, key) => {
return _.camelCase(key)
})
return _.get(colorsNormalized, _.camelCase(color), color)
}
module.exports = function ({ colors, backgroundColors }) {
if (_.isArray(backgroundColors)) {
backgroundColors = _(backgroundColors).flatMap(color => {
if (_.isString(color)) {
return [[color, color]]
}
return _.toPairs(color)
}).fromPairs()
}
return _(backgroundColors).toPairs().map(([className, colorName]) => {
const kebabClass = _.kebabCase(className)
return postcss.rule({
selector: `.bg-${kebabClass}`
}).append({
prop: 'background-color',
value: findColor(colors, colorName)
})
}).value()
}
| Add support for mixed "plain color string" and "color map" background defintitions | Add support for mixed "plain color string" and "color map" background defintitions
Lets you do this:
```
backgroundColors: [
'blue',
'purple',
'pink',
{
primary: 'white',
secondary: 'orange',
},
]
```
| JavaScript | mit | tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindcss/tailwindcss,tailwindlabs/tailwindcss | ---
+++
@@ -11,7 +11,12 @@
module.exports = function ({ colors, backgroundColors }) {
if (_.isArray(backgroundColors)) {
- backgroundColors = _(backgroundColors).map(color => [color, color]).fromPairs()
+ backgroundColors = _(backgroundColors).flatMap(color => {
+ if (_.isString(color)) {
+ return [[color, color]]
+ }
+ return _.toPairs(color)
+ }).fromPairs()
}
return _(backgroundColors).toPairs().map(([className, colorName]) => { |
62bffcab761d3ca395e821e1cd259dab9ed60bc5 | blocks/data/index.js | blocks/data/index.js | var Data = require('../../lib/data');
module.exports = {
className: 'data',
template: require('./index.html'),
data: {
name: 'Data',
icon: '/images/blocks_text.png',
attributes: {
label: {
label: 'Header Text',
type: 'string',
value: '',
placeholder: 'Responses',
skipAutoRender: true
},
color: {
label: 'Header and Title Text Color',
type: 'color',
value: '#36494A',
skipAutoRender: true
}
},
currentDataSets: [],
initialDataLoaded: false,
isInteractive: false,
sortOldest: false
},
ready: function (){
var self = this;
if (!self.$data || !self.$data.currentDataSets || self.$data.currentDataSets.length === 0) self.$data.initialDataLoaded = false;
// Fetch collected Data
self.currentDataSets = [];
if(!self.isEditing) {
var data = new Data(self.$parent.$parent.$data.app.id);
data.getAllDataSets(function(currentDataSets) {
self.$data.initialDataLoaded = true;
self.currentDataSets = currentDataSets;
});
}
else {
self.$data.initialDataLoaded = true;
}
}
};
| var Data = require('../../lib/data');
module.exports = {
className: 'data',
template: require('./index.html'),
data: {
name: 'Data',
icon: '/images/blocks_text.png',
attributes: {
label: {
label: 'Header Text',
type: 'string',
value: '',
placeholder: 'Responses',
skipAutoRender: true
},
color: {
label: 'Header and Title Text Color',
type: 'color',
value: '#36494A',
skipAutoRender: true
}
},
currentDataSets: [],
initialDataLoaded: false,
isInteractive: false,
sortOldest: false
},
ready: function () {
var self = this;
if (
!self.$data ||
!self.$data.currentDataSets ||
self.$data.currentDataSets.length === 0
) {
self.$data.initialDataLoaded = false;
}
// Fetch collected Data
self.currentDataSets = [];
if (!self.isEditing) {
var data = new Data(self.$parent.$parent.$data.app.id);
data.getAllDataSets(function (currentDataSets) {
self.$data.initialDataLoaded = true;
self.currentDataSets = currentDataSets;
});
} else {
self.$data.initialDataLoaded = true;
}
}
};
| Resolve style errors on data block | Resolve style errors on data block
| JavaScript | mpl-2.0 | cadecairos/webmaker-android,gvn/webmaker-android,toolness/webmaker-android,j796160836/webmaker-android,k88hudson/webmaker-android,secretrobotron/webmaker-android,secretrobotron/webmaker-android,alicoding/webmaker-android,codex8/webmaker-app,vazquez/webmaker-android,bolaram/webmaker-android,j796160836/webmaker-android,thejdeep/webmaker-app,alicoding/webmaker-android,adamlofting/webmaker-android,rodmoreno/webmaker-android,gvn/webmaker-android,rodmoreno/webmaker-android,thejdeep/webmaker-app,mozilla/webmaker-android,bolaram/webmaker-android,alanmoo/webmaker-android,mozilla/webmaker-android,k88hudson/webmaker-android,codex8/webmaker-app,vazquez/webmaker-android,alanmoo/webmaker-android | ---
+++
@@ -27,22 +27,27 @@
sortOldest: false
},
- ready: function (){
+ ready: function () {
var self = this;
- if (!self.$data || !self.$data.currentDataSets || self.$data.currentDataSets.length === 0) self.$data.initialDataLoaded = false;
+ if (
+ !self.$data ||
+ !self.$data.currentDataSets ||
+ self.$data.currentDataSets.length === 0
+ ) {
+ self.$data.initialDataLoaded = false;
+ }
// Fetch collected Data
self.currentDataSets = [];
- if(!self.isEditing) {
+ if (!self.isEditing) {
var data = new Data(self.$parent.$parent.$data.app.id);
- data.getAllDataSets(function(currentDataSets) {
+ data.getAllDataSets(function (currentDataSets) {
self.$data.initialDataLoaded = true;
self.currentDataSets = currentDataSets;
});
- }
- else {
+ } else {
self.$data.initialDataLoaded = true;
}
} |
247efe2dfbd2762628415137ac1a2f9023cabbf3 | boot/kernal/index.js | boot/kernal/index.js | var mkdirp = require('mkdirp');
var clicolour = require("cli-color");
var exec = require('child_process').exec;
exports.createTmp = function createTmp(argument) {
mkdirp("./tmp", function(err){
console.log(clicolour.cyanBright('Created ./tmp...')+clicolour.greenBright("OK"));
})
}
exports.clean = function clean(x) {
console.log('Cleaning out files');
console.log('Cleaned out ./tmp...'+clicolour.greenBright("OK"));
}
| var mkdirp = require('mkdirp');
var clicolour = require("cli-color");
var exec = require('child_process').exec;
exports.createTmp = function createTmp(argument) {
mkdirp("./tmp", function(err){
console.log(clicolour.cyanBright('Created ./tmp...')+clicolour.greenBright("OK"));
})
}
exports.clean = function clean(x) {
// clean out ./tmp
exec("rm -rfv ./tmp/*", function (error, stdout, stderr) {
console.log('Cleaned out ./tmp...'+clicolour.greenBright("OK"));
});
}
| Add cleaning of tmp into nodejs | Add cleaning of tmp into nodejs
| JavaScript | mit | Gum-Joe/boss.js,Gum-Joe/Web-OS,Gum-Joe/boss.js,Gum-Joe/boss.js,Gum-Joe/Web-OS,Gum-Joe/boss.js,Gum-Joe/Web-OS,Gum-Joe/boss.js,Gum-Joe/Web-OS,Gum-Joe/Web-OS,Gum-Joe/Web-OS,Gum-Joe/boss.js,Gum-Joe/Web-OS,Gum-Joe/boss.js | ---
+++
@@ -9,6 +9,8 @@
}
exports.clean = function clean(x) {
- console.log('Cleaning out files');
- console.log('Cleaned out ./tmp...'+clicolour.greenBright("OK"));
+ // clean out ./tmp
+ exec("rm -rfv ./tmp/*", function (error, stdout, stderr) {
+ console.log('Cleaned out ./tmp...'+clicolour.greenBright("OK"));
+ });
} |
2ada6c33fca5a88ae22411408b7f6e35fd309831 | app/assets/javascripts/angular/controllers/winged_monkey_controllers.js | app/assets/javascripts/angular/controllers/winged_monkey_controllers.js | var wingedMonkeyControllers = angular.module('wingedMonkeyControllers',[]);
wingedMonkeyControllers.controller("ProviderAppsCtrl", function($scope, $filter, ProviderApplication) {
$scope.appsLoaded = false;
$scope.refreshProviderApps = function() {
ProviderApplication.query(function(data){
$scope.providerApps = data;
$scope.appsLoaded = true;
});
};
$scope.refreshProviderApps();
$scope.destroyProviderApp = function(app_id) {
$scope.providerApps.forEach(function(app, index) {
if (app_id === app.id) {
app.$delete({id: app.id}, function() {
//success
$scope.providerApps.splice(index, 1);
}, function(response){
//failure
console.log(response);
});
}
});
};
});
| var wingedMonkeyControllers = angular.module('wingedMonkeyControllers',[]);
wingedMonkeyControllers.controller("ProviderAppsCtrl", function($scope, $filter, ProviderApplication) {
$scope.appsLoaded = false;
$scope.refreshProviderApps = function() {
ProviderApplication.query(function(data){
$scope.providerApps = data;
$scope.appsLoaded = true;
});
};
$scope.refreshProviderApps();
$scope.destroyProviderApp = function(app_id) {
$scope.providerApps.forEach(function(app, index) {
if (app_id === app.id) {
// app.$delete({id: app.id}, function() {
ProviderApplication.delete({id: app.id}, function() {
//success
app.state = "DELETING";
// $scope.providerApps.splice(index, 1);
}, function(response){
//failure
console.log(response);
});
}
});
};
});
| Stop functionality wont remove the application untill the refresh occurs | Stop functionality wont remove the application untill the refresh occurs
| JavaScript | apache-2.0 | jtomasek/wingedmonkey,jtomasek/wingedmonkey | ---
+++
@@ -15,9 +15,11 @@
$scope.destroyProviderApp = function(app_id) {
$scope.providerApps.forEach(function(app, index) {
if (app_id === app.id) {
- app.$delete({id: app.id}, function() {
+ // app.$delete({id: app.id}, function() {
+ ProviderApplication.delete({id: app.id}, function() {
//success
- $scope.providerApps.splice(index, 1);
+ app.state = "DELETING";
+ // $scope.providerApps.splice(index, 1);
}, function(response){
//failure
console.log(response); |
b4dbc7fdda88de3c18a2b1d23fb29894ae407903 | app/imports/ui/components/alerts/alert-ending-soon/alert-ending-soon.js | app/imports/ui/components/alerts/alert-ending-soon/alert-ending-soon.js | import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import moment from 'moment';
import './alert-ending-soon.html';
Template.AlertEndingSoon.onCreated(function onCreated() {
const self = this;
self.threshold = moment.duration(20, 'minutes').asMilliseconds();
self.timeRemaining = new ReactiveVar(0);
self.autorun(() => {
const queue = Template.currentData().queue;
if (self.timeRemainingInterval) Meteor.clearInterval(self.timeRemainingInterval);
self.timeRemainingInterval = Meteor.setInterval(() => {
self.timeRemaining.set(moment(queue.scheduledEndTime).diff(moment()));
}, 1000);
});
});
Template.AlertEndingSoon.helpers({
endingSoon(queue) {
const timeRemaining = Template.instance().timeRemaining.get();
return !queue.isEnded() &&
(timeRemaining > 0) &&
(timeRemaining < Template.instance().threshold);
},
timeRemaining() {
return moment.duration(Template.instance().timeRemaining.get()).humanize();
},
});
| import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import moment from 'moment';
import './alert-ending-soon.html';
Template.AlertEndingSoon.onCreated(function onCreated() {
const self = this;
self.threshold = moment.duration(20, 'minutes').asMilliseconds();
self.timeRemaining = new ReactiveVar(0);
self.autorun(() => {
const queue = Template.currentData().queue;
if (self.timeRemainingInterval) Meteor.clearInterval(self.timeRemainingInterval);
self.timeRemainingInterval = Meteor.setInterval(() => {
self.timeRemaining.set(moment(queue.scheduledEndTime).diff(moment()));
}, 1000);
});
});
Template.AlertEndingSoon.helpers({
endingSoon(queue) {
const timeRemaining = Template.instance().timeRemaining.get();
return !queue.isEnded() &&
(timeRemaining > 0) &&
(timeRemaining < Template.instance().threshold);
},
timeRemaining() {
return moment.duration(Template.instance().timeRemaining.get()).humanize();
},
});
Template.AlertEndingSoon.events({
'click .js-edit-end-time'() {
$('.modal-queue-edit').modal();
},
'click .js-end-now'() {
const ok = confirm('Are you sure you want to end this queue?');
if (!ok) return;
endQueue.call({
queueId: this.queue._id,
}, (err) => {
if (err) console.log(err);
});
},
});
| Add event handlers for links in ending soon alert | Add event handlers for links in ending soon alert
| JavaScript | mit | athyuttamre/signmeup,etremel/signmeup,athyuttamre/signmeup,gregcarlin/signmeup,etremel/signmeup,gregcarlin/signmeup,signmeup/signmeup,etremel/signmeup,gregcarlin/signmeup,signmeup/signmeup | ---
+++
@@ -34,3 +34,20 @@
return moment.duration(Template.instance().timeRemaining.get()).humanize();
},
});
+
+Template.AlertEndingSoon.events({
+ 'click .js-edit-end-time'() {
+ $('.modal-queue-edit').modal();
+ },
+
+ 'click .js-end-now'() {
+ const ok = confirm('Are you sure you want to end this queue?');
+ if (!ok) return;
+
+ endQueue.call({
+ queueId: this.queue._id,
+ }, (err) => {
+ if (err) console.log(err);
+ });
+ },
+}); |
65326a10745b64c6518868a83c5ce0aa7ff8097b | prelim/renderPuzzle.js | prelim/renderPuzzle.js | function renderPuzzle( levelNumber, canvas, width, height ) {
document.body.appendChild(canvas);
canvas.width = width;
canvas.height = height;
canvas.style.backgroundColor = '#333333';
canvas.id = 'gameView';
var levels = new Levels( new XSPRNG(1), 70, new MonochromaticPaletteBuilder());
var level = levels.get(levelNumber);
var vc = new ViewController( level, canvas, 2, 'white' );
vc.draw();
var inputController = new InputController( vc );
var keyboardInput = new KeyboardInput(inputController);
keyboardInput.listen();
}
| function renderPuzzle( levelNumber, canvas, width, height ) {
document.body.appendChild(canvas);
canvas.width = width;
canvas.height = height;
canvas.style.backgroundColor = '#333333';
canvas.id = 'gameView';
var levels = new Levels( new XSPRNG(1), 70, new MonochromaticPaletteBuilder());
var level = levels.get(levelNumber);
var vc = new ViewController( level, canvas, 2, 'white' );
vc.draw();
var inputController = new InputController( vc );
var keyboardInput = new KeyboardInput(inputController);
var touchInput = new TouchInput(inputController, canvas);
keyboardInput.listen();
touchInput.listen();
}
| Add touch input to puzzle rendering function | Add touch input to puzzle rendering function
| JavaScript | mit | mnito/factors-game,mnito/factors-game | ---
+++
@@ -18,5 +18,8 @@
var inputController = new InputController( vc );
var keyboardInput = new KeyboardInput(inputController);
+ var touchInput = new TouchInput(inputController, canvas);
+
keyboardInput.listen();
+ touchInput.listen();
} |
de54880d4ef939358cba6687a109b792475e03d0 | conf/server.js | conf/server.js | // This module is the server of my site.
// Require external dependecies.
var http = require('http');
var filed = require('filed');
var path = require('path');
var readFile = require('fs').readFile;
var publish = require('./publish');
// Start the site.
module.exports = function (config) {
var isInvalid
= !config || !config.port || !config.input || !config.output;
if (isInvalid) {
throw new Error('Invalid configuration');
}
// Create and start the server.
http.createServer(function (req, resp) {
var file = path.resolve(config.output + req.url);
var ext = file.split('.')[1];
var isPublish = req.url === config.hook;
if (isPublish) {
return publish(config, req, resp, function (err) {
console.log(err || 'Published on %s', new Date());
});
}
if (req.url != '/' && !ext) {
file += '.html';
} else if (!ext) {
file += '/';
}
req.pipe(filed(file)).pipe(resp);
}).listen(config.port, config.ip);
};
| // This module is the server of my site.
// Require external dependecies.
var http = require('http');
var filed = require('filed');
var path = require('path');
var readFile = require('fs').readFile;
var publish = require('./publish');
var bake = require('blake').bake;
// Start the site.
module.exports = function (config) {
var isInvalid
= !config || !config.port || !config.input || !config.output;
if (isInvalid) {
throw new Error('Invalid configuration');
}
// Create and start the server.
http.createServer(function (req, resp) {
var file = path.resolve(config.output + req.url);
var ext = file.split('.')[1];
var isPublish = req.url === config.hook;
if (isPublish) {
return publish(config, req, resp, function (err) {
console.log(err || 'Published on %s', new Date());
});
}
if (req.url != '/' && !ext) {
file += '.html';
} else if (!ext) {
file += '/';
}
req.pipe(filed(file)).pipe(resp);
}).listen(config.port, config.ip);
// Retrieve latest tweet and instapaper likes.
var tweet = path.resolve(config.input, 'data', 'tweet.json');
var likes = path.resolve(config.input, 'data', 'likes.json');
setInterval(function () {
bake(config.input, config.output, tweet, likes, function (err) {
console.log('Published tweet and likes on %s', new Date());
});
}, 3600000);
};
| Add tweet and like interval | Add tweet and like interval
| JavaScript | mit | michaelnisi/troubled,michaelnisi/troubled,michaelnisi/troubled | ---
+++
@@ -6,6 +6,7 @@
var path = require('path');
var readFile = require('fs').readFile;
var publish = require('./publish');
+var bake = require('blake').bake;
// Start the site.
module.exports = function (config) {
@@ -35,5 +36,15 @@
}
req.pipe(filed(file)).pipe(resp);
- }).listen(config.port, config.ip);
+ }).listen(config.port, config.ip);
+
+ // Retrieve latest tweet and instapaper likes.
+ var tweet = path.resolve(config.input, 'data', 'tweet.json');
+ var likes = path.resolve(config.input, 'data', 'likes.json');
+
+ setInterval(function () {
+ bake(config.input, config.output, tweet, likes, function (err) {
+ console.log('Published tweet and likes on %s', new Date());
+ });
+ }, 3600000);
}; |
8f89c947b4d12ddc7222843c0fc60300df96e72f | tests/util-tests.js | tests/util-tests.js | var util = require('../js/util');
var assert = require('assert');
describe('Hello World function', function() {
it('should always fail', function() {
assert.equal(false, false);
});
it('should just say hello', function() {
var answer = util.helloWorld();
assert.equal('Hello World\n', answer);
});
}); | var util = require('../js/util');
var assert = require('assert');
describe('Hello World function', function() {
it('should always fail', function() {
assert.equal(false, false);
});
it('should just say hello', function() {
var answer = util.helloWorld();
assert.equal('Hello World, wie geht es euch?\n', answer);
});
}); | FIX Fix test to match production code | FIX Fix test to match production code
| JavaScript | mit | fhinkel/SimpleChatServer,fhinkel/SimpleChatServer | ---
+++
@@ -10,6 +10,6 @@
it('should just say hello', function() {
var answer = util.helloWorld();
- assert.equal('Hello World\n', answer);
+ assert.equal('Hello World, wie geht es euch?\n', answer);
});
}); |
aecea1524533c36829bc9ebc933a925acb091f74 | config/site.js | config/site.js | module.exports = function(config) {
if(!config.port || !_.isNumber(config.port)) throw new Error('Port undefined or not a number');
var domain = 'changethisfool.com';
var c = {
defaults: {
title: 'Change This Fool',
name: 'change-this-fool',
protocol: 'http',
get host() {
return this.port ? this.hostname + ':' + this.port : this.hostname;
},
get url () {
return this.protocol + '://' + this.host + '/';
}
},
development: {
hostname: 'localhost',
port: process.env.EXTERNAL_PORT || config.port
},
testing: {
hostname: 'testing.' + domain
},
staging: {
hostname: 'staging.' + domain
},
production: {
hostname: domain
}
};
return _.merge(c.defaults, c[ENV]);
};
| module.exports = function(config) {
if(!config.port || !_.isNumber(config.port)) throw new Error('Port undefined or not a number');
var domain = 'changethisfool.com';
var c = {
defaults: {
title: 'Change This Fool',
name: 'change-this-fool',
protocol: 'http',
get host() {
return this.port ? this.hostname + ':' + this.port : this.hostname;
},
get url () {
return this.protocol + '://' + this.host + '/';
}
},
development: {
hostname: 'localhost',
port: process.env.EXTERNAL_PORT || process.env.PORT || config.port
},
testing: {
hostname: 'testing.' + domain
},
staging: {
hostname: 'staging.' + domain
},
production: {
hostname: domain
}
};
return _.merge(c.defaults, c[ENV]);
};
| Check for process.env.PORT before using config.port | Check for process.env.PORT before using config.port
| JavaScript | mit | thecodebureau/epiphany | ---
+++
@@ -18,7 +18,7 @@
development: {
hostname: 'localhost',
- port: process.env.EXTERNAL_PORT || config.port
+ port: process.env.EXTERNAL_PORT || process.env.PORT || config.port
},
testing: { |
5a18e7bc20eea459c4cef4fe41aa94b5c6f87175 | controllers/hemera/updateSlackProfile.js | controllers/hemera/updateSlackProfile.js | var hemera = require('./index');
var controller;
/**
* Every time a user posts a message, we update their slack profile so we can stay up to date on their profile
* @param {Object} bot
* @param {Object} message
*/
module.exports = function updateSlackProfile(bot, message) {
controller = hemerga.getController();
controller.storage.users.get(message.user, function(err, user) {
if (err) {
return console.error(err);
}
bot.api.users.info({user: message.user}, function(err, res) {
if (err) {
return console.error(err);
}
user.slackUser = res.user;
controller.storage.users.save(user, function() {});
});
});
};
| var hemera = require('./index');
var controller;
/**
* Every time a user posts a message, we update their slack profile so we can stay up to date on their profile
* @param {Object} bot
* @param {Object} message
*/
module.exports = function updateSlackProfile(bot, message) {
controller = hemera.getController();
controller.storage.users.get(message.user, function(err, user) {
if (err) {
return console.error(err);
}
bot.api.users.info({user: message.user}, function(err, res) {
if (err) {
return console.error(err);
}
if (!user) {
user = {
id: message.user,
};
}
user.slackUser = res.user;
controller.storage.users.save(user, function() {});
});
});
};
| Create a user if they don't exist | Create a user if they don't exist
| JavaScript | mit | tgolen/node-multi-slack | ---
+++
@@ -7,7 +7,7 @@
* @param {Object} message
*/
module.exports = function updateSlackProfile(bot, message) {
- controller = hemerga.getController();
+ controller = hemera.getController();
controller.storage.users.get(message.user, function(err, user) {
if (err) {
return console.error(err);
@@ -18,6 +18,12 @@
return console.error(err);
}
+ if (!user) {
+ user = {
+ id: message.user,
+ };
+ }
+
user.slackUser = res.user;
controller.storage.users.save(user, function() {});
}); |
ba3147083f0d41be4835098a77f988b2d49b545c | www/js/controllers/home_controller.js | www/js/controllers/home_controller.js | controllers.controller('HomeCtrl', function($scope, Settings, AdUtil) {
function showHomeAd() {
if(AdMob){//Because android need this on start up apparently
var platform = Settings.getPlatformSettings();
console.log('<GFF> HomeCtrl showHomeAd Banner AdUnit: ' + platform.developerBanner );
AdUtil.showBannerAd( platform.developerBanner );
}
}
$scope.$on('$ionicView.enter', showHomeAd );
ionic.Platform.ready( showHomeAd );//Because view events do not appear to fire when the view first loads
$scope.onEmailTap = function(){
window.open('mailto:support@giveforfreeonline.org', '_system', 'location=yes'); return false;
}
$scope.onFacebookTap = function(){
window.open('http://www.facebook.com', '_system', 'location=yes'); return false;
}
$scope.onTwitterTap = function(){
window.open('http://www.twitter.com', '_system', 'location=yes'); return false;
}
});
| controllers.controller('HomeCtrl', function($scope, Settings, AdUtil) {
function showHomeAd() {
if(AdMob){//Because android need this on start up apparently
var platform = Settings.getPlatformSettings();
console.log('<GFF> HomeCtrl showHomeAd Banner AdUnit: ' + platform.developerBanner );
AdUtil.showBannerAd( platform.developerBanner );
}
}
$scope.$on('$ionicView.enter', showHomeAd );
ionic.Platform.ready( showHomeAd );//Because view events do not appear to fire when the view first loads
$scope.onEmailTap = function(){
window.open('mailto:support@giveforfreeonline.org', '_system', 'location=yes'); return false;
}
$scope.onFacebookTap = function(){
window.open('https://www.facebook.com/Give-For-Free-643061692510804/', '_system', 'location=yes'); return false;
}
$scope.onTwitterTap = function(){
window.open('https://twitter.com/_giveforfree_', '_system', 'location=yes'); return false;
}
});
| Add twitter and Facebook links | Add twitter and Facebook links
| JavaScript | mit | flashquartermaster/Give-For-Free,flashquartermaster/Give-For-Free,flashquartermaster/Give-For-Free,flashquartermaster/Give-For-Free,flashquartermaster/Give-For-Free,flashquartermaster/Give-For-Free | ---
+++
@@ -17,10 +17,10 @@
}
$scope.onFacebookTap = function(){
- window.open('http://www.facebook.com', '_system', 'location=yes'); return false;
+ window.open('https://www.facebook.com/Give-For-Free-643061692510804/', '_system', 'location=yes'); return false;
}
$scope.onTwitterTap = function(){
- window.open('http://www.twitter.com', '_system', 'location=yes'); return false;
+ window.open('https://twitter.com/_giveforfree_', '_system', 'location=yes'); return false;
}
}); |
2caea723c87b1b7726264e7ff03621ad101ec0f9 | main.js | main.js | 'use strict';
var app = require('app');
var mainWindow = null;
var dribbbleData = null;
var menubar = require('menubar')
var mb = menubar({
index: 'file://' + __dirname + '/app/index.html',
icon: __dirname + '/app/assets/HotshotIcon.png',
width: 400,
height: 700,
'max-width': 440,
'min-height': 300,
'min-width': 300,
preloadWindow: true
});
app.on('window-all-closed', function() {
app.quit();
});
mb.on('show', function(){
// mb.window.webContents.send('focus');
mb.window.openDevTools();
});
| 'use strict';
var app = require('app');
var ipc = require('ipc');
var mainWindow = null;
var dribbbleData = null;
var menubar = require('menubar')
var mb = menubar({
index: 'file://' + __dirname + '/app/index.html',
icon: __dirname + '/app/assets/HotshotIcon.png',
width: 400,
height: 700,
'max-width': 440,
'min-height': 300,
'min-width': 300,
preloadWindow: true
});
app.on('window-all-closed', function() {
app.quit();
});
mb.on('show', function(){
// mb.window.webContents.send('focus');
// mb.window.openDevTools();
});
ipc.on('quit-button-clicked', function(event) {
app.quit();
});
| Add way to quit application via offcanvas menu | Add way to quit application via offcanvas menu
| JavaScript | cc0-1.0 | andrewnaumann/hotshot,andrewnaumann/hotshot | ---
+++
@@ -1,6 +1,6 @@
'use strict';
var app = require('app');
-
+var ipc = require('ipc');
var mainWindow = null;
var dribbbleData = null;
@@ -24,7 +24,11 @@
mb.on('show', function(){
// mb.window.webContents.send('focus');
- mb.window.openDevTools();
+// mb.window.openDevTools();
+});
+
+ipc.on('quit-button-clicked', function(event) {
+ app.quit();
});
|
2df528d81a60e1a8a71d5cdc3fb7ac063d235902 | test/special/index.js | test/special/index.js | 'use strict';
var _ = require('lodash');
var fs = require('fs');
var hljs = require('../../build');
var jsdom = require('jsdom').jsdom;
var utility = require('../utility');
describe('special cases tests', function() {
before(function() {
var blocks,
filename = utility.buildPath('fixtures', 'index.html'),
page = fs.readFileSync(filename, 'utf-8');
// Allows hljs to use document
global.document = jsdom(page);
// Setup hljs environment
hljs.configure({ tabReplace: ' ' });
hljs.initHighlighting();
// Setup hljs for non-`<pre><code>` tests
hljs.configure({ useBR: true });
blocks = document.querySelectorAll('.code');
_.each(blocks, hljs.highlightBlock);
});
require('./explicitLanguage');
require('./customMarkup');
require('./languageAlias');
require('./noHighlight');
require('./subLanguages');
require('./buildClassName');
require('./useBr');
});
| 'use strict';
var _ = require('lodash');
var fs = require('fs');
var hljs = require('../../build');
var jsdom = require('jsdom').jsdom;
var utility = require('../utility');
describe('special cases tests', function() {
before(function(done) {
var filename = utility.buildPath('fixtures', 'index.html');
fs.readFile(filename, 'utf-8', function(err, page) {
var blocks;
// Allows hljs to use document
global.document = jsdom(page);
// Setup hljs environment
hljs.configure({ tabReplace: ' ' });
hljs.initHighlighting();
// Setup hljs for non-`<pre><code>` tests
hljs.configure({ useBR: true });
blocks = document.querySelectorAll('.code');
_.each(blocks, hljs.highlightBlock);
done(err);
});
});
require('./explicitLanguage');
require('./customMarkup');
require('./languageAlias');
require('./noHighlight');
require('./subLanguages');
require('./buildClassName');
require('./useBr');
});
| Use the async version of readFile | Use the async version of readFile
| JavaScript | bsd-3-clause | lead-auth/highlight.js,StanislawSwierc/highlight.js,MakeNowJust/highlight.js,carlokok/highlight.js,VoldemarLeGrand/highlight.js,Sannis/highlight.js,0x7fffffff/highlight.js,isagalaev/highlight.js,dbkaplun/highlight.js,VoldemarLeGrand/highlight.js,highlightjs/highlight.js,Sannis/highlight.js,isagalaev/highlight.js,sourrust/highlight.js,carlokok/highlight.js,highlightjs/highlight.js,sourrust/highlight.js,MakeNowJust/highlight.js,bluepichu/highlight.js,carlokok/highlight.js,carlokok/highlight.js,VoldemarLeGrand/highlight.js,bluepichu/highlight.js,0x7fffffff/highlight.js,MakeNowJust/highlight.js,teambition/highlight.js,aurusov/highlight.js,highlightjs/highlight.js,tenbits/highlight.js,tenbits/highlight.js,bluepichu/highlight.js,highlightjs/highlight.js,sourrust/highlight.js,aurusov/highlight.js,palmin/highlight.js,dbkaplun/highlight.js,dbkaplun/highlight.js,palmin/highlight.js,palmin/highlight.js,aurusov/highlight.js,StanislawSwierc/highlight.js,Sannis/highlight.js,0x7fffffff/highlight.js,teambition/highlight.js,tenbits/highlight.js,teambition/highlight.js | ---
+++
@@ -7,23 +7,27 @@
var utility = require('../utility');
describe('special cases tests', function() {
- before(function() {
- var blocks,
- filename = utility.buildPath('fixtures', 'index.html'),
- page = fs.readFileSync(filename, 'utf-8');
+ before(function(done) {
+ var filename = utility.buildPath('fixtures', 'index.html');
- // Allows hljs to use document
- global.document = jsdom(page);
+ fs.readFile(filename, 'utf-8', function(err, page) {
+ var blocks;
- // Setup hljs environment
- hljs.configure({ tabReplace: ' ' });
- hljs.initHighlighting();
+ // Allows hljs to use document
+ global.document = jsdom(page);
- // Setup hljs for non-`<pre><code>` tests
- hljs.configure({ useBR: true });
+ // Setup hljs environment
+ hljs.configure({ tabReplace: ' ' });
+ hljs.initHighlighting();
- blocks = document.querySelectorAll('.code');
- _.each(blocks, hljs.highlightBlock);
+ // Setup hljs for non-`<pre><code>` tests
+ hljs.configure({ useBR: true });
+
+ blocks = document.querySelectorAll('.code');
+ _.each(blocks, hljs.highlightBlock);
+
+ done(err);
+ });
});
require('./explicitLanguage'); |
a1284f1be70ba643b23b17285b13119488e15bcc | dependument.js | dependument.js | #!/usr/bin/env node
(function() {
"use strict";
const fs = require('fs');
const CONFIG_FILE = "package.json";
console.log(readFile(CONFIG_FILE));
function readFile(path) {
let contents = fs.readFileSync(path);
return JSON.parse(contents);
}
})();
| #!/usr/bin/env node
(function() {
"use strict";
const fs = require('fs');
const CONFIG_FILE = "package.json";
(function() {
let file = readFile(CONFIG_FILE);
let dependencies = getDependencies(file);
console.log(dependencies);
})();
function getDependencies(file) {
let dependencies = file.dependencies;
if (dependencies === undefined
|| dependencies === null) {
dependencies = {};
}
return dependencies;
}
function readFile(path) {
let contents = fs.readFileSync(path);
return JSON.parse(contents);
}
})();
| Read the dependencies from the file | Read the dependencies from the file
| JavaScript | unlicense | Jameskmonger/dependument,dependument/dependument,dependument/dependument,Jameskmonger/dependument | ---
+++
@@ -6,7 +6,24 @@
const fs = require('fs');
const CONFIG_FILE = "package.json";
- console.log(readFile(CONFIG_FILE));
+ (function() {
+ let file = readFile(CONFIG_FILE);
+
+ let dependencies = getDependencies(file);
+
+ console.log(dependencies);
+ })();
+
+ function getDependencies(file) {
+ let dependencies = file.dependencies;
+
+ if (dependencies === undefined
+ || dependencies === null) {
+ dependencies = {};
+ }
+
+ return dependencies;
+ }
function readFile(path) {
let contents = fs.readFileSync(path); |
9f3ac4bd9932a0d2dc991199e41001ce30f8eecd | lib/plugins/write-file.js | lib/plugins/write-file.js | var fs = require('fs');
module.exports = function(context) {
//
// Write some data to a file.
//
context.writeFile = function(data, file) {
fs.writeFile(file, data, function(err) {
if (err) {
throw err;
}
});
};
};
| var fs = require('fs');
module.exports = function(context) {
//
// Write some data to a file.
// Creates new file with the name supplied if the file doesnt exist
//
context.writeFile = function(data, file) {
fs.open(file, 'a+', function(err, fd) {
if(err) {
throw err;
}
var buffer = new Buffer(data);
fs.write(fd, buffer, 0, buffer.length, null, function(err, bytread, buffer) {
if(err) {
throw err;
}
});
});
};
};
| Create file if file doesnt exist | Create file if file doesnt exist
| JavaScript | isc | fiveisprime/screpl | ---
+++
@@ -4,12 +4,22 @@
//
// Write some data to a file.
+ // Creates new file with the name supplied if the file doesnt exist
//
context.writeFile = function(data, file) {
- fs.writeFile(file, data, function(err) {
- if (err) {
+ fs.open(file, 'a+', function(err, fd) {
+ if(err) {
throw err;
}
+
+ var buffer = new Buffer(data);
+
+ fs.write(fd, buffer, 0, buffer.length, null, function(err, bytread, buffer) {
+ if(err) {
+ throw err;
+ }
+ });
+
});
};
}; |
590abe07d9af483dea0e82b1ee481e191821edc9 | aura-components/src/main/components/uiExamples/radio/radioController.js | aura-components/src/main/components/uiExamples/radio/radioController.js | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* 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.
*/
({
onRadio: function(cmp, evt) {
var elem = evt.getSource().getElement();
var selected = elem.textContent;
resultCmp = cmp.find("radioResult");
resultCmp.set("v.value", selected);
},
onGroup: function(cmp, evt) {
var elem = evt.getSource().getElement();
var selected = elem.textContent;
resultCmp = cmp.find("radioGroupResult");
resultCmp.set("v.value", selected);
}
})
| /*
* Copyright (C) 2013 salesforce.com, inc.
*
* 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.
*/
({
onRadio: function(cmp, evt) {
var selected = evt.source.get("v.label");
resultCmp = cmp.find("radioResult");
resultCmp.set("v.value", selected);
},
onGroup: function(cmp, evt) {
var selected = evt.source.get("v.label");
resultCmp = cmp.find("radioGroupResult");
resultCmp.set("v.value", selected);
}
})
| Remove use of getElement() in example | Remove use of getElement() in example
@rev W-3224090@
@rev goliver@ | JavaScript | apache-2.0 | madmax983/aura,forcedotcom/aura,forcedotcom/aura,forcedotcom/aura,madmax983/aura,forcedotcom/aura,madmax983/aura,forcedotcom/aura,madmax983/aura,madmax983/aura,madmax983/aura | ---
+++
@@ -15,15 +15,13 @@
*/
({
onRadio: function(cmp, evt) {
- var elem = evt.getSource().getElement();
- var selected = elem.textContent;
+ var selected = evt.source.get("v.label");
resultCmp = cmp.find("radioResult");
resultCmp.set("v.value", selected);
},
onGroup: function(cmp, evt) {
- var elem = evt.getSource().getElement();
- var selected = elem.textContent;
+ var selected = evt.source.get("v.label");
resultCmp = cmp.find("radioGroupResult");
resultCmp.set("v.value", selected);
} |
d458223003e0a110549c03862e7a00984a211719 | packages/@sanity/core/src/actions/dataset/import/getBatchedAssetImporter.js | packages/@sanity/core/src/actions/dataset/import/getBatchedAssetImporter.js | import through from 'through2'
import getAssetImporter from './getAssetImporter'
import promiseEach from 'promise-each-concurrency'
const batchSize = 10
const concurrency = 6
export default options => {
const assetImporter = getAssetImporter(options)
const documents = []
return through.obj(onChunk, onFlush)
async function uploadAssets(stream, cb) {
await promiseEach(documents, assetImporter.processDocument, {concurrency})
while (documents.length > 0) {
stream.push(documents.shift())
}
cb()
}
function onChunk(chunk, enc, cb) {
const newLength = documents.push(chunk)
if (newLength !== batchSize) {
return cb()
}
return uploadAssets(this, cb)
}
function onFlush(cb) {
if (documents.length === 0) {
cb()
return
}
uploadAssets(this, cb)
}
}
| import through from 'through2'
import getAssetImporter from './getAssetImporter'
import promiseEach from 'promise-each-concurrency'
const batchSize = 10
const concurrency = 6
export default options => {
const assetImporter = getAssetImporter(options)
const documents = []
return through.obj(onChunk, onFlush)
async function uploadAssets(stream, cb) {
try {
await promiseEach(documents, assetImporter.processDocument, {concurrency})
} catch (err) {
cb(err)
return
}
while (documents.length > 0) {
stream.push(documents.shift())
}
cb()
}
function onChunk(chunk, enc, cb) {
const newLength = documents.push(chunk)
if (newLength !== batchSize) {
return cb()
}
return uploadAssets(this, cb)
}
function onFlush(cb) {
if (documents.length === 0) {
cb()
return
}
uploadAssets(this, cb)
}
}
| Add try/catch around asset importing and emit error to stream | [core] Add try/catch around asset importing and emit error to stream
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -12,7 +12,12 @@
return through.obj(onChunk, onFlush)
async function uploadAssets(stream, cb) {
- await promiseEach(documents, assetImporter.processDocument, {concurrency})
+ try {
+ await promiseEach(documents, assetImporter.processDocument, {concurrency})
+ } catch (err) {
+ cb(err)
+ return
+ }
while (documents.length > 0) {
stream.push(documents.shift()) |
14d6dad3991c6a5f37cc801550bbdf4fc1475d75 | connectors/v2/baidu.js | connectors/v2/baidu.js | 'use strict';
/* global Connector */
Connector.playerSelector = '#playPanel > .panel-inner';
Connector.artistSelector = '.artist';
Connector.trackSelector = '.songname';
Connector.isPlaying = function () {
return !$('.play').hasClass('stop');
};
| 'use strict';
/* global Connector */
Connector.playerSelector = '#playPanel > .panel-inner';
Connector.artistSelector = '.artist';
Connector.trackSelector = '.songname';
Connector.currentTimeSelector = '.curTime';
Connector.durationSelector = '.totalTime';
Connector.isPlaying = function () {
return !$('.play').hasClass('stop');
};
| Add current time and duration processing to Baidu | Add current time and duration processing to Baidu
| JavaScript | mit | inverse/web-scrobbler,Paszt/web-scrobbler,alexesprit/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,ex47/web-scrobbler,alexesprit/web-scrobbler,carpet-berlin/web-scrobbler,Paszt/web-scrobbler,usdivad/web-scrobbler,david-sabata/web-scrobbler,ex47/web-scrobbler,carpet-berlin/web-scrobbler,usdivad/web-scrobbler,david-sabata/web-scrobbler,galeksandrp/web-scrobbler,galeksandrp/web-scrobbler,inverse/web-scrobbler | ---
+++
@@ -8,6 +8,10 @@
Connector.trackSelector = '.songname';
+Connector.currentTimeSelector = '.curTime';
+
+Connector.durationSelector = '.totalTime';
+
Connector.isPlaying = function () {
return !$('.play').hasClass('stop');
}; |
88440db50bce90f918beb61c0335294389015f69 | topics/about_scope.js | topics/about_scope.js | module("About Scope (topics/about_scope.js)");
thisIsAGlobalVariable = 77;
test("global variables", function() {
equal(__, thisIsAGlobalVariable, 'is thisIsAGlobalVariable defined in this scope?');
});
test("variables declared inside of a function", function() {
var outerVariable = "outer";
// this is a self-invoking function. Notice that it calls itself at the end ().
(function() {
var innerVariable = "inner";
equal(__, outerVariable, 'is outerVariable defined in this scope?');
equal(__, innerVariable, 'is innerVariable defined in this scope?');
})();
equal(__, outerVariable, 'is outerVariable defined in this scope?');
equal(__, typeof(innerVariable), 'is innerVariable defined in this scope?');
});
| module("About Scope (topics/about_scope.js)");
thisIsAGlobalVariable = 77;
test("global variables", function() {
equal(77, thisIsAGlobalVariable, 'is thisIsAGlobalVariable defined in this scope?');
});
test("variables declared inside of a function", function() {
var outerVariable = "outer";
// this is a self-invoking function. Notice that it calls itself at the end ().
(function() {
var innerVariable = "inner";
equal("outer", outerVariable, 'is outerVariable defined in this scope?');
equal("inner", innerVariable, 'is innerVariable defined in this scope?');
})();
equal("outer", outerVariable, 'is outerVariable defined in this scope?');
equal('undefined', typeof(innerVariable), 'is innerVariable defined in this scope?');
});
| Complete scope tests to pass | Complete scope tests to pass
| JavaScript | mit | supportbeam/javascript_koans,supportbeam/javascript_koans | ---
+++
@@ -3,7 +3,7 @@
thisIsAGlobalVariable = 77;
test("global variables", function() {
- equal(__, thisIsAGlobalVariable, 'is thisIsAGlobalVariable defined in this scope?');
+ equal(77, thisIsAGlobalVariable, 'is thisIsAGlobalVariable defined in this scope?');
});
test("variables declared inside of a function", function() {
@@ -12,10 +12,10 @@
// this is a self-invoking function. Notice that it calls itself at the end ().
(function() {
var innerVariable = "inner";
- equal(__, outerVariable, 'is outerVariable defined in this scope?');
- equal(__, innerVariable, 'is innerVariable defined in this scope?');
+ equal("outer", outerVariable, 'is outerVariable defined in this scope?');
+ equal("inner", innerVariable, 'is innerVariable defined in this scope?');
})();
- equal(__, outerVariable, 'is outerVariable defined in this scope?');
- equal(__, typeof(innerVariable), 'is innerVariable defined in this scope?');
+ equal("outer", outerVariable, 'is outerVariable defined in this scope?');
+ equal('undefined', typeof(innerVariable), 'is innerVariable defined in this scope?');
}); |
abf3f9d87828d7159c3c04a46b5e6630a6af43b7 | app/scripts/services/resources-service.js | app/scripts/services/resources-service.js | 'use strict';
(function() {
angular.module('ncsaas')
.service('resourcesService', ['RawResource', 'currentStateService', '$q', resourcesService]);
function resourcesService(RawResource, currentStateService, $q) {
var vm = this;
vm.getResourcesList = getResourcesList;
vm.getRawResourcesList = getRawResourcesList;
function getRawResourcesList() {
return RawResource.query();
}
function getResourcesList() {
var deferred = $q.defer();
currentStateService.getCustomer().then(function(response){
var customerName = response.name;
var resources = RawResource.query({customer_name: customerName});
deferred.resolve(resources);
}, function(err){
deferred.reject(err);
});
return deferred.promise;
}
}
})();
(function() {
angular.module('ncsaas')
.factory('RawResource', ['ENV', '$resource', RawResource]);
function RawResource(ENV, $resource) {
return $resource(
ENV.apiEndpoint + 'api/resources/', {},
{
update: {
method: 'PUT'
}
}
);
}
})();
| 'use strict';
(function() {
angular.module('ncsaas')
.service('resourcesService', ['RawResource', 'currentStateService', '$q', resourcesService]);
function resourcesService(RawResource, currentStateService, $q) {
var vm = this;
vm.getResourcesList = getResourcesList;
vm.getRawResourcesList = getRawResourcesList;
function getRawResourcesList() {
return RawResource.query();
}
function getResourcesList() {
var deferred = $q.defer();
currentStateService.getCustomer().then(function(response){
var customerName = response.name;
var resources = RawResource.query({customer_name: customerName});
deferred.resolve(resources);
}, function(err){
deferred.reject(err);
});
return deferred.promise;
}
}
})();
(function() {
angular.module('ncsaas')
.factory('RawResource', ['ENV', '$resource', RawResource]);
function RawResource(ENV, $resource) {
return $resource(
ENV.apiEndpoint + 'api/resources/', {},
{
}
);
}
})();
| Remove method update from RawResource service | Remove method update from RawResource service
| JavaScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -35,9 +35,6 @@
return $resource(
ENV.apiEndpoint + 'api/resources/', {},
{
- update: {
- method: 'PUT'
- }
}
);
} |
ae0e43c40e037a7631efc0e631c7b09a0c930909 | spec/renderer.spec.js | spec/renderer.spec.js | const MarkdownRenderer = require('../src/renderer').MarkdownRenderer
describe ('Renderer', () => {
var renderer
var callback
beforeEach(() => {
callback = jasmine.createSpy('callback')
renderer = new MarkdownRenderer(callback)
})
it('converts a markdown file', (done) => {
const markdownFilePath = __dirname + '/test_readme.md'
const expectedMarkdown = '^[^<>]*<div class="markdown-body"><h1 id="hello">Hello</h1></div>$'
renderer.loadFile(markdownFilePath, callback).then(() => {
expect(callback.calls.count()).toEqual(1)
expect(callback.calls.mostRecent().args[0]).toMatch(expectedMarkdown)
done()
}, done.fail)
})
})
| const MarkdownRenderer = require('../src/renderer').MarkdownRenderer
describe ('Renderer', () => {
var renderer
var callback
beforeEach(() => {
callback = jasmine.createSpy('callback')
renderer = new MarkdownRenderer(callback)
})
it('converts a markdown file', (done) => {
const markdownFilePath = __dirname + '/test_readme.md'
const expectedMarkdown = '^[^<>]*<div class="markdown-body"><h1 id="hello">Hello</h1></div>$'
renderer.loadFile(markdownFilePath, callback).then(() => {
expect(callback.calls.count()).toEqual(1)
expect(callback.calls.mostRecent().args[0]).toMatch(expectedMarkdown)
done()
}, done.fail)
})
it('converts a markdown string', (done) => {
var markdown = '## Hi'
const expectedMarkdown = '^[^<>]*<div class="markdown-body"><h2 id="hi">Hi</h2></div>$'
renderer.load(markdown, callback).then(() => {
expect(callback.calls.count()).toEqual(1)
expect(callback.calls.mostRecent().args[0]).toMatch(expectedMarkdown)
done()
}, done.fail)
})
})
| Add failing test for rendering markdown string | Add failing test for rendering markdown string
| JavaScript | unlicense | pfertyk/mauve,pfertyk/mauve | ---
+++
@@ -19,4 +19,15 @@
done()
}, done.fail)
})
+
+ it('converts a markdown string', (done) => {
+ var markdown = '## Hi'
+ const expectedMarkdown = '^[^<>]*<div class="markdown-body"><h2 id="hi">Hi</h2></div>$'
+
+ renderer.load(markdown, callback).then(() => {
+ expect(callback.calls.count()).toEqual(1)
+ expect(callback.calls.mostRecent().args[0]).toMatch(expectedMarkdown)
+ done()
+ }, done.fail)
+ })
}) |
25b98d508c2b9eb70a73c363ae6c29c54ad3920f | www/loginchecker.js | www/loginchecker.js | var _IsLoggedIn = undefined;
function checkIfLoggedInAndTriggerEvent(notifyLoggedOutEveryTime){
request({module:"user", type: "IsLoggedIn"}, function(res){
if(_IsLoggedIn === undefined){
$(document).trigger("InitialUserStatus", res.loggedIn);
}
if(res.loggedIn != _IsLoggedIn){
_IsLoggedIn = res.loggedIn;
$(document).trigger(_IsLoggedIn ? "logged_out_timer" : "logged_in_timer");
if(!_IsLoggedIn && typeof(Notifier) === "function")
new Notifier().show("You are not logged in!");
} else if(notifyLoggedOutEveryTime && !_IsLoggedIn){
new Notifier().show("You are not logged in!");
}
});
}
$(document).bind('request_error', function(){
checkIfLoggedInAndTriggerEvent(true);
});
setInterval(checkIfLoggedInAndTriggerEvent, 10000);
checkIfLoggedInAndTriggerEvent();
$(document).bind('InitialUserStatus', function(e, arg){
_IsLoggedIn = arg;
});
$(document).bind('LoggedIn', function(){
_IsLoggedIn = true;
});
$(document).bind('LoggedOut', function(){
_IsLoggedIn = false;
});
function isLoggedIn(){
return _IsLoggedIn;
} | var _IsLoggedIn = undefined;
function checkIfLoggedInAndTriggerEvent(notifyLoggedOutEveryTime){
request({module:"user", type: "IsLoggedIn"}, function(res){
if(_IsLoggedIn === undefined){
$(document).trigger("InitialUserStatus", res.loggedIn);
}
if(res.loggedIn != _IsLoggedIn){
_IsLoggedIn = res.loggedIn;
$(document).trigger(_IsLoggedIn ? "logged_out_timer" : "logged_in_timer");
if(!_IsLoggedIn && typeof(Notifier) === "function")
new Notifier().show("You are not logged in!");
} else if(notifyLoggedOutEveryTime && !_IsLoggedIn){
new Notifier().show("You are not logged in!");
}
});
}
var lastIsLoggedInErrorCheck = 0;
$(document).bind('request_error', function(){
if(new Date().getTime() > lastIsLoggedInErrorCheck + 1000) //Only notify about login errors every sec
checkIfLoggedInAndTriggerEvent(true);
lastIsLoggedInErrorCheck = new Date().getTime();
});
setInterval(checkIfLoggedInAndTriggerEvent, 10000);
checkIfLoggedInAndTriggerEvent();
$(document).bind('InitialUserStatus', function(e, arg){
_IsLoggedIn = arg;
});
$(document).bind('LoggedIn', function(){
_IsLoggedIn = true;
});
$(document).bind('LoggedOut', function(){
_IsLoggedIn = false;
});
function isLoggedIn(){
return _IsLoggedIn;
}
| Fix indefinite event loop on connection error | Fix indefinite event loop on connection error | JavaScript | mit | palantus/mod-user | ---
+++
@@ -1,5 +1,4 @@
var _IsLoggedIn = undefined;
-
function checkIfLoggedInAndTriggerEvent(notifyLoggedOutEveryTime){
request({module:"user", type: "IsLoggedIn"}, function(res){
@@ -21,8 +20,11 @@
}
+var lastIsLoggedInErrorCheck = 0;
$(document).bind('request_error', function(){
- checkIfLoggedInAndTriggerEvent(true);
+ if(new Date().getTime() > lastIsLoggedInErrorCheck + 1000) //Only notify about login errors every sec
+ checkIfLoggedInAndTriggerEvent(true);
+ lastIsLoggedInErrorCheck = new Date().getTime();
});
setInterval(checkIfLoggedInAndTriggerEvent, 10000); |
1dc9e07b3eba41f48806cc2545b190f048ab9019 | src/DataLinkMixin.js | src/DataLinkMixin.js | "use strict";
/**
* Since only a single constructor is being exported as module.exports this comment isn't documented.
* The class and module are the same thing, the contructor comment takes precedence.
* @module DataLinkMixin
*/
var EventEmitter = require('wolfy87-eventemitter');
var eventEmitter = new EventEmitter();
/**
* The function to set the DataSource a DataLink listens to, and listen to it
* * @param { DataSource } dataSource - The DataSource to listen to
*/
var setDataSource = function (dataSource) {
dataSource.addListener('dataChanged', function(event) {this.onDataChanged(event);});
};
/**
* A mixin to decorate a datalink with helper methods
* @mixin
* @example require('data-chains/src/DataLinkMixin').call({});
*/
module.exports = function () {
//Copy over everything in EventEmitter to the object
for (var k in eventEmitter) {
if (eventEmitter.hasOwnProperty(k)) {
this[k] = eventEmitter[k];
}
}
//Define a the listener, which delegates to methods the target object is exected to have
//Assign the datasource setter
this.setDataSource = setDataSource;
}
| "use strict";
/**
* Since only a single constructor is being exported as module.exports this comment isn't documented.
* The class and module are the same thing, the contructor comment takes precedence.
* @module DataLinkMixin
*/
var EventEmitter = require('wolfy87-eventemitter');
var eventEmitter = new EventEmitter();
/**
* The function to set the DataSource a DataLink listens to, and listen to it
* * @param { DataSource } dataSource - The DataSource to listen to
*/
var setDataSource = function (dataSource) {
dataSource.addListener('dataChanged', function(event) {this.onDataChanged(event);});
};
/**
* A mixin to decorate a datalink with helper methods
* @mixin
* @example require('data-chains/src/DataLinkMixin').call({});
*/
module.exports = function () {
//Copy over everything in EventEmitter to the object
for (var k in eventEmitter) {
if (!this.hasOwnProperty(k)) {
this[k] = eventEmitter[k];
}
}
//Define a the listener, which delegates to methods the target object is exected to have
//Assign the datasource setter
this.setDataSource = setDataSource;
}
| Switch it around, mixin everything that doesn't override a method already on the target. | Switch it around, mixin everything that doesn't override a method already on the target.
| JavaScript | mit | chad-autry/data-chains | ---
+++
@@ -25,7 +25,7 @@
//Copy over everything in EventEmitter to the object
for (var k in eventEmitter) {
- if (eventEmitter.hasOwnProperty(k)) {
+ if (!this.hasOwnProperty(k)) {
this[k] = eventEmitter[k];
}
} |
42fead0aa8484ea83c91781ee4c298248e0cccf2 | dom/Component.js | dom/Component.js | var Class = require('../Class'),
Publisher = require('../Publisher'),
create = require('./create'),
style = require('./style'),
getOffset = require('./getOffset')
module.exports = Class(Publisher, function() {
this.init = function() {
Publisher.prototype.init.apply(this)
}
this.render = function(win) {
this._win = win
this._doc = this._win.document
this._el = create('div', null, this._doc)
this.createContent()
return this
}
this.create = function(tag, properties) { return create(tag, properties, this._doc) }
this.append = function(element) { return this._el.appendChild(element) }
this.appendTo = function(element) { return element.appendChild(this._el) }
this.getOffset = function() { return getOffset(this._el) }
}) | var Class = require('../Class'),
Publisher = require('../Publisher'),
create = require('./create'),
style = require('./style'),
getOffset = require('./getOffset')
module.exports = Class(Publisher, function() {
this._tag = 'div'
this.init = function() {
Publisher.prototype.init.apply(this)
}
this.render = function(win, el) {
this._win = win
this._doc = this._win.document
this._el = el || create(this._tag, null, this._doc)
this.createContent()
return this
}
this.create = function(tag, properties) { return create(tag, properties, this._doc) }
this.append = function(element) { return this._el.appendChild(element) }
this.appendTo = function(element) { return element.appendChild(this._el) }
this.getOffset = function() { return getOffset(this._el) }
}) | Allow specifying the tag type of a dom component, and allow passing in the element a component should render in | Allow specifying the tag type of a dom component, and allow passing in the element a component should render in
| JavaScript | mit | ASAPPinc/std.js,marcuswestin/std.js | ---
+++
@@ -6,14 +6,16 @@
module.exports = Class(Publisher, function() {
+ this._tag = 'div'
+
this.init = function() {
Publisher.prototype.init.apply(this)
}
- this.render = function(win) {
+ this.render = function(win, el) {
this._win = win
this._doc = this._win.document
- this._el = create('div', null, this._doc)
+ this._el = el || create(this._tag, null, this._doc)
this.createContent()
return this
} |
02f9e21ff32ddbd4c829ae1a1370fe19e12938bd | lib/helpers/message-parsers.js | lib/helpers/message-parsers.js | module.exports.int = function(_msg) {
if (_msg.properties.contentType === 'application/json') {
return JSON.parse(_msg.content.toString());
}
return _msg.content.toString();
};
module.exports.out = function(content, options) {
if (typeof content === 'object') {
content = JSON.stringify(content);
options.contentType = 'application/json';
}
return new Buffer(content);
};
| module.exports.in = function(_msg) {
if (_msg.properties.contentType === 'application/json') {
return JSON.parse(_msg.content.toString());
}
return _msg.content.toString();
};
module.exports.out = function(content, options) {
if (typeof content === 'object') {
content = JSON.stringify(content);
options.contentType = 'application/json';
}
return new Buffer(content);
};
| FIx bad function naming in message formatter helper | FIx bad function naming in message formatter helper
| JavaScript | mit | dial-once/node-bunnymq | ---
+++
@@ -1,4 +1,4 @@
-module.exports.int = function(_msg) {
+module.exports.in = function(_msg) {
if (_msg.properties.contentType === 'application/json') {
return JSON.parse(_msg.content.toString());
} |
1e90e61bfe9b5fd6b0de0bc83b931bf7034ae885 | src/matchers/index.js | src/matchers/index.js | const _ = require('lodash/fp')
const fs = require('fs')
const path = require('path')
const matchers = _.flow(
_.map(file => path.basename(file, '.js')),
_.without(['index'])
)(fs.readdirSync(__dirname))
module.exports = _.flow(
_.map(matcher => require(`./${matcher}`)),
_.zipObject(matchers)
)(matchers)
| module.exports = {
Given: require('./Given'),
Nested: require('./Nested'),
Prop: require('./Prop'),
Rejects: require('./Rejects'),
Required: require('./Required'),
Resolves: require('./Resolves'),
Returns: require('./Returns'),
Test: require('./Test'),
Throws: require('./Throws')
}
| Use explicit exports for matchers. | Use explicit exports for matchers.
This was causing issues with importing *.test.js files and making this explicit
should also make it easier to convert to ES modules.
| JavaScript | isc | nickmccurdy/purespec | ---
+++
@@ -1,13 +1,11 @@
-const _ = require('lodash/fp')
-const fs = require('fs')
-const path = require('path')
-
-const matchers = _.flow(
- _.map(file => path.basename(file, '.js')),
- _.without(['index'])
-)(fs.readdirSync(__dirname))
-
-module.exports = _.flow(
- _.map(matcher => require(`./${matcher}`)),
- _.zipObject(matchers)
-)(matchers)
+module.exports = {
+ Given: require('./Given'),
+ Nested: require('./Nested'),
+ Prop: require('./Prop'),
+ Rejects: require('./Rejects'),
+ Required: require('./Required'),
+ Resolves: require('./Resolves'),
+ Returns: require('./Returns'),
+ Test: require('./Test'),
+ Throws: require('./Throws')
+} |
4b4020d9c2c489b8f113ed817e9b13d8f6003427 | app/components/html-editor.js | app/components/html-editor.js | /* eslint ember/order-in-components: 0 */
import $ from 'jquery';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { computed } from '@ember/object';
const defaultButtons = [
'bold',
'italic',
'subscript',
'superscript',
'formatOL',
'formatUL',
'insertLink',
'html'
];
export default Component.extend({
i18n: service(),
content: '',
/**
* Disable Froala's built in beacon tracking
* Has to be done on the global jQuery plugin object
*/
init() {
this._super(...arguments);
$.FE.DT = true;
},
options: computed('i18n.locale', function(){
const i18n = this.get('i18n');
const language = i18n.get('locale');
return {
key : 'vD1Ua1Mf1e1VSYKa1EPYD==',
theme : 'gray',
language,
toolbarInline: false,
placeholderText: '',
allowHTML: true,
saveInterval: false,
pastePlain: true,
spellcheck: true,
toolbarButtons: defaultButtons,
toolbarButtonsMD: defaultButtons,
toolbarButtonsSM: defaultButtons,
toolbarButtonsXS: defaultButtons,
quickInsertButtons: false,
pluginsEnabled: ['lists', 'code_view', 'link'],
};
})
});
| /* eslint ember/order-in-components: 0 */
import $ from 'jquery';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { computed } from '@ember/object';
const defaultButtons = [
'bold',
'italic',
'subscript',
'superscript',
'formatOL',
'formatUL',
'insertLink',
'html'
];
export default Component.extend({
i18n: service(),
content: '',
/**
* Disable Froala's built in beacon tracking
* Has to be done on the global jQuery plugin object
*/
init() {
this._super(...arguments);
$.FE.DT = true;
},
options: computed('i18n.locale', function(){
const i18n = this.get('i18n');
const language = i18n.get('locale');
return {
key : '3A9A5C4A3gC3E3C3E3B7A4A2F4B2D2zHMDUGENKACTMXQL==',
theme : 'gray',
language,
toolbarInline: false,
placeholderText: '',
allowHTML: true,
saveInterval: false,
pastePlain: true,
spellcheck: true,
toolbarButtons: defaultButtons,
toolbarButtonsMD: defaultButtons,
toolbarButtonsSM: defaultButtons,
toolbarButtonsXS: defaultButtons,
quickInsertButtons: false,
pluginsEnabled: ['lists', 'code_view', 'link'],
};
})
});
| Update our Froala Editor license key | Update our Froala Editor license key
| JavaScript | mit | jrjohnson/frontend,thecoolestguy/frontend,jrjohnson/frontend,djvoa12/frontend,ilios/frontend,dartajax/frontend,ilios/frontend,thecoolestguy/frontend,djvoa12/frontend,dartajax/frontend | ---
+++
@@ -31,7 +31,7 @@
const language = i18n.get('locale');
return {
- key : 'vD1Ua1Mf1e1VSYKa1EPYD==',
+ key : '3A9A5C4A3gC3E3C3E3B7A4A2F4B2D2zHMDUGENKACTMXQL==',
theme : 'gray',
language,
toolbarInline: false, |
22e488049a640d04cc5db19fec3043354ee335db | src/base/UserData.js | src/base/UserData.js | core.Class("lowland.base.UserData", {
construct : function() {
this.__$$userdata = {};
},
members : {
setUserData : function(key, value) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
if (!value) {
throw new Error("Parameter value not set");
}
}
this.__$$userdata[key] = value;
},
getUserData : function(key) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
}
return this.__$$userdata[key];
},
removeUserData : function(key) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
}
this.__$$userdata[key] = undefined;
}
}
}); | core.Class("lowland.base.UserData", {
construct : function() {
this.__$$userdata = {};
},
members : {
setUserData : function(key, value) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
if (!value) {
console.warn("Parameter value not set for key " + key);
}
}
this.__$$userdata[key] = value;
},
getUserData : function(key) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
}
return this.__$$userdata[key];
},
removeUserData : function(key) {
if (core.Env.getValue("debug")) {
if (!key) {
throw new Error("Parameter key not set");
}
}
this.__$$userdata[key] = undefined;
}
}
}); | Change from error to warn in userdata | Change from error to warn in userdata
| JavaScript | mit | fastner/lowland,fastner/lowland | ---
+++
@@ -10,7 +10,7 @@
throw new Error("Parameter key not set");
}
if (!value) {
- throw new Error("Parameter value not set");
+ console.warn("Parameter value not set for key " + key);
}
}
|
767bb63da813da20d02ba4dc938750d283fb10de | test/integration/fixtures/sampleapp/config/local.js | test/integration/fixtures/sampleapp/config/local.js | module.exports = {
log: {
level: 'silent'
},
views: {
locals: {
foo: '!bar!'
}
},
blueprints: {
defaultLimit: 10
},
models: {
migrate: 'alter'
},
globals: false
};
| module.exports = {
log: {
level: 'silent'
},
views: {
locals: {
foo: '!bar!'
}
},
models: {
migrate: 'alter'
},
globals: false
};
| Remove `defaultLimit` from test fixture app | Remove `defaultLimit` from test fixture app
| JavaScript | mit | rlugojr/sails,balderdashy/sails,rlugojr/sails | ---
+++
@@ -7,9 +7,6 @@
foo: '!bar!'
}
},
- blueprints: {
- defaultLimit: 10
- },
models: {
migrate: 'alter'
}, |
76c587ac9c7619aa9788daf960b7556b323fb08e | config/karma.conf.js | config/karma.conf.js | basePath = '../';
files = [
JASMINE,
JASMINE_ADAPTER,
'app/lib/jquery/jquery-*.js',
'app/lib/angular/angular.js',
'app/lib/angular/angular-*.js',
'app/lib/underscore.js',
'test/lib/angular/angular-mocks.js',
'app/lib/angular-ui/angular-ui-0.4.0/build/**/*.js',
'app/js/directives/*.js',
'app/js/**/*.js',
'test/unit/**/*.js'
];
autoWatch = false;
browsers = ['Chrome'];
junitReporter = {
outputFile: 'test_out/unit.xml',
suite: 'unit'
};
| basePath = '../';
files = [
JASMINE,
JASMINE_ADAPTER,
'app/lib/jquery/jquery-*.js',
'app/lib/angular/angular.js',
'app/lib/angular/angular-*.js',
'app/lib/underscore.js',
'test/lib/angular/angular-mocks.js',
'app/lib/angular-ui/angular-ui-0.4.0/build/**/*.js',
'app/js/directives/*.js',
'app/js/**/*.js',
'test/unit/**/*.js'
];
autoWatch = true;
browsers = ['PhantomJS'];
junitReporter = {
outputFile: 'test_out/unit.xml',
suite: 'unit'
};
| Set karma options up for faster unit tests | Set karma options up for faster unit tests
| JavaScript | mit | DerekDomino/forms-angular,behzad88/forms-angular,behzad88/forms-angular,DerekDomino/forms-angular,forms-angular/forms-angular,b12consulting/forms-angular,forms-angular/forms-angular,b12consulting/forms-angular,forms-angular/forms-angular,DerekDomino/forms-angular | ---
+++
@@ -14,9 +14,9 @@
'test/unit/**/*.js'
];
-autoWatch = false;
+autoWatch = true;
-browsers = ['Chrome'];
+browsers = ['PhantomJS'];
junitReporter = {
outputFile: 'test_out/unit.xml', |
0605156573b379514f243119d20f55fb8ce8b660 | view/dbjs/active-managers-select.js | view/dbjs/active-managers-select.js | 'use strict';
var d = require('d')
, db = require('mano').db
, _ = require('mano').i18n.bind('View: Manager Select');
module.exports = function (descriptor) {
Object.defineProperties(descriptor, {
inputOptions: d({
list: db.User.instances.filterByKey('isManagerActive').toArray(function (a, b) {
return a.fullName.localeCompare(b.fullName);
}),
property: 'fullName',
chooseLabel: _("Select manager:")
})
});
};
| 'use strict';
var d = require('d')
, activeManagers = require('../../users/active-managers')
, _ = require('mano').i18n.bind('View: Manager Select');
module.exports = function (descriptor) {
Object.defineProperties(descriptor, {
inputOptions: d({
list: activeManagers.toArray(function (a, b) {
return a.fullName.toLowerCase().localeCompare(b.fullName.toLowerCase());
}),
property: 'fullName',
chooseLabel: _("Select manager:")
})
});
};
| Use managers list + case insensitive comparison | Use managers list + case insensitive comparison
| JavaScript | mit | egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations | ---
+++
@@ -1,14 +1,14 @@
'use strict';
var d = require('d')
- , db = require('mano').db
+ , activeManagers = require('../../users/active-managers')
, _ = require('mano').i18n.bind('View: Manager Select');
module.exports = function (descriptor) {
Object.defineProperties(descriptor, {
inputOptions: d({
- list: db.User.instances.filterByKey('isManagerActive').toArray(function (a, b) {
- return a.fullName.localeCompare(b.fullName);
+ list: activeManagers.toArray(function (a, b) {
+ return a.fullName.toLowerCase().localeCompare(b.fullName.toLowerCase());
}),
property: 'fullName',
chooseLabel: _("Select manager:") |
7daab629eaccd22f474da04a9d83f560dbeb4685 | src/post/LikesList.js | src/post/LikesList.js | import React, { Component } from 'react';
import { Link } from 'react-router';
import Avatar from '../widgets/Avatar';
import './LikesList.scss';
export default class LikesList extends Component {
constructor(props) {
super(props);
this.state = {
show: 10,
};
}
handleShowMore() {
this.setState({
show: this.state.show + 10,
});
}
render() {
const { activeVotes } = this.props;
const hasMore = activeVotes.length > this.state.show;
return (
<div className="LikesList">
{
activeVotes.slice(0, this.state.show).map(vote =>
<div className="LikesList__item" key={vote.voter}>
<Avatar xs username={vote.voter} />
{ ' ' }
<Link to={`/@${vote.voter}`}>
@{vote.voter}
</Link>
{ ' ' }
{vote.percent < 0
? 'Disliked'
: 'Liked'
}
</div>
)
}
{ hasMore &&
<a
className="LikesList__showMore"
tabIndex="0"
onClick={() => this.handleShowMore()}
>
See More Likes
</a>
}
</div>
);
}
}
| import React, { Component } from 'react';
import { Link } from 'react-router';
import Avatar from '../widgets/Avatar';
import './LikesList.scss';
export default class LikesList extends Component {
constructor(props) {
super(props);
this.state = {
show: 10,
};
}
handleShowMore() {
this.setState({
show: this.state.show + 10,
});
}
render() {
const { activeVotes } = this.props;
const hasMore = activeVotes.length > this.state.show;
return (
<div className="LikesList">
{
activeVotes.slice(0, this.state.show).map(vote =>
<div className="LikesList__item" key={vote.voter}>
<Avatar xs username={vote.voter} />
{ ' ' }
<Link to={`/@${vote.voter}`}>
@{vote.voter}
</Link>
{ ' ' }
{vote.percent < 0
? <span className="text-danger">Disliked</span>
: 'Liked'
}
</div>
)
}
{ hasMore &&
<a
className="LikesList__showMore"
tabIndex="0"
onClick={() => this.handleShowMore()}
>
See More Likes
</a>
}
</div>
);
}
}
| Add red color on dislikes | Add red color on dislikes
| JavaScript | mit | ryanbaer/busy,Sekhmet/busy,Sekhmet/busy,ryanbaer/busy,busyorg/busy,busyorg/busy | ---
+++
@@ -33,7 +33,7 @@
</Link>
{ ' ' }
{vote.percent < 0
- ? 'Disliked'
+ ? <span className="text-danger">Disliked</span>
: 'Liked'
}
</div> |
f0678e2e83fbddd440c775742691da408e21367b | plugins/services/src/js/constants/DefaultApp.js | plugins/services/src/js/constants/DefaultApp.js | const DEFAULT_APP_RESOURCES = {cpus: 1, mem: 128};
const DEFAULT_APP_SPEC = Object.assign({instances: 1}, DEFAULT_APP_RESOURCES);
module.exports = {
DEFAULT_APP_RESOURCES,
DEFAULT_APP_SPEC
};
| const DEFAULT_APP_RESOURCES = {cpus: 0.1, mem: 128};
const DEFAULT_APP_SPEC = Object.assign({instances: 1}, DEFAULT_APP_RESOURCES);
module.exports = {
DEFAULT_APP_RESOURCES,
DEFAULT_APP_SPEC
};
| Change CPU default from 1 to 0.1 | Change CPU default from 1 to 0.1
| JavaScript | apache-2.0 | dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui | ---
+++
@@ -1,4 +1,4 @@
-const DEFAULT_APP_RESOURCES = {cpus: 1, mem: 128};
+const DEFAULT_APP_RESOURCES = {cpus: 0.1, mem: 128};
const DEFAULT_APP_SPEC = Object.assign({instances: 1}, DEFAULT_APP_RESOURCES);
module.exports = { |
78ce6d2bf9c2307f322f1d2ea9a28639868445c6 | src/client/js/main.js | src/client/js/main.js | const React = require("react");
const ReactDOM = require("react-dom");
const HeroUnit = require("./components/main.jsx");
const data = require("../../data/schedule.json");
const projectConfig = require("../../../project.config.js");
ReactDOM.render(
React.createElement(HeroUnit, {
homeTeam: projectConfig.homeTeam,
homeStadium: projectConfig.homeStadium,
data
}),
document.getElementById("react-container")
);
| const React = require("react");
const ReactDOM = require("react-dom");
const HeroUnit = require("./components/main.js");
const data = require("../../data/schedule.json");
const projectConfig = require("../../../project.config.js");
ReactDOM.render(
React.createElement(HeroUnit, {
homeTeam: projectConfig.homeTeam,
homeStadium: projectConfig.homeStadium,
data
}),
document.getElementById("react-container")
);
| Update filename for new jsx=>js conversion | Update filename for new jsx=>js conversion
| JavaScript | mit | baer/isThereAFuckingGame | ---
+++
@@ -1,7 +1,7 @@
const React = require("react");
const ReactDOM = require("react-dom");
-const HeroUnit = require("./components/main.jsx");
+const HeroUnit = require("./components/main.js");
const data = require("../../data/schedule.json");
const projectConfig = require("../../../project.config.js"); |
8742599f32274925b24b668e8915ce2966d8ea89 | src/config/package.js | src/config/package.js | 'use strict';
/**
* dependency package versions
*/
export default {
redis: '2.3.0',
sqlite3: '3.1.4',
ejs: '2.3.4',
jade: '1.11.0',
mongodb: '2.0.48',
memjs: '0.8.7',
sockjs: '0.3.15',
nunjucks: '2.2.0',
'socket.io': '1.3.7',
pg: '4.4.3',
'source-map-support': '0.4.0'
}; | 'use strict';
/**
* dependency package versions
*/
export default {
redis: '2.3.0',
sqlite3: '3.1.4',
ejs: '2.3.4',
jade: '1.11.0',
mongodb: '2.0.48',
memjs: '0.8.7',
sockjs: '0.3.15',
nunjucks: '2.2.0',
'socket.io': '1.3.7',
pg: '7.0.1',
'source-map-support': '0.4.0'
}; | Upgrade pg version to 7.0.1 | Upgrade pg version to 7.0.1
| JavaScript | mit | Qihoo360/thinkjs,thinkjs/thinkjs,snadn/thinkjs,75team/thinkjs,75team/thinkjs,75team/thinkjs | ---
+++
@@ -12,6 +12,6 @@
sockjs: '0.3.15',
nunjucks: '2.2.0',
'socket.io': '1.3.7',
- pg: '4.4.3',
+ pg: '7.0.1',
'source-map-support': '0.4.0'
}; |
e197f10b72a8f3dea6d25d06c4c902e6c7d80ad8 | backend/servers/mcapid/lib/dal/files.js | backend/servers/mcapid/lib/dal/files.js | module.exports = function(r) {
const {addFileToDirectoryInProject} = require('./dir-utils')(r);
const uploadFileToProjectDirectory = async(file, projectId, directoryId, userId) => {
let upload = await addFileToDirectoryInProject(file, directoryId, projectId, userId);
return upload;
};
const moveFileToDirectory = async(fileId, oldDirectoryId, newDirectoryId) => {
await r.table('datadir2datafile').getAll([oldDirectoryId, fileId], {index: 'datadir_datafile'})
.update({datadir_id: newDirectoryId});
return await getFile(fileId);
};
const getFile = async(fileId) => {
return await r.table('datafiles').get(fileId).merge(() => {
return {
directory: r.table('datadir2datafile').getAll(fileId, {index: 'datafile_id'})
.eqJoin('datadir_id', r.table('datadirs')).zip()
.without('datadir_id', 'datafile_id').nth(0)
};
});
};
return {
uploadFileToProjectDirectory,
moveFileToDirectory,
getFile,
};
}; | module.exports = function(r) {
const {addFileToDirectoryInProject} = require('./dir-utils')(r);
const uploadFileToProjectDirectory = async(file, projectId, directoryId, userId) => {
let upload = await addFileToDirectoryInProject(file, directoryId, projectId, userId);
return upload;
};
const moveFileToDirectory = async(fileId, oldDirectoryId, newDirectoryId) => {
let rv = await r.table('datadir2datafile').getAll([oldDirectoryId, fileId], {index: 'datadir_datafile'})
.update({datadir_id: newDirectoryId});
if (!rv.replaced) {
throw new Error(`Unable to move file ${fileId} in directory ${oldDirectoryId} into directory ${newDirectoryId}`);
}
return await getFile(fileId);
};
const getFile = async(fileId) => {
return await r.table('datafiles').get(fileId).merge(() => {
return {
directory: r.table('datadir2datafile').getAll(fileId, {index: 'datafile_id'})
.eqJoin('datadir_id', r.table('datadirs')).zip()
.without('datadir_id', 'datafile_id').nth(0)
};
});
};
return {
uploadFileToProjectDirectory,
moveFileToDirectory,
getFile,
};
}; | Throw an error if nothing is changed on a file move | Throw an error if nothing is changed on a file move
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -8,8 +8,11 @@
};
const moveFileToDirectory = async(fileId, oldDirectoryId, newDirectoryId) => {
- await r.table('datadir2datafile').getAll([oldDirectoryId, fileId], {index: 'datadir_datafile'})
+ let rv = await r.table('datadir2datafile').getAll([oldDirectoryId, fileId], {index: 'datadir_datafile'})
.update({datadir_id: newDirectoryId});
+ if (!rv.replaced) {
+ throw new Error(`Unable to move file ${fileId} in directory ${oldDirectoryId} into directory ${newDirectoryId}`);
+ }
return await getFile(fileId);
};
|
19faa2f7d98a8a9212bf253668bc0f8ab066d3ee | bundles/ranvier-combat/commands/kill.js | bundles/ranvier-combat/commands/kill.js | 'use strict';
module.exports = (srcPath) => {
const Broadcast = require(srcPath + 'Broadcast');
const Parser = require(srcPath + 'CommandParser').CommandParser;
return {
aliases: ['attack', 'slay'],
command : (state) => (args, player) => {
args = args.trim();
if (!args.length) {
return Broadcast.sayAt(player, 'Kill whom?');
}
if (player.isInCombat()) {
return Broadcast.sayAt(player, "You're too busy fighting!");
}
let target = null;
try {
target = player.findCombatant(args);
} catch (e) {
return Broadcast.sayAt(player, e.message);
}
if (!target) {
return Broadcast.sayAt(player, "They aren't here.");
}
Broadcast.sayAt(player, `You attack ${target.name}.`);
player.initiateCombat(target);
Broadcast.sayAtExcept(player.room, `${player.name} attacks ${target.name}!`, [player, target]);
if (!target.isNpc) {
Broadcast.sayAt(target, `${player.name} attacks you!`);
}
}
};
};
| 'use strict';
module.exports = (srcPath) => {
const Broadcast = require(srcPath + 'Broadcast');
const Parser = require(srcPath + 'CommandParser').CommandParser;
return {
aliases: ['attack', 'slay'],
command : (state) => (args, player) => {
args = args.trim();
if (!args.length) {
return Broadcast.sayAt(player, 'Kill whom?');
}
let target = null;
try {
target = player.findCombatant(args);
} catch (e) {
return Broadcast.sayAt(player, e.message);
}
if (!target) {
return Broadcast.sayAt(player, "They aren't here.");
}
Broadcast.sayAt(player, `You attack ${target.name}.`);
player.initiateCombat(target);
Broadcast.sayAtExcept(player.room, `${player.name} attacks ${target.name}!`, [player, target]);
if (!target.isNpc) {
Broadcast.sayAt(target, `${player.name} attacks you!`);
}
}
};
};
| Allow player to engage multiple enemies at once | Allow player to engage multiple enemies at once
| JavaScript | mit | shawncplus/ranviermud | ---
+++
@@ -11,10 +11,6 @@
if (!args.length) {
return Broadcast.sayAt(player, 'Kill whom?');
- }
-
- if (player.isInCombat()) {
- return Broadcast.sayAt(player, "You're too busy fighting!");
}
let target = null; |
cd461531e850fd30cbd5e1903308b25b19460c0a | MarkdownConverter/Resources/Files.js | MarkdownConverter/Resources/Files.js | const Path = require("path");
module.exports = {
SystemStyle: Path.join(__dirname, "css", "styles.css"),
DefaultStyle: Path.join(__dirname, "css", "markdown.css"),
DefaultHighlight: Path.join(__dirname, "css", "highlight.css"),
EmojiStyle: Path.join(__dirname, "css", "emoji.css"),
SystemTemplate: Path.join(__dirname, "SystemTemplate.html"),
HighlightJSStylesDir: Path.join(__dirname, "..", "node_modules", "highlightjs", "styles")
} | const Path = require("path");
module.exports = {
SystemStyle: Path.join(__dirname, "css", "styles.css"),
DefaultStyle: Path.join(__dirname, "css", "markdown.css"),
DefaultHighlight: Path.join(__dirname, "css", "highlight.css"),
EmojiStyle: Path.join(__dirname, "css", "emoji.css"),
SystemTemplate: Path.join(__dirname, "SystemTemplate.html"),
HighlightJSStylesDir: Path.join(__dirname, "..", "..", "node_modules", "highlightjs", "styles")
} | Fix the path to the highlight-js directory | Fix the path to the highlight-js directory
| JavaScript | mit | manuth/MarkdownConverter,manuth/MarkdownConverter,manuth/MarkdownConverter | ---
+++
@@ -6,5 +6,5 @@
DefaultHighlight: Path.join(__dirname, "css", "highlight.css"),
EmojiStyle: Path.join(__dirname, "css", "emoji.css"),
SystemTemplate: Path.join(__dirname, "SystemTemplate.html"),
- HighlightJSStylesDir: Path.join(__dirname, "..", "node_modules", "highlightjs", "styles")
+ HighlightJSStylesDir: Path.join(__dirname, "..", "..", "node_modules", "highlightjs", "styles")
} |
dec162c8555fadb12abf8c390f0d899061f5775c | server/models/index.js | server/models/index.js | import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
// import configs from '../config/config';
const basename = path.basename(module.filename);
// const env = process.env.NODE_ENV || 'development';
// const config = configs[env];
const db = {};
let sequelize;
if (process.env.DATABASE_URL_TEST) {
sequelize = new Sequelize(process.env.DATABASE_URL_TEST);
} else {
const config = {
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
host: process.env.DB_HOST,
dialect: 'postgres'
};
sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USERNAME,
process.env.DB_PASSWORD, config);
}
fs
.readdirSync(__dirname)
.filter((file) => {
const fileName = (file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js');
return fileName;
})
.forEach((file) => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
| import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
const basename = path.basename(module.filename);
const db = {};
let sequelize;
if (process.env.DATABASE_URL || process.env.DATABASE_URL_TEST) {
sequelize = new Sequelize(process.env.DATABASE_URL
|| process.env.DATABASE_URL_TEST);
} else {
const config = {
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
host: process.env.DB_HOST,
dialect: 'postgres'
};
sequelize = new Sequelize(process.env.DB_DATABASE, process.env.DB_USERNAME,
process.env.DB_PASSWORD, config);
}
fs
.readdirSync(__dirname)
.filter((file) => {
const fileName = (file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js');
return fileName;
})
.forEach((file) => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
module.exports = db;
| Fix app crash on travis CI and heroku | Fix app crash on travis CI and heroku
| JavaScript | apache-2.0 | larrystone/BC-26-More-Recipes,larrystone/BC-26-More-Recipes | ---
+++
@@ -1,17 +1,15 @@
import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
-// import configs from '../config/config';
const basename = path.basename(module.filename);
-// const env = process.env.NODE_ENV || 'development';
-// const config = configs[env];
const db = {};
let sequelize;
-if (process.env.DATABASE_URL_TEST) {
- sequelize = new Sequelize(process.env.DATABASE_URL_TEST);
+if (process.env.DATABASE_URL || process.env.DATABASE_URL_TEST) {
+ sequelize = new Sequelize(process.env.DATABASE_URL
+ || process.env.DATABASE_URL_TEST);
} else {
const config = {
username: process.env.DB_USERNAME,
@@ -44,6 +42,5 @@
});
db.sequelize = sequelize;
-db.Sequelize = Sequelize;
module.exports = db; |
47135b7ca6c91ff4ae7f714d316f15a6ed3d3cc6 | index.js | index.js | 'use strict';
var color = require('color')
, hex = require('text-hex');
/**
* Generate a color for a given name. But be reasonably smart about it by
* understanding name spaces and coloring each namespace a bit lighter so they
* still have the same base color as the root.
*
* @param {String} name The namespace
* @returns {String} color
* @api private
*/
module.exports = function colorspace(namespace, delimiter) {
namespace = namespace.split(delimiter || ':');
for (var base = hex(namespace[0]), i = 0, l = namespace.length - 1; i < l; i++) {
base = color(base)
.mix(color(hex(namespace[i + 1])))
.saturate(1)
.hex();
}
return base;
};
| 'use strict';
var color = require('color')
, hex = require('text-hex');
/**
* Generate a color for a given name. But be reasonably smart about it by
* understanding name spaces and coloring each namespace a bit lighter so they
* still have the same base color as the root.
*
* @param {String} name The namespace
* @returns {String} color
* @api private
*/
module.exports = function colorspace(namespace, delimiter) {
var split = namespace.split(delimiter || ':');
var base = hex(split[0]);
if (!split.length) return base;
for (var i = 0, l = split.length - 1; i < l; i++) {
base = color(base)
.mix(color(hex(split[i + 1])))
.saturate(1)
.hex();
}
return base;
};
| Return early when no namespace is used | [minor] Return early when no namespace is used
| JavaScript | mit | bigpipe/colorspace | ---
+++
@@ -13,11 +13,14 @@
* @api private
*/
module.exports = function colorspace(namespace, delimiter) {
- namespace = namespace.split(delimiter || ':');
+ var split = namespace.split(delimiter || ':');
+ var base = hex(split[0]);
- for (var base = hex(namespace[0]), i = 0, l = namespace.length - 1; i < l; i++) {
+ if (!split.length) return base;
+
+ for (var i = 0, l = split.length - 1; i < l; i++) {
base = color(base)
- .mix(color(hex(namespace[i + 1])))
+ .mix(color(hex(split[i + 1])))
.saturate(1)
.hex();
} |
7b9c2ef3a0b044ea2697848a7f91c9e380878934 | index.js | index.js | var argv = require( 'minimist' )( process.argv.slice( 2 ) );
var downloadSite = require( './download' );
if ( ! argv.site ) {
console.error( 'Provide a site with the --site option' );
process.exit( 1 );
}
var wpcom = require( 'wpcom' )();
var site = wpcom.site( argv.site );
// TODO: verify we connected
if ( argv.download ) {
downloadSite( site );
}
| var parseArgs = require( 'minimist' );
var downloadSite = require( './download' );
var argv = parseArgs( process.argv.slice( 2 ), {
boolean: true
} );
if ( ! argv.site ) {
console.error( 'Provide a site with the --site option' );
process.exit( 1 );
}
if ( ! argv.download && ! argv.upload ) {
console.error( 'Either --download or --upload are required' );
process.exit( 1 );
}
var wpcom = require( 'wpcom' )();
var site = wpcom.site( argv.site );
// TODO: verify we connected
if ( argv.download ) {
downloadSite( site );
}
| Make sure --download or --upload are specified | Make sure --download or --upload are specified
| JavaScript | mit | sirbrillig/wordpress-warp,sirbrillig/wordpress-warp | ---
+++
@@ -1,8 +1,17 @@
-var argv = require( 'minimist' )( process.argv.slice( 2 ) );
+var parseArgs = require( 'minimist' );
var downloadSite = require( './download' );
+
+var argv = parseArgs( process.argv.slice( 2 ), {
+ boolean: true
+} );
if ( ! argv.site ) {
console.error( 'Provide a site with the --site option' );
+ process.exit( 1 );
+}
+
+if ( ! argv.download && ! argv.upload ) {
+ console.error( 'Either --download or --upload are required' );
process.exit( 1 );
}
|
187269cfc24909ee5c21d33d9680f7d1467ab03b | app/components/Settings/components/notifications-panel.js | app/components/Settings/components/notifications-panel.js | import React from 'react';
import PropTypes from 'prop-types';
import { RadioGroup, Radio, Checkbox } from '@blueprintjs/core';
import { NotificationTypes } from 'enums';
const NotificationsPanel = ({
notificationType,
onSettingsChange,
setNotificationType,
continuousMode,
setContinuousMode
}) => (
<div className="mt-1">
<label className="pt-label">Continuous Mode</label>
<Checkbox
label="Ask for confirmation before moving onto the next phase"
checked={continuousMode}
onChange={e => {
onSettingsChange(
'system.continuousMode',
e.target.checked,
setContinuousMode
);
}}
/>
<RadioGroup
label="Notify me of..."
onChange={e =>
onSettingsChange(
'system.notificationType',
e.target.value,
setNotificationType
)}
selectedValue={notificationType}
>
<Radio
label="Phase changes when window is not active"
value={NotificationTypes.PHASE_CHANGES_NO_WINDOW}
/>
<Radio
label="Phase changes all the time"
value={NotificationTypes.PHASE_CHANGES_ALL}
/>
</RadioGroup>
</div>
);
NotificationsPanel.propTypes = {
notificationType: PropTypes.string.isRequired,
onSettingsChange: PropTypes.func.isRequired,
setNotificationType: PropTypes.func.isRequired,
continuousMode: PropTypes.bool.isRequired,
setContinuousMode: PropTypes.func.isRequired
};
export default NotificationsPanel;
| import React from 'react';
import PropTypes from 'prop-types';
import { RadioGroup, Radio, Checkbox } from '@blueprintjs/core';
import { NotificationTypes } from 'enums';
const NotificationsPanel = ({
notificationType,
onSettingsChange,
setNotificationType,
continuousMode,
setContinuousMode
}) => (
<div className="mt-1">
<Checkbox
label="Ask for confirmation before moving onto the next phase"
checked={continuousMode}
onChange={e => {
onSettingsChange(
'system.continuousMode',
e.target.checked,
setContinuousMode
);
}}
/>
<RadioGroup
label="Notify me of..."
onChange={e =>
onSettingsChange(
'system.notificationType',
e.target.value,
setNotificationType
)}
selectedValue={notificationType}
>
<Radio
label="Phase changes when window is not active"
value={NotificationTypes.PHASE_CHANGES_NO_WINDOW}
/>
<Radio
label="Phase changes all the time"
value={NotificationTypes.PHASE_CHANGES_ALL}
/>
</RadioGroup>
</div>
);
NotificationsPanel.propTypes = {
notificationType: PropTypes.string.isRequired,
onSettingsChange: PropTypes.func.isRequired,
setNotificationType: PropTypes.func.isRequired,
continuousMode: PropTypes.bool.isRequired,
setContinuousMode: PropTypes.func.isRequired
};
export default NotificationsPanel;
| Remove label and just show checkbox | feat: Remove label and just show checkbox
| JavaScript | mit | builtwithluv/ZenFocus,builtwithluv/ZenFocus | ---
+++
@@ -12,7 +12,6 @@
setContinuousMode
}) => (
<div className="mt-1">
- <label className="pt-label">Continuous Mode</label>
<Checkbox
label="Ask for confirmation before moving onto the next phase"
checked={continuousMode} |
dbd5d56fe2fa39c89d063bfbbf0f0fdfedae8168 | packages/lesswrong/server/mapsUtils.js | packages/lesswrong/server/mapsUtils.js | import { getSetting } from 'meteor/vulcan:core';
import googleMaps from '@google/maps'
const googleMapsApiKey = getSetting('googleMaps.serverApiKey', null)
let googleMapsClient = null
if (googleMapsApiKey) {
googleMapsClient = googleMaps.createClient({
key: googleMapsApiKey,
Promise: Promise
});
} else {
// eslint-disable-next-line no-console
console.log("No Google maps API key provided, please provide one for proper geocoding")
}
export async function getLocalTime(time, googleLocation) {
try {
const { geometry: { location } } = googleLocation
const apiResponse = await googleMapsClient.timezone({location, timestamp: new Date(time)}).asPromise()
const { json: { dstOffset, rawOffset } } = apiResponse //dstOffset and rawOffset are in the unit of seconds
const localTimestamp = new Date(time).getTime() + ((dstOffset + rawOffset)*1000) // Translate seconds to milliseconds
return new Date(localTimestamp)
} catch(err) {
// eslint-disable-next-line no-console
console.error("Error in getting local time:", err)
throw err
}
}
| import { getSetting } from 'meteor/vulcan:core';
import googleMaps from '@google/maps'
const googleMapsApiKey = getSetting('googleMaps.serverApiKey', null)
let googleMapsClient = null
if (googleMapsApiKey) {
googleMapsClient = googleMaps.createClient({
key: googleMapsApiKey,
Promise: Promise
});
} else {
// eslint-disable-next-line no-console
console.log("No Server-side Google maps API key provided, please provide one for proper timezone handling")
}
export async function getLocalTime(time, googleLocation) {
if (!googleMapsClient) {
// eslint-disable-next-line no-console
console.log("No Server-side Google Maps API key provided, can't resolve local time")
return null
}
try {
const { geometry: { location } } = googleLocation
const apiResponse = await googleMapsClient.timezone({location, timestamp: new Date(time)}).asPromise()
const { json: { dstOffset, rawOffset } } = apiResponse //dstOffset and rawOffset are in the unit of seconds
const localTimestamp = new Date(time).getTime() + ((dstOffset + rawOffset)*1000) // Translate seconds to milliseconds
return new Date(localTimestamp)
} catch(err) {
// eslint-disable-next-line no-console
console.error("Error in getting local time:", err)
throw err
}
}
| Improve error handling without API key | Improve error handling without API key
| JavaScript | mit | Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope | ---
+++
@@ -10,10 +10,15 @@
});
} else {
// eslint-disable-next-line no-console
- console.log("No Google maps API key provided, please provide one for proper geocoding")
+ console.log("No Server-side Google maps API key provided, please provide one for proper timezone handling")
}
export async function getLocalTime(time, googleLocation) {
+ if (!googleMapsClient) {
+ // eslint-disable-next-line no-console
+ console.log("No Server-side Google Maps API key provided, can't resolve local time")
+ return null
+ }
try {
const { geometry: { location } } = googleLocation
const apiResponse = await googleMapsClient.timezone({location, timestamp: new Date(time)}).asPromise() |
4961e4c984cee1c13f15966b670fccb0360391ee | src/main/web/js/app/pym-interactive.js | src/main/web/js/app/pym-interactive.js |
$(function() {
$('div.pym-interactive').each(function(index, element) {
new pym.Parent($(element).attr('id'), $(element).data('url'));
});
});
|
$(function() {
$('div.pym-interactive').each(function(index, element) {
var pymParent = new pym.Parent($(element).attr('id'), $(element).data('url'));
pymParent.onMessage('height', function(height) {
addIframeHeightToEmbedCode($(this), height);
});
});
});
function addIframeHeightToEmbedCode(container, height) {
var interactiveId = container.attr('id');
var input = document.getElementById("embed-" + interactiveId);
input.value = buildEmbedCode(input.value, height);
}
function buildEmbedCode(embedCode, height) {
// replace any existing height attributes caused by multiple
// re-sizes when child page uses JS to hide on page elements
if (embedCode.indexOf("height") !== -1) {
return embedCode.replace(/height=(\"|')[^(\"|')]*(\"|') /, 'height="' + height + 'px" ')
}
return embedCode.substr(0, 7) + ' height="' + height + 'px" ' + embedCode.substr(8, embedCode.length);
}
| Build embed code including height attrbute on height message from pym child | Build embed code including height attrbute on height message from pym child
| JavaScript | mit | ONSdigital/babbage,ONSdigital/babbage,ONSdigital/babbage,ONSdigital/babbage | ---
+++
@@ -1,6 +1,25 @@
$(function() {
$('div.pym-interactive').each(function(index, element) {
- new pym.Parent($(element).attr('id'), $(element).data('url'));
+ var pymParent = new pym.Parent($(element).attr('id'), $(element).data('url'));
+ pymParent.onMessage('height', function(height) {
+ addIframeHeightToEmbedCode($(this), height);
+ });
});
});
+
+function addIframeHeightToEmbedCode(container, height) {
+ var interactiveId = container.attr('id');
+ var input = document.getElementById("embed-" + interactiveId);
+ input.value = buildEmbedCode(input.value, height);
+}
+
+function buildEmbedCode(embedCode, height) {
+ // replace any existing height attributes caused by multiple
+ // re-sizes when child page uses JS to hide on page elements
+ if (embedCode.indexOf("height") !== -1) {
+ return embedCode.replace(/height=(\"|')[^(\"|')]*(\"|') /, 'height="' + height + 'px" ')
+ }
+
+ return embedCode.substr(0, 7) + ' height="' + height + 'px" ' + embedCode.substr(8, embedCode.length);
+} |
91c61c8d9ad1fc6ed7561f95de347334ea387f04 | app/assets/javascripts/frontend.js | app/assets/javascripts/frontend.js | // Frontend manifest
//= require transactions
//= require media-player-loader
//= require checkbox-filter
//= require support
//= require live-search
//= require shared_mustache
//= require templates
//= require track-external-links
//= require search
| // Frontend manifest
// Note: The ordering of these JavaScript includes matters.
//= require transactions
//= require media-player-loader
//= require checkbox-filter
//= require support
//= require live-search
//= require shared_mustache
//= require templates
//= require track-external-links
//= require search
| Add comment: explain JS deps ordering matters | Add comment: explain JS deps ordering matters
Make it clear to others looking at the frontend.js file that the
ordering of the JS includes matters.
| JavaScript | mit | alphagov/frontend,alphagov/frontend,alphagov/frontend,alphagov/frontend | ---
+++
@@ -1,4 +1,5 @@
// Frontend manifest
+// Note: The ordering of these JavaScript includes matters.
//= require transactions
//= require media-player-loader
//= require checkbox-filter |
e781a6a037ae7f7888b84d6f83801305bf2d1205 | plugins/auth/flat_file.js | plugins/auth/flat_file.js | // Auth against a flat file
exports.register = function () {
this.inherits('auth/auth_base');
}
exports.hook_capabilities = function (next, connection) {
// don't allow AUTH unless private IP or encrypted
if (!net_utils.is_rfc1918(connection.remote_ip) && !connection.using_tls) return next();
var config = this.config.get('auth_flat_file.ini');
var methods = (config.core && config.core.methods ) ? config.core.methods.split(',') : null;
if(methods && methods.length > 0) {
connection.capabilities.push('AUTH ' + methods.join(' '));
connection.notes.allowed_auth_methods = methods;
}
next();
};
exports.get_plain_passwd = function (user, cb) {
var config = this.config.get('auth_flat_file.ini');
if (config.users[user]) {
return cb(config.users[user]);
}
return cb();
}
| // Auth against a flat file
var net_utils = require('./net_utils');
exports.register = function () {
this.inherits('auth/auth_base');
}
exports.hook_capabilities = function (next, connection) {
// don't allow AUTH unless private IP or encrypted
if (!net_utils.is_rfc1918(connection.remote_ip) && !connection.using_tls) return next();
var config = this.config.get('auth_flat_file.ini');
var methods = (config.core && config.core.methods ) ? config.core.methods.split(',') : null;
if(methods && methods.length > 0) {
connection.capabilities.push('AUTH ' + methods.join(' '));
connection.notes.allowed_auth_methods = methods;
}
next();
};
exports.get_plain_passwd = function (user, cb) {
var config = this.config.get('auth_flat_file.ini');
if (config.users[user]) {
return cb(config.users[user]);
}
return cb();
}
| Fix ReferenceError: net_utils is not defined reported on IRC | Fix ReferenceError: net_utils is not defined reported on IRC | JavaScript | mit | craigslist/Haraka,hiteshjoshi/my-haraka-config,AbhilashSrivastava/haraka_sniffer,Synchro/Haraka,danucalovj/Haraka,hatsebutz/Haraka,typingArtist/Haraka,hatsebutz/Haraka,pedroaxl/Haraka,craigslist/Haraka,MignonCornet/Haraka,MignonCornet/Haraka,fredjean/Haraka,MignonCornet/Haraka,typingArtist/Haraka,Dexus/Haraka,slattery/Haraka,jaredj/Haraka,msimerson/Haraka,AbhilashSrivastava/haraka_sniffer,Synchro/Haraka,baudehlo/Haraka,danucalovj/Haraka,hiteshjoshi/my-haraka-config,baudehlo/Haraka,Dexus/Haraka,baudehlo/Haraka,abhas/Haraka,fredjean/Haraka,zombified/Haraka,jaredj/Haraka,bsmr-x-script/Haraka,AbhilashSrivastava/haraka_sniffer,slattery/Haraka,hatsebutz/Haraka,niteoweb/Haraka,hiteshjoshi/my-haraka-config,jjz/Haraka,DarkSorrow/Haraka,abhas/Haraka,AbhilashSrivastava/haraka_sniffer,typingArtist/Haraka,slattery/Haraka,smfreegard/Haraka,smfreegard/Haraka,pedroaxl/Haraka,Dexus/Haraka,haraka/Haraka,Dexus/Haraka,bsmr-x-script/Haraka,typingArtist/Haraka,bsmr-x-script/Haraka,jjz/Haraka,jjz/Haraka,DarkSorrow/Haraka,Synchro/Haraka,fredjean/Haraka,msimerson/Haraka,jaredj/Haraka,jaredj/Haraka,MignonCornet/Haraka,danucalovj/Haraka,zombified/Haraka,niteoweb/Haraka,smfreegard/Haraka,niteoweb/Haraka,haraka/Haraka,zombified/Haraka,smfreegard/Haraka,DarkSorrow/Haraka,fatalbanana/Haraka,DarkSorrow/Haraka,msimerson/Haraka,haraka/Haraka,bsmr-x-script/Haraka,hatsebutz/Haraka,abhas/Haraka,msimerson/Haraka,fatalbanana/Haraka,fatalbanana/Haraka,craigslist/Haraka,danucalovj/Haraka,jjz/Haraka,Synchro/Haraka,craigslist/Haraka,pedroaxl/Haraka,fatalbanana/Haraka,haraka/Haraka,zombified/Haraka,slattery/Haraka,baudehlo/Haraka | ---
+++
@@ -1,4 +1,5 @@
// Auth against a flat file
+var net_utils = require('./net_utils');
exports.register = function () {
this.inherits('auth/auth_base'); |
67830a4214f33ee1e9c94fdfc5dd27747563579e | src/app/api/Actions.js | src/app/api/Actions.js | import {
REQUESTING,
RECEIVE_TOP_RATED,
RECEIVE_NOW_SHOWING,
RECEIVE_POPULAR
} from "./ActionTypes"
export function request() {
return {
type: REQUESTING
}
}
export function receivedNowShowing(data) {
return {
type: RECEIVE_NOW_SHOWING,
data
}
}
export function receivedPopular(data) {
return {
type: RECEIVE_NOW_SHOWING,
data
}
}
export function receivedTopRated(data) {
return {
type: RECEIVE_NOW_SHOWING,
data
}
}
export function error(error) {
return {
type: API_FAILURE,
error
}
}
| import {
REQUESTING,
RECEIVE_TOP_RATED,
RECEIVE_NOW_SHOWING,
RECEIVE_POPULAR
} from "./ActionTypes"
export function request() {
return {
type: REQUESTING
}
}
export function receivedNowShowing(data) {
return {
type: RECEIVE_NOW_SHOWING,
data
}
}
export function receivedPopular(data) {
return {
type: RECEIVE_POPULAR,
data
}
}
export function receivedTopRated(data) {
return {
type: RECEIVE_TOP_RATED,
data
}
}
export function error(error) {
return {
type: API_FAILURE,
error
}
}
| Use proper action type for different movies | Use proper action type for different movies
| JavaScript | mit | Guru107/test_app | ---
+++
@@ -20,14 +20,14 @@
export function receivedPopular(data) {
return {
- type: RECEIVE_NOW_SHOWING,
+ type: RECEIVE_POPULAR,
data
}
}
export function receivedTopRated(data) {
return {
- type: RECEIVE_NOW_SHOWING,
+ type: RECEIVE_TOP_RATED,
data
}
} |
b0bc5f4bbef6c297119146f3528bfdb15138a4fd | test/minify/config.js | test/minify/config.js | // just to make sure this file is being minified properly
var foobar = (function() {
var anotherLongVariableName = "foo";
var baz = "baz";
return anotherLongVariableName + baz;
}());
System.paths.foo = "bar";
| // just to make sure this file is being minified properly
// this code is a noop meant to force UglifyJS to include the
// `anotherLongVariableName` (with the mangle flag off) in the minified code
// for testing purposes
var anotherLongVariableName;
function funcName(firstLongName, lastLongName) {
anotherLongVariableName = firstLongName + lastLongName;
}
if (anotherLongVariableName == "foo") { console.log(); };
System.paths.foo = "bar";
| Adjust code to workaround UglifyJS dead code removal | Adjust code to workaround UglifyJS dead code removal
| JavaScript | mit | stealjs/steal-tools,stealjs/steal-tools | ---
+++
@@ -1,8 +1,14 @@
// just to make sure this file is being minified properly
-var foobar = (function() {
- var anotherLongVariableName = "foo";
- var baz = "baz";
- return anotherLongVariableName + baz;
-}());
+
+// this code is a noop meant to force UglifyJS to include the
+// `anotherLongVariableName` (with the mangle flag off) in the minified code
+// for testing purposes
+var anotherLongVariableName;
+
+function funcName(firstLongName, lastLongName) {
+ anotherLongVariableName = firstLongName + lastLongName;
+}
+
+if (anotherLongVariableName == "foo") { console.log(); };
System.paths.foo = "bar"; |
5124396ada1aa788d80403b4056c675b6324ba34 | src/client/app/boot.js | src/client/app/boot.js | import Application from './components/application';
import logger from 'debug';
import React from 'react';
import { Provider } from 'react-redux';
import startRouter from './router';
import { configureStore } from './store.js';
import en from './locales/en';
import fr from './locales/fr';
const debug = logger('app:boot');
export default function boot(data) {
debug('Prepare application to boot.');
debug('Get localization strings based on given locale.');
const locale = data.locale;
const localesLoader = {en, fr};
let phrases = localesLoader[locale];
if (!phrases) {
debug(`Localized strings could not be found for locale ${locale}, `
`using EN locale instead.`);
phrases = localesLoader.en;
}
// Initialize polyglot object with phrases.
const Polyglot = require('node-polyglot');
const polyglot = new Polyglot({locale: locale});
polyglot.extend(phrases);
const store = configureStore(data);
const history = startRouter(store);
const application = (
<Provider store={store}>
<Application />
</Provider>
);
debug('Application configured, ready to start.');
polyglot.t('toto');
return {
router: history,
store,
t: polyglot.t.bind(polyglot),
application,
};
}
| import Application from './components/application';
import logger from 'debug';
import React from 'react';
import { Provider } from 'react-redux';
import startRouter from './router';
import { configureStore } from './store.js';
import en from './locales/en';
import fr from './locales/fr';
const debug = logger('app:boot');
export default function boot(data) {
debug('Prepare application to boot.');
debug('Get localization strings based on given locale.');
const locale = data.locale;
const localesLoader = {en, fr};
let phrases = localesLoader[locale];
if (!phrases) {
debug(`Localized strings could not be found for locale ${locale}, `
`using EN locale instead.`);
phrases = localesLoader.en;
}
// Initialize polyglot object with phrases.
const Polyglot = require('node-polyglot');
const polyglot = new Polyglot({
allowMissing: process.env.NODE_ENV === 'production',
locale: locale,
});
polyglot.extend(phrases);
const store = configureStore(data);
const history = startRouter(store);
const application = (
<Provider store={store}>
<Application />
</Provider>
);
debug('Application configured, ready to start.');
polyglot.t('toto');
return {
router: history,
store,
t: polyglot.t.bind(polyglot),
application,
};
}
| Set allowMissing based on environment | Set allowMissing based on environment
| JavaScript | mit | jsilvestre/tasky,jsilvestre/tasky,jsilvestre/tasky | ---
+++
@@ -27,7 +27,10 @@
// Initialize polyglot object with phrases.
const Polyglot = require('node-polyglot');
- const polyglot = new Polyglot({locale: locale});
+ const polyglot = new Polyglot({
+ allowMissing: process.env.NODE_ENV === 'production',
+ locale: locale,
+ });
polyglot.extend(phrases);
const store = configureStore(data); |
5807a4997fb651adba6665ccf9f7edf1517c86d8 | test/registry.spec.js | test/registry.spec.js | import test from 'ava';
test.todo('Write test for Registry');
| import test from 'ava';
import Registry from '../src/registry';
test('Registry returns a registry', t => {
let registry = Registry([document.body]);
t.deepEqual(registry, {
current: [],
elements: [document.body],
handlers: { enter: [], exit: [] },
singles: { enter: [], exit: [] }
});
});
| Add initial tests for Registry | Add initial tests for Registry
| JavaScript | mit | kudago/in-view,camwiegert/in-view | ---
+++
@@ -1,3 +1,12 @@
import test from 'ava';
+import Registry from '../src/registry';
-test.todo('Write test for Registry');
+test('Registry returns a registry', t => {
+ let registry = Registry([document.body]);
+ t.deepEqual(registry, {
+ current: [],
+ elements: [document.body],
+ handlers: { enter: [], exit: [] },
+ singles: { enter: [], exit: [] }
+ });
+}); |
67d8f92bc99e95ec0c567250eae0f8aca5cadd76 | app/components/organization/Welcome.js | app/components/organization/Welcome.js | import React from 'react';
import PipelineIcon from '../icons/Pipeline';
class Welcome extends React.Component {
static propTypes = {
organization: React.PropTypes.string.isRequired
}
render() {
return (
<div className="center p4">
<PipelineIcon />
<h1 className="h3 m0 mt2 mb4">Create your first pipeline</h1>
<p className="mx-auto" style={{ maxWidth: "30em" }}>Pipelines define the tasks to be run on your agents. It’s best to keep each pipeline focussed on a single part of your delivery pipeline, such as testing, deployments or infrastructure. Once created, you can connect your pipeline with your source control or trigger it via the API.</p>
<p className="dark-gray">Need inspiration? See the <a target="_blank" href="https://github.com/buildkite/example-pipelines">example pipelines</a> GitHub repo.</p>
<p>
<a className="mt4 btn btn-primary bg-lime hover-white white rounded" href={`/organizations/${this.props.organization}/pipelines/new`}>New Pipeline</a>
</p>
</div>
);
}
}
export default Welcome;
| import React from 'react';
import PipelineIcon from '../icons/Pipeline';
class Welcome extends React.Component {
static propTypes = {
organization: React.PropTypes.string.isRequired
}
render() {
return (
<div className="center p4">
<PipelineIcon />
<h1 className="h3 m0 mt2 mb4">Create your first pipeline</h1>
<p className="mx-auto" style={{ maxWidth: "30em" }}>Pipelines define the tasks to be run on your agents. It’s best to keep each pipeline focussed on a single part of your delivery pipeline, such as testing, deployments or infrastructure. Once created, you can connect your pipeline with your source control or trigger it via the API.</p>
<p className="dark-gray">Need inspiration? See the <a className="blue hover-navy text-decoration-none hover-underline" target="_blank" href="https://github.com/buildkite/example-pipelines">example pipelines</a> GitHub repo.</p>
<p>
<a className="mt4 btn btn-primary bg-lime hover-white white rounded" href={`/organizations/${this.props.organization}/pipelines/new`}>New Pipeline</a>
</p>
</div>
);
}
}
export default Welcome;
| Make 'example pipelines' link the same blue link | Make 'example pipelines' link the same blue link
| JavaScript | mit | fotinakis/buildkite-frontend,buildkite/frontend,fotinakis/buildkite-frontend,buildkite/frontend | ---
+++
@@ -13,7 +13,7 @@
<PipelineIcon />
<h1 className="h3 m0 mt2 mb4">Create your first pipeline</h1>
<p className="mx-auto" style={{ maxWidth: "30em" }}>Pipelines define the tasks to be run on your agents. It’s best to keep each pipeline focussed on a single part of your delivery pipeline, such as testing, deployments or infrastructure. Once created, you can connect your pipeline with your source control or trigger it via the API.</p>
- <p className="dark-gray">Need inspiration? See the <a target="_blank" href="https://github.com/buildkite/example-pipelines">example pipelines</a> GitHub repo.</p>
+ <p className="dark-gray">Need inspiration? See the <a className="blue hover-navy text-decoration-none hover-underline" target="_blank" href="https://github.com/buildkite/example-pipelines">example pipelines</a> GitHub repo.</p>
<p>
<a className="mt4 btn btn-primary bg-lime hover-white white rounded" href={`/organizations/${this.props.organization}/pipelines/new`}>New Pipeline</a>
</p> |
ebccc846b56b4591a011666953a6ad75ef35fabc | src/components/Head.js | src/components/Head.js | import React from 'react'
export default class Head extends React.Component {
render() {
return (
<head>
<meta charSet="utf-8"/>
<meta httpEquiv="X-UA-compatible" content="IE=edge, chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="description" content="Maxime Le Conte des Floris is a web developer and open source enthusiast located in Bordeaux."/>
<meta name="author" content="Maxime Le Conte des Floris"/>
<meta name="theme-color" content="#333"/>
<title>{this.props.title}</title>
<link rel="manifest" href="/manifest.json"/>
<link rel="stylesheet" href="/styles.css"/>
</head>
)
}
}
| import React from 'react'
export default class Head extends React.Component {
render() {
return (
<head>
<meta charSet="utf-8"/>
<meta httpEquiv="X-UA-compatible" content="IE=edge, chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="description" content="Maxime Le Conte des Floris is a web developer and open source enthusiast located in Bordeaux."/>
<meta name="author" content="Maxime Le Conte des Floris"/>
<meta name="theme-color" content="#333"/>
<title>{this.props.title}</title>
<link rel="manifest" href="/manifest.json"/>
<link rel="stylesheet" type="text/css" href="/styles.css"/>
</head>
)
}
}
| Add type text/css to stylesheet | Add type text/css to stylesheet
| JavaScript | mit | mlcdf/website,mlcdf/website | ---
+++
@@ -12,7 +12,7 @@
<meta name="theme-color" content="#333"/>
<title>{this.props.title}</title>
<link rel="manifest" href="/manifest.json"/>
- <link rel="stylesheet" href="/styles.css"/>
+ <link rel="stylesheet" type="text/css" href="/styles.css"/>
</head>
)
} |
fab4325bf85c8aa4386464b09781d385b07f5c77 | src/browser_tools/chrome_new_tab_pretty.user.js | src/browser_tools/chrome_new_tab_pretty.user.js | // ==UserScript==
// @name Chrome New Tab Prettify.
// @namespace https://github.com/kilfu0701
// @version 0.1
// @description Prettify UI on Chrome new tab.
// @author kilfu0701
// @match /^http[s]?:\/\/www.google*/
// @run-at document-ready
// @include /^http[s]?:\/\/www.google*/
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant none
// ==/UserScript==
if(location.pathname === "/_/chrome/newtab") {
$('.mv-hide').hide();
}
| // ==UserScript==
// @name Chrome New Tab Prettify.
// @namespace https://github.com/kilfu0701
// @version 0.1
// @description Prettify UI on Chrome new tab.
// @author kilfu0701
// @match /^http[s]?:\/\/www.google*/
// @run-at document-ready
// @include /^http[s]?:\/\/www.google*/
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant none
// ==/UserScript==
if(location.pathname === "/_/chrome/newtab") {
$('.mv-hide').hide();
$('#lga').hide();
$('#f').hide();
}
| Hide logo and search bar in chrome new tab. | Hide logo and search bar in chrome new tab.
| JavaScript | mit | kilfu0701/thk-user-script | ---
+++
@@ -13,4 +13,6 @@
if(location.pathname === "/_/chrome/newtab") {
$('.mv-hide').hide();
+ $('#lga').hide();
+ $('#f').hide();
} |
6cf484c9a3ce5aa141363ae67c58fa94d055a105 | app/assets/javascripts/app/views/bookmarklet_view.js | app/assets/javascripts/app/views/bookmarklet_view.js | app.views.Bookmarklet = Backbone.View.extend({
separator: ' - ',
initialize: function(opts) {
// init a standalone publisher
app.publisher = new app.views.Publisher({standalone: true});
app.publisher.on('publisher:add', this._postSubmit, this);
app.publisher.on('publisher:sync', this._postSuccess, this);
app.publisher.on('publisher:error', this._postError, this);
this.param_contents = opts;
},
render: function() {
app.publisher.open();
app.publisher.setText(this._publisherContent());
return this;
},
_publisherContent: function() {
var p = this.param_contents;
if( p.content ) return p.content;
var contents = p.title + this.separator + p.url;
if( p.notes ) contents += this.separator + p.notes;
return contents;
},
_postSubmit: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_submit'));
},
_postSuccess: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_success'));
app.publisher.close();
_.delay(window.close, 2000);
},
_postError: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_error'));
}
});
| app.views.Bookmarklet = Backbone.View.extend({
separator: ' - ',
initialize: function(opts) {
// init a standalone publisher
app.publisher = new app.views.Publisher({standalone: true});
app.publisher.on('publisher:add', this._postSubmit, this);
app.publisher.on('publisher:sync', this._postSuccess, this);
app.publisher.on('publisher:error', this._postError, this);
this.param_contents = opts;
},
render: function() {
app.publisher.open();
app.publisher.setText(this._publisherContent());
return this;
},
_publisherContent: function() {
var p = this.param_contents;
if( p.content ) return p.content;
var contents = p.title + this.separator + p.url;
if( p.notes ) contents += this.separator + p.notes;
return contents;
},
_postSubmit: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_submit'));
},
_postSuccess: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_success'));
app.publisher.close();
this.$("#publisher").addClass("hidden");
_.delay(window.close, 2000);
},
_postError: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_error'));
}
});
| Make sure publisher is totally hidden in bookmarklet after post success | Make sure publisher is totally hidden in bookmarklet after post success
| JavaScript | agpl-3.0 | geraspora/diaspora,jhass/diaspora,Flaburgan/diaspora,diaspora/diaspora,Amadren/diaspora,diaspora/diaspora,geraspora/diaspora,despora/diaspora,Amadren/diaspora,Amadren/diaspora,Muhannes/diaspora,SuperTux88/diaspora,jhass/diaspora,KentShikama/diaspora,spixi/diaspora,jhass/diaspora,SuperTux88/diaspora,SuperTux88/diaspora,SuperTux88/diaspora,Muhannes/diaspora,Muhannes/diaspora,KentShikama/diaspora,geraspora/diaspora,despora/diaspora,spixi/diaspora,geraspora/diaspora,Muhannes/diaspora,Amadren/diaspora,despora/diaspora,diaspora/diaspora,diaspora/diaspora,Flaburgan/diaspora,KentShikama/diaspora,KentShikama/diaspora,despora/diaspora,spixi/diaspora,jhass/diaspora,spixi/diaspora,Flaburgan/diaspora,Flaburgan/diaspora | ---
+++
@@ -35,6 +35,7 @@
_postSuccess: function(evt) {
this.$('h4').text(Diaspora.I18n.t('bookmarklet.post_success'));
app.publisher.close();
+ this.$("#publisher").addClass("hidden");
_.delay(window.close, 2000);
},
|
829082a9fdb07be6892b9fc552e874e9b1eeb81c | addon/components/data-visual.js | addon/components/data-visual.js | import Ember from 'ember';
import layout from '../templates/components/data-visual';
import Stage from '../system/stage';
export default Ember.Component.extend({
classNames: [ 'data-visual' ],
layout,
width: 300,
height: 150,
stage: null,
initializeGraphicsContext() {
var element = this.element;
var fragment = document.createDocumentFragment();
Stage.stages.forEach(stage => {
fragment.appendChild(document.createComment(stage));
});
element.insertBefore(fragment, element.firstChild);
this.set('stage', Stage.create({ element }));
this.measure();
},
measure() {
this.set('width', this.$().width());
this.set('height', this.$().height());
},
didInsertElement() {
Ember.$(window).on(`resize.${this.get('elementId')}`, Ember.run.bind(this, this.measure));
Ember.run.scheduleOnce('render', this, this.initializeGraphicsContext);
},
willDestroyElement() {
Ember.$(window).off(`resize.${this.get('elementId')}`);
}
});
| import Ember from 'ember';
import Stage from '../system/stage';
export default Ember.Component.extend({
classNames: [ 'data-visual' ],
width: 300,
height: 150,
stage: null,
initializeGraphicsContext() {
var element = this.element;
var fragment = document.createDocumentFragment();
Stage.stages.forEach(stage => {
fragment.appendChild(document.createComment(stage));
});
element.insertBefore(fragment, element.firstChild);
this.set('stage', Stage.create({ element }));
this.measure();
},
measure() {
this.set('width', this.$().width());
this.set('height', this.$().height());
},
didInsertElement() {
Ember.$(window).on(`resize.${this.get('elementId')}`, Ember.run.bind(this, this.measure));
Ember.run.scheduleOnce('render', this, this.initializeGraphicsContext);
},
willDestroyElement() {
Ember.$(window).off(`resize.${this.get('elementId')}`);
}
});
| Remove explicit layout; too eager | Remove explicit layout; too eager | JavaScript | mit | ming-codes/ember-cli-d3,ming-codes/ember-cli-d3 | ---
+++
@@ -1,11 +1,9 @@
import Ember from 'ember';
-import layout from '../templates/components/data-visual';
import Stage from '../system/stage';
export default Ember.Component.extend({
classNames: [ 'data-visual' ],
- layout,
width: 300,
height: 150, |
f073042945f2f876cccc35c59c4eff0b0cfb4535 | app/assets/javascripts/bootstrap-dropdown-submenu.js | app/assets/javascripts/bootstrap-dropdown-submenu.js | $(document).ready(function () {
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function (event) {
event.preventDefault();
event.stopPropagation();
$(this).parent().addClass('open');
var menu = $(this).parent().find("ul");
var menupos = menu.offset();
if ((menupos.left + menu.width()) + 30 > $(window).width()) {
var newpos = -menu.width();
} else {
var newpos = $(this).parent().width();
}
menu.css({left: newpos});
});
});
| $(document).ready(function () {
function openSubMenu(event) {
if (this.pathname === '/') {
event.preventDefault();
}
event.stopPropagation();
$(this).parent().addClass('open');
var menu = $(this).parent().find("ul");
var menupos = menu.offset();
if ((menupos.left + menu.width()) + 30 > $(window).width()) {
var newpos = -menu.width();
} else {
var newpos = $(this).parent().width();
}
menu.css({left: newpos});
}
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', openSubMenu).on('mouseenter', openSubMenu);
});
| Enable menu access on hover and links from section titles | Enable menu access on hover and links from section titles
| JavaScript | bsd-3-clause | openHPI/codeocean,openHPI/codeocean,openHPI/codeocean,openHPI/codeocean,openHPI/codeocean,openHPI/codeocean | ---
+++
@@ -1,6 +1,9 @@
$(document).ready(function () {
- $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function (event) {
- event.preventDefault();
+
+ function openSubMenu(event) {
+ if (this.pathname === '/') {
+ event.preventDefault();
+ }
event.stopPropagation();
$(this).parent().addClass('open');
@@ -13,5 +16,7 @@
var newpos = $(this).parent().width();
}
menu.css({left: newpos});
- });
+ }
+
+ $('ul.dropdown-menu [data-toggle=dropdown]').on('click', openSubMenu).on('mouseenter', openSubMenu);
}); |
70b62a39c353ff3ebe4847868feb24907d27cea3 | app/assets/javascripts/lga_filter.js | app/assets/javascripts/lga_filter.js | $(function() {
$('#lga_filter').keyup(function(ev) {
var list = $('#lga_list');
var filter = $(this).val();
if (filter === '') {
// Show all when the filter is cleared
list.find('div.lga').show();
} else {
// Hide all LGAs that don't match the filter
var filterRegexp = new RegExp(filter, 'i');
list.find('div.lga').each(function(index, lga_element) {
var name = $(lga_element).data('name');
$(lga_element).toggle(filterRegexp.test(name));
});
}
if(ev.which === 13) {
var visible = list.find('div.lga:visible');
if (visible.length === 1) {
window.location.href = visible.find('a.resource-title').attr('href');
}
}
});
});
| $(function() {
function strip(from) {
if(from !== undefined) {
from = from.replace(/^\s+/, '');
for (var i = from.length - 1; i >= 0; i--) {
if (/\S/.test(from.charAt(i))) {
from = from.substring(0, i + 1);
break;
}
}
return from;
} else {
""
}
}
function filter(ev) {
var list = $('#lga_list');
var filter = strip($('#lga_filter').val());
if (filter === '') {
// Show all when the filter is cleared
list.find('div.lga').show();
} else {
// Hide all LGAs that don't match the filter
var filterRegexp = new RegExp(filter, 'i');
list.find('div.lga').each(function(index, lga_element) {
var name = $(lga_element).data('name');
$(lga_element).toggle(filterRegexp.test(name));
});
}
if(ev !== undefined) {
if(ev.which === 13) {
var visible = list.find('div.lga:visible');
if (visible.length === 1) {
window.location.href = visible.find('a.resource-title').attr('href');
}
}
}
}
$('#lga_filter').keyup(filter);
filter();
});
| Fix filter bugs for council list filter | Fix filter bugs for council list filter
| JavaScript | apache-2.0 | NSWPlanning/data-verification-tool,NSWPlanning/data-verification-tool,NSWPlanning/data-verification-tool | ---
+++
@@ -1,7 +1,22 @@
$(function() {
- $('#lga_filter').keyup(function(ev) {
+ function strip(from) {
+ if(from !== undefined) {
+ from = from.replace(/^\s+/, '');
+ for (var i = from.length - 1; i >= 0; i--) {
+ if (/\S/.test(from.charAt(i))) {
+ from = from.substring(0, i + 1);
+ break;
+ }
+ }
+ return from;
+ } else {
+ ""
+ }
+ }
+
+ function filter(ev) {
var list = $('#lga_list');
- var filter = $(this).val();
+ var filter = strip($('#lga_filter').val());
if (filter === '') {
// Show all when the filter is cleared
@@ -15,11 +30,16 @@
});
}
- if(ev.which === 13) {
- var visible = list.find('div.lga:visible');
- if (visible.length === 1) {
- window.location.href = visible.find('a.resource-title').attr('href');
+ if(ev !== undefined) {
+ if(ev.which === 13) {
+ var visible = list.find('div.lga:visible');
+ if (visible.length === 1) {
+ window.location.href = visible.find('a.resource-title').attr('href');
+ }
}
}
- });
+ }
+
+ $('#lga_filter').keyup(filter);
+ filter();
}); |
10ce33fdc1035c764f27c69562b8f2a409e419fa | src/server/routes.js | src/server/routes.js | const listenerUser = require ('./listenerUser');
const listenerApp = require ('./listenerApp');
// Initialize routes.
function init (app) {
listenerUser.init ();
listenerApp.init ();
app.post ('/api/login', listenerUser.login);
app.post ('/api/logout', listenerUser.logout);
app.get ('/api/verifylogin', listenerUser.verifyLogin);
app.post ('/api/register', listenerUser.register);
app.get ('/api/profile', isAuthenticated, listenerUser.getProfile);
app.post ('/api/profile', isAuthenticated, listenerUser.updateProfile);
app.get ('/api/polls', listenerApp.getPolls);
app.get ('/api/polls/:_id', isAuthenticated, listenerApp.getPoll);
app.post ('/api/polls', isAuthenticated, listenerApp.addPoll);
app.post ('/api/polls/:_id', isAuthenticated, listenerApp.updatePoll);
app.delete ('/api/polls/:_id', isAuthenticated, listenerApp.deletePoll);
app.post ('/api/polls/:_id/votes/:choice', listenerApp.vote);
}
// authenticate, if passing continue, otherwise return 401 (auth failure)
function isAuthenticated (req, res, next) {
if (req.isAuthenticated ()) {
next ();
}
res.status (401).json ({});
}
exports.init = init;
| const listenerUser = require ('./listenerUser');
const listenerApp = require ('./listenerApp');
// Initialize routes.
function init (app) {
listenerUser.init ();
listenerApp.init ();
app.post ('/api/login', listenerUser.login);
app.post ('/api/logout', listenerUser.logout);
app.get ('/api/verifylogin', listenerUser.verifyLogin);
app.post ('/api/register', listenerUser.register);
app.get ('/api/profile', isAuthenticated, listenerUser.getProfile);
app.post ('/api/profile', isAuthenticated, listenerUser.updateProfile);
app.get ('/api/polls', listenerApp.getPolls);
app.get ('/api/polls/:_id', isAuthenticated, listenerApp.getPoll);
app.post ('/api/polls', isAuthenticated, listenerApp.addPoll);
app.post ('/api/polls/:_id', isAuthenticated, listenerApp.updatePoll);
app.delete ('/api/polls/:_id', isAuthenticated, listenerApp.deletePoll);
app.post ('/api/polls/:_id/votes/:choice', listenerApp.vote);
}
// authenticate, if passing continue, otherwise return 401 (auth failure)
function isAuthenticated (req, res, next) {
if (req.isAuthenticated ()) {
return next ();
} else {
return res.status (401).json ({});
}
}
exports.init = init;
| Correct return handling for authentication middleware function | Correct return handling for authentication middleware function
| JavaScript | mit | fcc-joemcintyre/pollster,fcc-joemcintyre/pollster,fcc-joemcintyre/pollster | ---
+++
@@ -23,9 +23,10 @@
// authenticate, if passing continue, otherwise return 401 (auth failure)
function isAuthenticated (req, res, next) {
if (req.isAuthenticated ()) {
- next ();
+ return next ();
+ } else {
+ return res.status (401).json ({});
}
- res.status (401).json ({});
}
exports.init = init; |
344b2d6018ba63f139da4529978587e209d9566b | lib/run_cmd.js | lib/run_cmd.js | 'use strict'
var path = require('path')
var async = require('async')
var config = require('./config')
var child_process = require('child_process')
function runCmd (cwd, argv) {
var scripts = argv._.slice(1)
var pkg = require(path.join(cwd, 'package.json'))
if (!scripts.length) {
var availableScripts = Object.keys(pkg.scripts || [])
console.log('Available scripts: ' + availableScripts.join(', '))
return
}
var env = Object.create(process.env)
env.PATH = [path.join(cwd, 'node_modules/.bin'), process.env.PATH].join(path.delimiter)
async.mapSeries(scripts, function execScript (scriptName, cb) {
var scriptCmd = pkg.scripts[scriptName]
if (!scriptCmd) return cb(null, null)
var childProcess = child_process.spawn(config.sh, [config.shFlag, scriptCmd], {
env: env,
stdio: 'inherit'
})
childProcess.on('close', cb.bind(null, null))
childProcess.on('error', cb)
}, function (err, statuses) {
if (err) throw err
var info = scripts.map(function (script, i) {
return script + ' exited with status ' + statuses[i]
}).join('\n')
console.log(info)
var success = statuses.every(function (code) { return code === 0 })
process.exit(success | 0)
})
}
module.exports = runCmd
| 'use strict'
var path = require('path')
var async = require('async')
var config = require('./config')
var child_process = require('child_process')
var assign = require('object-assign')
function runCmd (cwd, argv) {
var scripts = argv._.slice(1)
var pkg = require(path.join(cwd, 'package.json'))
if (!scripts.length) {
var availableScripts = Object.keys(pkg.scripts || [])
console.log('Available scripts: ' + availableScripts.join(', '))
return
}
var env = assign({}, process.env, {
PATH: [
path.join(cwd, 'node_modules/.bin'), process.env.PATH
].join(path.delimiter)
})
async.mapSeries(scripts, function execScript (scriptName, cb) {
var scriptCmd = pkg.scripts[scriptName]
if (!scriptCmd) return cb(null, null)
var childProcess = child_process.spawn(config.sh, [config.shFlag, scriptCmd], {
env: env,
stdio: 'inherit'
})
childProcess.on('close', cb.bind(null, null))
childProcess.on('error', cb)
}, function (err, statuses) {
if (err) throw err
var info = scripts.map(function (script, i) {
return script + ' exited with status ' + statuses[i]
}).join('\n')
console.log(info)
var success = statuses.every(function (code) { return code === 0 })
process.exit(success | 0)
})
}
module.exports = runCmd
| Refactor env in run command | Refactor env in run command
| JavaScript | mit | alexanderGugel/ied,alexanderGugel/mpm | ---
+++
@@ -4,6 +4,7 @@
var async = require('async')
var config = require('./config')
var child_process = require('child_process')
+var assign = require('object-assign')
function runCmd (cwd, argv) {
var scripts = argv._.slice(1)
@@ -15,8 +16,11 @@
return
}
- var env = Object.create(process.env)
- env.PATH = [path.join(cwd, 'node_modules/.bin'), process.env.PATH].join(path.delimiter)
+ var env = assign({}, process.env, {
+ PATH: [
+ path.join(cwd, 'node_modules/.bin'), process.env.PATH
+ ].join(path.delimiter)
+ })
async.mapSeries(scripts, function execScript (scriptName, cb) {
var scriptCmd = pkg.scripts[scriptName] |
e7477b991a2f452d25ac35475e8adecceb7fac85 | 2017/01.js | 2017/01.js | // Part 1
[...document.body.textContent.trim()].reduce((s,c,i,a)=>(c==a[(i+1)%a.length])*c+s,0)
// Part 2
[...document.body.textContent.trim()].reduce((s,c,i,a)=>(l=>c==a[(i+l/2)%l])(a.length)*c+s,0)
| // Part 1
[...document.body.innerText.trim()].reduce((s,c,i,a)=>(c==a[(i+1)%a.length])*c+s,0)
// Part 2
[...document.body.innerText.trim()].reduce((s,c,i,a)=>(l=>c==a[(i+l/2)%l])(a.length)*c+s,0)
| Use body.innerText instead of textContent | Use body.innerText instead of textContent
| JavaScript | mit | yishn/adventofcode,yishn/adventofcode | ---
+++
@@ -1,5 +1,5 @@
// Part 1
-[...document.body.textContent.trim()].reduce((s,c,i,a)=>(c==a[(i+1)%a.length])*c+s,0)
+[...document.body.innerText.trim()].reduce((s,c,i,a)=>(c==a[(i+1)%a.length])*c+s,0)
// Part 2
-[...document.body.textContent.trim()].reduce((s,c,i,a)=>(l=>c==a[(i+l/2)%l])(a.length)*c+s,0)
+[...document.body.innerText.trim()].reduce((s,c,i,a)=>(l=>c==a[(i+l/2)%l])(a.length)*c+s,0) |
fce850eeb8b91f00d4cdeaf7cfa3d74e7b47b4c0 | lib/cli/src/generators/WEB-COMPONENTS/template-csf/.storybook/preview.js | lib/cli/src/generators/WEB-COMPONENTS/template-csf/.storybook/preview.js | /* global window */
import {
configure,
addParameters,
// setCustomElements,
} from '@storybook/web-components';
// import customElements from '../custom-elements.json';
// setCustomElements(customElements);
addParameters({
docs: {
iframeHeight: '200px',
},
});
// configure(require.context('../stories', true, /\.stories\.(js|mdx)$/), module);
// force full reload to not reregister web components
const req = require.context('../stories', true, /\.stories\.(js|mdx)$/);
configure(req, module);
if (module.hot) {
module.hot.accept(req.id, () => {
const currentLocationHref = window.location.href;
window.history.pushState(null, null, currentLocationHref);
window.location.reload();
});
}
| // import { setCustomElements } from '@storybook/web-components';
// import customElements from '../custom-elements.json';
// setCustomElements(customElements);
| Fix project template for web-components | CLI: Fix project template for web-components
| JavaScript | mit | storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -1,30 +1,3 @@
-/* global window */
-
-import {
- configure,
- addParameters,
- // setCustomElements,
-} from '@storybook/web-components';
-
+// import { setCustomElements } from '@storybook/web-components';
// import customElements from '../custom-elements.json';
-
// setCustomElements(customElements);
-
-addParameters({
- docs: {
- iframeHeight: '200px',
- },
-});
-
-// configure(require.context('../stories', true, /\.stories\.(js|mdx)$/), module);
-
-// force full reload to not reregister web components
-const req = require.context('../stories', true, /\.stories\.(js|mdx)$/);
-configure(req, module);
-if (module.hot) {
- module.hot.accept(req.id, () => {
- const currentLocationHref = window.location.href;
- window.history.pushState(null, null, currentLocationHref);
- window.location.reload();
- });
-} |
702c888a12716d96f7382fbf2d995fbaf4243a4a | store/search/quick-search/index.js | store/search/quick-search/index.js | let SearchStore = require('../search-store');
/**
* Class standing for all advanced search information.
* The state should be the complete state of the page.
*/
class QuickSearchStore extends SearchStore{
constructor(conf){
conf = conf || {};
conf.definition = {
query: 'query',
scope: 'scope',
results: 'results',
totalCount: 'totalCount'
};
conf.identifier = 'QUICK_SEARCH';
super(conf);
}
}
module.exports = QuickSearchStore;
| let SearchStore = require('../search-store');
/**
* Class standing for all advanced search information.
* The state should be the complete state of the page.
*/
class QuickSearchStore extends SearchStore{
constructor(conf){
conf = conf || {};
conf.definition = {
query: 'query',
scope: 'scope',
results: 'results',
facets: 'facets',
totalCount: 'totalCount'
};
conf.identifier = 'QUICK_SEARCH';
super(conf);
}
}
module.exports = QuickSearchStore;
| Add missing property, the facets (used for group counts) | [quick-search-store] Add missing property, the facets (used for group counts)
| JavaScript | mit | Jerom138/focus,KleeGroup/focus-core,Jerom138/focus,Jerom138/focus | ---
+++
@@ -10,6 +10,7 @@
query: 'query',
scope: 'scope',
results: 'results',
+ facets: 'facets',
totalCount: 'totalCount'
};
conf.identifier = 'QUICK_SEARCH'; |
8599b9c74d4273843cb5ae4f11a5799c2f1f8cc5 | koans/AboutPromises.js | koans/AboutPromises.js | describe("About Promises", function () {
describe("Asynchronous Flow", function () {
it("should understand promise declaration usage", function () {
});
});
});
| describe("About Promises", function () {
describe("Asynchronous Flow", function () {
it("should understand promise usage", function () {
function isZero(number) {
return new Promise(function(resolve, reject) {
if(number === 0) {
resolve();
} else {
reject(number + ' is not zero!');
}
})
}
expect(isZero(0) instanceof Promise).toEqual(FILL_ME_IN);
expect(typeof isZero(0)).toEqual(FILL_ME_IN);
});
});
});
| Add type test for promises | feat: Add type test for promises
| JavaScript | mit | tawashley/es6-javascript-koans,tawashley/es6-javascript-koans,tawashley/es6-javascript-koans | ---
+++
@@ -2,8 +2,20 @@
describe("Asynchronous Flow", function () {
- it("should understand promise declaration usage", function () {
-
+ it("should understand promise usage", function () {
+
+ function isZero(number) {
+ return new Promise(function(resolve, reject) {
+ if(number === 0) {
+ resolve();
+ } else {
+ reject(number + ' is not zero!');
+ }
+ })
+ }
+
+ expect(isZero(0) instanceof Promise).toEqual(FILL_ME_IN);
+ expect(typeof isZero(0)).toEqual(FILL_ME_IN);
});
});
}); |
bf32038659afa4a77cdd79c59c52d9a9adb9b1d8 | lathe/js/box-colors.js | lathe/js/box-colors.js | /* eslint-env es6 */
/* global THREE */
window.applyBoxVertexColors = (function() {
'use strict';
return function vertexColors( geometry ) {
const red = new THREE.Color( '#f00');
const green = new THREE.Color( '#0f0' );
const blue = new THREE.Color( '#00f' );
geometry.faces.forEach( face => {
face.vertexColors = [ red, green, blue ];
});
return geometry;
};
}());
| /* eslint-env es6 */
/* global THREE, Indices */
window.applyBoxVertexColors = (function() {
'use strict';
function setFaceVertexColor( face, index, color ) {
if ( face.a === index ) {
face.vertexColors[ 0 ] = color;
}
if ( face.b === index ) {
face.vertexColors[ 1 ] = color;
}
if ( face.c === index ) {
face.vertexColors[ 2 ] = color;
}
}
return function vertexColors( geometry, colors ) {
Object.keys( colors ).forEach( key => {
const color = new THREE.Color( colors[ key ] );
const indices = Indices[ key.toUpperCase() ];
geometry.faces.forEach( face => {
if ( Array.isArray( indices ) ) {
indices.forEach( index =>
setFaceVertexColor( face, index, color )
);
} else {
setFaceVertexColor( face, indices, color );
}
});
});
return geometry;
};
}());
// Like _.defaults, but with THREE.Face vertexColors.
window.defaultsVertexColor = (function() {
'use strict';
return function defaults( geometry, defaultColor ) {
defaultColor = new THREE.Color( defaultColor );
geometry.faces.forEach( face => {
for ( let i = 0; i < 3; i++ ) {
if ( face.vertexColors[ i ] === undefined ) {
face.vertexColors[ i ] = defaultColor;
}
}
});
return geometry;
};
}());
| Add BoxGeometry vertex colors helper. | lathe[cuboid}: Add BoxGeometry vertex colors helper.
| JavaScript | mit | razh/experiments-three.js,razh/experiments-three.js | ---
+++
@@ -1,17 +1,57 @@
/* eslint-env es6 */
-/* global THREE */
+/* global THREE, Indices */
window.applyBoxVertexColors = (function() {
'use strict';
- return function vertexColors( geometry ) {
- const red = new THREE.Color( '#f00');
- const green = new THREE.Color( '#0f0' );
- const blue = new THREE.Color( '#00f' );
+ function setFaceVertexColor( face, index, color ) {
+ if ( face.a === index ) {
+ face.vertexColors[ 0 ] = color;
+ }
- geometry.faces.forEach( face => {
- face.vertexColors = [ red, green, blue ];
+ if ( face.b === index ) {
+ face.vertexColors[ 1 ] = color;
+ }
+
+ if ( face.c === index ) {
+ face.vertexColors[ 2 ] = color;
+ }
+ }
+
+ return function vertexColors( geometry, colors ) {
+ Object.keys( colors ).forEach( key => {
+ const color = new THREE.Color( colors[ key ] );
+ const indices = Indices[ key.toUpperCase() ];
+
+ geometry.faces.forEach( face => {
+ if ( Array.isArray( indices ) ) {
+ indices.forEach( index =>
+ setFaceVertexColor( face, index, color )
+ );
+ } else {
+ setFaceVertexColor( face, indices, color );
+ }
+ });
});
return geometry;
};
}());
+
+// Like _.defaults, but with THREE.Face vertexColors.
+window.defaultsVertexColor = (function() {
+ 'use strict';
+
+ return function defaults( geometry, defaultColor ) {
+ defaultColor = new THREE.Color( defaultColor );
+
+ geometry.faces.forEach( face => {
+ for ( let i = 0; i < 3; i++ ) {
+ if ( face.vertexColors[ i ] === undefined ) {
+ face.vertexColors[ i ] = defaultColor;
+ }
+ }
+ });
+
+ return geometry;
+ };
+}()); |
41e40acc7a7afe8d5bde99ed41a730cd88d73e86 | reddit/old-reddit-hide-offline-presence.user.js | reddit/old-reddit-hide-offline-presence.user.js | // ==UserScript==
// @name Hide offline presence dot on old reddit
// @namespace https://mathemaniac.org
// @version 1.0
// @description Hides the offline presence dot from old reddit. Only hides offline presence, so you notice if you're displayed as online. https://old.reddit.com/r/changelog/comments/lx08r2/announcing_online_presence_indicators/
// @author Sebastian Paaske Tørholm
// @match https://old.reddit.com/*
// @icon https://www.google.com/s2/favicons?domain=reddit.com
// @grant none
// ==/UserScript==
(function() {
'use strict';
document.head.insertAdjacentHTML('beforeend', `
<style>#header-bottom-right .presence_circle.offline { display: none !important; }</style>
`);
})();
| // ==UserScript==
// @name Hide offline presence dot on old reddit
// @namespace https://mathemaniac.org
// @version 1.0.1
// @description Hides the offline presence dot from old reddit. Only hides offline presence, so you notice if you're displayed as online. https://old.reddit.com/r/changelog/comments/lx08r2/announcing_online_presence_indicators/
// @author Sebastian Paaske Tørholm
// @match https://old.reddit.com/*
// @icon https://www.google.com/s2/favicons?domain=reddit.com
// @grant none
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
document.head.insertAdjacentHTML('beforeend', `
<style>#header-bottom-right .presence_circle.offline { display: none !important; }</style>
`);
})();
| Make script run on document start to help on dot flashes | Make script run on document start to help on dot flashes
| JavaScript | mit | Eckankar/userscripts,Eckankar/userscripts | ---
+++
@@ -1,12 +1,13 @@
// ==UserScript==
// @name Hide offline presence dot on old reddit
// @namespace https://mathemaniac.org
-// @version 1.0
+// @version 1.0.1
// @description Hides the offline presence dot from old reddit. Only hides offline presence, so you notice if you're displayed as online. https://old.reddit.com/r/changelog/comments/lx08r2/announcing_online_presence_indicators/
// @author Sebastian Paaske Tørholm
// @match https://old.reddit.com/*
// @icon https://www.google.com/s2/favicons?domain=reddit.com
// @grant none
+// @run-at document-start
// ==/UserScript==
(function() { |
838745ae7fea6685498bab8b66a043090a582774 | server/channels/__tests__/authAdmin.js | server/channels/__tests__/authAdmin.js | jest.mock('../../models/meeting');
jest.mock('../../utils');
const { emit, broadcast } = require('../../utils');
const { createGenfors } = require('../../models/meeting');
const { generateGenfors, generateSocket } = require('../../utils/generateTestData');
const { createGenfors: createGenforsListener } = require('../auth');
const generateData = data => Object.assign({}, data);
beforeEach(() => {
process.env.SDF_GENFORS_ADMIN_PASSWORD = 'correct';
});
describe('admin creates genfors', () => {
it('returns invalid admin password if incorrect', async () => {
await createGenforsListener(generateSocket(), generateData());
expect(emit.mock.calls).toMatchSnapshot();
expect(broadcast.mock.calls).toEqual([]);
});
it('creates a new meeting if admin password is correct', async () => {
createGenfors.mockImplementation(async () => generateGenfors());
await createGenforsListener(generateSocket(), generateData({ password: 'correct' }));
expect(emit.mock.calls).toEqual([]);
expect(broadcast.mock.calls).toEqual([]);
});
});
afterEach(() => {
process.env.SDF_GENFORS_ADMIN_PASSWORD = '';
});
| jest.mock('../../models/meeting');
jest.mock('../../utils');
const { emit, broadcast } = require('../../utils');
const { createGenfors } = require('../../models/meeting');
const { generateGenfors, generateSocket } = require('../../utils/generateTestData');
const { createGenfors: createGenforsListener } = require('../auth');
const MOCK_PW = 'correct';
const generateData = data => Object.assign({}, data);
beforeEach(() => {
process.env.SDF_GENFORS_ADMIN_PASSWORD = MOCK_PW;
});
describe('admin creates genfors', () => {
it('returns invalid admin password if incorrect', async () => {
await createGenforsListener(generateSocket(), generateData());
expect(emit.mock.calls).toMatchSnapshot();
expect(broadcast.mock.calls).toEqual([]);
});
it('creates a new meeting if admin password is correct', async () => {
createGenfors.mockImplementation(async () => generateGenfors());
await createGenforsListener(generateSocket(), generateData({ password: MOCK_PW }));
expect(emit.mock.calls).toEqual([]);
expect(broadcast.mock.calls).toEqual([]);
});
});
afterEach(() => {
process.env.SDF_GENFORS_ADMIN_PASSWORD = '';
});
| Make mocked admin password be a constant | Make mocked admin password be a constant
| JavaScript | mit | dotkom/super-duper-fiesta,dotkom/super-duper-fiesta,dotkom/super-duper-fiesta | ---
+++
@@ -5,10 +5,13 @@
const { generateGenfors, generateSocket } = require('../../utils/generateTestData');
const { createGenfors: createGenforsListener } = require('../auth');
+
+const MOCK_PW = 'correct';
+
const generateData = data => Object.assign({}, data);
beforeEach(() => {
- process.env.SDF_GENFORS_ADMIN_PASSWORD = 'correct';
+ process.env.SDF_GENFORS_ADMIN_PASSWORD = MOCK_PW;
});
describe('admin creates genfors', () => {
@@ -22,7 +25,7 @@
it('creates a new meeting if admin password is correct', async () => {
createGenfors.mockImplementation(async () => generateGenfors());
- await createGenforsListener(generateSocket(), generateData({ password: 'correct' }));
+ await createGenforsListener(generateSocket(), generateData({ password: MOCK_PW }));
expect(emit.mock.calls).toEqual([]);
expect(broadcast.mock.calls).toEqual([]); |
dcecb81dba5a938beb7be702f2ab2012f0545594 | server/controllers/hotel-controller.js | server/controllers/hotel-controller.js | "use strict";
const HotelData = require("../data").hotel;
const UserData = require("../data").users;
const breedsData = require("../data/models/breeds");
function loadRegisterPage(req, res) {
if(!req.isAuthenticated()){
return res.redirect("../auth/login");
}
var user = req.user;
res.render("hotel/register", {
breeds: breedsData,
user: user
});
}
function registerHotel(req, res) {
if(!req.isAuthenticated()){
return res.redirect("../auth/login");
}
const body = req.body;
var user = req.user;
let newHotelData = {
name: body.name,
owner: user._id,
address: body.address,
phoneNumber: body.phoneNumber,
species: body.species
};
HotelData
.createHotel(newHotelData)
.then(() => {
//TODO:redirect somewhere
res.send(JSON.stringify(newHotelData));
})
.catch((err) => {
res.status(500);
res.send(500, "Registration failed\r\n");
res.end();
});
//TODO: Update user (add new hotel to his list hotels)
}
module.exports = {
loadRegisterPage,
registerHotel,
};
| "use strict";
const HotelData = require("../data").hotel;
const UserData = require("../data").users;
const breedsData = require("../data/models/breeds");
function loadRegisterPage(req, res) {
if (!req.isAuthenticated()) {
return res.redirect("../auth/login");
}
var user = req.user;
res.render("hotel/register", {
breeds: breedsData,
user: user
});
}
function registerHotel(req, res) {
if (!req.isAuthenticated()) {
return res.redirect("../auth/login");
}
const body = req.body;
var user = req.user;
let newHotelData = {
name: body.name,
owner: user._id,
address: body.address,
phoneNumber: body.phoneNumber,
species: body.species
};
HotelData
.createHotel(newHotelData)
.then(() => {
res.redirect("/");
})
.catch((err) => {
res.status(500);
res.send(500, "Registration failed\r\n");
res.end();
});
//TODO: Update user (add new hotel to his list hotels)
}
module.exports = {
loadRegisterPage,
registerHotel,
}; | Fix redirect to home when add hotel. | Fix redirect to home when add hotel.
| JavaScript | mit | ilian1902/Team-D-Animals-Hotel,ilian1902/Team-D-Animals-Hotel,knmitrofanov/animalshotel,knmitrofanov/animalshotel | ---
+++
@@ -5,46 +5,45 @@
const breedsData = require("../data/models/breeds");
function loadRegisterPage(req, res) {
- if(!req.isAuthenticated()){
- return res.redirect("../auth/login");
- }
- var user = req.user;
- res.render("hotel/register", {
- breeds: breedsData,
- user: user
- });
+ if (!req.isAuthenticated()) {
+ return res.redirect("../auth/login");
+ }
+ var user = req.user;
+ res.render("hotel/register", {
+ breeds: breedsData,
+ user: user
+ });
}
function registerHotel(req, res) {
- if(!req.isAuthenticated()){
- return res.redirect("../auth/login");
- }
- const body = req.body;
- var user = req.user;
-
- let newHotelData = {
- name: body.name,
- owner: user._id,
+ if (!req.isAuthenticated()) {
+ return res.redirect("../auth/login");
+ }
+ const body = req.body;
+ var user = req.user;
+
+ let newHotelData = {
+ name: body.name,
+ owner: user._id,
address: body.address,
phoneNumber: body.phoneNumber,
species: body.species
- };
+ };
- HotelData
- .createHotel(newHotelData)
- .then(() => {
- //TODO:redirect somewhere
- res.send(JSON.stringify(newHotelData));
- })
- .catch((err) => {
- res.status(500);
- res.send(500, "Registration failed\r\n");
- res.end();
- });
- //TODO: Update user (add new hotel to his list hotels)
+ HotelData
+ .createHotel(newHotelData)
+ .then(() => {
+ res.redirect("/");
+ })
+ .catch((err) => {
+ res.status(500);
+ res.send(500, "Registration failed\r\n");
+ res.end();
+ });
+ //TODO: Update user (add new hotel to his list hotels)
}
-module.exports = {
- loadRegisterPage,
- registerHotel,
+module.exports = {
+ loadRegisterPage,
+ registerHotel,
}; |
e457d0dcb9af16528f6d84ff7b5c726edb2f1478 | prolific.syslog/syslog.argv.js | prolific.syslog/syslog.argv.js | /*
___ usage ___ en_US ___
usage: prolific syslog <options>
-a, --application <string>
The application name to display in the syslog record. Defaults to
the value of `process.title` which will always be `node`.
-h, --hostname <string>
The hostname to display in the syslog record. Defaults to the value
of `require('os').hostname()`.
-f, --facility <string>
The syslog facility to encode in the syslog record. Defaults to `local0`.
-p, --pid <string>
The process id to display in the syslog record. Defaults to
the value of `process.pid`.
-s, --serializer <string>
The type of serializer for the payload. Defaults to "json".
--help display this message
___ $ ___ en_US ___
___ . ___
*/
require('arguable')(module, require('cadence')(function (async, program) {
program.helpIf(program.command.params.help)
var response = {
moduleName: 'prolific.syslog/syslog.processor',
parameters: { params: program.command.param },
argv: program.argv,
terminal: program.command.terminal
}
if (process.mainModule == module) {
console.log(response)
}
return response
}))
| /*
___ usage ___ en_US ___
usage: prolific syslog <options>
-a, --application <string>
The application name to display in the syslog record. Defaults to
the value of `process.title` which will always be `node`.
-h, --hostname <string>
The hostname to display in the syslog record. Defaults to the value
of `require('os').hostname()`.
-f, --facility <string>
The syslog facility to encode in the syslog record. Defaults to `local0`.
-p, --pid <string>
The process id to display in the syslog record. Defaults to
the value of `process.pid`.
-s, --serializer <string>
The type of serializer for the payload. Defaults to "json".
--help display this message
___ $ ___ en_US ___
___ . ___
*/
require('arguable')(module, require('cadence')(function (async, program) {
program.helpIf(program.command.params.help)
var response = {
moduleName: 'prolific.syslog/syslog.processor',
parameters: { params: program.command.param },
argv: program.argv,
terminal: program.command.terminal
}
if (process.mainModule == module) {
console.log(response)
}
return response
}))
module.exports.isProlific = true
| Add flag for new module loader. | Add flag for new module loader.
| JavaScript | mit | bigeasy/prolific,bigeasy/prolific | ---
+++
@@ -40,3 +40,5 @@
}
return response
}))
+
+module.exports.isProlific = true |
651bc5ecf574d4716683343c9f543d88263fd4cb | models/base.js | models/base.js | var Arrow = require('arrow');
module.exports = Arrow.createModel('base', {
connector: 'appc.redis',
fields: { },
expire: function expire(seconds, callback){
return this.getConnector().expire(this.getModel(), this, seconds, callback);
},
expireAt: function expireAt(date, callback){
return this.getConnector().expireAt(this.getModel(), this, date, callback);
},
keys: function keys(limit, callback){
return this.getConnector().keys(this.getModel(), limit, callback);
},
persist: function persist(callback){
return this.getConnector().persist(this.getModel(), this, callback);
},
ttl: function ttl(callback){
return this.getConnector().ttl(this.getModel(), this, callback);
}
}); | var Arrow = require('arrow');
var Base = Arrow.Model.extend('base', {
connector: 'appc.redis',
fields: { },
expire: function expire(seconds, callback){
return this.getConnector().expire(this.getModel(), this, seconds, callback);
},
expireAt: function expireAt(date, callback){
return this.getConnector().expireAt(this.getModel(), this, date, callback);
},
keys: function keys(limit, callback){
return this.getConnector().keys(this.getModel(), limit, callback);
},
persist: function persist(callback){
return this.getConnector().persist(this.getModel(), this, callback);
},
ttl: function ttl(callback){
return this.getConnector().ttl(this.getModel(), this, callback);
}
});
module.exports = Base; | Switch out 'createModel' for 'extend' | Switch out 'createModel' for 'extend'
| JavaScript | apache-2.0 | titanium-forks/appcelerator.appc.redis | ---
+++
@@ -1,6 +1,6 @@
var Arrow = require('arrow');
-module.exports = Arrow.createModel('base', {
+var Base = Arrow.Model.extend('base', {
connector: 'appc.redis',
@@ -27,3 +27,5 @@
}
});
+
+module.exports = Base; |
a25dadd4f4078965e647ec34265cdfe5fd879826 | client/src/components/LastVotes.js | client/src/components/LastVotes.js | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import css from './LastVotes.css';
import { voteWithNameSelector } from '../selectors/voting';
const LastVotes = ({ votes }) => (
<div className={css.component}>
<h3>Siste stemmer</h3>
{ votes.length > 0 ? votes.map(vote => (
<div className={css.vote}>
{ vote.voter }: { vote.alternative }
</div>
))
: (
<div>Ingen stemmer enda</div>
)}
</div>
);
LastVotes.propTypes = {
votes: PropTypes.shape({
voter: PropTypes.string.isRequired,
alternative: PropTypes.string.isRequired,
}).isRequired,
};
const mapStateToProps = state => ({
votes: voteWithNameSelector(state).slice(0, 5),
});
export default connect(mapStateToProps)(LastVotes);
| import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import css from './LastVotes.css';
import { voteWithNameSelector } from '../selectors/voting';
import { activeIssueExists, getOwnVote, getIssueKey } from '../selectors/issues';
const LastVotes = ({ votes, hideVotes }) => {
if (hideVotes) {
return null;
}
return (
<div className={css.component}>
<h3>Siste stemmer</h3>
{ votes.length > 0 ? votes.map(vote => (
<div className={css.vote}>
{ vote.voter }: { vote.alternative }
</div>
))
: (
<div>Ingen stemmer enda</div>
)}
</div>
);
};
LastVotes.propTypes = {
votes: PropTypes.shape({
voter: PropTypes.string.isRequired,
alternative: PropTypes.string.isRequired,
}).isRequired,
hideVotes: PropTypes.bool.isRequired,
};
const mapStateToProps = state => ({
votes: voteWithNameSelector(state).slice(0, 5),
hideVotes: (
!activeIssueExists(state)
|| !getOwnVote(state, state.auth.id)
|| getIssueKey(state, 'showOnlyWinner')
),
});
export default connect(mapStateToProps)(LastVotes);
| Hide last votes unless there is an active issue with public votes and user has voted | Hide last votes unless there is an active issue with public votes and
user has voted
| JavaScript | mit | dotkom/super-duper-fiesta,dotkom/super-duper-fiesta,dotkom/super-duper-fiesta | ---
+++
@@ -3,30 +3,42 @@
import { connect } from 'react-redux';
import css from './LastVotes.css';
import { voteWithNameSelector } from '../selectors/voting';
+import { activeIssueExists, getOwnVote, getIssueKey } from '../selectors/issues';
-const LastVotes = ({ votes }) => (
- <div className={css.component}>
- <h3>Siste stemmer</h3>
- { votes.length > 0 ? votes.map(vote => (
- <div className={css.vote}>
- { vote.voter }: { vote.alternative }
- </div>
- ))
- : (
- <div>Ingen stemmer enda</div>
- )}
- </div>
-);
+const LastVotes = ({ votes, hideVotes }) => {
+ if (hideVotes) {
+ return null;
+ }
+ return (
+ <div className={css.component}>
+ <h3>Siste stemmer</h3>
+ { votes.length > 0 ? votes.map(vote => (
+ <div className={css.vote}>
+ { vote.voter }: { vote.alternative }
+ </div>
+ ))
+ : (
+ <div>Ingen stemmer enda</div>
+ )}
+ </div>
+ );
+};
LastVotes.propTypes = {
votes: PropTypes.shape({
voter: PropTypes.string.isRequired,
alternative: PropTypes.string.isRequired,
}).isRequired,
+ hideVotes: PropTypes.bool.isRequired,
};
const mapStateToProps = state => ({
votes: voteWithNameSelector(state).slice(0, 5),
+ hideVotes: (
+ !activeIssueExists(state)
+ || !getOwnVote(state, state.auth.id)
+ || getIssueKey(state, 'showOnlyWinner')
+ ),
});
export default connect(mapStateToProps)(LastVotes); |
ea7cba4da1698273cb0023c30ae4f00268129e1c | lib/tests/dashboard.js | lib/tests/dashboard.js | var Mocha = require('mocha'),
_ = require('underscore'),
moduleTest = require('./module');
module.exports = function (browser, dashboard, suite, config) {
suite = Mocha.Suite.create(suite, dashboard.title);
suite.beforeAll(function () {
return browser.get(config.baseUrl + dashboard.slug)
.$('body.ready', 5000)
// if a dashboard isn't ready after 5s then there's probably a failed module
// run module tests to help establish which
.fail(function () {});
});
var tests = {
exists: function exists() {
return browser
.title()
.should.become(dashboard.title + ' - ' + dashboard.strapline + ' - GOV.UK')
.$('h1').text()
.should.eventually.equal(dashboard.strapline + '\n' + dashboard.title)
.$('body.ready')
.should.eventually.exist;
}
};
_.each(tests, function (test, key) {
suite.addTest(new Mocha.Test(key, test));
});
var modules = Mocha.Suite.create(suite, 'modules');
dashboard.modules.forEach(function (module) {
moduleTest(browser, module, modules, config);
});
}; | var Mocha = require('mocha'),
_ = require('underscore'),
moduleTest = require('./module');
module.exports = function (browser, dashboard, suite, config) {
suite = Mocha.Suite.create(suite, dashboard.title);
suite.beforeAll(function () {
return browser.get(config.baseUrl + dashboard.slug)
.setWindowSize(1024, 800)
.$('body.ready', 5000)
// if a dashboard isn't ready after 5s then there's probably a failed module
// run module tests to help establish which
.fail(function () {});
});
var tests = {
exists: function exists() {
return browser
.title()
.should.become(dashboard.title + ' - ' + dashboard.strapline + ' - GOV.UK')
.$('h1').text()
.should.eventually.equal(dashboard.strapline + '\n' + dashboard.title)
.$('body.ready')
.should.eventually.exist;
}
};
_.each(tests, function (test, key) {
suite.addTest(new Mocha.Test(key, test));
});
var modules = Mocha.Suite.create(suite, 'modules');
dashboard.modules.forEach(function (module) {
moduleTest(browser, module, modules, config);
});
}; | Set window size to desktop display dimensions | Set window size to desktop display dimensions
Some tests were failing because the default window dimensions cause the site to display in "mobile" format, truncating some elements and causing tests to fail.
| JavaScript | mit | alphagov/cheapseats | ---
+++
@@ -8,6 +8,7 @@
suite.beforeAll(function () {
return browser.get(config.baseUrl + dashboard.slug)
+ .setWindowSize(1024, 800)
.$('body.ready', 5000)
// if a dashboard isn't ready after 5s then there's probably a failed module
// run module tests to help establish which |
07d763d5ce597abba1193cccee3ad7fca0d4cd97 | plugins/cloudimport/templates/load_buttons.js | plugins/cloudimport/templates/load_buttons.js | PluginsAPI.Dashboard.addNewTaskButton(
["cloudimport/build/ImportView.js"],
function(args, ImportView) {
return React.createElement(ImportView, {
onNewTaskAdded: args.onNewTaskAdded,
projectId: args.projectId,
apiURL: "{{ api_url }}",
});
}
);
PluginsAPI.Dashboard.addTaskActionButton(
["cloudimport/build/TaskView.js"],
function(args, ImportView) {
$.ajax({
url: "{{ api_url }}/projects/" + args.task.project + "/tasks/" + args.task.id + "/checkforurl",
dataType: 'json',
async: false,
success: function(data) {
if (data.folder_url) {
return React.createElement(ImportView, {
folderUrl: data.folder_url,
});
}
}
});
}
);
| PluginsAPI.Dashboard.addNewTaskButton(
["cloudimport/build/ImportView.js"],
function(args, ImportView) {
return React.createElement(ImportView, {
onNewTaskAdded: args.onNewTaskAdded,
projectId: args.projectId,
apiURL: "{{ api_url }}",
});
}
);
PluginsAPI.Dashboard.addTaskActionButton(
["cloudimport/build/TaskView.js"],
function(args, TaskView) {
var reactElement;
$.ajax({
url: "{{ api_url }}/projects/" + args.task.project + "/tasks/" + args.task.id + "/checkforurl",
dataType: 'json',
async: false,
success: function(data) {
if (data.folder_url) {
reactElement = React.createElement(TaskView, {
folderUrl: data.folder_url,
});
}
}
});
return reactElement;
}
);
| Fix to show task button | Fix to show task button
| JavaScript | agpl-3.0 | pierotofy/WebODM,OpenDroneMap/WebODM,pierotofy/WebODM,pierotofy/WebODM,pierotofy/WebODM,OpenDroneMap/WebODM,OpenDroneMap/WebODM,OpenDroneMap/WebODM,OpenDroneMap/WebODM,pierotofy/WebODM | ---
+++
@@ -11,18 +11,20 @@
PluginsAPI.Dashboard.addTaskActionButton(
["cloudimport/build/TaskView.js"],
- function(args, ImportView) {
+ function(args, TaskView) {
+ var reactElement;
$.ajax({
url: "{{ api_url }}/projects/" + args.task.project + "/tasks/" + args.task.id + "/checkforurl",
dataType: 'json',
async: false,
success: function(data) {
if (data.folder_url) {
- return React.createElement(ImportView, {
+ reactElement = React.createElement(TaskView, {
folderUrl: data.folder_url,
});
}
}
});
+ return reactElement;
}
); |
70b72554e264bb3d06f6116080252c20b19bce25 | take-002-nodejs-server-clone/server.js | take-002-nodejs-server-clone/server.js | var express = require('express'),
mongoose = require('mongoose'),
app = express()
app.set('port', process.env.PORT || 3000)
app.set('mongodb-url', process.env.MONGODB_URL || 'mongodb://localhost/hangman')
if ('test' === app.get('env')) {
app.set('port', 9000)
app.set('mongodb-url', 'mongodb://localhost/hangman-test')
}
mongoose.connect(app.get('mongodb-url'))
app.use(require('morgan')('dev'))
app.use(require('body-parser').json())
app.get('/', function(req, res) {
res.json({
'index': '/',
'me': '/me',
'prisoners': '/prisoners'
})
})
if (require.main === module) {
mongoose.connection.on('connected', function() {
console.log('Connected to %s', app.get('mongodb-url'))
app.listen(app.get('port'), function() {
console.log('Listening on port %d', app.get('port'))
})
})
}
| var express = require('express'),
mongoose = require('mongoose'),
util = require('util'),
_ = require('lodash'),
app = express()
app.set('port', process.env.PORT || 3000)
app.set('mongodb-url', process.env.MONGODB_URL || 'mongodb://localhost/hangman')
if ('test' === app.get('env')) {
app.set('port', 9000)
app.set('mongodb-url', 'mongodb://localhost/hangman-test')
}
mongoose.connect(app.get('mongodb-url'))
var User = mongoose.model('User', (function() {
return mongoose.Schema({
'email_address': {type: String, required: 'Missing required field [{PATH}]'},
'password': {type: String, required: 'Missing required field [{PATH}]'}
})
})())
app.use(require('morgan')('dev'))
app.use(require('body-parser').urlencoded({extended: true}))
app.get('/', function(req, res) {
res.json({
'index': '/',
'me': '/me',
'prisoners': '/prisoners'
})
})
app.post('/me', function(req, res) {
new User(req.body).save(function(err, user) {
if (err) {
return res.send(400, {
'status': 'Bad Request',
'status_code': 400,
'description': _(err.errors).chain().values().pluck('message').join(', ').value()
})
}
res.location(util.format('/users/%s', user.id))
res.send(201)
})
})
if (require.main === module) {
mongoose.connection.on('connected', function() {
console.log('Connected to %s', app.get('mongodb-url'))
app.listen(app.get('port'), function() {
console.log('Listening on port %d', app.get('port'))
})
})
}
| Create User document after POST /me | [take-002] Create User document after POST /me
| JavaScript | mit | gabrielelana/hangman-http-kata | ---
+++
@@ -1,5 +1,7 @@
var express = require('express'),
mongoose = require('mongoose'),
+ util = require('util'),
+ _ = require('lodash'),
app = express()
app.set('port', process.env.PORT || 3000)
@@ -12,14 +14,35 @@
mongoose.connect(app.get('mongodb-url'))
+var User = mongoose.model('User', (function() {
+ return mongoose.Schema({
+ 'email_address': {type: String, required: 'Missing required field [{PATH}]'},
+ 'password': {type: String, required: 'Missing required field [{PATH}]'}
+ })
+})())
+
app.use(require('morgan')('dev'))
-app.use(require('body-parser').json())
+app.use(require('body-parser').urlencoded({extended: true}))
app.get('/', function(req, res) {
res.json({
'index': '/',
'me': '/me',
'prisoners': '/prisoners'
+ })
+})
+
+app.post('/me', function(req, res) {
+ new User(req.body).save(function(err, user) {
+ if (err) {
+ return res.send(400, {
+ 'status': 'Bad Request',
+ 'status_code': 400,
+ 'description': _(err.errors).chain().values().pluck('message').join(', ').value()
+ })
+ }
+ res.location(util.format('/users/%s', user.id))
+ res.send(201)
})
})
|
1a573086b88669d8edf4097201d4df7ff53427ee | gulp/utils/notify.js | gulp/utils/notify.js | var notifier = new require("node-notifier")({});
var extend = require("extend");
var path = require("path");
var CFG = require("./config.js");
var pkg = require(path.join("..", "..", CFG.FILE.config.pkg));
module.exports = {
defaults: {
title: pkg.name
},
showNotification: function (options) {
extend(options, this.defaults);
if("undefined" !== typeof(process.env.REMEMBER_CI)) {
// Running inside a CI environment, do not show notifications
console.log("[notification]", options.message);
} else {
// Running inside a non-CI environment, okay to show notifications
notifier.notify(options);
}
},
appIcon: {
sass: __dirname + "/asset/image/sass-logo.png",
karma: __dirname + "/asset/image/karma-logo.png"
}
};
| var notifier = new require("node-notifier");
var extend = require("extend");
var path = require("path");
var CFG = require("./config.js");
var pkg = require(path.join("..", "..", CFG.FILE.config.pkg));
module.exports = {
defaults: {
title: pkg.name
},
showNotification: function (options) {
extend(options, this.defaults);
if("undefined" !== typeof(process.env.REMEMBER_CI)) {
// Running inside a CI environment, do not show notifications
console.log("[notification]", options.message);
} else {
// Running inside a non-CI environment, okay to show notifications
notifier.notify(options);
}
},
appIcon: {
sass: __dirname + "/asset/image/sass-logo.png",
karma: __dirname + "/asset/image/karma-logo.png"
}
};
| Update node-notifier initialization as per the new version. | Update node-notifier initialization as per the new version.
| JavaScript | mit | rishabhsrao/remember,rishabhsrao/remember,rishabhsrao/remember | ---
+++
@@ -1,4 +1,4 @@
-var notifier = new require("node-notifier")({});
+var notifier = new require("node-notifier");
var extend = require("extend");
var path = require("path");
var CFG = require("./config.js"); |
cde94167d2bb18a2873a943c7df25dd8258e117f | client/components/FileDescription.js | client/components/FileDescription.js | import React from 'react';
export default class FileDescription extends React.Component {
render() {
return <div className="file-description">
<span className="file-name">{this.props.file.name}</span>
<span className="file-size">{this.props.file.size}</span>
<span className="file-type">{this.props.file.type}</span>
</div>;
}
}
| import React from 'react';
export default class FileDescription extends React.Component {
render() {
return <div className="file-description">
<span className="file-name">{this.props.file.name}</span>
</div>;
}
}
| Remove file size and type descriptors. | Remove file size and type descriptors.
| JavaScript | bsd-3-clause | gramakri/filepizza,bradparks/filepizza_javascript_send_files_webrtc,hanford/filepizza,Ribeiro/filepizza,pquochoang/filepizza,jekrb/filepizza,codevlabs/filepizza,codebhendi/filepizza | ---
+++
@@ -5,8 +5,6 @@
render() {
return <div className="file-description">
<span className="file-name">{this.props.file.name}</span>
- <span className="file-size">{this.props.file.size}</span>
- <span className="file-type">{this.props.file.type}</span>
</div>;
}
|
930860fb4f12b720a15536b52685ba3beffa47c6 | client/src/loading/loadingActions.js | client/src/loading/loadingActions.js | /*
* Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved.
*
* This file is part of BoxCharter.
*
* BoxCharter is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* BoxCharter is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with BoxCharter. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* Action creators for loading state.
* @module
* loadingActions
*/
import { CANCEL_ALL_LOADING } from './loadingActionTypes';
/**
* Return CANCEL_ALL_LOADING action.
* @function clearLoadingEvents
* @returns {object} - CANCEL_ALL_LOADING action.
*/
const clearLoadingEvents = () => ({ type: CANCEL_ALL_LOADING });
module.exports = {
clearLoadingEvents,
};
| /*
* Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved.
*
* This file is part of BoxCharter.
*
* BoxCharter is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* BoxCharter is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with BoxCharter. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* Action creators for loading state.
* @module
* loadingActions
*/
import { CANCEL_ALL_LOADING } from './loadingActionTypes';
// TODO: call this upon page refresh
// (where? get funny routing errors if I make App a connected component...)
/**
* Return CANCEL_ALL_LOADING action.
* @function clearLoadingEvents
* @returns {object} - CANCEL_ALL_LOADING action.
*/
const clearLoadingEvents = () => ({ type: CANCEL_ALL_LOADING });
module.exports = {
clearLoadingEvents,
};
| Add TODO for clear loading upon refresh | Add TODO for clear loading upon refresh
| JavaScript | agpl-3.0 | flyrightsister/boxcharter,flyrightsister/boxcharter | ---
+++
@@ -26,6 +26,9 @@
import { CANCEL_ALL_LOADING } from './loadingActionTypes';
+// TODO: call this upon page refresh
+// (where? get funny routing errors if I make App a connected component...)
+
/**
* Return CANCEL_ALL_LOADING action.
* @function clearLoadingEvents |
9ff4f729ba2970cd1407f47d7d1ceecc52dd7f61 | lib/common/annotate.js | lib/common/annotate.js | define(['../is', '../array/last', '../functional'], function(is, last, functional) {
var map = functional.map;
var filter = functional.filter;
var forEach = functional.forEach;
function annotate() {
var args = Array.prototype.slice.call(arguments);
var fn = args.shift();
if(is.string(last(args))) {
fn._doc = args.pop();
}
forEach(function(arg) {
if(!is.fn(arg)) console.warn('Invariant' + arg + 'is not a function!');
}, args);
fn._invariants = args;
return function() {
var curArgs = arguments;
var info = map(function(arg, i) {
var curArg = curArgs[i];
if(is.fn(arg)) {
if(arg(curArg)) return {
state: 'ok',
arg: curArg
};
else return {
state: 'error',
info: 'Parameter check failed!',
arg: curArg
};
}
else {
return {
state: 'error',
info: 'Parameter checker is not a function!',
arg: curArg
};
}
}, args);
var isOk = filter(function(k) {
return k.state == 'ok';
}, info).length == info.length;
if(isOk) return fn.apply(undefined, curArgs);
else console.warn(info);
};
}
return annotate;
});
| define(['../is', '../array/last', '../functional'], function(is, last, functional) {
var map = functional.map;
var filter = functional.filter;
var forEach = functional.forEach;
function annotate() {
var args = Array.prototype.slice.call(arguments);
var fn = args.shift();
var doc;
var invariants;
if(is.string(last(args))) {
doc = args.pop();
}
forEach(function(arg) {
if(!is.fn(arg)) console.warn('Invariant' + arg + 'is not a function!');
}, args);
invariants = args;
var ret = function() {
var curArgs = arguments;
var info = map(function(arg, i) {
var curArg = curArgs[i];
if(is.fn(arg)) {
if(arg(curArg)) return {
state: 'ok',
arg: curArg
};
else return {
state: 'error',
info: 'Parameter check failed!',
arg: curArg
};
}
else {
return {
state: 'error',
info: 'Parameter checker is not a function!',
arg: curArg
};
}
}, args);
var isOk = filter(function(k) {
return k.state == 'ok';
}, info).length == info.length;
if(isOk) return fn.apply(undefined, curArgs);
else console.warn(info);
};
ret._doc = doc;
ret._invariants = invariants;
return ret;
}
return annotate;
});
| Attach metadata to the right function | Attach metadata to the right function
| JavaScript | mit | bebraw/funkit,bebraw/funkit | ---
+++
@@ -6,18 +6,20 @@
function annotate() {
var args = Array.prototype.slice.call(arguments);
var fn = args.shift();
+ var doc;
+ var invariants;
if(is.string(last(args))) {
- fn._doc = args.pop();
+ doc = args.pop();
}
forEach(function(arg) {
if(!is.fn(arg)) console.warn('Invariant' + arg + 'is not a function!');
}, args);
- fn._invariants = args;
+ invariants = args;
- return function() {
+ var ret = function() {
var curArgs = arguments;
var info = map(function(arg, i) {
@@ -49,6 +51,10 @@
if(isOk) return fn.apply(undefined, curArgs);
else console.warn(info);
};
+ ret._doc = doc;
+ ret._invariants = invariants;
+
+ return ret;
}
return annotate;
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.