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 |
|---|---|---|---|---|---|---|---|---|---|---|
1944548e8ea77174d0929230e07a78220d3fe2ff | app/assets/javascripts/url-helpers.js | app/assets/javascripts/url-helpers.js | var getUrlVar = function(key) {
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && unescape(result[1]) || "";
};
var getIDFromURL = function(key) {
var result = new RegExp(key + "/([0-9a-zA-Z\-]*)", "i").exec(window.location.pathname);
if (result === 'new') {
return '';
}
return result && unescape(result[1]) || '';
};
| var getUrlVar = function(key) {
var result = new RegExp(key + '=([^&]*)', 'i').exec(window.location.search);
return result && decodeURIComponent(result[1]) || '';
};
var getIDFromURL = function(key) {
var result = new RegExp(key + '/([0-9a-zA-Z\-]*)', 'i').exec(window.location.pathname);
if (result === 'new') {
return '';
}
return result && decodeURIComponent(result[1]) || '';
};
| Fix mixture of quotes and deprecated unescape method usage | Fix mixture of quotes and deprecated unescape method usage
| JavaScript | mit | openfarmcc/OpenFarm,RickCarlino/OpenFarm,CloCkWeRX/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm,CloCkWeRX/OpenFarm,CloCkWeRX/OpenFarm,CloCkWeRX/OpenFarm,openfarmcc/OpenFarm,RickCarlino/OpenFarm | ---
+++
@@ -1,12 +1,12 @@
var getUrlVar = function(key) {
- var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
- return result && unescape(result[1]) || "";
+ var result = new RegExp(key + '=([^&]*)', 'i').exec(window.location.search);
+ return result && decodeURIComponent(result[1]) || '';
};
var getIDFromURL = function(key) {
- var result = new RegExp(key + "/([0-9a-zA-Z\-]*)", "i").exec(window.location.pathname);
+ var result = new RegExp(key + '/([0-9a-zA-Z\-]*)', 'i').exec(window.location.pathname);
if (result === 'new') {
return '';
}
- return result && unescape(result[1]) || '';
+ return result && decodeURIComponent(result[1]) || '';
}; |
7fe3fdf119d99e40b9917696a90244f05a0205ee | paths.js | paths.js | var src = exports.src = {};
src.app = [
'src/index.js',
'src/api.js',
'src/app.js'
];
src.dummy = [
'src/dummy.js',
'src/fixtures.js'
];
src.lib = [].concat(
src.app,
src.dummy);
src.demo = [].concat(src.lib, [
'src/demo.js'
]);
src.prd = [].concat(src.app, [
'src/init.js'
]);
src.all = [
'src/**/*.js'
];
module.exports = {
src: src,
dest: {
prd: 'lib/vumi-ureport.js',
demo: 'lib/vumi-ureport.demo.js'
},
test: {
spec: [
'test/**/*.test.js'
],
requires: [
'test/setup.js'
]
}
};
| var src = exports.src = {};
src.app = [
'src/index.js',
'src/api.js',
'src/app.js'
];
src.dummy = [
'src/fixtures.js',
'src/dummy.js'
];
src.lib = [].concat(
src.app,
src.dummy);
src.demo = [].concat(src.lib, [
'src/demo.js'
]);
src.prd = [].concat(src.app, [
'src/init.js'
]);
src.all = [
'src/**/*.js'
];
module.exports = {
src: src,
dest: {
prd: 'lib/vumi-ureport.js',
demo: 'lib/vumi-ureport.demo.js'
},
test: {
spec: [
'test/**/*.test.js'
],
requires: [
'test/setup.js'
]
}
};
| Switch around fixtures.js and dummy.js in path config | Switch around fixtures.js and dummy.js in path config
| JavaScript | bsd-3-clause | praekelt/vumi-ureport,praekelt/vumi-ureport | ---
+++
@@ -7,8 +7,8 @@
];
src.dummy = [
- 'src/dummy.js',
- 'src/fixtures.js'
+ 'src/fixtures.js',
+ 'src/dummy.js'
];
src.lib = [].concat( |
fd474b753aa3fc34c8a494f578b8ab50bffadcc1 | server/api/attachments/dal.js | server/api/attachments/dal.js | var db = require('tresdb-db');
exports.count = function (callback) {
// Count non-deleted attachments
//
// Parameters:
// callback
// function (err, number)
//
db.collection('attachments').countDocuments({
deleted: false,
})
.then(function (number) {
return callback(null, number);
})
.catch(function (err) {
return callback(err);
});
};
exports.create = function (params, callback) {
// Parameters:
// params:
// username
// string
// filepath
// string or null
// The relative path of the file in the uploads dir
// mimetype
// string or null
// thumbfilepath
// string or null
// The relative path of the thumbnail file in the uploads dir
// thumbmimetype
// string or null
// callback
// function (err, attachment)
var attachment = {
key: generate()
user: params.username,
time: timestamp(),
deleted: false,
filepath: params.filepath,
mimetype: params.mimetype,
thumbfilepath: params.thumbfilepath,
thumbmimetype: params.thumbmimetype,
};
db.collection('attachments').insertOne(attachment, function (err) {
if (err) {
// TODO key already exists
return callback(err);
}
return callback(null, attachment);
});
};
| var db = require('tresdb-db');
var keygen = require('tresdb-key');
exports.count = function (callback) {
// Count non-deleted attachments
//
// Parameters:
// callback
// function (err, number)
//
db.collection('attachments').countDocuments({
deleted: false,
})
.then(function (number) {
return callback(null, number);
})
.catch(function (err) {
return callback(err);
});
};
exports.create = function (params, callback) {
// Parameters:
// params:
// username
// string
// filepath
// string or null
// The relative path of the file in the uploads dir
// mimetype
// string or null
// thumbfilepath
// string or null
// The relative path of the thumbnail file in the uploads dir
// thumbmimetype
// string or null
// callback
// function (err, attachment)
var attachment = {
key: keygen.generate(),
user: params.username,
time: timestamp(),
deleted: false,
filepath: params.filepath,
mimetype: params.mimetype,
thumbfilepath: params.thumbfilepath,
thumbmimetype: params.thumbmimetype,
};
db.collection('attachments').insertOne(attachment, function (err) {
if (err) {
// TODO key already exists
return callback(err);
}
return callback(null, attachment);
});
};
| Use tresdb-key in attachment generation | Use tresdb-key in attachment generation
| JavaScript | mit | axelpale/tresdb,axelpale/tresdb | ---
+++
@@ -1,4 +1,5 @@
var db = require('tresdb-db');
+var keygen = require('tresdb-key');
exports.count = function (callback) {
// Count non-deleted attachments
@@ -37,7 +38,7 @@
// function (err, attachment)
var attachment = {
- key: generate()
+ key: keygen.generate(),
user: params.username,
time: timestamp(),
deleted: false, |
2cba580ff50b0f5f60933f4165973726a4f47073 | app/assets/javascripts/users.js | app/assets/javascripts/users.js | $(() => {
if (location.pathname === '/users/sign_up' || location.pathname === '/users/sign_in' && !navigator.cookieEnabled) {
$('input[type="submit"]').attr('disabled', true).addClass('is-muted is-outlined');
$('.js-errors').text('Cookies must be enabled in your browser for you to be able to sign up or sign in.');
}
}); | $(() => {
if ((location.pathname === '/users/sign_up' || location.pathname === '/users/sign_in') && !navigator.cookieEnabled) {
$('input[type="submit"]').attr('disabled', true).addClass('is-muted is-outlined');
$('.js-errors').text('Cookies must be enabled in your browser for you to be able to sign up or sign in.');
}
}); | Fix bug where Signup form is incorrectyl disabled | Fix bug where Signup form is incorrectyl disabled
The signup form is being disabled in all cases because of an operator
precedence problem.
| JavaScript | agpl-3.0 | ArtOfCode-/qpixel,ArtOfCode-/qpixel,ArtOfCode-/qpixel,ArtOfCode-/qpixel | ---
+++
@@ -1,5 +1,5 @@
$(() => {
- if (location.pathname === '/users/sign_up' || location.pathname === '/users/sign_in' && !navigator.cookieEnabled) {
+ if ((location.pathname === '/users/sign_up' || location.pathname === '/users/sign_in') && !navigator.cookieEnabled) {
$('input[type="submit"]').attr('disabled', true).addClass('is-muted is-outlined');
$('.js-errors').text('Cookies must be enabled in your browser for you to be able to sign up or sign in.');
} |
e9c8040befea76e0462f845822d136f39bdfb17a | app/components/child-comment.js | app/components/child-comment.js | import Ember from 'ember';
export default Ember.Component.extend({
classNameBindings: ['offset:col-md-offset-1'],
offset: false,
timestamp: function() {
return moment.unix(this.get('comment.time')).fromNow();
}.property('time'),
actions: {
followUser: function(userId) {
var sessionData = sessionStorage['firebase:session::ember-hacker-news'];
var authToken = JSON.parse(sessionData)['token'];
var uid = JSON.parse(sessionData)['uid'];
console.log('Auth token: ' + authToken);
console.log('uid: ' + uid);
var followTarget = userId;
var record = this.store.find('account', uid).then(addFollowing);
function addFollowing(user) {
var newList = user.get('following').push(userId);
user.save().then(null, function(error) {
console.log(error);
});
}
console.log('Following ' + userId);
},
saveComment: function(commentId) {
console.log('Comment saved');
}
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
classNameBindings: ['offset:col-md-offset-1'],
offset: false,
timestamp: function() {
return moment.unix(this.get('comment.time')).fromNow();
}.property('time'),
actions: {
followUser: function(userId) {
var sessionData = sessionStorage['firebase:session::ember-hacker-news'];
var authToken = JSON.parse(sessionData)['token'];
var uid = JSON.parse(sessionData)['uid'];
console.log('Auth token: ' + authToken);
console.log('uid: ' + uid);
var followTarget = userId;
this.store.find('account', uid).then(addFollowing);
function addFollowing(user) {
var newList = user.get('following').push(userId);
user.save().then(null, function(error) {
console.log(error);
});
}
console.log('Following ' + userId);
},
saveComment: function(commentId) {
var sessionData = sessionStorage['firebase:session::ember-hacker-news'];
var authToken = JSON.parse(sessionData)['token'];
var uid = JSON.parse(sessionData)['uid'];
this.store.find('account', uid).then(function(o) {
o.get('favorites').push(commentId);
o.save().then(function(success) {
console.log('Comment saved');
}, function(error) {
console.log('Error: Comment was not saved');
});
});
}
}
});
| Save favorite comments to account | Save favorite comments to account
| JavaScript | mit | stevenwu/hacker-news | ---
+++
@@ -17,7 +17,7 @@
var followTarget = userId;
- var record = this.store.find('account', uid).then(addFollowing);
+ this.store.find('account', uid).then(addFollowing);
function addFollowing(user) {
var newList = user.get('following').push(userId);
user.save().then(null, function(error) {
@@ -27,8 +27,20 @@
console.log('Following ' + userId);
},
+
saveComment: function(commentId) {
- console.log('Comment saved');
+ var sessionData = sessionStorage['firebase:session::ember-hacker-news'];
+ var authToken = JSON.parse(sessionData)['token'];
+ var uid = JSON.parse(sessionData)['uid'];
+
+ this.store.find('account', uid).then(function(o) {
+ o.get('favorites').push(commentId);
+ o.save().then(function(success) {
+ console.log('Comment saved');
+ }, function(error) {
+ console.log('Error: Comment was not saved');
+ });
+ });
}
}
}); |
3436424d9d945c3132fa196f219fe08fd6887dcd | lib/optionlist.js | lib/optionlist.js | import PropTypes from "prop-types";
import React, { Component } from "react";
import {
StyleSheet,
ScrollView,
View,
TouchableWithoutFeedback,
ViewPropTypes
} from "react-native";
export default class OptionList extends Component {
static defaultProps = {
onSelect: () => {}
};
static propTypes = {
style: ViewPropTypes.style,
onSelect: PropTypes.func
};
render() {
const { style, children, onSelect, selectedStyle, selected } = this.props;
const renderedItems = React.Children.map(children, (item, key) => (
<TouchableWithoutFeedback
key={key}
style={{ borderWidth: 0 }}
onPress={() => onSelect(item.props.children, item.props.value)}
>
<View
style={[
{ borderWidth: 0 },
item.props.value === selected ? selectedStyle : null
]}
>
{item}
</View>
</TouchableWithoutFeedback>
));
return (
<View style={[styles.scrollView, style]}>
<ScrollView automaticallyAdjustContentInsets={false} bounces={false}>
{renderedItems}
</ScrollView>
</View>
);
}
}
var styles = StyleSheet.create({
scrollView: {
height: 120,
width: 300,
borderWidth: 1
}
});
| import PropTypes from "prop-types";
import React, { Component } from "react";
import {
StyleSheet,
ScrollView,
View,
TouchableWithoutFeedback,
ViewPropTypes
} from "react-native";
export default class OptionList extends Component {
static defaultProps = {
onSelect: () => {}
};
static propTypes = {
style: ViewPropTypes.style,
onSelect: PropTypes.func
};
render() {
const { style, children, onSelect, selectedStyle, selected } = this.props;
const renderedItems = React.Children.map(children, (item, key) => (
if (!item) return null
<TouchableWithoutFeedback
key={key}
style={{ borderWidth: 0 }}
onPress={() => onSelect(item.props.children, item.props.value)}
>
<View
style={[
{ borderWidth: 0 },
item.props.value === selected ? selectedStyle : null
]}
>
{item}
</View>
</TouchableWithoutFeedback>
));
return (
<View style={[styles.scrollView, style]}>
<ScrollView automaticallyAdjustContentInsets={false} bounces={false}>
{renderedItems}
</ScrollView>
</View>
);
}
}
var styles = StyleSheet.create({
scrollView: {
height: 120,
width: 300,
borderWidth: 1
}
});
| Make OptionList return gracefully when iterating over falsy values | Make OptionList return gracefully when iterating over falsy values | JavaScript | mit | gs-akhan/react-native-chooser | ---
+++
@@ -20,6 +20,7 @@
render() {
const { style, children, onSelect, selectedStyle, selected } = this.props;
const renderedItems = React.Children.map(children, (item, key) => (
+ if (!item) return null
<TouchableWithoutFeedback
key={key}
style={{ borderWidth: 0 }} |
c0204e51c9077f8771f495bb1ffa224e25655322 | website/app/components/project/processes/mc-project-processes.component.js | website/app/components/project/processes/mc-project-processes.component.js | (function (module) {
module.component('mcProjectProcesses', {
templateUrl: 'components/project/processes/mc-project-processes.html',
controller: 'MCProjectProcessesComponentController'
});
module.controller('MCProjectProcessesComponentController', MCProjectProcessesComponentController);
MCProjectProcessesComponentController.$inject = ["project", "$stateParams"];
function MCProjectProcessesComponentController(project, $stateParams) {
var ctrl = this;
ctrl.processes = project.get().processes;
///////////////////////////
}
}(angular.module('materialscommons')));
| (function (module) {
module.component('mcProjectProcesses', {
templateUrl: 'components/project/processes/mc-project-processes.html',
controller: 'MCProjectProcessesComponentController'
});
module.controller('MCProjectProcessesComponentController', MCProjectProcessesComponentController);
MCProjectProcessesComponentController.$inject = ['project', '$stateParams', '$state', '$filter'];
function MCProjectProcessesComponentController(project, $stateParams, $state, $filter) {
var ctrl = this;
ctrl.processes = project.get().processes;
if (!$stateParams.process_id && ctrl.processes.length) {
ctrl.processes = $filter('orderBy')(ctrl.processes, 'name');
var firstProcess = ctrl.processes[0];
$state.go('project.processes.process', {process_id: firstProcess.id});
}
///////////////////////////
}
}(angular.module('materialscommons')));
| Sort processes and if there is no process id go to the first one. | Sort processes and if there is no process id go to the first one.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -5,12 +5,18 @@
});
module.controller('MCProjectProcessesComponentController', MCProjectProcessesComponentController);
- MCProjectProcessesComponentController.$inject = ["project", "$stateParams"];
- function MCProjectProcessesComponentController(project, $stateParams) {
+ MCProjectProcessesComponentController.$inject = ['project', '$stateParams', '$state', '$filter'];
+ function MCProjectProcessesComponentController(project, $stateParams, $state, $filter) {
var ctrl = this;
ctrl.processes = project.get().processes;
+ if (!$stateParams.process_id && ctrl.processes.length) {
+ ctrl.processes = $filter('orderBy')(ctrl.processes, 'name');
+ var firstProcess = ctrl.processes[0];
+ $state.go('project.processes.process', {process_id: firstProcess.id});
+ }
+
///////////////////////////
}
}(angular.module('materialscommons'))); |
f24f75fc51c6bf508ec122bc5f25bcaaf1988219 | index.js | index.js | #!/usr/bin/env node
const express = require('express');
const fileExists = require('file-exists');
const bodyParser = require('body-parser');
const fs = require('fs');
const { port = 8123 } = require('minimist')(process.argv.slice(2));
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('*', (req, res) => {
const filePath = req.get('X-Requested-File-Path');
if (!filePath) {
return res.status(500).send('Server did not provide file path');
}
if (!fileExists(filePath)) {
return res.status(404).send('Cannot find such file on the server');
}
try {
require(filePath)(req, res); // eslint-disable-line global-require
} catch (e) {
return res.status(500).send(`<pre>${e.stack}</pre>`);
}
const watcher = fs.watch(filePath, (eventType) => {
if (eventType === 'change') {
delete require.cache[require.resolve(filePath)];
watcher.close();
}
});
return undefined;
});
app.listen(port, () => {
console.log(`node-direct listening on port ${port}!`);
});
| #!/usr/bin/env node
const express = require('express');
const fileExists = require('file-exists');
const bodyParser = require('body-parser');
const fs = require('fs');
const { port = 8123 } = require('minimist')(process.argv.slice(2));
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.all('*', (req, res) => {
const filePath = req.get('X-Requested-File-Path');
if (!filePath) {
return res.status(500).send('Server did not provide file path');
}
if (!fileExists(filePath)) {
return res.status(404).send('Cannot find such file on the server');
}
try {
require(filePath)(req, res); // eslint-disable-line global-require
} catch (e) {
return res.status(500).send(`<pre>${e.stack}</pre>`);
}
const watcher = fs.watch(filePath, (eventType) => {
if (eventType === 'change') {
delete require.cache[require.resolve(filePath)];
watcher.close();
}
});
return undefined;
});
app.listen(port, () => {
console.log(`node-direct listening on port ${port}!`);
});
| Handle all requests, not only GET | feat: Handle all requests, not only GET
| JavaScript | mit | finom/node-direct,finom/node-direct | ---
+++
@@ -10,7 +10,7 @@
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
-app.get('*', (req, res) => {
+app.all('*', (req, res) => {
const filePath = req.get('X-Requested-File-Path');
if (!filePath) { |
2db58a7024cade6d205a55afcfa40cf12bd43c69 | index.js | index.js | 'use strict';
var deepFind = function(obj, path) {
if ((typeof obj !== "object") | obj === null) {
return undefined;
}
if (typeof path === 'string') {
path = path.split('.');
}
if (!Array.isArray(path)) {
path = path.concat();
}
return path.reduce(function (o, part) {
var keys = part.match(/\[(.*?)\]/);
if (keys) {
var key = part.replace(keys[0], '');
return o[key][keys[1]];
}
return o[part];
}, obj);
};
module.exports = deepFind;
| 'use strict';
var deepFind = function(obj, path) {
if (((typeof obj !== "object") && (typeof obj !== "function")) | obj === null) {
return undefined;
}
if (typeof path === 'string') {
path = path.split('.');
}
if (!Array.isArray(path)) {
path = path.concat();
}
return path.reduce(function (o, part) {
var keys = part.match(/\[(.*?)\]/);
if (keys) {
var key = part.replace(keys[0], '');
return o[key][keys[1]];
}
return o[part];
}, obj);
};
module.exports = deepFind;
| Add capability to retrieve properties of functions | Add capability to retrieve properties of functions
| JavaScript | mit | yashprit/deep-find | ---
+++
@@ -2,7 +2,7 @@
var deepFind = function(obj, path) {
- if ((typeof obj !== "object") | obj === null) {
+ if (((typeof obj !== "object") && (typeof obj !== "function")) | obj === null) {
return undefined;
}
if (typeof path === 'string') { |
c9a7cc0dd50e934bb214c7988081b2bbe5bfa397 | lib/stringutil.js | lib/stringutil.js | /*jshint node: true */
"use strict";
module.exports = {
/**
* Returns true if and only if the string value of the first argument
* ends with the given suffix. Otherwise, returns false. Does NOT support
* the length argument.
*
* Normally, one would just use String.prototype.endsWith, but since there
* are Node versions out there which don't support ES6 yet, this function
* exists. It either wraps the native method, or alternatively performs
* the check manually.
*/
endsWith: function (str, suffix) {
var subject = str.toString();
if (typeof subject.endsWith === "function") {
return subject.endsWith(suffix);
}
if (suffix === "") {
return true;
}
return subject.slice(-suffix.length) === suffix;
},
};
| /*jshint node: true */
"use strict";
module.exports = {
/**
* Returns true if and only if the string value of the first argument
* ends with the given suffix. Otherwise, returns false. Does NOT support
* the length argument.
*
* Normally, one would just use String.prototype.endsWith, but since there
* are Node versions out there which don't support ES6 yet, this function
* exists. It either wraps the native method, or alternatively performs
* the check manually.
*/
endsWith: function (str, suffix) {
var subject = str.toString();
suffix = "" + suffix;
if (typeof subject.endsWith === "function") {
return subject.endsWith(suffix);
}
if (suffix === "") {
return true;
}
return subject.slice(-suffix.length) === suffix;
},
};
| Fix TypeError for endsWith() with `null` suffix | Fix TypeError for endsWith() with `null` suffix
| JavaScript | mit | JangoBrick/teval,JangoBrick/teval | ---
+++
@@ -16,6 +16,7 @@
endsWith: function (str, suffix) {
var subject = str.toString();
+ suffix = "" + suffix;
if (typeof subject.endsWith === "function") {
return subject.endsWith(suffix); |
d4a1349279c3218f75db94e3243cd272bf05e5e4 | app.js | app.js | /*jshint esversion: 6 */
const primed = angular.module('primed', ['ngRoute', 'ngResource']);
| /*jshint esversion: 6 */
const primed = angular.module('primed', ['ngRoute', 'ngResource']);
primed.controller('homeController', ['$scope', function($scope) {
}]);
primed.controller('forecastController', ['$scope', function($scope) {
}]);
| Set up controllers for home and forecast | Set up controllers for home and forecast
| JavaScript | mit | adam-rice/Primed,adam-rice/Primed | ---
+++
@@ -1,3 +1,11 @@
/*jshint esversion: 6 */
const primed = angular.module('primed', ['ngRoute', 'ngResource']);
+
+primed.controller('homeController', ['$scope', function($scope) {
+
+}]);
+
+primed.controller('forecastController', ['$scope', function($scope) {
+
+}]); |
4bdcfd07a97de370aead0cbb8a9707568c9e4138 | test/page.js | test/page.js | var fs = require('fs');
var path = require('path');
var assert = require('assert');
var page = require('../').parse.page;
var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/PAGE.md'), 'utf8');
var LEXED = page(CONTENT);
describe('Page parsing', function() {
it('should detection sections', function() {
assert.equal(LEXED.length, 3);
});
it('should detection section types', function() {
assert.equal(LEXED[0].type, 'normal');
assert.equal(LEXED[1].type, 'exercise');
assert.equal(LEXED[2].type, 'normal');
});
it('should gen content for normal sections', function() {
assert(LEXED[0].content);
assert(LEXED[2].content);
});
it('should gen code and content for exercise sections', function() {
assert(LEXED[1].content);
assert(LEXED[1].code);
assert(LEXED[1].code.base);
assert(LEXED[1].code.solution);
assert(LEXED[1].code.validation);
});
});
| var fs = require('fs');
var path = require('path');
var assert = require('assert');
var page = require('../').parse.page;
var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/PAGE.md'), 'utf8');
var LEXED = page(CONTENT);
var HR_CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/HR_PAGE.md'), 'utf8');
var HR_LEXED = page(HR_CONTENT);
describe('Page parsing', function() {
it('should detection sections', function() {
assert.equal(LEXED.length, 3);
});
it('should detection section types', function() {
assert.equal(LEXED[0].type, 'normal');
assert.equal(LEXED[1].type, 'exercise');
assert.equal(LEXED[2].type, 'normal');
});
it('should gen content for normal sections', function() {
assert(LEXED[0].content);
assert(LEXED[2].content);
});
it('should gen code and content for exercise sections', function() {
assert(LEXED[1].content);
assert(LEXED[1].code);
assert(LEXED[1].code.base);
assert(LEXED[1].code.solution);
assert(LEXED[1].code.validation);
});
it('should merge sections correctly', function() {
// One big section
assert.equal(HR_LEXED.length, 1);
// HRs inserted correctly
assert.equal(HR_LEXED[0].content.match(/<hr>/g).length, 2);
});
});
| Add tests for section merging | Add tests for section merging
| JavaScript | apache-2.0 | svenkatreddy/gitbook,intfrr/gitbook,guiquanz/gitbook,minghe/gitbook,GitbookIO/gitbook,qingying5810/gitbook,ferrior30/gitbook,haamop/documentation,palerdot/gitbook,gaearon/gitbook,ShaguptaS/gitbook,escopecz/documentation,rohan07/gitbook,bjlxj2008/gitbook,gaearon/gitbook,ferrior30/gitbook,jocr1627/gitbook,bjlxj2008/gitbook,iflyup/gitbook,jasonslyvia/gitbook,youprofit/gitbook,alex-dixon/gitbook,guiquanz/gitbook,CN-Sean/gitbook,shibe97/gitbook,xiongjungit/gitbook,switchspan/gitbook,jasonslyvia/gitbook,npracht/documentation,nycitt/gitbook,tshoper/gitbook,gencer/gitbook,youprofit/gitbook,npracht/documentation,hongbinz/gitbook,justinleoye/gitbook,FKV587/gitbook,athiruban/gitbook,wewelove/gitbook,codepiano/gitbook,intfrr/gitbook,vehar/gitbook,a-moses/gitbook,ZachLamb/gitbook,xcv58/gitbook,iamchenxin/gitbook,snowsnail/gitbook,palerdot/gitbook,CN-Sean/gitbook,sunlianghua/gitbook,megumiteam/documentation,grokcoder/gitbook,sunlianghua/gitbook,minghe/gitbook,hujianfei1989/gitbook,qingying5810/gitbook,gdbooks/gitbook,ryanswanson/gitbook,jocr1627/gitbook,webwlsong/gitbook,hujianfei1989/gitbook,iflyup/gitbook,OriPekelman/gitbook,haamop/documentation,grokcoder/gitbook,vehar/gitbook,alex-dixon/gitbook,bradparks/gitbook,wewelove/gitbook,iamchenxin/gitbook,xcv58/gitbook,sudobashme/gitbook,escopecz/documentation,rohan07/gitbook,snowsnail/gitbook,lucciano/gitbook,a-moses/gitbook,nycitt/gitbook,gencer/gitbook,2390183798/gitbook,Abhikos/gitbook,mautic/documentation,thelastmile/gitbook,mruse/gitbook,codepiano/gitbook,anrim/gitbook,mautic/documentation,bradparks/gitbook,kamyu104/gitbook,JohnTroony/gitbook,mruse/gitbook,JohnTroony/gitbook,xxxhycl2010/gitbook,megumiteam/documentation,yaonphy/SwiftBlog,boyXiong/gitbook,OriPekelman/gitbook,justinleoye/gitbook,FKV587/gitbook,lucciano/gitbook,xiongjungit/gitbook,ZachLamb/gitbook,ShaguptaS/gitbook,Keystion/gitbook,JozoVilcek/gitbook,hongbinz/gitbook,gdbooks/gitbook,2390183798/gitbook,kamyu104/gitbook,webwlsong/gitbook,tshoper/gitbook,svenkatreddy/gitbook,tzq668766/gitbook,tzq668766/gitbook,athiruban/gitbook,strawluffy/gitbook,switchspan/gitbook,thelastmile/gitbook,shibe97/gitbook,boyXiong/gitbook,xxxhycl2010/gitbook,sudobashme/gitbook | ---
+++
@@ -7,6 +7,9 @@
var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/PAGE.md'), 'utf8');
var LEXED = page(CONTENT);
+
+var HR_CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/HR_PAGE.md'), 'utf8');
+var HR_LEXED = page(HR_CONTENT);
describe('Page parsing', function() {
it('should detection sections', function() {
@@ -31,4 +34,12 @@
assert(LEXED[1].code.solution);
assert(LEXED[1].code.validation);
});
+
+ it('should merge sections correctly', function() {
+ // One big section
+ assert.equal(HR_LEXED.length, 1);
+
+ // HRs inserted correctly
+ assert.equal(HR_LEXED[0].content.match(/<hr>/g).length, 2);
+ });
}); |
ae10cb3c2b3dd964c6d1f0bd670410b1833db1a5 | index.js | index.js | require('./lib/boot/logger');
var defaultConfig = {
amqpUrl: process.env.AMQP_URL || 'amqp://localhost',
amqpPrefetch: process.env.AMQP_PREFETCH || 10,
amqpRequeue: true
};
module.exports = function(config) {
for (var key in config) {
if (config.hasOwnProperty(key) && defaultConfig.hasOwnProperty(key)) {
defaultConfig[key] = config[key];
}
}
defaultConfig.amqpPrefetch = parseInt(defaultConfig.amqpPrefetch);
return {
producer: require('./lib/producer')(defaultConfig),
consumer: require('./lib/consumer')(defaultConfig)
};
};
| require('./lib/boot/logger');
var defaultConfig = {
amqpUrl: process.env.AMQP_URL || 'amqp://localhost',
amqpPrefetch: process.env.AMQP_PREFETCH || 0,
amqpRequeue: true
};
module.exports = function(config) {
for (var key in config) {
if (config.hasOwnProperty(key) && defaultConfig.hasOwnProperty(key)) {
defaultConfig[key] = config[key];
}
}
defaultConfig.amqpPrefetch = parseInt(defaultConfig.amqpPrefetch);
return {
producer: require('./lib/producer')(defaultConfig),
consumer: require('./lib/consumer')(defaultConfig)
};
};
| Set default prefetech to unlimited value | Set default prefetech to unlimited value
| JavaScript | mit | dial-once/node-bunnymq | ---
+++
@@ -2,7 +2,7 @@
var defaultConfig = {
amqpUrl: process.env.AMQP_URL || 'amqp://localhost',
- amqpPrefetch: process.env.AMQP_PREFETCH || 10,
+ amqpPrefetch: process.env.AMQP_PREFETCH || 0,
amqpRequeue: true
};
|
9bb668b1066497413f8abd0fff79e835ff781662 | index.js | index.js | var path = require('path');
var findParentDir = require('find-parent-dir');
var fs = require('fs');
function resolve(targetUrl, source) {
var packageRoot = findParentDir.sync(source, 'node_modules');
if (!packageRoot) {
return null;
}
var filePath = path.resolve(packageRoot, 'node_modules', targetUrl);
var isPotentiallyDirectory = !path.extname(filePath);
if (isPotentiallyDirectory) {
if (fs.existsSync(filePath + '.scss')) {
return path.resolve(filePath, 'index');
}
if (fs.existsSync(filePath)) {
return path.resolve(filePath, 'index');
}
}
if (fs.existsSync(path.dirname(filePath))) {
return filePath;
}
return resolve(targetUrl, path.dirname(packageRoot));
}
module.exports = function importer (url, prev, done) {
return (url[ 0 ] === '~') ? { file: resolve(url.substr(1), prev) } : null;
};
| var path = require('path');
var findParentDir = require('find-parent-dir');
var fs = require('fs');
function resolve(targetUrl, source) {
var packageRoot = findParentDir.sync(source, 'node_modules');
if (!packageRoot) {
return null;
}
var filePath = path.resolve(packageRoot, 'node_modules', targetUrl);
var isPotentiallyDirectory = !path.extname(filePath);
if (isPotentiallyDirectory) {
if (fs.existsSync(filePath + '.scss')) {
return filePath + '.scss';
}
if (fs.existsSync(filePath)) {
return path.resolve(filePath, 'index');
}
}
if (fs.existsSync(path.dirname(filePath))) {
return filePath;
}
return resolve(targetUrl, path.dirname(packageRoot));
}
module.exports = function importer (url, prev, done) {
return (url[ 0 ] === '~') ? { file: resolve(url.substr(1), prev) } : null;
};
| Fix path on .scss file detected | Fix path on .scss file detected | JavaScript | apache-2.0 | matthewdavidson/node-sass-tilde-importer | ---
+++
@@ -14,7 +14,7 @@
if (isPotentiallyDirectory) {
if (fs.existsSync(filePath + '.scss')) {
- return path.resolve(filePath, 'index');
+ return filePath + '.scss';
}
if (fs.existsSync(filePath)) { |
d21950affe91ead5be06c1197441577053464dcc | index.js | index.js | 'use strict';
var throttle = require('throttleit');
function requestProgress(request, options) {
var reporter;
var delayTimer;
var delayCompleted;
var totalSize;
var previousReceivedSize;
var receivedSize = 0;
var state = {};
options = options || {};
options.throttle = options.throttle == null ? 1000 : options.throttle;
options.delay = options.delay || 0;
request
.on('response', function (response) {
state.total = totalSize = Number(response.headers['content-length']);
receivedSize = 0;
// Check if there's no total size or is invalid (NaN)
if (!totalSize) {
return;
}
// Throttle the function
reporter = throttle(function () {
// If there received size is the same, abort
if (previousReceivedSize === receivedSize) {
return;
}
state.received = previousReceivedSize = receivedSize;
state.percent = Math.round(receivedSize / totalSize * 100);
request.emit('progress', state);
}, options.throttle);
// Delay the progress report
delayTimer = setTimeout(function () {
delayCompleted = true;
delayTimer = null;
}, options.delay);
})
.on('data', function (data) {
receivedSize += data.length;
if (delayCompleted) {
reporter();
}
})
.on('end', function () {
if (!delayCompleted) {
clearTimeout(delayTimer);
}
});
return request;
}
module.exports = requestProgress;
| 'use strict';
var throttle = require('throttleit');
function requestProgress(request, options) {
var reporter;
var delayTimer;
var delayCompleted;
var totalSize;
var previousReceivedSize;
var receivedSize = 0;
var state = {};
options = options || {};
options.throttle = options.throttle == null ? 1000 : options.throttle;
options.delay = options.delay || 0;
request
.on('request', function () {
receivedSize = 0;
})
.on('response', function (response) {
state.total = totalSize = Number(response.headers['content-length']);
receivedSize = 0;
// Check if there's no total size or is invalid (NaN)
if (!totalSize) {
return;
}
// Throttle the function
reporter = throttle(function () {
// If there received size is the same, abort
if (previousReceivedSize === receivedSize) {
return;
}
state.received = previousReceivedSize = receivedSize;
state.percent = Math.round(receivedSize / totalSize * 100);
request.emit('progress', state);
}, options.throttle);
// Delay the progress report
delayTimer = setTimeout(function () {
delayCompleted = true;
delayTimer = null;
}, options.delay);
})
.on('data', function (data) {
receivedSize += data.length;
if (delayCompleted) {
reporter();
}
})
.on('end', function () {
if (!delayCompleted) {
clearTimeout(delayTimer);
}
});
return request;
}
module.exports = requestProgress;
| Reset size also on 'request'. | Reset size also on 'request'.
| JavaScript | mit | IndigoUnited/node-request-progress | ---
+++
@@ -16,6 +16,9 @@
options.delay = options.delay || 0;
request
+ .on('request', function () {
+ receivedSize = 0;
+ })
.on('response', function (response) {
state.total = totalSize = Number(response.headers['content-length']);
receivedSize = 0; |
8aef4999d40fa0cedd3deb56daadbcd09eeece09 | index.js | index.js | 'use strict';
import { NativeAppEventEmitter, NativeModules } from 'react-native';
const ReactNativeBluetooth = NativeModules.ReactNativeBluetooth;
const didChangeState = (callback) => {
var subscription = NativeAppEventEmitter.addListener(
ReactNativeBluetooth.StateChanged,
callback
);
ReactNativeBluetooth.notifyCurrentState();
return function() {
subscription.remove();
};
};
export default {
didChangeState,
};
| 'use strict';
import { NativeAppEventEmitter, NativeModules } from 'react-native';
const ReactNativeBluetooth = NativeModules.ReactNativeBluetooth;
const didChangeState = (callback) => {
var subscription = NativeAppEventEmitter.addListener(
ReactNativeBluetooth.StateChanged,
callback
);
ReactNativeBluetooth.notifyCurrentState();
return function() {
subscription.remove();
};
};
const DefaultScanOptions = {
uuids: [],
timeout: 10000,
};
const Scan = {
stopAfter: (timeout) => {
return new Promise(resolve => {
setTimeout(() => {
ReactNativeBluetooth.stopScan()
.then(resolve)
.catch(console.log.bind(console));
}, timeout);
})
}
}
const startScan = (customOptions = {}) => {
let options = Object.assign({}, DefaultScanOptions, customOptions);
return ReactNativeBluetooth.startScan(options.uuids).then(() => Scan);
}
const didDiscoverDevice = (callback) => {
var subscription = NativeAppEventEmitter.addListener(
ReactNativeBluetooth.DeviceDiscovered,
callback
);
return function() {
subscription.remove();
};
};
export default {
didChangeState,
startScan,
didDiscoverDevice,
};
| Implement startScan(), stopScan() and didDiscoverDevice() | js: Implement startScan(), stopScan() and didDiscoverDevice()
| JavaScript | apache-2.0 | sogilis/react-native-bluetooth,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth,sogilis/react-native-bluetooth,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth-manager,sogilis/react-native-bluetooth | ---
+++
@@ -16,6 +16,42 @@
};
};
+const DefaultScanOptions = {
+ uuids: [],
+ timeout: 10000,
+};
+
+const Scan = {
+ stopAfter: (timeout) => {
+ return new Promise(resolve => {
+ setTimeout(() => {
+ ReactNativeBluetooth.stopScan()
+ .then(resolve)
+ .catch(console.log.bind(console));
+ }, timeout);
+ })
+ }
+}
+
+const startScan = (customOptions = {}) => {
+ let options = Object.assign({}, DefaultScanOptions, customOptions);
+
+ return ReactNativeBluetooth.startScan(options.uuids).then(() => Scan);
+}
+
+const didDiscoverDevice = (callback) => {
+ var subscription = NativeAppEventEmitter.addListener(
+ ReactNativeBluetooth.DeviceDiscovered,
+ callback
+ );
+
+ return function() {
+ subscription.remove();
+ };
+};
+
export default {
didChangeState,
+ startScan,
+ didDiscoverDevice,
}; |
49dfc1e0d40375461c49699bf4285e17ab725e35 | index.js | index.js | module.exports = function(options) {
var cb = (options && options.variable) || 'cb';
var regexp = new RegExp('(?:\\b|&)' + cb + '=([a-zA-Z$_][a-zA-Z0-9$_]*)(?:&|$)');
return {
reshook: function(server, tile, req, res, result, callback) {
if (result.headers['Content-Type'] !== 'application/json') return callback();
if (!tile.qs) return callback();
var match = tile.qs.match(regexp);
if (!match) return callback();
var callbackName = match[1];
var callbackLength = callbackName.length;
var newBuffer = new Buffer(result.buffer.length + callbackLength + 2);
newBuffer.write(callbackName + '(');
newBuffer.write(result.buffer.toString('utf8'), callbackLength + 1);
newBuffer.write(')', newBuffer.length - 1);
result.buffer = newBuffer;
result.headers['Content-Type'] = 'text/javascript';
callback();
}
};
};
| module.exports = function(options) {
var cb = (options && options.variable) || 'cb';
var regexp = new RegExp('(?:\\b|&)' + cb + '=([a-zA-Z$_][\.a-zA-Z0-9$_]*)(?:&|$)');
return {
reshook: function(server, tile, req, res, result, callback) {
if (result.headers['Content-Type'] !== 'application/json') return callback();
if (!tile.qs) return callback();
var match = tile.qs.match(regexp);
if (!match) return callback();
var callbackName = match[1];
var callbackLength = callbackName.length;
var newBuffer = new Buffer(result.buffer.length + callbackLength + 2);
newBuffer.write(callbackName + '(');
newBuffer.write(result.buffer.toString('utf8'), callbackLength + 1);
newBuffer.write(')', newBuffer.length - 1);
result.buffer = newBuffer;
result.headers['Content-Type'] = 'text/javascript';
callback();
}
};
};
| Allow dots in callback names. | Allow dots in callback names.
| JavaScript | apache-2.0 | naturalatlas/tilestrata-jsonp | ---
+++
@@ -1,6 +1,6 @@
module.exports = function(options) {
var cb = (options && options.variable) || 'cb';
- var regexp = new RegExp('(?:\\b|&)' + cb + '=([a-zA-Z$_][a-zA-Z0-9$_]*)(?:&|$)');
+ var regexp = new RegExp('(?:\\b|&)' + cb + '=([a-zA-Z$_][\.a-zA-Z0-9$_]*)(?:&|$)');
return {
reshook: function(server, tile, req, res, result, callback) {
if (result.headers['Content-Type'] !== 'application/json') return callback(); |
1a88800d7b13b65206818de6e472ceef30054892 | index.js | index.js | const ghost = require('ghost');
ghost().then(function (ghostServer) {
ghostServer.start();
});
| const ghost = require('ghost');
ghost({
config: path.join(__dirname, 'config.js')
}).then(function (ghostServer) {
ghostServer.start();
});
| Add explicit config.js to ghost constructor | Add explicit config.js to ghost constructor
| JavaScript | mit | jtanguy/clevercloud-ghost | ---
+++
@@ -1,5 +1,7 @@
const ghost = require('ghost');
-ghost().then(function (ghostServer) {
+ghost({
+ config: path.join(__dirname, 'config.js')
+}).then(function (ghostServer) {
ghostServer.start();
}); |
a6542ba90043060ae4a878688a7913497913695d | index.js | index.js | "use strict";
var express = require("express");
module.exports = function () {
var app = express();
// 404 everything
app.all("*", function (req, res) {
res.status(404);
res.jsonp({ error: "404 - page not found" });
});
return app;
};
| "use strict";
var express = require("express");
module.exports = function () {
var app = express();
// fake handler for the books endpoints
app.get("/books/:isbn", function (req, res) {
var isbn = req.param("isbn");
res.jsonp({
isbn: isbn,
title: "Title of " + isbn,
author: "Author of " + isbn,
});
});
// 404 everything
app.all("*", function (req, res) {
res.status(404);
res.jsonp({ error: "404 - page not found" });
});
return app;
};
| Add handler to return faked book results | Add handler to return faked book results
| JavaScript | agpl-3.0 | OpenBookPrices/openbookprices-api | ---
+++
@@ -5,6 +5,16 @@
module.exports = function () {
var app = express();
+
+ // fake handler for the books endpoints
+ app.get("/books/:isbn", function (req, res) {
+ var isbn = req.param("isbn");
+ res.jsonp({
+ isbn: isbn,
+ title: "Title of " + isbn,
+ author: "Author of " + isbn,
+ });
+ });
// 404 everything
app.all("*", function (req, res) { |
a326ba30f5781c1a1297bb20636023021ed4baab | tests/unit/components/tooltip-on-parent-test.js | tests/unit/components/tooltip-on-parent-test.js | import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
let component;
moduleForComponent('tooltip-on-parent', 'Unit | Component | tooltip on parent', {
unit: true,
setup() {
component = this.subject();
},
});
test('The component registers itself', function(assert) {
const parentView = Ember.View.create({
renderTooltip() {
assert.ok(true,
'The renderTooltip() method should be called on the parent view after render');
}
});
assert.expect(4);
component.set('parentView', parentView);
assert.equal(component._state, 'preRender',
'Should create the component instance');
assert.ok(!!component.registerOnParent,
'The component should have a public registerOnParent method');
this.render();
assert.equal(component._state, 'inDOM');
});
| import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
let component;
moduleForComponent('tooltip-on-parent', 'Unit | Component | tooltip on parent', {
unit: true,
setup() {
component = this.subject();
},
});
test('The component registers itself', function(assert) {
const parentView = Ember.View.create({
renderTooltip() {
assert.ok(true,
'The renderTooltip() method should be called on the parent view after render');
}
});
assert.expect(3);
component.set('parentView', parentView);
assert.equal(component._state, 'preRender',
'Should create the component instance');
assert.ok(!!component.registerOnParent,
'The component should have a public registerOnParent method');
this.render();
});
| Fix for tooltip on parent element being removed | Fix for tooltip on parent element being removed
| JavaScript | mit | sir-dunxalot/ember-tooltips,cdl/ember-tooltips,cdl/ember-tooltips,zenefits/ember-tooltips,zenefits/ember-tooltips,kmiyashiro/ember-tooltips,maxhungry/ember-tooltips,sir-dunxalot/ember-tooltips,maxhungry/ember-tooltips,kmiyashiro/ember-tooltips | ---
+++
@@ -19,7 +19,7 @@
}
});
- assert.expect(4);
+ assert.expect(3);
component.set('parentView', parentView);
@@ -31,6 +31,4 @@
this.render();
- assert.equal(component._state, 'inDOM');
-
}); |
0ad5c3272b7e63337c4196b2ebc08eac07dfadc1 | app/assets/javascripts/responses.js | app/assets/javascripts/responses.js | $(document).ready( function () {
$("button.upvote").click( function() {
var commentId = $(".upvote").data("id");
event.preventDefault();
$.ajax({
url: '/response/up_vote',
method: 'POST',
data: { id: commentId },
dataType: 'JSON'
}).done( function (response) {
}).fail( function (response) {
console.log(response);
})
})
})
| $(document).ready( function () {
$("button.upvote").click( function() {
var commentId = $(".upvote").data("id");
event.preventDefault();
$.ajax({
url: '/response/up_vote',
method: 'POST',
data: { id: commentId },
dataType: 'JSON'
}).done( function (response) {
$("button.upvote").closest(".response").append("<p>" + response + "</p>")
}).fail( function (response) {
console.log("Failed. Here is the response:")
console.log(response);
})
})
})
| Add ajax to upvote a response. | Add ajax to upvote a response.
| JavaScript | mit | great-horned-owls-2014/dbc-what-is-this,great-horned-owls-2014/dbc-what-is-this | ---
+++
@@ -8,7 +8,9 @@
data: { id: commentId },
dataType: 'JSON'
}).done( function (response) {
+ $("button.upvote").closest(".response").append("<p>" + response + "</p>")
}).fail( function (response) {
+ console.log("Failed. Here is the response:")
console.log(response);
})
}) |
cdaf0617ab59f81b251ab92cb7f797e3b626dbc1 | cli.js | cli.js | #!/usr/bin/env node
'use strict';
var meow = require('meow');
var zipGot = require('./');
var objectAssign = require('object-assign');
var cli = meow({
help: [
'Usage',
' zip-got <url> <exclude-patterns>... --cleanup --extract',
'',
'Example',
' zip-got http://unicorns.com/unicorns.zip \'__MACOSX/**\' \'bower.json\' \'README.md\' \'LICENSE.md\' --dest=\'./.tmp\' --cleanup --extract',
'',
'Options',
'--dest: dest path to download a zip file',
'--cleanup: remove the zip file after extracting',
'--extract: extract the zip file after downloading',
'',
'<url> url of zip file trying to download',
'<exclude-patterns> pattern to exclude some of the files when it is extracted'
]
});
var url = cli.input.shift();
var opts = objectAssign({
exclude: cli.input,
dest: cli.flags.dest || process.cwd(),
cleanup: cli.flags.cleanup,
extract: cli.flags.extract
});
zipGot(url, opts, function(err) {
if (err) {
console.error(err);
return;
}
console.log(url, 'has been downloaded');
});
| #!/usr/bin/env node
'use strict';
var meow = require('meow');
var zipGot = require('./');
var objectAssign = require('object-assign');
var cli = meow({
help: [
'Usage',
' zip-got <url> <exclude-patterns>... --cleanup --extract',
'',
'Example',
' zip-got http://unicorns.com/unicorns.zip \'__MACOSX/**\' \'bower.json\' \'README.md\' \'LICENSE.md\' --dest=\'./.tmp\' --cleanup --extract',
'',
'Options',
'--dest: dest path to download a zip file',
'--cleanup: remove the zip file after extracting',
'--extract: extract the zip file after downloading',
'',
'<url> url of zip file trying to download',
'<exclude-patterns> pattern to exclude some of the files when it is extracted'
]
});
var url = cli.input.shift();
var opts = objectAssign({
exclude: cli.input,
dest: process.cwd()
}, cli.flags);
zipGot(url, opts, function(err) {
if (err) {
console.error(err);
return;
}
console.log(url, 'has been downloaded');
});
| Fix code style of assign | Fix code style of assign
| JavaScript | mit | ragingwind/zip-got,ragingwind/node-got-zip | ---
+++
@@ -25,10 +25,8 @@
var url = cli.input.shift();
var opts = objectAssign({
exclude: cli.input,
- dest: cli.flags.dest || process.cwd(),
- cleanup: cli.flags.cleanup,
- extract: cli.flags.extract
-});
+ dest: process.cwd()
+}, cli.flags);
zipGot(url, opts, function(err) {
if (err) { |
7af0c2ae8b4b051f380c11bef21cc4f3ef5ee2b8 | config/protractor.config.js | config/protractor.config.js | require('ts-node/register');
exports.config = {
baseUrl: 'http://127.0.0.1:8100/',
seleniumAddress: 'http://127.0.0.1:4723/wd/hub',
specs: [
'../src/**/*.e2e.ts'
],
exclude: [],
framework: 'mocha',
allScriptsTimeout: 110000,
directConnect: true,
capabilities: {
'browserName': 'chrome',
'deviceName' : 'Android Emulator',
'chromeOptions': {
args: ['--disable-web-security'],
}
},
onPrepare: function() {
browser.ignoreSynchronization = true;
}
};
| require('ts-node/register');
exports.config = {
baseUrl: 'http://127.0.0.1:8100/',
seleniumAddress: 'http://127.0.0.1:4723/wd/hub',
specs: [
'../src/**/*.e2e.ts'
],
exclude: [],
framework: 'mocha',
allScriptsTimeout: 110000,
directConnect: true,
capabilities: {
'browserName': 'chrome',
'deviceName' : 'Android Emulator',
'chromeOptions': {
args: ['--disable-web-security'],
}
},
onPrepare: function() {
// browser.ignoreSynchronization = true;
}
};
| Modify to wait until angular is loaded on protractor | Modify to wait until angular is loaded on protractor
| JavaScript | mit | takeo-asai/typescript-starter,takeo-asai/typescript-starter,takeo-asai/typescript-starter,takeo-asai/typescript-starter | ---
+++
@@ -23,6 +23,6 @@
},
onPrepare: function() {
- browser.ignoreSynchronization = true;
+ // browser.ignoreSynchronization = true;
}
}; |
75ef865f8867e45cfe60b8222de85ea20ac50670 | server/controllers/userFiles.js | server/controllers/userFiles.js | //
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const path = require('path'),
send = require('koa-send'),
conf = require('../lib/conf');
const oneYearInSeconds = 60 * 60 * 24 * 365;
let dataDirectory = path.normalize(conf.get('files:upload_directory'));
// TBD: move this to library. Add exists check.
if (dataDirectory.charAt(0) !== path.sep) {
dataDirectory = path.join(__dirname, '..', '..', dataDirectory);
}
module.exports = function*() {
let file = this.params.file;
let firstTwo = file.substring(0, 2);
yield send(this, dataDirectory + path.sep + firstTwo + path.sep + file);
this.set('Cache-Control', 'public, max-age=' + oneYearInSeconds);
};
| //
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const path = require('path'),
send = require('koa-send'),
conf = require('../lib/conf');
const oneYearInSeconds = 60 * 60 * 24 * 365;
let dataDirectory = path.normalize(conf.get('files:upload_directory'));
// TBD: move this to library. Add exists check.
if (dataDirectory.charAt(0) !== path.sep) {
dataDirectory = path.join(__dirname, '..', '..', dataDirectory);
}
module.exports = function*() {
let file = this.params.file;
let filePath = path.join(file.substring(0, 2), file);
yield send(this, filePath, { root: dataDirectory });
this.set('Cache-Control', 'public, max-age=' + oneYearInSeconds);
};
| Fix serving of user uploaded files | Fix serving of user uploaded files
| JavaScript | apache-2.0 | ilkkao/mas,ilkkao/mas,ilkkao/mas,ilkkao/mas | ---
+++
@@ -30,9 +30,9 @@
module.exports = function*() {
let file = this.params.file;
- let firstTwo = file.substring(0, 2);
+ let filePath = path.join(file.substring(0, 2), file);
- yield send(this, dataDirectory + path.sep + firstTwo + path.sep + file);
+ yield send(this, filePath, { root: dataDirectory });
this.set('Cache-Control', 'public, max-age=' + oneYearInSeconds);
}; |
81702fccfd16cae2feb1d083cfc782c1fb9ecc3c | src/js/utils/ScrollbarUtil.js | src/js/utils/ScrollbarUtil.js | import GeminiScrollbar from 'react-gemini-scrollbar';
let scrollbarWidth = null;
const ScrollbarUtil = {
/**
* Taken from Gemini's source code with some edits
* https://github.com/noeldelgado/gemini-scrollbar/blob/master/index.js#L22
* @param {Object} options
* @return {Number} The width of the native scrollbar
*/
getScrollbarWidth(options = {}) {
if (scrollbarWidth == null || options.forceUpdate) {
let element = global.document.createElement('div');
element.style.position = 'absolute';
element.style.top = '-9999px';
element.style.width = '100px';
element.style.height = '100px';
element.style.overflow = 'scroll';
element.style.msOverflowStyle = 'scrollbar';
global.document.body.appendChild(element);
scrollbarWidth = (element.offsetWidth - element.clientWidth);
global.document.body.removeChild(element);
}
return scrollbarWidth;
},
updateWithRef(containerRef) {
// Use the containers gemini ref if present
if (containerRef.geminiRef != null) {
this.updateWithRef(containerRef.geminiRef);
return;
}
if (containerRef instanceof GeminiScrollbar) {
containerRef.scrollbar.update();
}
}
};
module.exports = ScrollbarUtil;
| import GeminiScrollbar from 'react-gemini-scrollbar';
let scrollbarWidth = null;
const ScrollbarUtil = {
/**
* Taken from Gemini's source code with some edits
* https://github.com/noeldelgado/gemini-scrollbar/blob/master/index.js#L22
* @param {Object} options
* @return {Number} The width of the native scrollbar
*/
getScrollbarWidth(options = {}) {
if (scrollbarWidth == null || options.forceUpdate) {
let element = global.document.createElement('div');
element.style.position = 'absolute';
element.style.top = '-9999px';
element.style.width = '100px';
element.style.height = '100px';
element.style.overflow = 'scroll';
element.style.msOverflowStyle = 'scrollbar';
global.document.body.appendChild(element);
scrollbarWidth = (element.offsetWidth - element.clientWidth);
global.document.body.removeChild(element);
}
return scrollbarWidth;
},
updateWithRef(containerRef) {
// Use the containers gemini ref if present
if (containerRef != null && containerRef.geminiRef != null) {
this.updateWithRef(containerRef.geminiRef);
return;
}
if (containerRef instanceof GeminiScrollbar) {
containerRef.scrollbar.update();
}
}
};
module.exports = ScrollbarUtil;
| Add null check for containerRef | Add null check for containerRef
| JavaScript | apache-2.0 | dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui | ---
+++
@@ -29,8 +29,8 @@
},
updateWithRef(containerRef) {
- // Use the containers gemini ref if present
- if (containerRef.geminiRef != null) {
+ // Use the containers gemini ref if present
+ if (containerRef != null && containerRef.geminiRef != null) {
this.updateWithRef(containerRef.geminiRef);
return; |
ec25aaaa53dcfa271f73a8f45fe65fd6e15f7973 | src/utils/is-plain-object.js | src/utils/is-plain-object.js | // Adapted from https://github.com/jonschlinkert/is-plain-object
function isObject(val) {
return val != null && typeof val === 'object' && Array.isArray(val) === false;
}
function isObjectObject(o) {
return isObject(o) === true
&& Object.prototype.toString.call(o) === '[object Object]';
}
export default function isPlainObject(o) {
if (isObjectObject(o) === false) return false;
// If has modified constructor
const ctor = o.constructor;
if (typeof ctor !== 'function') return false;
// If has modified prototype
const prot = ctor.prototype;
if (isObjectObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) {
return false;
}
// Most likely a plain Object
return true;
}
| // Adapted from https://github.com/jonschlinkert/is-plain-object
function isObject(val) {
return val != null && typeof val === 'object' && Array.isArray(val) === false;
}
function isObjectObject(o) {
return isObject(o) === true
&& Object.prototype.toString.call(o) === '[object Object]';
}
export default function isPlainObject(o) {
if (isObjectObject(o) === false) return false;
// If has modified constructor
const ctor = o.constructor;
if (typeof ctor !== 'function') return false;
// If has modified prototype
const prot = ctor.prototype;
if (isObjectObject(prot) === false) return false;
// If constructor does not have an Object-specific method
if (prot.hasOwnProperty('isPrototypeOf') === false) { // eslint-disable-line no-prototype-builtins
return false;
}
// Most likely a plain Object
return true;
}
| Disable the lint error about using hasOwnProperty. That call should be fine in this context. | Disable the lint error about using hasOwnProperty. That call should be fine in this context.
| JavaScript | mit | chentsulin/react-redux-sweetalert | ---
+++
@@ -20,7 +20,7 @@
if (isObjectObject(prot) === false) return false;
// If constructor does not have an Object-specific method
- if (prot.hasOwnProperty('isPrototypeOf') === false) {
+ if (prot.hasOwnProperty('isPrototypeOf') === false) { // eslint-disable-line no-prototype-builtins
return false;
}
|
99f1680999747da59ef4b90bafddb467a92c5e19 | assets/js/modules/optimize/index.js | assets/js/modules/optimize/index.js | /**
* Optimize module initialization.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { addFilter } from '@wordpress/hooks';
/**
* Internal dependencies
*/
import './datastore';
import { SetupMain as OptimizeSetup } from './components/setup';
import { SettingsMain as OptimizeSettings } from './components/settings';
import { fillFilterWithComponent } from '../../util';
/**
* Add components to the settings page.
*/
addFilter(
'googlesitekit.ModuleSettingsDetails-optimize',
'googlesitekit.OptimizeModuleSettingsDetails',
fillFilterWithComponent( OptimizeSettings )
);
/**
* Add component to the setup wizard.
*/
addFilter(
'googlesitekit.ModuleSetup-optimize',
'googlesitekit.OptimizeModuleSetupWizard',
fillFilterWithComponent( OptimizeSetup )
);
| /**
* Optimize module initialization.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import domReady from '@wordpress/dom-ready';
import { addFilter } from '@wordpress/hooks';
/**
* Internal dependencies
*/
import './datastore';
import Data from 'googlesitekit-data';
import { SetupMain as OptimizeSetup } from './components/setup';
import { SettingsEdit, SettingsView } from './components/settings';
import { fillFilterWithComponent } from '../../util';
import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
/**
* Add component to the setup wizard.
*/
addFilter(
'googlesitekit.ModuleSetup-optimize',
'googlesitekit.OptimizeModuleSetupWizard',
fillFilterWithComponent( OptimizeSetup )
);
domReady( () => {
Data.dispatch( CORE_MODULES ).registerModule(
'optimize',
{
settingsEditComponent: SettingsEdit,
settingsViewComponent: SettingsView,
}
);
} );
| Refactor Optimize with registered components. | Refactor Optimize with registered components.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -19,24 +19,18 @@
/**
* WordPress dependencies
*/
+import domReady from '@wordpress/dom-ready';
import { addFilter } from '@wordpress/hooks';
/**
* Internal dependencies
*/
import './datastore';
+import Data from 'googlesitekit-data';
import { SetupMain as OptimizeSetup } from './components/setup';
-import { SettingsMain as OptimizeSettings } from './components/settings';
+import { SettingsEdit, SettingsView } from './components/settings';
import { fillFilterWithComponent } from '../../util';
-
-/**
- * Add components to the settings page.
- */
-addFilter(
- 'googlesitekit.ModuleSettingsDetails-optimize',
- 'googlesitekit.OptimizeModuleSettingsDetails',
- fillFilterWithComponent( OptimizeSettings )
-);
+import { STORE_NAME as CORE_MODULES } from '../../googlesitekit/modules/datastore/constants';
/**
* Add component to the setup wizard.
@@ -46,3 +40,13 @@
'googlesitekit.OptimizeModuleSetupWizard',
fillFilterWithComponent( OptimizeSetup )
);
+
+domReady( () => {
+ Data.dispatch( CORE_MODULES ).registerModule(
+ 'optimize',
+ {
+ settingsEditComponent: SettingsEdit,
+ settingsViewComponent: SettingsView,
+ }
+ );
+} ); |
d4b9fd4ab129d3e5f8eefcdc368f951e8fd51bee | src/js/posts/components/search-posts-well.js | src/js/posts/components/search-posts-well.js | import React from 'react';
import PropTypes from 'prop-types';
import {
Well, InputGroup, FormControl, Button, Glyphicon
} from 'react-bootstrap';
class SearchPostsWell extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
if (this.props.onSubmit) {
const q = this.q.value.trim();
if (q) {
this.props.onSubmit(q);
}
}
}
render() {
const {q, pending} = this.props;
return (
<Well>
<h4>Blog Search</h4>
<form autoComplete="off" onSubmit={this.handleSubmit}>
<InputGroup>
<FormControl inputRef={ ref => {
this.q = ref;
}}
defaultValue={q} />
<InputGroup.Button>
<Button disabled={pending}>
<Glyphicon glyph="search" />
</Button>
</InputGroup.Button>
</InputGroup>
</form>
</Well>
);
}
}
SearchPostsWell.propTypes = {
q: PropTypes.string,
pending: PropTypes.bool,
onSubmit: PropTypes.func
};
export default SearchPostsWell; | import React from 'react';
import PropTypes from 'prop-types';
import {
Well, InputGroup, FormControl, Button, Glyphicon
} from 'react-bootstrap';
class SearchPostsWell extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
if (this.props.onSubmit) {
const q = this.q.value.trim();
if (q) {
this.props.onSubmit(q);
}
}
}
render() {
const {q, pending} = this.props;
return (
<Well>
<h4>Blog Search</h4>
<form autoComplete="off" onSubmit={this.handleSubmit}>
<InputGroup>
<FormControl inputRef={ ref => {
this.q = ref;
}}
defaultValue={q} />
<InputGroup.Button>
<Button disabled={pending} type="submit">
<Glyphicon glyph="search" />
</Button>
</InputGroup.Button>
</InputGroup>
</form>
</Well>
);
}
}
SearchPostsWell.propTypes = {
q: PropTypes.string,
pending: PropTypes.bool,
onSubmit: PropTypes.func
};
export default SearchPostsWell;
| Use submit button type in search posts well. | Use submit button type in search posts well.
| JavaScript | mit | akornatskyy/sample-blog-react-redux,akornatskyy/sample-blog-react-redux | ---
+++
@@ -35,7 +35,7 @@
}}
defaultValue={q} />
<InputGroup.Button>
- <Button disabled={pending}>
+ <Button disabled={pending} type="submit">
<Glyphicon glyph="search" />
</Button>
</InputGroup.Button> |
507b31b8ec5b3234db3a32e2c0a0359c9ac2cccb | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/app/src/components/Counter/Counter.js | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/app/src/components/Counter/Counter.js | import React, {useState} from 'react';
import PropTypes from 'prop-types';
const Counter = ({initialCount}) => {
const [count, setCount] = useState(initialCount);
const increment = () => setCount(count + 1);
return (
<div>
<h2>Count: {count}</h2>
<button
type="button"
onClick={increment}
>
Increment
</button>
</div>
);
};
Counter.propTypes = {
initialCount: PropTypes.number,
};
Counter.defaultProps = {
initialCount: 0,
};
export default Counter;
| import React, {useState} from 'react';
import PropTypes from 'prop-types';
const Counter = ({initialCount}) => {
const [count, setCount] = useState(initialCount);
const increment = useCallback(() => setCount(count + 1), [count]);
return (
<div>
<h2>Count: {count}</h2>
<button
type="button"
onClick={increment}
>
Increment
</button>
</div>
);
};
Counter.propTypes = {
initialCount: PropTypes.number,
};
Counter.defaultProps = {
initialCount: 0,
};
export default Counter;
| Use useCallback so that `increment` is memoized | Use useCallback so that `increment` is memoized
| JavaScript | isc | thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template | ---
+++
@@ -3,7 +3,7 @@
const Counter = ({initialCount}) => {
const [count, setCount] = useState(initialCount);
- const increment = () => setCount(count + 1);
+ const increment = useCallback(() => setCount(count + 1), [count]);
return (
<div> |
f24990cf94729e2aa25ea6e8cf4a32e0e38b150f | lib/control-panel.js | lib/control-panel.js | "use strict";
var messages = require("./messages");
var config = require("./config");
var snippetUtils = require("./snippet").utils;
var connect = require("connect");
var http = require("http");
/**
* Launch the server for serving the client JS plus static files
* @param {String} scriptTags
* @param {Object} options
* @param {Function} scripts
* @returns {http.Server}
*/
module.exports.launchControlPanel = function (scriptTags, options, scripts) {
var clientScripts = messages.clientScript(options, true);
var app =
connect()
.use(clientScripts.versioned, scripts)
.use(snippetUtils.getSnippetMiddleware(scriptTags))
.use(connect.static(config.controlPanel.baseDir));
return http.createServer(app);
}; | "use strict";
var messages = require("./messages");
var config = require("./config");
var snippetUtils = require("./snippet").utils;
var connect = require("connect");
var http = require("http");
/**
* Launch the server for serving the client JS plus static files
* @param {String} scriptTags
* @param {Object} options
* @param {Function} scripts
* @returns {http.Server}
*/
module.exports.launchControlPanel = function (scriptTags, options, scripts) {
var clientScripts = messages.clientScript(options, true);
var app =
connect()
.use(clientScripts.versioned, scripts)
.use(clientScripts.path, scripts)
.use(snippetUtils.getSnippetMiddleware(scriptTags))
.use(connect.static(config.controlPanel.baseDir));
return http.createServer(app);
}; | Make un-versioned client script return the latest | Make un-versioned client script return the latest
| JavaScript | apache-2.0 | EdwonLim/browser-sync,stevemao/browser-sync,stevemao/browser-sync,zhelezko/browser-sync,EdwonLim/browser-sync,syarul/browser-sync,BrowserSync/browser-sync,Plou/browser-sync,nitinsurana/browser-sync,schmod/browser-sync,chengky/browser-sync,BrowserSync/browser-sync,schmod/browser-sync,Teino1978-Corp/Teino1978-Corp-browser-sync,chengky/browser-sync,michaelgilley/browser-sync,d-g-h/browser-sync,mcanthony/browser-sync,felixdae/browser-sync,pepelsbey/browser-sync,beni55/browser-sync,harmoney-nikr/browser-sync,michaelgilley/browser-sync,Plou/browser-sync,nitinsurana/browser-sync,pmq20/browser-sync,syarul/browser-sync,guiquanz/browser-sync,Teino1978-Corp/Teino1978-Corp-browser-sync,d-g-h/browser-sync,mnquintana/browser-sync,lookfirst/browser-sync,markcatley/browser-sync,guiquanz/browser-sync,pepelsbey/browser-sync,naoyak/browser-sync,BrowserSync/browser-sync,zhelezko/browser-sync,BrowserSync/browser-sync,shelsonjava/browser-sync,cnbin/browser-sync,portned/browser-sync,pmq20/browser-sync,Iced-Tea/browser-sync,Iced-Tea/browser-sync,harmoney-nikr/browser-sync,portned/browser-sync,mcanthony/browser-sync,felixdae/browser-sync,nothiphop/browser-sync,beni55/browser-sync,shelsonjava/browser-sync,nothiphop/browser-sync,naoyak/browser-sync | ---
+++
@@ -21,6 +21,7 @@
var app =
connect()
.use(clientScripts.versioned, scripts)
+ .use(clientScripts.path, scripts)
.use(snippetUtils.getSnippetMiddleware(scriptTags))
.use(connect.static(config.controlPanel.baseDir));
|
57a15a5194bc95b77110150d06d05a7b870804ce | lib/graceful-exit.js | lib/graceful-exit.js | var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = function(radiodan){
return function() {
clearPlayers(radiodan.cache.players).then(
function() {
process.exit(1);
}
);
function clearPlayers(players) {
var playerIds = Object.keys(players),
resolved = utils.promise.resolve();
if(playerIds.length === 0){
return resolved;
}
return Object.keys(players).reduce(function(previous, current){
return previous.then(players[current].clear);
}, resolved);
}
};
};
| var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = function(radiodan){
return function() {
clearPlayers(radiodan.cache.players).then(
function() {
process.exit(0);
},
function() {
process.exit(1);
}
);
function clearPlayers(players) {
var playerIds = Object.keys(players),
resolved = utils.promise.resolve();
if(playerIds.length === 0){
return resolved;
}
return Object.keys(players).reduce(function(previous, current){
return previous.then(players[current].clear);
}, resolved);
}
};
};
| Add exit(1) if any promises fail during exit | Add exit(1) if any promises fail during exit
| JavaScript | apache-2.0 | radiodan/magic-button,radiodan/magic-button | ---
+++
@@ -4,6 +4,9 @@
module.exports = function(radiodan){
return function() {
clearPlayers(radiodan.cache.players).then(
+ function() {
+ process.exit(0);
+ },
function() {
process.exit(1);
} |
8baf5366ca919593fe2f00dc245cba9eac984139 | bot.js | bot.js | var Twit = require('twit');
var twitInfo = [consumer_key, consumer_secret, access_token, access_token_secret];
//use when testing locally
// var twitInfo = require('./config.js')
var twitter = new Twit(twitInfo);
var useUpperCase = function(wordList) {
var tempList = Object.keys(wordList).filter(function(word) {
return word[0] >= "A" && word[0] <= "Z";
});
return tempList[~~(Math.random()*tempList.length)];
};
var MarkovChain = require('markovchain')
, fs = require('fs')
, quotes = new MarkovChain(fs.readFileSync('./rabelais.txt', 'utf8'));
function generateSentence() {
return quotes.start(useUpperCase).end(Math.floor((Math.random() * 3) + 6)).process() + ".";
}
function postTweet(sentence) {
var tweet = {
status: sentence
};
twitter.post('statuses/update', tweet , function(err, data, response) {
if (err) {
// console.log("5OMeTh1nG weNt wR0ng");
} else {
// console.log("Tweet sucessful");
}
});
}
postTweet(generateSentence);
// second parameter is in miliseconds
setInterval(postTweet(generateSentence), 1000*60*60*11);
| var Twit = require('twit');
var twitInfo = [CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET];
//use when testing locally
// var twitInfo = require('./config.js')
var twitter = new Twit(twitInfo);
var useUpperCase = function(wordList) {
var tempList = Object.keys(wordList).filter(function(word) {
return word[0] >= "A" && word[0] <= "Z";
});
return tempList[~~(Math.random()*tempList.length)];
};
var MarkovChain = require('markovchain')
, fs = require('fs')
, quotes = new MarkovChain(fs.readFileSync('./rabelais.txt', 'utf8'));
function generateSentence() {
return quotes.start(useUpperCase).end(Math.floor((Math.random() * 3) + 6)).process() + ".";
}
function postTweet(sentence) {
var tweet = {
status: sentence
};
twitter.post('statuses/update', tweet , function(err, data, response) {
if (err) {
// console.log("5OMeTh1nG weNt wR0ng");
} else {
// console.log("Tweet sucessful");
}
});
}
postTweet(generateSentence);
// second parameter is in miliseconds
MNMNsetInterval(postTweet(generateSentence), 1000*60*60*11);
| Change API keys to uppercase | Change API keys to uppercase
| JavaScript | mit | almightyboz/RabelaisMarkov | ---
+++
@@ -1,5 +1,5 @@
var Twit = require('twit');
-var twitInfo = [consumer_key, consumer_secret, access_token, access_token_secret];
+var twitInfo = [CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET];
//use when testing locally
// var twitInfo = require('./config.js')
@@ -38,4 +38,4 @@
postTweet(generateSentence);
// second parameter is in miliseconds
-setInterval(postTweet(generateSentence), 1000*60*60*11);
+MNMNsetInterval(postTweet(generateSentence), 1000*60*60*11); |
cb7990566b9ac406946d57a0c4f00fb625d21efd | cli.js | cli.js | #!/usr/bin/env node
var browserslist = require('./');
var pkg = require('./package.json');
var args = process.argv.slice(2);
if ( args.length <= 0 || args.indexOf('--help') >= 0 ) {
console.log([
'',
pkg.name + ' - ' + pkg.description,
'',
'Usage:',
'',
' ' + pkg.name + ' query ...'
].join('\n'));
return;
}
if ( args.indexOf('--version') >= 0 ) {
console.log(pkg.version);
return;
}
browserslist(args).forEach(function (browser) {
console.log(browser);
});
| #!/usr/bin/env node
var browserslist = require('./');
var pkg = require('./package.json');
var args = process.argv.slice(2);
function isArg(arg) {
return args.indexOf(arg) >= 0;
}
if ( args.length === 0 || isArg('--help') >= 0 || isArg('-h') >= 0 ) {
console.log([
'',
pkg.name + ' - ' + pkg.description,
'',
'Usage:',
'',
' ' + pkg.name + ' query ...'
].join('\n'));
return;
}
if ( args.indexOf('--version') >= 0 ) {
console.log(pkg.version);
return;
}
browserslist(args).forEach(function (browser) {
console.log(browser);
});
| Add -h option to CLI | Add -h option to CLI
| JavaScript | mit | mdix/browserslist,ai/browserslist | ---
+++
@@ -4,7 +4,11 @@
var pkg = require('./package.json');
var args = process.argv.slice(2);
-if ( args.length <= 0 || args.indexOf('--help') >= 0 ) {
+function isArg(arg) {
+ return args.indexOf(arg) >= 0;
+}
+
+if ( args.length === 0 || isArg('--help') >= 0 || isArg('-h') >= 0 ) {
console.log([
'',
pkg.name + ' - ' + pkg.description, |
7cd66b92b824262a898bf539b0faba5ace6eaa0c | raf.js | raf.js | /*
* raf.js
* https://github.com/ngryman/raf.js
*
* original requestAnimationFrame polyfill by Erik Möller
* inspired from paul_irish gist and post
*
* Copyright (c) 2013 ngryman
* Licensed under the MIT license.
*/
(function(window) {
var lastTime = 0,
vendors = ['webkit', 'moz'],
requestAnimationFrame = window.requestAnimationFrame,
cancelAnimationFrame = window.cancelAnimationFrame,
i = vendors.length;
// try to un-prefix existing raf
while (--i >= 0 && !requestAnimationFrame) {
requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame'];
}
// polyfill with setTimeout fallback
// heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945
if (!requestAnimationFrame || !cancelAnimationFrame) {
requestAnimationFrame = function(callback) {
var now = Date.now(), nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() {
callback(lastTime = nextTime);
}, nextTime - now);
};
cancelAnimationFrame = clearTimeout;
}
// export to window
window.requestAnimationFrame = requestAnimationFrame;
window.cancelAnimationFrame = cancelAnimationFrame;
}(window)); | /*
* raf.js
* https://github.com/ngryman/raf.js
*
* original requestAnimationFrame polyfill by Erik Möller
* inspired from paul_irish gist and post
*
* Copyright (c) 2013 ngryman
* Licensed under the MIT license.
*/
(function(window) {
var lastTime = 0,
vendors = ['webkit', 'moz'],
requestAnimationFrame = window.requestAnimationFrame,
cancelAnimationFrame = window.cancelAnimationFrame,
i = vendors.length;
// try to un-prefix existing raf
while (--i >= 0 && !requestAnimationFrame) {
requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame'];
}
// polyfill with setTimeout fallback
// heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945
if (!requestAnimationFrame || !cancelAnimationFrame) {
requestAnimationFrame = function(callback) {
var now = new Date().getTime(), nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() {
callback(lastTime = nextTime);
}, nextTime - now);
};
cancelAnimationFrame = clearTimeout;
}
// export to window
window.requestAnimationFrame = requestAnimationFrame;
window.cancelAnimationFrame = cancelAnimationFrame;
}(window));
| Fix IE 8 by using compatible date methods | Fix IE 8 by using compatible date methods
`Date.now()` is not supported in IE8 | JavaScript | mit | ngryman/raf.js | ---
+++
@@ -26,7 +26,7 @@
// heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945
if (!requestAnimationFrame || !cancelAnimationFrame) {
requestAnimationFrame = function(callback) {
- var now = Date.now(), nextTime = Math.max(lastTime + 16, now);
+ var now = new Date().getTime(), nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() {
callback(lastTime = nextTime);
}, nextTime - now); |
315f321d0c0d55669519cee39d0218cc4b71323f | src/js/actions/NotificationsActions.js | src/js/actions/NotificationsActions.js | import AppDispatcher from '../dispatcher/AppDispatcher';
import AppConstants from '../constants/AppConstants';
export default {
add: function(type, content) {
var id = Date.now();
var notification = { _id: id, type: type, content: content };
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_ADD,
notification : notification
});
setTimeout(() => {
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_REMOVE,
_id : id
});
}, 2000);
}
}
| import AppDispatcher from '../dispatcher/AppDispatcher';
import AppConstants from '../constants/AppConstants';
export default {
add: function(type, content, duration) {
if(duration === undefined) duration = 3000;
var id = Date.now();
var notification = { _id: id, type: type, content: content };
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_ADD,
notification : notification
});
setTimeout(() => {
AppDispatcher.dispatch({
actionType : AppConstants.APP_NOTIFICATION_REMOVE,
_id : id
});
}, duration);
}
}
| Add duration to notifications API | Add duration to notifications API
| JavaScript | mit | KeitIG/museeks,KeitIG/museeks,MrBlenny/museeks,KeitIG/museeks,MrBlenny/museeks | ---
+++
@@ -5,7 +5,9 @@
export default {
- add: function(type, content) {
+ add: function(type, content, duration) {
+
+ if(duration === undefined) duration = 3000;
var id = Date.now();
var notification = { _id: id, type: type, content: content };
AppDispatcher.dispatch({
@@ -18,6 +20,6 @@
actionType : AppConstants.APP_NOTIFICATION_REMOVE,
_id : id
});
- }, 2000);
+ }, duration);
}
} |
33904221107d2f521b743ad06162b7b274f2d9ca | html/js/code.js | html/js/code.js | $(document).ready(function(){
var latlng = new google.maps.LatLng(45.5374054, -122.65028);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
function correctHeight() {
var window_height = $(window).height();
var header_height = $("#search-container").offset().top;
$("#search-results").height(window_height - header_height - 20); //-20 for padding
$("#map_canvas").height(window_height - header_height);
}
correctHeight();
jQuery.event.add(window, "resize", correctHeight);
});
| var makeMap = function() {
var latlng = new google.maps.LatLng(45.5374054, -122.65028);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
function correctHeight() {
var window_height = $(window).height();
var header_height = $("#search-container").offset().top;
$("#search-results").height(window_height - header_height - 20); //-20 for padding
$("#map_canvas").height(window_height - header_height);
}
correctHeight();
jQuery.event.add(window, "resize", correctHeight);
};
$(document).ready(makeMap);
| Create makeMap function (helps for testing later) | Create makeMap function (helps for testing later)
| JavaScript | mit | jlavallee/HotGator,jlavallee/HotGator | ---
+++
@@ -1,4 +1,5 @@
-$(document).ready(function(){
+var makeMap = function() {
+
var latlng = new google.maps.LatLng(45.5374054, -122.65028);
var myOptions = {
zoom: 8,
@@ -16,4 +17,6 @@
correctHeight();
jQuery.event.add(window, "resize", correctHeight);
-});
+};
+
+$(document).ready(makeMap); |
3e4c82c5571f056be85fed1ae0fe3349ecfbb3d9 | config/webpack-config-legacy-build.js | config/webpack-config-legacy-build.js | const path = require('path');
module.exports = {
entry: './build/index.js',
devtool: 'source-map',
mode: 'production',
resolve: {
alias: {
ol: path.resolve('./src/ol'),
},
},
output: {
path: path.resolve('./build/legacy'),
filename: 'ol.js',
library: 'ol',
libraryTarget: 'umd',
libraryExport: 'default',
},
};
| const path = require('path');
module.exports = {
entry: './build/index.js',
devtool: 'source-map',
mode: 'production',
resolve: {
alias: {
ol: path.resolve('./build/ol'),
},
},
output: {
path: path.resolve('./build/legacy'),
filename: 'ol.js',
library: 'ol',
libraryTarget: 'umd',
libraryExport: 'default',
},
};
| Use transpiled modules for legacy build | Use transpiled modules for legacy build
| JavaScript | bsd-2-clause | oterral/ol3,stweil/ol3,stweil/openlayers,adube/ol3,ahocevar/ol3,adube/ol3,ahocevar/openlayers,stweil/openlayers,ahocevar/openlayers,ahocevar/ol3,ahocevar/ol3,ahocevar/openlayers,oterral/ol3,stweil/ol3,adube/ol3,openlayers/openlayers,stweil/openlayers,ahocevar/ol3,stweil/ol3,oterral/ol3,stweil/ol3,openlayers/openlayers,bjornharrtell/ol3,bjornharrtell/ol3,bjornharrtell/ol3,openlayers/openlayers | ---
+++
@@ -5,7 +5,7 @@
mode: 'production',
resolve: {
alias: {
- ol: path.resolve('./src/ol'),
+ ol: path.resolve('./build/ol'),
},
},
output: { |
da7a5d7b717df6312bba26de5cf83fab651c37d8 | src/validation-strategies/one-valid-issue.js | src/validation-strategies/one-valid-issue.js | import issueStrats from '../issue-strategies/index.js';
import * as promiseUtils from '../promise-utils.js';
function validateStrategies(issueKey, jiraClientAPI) {
return jiraClientAPI.findIssue(issueKey)
.then(content =>
issueStrats[content.fields.issuetype.name].apply(content, jiraClientAPI)
)
.catch(content => Promise.reject(new Error(`${issueKey} does not have a valid issuetype`)));
}
export default function apply(issues, jiraClientAPI) {
return promiseUtils.anyPromise(issues.map(i => validateStrategies(i, jiraClientAPI)));
}
| import issueStrats from '../issue-strategies/index.js';
import * as promiseUtils from '../promise-utils.js';
function validateStrategies(issueKey, jiraClientAPI) {
return jiraClientAPI.findIssue(issueKey)
.then(content => {
if (!issueStrats[content.fields.issuetype.name]) {
return Promise.reject(new Error(`${issueKey} does not have a valid issuetype`));
}
return issueStrats[content.fields.issuetype.name].apply(content, jiraClientAPI);
});
}
export default function apply(issues, jiraClientAPI) {
return promiseUtils.anyPromise(issues.map(i => validateStrategies(i, jiraClientAPI)));
}
| Fix bug in no issue validation logic | Fix bug in no issue validation logic
| JavaScript | mit | TWExchangeSolutions/jira-precommit-hook,DarriusWrightGD/jira-precommit-hook | ---
+++
@@ -3,10 +3,13 @@
function validateStrategies(issueKey, jiraClientAPI) {
return jiraClientAPI.findIssue(issueKey)
- .then(content =>
- issueStrats[content.fields.issuetype.name].apply(content, jiraClientAPI)
- )
- .catch(content => Promise.reject(new Error(`${issueKey} does not have a valid issuetype`)));
+ .then(content => {
+ if (!issueStrats[content.fields.issuetype.name]) {
+ return Promise.reject(new Error(`${issueKey} does not have a valid issuetype`));
+ }
+
+ return issueStrats[content.fields.issuetype.name].apply(content, jiraClientAPI);
+ });
}
export default function apply(issues, jiraClientAPI) { |
761be726ceecbbd6857e1d229729ad78d327a685 | src/utils/packetCodes.js | src/utils/packetCodes.js | module.exports = {
// Packet constants
PLAYER_START: "1",
PLAYER_ADD: "2",
PLAYER_ANGLE: "2",
PLAYER_UPDATE: "3",
PLAYER_ATTACK :"4",
LEADERBOAD: "5",
PLAYER_MOVE: "3",
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
LOAD_GAME_OBJ: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8",
CLAN_CREATE: "8",
PLAYER_LEAVE_CLAN: "9",
STAT_UPDATE: "9",
CLAN_REQ_JOIN: "10",
UPDATE_HEALTH: "10",
CLAN_ACC_JOIN: "11",
CLAN_KICK: "12",
ITEM_BUY: "13",
UPDATE_AGE: "15",
UPGRADES: "16",
CHAT: "ch",
CLAN_DEL: "ad",
PLAYER_SET_CLAN: "st",
SET_CLAN_PLAYERS: "sa",
CLAN_ADD: "ac",
CLAN_NOTIFY: "an",
MINIMAP: "mm",
UPDATE_STORE: "us",
DISCONN: "d"
} | module.exports = {
// Packet constants
PLAYER_START: "1",
PLAYER_ADD: "2",
PLAYER_ANGLE: "2",
PLAYER_UPDATE: "3",
PLAYER_ATTACK :"4",
LEADERBOAD: "5",
PLAYER_MOVE: "3",
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
LOAD_GAME_OBJ: "6",
PLAYER_UPGRADE: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8",
CLAN_CREATE: "8",
PLAYER_LEAVE_CLAN: "9",
STAT_UPDATE: "9",
CLAN_REQ_JOIN: "10",
UPDATE_HEALTH: "10",
CLAN_ACC_JOIN: "11",
CLAN_KICK: "12",
ITEM_BUY: "13",
UPDATE_AGE: "15",
UPGRADES: "16",
CHAT: "ch",
CLAN_DEL: "ad",
PLAYER_SET_CLAN: "st",
SET_CLAN_PLAYERS: "sa",
CLAN_ADD: "ac",
CLAN_NOTIFY: "an",
MINIMAP: "mm",
UPDATE_STORE: "us",
DISCONN: "d"
} | Add player upgrade packet code | Add player upgrade packet code
| JavaScript | mit | wwwwwwwwwwwwwwwwwwwwwwwwwwwwww/m.io | ---
+++
@@ -10,6 +10,7 @@
PLAYER_REMOVE: "4",
LEADERS_UPDATE: "5",
LOAD_GAME_OBJ: "6",
+ PLAYER_UPGRADE: "6",
GATHER_ANIM: "7",
AUTO_ATK: "7",
WIGGLE: "8", |
c8de21c9a250922a26741e98d79df683ccdcaa65 | www/src/app/pages/admin/organizations/list/organizations.page.controller.js | www/src/app/pages/admin/organizations/list/organizations.page.controller.js | 'use strict';
import _ from 'lodash/core';
export default class OrganizationsPageController {
constructor($log, OrganizationService) {
'ngInject';
this.$log = $log;
this.OrganizationService = OrganizationService;
}
$onInit() {
this.state = {
showForm: false,
formData: {}
};
}
create() {
this.OrganizationService.create(
_.pick(this.state.formData, ['name', 'description'])
).then(response => {
this.$log.log('Organization created', response);
this.reload();
this.$onInit();
});
}
disable(id) {
this.OrganizationService.disable(id).then(response => {
this.$log.log(`Organization ${id} deleted`, response);
this.reload();
});
}
enable(id) {
this.OrganizationService.enable(id).then(response => {
this.$log.log(`Organization ${id} deleted`, response);
this.reload();
});
}
reload() {
this.OrganizationService.list().then(
organizations => (this.organizations = organizations)
);
}
}
| 'use strict';
import _ from 'lodash/core';
export default class OrganizationsPageController {
constructor($log, OrganizationService, NotificationService, ModalService) {
'ngInject';
this.$log = $log;
this.OrganizationService = OrganizationService;
this.NotificationService = NotificationService;
this.ModalService = ModalService;
}
$onInit() {
this.state = {
showForm: false,
formData: {}
};
}
create() {
this.OrganizationService.create(
_.pick(this.state.formData, ['name', 'description'])
).then(response => {
this.$log.log('Organization created', response);
this.reload();
this.$onInit();
});
}
disable(id) {
let modalInstance = this.ModalService.confirm(
'Disable organization',
`Are your sure you want to disable this organization? Its users will no longer be able to have access to Cortex.`,
{
flavor: 'danger',
okText: 'Yes, disable it'
}
);
modalInstance.result
.then(() => this.OrganizationService.disable(id))
.then(() => {
this.reload();
this.NotificationService.success('The organization has been disabled');
})
.catch(err => {
if (!_.isString(err)) {
this.NotificationService.error('Unable to disable the organization.');
}
});
}
enable(id) {
let modalInstance = this.ModalService.confirm(
'Enable organization',
`Are your sure you want to enable this organization? Its users will have access to Cortex.`,
{
flavor: 'primary',
okText: 'Yes, enable it'
}
);
modalInstance.result
.then(() => this.OrganizationService.enable(id))
.then(() => {
this.reload();
this.NotificationService.success('The organization has been enabled');
})
.catch(err => {
if (!_.isString(err)) {
this.NotificationService.error('Unable to enabled the organization.');
}
});
}
reload() {
this.OrganizationService.list().then(
organizations => (this.organizations = organizations)
);
}
}
| Add confirmation dialog when enabling/disabling an organization | Add confirmation dialog when enabling/disabling an organization
| JavaScript | agpl-3.0 | CERT-BDF/Cortex,CERT-BDF/Cortex,CERT-BDF/Cortex,CERT-BDF/Cortex | ---
+++
@@ -3,11 +3,13 @@
import _ from 'lodash/core';
export default class OrganizationsPageController {
- constructor($log, OrganizationService) {
+ constructor($log, OrganizationService, NotificationService, ModalService) {
'ngInject';
this.$log = $log;
this.OrganizationService = OrganizationService;
+ this.NotificationService = NotificationService;
+ this.ModalService = ModalService;
}
$onInit() {
@@ -28,17 +30,49 @@
}
disable(id) {
- this.OrganizationService.disable(id).then(response => {
- this.$log.log(`Organization ${id} deleted`, response);
- this.reload();
- });
+ let modalInstance = this.ModalService.confirm(
+ 'Disable organization',
+ `Are your sure you want to disable this organization? Its users will no longer be able to have access to Cortex.`,
+ {
+ flavor: 'danger',
+ okText: 'Yes, disable it'
+ }
+ );
+
+ modalInstance.result
+ .then(() => this.OrganizationService.disable(id))
+ .then(() => {
+ this.reload();
+ this.NotificationService.success('The organization has been disabled');
+ })
+ .catch(err => {
+ if (!_.isString(err)) {
+ this.NotificationService.error('Unable to disable the organization.');
+ }
+ });
}
enable(id) {
- this.OrganizationService.enable(id).then(response => {
- this.$log.log(`Organization ${id} deleted`, response);
- this.reload();
- });
+ let modalInstance = this.ModalService.confirm(
+ 'Enable organization',
+ `Are your sure you want to enable this organization? Its users will have access to Cortex.`,
+ {
+ flavor: 'primary',
+ okText: 'Yes, enable it'
+ }
+ );
+
+ modalInstance.result
+ .then(() => this.OrganizationService.enable(id))
+ .then(() => {
+ this.reload();
+ this.NotificationService.success('The organization has been enabled');
+ })
+ .catch(err => {
+ if (!_.isString(err)) {
+ this.NotificationService.error('Unable to enabled the organization.');
+ }
+ });
}
reload() { |
d7070f4e55ba327ccce81de398d8a4ae66e38d06 | blueprints/ember-cli-react/index.js | blueprints/ember-cli-react/index.js | /*jshint node:true*/
var pkg = require('../../package.json');
function getPeerDependencyVersion(packageJson, name) {
var peerDependencies = packageJson.peerDependencies;
return peerDependencies[name];
}
module.exports = {
description: 'Install ember-cli-react dependencies into your app.',
normalizeEntityName: function() {},
// Install react into host app
afterInstall: function() {
const packages = [
{
name: 'react',
target: getPeerDependencyVersion(pkg, 'react'),
},
{
name: 'react-dom',
target: getPeerDependencyVersion(pkg, 'react-dom'),
},
];
return this.addPackagesToProject(packages);
},
};
| /*jshint node:true*/
var pkg = require('../../package.json');
function getDependencyVersion(packageJson, name) {
var dependencies = packageJson.dependencies;
var devDependencies = packageJson.devDependencies;
return dependencies[name] || devDependencies[name];
}
function getPeerDependencyVersion(packageJson, name) {
var peerDependencies = packageJson.peerDependencies;
return peerDependencies[name];
}
module.exports = {
description: 'Install ember-cli-react dependencies into your app.',
normalizeEntityName: function() {},
// Install react into host app
afterInstall: function() {
const packages = [
{
name: 'ember-auto-import',
target: getDependencyVersion(pkg, 'ember-auto-import'),
},
{
name: 'react',
target: getPeerDependencyVersion(pkg, 'react'),
},
{
name: 'react-dom',
target: getPeerDependencyVersion(pkg, 'react-dom'),
},
];
return this.addPackagesToProject(packages);
},
};
| Install `ember-auto-import` to Ember App during `ember install` | Install `ember-auto-import` to Ember App during `ember install`
| JavaScript | mit | pswai/ember-cli-react,pswai/ember-cli-react | ---
+++
@@ -1,6 +1,13 @@
/*jshint node:true*/
var pkg = require('../../package.json');
+
+function getDependencyVersion(packageJson, name) {
+ var dependencies = packageJson.dependencies;
+ var devDependencies = packageJson.devDependencies;
+
+ return dependencies[name] || devDependencies[name];
+}
function getPeerDependencyVersion(packageJson, name) {
var peerDependencies = packageJson.peerDependencies;
@@ -17,6 +24,10 @@
afterInstall: function() {
const packages = [
{
+ name: 'ember-auto-import',
+ target: getDependencyVersion(pkg, 'ember-auto-import'),
+ },
+ {
name: 'react',
target: getPeerDependencyVersion(pkg, 'react'),
}, |
e2367d78b76e73a56ca7e1d04c87d6727a169397 | lib/build/source-map-support.js | lib/build/source-map-support.js | /**
* See https://github.com/evanw/node-source-map-support#browser-support
* This is expected to be included in a browserify-module to give proper stack traces, based on browserify's source maps.
*/
require('source-map-support').install();
| /**
* See https://github.com/evanw/node-source-map-support#browser-support
* This is expected to be included in a browserify-module to give proper stack traces, based on browserify's source maps.
*/
if (window.location.search.indexOf('disablesourcemaps') === -1) {
require('source-map-support').install();
}
| Add querystring flag to disable sourcemaps | Add querystring flag to disable sourcemaps
| JavaScript | bsd-3-clause | splashblot/dronedb,codeandtheory/cartodb,splashblot/dronedb,CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,splashblot/dronedb,codeandtheory/cartodb,codeandtheory/cartodb,CartoDB/cartodb,splashblot/dronedb,CartoDB/cartodb,codeandtheory/cartodb,codeandtheory/cartodb,CartoDB/cartodb | ---
+++
@@ -2,4 +2,6 @@
* See https://github.com/evanw/node-source-map-support#browser-support
* This is expected to be included in a browserify-module to give proper stack traces, based on browserify's source maps.
*/
-require('source-map-support').install();
+if (window.location.search.indexOf('disablesourcemaps') === -1) {
+ require('source-map-support').install();
+} |
eed6ca7654f6b794eb2d8731838a8998fdd8d9ba | tests/config/karma.browserstack.conf.js | tests/config/karma.browserstack.conf.js | const base = require('./karma.base.conf');
module.exports = function(config) {
config.set(Object.assign(base, {
browserStack: {
username: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY
},
customLaunchers: {
bs_safari_mac: {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Sierra'
},
bs_firefox_mac: {
base: 'BrowserStack',
browser: 'firefox',
os: 'OS X',
os_version: 'Sierra'
},
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
os: 'OS X',
os_version: 'Sierra'
}
},
browsers: ['bs_safari_mac', 'bs_firefox_mac', 'bs_chrome_mac'],
autoWatch: false,
singleRun: true,
reporters: ['dots', 'BrowserStack']
}));
};
| const base = require('./karma.base.conf');
module.exports = function(config) {
config.set(Object.assign(base, {
browserStack: {
username: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY
},
customLaunchers: {
bs_safari_mac: {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Sierra'
},
bs_firefox_mac: {
base: 'BrowserStack',
browser: 'firefox',
os: 'OS X',
os_version: 'Sierra'
},
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
os: 'OS X',
os_version: 'Sierra'
}
},
browsers: ['bs_safari_mac', 'bs_firefox_mac', 'bs_chrome_mac'],
autoWatch: false,
singleRun: true,
reporters: ['dots', 'BrowserStack', 'coverage']
}));
};
| Add coverage reporter to browserstack build | Add coverage reporter to browserstack build
| JavaScript | apache-2.0 | weepower/wee-core | ---
+++
@@ -31,6 +31,6 @@
browsers: ['bs_safari_mac', 'bs_firefox_mac', 'bs_chrome_mac'],
autoWatch: false,
singleRun: true,
- reporters: ['dots', 'BrowserStack']
+ reporters: ['dots', 'BrowserStack', 'coverage']
}));
}; |
652f9ddc899d89f98c7f45a85ad81e90428cf922 | packages/whosmysanta-backend/src/data/index.js | packages/whosmysanta-backend/src/data/index.js | import mongoose from 'mongoose';
const host = process.env.MONGO_HOST;
const database = encodeURIComponent(process.env.MONGO_DATABASE);
const user = encodeURIComponent(process.env.MONGO_USER);
const password = encodeURIComponent(process.env.MONGO_PASS);
export default function connectDatabase() {
// Use node version of Promise for mongoose
mongoose.Promise = global.Promise;
// Connect to mlab database
return mongoose.connect(`mongodb://${user}:${password}@${host}/${database}`);
}
| import mongoose from 'mongoose';
const host = process.env.MONGO_HOST;
const database = encodeURIComponent(process.env.MONGO_DATABASE);
const user = encodeURIComponent(process.env.MONGO_USER);
const password = encodeURIComponent(process.env.MONGO_PASS);
// Use node version of Promise for mongoose
mongoose.Promise = global.Promise;
export default function connectDatabase() {
// Connect to mlab database
return mongoose.connect(`mongodb://${user}:${password}@${host}/${database}`);
}
| Move mongoose.Promise reassignment out of function | Move mongoose.Promise reassignment out of function
| JavaScript | mit | WhosMySanta/app,WhosMySanta/app,WhosMySanta/whosmysanta | ---
+++
@@ -5,10 +5,10 @@
const user = encodeURIComponent(process.env.MONGO_USER);
const password = encodeURIComponent(process.env.MONGO_PASS);
+// Use node version of Promise for mongoose
+mongoose.Promise = global.Promise;
+
export default function connectDatabase() {
- // Use node version of Promise for mongoose
- mongoose.Promise = global.Promise;
-
// Connect to mlab database
return mongoose.connect(`mongodb://${user}:${password}@${host}/${database}`);
} |
84220dd29e94cd40daf4d04c227a8e4c0d02cb93 | lib/protobuf/imports/message.js | lib/protobuf/imports/message.js | 'use strict';
Qt.include('call.js');
var createMessageType = (function() {
var MessageBase = (function() {
var constructor = function(descriptor) {
this._descriptor = descriptor;
this.serializeTo = function(output, cb) {
try {
output.descriptor = this._descriptor;
var call = new UnaryMethod(output);
call.call(this, function(data, err) {
if (data) {
console.warn('Serialize callback received data object unexpectedly and ignored it.');
}
cb(err);
});
} catch (err) {
console.log('Serialize Error !');
console.error(err);
console.error(err.stack);
cb && cb(err);
}
};
};
Object.defineProperties(constructor, {
FIELD: {value: 0},
ONEOF: {value: 1},
});
return constructor;
})();
var createMessageType = function(type, desc) {
type.prototype = new MessageBase(desc);
type.parseFrom = function(input, cb) {
try {
input.descriptor = desc;
var call = new UnaryMethod(input);
call.call(undefined, function(data, err) {
if (err) {
cb(undefined, err);
} else {
var obj = new type();
obj._mergeFromRawArray(data);
cb(obj);
}
});
} catch (err) {
console.log('Parse Error !');
console.error(err);
console.error(err.stack);
cb && cb(undefined, err);
}
};
};
return createMessageType;
})();
| 'use strict';
Qt.include('call.js');
var createMessageType = (function() {
var MessageBase = (function() {
var constructor = function(descriptor) {
this._descriptor = descriptor;
this.serializeTo = function(output, cb) {
try {
output.descriptor = this._descriptor;
var call = new UnaryMethod(output);
call.call(this, function(data, err) {
if (data) {
console.warn('Serialize callback received data object unexpectedly and ignored it.');
}
cb && cb(err);
});
} catch (err) {
console.log('Serialize Error !');
console.error(err);
console.error(err.stack);
cb && cb(err);
}
};
};
Object.defineProperties(constructor, {
FIELD: {value: 0},
ONEOF: {value: 1},
});
return constructor;
})();
var createMessageType = function(type, desc) {
type.prototype = new MessageBase(desc);
type.parseFrom = function(input, cb) {
try {
input.descriptor = desc;
var call = new UnaryMethod(input);
call.call(undefined, function(data, err) {
if (err) {
cb(undefined, err);
} else {
var obj = new type();
obj._mergeFromRawArray(data);
cb(obj);
}
});
} catch (err) {
console.log('Parse Error !');
console.error(err);
console.error(err.stack);
cb && cb(undefined, err);
}
};
};
return createMessageType;
})();
| Allow ommiting callback argument for serialize method | Allow ommiting callback argument for serialize method
| JavaScript | mit | nsuke/protobuf-qml,nsuke/protobuf-qml,nsuke/protobuf-qml,nsuke/protobuf-qml | ---
+++
@@ -14,7 +14,7 @@
if (data) {
console.warn('Serialize callback received data object unexpectedly and ignored it.');
}
- cb(err);
+ cb && cb(err);
});
} catch (err) {
console.log('Serialize Error !'); |
3c23af1029c081be78aed07725495eaf2d8506f5 | src/App.js | src/App.js | import React, { Component } from 'react';
import Button from './components/Button.jsx';
export default class App extends Component {
constructor() {
super();
this.state = {
selectedRange: 'bar',
ranges: []
};
}
handleClick = (foo) => {
this.setState({selectedRange: foo});
};
render() {
return (
<div className='app-container'>
<h1>App</h1>
<Button handleClick={this.handleClick.bind(null, 'blerg')}>Click me!</Button>
<span>{this.state.selectedRange}</span>
</div>
);
}
}
| import React, { Component } from 'react';
import Button from './components/Button';
export default class App extends Component {
constructor() {
super();
this.state = {
selectedRange: 'bar',
ranges: []
};
}
handleClick = (foo) => {
this.setState({selectedRange: foo});
};
render() {
return (
<div className='app-container'>
<h1>App</h1>
<Button handleClick={this.handleClick.bind(null, 'blerg')}>Click me!</Button>
<span>{this.state.selectedRange}</span>
</div>
);
}
}
| Remove unneeded component import extension | Remove unneeded component import extension
| JavaScript | mit | monners/date-range-list,monners/date-range-list | ---
+++
@@ -1,5 +1,5 @@
import React, { Component } from 'react';
-import Button from './components/Button.jsx';
+import Button from './components/Button';
export default class App extends Component {
constructor() { |
01c0bc1440fb4c14a8ae49b667fba0ab09accbc8 | src/components/Navbar/Navbar.js | src/components/Navbar/Navbar.js | import React from 'react';
import { Link } from 'react-router';
import './Navbar.scss';
export default class Navbar extends React.Component {
render () {
return (
<div className='navigation-items'>
<Link className='links' to='/about'>About me</Link>
<Link className='links' to='http://terakilobyte.com'>Blog</Link>
<Link className='links' to='http://twitter.com/terakilobyte'>Twitter</Link>
<Link className='links' to='http://github.com/terakilobyte'>Github</Link>
<Link className='links' to='/playground'>Playground</Link>
</div>
);
}
}
| import React from 'react';
import { Link } from 'react-router';
import './Navbar.scss';
export default class Navbar extends React.Component {
render () {
return (
<div className='navigation-items'>
<Link className='links' to='/about'>About me</Link>
<a className='links' to='http://terakilobyte.com'>Blog</a>
<a className='links' to='http://twitter.com/terakilobyte'>Twitter</a>
<a className='links' to='http://github.com/terakilobyte'>Github</a>
<Link className='links' to='/playground'>Playground</Link>
</div>
);
}
}
| Change external Links to a tags | Change external Links to a tags
| JavaScript | mit | terakilobyte/terakilobyte.github.io,terakilobyte/terakilobyte.github.io | ---
+++
@@ -8,9 +8,9 @@
return (
<div className='navigation-items'>
<Link className='links' to='/about'>About me</Link>
- <Link className='links' to='http://terakilobyte.com'>Blog</Link>
- <Link className='links' to='http://twitter.com/terakilobyte'>Twitter</Link>
- <Link className='links' to='http://github.com/terakilobyte'>Github</Link>
+ <a className='links' to='http://terakilobyte.com'>Blog</a>
+ <a className='links' to='http://twitter.com/terakilobyte'>Twitter</a>
+ <a className='links' to='http://github.com/terakilobyte'>Github</a>
<Link className='links' to='/playground'>Playground</Link>
</div>
); |
dfc02887804e7c5b2ce1555677cff4cd4910391c | templates/base/environment.js | templates/base/environment.js | var config = {
/*
metrics: {
port: 4001
}
*/
/* // For Passport auth via geddy-passport
, passport: {
twitter: {
consumerKey: 'XXXXX'
, consumerSecret: 'XXXXX'
}
, facebook: {
clientID: 'XXXXX'
, clientSecret: 'XXXXX'
}
}
*/
};
module.exports = config;
| var config = {
/*
metrics: {
port: 4001
}
*/
/* // For Passport auth via geddy-passport
, passport: {
successRedirect: '/'
, failureRedirect: '/login'
, twitter: {
consumerKey: 'XXXXX'
, consumerSecret: 'XXXXX'
}
, facebook: {
clientID: 'XXXXX'
, clientSecret: 'XXXXX'
}
}
*/
};
module.exports = config;
| Add success/failure redirects to Passport config | Add success/failure redirects to Passport config
| JavaScript | apache-2.0 | kolonse/ejs,mmis1000/ejs-promise,rpaterson/ejs,cnwhy/ejs,xanxiver/ejs,cnwhy/ejs,mde/ejs,TimothyGu/ejs-tj,TimothyGu/ejs-tj,jtsay362/solveforall-ejs2,operatino/ejs,tyduptyler13/ejs,insidewarehouse/ejs,zensh/ejs,kolonse/ejs,zensh/ejs,insidewarehouse/ejs | ---
+++
@@ -6,7 +6,9 @@
*/
/* // For Passport auth via geddy-passport
, passport: {
- twitter: {
+ successRedirect: '/'
+ , failureRedirect: '/login'
+ , twitter: {
consumerKey: 'XXXXX'
, consumerSecret: 'XXXXX'
} |
a5747b9e826d79342b54d08857b57cb523e9225f | javascripts/ai.js | javascripts/ai.js | var AI;
AI = function(baseSpeed) {
this.baseSpeed = baseSpeed;
};
// Simply follows the ball at all times
AI.prototype.easy = function(player, ball) {
'use strict';
var newY;
newY = ball.y - (player.paddle.y + player.paddle.height / 2);
if (newY < 0 && newY < -4) {
newY = -this.baseSpeed;
} else if (newY > 0 && newY > 4) {
newY = this.baseSpeed;
}
return newY;
};
// Follows the ball only when in its half, otherwise stay put
AI.prototype.medium = function(player, ball, canvasWidth, canvasHeight) {
'use strict';
var newY;
// If ball is moving towards computer
if (ball.xSpeed > 0 && ball.x > (canvasWidth / 1.75)) {
// Follow the ball
newY = ball.y - (player.paddle.y + player.paddle.height / 2);
if (newY < 0 && newY < -4) {
newY = -(this.baseSpeed + 0.5);
} else if (newY > 0 && newY > 4) {
newY = this.baseSpeed + 0.5;
}
} else {
newY = 0;
}
return newY;
};
// Predict where the ball is going to land
AI.prototype.hard = function(player, ball, canvasWidth, canvasHeight) {
'use strict';
var newY;
return newY;
};
| var AI;
AI = function(baseSpeed) {
this.baseSpeed = baseSpeed;
};
// Simply follows the ball at all times
AI.prototype.easy = function(player, ball) {
'use strict';
var newY;
newY = ball.y - (player.paddle.y + player.paddle.height / 2);
if (newY < -4) {
newY = -this.baseSpeed;
} else if (newY > 4) {
newY = this.baseSpeed;
}
return newY;
};
// Follows the ball only when in its half, otherwise stay put
AI.prototype.medium = function(player, ball, canvasWidth, canvasHeight) {
'use strict';
var newY;
// If ball is moving towards computer
if (ball.xSpeed > 0 && ball.x > (canvasWidth / 1.75)) {
// Follow the ball
newY = ball.y - (player.paddle.y + player.paddle.height / 2);
if (newY < -4) {
newY = -(this.baseSpeed + 0.5);
} else if (newY > 4) {
newY = this.baseSpeed + 0.5;
}
} else {
newY = 0;
}
return newY;
};
// Predict where the ball is going to land
AI.prototype.hard = function(player, ball, canvasWidth, canvasHeight) {
'use strict';
var newY;
return newY;
};
| Remove unnecessary ball speed checks | Remove unnecessary ball speed checks
| JavaScript | mit | msanatan/pong,msanatan/pong,msanatan/pong | ---
+++
@@ -9,9 +9,9 @@
'use strict';
var newY;
newY = ball.y - (player.paddle.y + player.paddle.height / 2);
- if (newY < 0 && newY < -4) {
+ if (newY < -4) {
newY = -this.baseSpeed;
- } else if (newY > 0 && newY > 4) {
+ } else if (newY > 4) {
newY = this.baseSpeed;
}
@@ -26,9 +26,9 @@
if (ball.xSpeed > 0 && ball.x > (canvasWidth / 1.75)) {
// Follow the ball
newY = ball.y - (player.paddle.y + player.paddle.height / 2);
- if (newY < 0 && newY < -4) {
+ if (newY < -4) {
newY = -(this.baseSpeed + 0.5);
- } else if (newY > 0 && newY > 4) {
+ } else if (newY > 4) {
newY = this.baseSpeed + 0.5;
}
} else { |
17d1c09accef6235dd29b4fd7f7bc25392092944 | app/assets/javascripts/ng-app/app.js | app/assets/javascripts/ng-app/app.js | angular.module('myApp', [
'ngAnimate',
'ui.router',
'templates'
])
.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
/**
* Routes and States
*/
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home.html',
controller: 'HomeCtrl'
});
// default fall back route
$urlRouterProvider.otherwise('/');
// enable HTML5 mode for SEO
$locationProvider.html5Mode(true);
}); | angular.module('myApp', [
'ngAnimate',
'ui.router',
'templates'
])
.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
/**
* Routes and States
*/
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home.html',
controller: 'HomeCtrl'
});
// default fall back route
$urlRouterProvider.otherwise('/');
// enable HTML5 mode for SEO
// $locationProvider.html5Mode(true);
}); | Remove html5mode since it was causing an error and looking for a base tag | Remove html5mode since it was causing an error and looking for a base tag
| JavaScript | mit | jeremymcintyre/rails-angular-sandbox,jeremymcintyre/rails-angular-sandbox,jeremymcintyre/rails-angular-sandbox | ---
+++
@@ -3,7 +3,7 @@
'ui.router',
'templates'
])
- .config(function($stateProvider, $urlRouterProvider, $locationProvider) {
+ .config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
/**
* Routes and States
*/
@@ -18,6 +18,6 @@
$urlRouterProvider.otherwise('/');
// enable HTML5 mode for SEO
- $locationProvider.html5Mode(true);
+ // $locationProvider.html5Mode(true);
}); |
4ee7bc82b1282e718f88ba36ca2f7236f0019273 | server/db/schemas/User.js | server/db/schemas/User.js | const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
_id: { type: Number },
profileImageName: { type: String, default: 'default.png' },
email: { type: String, unique: true },
phoneNumber: { type: String },
name: {
first: { type: String, trim: true },
last: { type: String, trim: true }
},
registeredDate: { type: Date, default: Date.now },
admin: { type: Boolean, default: false },
verified: { type: Boolean, default: false }
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
userSchema.methods.findCamps = function() {
return this.model('Camp').find().or([{ ambassador: this._id }, { director: this._id}, { teachers: this._id }]).populate('location').exec();
}
userSchema.virtual('name.full').get(function() {
return this.name.first + ' ' + this.name.last;
});
module.exports = { name: 'User', schema: userSchema }; | const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
_id: { type: Number },
profileImageName: { type: String, default: 'default.png' },
email: { type: String, unique: true },
age: { type: Number, min: 10, max: 100 },
grade: { type: Number, min: 8, max: 12 },
phoneNumber: { type: String },
name: {
first: { type: String, trim: true },
last: { type: String, trim: true }
},
application: {
recommender: { type: Number, ref: 'User' },
why: String,
writingFileName: String
},
registeredDate: { type: Date, default: Date.now },
admin: { type: Boolean, default: false },
verified: { type: Boolean, default: false }
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
userSchema.methods.findCamps = function() {
return this.model('Camp').find().or([{ ambassador: this._id }, { director: this._id}, { teachers: this._id }]).populate('location').exec();
}
userSchema.virtual('name.full').get(function() {
return this.name.first + ' ' + this.name.last;
});
module.exports = { name: 'User', schema: userSchema }; | Update user schema for application merge | Update user schema for application merge
| JavaScript | mit | KidsTales/kt-web,KidsTales/kt-web | ---
+++
@@ -5,10 +5,17 @@
_id: { type: Number },
profileImageName: { type: String, default: 'default.png' },
email: { type: String, unique: true },
+ age: { type: Number, min: 10, max: 100 },
+ grade: { type: Number, min: 8, max: 12 },
phoneNumber: { type: String },
name: {
first: { type: String, trim: true },
last: { type: String, trim: true }
+ },
+ application: {
+ recommender: { type: Number, ref: 'User' },
+ why: String,
+ writingFileName: String
},
registeredDate: { type: Date, default: Date.now },
admin: { type: Boolean, default: false }, |
d45df4a5745c2bb3f5301f7a0ef587a3c5a73594 | assets/js/util/is-site-kit-screen.js | assets/js/util/is-site-kit-screen.js | /**
* Utility function to check whether or not a view-context is a site kit view.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import includes from 'lodash/includes';
/**
* Internal dependencies
*/
import { SITE_KIT_VIEW_CONTEXTS } from '../googlesitekit/constants';
/**
* Checks whether or not the current viewContext is a Site Kit screen.
*
* @since n.e.x.t
*
* @param {string} viewContext THe view-context.
* @return {boolean} TRUE if the passed view-context is a site kit view; otherwise FALSE.
*/
const isSiteKitScreen = ( viewContext ) =>
includes( SITE_KIT_VIEW_CONTEXTS, viewContext );
export default isSiteKitScreen;
| /**
* Utility function to check whether or not a view-context is a site kit view.
*
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import { SITE_KIT_VIEW_CONTEXTS } from '../googlesitekit/constants';
/**
* Checks whether or not the current viewContext is a Site Kit screen.
*
* @since n.e.x.t
*
* @param {string} viewContext The view-context.
* @return {boolean} TRUE if the passed view-context is a site kit view; otherwise FALSE.
*/
const isSiteKitScreen = ( viewContext ) =>
SITE_KIT_VIEW_CONTEXTS.includes( viewContext );
export default isSiteKitScreen;
| Use vanilla includes function. Correct capitalisation. | Use vanilla includes function. Correct capitalisation.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -17,11 +17,6 @@
*/
/**
- * External dependencies
- */
-import includes from 'lodash/includes';
-
-/**
* Internal dependencies
*/
import { SITE_KIT_VIEW_CONTEXTS } from '../googlesitekit/constants';
@@ -31,10 +26,10 @@
*
* @since n.e.x.t
*
- * @param {string} viewContext THe view-context.
+ * @param {string} viewContext The view-context.
* @return {boolean} TRUE if the passed view-context is a site kit view; otherwise FALSE.
*/
const isSiteKitScreen = ( viewContext ) =>
- includes( SITE_KIT_VIEW_CONTEXTS, viewContext );
+ SITE_KIT_VIEW_CONTEXTS.includes( viewContext );
export default isSiteKitScreen; |
4bbc355d992c2998f93058770d9f29faf3d9bc11 | generators/project/templates/config/_eslintrc_webapp.js | generators/project/templates/config/_eslintrc_webapp.js | module.exports = {
env: {
amd: <%= (moduleFormat === 'amd') %>,
commonjs: <%= (moduleFormat === 'commonjs') %>,
es6: true,
browser: true,
jquery: true,
mocha: <%= !useJest %>,
jest: <%= useJest %>
},
globals: {
sinon: true
},
extends: 'omaha-prime-grade',
plugins: [
'backbone'
],
rules: {
'backbone/collection-model': ['warn'],
'backbone/defaults-on-top': ['warn'],
'backbone/model-defaults': ['warn'],
'backbone/no-collection-models': ['warn'],
'backbone/no-model-attributes': ['warn']
}
};
| module.exports = {
env: {
amd: <%= (moduleFormat === 'amd') %>,
commonjs: <%= (moduleFormat === 'commonjs') %>,
es6: true,
browser: true,
jquery: true,
mocha: <%= !useJest %>,
jest: <%= !!useJest %>
},
globals: {
sinon: true
},
extends: 'omaha-prime-grade',
plugins: [
'backbone'
],
rules: {
'backbone/collection-model': ['warn'],
'backbone/defaults-on-top': ['warn'],
'backbone/model-defaults': ['warn'],
'backbone/no-collection-models': ['warn'],
'backbone/no-model-attributes': ['warn']
}
};
| Fix jest env template value | Fix jest env template value
| JavaScript | mit | jhwohlgemuth/generator-techtonic,jhwohlgemuth/generator-techtonic,omahajs/generator-omaha,omahajs/generator-omaha,omahajs/generator-omaha,jhwohlgemuth/generator-techtonic,omahajs/generator-omaha | ---
+++
@@ -6,7 +6,7 @@
browser: true,
jquery: true,
mocha: <%= !useJest %>,
- jest: <%= useJest %>
+ jest: <%= !!useJest %>
},
globals: {
sinon: true |
d7cbc2ec2c2e73d9f885ee0de8f395c0fdcbd24b | ui/features/lti_collaborations/index.js | ui/features/lti_collaborations/index.js | /*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import router from './react/router'
router.start()
| /*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import router from './react/router'
import ready from '@instructure/ready'
ready(() => {
router.start()
})
| Fix lti collaborations page unresponsive on load in chrome | Fix lti collaborations page unresponsive on load in chrome
fixes VICE-2440
flag=none
Test Plan:
- follow repro steps in linked ticket
Change-Id: I9b682719ea1e258f98caf90a197167a031995f7b
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/284881
Reviewed-by: Jeffrey Johnson <7a0f98bfe168bc29d5611ba0275e88567b492abc@instructure.com>
Product-Review: Jeffrey Johnson <7a0f98bfe168bc29d5611ba0275e88567b492abc@instructure.com>
QA-Review: Caleb Guanzon <54fa1f30d451e4f3c341a8f3c47c9215fd0be9c6@instructure.com>
Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com>
| JavaScript | agpl-3.0 | instructure/canvas-lms,sfu/canvas-lms,instructure/canvas-lms,instructure/canvas-lms,sfu/canvas-lms,sfu/canvas-lms,sfu/canvas-lms,instructure/canvas-lms,instructure/canvas-lms,instructure/canvas-lms,sfu/canvas-lms,sfu/canvas-lms,instructure/canvas-lms,sfu/canvas-lms | ---
+++
@@ -17,5 +17,8 @@
*/
import router from './react/router'
+import ready from '@instructure/ready'
-router.start()
+ready(() => {
+ router.start()
+}) |
b25d54624f98726483c25a4f5f25419b1ae42660 | timeout.js | timeout.js | 'use strict'; /*jslint node: true, es5: true, indent: 2 */
var util = require('util');
var stream = require('stream');
var TimeoutDetector = module.exports = function(opts) {
if (opts === undefined) opts = {};
// opts = {[timeout: 60 (seconds)]}
stream.Transform.call(this, opts);
if (opts.timeout !== undefined) {
// ensure we get something every x seconds.
this.timeout_ms = opts.timeout * 1000;
setInterval(this._check.bind(this), this.timeout_ms);
}
};
util.inherits(TimeoutDetector, stream.Transform);
TimeoutDetector.prototype._check = function() {
// silent_ms: milliseconds since we got some incoming data
var silent_ms = Date.now() - this.last;
if (silent_ms > this.timeout_ms) {
this.emit('error', new Error('Timeout pipe timed out.'));
}
};
TimeoutDetector.prototype._transform = function(chunk, encoding, callback) {
this.last = Date.now();
this.push(chunk);
callback();
};
| 'use strict'; /*jslint node: true, es5: true, indent: 2 */
var util = require('util');
var stream = require('stream');
var TimeoutDetector = module.exports = function(opts) {
if (!opts || !opts.timeout) throw new Error('TimeoutDetector({timeout: ...}) is a required parameter.');
stream.Transform.call(this, opts);
this.timeout_ms = opts.timeout * 1000;
setInterval(this._check.bind(this), this.timeout_ms);
};
util.inherits(TimeoutDetector, stream.Transform);
TimeoutDetector.prototype._check = function() {
// silent_ms: milliseconds since we got some incoming data
var silent_ms = Date.now() - this.last;
if (silent_ms > this.timeout_ms) {
// ensure we get something every x seconds.
this.emit('error', new Error('TimeoutDetector timed out.'));
}
};
TimeoutDetector.prototype._transform = function(chunk, encoding, callback) {
this.last = Date.now();
this.push(chunk);
callback();
};
| Trim down defaults out of TimeoutDetector. | Trim down defaults out of TimeoutDetector.
| JavaScript | mit | chbrown/twilight,chbrown/twilight,chbrown/tweetjobs | ---
+++
@@ -3,15 +3,10 @@
var stream = require('stream');
var TimeoutDetector = module.exports = function(opts) {
- if (opts === undefined) opts = {};
- // opts = {[timeout: 60 (seconds)]}
+ if (!opts || !opts.timeout) throw new Error('TimeoutDetector({timeout: ...}) is a required parameter.');
stream.Transform.call(this, opts);
-
- if (opts.timeout !== undefined) {
- // ensure we get something every x seconds.
- this.timeout_ms = opts.timeout * 1000;
- setInterval(this._check.bind(this), this.timeout_ms);
- }
+ this.timeout_ms = opts.timeout * 1000;
+ setInterval(this._check.bind(this), this.timeout_ms);
};
util.inherits(TimeoutDetector, stream.Transform);
@@ -19,7 +14,8 @@
// silent_ms: milliseconds since we got some incoming data
var silent_ms = Date.now() - this.last;
if (silent_ms > this.timeout_ms) {
- this.emit('error', new Error('Timeout pipe timed out.'));
+ // ensure we get something every x seconds.
+ this.emit('error', new Error('TimeoutDetector timed out.'));
}
};
|
17e1e14851112344b59b366676b3378ae09e798a | src/actions/action-creators.js | src/actions/action-creators.js | import dispatcher from '../dispatcher/dispatcher';
import actionTypes from '../constants/action-types';
import axios from 'axios';
import {
apiConstants
} from '../constants/api-constants';
const {
baseURL,
apiKey,
userName
} = apiConstants;
export function fetchUser() {
let getUserInfo = axios.create({
baseURL,
url: `?format=json&method=user.getinfo&user=${userName}&api_key=${apiKey}`
});
getUserInfo()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.userRetrieved,
user: response.data.user
});
});
}
export function fetchRecentTracks() {
let getRecentTracks = axios.create({
baseURL,
url: `?format=json&method=user.getrecenttracks&user=${userName}&api_key=${apiKey}`
});
getRecentTracks()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.recentTracksRetreived,
recentTracks: response.data.recenttracks.track
});
});
}
export function fetchTopArtists() {
let getTopArtists = axios.create({
baseURL,
url: `?format=json&method=user.gettopartists&user=${userName}&api_key=${apiKey}`
});
getTopArtists()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.topArtistsRetreived,
topArtists: response.data.topartists.artist
});
});
}
| import dispatcher from '../dispatcher/dispatcher';
import actionTypes from '../constants/action-types';
import axios from 'axios';
import {
apiConstants
} from '../constants/api-constants';
const {
baseURL,
apiKey,
userName
} = apiConstants;
export function fetchUser() {
let getUserInfo = axios.create({
baseURL,
url: `?format=json&method=user.getinfo&user=${userName}&api_key=${apiKey}`
});
getUserInfo()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.userRetrieved,
user: response.data.user
});
});
}
export function fetchRecentTracks(limit) {
let getRecentTracks = axios.create({
baseURL,
url: `?format=json&method=user.getrecenttracks&user=${userName}&limit=${limit}&api_key=${apiKey}`
});
getRecentTracks()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.recentTracksRetreived,
recentTracks: response.data.recenttracks.track
});
});
}
export function fetchTopArtists() {
let getTopArtists = axios.create({
baseURL,
url: `?format=json&method=user.gettopartists&user=${userName}&api_key=${apiKey}`
});
getTopArtists()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.topArtistsRetreived,
topArtists: response.data.topartists.artist
});
});
}
| Add ‘limit’ parameter to the fetchRecentTracks action to set the number of recent tracks to be retrieved | Add ‘limit’ parameter to the fetchRecentTracks action to set the number
of recent tracks to be retrieved
| JavaScript | bsd-3-clause | jeromelachaud/Last.fm-Activities-React,jeromelachaud/Last.fm-Activities-React | ---
+++
@@ -26,10 +26,10 @@
});
}
-export function fetchRecentTracks() {
+export function fetchRecentTracks(limit) {
let getRecentTracks = axios.create({
baseURL,
- url: `?format=json&method=user.getrecenttracks&user=${userName}&api_key=${apiKey}`
+ url: `?format=json&method=user.getrecenttracks&user=${userName}&limit=${limit}&api_key=${apiKey}`
});
getRecentTracks()
.then((response) => { |
0104841e84a3cdd1019f416678621e7bd9606802 | src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/editor/select-cell-radio-editor.js | src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/editor/select-cell-radio-editor.js | /*global define*/
define([
'underscore',
'backgrid'
], function (_, Backgrid) {
'use strict';
var SelectCellRadioEditor;
SelectCellRadioEditor = Backgrid.SelectCellEditor.extend({
/**
* @inheritDoc
*/
tagName: "div",
/**
* @inheritDoc
*/
events: {
"change": "save",
"blur": "close",
"keydown": "close",
"click": "onClick"
},
/**
* @inheritDoc
*/
template: _.template('<input name="<%- this.model.cid + \'_\' + this.cid %>" type="radio" value="<%- value %>" <%= selected ? checked : "" %>><%- text %>', null, {variable: null}),
/**
* @param {Object} event
*/
onClick: function (event) {
event.stopPropagation();
}
});
return SelectCellRadioEditor;
});
| /*global define*/
define([
'underscore',
'backgrid'
], function (_, Backgrid) {
'use strict';
var SelectCellRadioEditor;
SelectCellRadioEditor = Backgrid.SelectCellEditor.extend({
/**
* @inheritDoc
*/
tagName: "ul class='icons-ul'",
/**
* @inheritDoc
*/
events: {
"change": "save",
"blur": "close",
"keydown": "close",
"click": "onClick"
},
/**
* @inheritDoc
*/
template: _.template('<li><input id="<%- this.model.cid + \'_\' + this.cid + \'_\' + value %>" name="<%- this.model.cid + \'_\' + this.cid %>" type="radio" value="<%- value %>" <%= selected ? "checked" : "" %>><label for="<%- this.model.cid + \'_\' + this.cid + \'_\' + value %>"><%- text %></label></li>', null, {variable: null}),
/**
* @inheritDoc
*/
save: function () {
var model = this.model;
var column = this.column;
model.set(column.get("name"), this.formatter.toRaw(this.$el.find(':checked').val(), model));
},
/**
* @param {Object} event
*/
onClick: function (event) {
event.stopPropagation();
}
});
return SelectCellRadioEditor;
});
| Create editor for input=radio, apply it in select-cell - fix radio buttons | BB-701: Create editor for input=radio, apply it in select-cell
- fix radio buttons
| JavaScript | mit | 2ndkauboy/platform,trustify/oroplatform,geoffroycochard/platform,northdakota/platform,ramunasd/platform,Djamy/platform,2ndkauboy/platform,trustify/oroplatform,orocrm/platform,geoffroycochard/platform,hugeval/platform,geoffroycochard/platform,Djamy/platform,hugeval/platform,orocrm/platform,Djamy/platform,northdakota/platform,2ndkauboy/platform,hugeval/platform,orocrm/platform,ramunasd/platform,trustify/oroplatform,northdakota/platform,ramunasd/platform | ---
+++
@@ -11,7 +11,7 @@
/**
* @inheritDoc
*/
- tagName: "div",
+ tagName: "ul class='icons-ul'",
/**
* @inheritDoc
@@ -26,7 +26,16 @@
/**
* @inheritDoc
*/
- template: _.template('<input name="<%- this.model.cid + \'_\' + this.cid %>" type="radio" value="<%- value %>" <%= selected ? checked : "" %>><%- text %>', null, {variable: null}),
+ template: _.template('<li><input id="<%- this.model.cid + \'_\' + this.cid + \'_\' + value %>" name="<%- this.model.cid + \'_\' + this.cid %>" type="radio" value="<%- value %>" <%= selected ? "checked" : "" %>><label for="<%- this.model.cid + \'_\' + this.cid + \'_\' + value %>"><%- text %></label></li>', null, {variable: null}),
+
+ /**
+ * @inheritDoc
+ */
+ save: function () {
+ var model = this.model;
+ var column = this.column;
+ model.set(column.get("name"), this.formatter.toRaw(this.$el.find(':checked').val(), model));
+ },
/**
* @param {Object} event |
752b6fa627271582c8facb56c80d65ae5cd246f9 | lib/parse-args.js | lib/parse-args.js | var minimist = require('minimist')
var xtend = require('xtend')
module.exports = parseArgs
function parseArgs (args, opt) {
var argv = minimist(args, {
boolean: [
'stream',
'debug',
'errorHandler',
'forceDefaultIndex',
'open',
'portfind',
'ndjson',
'verbose',
'cors',
'ssl'
],
string: [
'host',
'port',
'dir',
'onupdate',
'serve',
'title',
'watchGlob',
'cert',
'key'
],
default: module.exports.defaults,
alias: {
port: 'p',
ssl: 'S',
serve: 's',
cert: 'C',
key: 'K',
verbose: 'v',
help: 'h',
host: 'H',
dir: 'd',
live: 'l',
open: 'o',
watchGlob: [ 'wg', 'watch-glob' ],
errorHandler: 'error-handler',
forceDefaultIndex: 'force-default-index',
'live-port': ['L', 'livePort'],
pushstate: 'P'
},
'--': true
})
return xtend(argv, opt)
}
module.exports.defaults = {
title: 'budo',
port: 9966,
debug: true,
stream: true,
errorHandler: true,
portfind: true
}
| var minimist = require('minimist')
var xtend = require('xtend')
module.exports = parseArgs
function parseArgs (args, opt) {
var argv = minimist(args, {
boolean: [
'stream',
'debug',
'errorHandler',
'forceDefaultIndex',
'open',
'portfind',
'pushstate',
'ndjson',
'verbose',
'cors',
'ssl'
],
string: [
'host',
'port',
'dir',
'onupdate',
'serve',
'title',
'watchGlob',
'cert',
'key'
],
default: module.exports.defaults,
alias: {
port: 'p',
ssl: 'S',
serve: 's',
cert: 'C',
key: 'K',
verbose: 'v',
help: 'h',
host: 'H',
dir: 'd',
live: 'l',
open: 'o',
watchGlob: [ 'wg', 'watch-glob' ],
errorHandler: 'error-handler',
forceDefaultIndex: 'force-default-index',
'live-port': ['L', 'livePort'],
pushstate: 'P'
},
'--': true
})
return xtend(argv, opt)
}
module.exports.defaults = {
title: 'budo',
port: 9966,
debug: true,
stream: true,
errorHandler: true,
portfind: true
}
| Add pushstate flags to booleans | Add pushstate flags to booleans
| JavaScript | mit | msfeldstein/budo,mattdesl/budo,msfeldstein/budo,mattdesl/budo | ---
+++
@@ -11,6 +11,7 @@
'forceDefaultIndex',
'open',
'portfind',
+ 'pushstate',
'ndjson',
'verbose',
'cors', |
bacca2639a4f76be79fff09a4442b3be9ecf861c | app/components/session-verify.js | app/components/session-verify.js | import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';
export default Component.extend({
router: service(),
currentUser: service(),
store: service(),
flashMessages: service(),
verifySessionModal: false,
verifySessionModalError: false,
verifySession: task(function *() {
try {
yield this.get('model').verify({
'by': this.get('currentUser.user.id')
});
this.get('model').reload();
this.set('verifySessionModal', false);
this.set('verifySessionModalError', false);
this.get('flashMessages').success("Verified!");
this.get('router').transitionTo('dashboard.conventions.convention.sessions.session.details');
} catch(e) {
this.set('verifySessionModalError', true);
}
}).drop(),
});
| import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';
export default Component.extend({
router: service(),
currentUser: service(),
store: service(),
flashMessages: service(),
verifySessionModal: false,
verifySessionModalError: false,
verifySession: task(function *() {
try {
yield this.get('model').verify({
'by': this.get('currentUser.user.id')
});
this.get('model').reload();
this.set('verifySessionModal', false);
this.set('verifySessionModalError', false);
this.get('flashMessages').success("Verified!");
this.get('router').transitionTo('dashboard.conventions.convention.sessions.session.reports');
} catch(e) {
this.set('verifySessionModalError', true);
}
}).drop(),
});
| Move to reports on Session verification | Move to reports on Session verification
| JavaScript | bsd-2-clause | barberscore/barberscore-web,barberscore/barberscore-web,barberscore/barberscore-web | ---
+++
@@ -18,7 +18,7 @@
this.set('verifySessionModal', false);
this.set('verifySessionModalError', false);
this.get('flashMessages').success("Verified!");
- this.get('router').transitionTo('dashboard.conventions.convention.sessions.session.details');
+ this.get('router').transitionTo('dashboard.conventions.convention.sessions.session.reports');
} catch(e) {
this.set('verifySessionModalError', true);
} |
ddd9683976e6c41e6e6e2bd9de58232fabc2197b | portal/js/app.js | portal/js/app.js | var App = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'https://website-api.withregard.io',
namespace: 'v1'
});
App.ApplicationSerializer = DS.RESTSerializer.extend({
primaryKey: '_id',
serializeHasMany: function (record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') {
json[key] = Ember.get(record, key).mapBy('id');
}
}
});
App.ProjectView = Ember.View.extend({
didInsertElement: function() {
$(document).foundation();
}
}) | var App = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'https://website-api.withregard.io',
namespace: 'v1',
ajax: function(url, method, hash) {
hash.xhrFields = {withCredentials: true};
return this._super(url, method, hash);
}
});
App.ApplicationSerializer = DS.RESTSerializer.extend({
primaryKey: '_id',
serializeHasMany: function (record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') {
json[key] = Ember.get(record, key).mapBy('id');
}
}
});
App.ProjectView = Ember.View.extend({
didInsertElement: function() {
$(document).foundation();
}
}) | Send cookies with AJAX requests | Send cookies with AJAX requests
| JavaScript | apache-2.0 | with-regard/regard-website | ---
+++
@@ -5,7 +5,11 @@
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'https://website-api.withregard.io',
- namespace: 'v1'
+ namespace: 'v1',
+ ajax: function(url, method, hash) {
+ hash.xhrFields = {withCredentials: true};
+ return this._super(url, method, hash);
+ }
});
App.ApplicationSerializer = DS.RESTSerializer.extend({ |
f147f649aaad040522d93becb2a7bc845494fc76 | gemini/index.js | gemini/index.js | gemini.suite('CSS component', (suite) => {
suite.setUrl('/?selectedKind=CSS%20component&selectedStory=default')
.setCaptureElements('#storybook-preview-iframe')
.capture('plain');
});
gemini.suite('Stateless functional component', (suite) => {
suite.setUrl('/?selectedKind=Stateless%20functional%20component&selectedStory=default')
.setCaptureElements('#storybook-preview-iframe')
.capture('plain');
});
gemini.suite('Web Component', (suite) => {
suite.setUrl('/?selectedKind=Web%20component&selectedStory=default')
.setCaptureElements('#storybook-preview-iframe')
.capture('plain');
});
| gemini.suite('CSS component', (suite) => {
suite.setUrl('/iframe.html?selectedKind=CSS%20component&selectedStory=default')
.setCaptureElements('body')
.before((actions) => {
actions.setWindowSize(1024, 768);
})
.capture('plain');
});
gemini.suite('Stateless functional component', (suite) => {
suite.setUrl('/iframe.html?selectedKind=Stateless%20functional%20component&selectedStory=default')
.setCaptureElements('body')
.before((actions) => {
actions.setWindowSize(1024, 768);
})
.capture('plain');
});
gemini.suite('Web Component', (suite) => {
suite.setUrl('/iframe.html?selectedKind=Web%20component&selectedStory=default')
.setCaptureElements('body')
.before((actions) => {
actions.setWindowSize(1024, 768);
})
.capture('plain');
});
| Test the frame contents directly | Test the frame contents directly
| JavaScript | mit | z-kit/component,z-kit/z-hello,z-kit/component,z-kit/z-hello | ---
+++
@@ -1,17 +1,26 @@
gemini.suite('CSS component', (suite) => {
- suite.setUrl('/?selectedKind=CSS%20component&selectedStory=default')
- .setCaptureElements('#storybook-preview-iframe')
+ suite.setUrl('/iframe.html?selectedKind=CSS%20component&selectedStory=default')
+ .setCaptureElements('body')
+ .before((actions) => {
+ actions.setWindowSize(1024, 768);
+ })
.capture('plain');
});
gemini.suite('Stateless functional component', (suite) => {
- suite.setUrl('/?selectedKind=Stateless%20functional%20component&selectedStory=default')
- .setCaptureElements('#storybook-preview-iframe')
+ suite.setUrl('/iframe.html?selectedKind=Stateless%20functional%20component&selectedStory=default')
+ .setCaptureElements('body')
+ .before((actions) => {
+ actions.setWindowSize(1024, 768);
+ })
.capture('plain');
});
gemini.suite('Web Component', (suite) => {
- suite.setUrl('/?selectedKind=Web%20component&selectedStory=default')
- .setCaptureElements('#storybook-preview-iframe')
+ suite.setUrl('/iframe.html?selectedKind=Web%20component&selectedStory=default')
+ .setCaptureElements('body')
+ .before((actions) => {
+ actions.setWindowSize(1024, 768);
+ })
.capture('plain');
}); |
c623338be8d8ffe4771d670dc63d3ecaa8c1e43d | test/resources/queue/handler.js | test/resources/queue/handler.js | import test from 'ava'
import { assert } from '../../utils/chai'
import { normalizeHandler } from '../../utils/normalizer'
import * as queue from '../../../src/resources/queue/handler'
const create = normalizeHandler(queue.create)
const show = normalizeHandler(queue.show)
const queueMock = {
name: 'test-queue',
url: 'http://yopa/queue/test'
}
test('creates a queue', async (t) => {
const { body, statusCode } = await create({
body: queueMock
})
t.is(statusCode, 201)
assert.containSubset(body, {
name: 'test-queue',
url: 'http://yopa/queue/test'
})
})
test('shows a queue', async (t) => {
const createdQueue = await create({
body: queueMock
})
const { body, statusCode } = await show({
pathParameters: {
id: createdQueue.body.id
}
})
t.is(statusCode, 200)
t.deepEqual(body, createdQueue.body)
})
test.only('tries to find a queue that does not exist', async (t) => {
const { statusCode } = await show({
pathParameters: {
id: 'queue_xxx'
}
})
t.is(statusCode, 404)
})
| import test from 'ava'
import { assert } from '../../utils/chai'
import { normalizeHandler } from '../../utils/normalizer'
import * as queue from '../../../src/resources/queue/handler'
const create = normalizeHandler(queue.create)
const show = normalizeHandler(queue.show)
const queueMock = {
name: 'test-queue',
url: 'http://yopa/queue/test'
}
test('creates a queue', async (t) => {
const { body, statusCode } = await create({
body: queueMock
})
t.is(statusCode, 201)
assert.containSubset(body, {
name: 'test-queue',
url: 'http://yopa/queue/test'
})
})
test('shows a queue', async (t) => {
const createdQueue = await create({
body: queueMock
})
const { body, statusCode } = await show({
pathParameters: {
id: createdQueue.body.id
}
})
t.is(statusCode, 200)
t.deepEqual(body, createdQueue.body)
})
test('tries to find a queue that does not exist', async (t) => {
const { statusCode } = await show({
pathParameters: {
id: 'queue_xxx'
}
})
t.is(statusCode, 404)
})
| Remove unwanted only from tests | Remove unwanted only from tests
| JavaScript | mit | vcapretz/superbowleto,vcapretz/superbowleto | ---
+++
@@ -39,7 +39,7 @@
t.deepEqual(body, createdQueue.body)
})
-test.only('tries to find a queue that does not exist', async (t) => {
+test('tries to find a queue that does not exist', async (t) => {
const { statusCode } = await show({
pathParameters: {
id: 'queue_xxx' |
c94b627360ff4801d64e676e3714faa9a3490c40 | app/scripts/services/webservice.js | app/scripts/services/webservice.js | 'use strict';
/**
* @ngdoc service
* @name dockstore.ui.WebService
* @description
* # WebService
* Constant in the dockstore.ui.
*/
angular.module('dockstore.ui')
.constant('WebService', {
API_URI: 'http://www.dockstore.org:8080',
API_URI_DEBUG: 'http://www.dockstore.org/tests/dummy-data',
GITHUB_AUTH_URL: 'https://github.com/login/oauth/authorize',
GITHUB_CLIENT_ID: '7ad54aa857c6503013ea',
GITHUB_REDIRECT_URI: 'http://www.dockstore.org/%23/login',
GITHUB_SCOPE: 'read:org',
QUAYIO_AUTH_URL: 'https://quay.io/oauth/authorize',
QUAYIO_CLIENT_ID: 'X5HST9M57O6A57GZFX6T',
QUAYIO_REDIRECT_URI: 'http://www.dockstore.org/%23/onboarding',
QUAYIO_SCOPE: 'repo:read,user:read'
});
| 'use strict';
/**
* @ngdoc service
* @name dockstore.ui.WebService
* @description
* # WebService
* Constant in the dockstore.ui.
*/
angular.module('dockstore.ui')
.constant('WebService', {
API_URI: 'http://www.dockstore.org:8080',
API_URI_DEBUG: 'http://www.dockstore.org/tests/dummy-data',
GITHUB_AUTH_URL: 'https://github.com/login/oauth/authorize',
GITHUB_CLIENT_ID: '7ad54aa857c6503013ea',
GITHUB_REDIRECT_URI: 'http://www.dockstore.org/%23/login',
GITHUB_SCOPE: 'read:org',
QUAYIO_AUTH_URL: 'https://quay.io/oauth/authorize',
QUAYIO_CLIENT_ID: 'X5HST9M57O6A57GZFX6T',
QUAYIO_REDIRECT_URI: 'http://www.dockstore.org/%23/onboarding',
QUAYIO_SCOPE: 'repo:read,user:read',
DSCLI_RELEASE_URL: 'https://github.com/CancerCollaboratory/dockstore/releases/download/0.0.4/dockstore'
});
| Add Dockstore CLI Release URL config. | Add Dockstore CLI Release URL config.
| JavaScript | apache-2.0 | ga4gh/dockstore-ui,ga4gh/dockstore-ui,ga4gh/dockstore-ui | ---
+++
@@ -20,5 +20,7 @@
QUAYIO_AUTH_URL: 'https://quay.io/oauth/authorize',
QUAYIO_CLIENT_ID: 'X5HST9M57O6A57GZFX6T',
QUAYIO_REDIRECT_URI: 'http://www.dockstore.org/%23/onboarding',
- QUAYIO_SCOPE: 'repo:read,user:read'
+ QUAYIO_SCOPE: 'repo:read,user:read',
+
+ DSCLI_RELEASE_URL: 'https://github.com/CancerCollaboratory/dockstore/releases/download/0.0.4/dockstore'
}); |
530467c4840fcd528cd836d1e25fa3174c6b3b9e | extension/keysocket-yandex-music.js | extension/keysocket-yandex-music.js | var playTarget = '.b-jambox__play';
var nextTarget = '.b-jambox__next';
var prevTarget = '.b-jambox__prev';
function onKeyPress(key) {
if (key === PREV) {
simulateClick(document.querySelector(prevTarget));
} else if (key === NEXT) {
simulateClick(document.querySelector(nextTarget));
} else if (key === PLAY) {
simulateClick(document.querySelector(playTarget));
}
} | var playTarget = '.player-controls__btn_play';
var nextTarget = '.player-controls__btn_next';
var prevTarget = '.player-controls__btn_prev';
function onKeyPress(key) {
if (key === PREV) {
simulateClick(document.querySelector(prevTarget));
} else if (key === NEXT) {
simulateClick(document.querySelector(nextTarget));
} else if (key === PLAY) {
simulateClick(document.querySelector(playTarget));
}
}
| Update locators for redesigned Yandex Music | Update locators for redesigned Yandex Music | JavaScript | apache-2.0 | borismus/keysocket,iver56/keysocket,feedbee/keysocket,vinyldarkscratch/keysocket,feedbee/keysocket,borismus/keysocket,noelmansour/keysocket,kristianj/keysocket,ALiangLiang/keysocket,kristianj/keysocket,chrisdeely/keysocket,legionaryu/keysocket,vladikoff/keysocket,vinyldarkscratch/keysocket,Whoaa512/keysocket | ---
+++
@@ -1,6 +1,6 @@
-var playTarget = '.b-jambox__play';
-var nextTarget = '.b-jambox__next';
-var prevTarget = '.b-jambox__prev';
+var playTarget = '.player-controls__btn_play';
+var nextTarget = '.player-controls__btn_next';
+var prevTarget = '.player-controls__btn_prev';
function onKeyPress(key) {
if (key === PREV) { |
b94a452d4030829731047014cefa4f178591f891 | src/scripts/plugins/Storage.js | src/scripts/plugins/Storage.js | class Storage extends Phaser.Plugin {
constructor (game, parent) {
super(game, parent);
}
init (name) {
localforage.config({ name });
}
// --------------------------------------------------------------------------
fetch (key, callback = () => {}, context = null) {
localforage.getItem(key, this._wrap(callback, context));
}
store (key, value, callback = () => {}, context = null) {
localforage.setItem(key, value, this._wrap(callback, context));
}
remove (key, callback = () => {}, context = null) {
localforage.removeItem(key, this._wrap(callback, context));
}
clear (callback = () => {}, context = null) {
localforage.clear(this._wrap(callback, context));
}
length (callback = () => {}, context = null) {
localforage.length(this._wrap(callback, context));
}
key (keyIndex, callback = () => {}, context = null) {
localforage.key(keyIndex, this._wrap(callback, context));
}
keys (callback = () => {}, context = null) {
localforage.keys(this._wrap(callback, context));
}
iterate (iterator, iterContext, callback = () => {}, cbContext = null) {
localforage.iterate(
this._wrap(iterator, iterContext),
this._wrap(callback, cbContext));
}
// --------------------------------------------------------------------------
_wrap (callback, context) {
return (... args) => { callback.apply(context, args); };
}
}
export default Storage;
| class Storage extends Phaser.Plugin {
constructor (game, parent) {
super(game, parent);
}
init (name, version = '1.0') {
localforage.config({ name, version });
}
// --------------------------------------------------------------------------
fetch (key, callback = () => {}, context = null) {
localforage.getItem(key, this._wrap(callback, context));
}
store (key, value, callback = () => {}, context = null) {
localforage.setItem(key, value, this._wrap(callback, context));
}
remove (key, callback = () => {}, context = null) {
localforage.removeItem(key, this._wrap(callback, context));
}
clear (callback = () => {}, context = null) {
localforage.clear(this._wrap(callback, context));
}
length (callback = () => {}, context = null) {
localforage.length(this._wrap(callback, context));
}
key (keyIndex, callback = () => {}, context = null) {
localforage.key(keyIndex, this._wrap(callback, context));
}
keys (callback = () => {}, context = null) {
localforage.keys(this._wrap(callback, context));
}
iterate (iterator, iterContext, callback = () => {}, cbContext = null) {
localforage.iterate(
this._wrap(iterator, iterContext),
this._wrap(callback, cbContext));
}
// --------------------------------------------------------------------------
_wrap (callback, context) {
return (... args) => { callback.apply(context, args); };
}
}
export default Storage;
| Allow an extra argument to be passed, identifying the storage version in use. | Allow an extra argument to be passed, identifying the storage version in use.
| JavaScript | mit | rblopes/heart-star,rblopes/heart-star | ---
+++
@@ -4,8 +4,8 @@
super(game, parent);
}
- init (name) {
- localforage.config({ name });
+ init (name, version = '1.0') {
+ localforage.config({ name, version });
}
// -------------------------------------------------------------------------- |
ae78fc5de9f85dd9e13412f626b643314799e487 | lib/runner/request-helpers-postsend.js | lib/runner/request-helpers-postsend.js | var AuthLoader = require('../authorizer/index').AuthLoader,
createAuthInterface = require('../authorizer/auth-interface'),
util = require('../authorizer/util');
module.exports = [
// Post authorization.
function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
// bail out if interactive mode is disabled
if (!util.isInteractiveForAuth(run.options, context.auth.type)) { return done(); }
var auth = context.auth,
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
if (err) { return done(err); }
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true});
});
}
];
| var _ = require('lodash'),
AuthLoader = require('../authorizer/index').AuthLoader,
createAuthInterface = require('../authorizer/auth-interface'),
util = require('../authorizer/util');
module.exports = [
// Post authorization.
function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
// bail out if interactive mode is disabled
if (!util.isInteractiveForAuth(run.options, context.auth.type)) { return done(); }
var auth = context.auth,
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
if (err) { return done(err); }
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true});
});
}
];
| Fix missing import in merge conflict resolution | Fix missing import in merge conflict resolution
| JavaScript | apache-2.0 | postmanlabs/postman-runtime,postmanlabs/postman-runtime | ---
+++
@@ -1,4 +1,6 @@
-var AuthLoader = require('../authorizer/index').AuthLoader,
+var _ = require('lodash'),
+
+ AuthLoader = require('../authorizer/index').AuthLoader,
createAuthInterface = require('../authorizer/auth-interface'),
util = require('../authorizer/util'); |
4bac6994b83e1ae64a01bb25e060a3730571df38 | lib/index.js | lib/index.js | 'use strict';
var child_process = require('child_process');
var fs = require('fs');
var Module = require('module');
var path = require('path');
var _ = require('lodash');
var originalRequire = module.require;
module.require = function(pth) {
if(path.extname(pth) === '.git') return loadGit(pth);
return originalRequire;
};
function loadGit(url) {
var nodeModulesPath = path.join(process.cwd(), 'node_modules');
var oldModules = fs.readdirSync(nodeModulesPath);
child_process.execSync('npm install --save ' + url + ' ');
var newModules = fs.readdirSync(nodeModulesPath);
var added = _.difference(oldModules, newModules)[0];
if(added) return originalRequire(added);
else return undefined;
}
exports = module.exports = loadGit;
console.log(require('git://github.com/yamadapc/mocha-spec-cov-alt.git'));
| 'use strict';
var child_process = require('child_process');
var fs = require('fs');
var Module = require('module');
var path = require('path');
var _ = require('lodash');
require.extensions['.git'] = loadGit;
function loadGit(url, save) {
var nodeModulesPath = path.join(process.cwd(), 'node_modules');
var oldModules = fs.readdirSync(nodeModulesPath);
var command = 'npm install ' + (save ? '--save' : '') + ' ' + url + ' ';
child_process.execSync(command, {
stdio: 'ignore',
});
var newModules = fs.readdirSync(nodeModulesPath);
var added = _.difference(oldModules, newModules)[0];
if(added) return originalRequire(added);
else return undefined;
}
exports = module.exports = loadGit;
| Make the implementation much more elegant | Make the implementation much more elegant
| JavaScript | mit | yamadapc/nrequire | ---
+++
@@ -5,21 +5,18 @@
var path = require('path');
var _ = require('lodash');
-var originalRequire = module.require;
-module.require = function(pth) {
- if(path.extname(pth) === '.git') return loadGit(pth);
- return originalRequire;
-};
+require.extensions['.git'] = loadGit;
-function loadGit(url) {
+function loadGit(url, save) {
var nodeModulesPath = path.join(process.cwd(), 'node_modules');
var oldModules = fs.readdirSync(nodeModulesPath);
- child_process.execSync('npm install --save ' + url + ' ');
+ var command = 'npm install ' + (save ? '--save' : '') + ' ' + url + ' ';
+ child_process.execSync(command, {
+ stdio: 'ignore',
+ });
var newModules = fs.readdirSync(nodeModulesPath);
var added = _.difference(oldModules, newModules)[0];
if(added) return originalRequire(added);
else return undefined;
}
exports = module.exports = loadGit;
-
-console.log(require('git://github.com/yamadapc/mocha-spec-cov-alt.git')); |
7fdc72722c0bd39d485382a0df199e933c87b9c0 | lib/index.js | lib/index.js | // Dependencies
var Typpy = require("typpy")
, NodeElm = require("./composition/node")
, Composition = require("./composition")
, Enny = require("enny")
;
function Parser(input, appService, moduleInfo, callback) {
// Add the instances
var comp = new Composition({
instances: input
, appService: appService
, moduleInfo: moduleInfo
})
comp.parseFlow();
comp.addConnections();
callback(null, comp);
}
module.exports = Parser;
| // Dependencies
var Typpy = require("typpy")
, NodeElm = require("./composition/node")
, Composition = require("./composition")
, Enny = require("enny")
;
function Parser(input, appService, moduleInfo, callback) {
// Add the instances
var comp = new Composition({
instances: input
, appService: appService
, moduleInfo: moduleInfo
})
comp.parseFlow();
comp.addConnections();
callback(null, comp);
}
if (typeof window === "object") {
window.EngineParser = Parser;
}
module.exports = Parser;
| Create a global when running in browser | Create a global when running in browser
| JavaScript | mit | jillix/engine-builder | ---
+++
@@ -20,4 +20,8 @@
callback(null, comp);
}
+if (typeof window === "object") {
+ window.EngineParser = Parser;
+}
+
module.exports = Parser; |
8290936c560abc56ee43635ff7c90b14ea3042d2 | lib/redis.js | lib/redis.js | 'use strict';
const async = require('async');
const redis = require('redis').createClient(6379, 'redis');
module.exports = redis;
module.exports.jenkinsChanged = function(nodes, cb) {
async.filter(nodes, function(node, cb) {
const key = `node:${node.displayName}`;
node.offline = !!(node.offline || node.temporarilyOffline) + 0;
redis.hget(key, 'offline', function(err, offline) {
if (err) { return cb(err); }
offline = parseInt(offline || 0, 10);
redis.hset(key, 'offline', node.offline, function(err) {
if (err) { return cb(err); }
cb(!!(node.offline ^ offline));
});
});
}, function(nodes) {
cb(null, nodes);
});
};
| 'use strict';
const async = require('async');
const redis = require('redis').createClient(6379, 'redis');
module.exports = redis;
module.exports.jenkinsChanged = function(nodes, cb) {
async.filter(nodes, function(node, cb) {
const key = `node:${node.name || node.displayName}`;
node.offline = !!(node.offline || node.temporarilyOffline) + 0;
redis.hget(key, 'offline', function(err, offline) {
if (err) { return cb(err); }
offline = parseInt(offline || 0, 10);
redis.hset(key, 'offline', node.offline, function(err) {
if (err) { return cb(err); }
cb(!!(node.offline ^ offline));
});
});
}, function(nodes) {
cb(null, nodes);
});
};
| Add support for alternative Jenkins node name | Add support for alternative Jenkins node name
| JavaScript | mit | Starefossen/jenkins-monitor | ---
+++
@@ -7,7 +7,7 @@
module.exports.jenkinsChanged = function(nodes, cb) {
async.filter(nodes, function(node, cb) {
- const key = `node:${node.displayName}`;
+ const key = `node:${node.name || node.displayName}`;
node.offline = !!(node.offline || node.temporarilyOffline) + 0;
redis.hget(key, 'offline', function(err, offline) { |
fac6e93a0fe817fb3315f1f0806004c0e07cf64c | frontend/src/contexts/UiProvider.js | frontend/src/contexts/UiProvider.js | import React, { createContext, useState } from 'react';
import PropTypes from 'prop-types';
const UiContext = createContext({
uiDarkMode: false,
uiIsLoading: false,
uiIsAnimating: false,
});
const UiProvider = ({ children }) => {
const [uiDarkMode, setUiDarkMode] = useState(false);
const [uiIsLoading, setUiIsLoading] = useState(false);
const [uiIsAnimating, setUiIsAnimating] = useState(false);
return (
<UiContext.Provider
value={{
uiDarkMode,
setUiDarkMode,
uiIsLoading,
setUiIsLoading,
uiIsAnimating,
setUiIsAnimating,
}}
>
{children}
</UiContext.Provider>
);
};
UiProvider.propTypes = {
children: PropTypes.node,
};
export { UiContext, UiProvider };
| import React, { createContext, useState } from 'react';
import PropTypes from 'prop-types';
const UiContext = createContext({
uiDarkMode: true,
uiIsLoading: false,
uiIsAnimating: false,
});
const UiProvider = ({ children }) => {
const [uiDarkMode, setUiDarkMode] = useState(true);
const [uiIsLoading, setUiIsLoading] = useState(false);
const [uiIsAnimating, setUiIsAnimating] = useState(false);
return (
<UiContext.Provider
value={{
uiDarkMode,
setUiDarkMode,
uiIsLoading,
setUiIsLoading,
uiIsAnimating,
setUiIsAnimating,
}}
>
{children}
</UiContext.Provider>
);
};
UiProvider.propTypes = {
children: PropTypes.node,
};
export { UiContext, UiProvider };
| Enable 'dark mode' by default | :crescent_moon: Enable 'dark mode' by default
| JavaScript | mit | dreamyguy/gitinsight,dreamyguy/gitinsight,dreamyguy/gitinsight | ---
+++
@@ -2,13 +2,13 @@
import PropTypes from 'prop-types';
const UiContext = createContext({
- uiDarkMode: false,
+ uiDarkMode: true,
uiIsLoading: false,
uiIsAnimating: false,
});
const UiProvider = ({ children }) => {
- const [uiDarkMode, setUiDarkMode] = useState(false);
+ const [uiDarkMode, setUiDarkMode] = useState(true);
const [uiIsLoading, setUiIsLoading] = useState(false);
const [uiIsAnimating, setUiIsAnimating] = useState(false);
|
1b73b33858db20c9cfdc171a406d12c1bcfa590f | src/util/logger/serializers.js | src/util/logger/serializers.js | /**
* @param {import('discord.js').Guild} guild
*/
function guild (guild) {
return `${guild.id}, ${guild.name}`
}
/**
* @param {import('discord.js').TextChannel} channel
*/
function channel (channel) {
return `(${channel.guild.id}) ${channel.id}, ${channel.name}`
}
/**
* @param {import('discord.js').User} user
*/
function user (user) {
return `${user.id}, ${user.username}`
}
module.exports = {
guild,
channel,
user
}
| /**
* @param {import('discord.js').Guild} guild
*/
function guild (guild) {
return `${guild.id}, ${guild.name}`
}
/**
* @param {import('discord.js').TextChannel} channel
*/
function channel (channel) {
return `${channel.id}, ${channel.name}`
}
/**
* @param {import('discord.js').User} user
*/
function user (user) {
return `${user.id}, ${user.username}`
}
module.exports = {
guild,
channel,
user
}
| Remove dupe info in channel log serializer | Remove dupe info in channel log serializer
| JavaScript | mit | synzen/Discord.RSS,synzen/Discord.RSS | ---
+++
@@ -9,7 +9,7 @@
* @param {import('discord.js').TextChannel} channel
*/
function channel (channel) {
- return `(${channel.guild.id}) ${channel.id}, ${channel.name}`
+ return `${channel.id}, ${channel.name}`
}
/** |
fde26acaffdb416751ff17c391f3a411e8d9207b | 404/main.js | 404/main.js | // 404 page using mapbox to show cities around the world.
// Helper to generate the kind of coordinate pairs I'm using to store cities
function bounds() {
var center = map.getCenter();
return {lat: center.lat, lng: center.lng, zoom: map.getZoom()};
}
L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg";
var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false});
function go(city) {
var placenames = Object.keys(places);
city = city || placenames[Math.floor(Math.random() * placenames.length)];
var pos = places[city];
map.setView(
[pos.lat, pos.lng],
pos.zoom
);
}
go();
| // 404 page using mapbox to show cities around the world.
// Helper to generate the kind of coordinate pairs I'm using to store cities
function bounds() {
var center = map.getCenter();
return {lat: center.lat, lng: center.lng, zoom: map.getZoom()};
}
L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg";
var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false});
function go(city) {
var placenames = Object.keys(places);
city = city || placenames[Math.floor(Math.random() * placenames.length)];
var pos = places[city];
map.setView(
[pos.lat, pos.lng],
pos.zoom
);
}
if (places[window.location.search.substring(1)]) {
go(window.location.search.substring(1));
} else {
go();
}
| Allow direct linking to cities | Allow direct linking to cities
| JavaScript | mit | controversial/controversial.io,controversial/controversial.io,controversial/controversial.io | ---
+++
@@ -20,4 +20,8 @@
);
}
-go();
+if (places[window.location.search.substring(1)]) {
+ go(window.location.search.substring(1));
+} else {
+ go();
+} |
4acee6d5936b15656ea280b24b98de6771849497 | src/js/utils/allowed-upload-file-extensions.js | src/js/utils/allowed-upload-file-extensions.js | 'use strict';
// APEP capital cases are also provided. Apple devices tend to provide uppercase file extensions and this conflicts with a known bug
// APEP See : https://github.com/Artear/ReactResumableJS/issues/20
var imageFileTypes = ["png", "PNG", "jpg", "JPG","JPEG","jpeg", "webp", "WEBP", "gif", "GIF", "svg", "SVG"];
var videoFileTypes = ["mov", "MOV", 'mp4', "MP4", "webm", "WEBM", "flv", "FLV", "wmv", "WMV", "avi", "AVI",
"ogg", "OGG", "ogv", "OGV", "qt", "QT", "asf", "ASF", "mpg", "MPG", "3gp", "3GP"];
var audioFileTypes = ["mp3", "MP3", "wav", "WAV"];
var allFileTypes = imageFileTypes.concat(videoFileTypes);
allFileTypes = allFileTypes.concat(audioFileTypes);
module.exports = {
IMAGE_FILE_TYPES: imageFileTypes,
VIDEO_FILE_TYPES: videoFileTypes,
AUDIO_FILE_TYPES: audioFileTypes,
ALL_FILE_TYPES: allFileTypes
};
| 'use strict';
// APEP capital cases are also provided. Apple devices tend to provide uppercase file extensions and this conflicts with a known bug
// APEP See : https://github.com/Artear/ReactResumableJS/issues/20
var imageFileTypes = ["png", "PNG", "jpg", "JPG","JPEG","jpeg", "webp", "WEBP", "gif", "GIF", "svg", "SVG"];
var videoFileTypes = ["mov", "MOV", 'mp4', "MP4", "webm", "WEBM", "flv", "FLV", "wmv", "WMV", "avi", "AVI",
"ogg", "OGG", "ogv", "OGV", "qt", "QT", "asf", "ASF", "mpg", "MPG", "3gp", "3GP"];
var audioFileTypes = ["mp3", "MP3", "wav", "WAV", "m4a", "M4A"];
var allFileTypes = imageFileTypes.concat(videoFileTypes);
allFileTypes = allFileTypes.concat(audioFileTypes);
module.exports = {
IMAGE_FILE_TYPES: imageFileTypes,
VIDEO_FILE_TYPES: videoFileTypes,
AUDIO_FILE_TYPES: audioFileTypes,
ALL_FILE_TYPES: allFileTypes
};
| Allow m4a audio files to be uploaded. | Allow m4a audio files to be uploaded.
Again, the resumable.js bug, where the capital file extensions are an issue, and require explicit declaration of file types.
| JavaScript | mit | UoSMediaFrameworks/uos-media-playback-framework-legacy,UoSMediaFrameworks/uos-media-playback-framework-legacy,UoSMediaFrameworks/uos-media-playback-framework-legacy | ---
+++
@@ -5,7 +5,7 @@
var imageFileTypes = ["png", "PNG", "jpg", "JPG","JPEG","jpeg", "webp", "WEBP", "gif", "GIF", "svg", "SVG"];
var videoFileTypes = ["mov", "MOV", 'mp4', "MP4", "webm", "WEBM", "flv", "FLV", "wmv", "WMV", "avi", "AVI",
"ogg", "OGG", "ogv", "OGV", "qt", "QT", "asf", "ASF", "mpg", "MPG", "3gp", "3GP"];
-var audioFileTypes = ["mp3", "MP3", "wav", "WAV"];
+var audioFileTypes = ["mp3", "MP3", "wav", "WAV", "m4a", "M4A"];
var allFileTypes = imageFileTypes.concat(videoFileTypes);
allFileTypes = allFileTypes.concat(audioFileTypes); |
def7c0fcb0c0c2adbd66d530d0634d6a6e53f0d7 | virun.js | virun.js | var virus = document.querySelector("div");
var x = 1;
var y = 0;
var vy = 0;
var ay = 0;
var vx = .1; // px per millisecond
var startTime = Date.now();
var clickTime;
timer = setInterval(function animate() {
var t = Date.now() - startTime;
x = vx * t;
y = vy * t + 400;
virus.style.left = x + "px";
virus.style.top = y + "px";
if ( x > document.body.clientWidth) {
startTime = Date.now();
}
if (ay >= .001) {
var t = Date.now() - clickTime;
vy = ay * t;
}
},20); // ms | 1000/20 = 50 frames per second (50 fps)
virus.addEventListener("click", function onclick(event) {
ay = .001;
clickTime = Date.now();
});
| var virus = document.querySelector("div");
var x = 1;
var y = 0;
var vy = 0;
var ay = 0;
var vx = .1; // px per millisecond
var startTime = Date.now();
var clickTime;
timer = setInterval(function animate() {
var t = Date.now() - startTime;
x = vx * t;
y = vy * t + 400;
virus.style.left = x + "px";
virus.style.top = y + "px";
if ( x > document.body.clientWidth) {
startTime = Date.now();
}
if (ay >= .001) {
var t = Date.now() - clickTime;
vy = ay * t;
}
//if ( y > document.body.clientHeight && x > document.body.clientWidth) {
// console.log("hello");
// startTime = Date.now();
//}
if (y > screen.height){
console.log("hello");
startTime = Date.now();
vy = 0;
ay = 0;
}
//if ( y > document.body.clientHeight && x > document.body.clientWidth) {
// console.log("second if");
// vy = 0;
// ay = 0;
//}
},20); // ms | 1000/20 = 50 frames per second (50 fps)
virus.addEventListener("click", function onclick(event) {
ay = .001;
clickTime = Date.now();
});
| Add property screen.height, so that the ufo, once it is shot and falls, returns to start position and flies the same horizontal line like in the beginning | Add property screen.height, so that the ufo, once it is shot and falls, returns to start position and flies the same horizontal line like in the beginning
| JavaScript | mit | BOZ2323/virun,BOZ2323/virun | ---
+++
@@ -21,11 +21,27 @@
var t = Date.now() - clickTime;
vy = ay * t;
}
+ //if ( y > document.body.clientHeight && x > document.body.clientWidth) {
+ // console.log("hello");
+ // startTime = Date.now();
+ //}
+ if (y > screen.height){
+ console.log("hello");
+ startTime = Date.now();
+ vy = 0;
+ ay = 0;
+ }
+ //if ( y > document.body.clientHeight && x > document.body.clientWidth) {
+ // console.log("second if");
+ // vy = 0;
+ // ay = 0;
+//}
},20); // ms | 1000/20 = 50 frames per second (50 fps)
virus.addEventListener("click", function onclick(event) {
ay = .001;
clickTime = Date.now();
+
});
|
d0f07c2bdcf3b282555ab86c47c19e953b3f9715 | test/client/tab_broker_test.js | test/client/tab_broker_test.js | var Q = require('q');
var tabBroker = require('../../src/js/client/tab_broker');
exports.query = {
setUp: function(cb) {
var chrome = {
runtime: {
sendMessage: function(opts, callback) {
callback({tabs: [{id: 2}, {id: 1}, {id: 3}], lastActive: 2});
}
}
};
this.api = tabBroker(chrome);
cb();
},
getsTabsInOrderFromServer: function(test) {
this.api.query('', false)
.then(function(tabs) {
test.deepEqual(tabs, [{id: 2}, {id: 1}, {id: 3}]);
test.done();
});
}
};
exports.switchTo = {
setUp: function(cb) {
var chrome = this.chrome = {
runtime: {
sendMessage: function(opts) {
if (!chrome.runtime.sendMessage.calls) chrome.runtime.sendMessage.calls = [];
chrome.runtime.sendMessage.calls.push(opts)
}
}
};
this.api = tabBroker(this.chrome);
cb();
},
sendsMessageToChangeTabs: function(test) {
this.api.switchTo({id: 123});
test.deepEqual(this.chrome.runtime.sendMessage.calls[0], {switchToTabId: 123});
test.done();
}
};
| var Q = require('q');
var tabBroker = require('../../src/js/client/tab_broker');
exports.query = {
setUp: function(cb) {
var chrome = {
runtime: {
sendMessage: function(opts, callback) {
callback({tabs: [{id: 1}, {id: 2}, {id: 3}], lastActive: 2});
}
}
};
this.api = tabBroker(chrome);
cb();
},
getsTabsInOrderFromServer: function(test) {
this.api.query('', false)
.then(function(tabs) {
test.deepEqual(tabs, [{id: 2}, {id: 1}, {id: 3}]);
test.done();
});
}
};
exports.switchTo = {
setUp: function(cb) {
var chrome = this.chrome = {
runtime: {
sendMessage: function(opts) {
if (!chrome.runtime.sendMessage.calls) chrome.runtime.sendMessage.calls = [];
chrome.runtime.sendMessage.calls.push(opts)
}
}
};
this.api = tabBroker(this.chrome);
cb();
},
sendsMessageToChangeTabs: function(test) {
this.api.switchTo({id: 123});
test.deepEqual(this.chrome.runtime.sendMessage.calls[0], {switchToTabId: 123});
test.done();
}
};
| Change tabBroker test to test ordering | Change tabBroker test to test ordering
| JavaScript | mit | findjashua/chrome-fast-tab-switcher,eanplatter/chrome-fast-tab-switcher,eanplatter/chrome-fast-tab-switcher,BinaryMuse/chrome-fast-tab-switcher,modulexcite/chrome-fast-tab-switcher,alubling/chrome-fast-tab-switcher,BinaryMuse/chrome-fast-tab-switcher,billychan/chrome-fast-tab-switcher,eanplatter/chrome-fast-tab-switcher,findjashua/chrome-fast-tab-switcher,BinaryMuse/chrome-fast-tab-switcher,billychan/chrome-fast-tab-switcher,modulexcite/chrome-fast-tab-switcher,alubling/chrome-fast-tab-switcher,alubling/chrome-fast-tab-switcher,billychan/chrome-fast-tab-switcher,findjashua/chrome-fast-tab-switcher,modulexcite/chrome-fast-tab-switcher | ---
+++
@@ -6,7 +6,7 @@
var chrome = {
runtime: {
sendMessage: function(opts, callback) {
- callback({tabs: [{id: 2}, {id: 1}, {id: 3}], lastActive: 2});
+ callback({tabs: [{id: 1}, {id: 2}, {id: 3}], lastActive: 2});
}
}
}; |
b834bacb099306bac030b37477fbee0b4a3324de | Gulpfile.js | Gulpfile.js | var gulp = require("gulp"),
util = require("gulp-util"),
minifyHtml = require("gulp-minify-html"),
less = require("gulp-less"),
minifyCss = require("gulp-minify-css"),
minifyJs = require("gulp-uglify");
gulp.task("html", function() {
util.log("Minifying...");
gulp.src("src/html/*.html")
.pipe(minifyHtml({}))
.pipe(gulp.dest("public/"));
util.log("Done!");
});
gulp.task("less", function() {
util.log("Compiling and minifying...");
gulp.src("src/less/*.less")
.pipe(less())
.pipe(minifyCss({cache: false}))
.pipe(gulp.dest("public/css/"));
util.log("Done!");
});
gulp.task("js", function() {
util.log("Minifying...");
gulp.src("src/js/*.js")
.pipe(minifyJs({mangle: false}))
.pipe(gulp.dest("public/js/"));
util.log("Done!");
});
gulp.task("watch", function() {
gulp.watch("src/html/*.html", ["html"]);
gulp.watch("src/less/**/*.less", ["less"]);
gulp.watch("src/js/*.js", ["js"]);
});
gulp.task("default", ["html", "less", "js", "watch"], function() {
util.log("Done!");
});
| var gulp = require("gulp"),
util = require("gulp-util"),
minifyHtml = require("gulp-minify-html"),
less = require("gulp-less"),
minifyCss = require("gulp-minify-css"),
minifyJs = require("gulp-uglify");
gulp.task("html", function() {
util.log("Minifying...");
gulp.src("src/html/*.html")
.pipe(minifyHtml({}))
.pipe(gulp.dest("public/"));
util.log("Done!");
});
gulp.task("less", function() {
util.log("Compiling and minifying...");
gulp.src("src/less/*.less")
.pipe(less())
.pipe(minifyCss({cache: false}))
.pipe(gulp.dest("public/css/"));
util.log("Done!");
});
gulp.task("js", function() {
util.log("Minifying...");
gulp.src("src/js/*.js")
.pipe(minifyJs({mangle: false, compress: false}))
.pipe(gulp.dest("public/js/"));
util.log("Done!");
});
gulp.task("watch", function() {
gulp.watch("src/html/*.html", ["html"]);
gulp.watch("src/less/**/*.less", ["less"]);
gulp.watch("src/js/*.js", ["js"]);
});
gulp.task("default", ["html", "less", "js", "watch"], function() {
util.log("Done!");
});
| Add compress: false for proper results. | Add compress: false for proper results.
| JavaScript | mit | bound1ess/todo-app,bound1ess/todo-app,bound1ess/todo-app | ---
+++
@@ -30,7 +30,7 @@
util.log("Minifying...");
gulp.src("src/js/*.js")
- .pipe(minifyJs({mangle: false}))
+ .pipe(minifyJs({mangle: false, compress: false}))
.pipe(gulp.dest("public/js/"));
util.log("Done!"); |
1d8cc9075091f1fe31e4d1d3a47a61abaefcd6f5 | lib/services/apimanagement/lib/models/requestReportCollection.js | lib/services/apimanagement/lib/models/requestReportCollection.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Paged Report records list representation.
*/
class RequestReportCollection extends Array {
/**
* Create a RequestReportCollection.
* @member {number} [count] Total record count number across all pages.
*/
constructor() {
super();
}
/**
* Defines the metadata of RequestReportCollection
*
* @returns {object} metadata of RequestReportCollection
*
*/
mapper() {
return {
required: false,
serializedName: 'RequestReportCollection',
type: {
name: 'Composite',
className: 'RequestReportCollection',
modelProperties: {
value: {
required: false,
serializedName: '',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'RequestReportRecordContractElementType',
type: {
name: 'Composite',
className: 'RequestReportRecordContract'
}
}
}
}
count: {
required: false,
serializedName: 'count',
type: {
name: 'Number'
}
}
}
}
};
}
}
module.exports = RequestReportCollection;
| /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Paged Report records list representation.
*/
class RequestReportCollection extends Array {
/**
* Create a RequestReportCollection.
* @member {number} [count] Total record count number across all pages.
*/
constructor() {
super();
}
/**
* Defines the metadata of RequestReportCollection
*
* @returns {object} metadata of RequestReportCollection
*
*/
mapper() {
return {
required: false,
serializedName: 'RequestReportCollection',
type: {
name: 'Composite',
className: 'RequestReportCollection',
modelProperties: {
value: {
required: false,
serializedName: '',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'RequestReportRecordContractElementType',
type: {
name: 'Composite',
className: 'RequestReportRecordContract'
}
}
}
},
count: {
required: false,
serializedName: 'count',
type: {
name: 'Number'
}
}
}
}
};
}
}
module.exports = RequestReportCollection;
| Add missing comma in apimanagement mapper | Add missing comma in apimanagement mapper
| JavaScript | mit | xingwu1/azure-sdk-for-node,xingwu1/azure-sdk-for-node,Azure/azure-sdk-for-node,xingwu1/azure-sdk-for-node,Azure/azure-sdk-for-node,Azure/azure-sdk-for-node | ---
+++
@@ -50,7 +50,7 @@
}
}
}
- }
+ },
count: {
required: false,
serializedName: 'count', |
a7cde01856ed053477d1edf907f4236ae2dbb23e | trex/static/js/controllers.js | trex/static/js/controllers.js | var trexControllers = angular.module('trexControllers', []);
trexControllers.controller('ProjectListCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get('/api/1/projects/').success(function(data) {
$scope.projects = data;
});
$scope.order = "name";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
trexControllers.controller('ProjectDetailCtrl',
['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$http.get('/api/1/projects/' + $routeParams.id).success(function(data) {
$scope.project = data;
});
$http.get('/api/1/projects/' + $routeParams.id + "/entries").success(
function(data) {
$scope.entries = data;
});
$scope.order = "name";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
| var trexControllers = angular.module('trexControllers', []);
trexControllers.controller('ProjectListCtrl', ['$scope', 'Project',
function($scope, Project) {
$scope.projects = Project.query();
$scope.order = "name";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
trexControllers.controller('ProjectDetailCtrl',
['$scope', '$routeParams', 'Project',
function($scope, $routeParams, Project) {
$scope.project = Project.get({projectId: $routeParams.id});
$scope.entries = Project.entries({projectId: $routeParams.id});
// $http.get('/api/1/projects/' + $routeParams.id + "/entries").success(
// function(data) {
// });
$scope.order = "id";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
| Use new services for retreiving the Project and Entry | Use new services for retreiving the Project and Entry
| JavaScript | mit | bjoernricks/trex,bjoernricks/trex | ---
+++
@@ -1,10 +1,8 @@
var trexControllers = angular.module('trexControllers', []);
-trexControllers.controller('ProjectListCtrl', ['$scope', '$http',
- function($scope, $http) {
- $http.get('/api/1/projects/').success(function(data) {
- $scope.projects = data;
- });
+trexControllers.controller('ProjectListCtrl', ['$scope', 'Project',
+ function($scope, Project) {
+ $scope.projects = Project.query();
$scope.order = "name";
$scope.orderreverse = false;
@@ -19,16 +17,14 @@
]);
trexControllers.controller('ProjectDetailCtrl',
- ['$scope', '$routeParams', '$http',
- function($scope, $routeParams, $http) {
- $http.get('/api/1/projects/' + $routeParams.id).success(function(data) {
- $scope.project = data;
- });
- $http.get('/api/1/projects/' + $routeParams.id + "/entries").success(
- function(data) {
- $scope.entries = data;
- });
- $scope.order = "name";
+ ['$scope', '$routeParams', 'Project',
+ function($scope, $routeParams, Project) {
+ $scope.project = Project.get({projectId: $routeParams.id});
+ $scope.entries = Project.entries({projectId: $routeParams.id});
+ // $http.get('/api/1/projects/' + $routeParams.id + "/entries").success(
+ // function(data) {
+ // });
+ $scope.order = "id";
$scope.orderreverse = false;
$scope.setOrder = function(name) { |
dd950e957c2acc4b12160c0d64721506cab0348f | Gulpfile.js | Gulpfile.js | var gulp = require('gulp'),
$ = require('gulp-load-plugins')();
gulp.task('styles', function() {
gulp.src('app/**/*.scss')
.pipe($.watch(function(files) {
files.pipe($.sass())
.pipe($.autoprefixer())
.pipe($.minifyCss())
.pipe(gulp.dest('./dist'))
.pipe($.livereload());
}));
});
gulp.task('copy', function() {
gulp.src('app/**/*.html')
.pipe($.watch())
.pipe($.embedlr())
.pipe(gulp.dest('./dist'))
});
gulp.task('serve', $.serve({
root: ['dist', 'app'],
port: 9000
}));
gulp.task('default', ['styles', 'copy', 'serve']);
| var gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
browserSync = require('browser-sync'),
reload = browserSync.reload,
config = {
// destinations
tmp: '.tmp',
app: 'app',
dist: 'dist',
// globs
sass: 'app/**/*.scss',
};
gulp.task('copy', function() {
gulp.src('app/**/*.html')
.pipe($.watch())
.pipe(gulp.dest('./dist'))
});
gulp.task('sass', function() {
return gulp.src(config.sass)
.pipe($.plumber())
.pipe($.sass())
.pipe($.autoprefixer())
/*.pipe($.minifyCss())*/
.pipe(gulp.dest(config.tmp))
.pipe(reload({stream: true}));
});
gulp.task('browser-sync', function() {
return browserSync({
server: {
baseDir: [config.tmp, config.app]
}
})
});
gulp.task('watch', function() {
$.watch({glob: config.sass, name: 'Sass'}, ['sass']);
});
gulp.task('default', ['sass', 'copy', 'watch', 'browser-sync']);
| Update intensely to be much better. | Update intensely to be much better.
| JavaScript | mit | SevereOverfl0w/generator-buymilk | ---
+++
@@ -1,28 +1,43 @@
var gulp = require('gulp'),
- $ = require('gulp-load-plugins')();
+ $ = require('gulp-load-plugins')(),
+ browserSync = require('browser-sync'),
+ reload = browserSync.reload,
+ config = {
+ // destinations
+ tmp: '.tmp',
+ app: 'app',
+ dist: 'dist',
+ // globs
+ sass: 'app/**/*.scss',
+ };
-
-gulp.task('styles', function() {
- gulp.src('app/**/*.scss')
- .pipe($.watch(function(files) {
- files.pipe($.sass())
- .pipe($.autoprefixer())
- .pipe($.minifyCss())
- .pipe(gulp.dest('./dist'))
- .pipe($.livereload());
- }));
-});
gulp.task('copy', function() {
gulp.src('app/**/*.html')
.pipe($.watch())
- .pipe($.embedlr())
.pipe(gulp.dest('./dist'))
});
-gulp.task('serve', $.serve({
- root: ['dist', 'app'],
- port: 9000
-}));
+gulp.task('sass', function() {
+ return gulp.src(config.sass)
+ .pipe($.plumber())
+ .pipe($.sass())
+ .pipe($.autoprefixer())
+ /*.pipe($.minifyCss())*/
+ .pipe(gulp.dest(config.tmp))
+ .pipe(reload({stream: true}));
+});
-gulp.task('default', ['styles', 'copy', 'serve']);
+gulp.task('browser-sync', function() {
+ return browserSync({
+ server: {
+ baseDir: [config.tmp, config.app]
+ }
+ })
+});
+
+gulp.task('watch', function() {
+ $.watch({glob: config.sass, name: 'Sass'}, ['sass']);
+});
+
+gulp.task('default', ['sass', 'copy', 'watch', 'browser-sync']); |
3411cef46121ed8f27468275a6149ee1a55fd717 | SmartyFace.js | SmartyFace.js | // ==UserScript==
// @name SmartyFace
// @description Text Prediction on facepunch
// @author benjojo
// @namespace http://facepunch.com
// @include http://facepunch.com/*
// @include http://www.facepunch.com/*
// @include https://facepunch.com/*
// @include https://www.facepunch.com/*
// @version 1
// ==/UserScript==
var endPoint = "http://text.nsa.me.uk/pose";
function findTextBoxes (argument) {
var boxes = $('textarea');
var parent = boxes[2].parentNode;
$(parent).prepend("<i id=\"SmartyFace\" style=\"pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\">This is a test wow. such test</i>");
var textarea = boxes[2];
$(boxes[2]).keypress(function(a) {
var text = $(textarea).val();
$.post( endPoint, { post: text })
.done(function( data ) {
$('#SmartyFace').html($(textarea).val()+data);
});
// $('#SmartyFace').html($(textarea).val());
});
}
findTextBoxes(); | // ==UserScript==
// @name SmartyFace
// @description Text Prediction on facepunch
// @author benjojo
// @namespace http://facepunch.com
// @include http://facepunch.com/*
// @include http://www.facepunch.com/*
// @include https://facepunch.com/*
// @include https://www.facepunch.com/*
// @version 1
// ==/UserScript==
var endPoint = "http://text.nsa.me.uk/pose";
function findTextBoxes (argument) {
var boxes = $('textarea');
var parent = boxes[2].parentNode;
$(parent).prepend("<i id=\"SmartyFace\" style=\"pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\">Type Reply Here</i>");
var textarea = boxes[2];
$(boxes[2]).keypress(function(a) {
var text = $(textarea).val();
$.post( endPoint, { post: text })
.done(function( data ) {
$('#SmartyFace').html($(textarea).val()+data);
});
// $('#SmartyFace').html($(textarea).val());
});
}
findTextBoxes(); | Make the starting text more sane | Make the starting text more sane
| JavaScript | mit | benjojo/SmartyFace | ---
+++
@@ -16,7 +16,7 @@
function findTextBoxes (argument) {
var boxes = $('textarea');
var parent = boxes[2].parentNode;
- $(parent).prepend("<i id=\"SmartyFace\" style=\"pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\">This is a test wow. such test</i>");
+ $(parent).prepend("<i id=\"SmartyFace\" style=\"pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\">Type Reply Here</i>");
var textarea = boxes[2];
$(boxes[2]).keypress(function(a) {
var text = $(textarea).val(); |
f98f6b4660110f1421eae1f484d9242b62b0697d | src/swagger/add-model.js | src/swagger/add-model.js | 'use strict';
var _ = require('lodash');
var swagger = require('swagger-spec-express');
var schemaKeys = Object.keys(require('swagger-spec-express/lib/schemas/schema.json').properties);
schemaKeys.push('definitions');
module.exports = function addModel(schema) {
var modelSchema = _.cloneDeep(_.pick(schema, schemaKeys));
stripSpecificProperties(modelSchema);
swagger.common.addModel(modelSchema, {validation: 'warn'});
};
const propertiesToStrip = ['faker', 'chance'];
function stripSpecificProperties(schema) {
if (_.isArray(schema)) {
schema.forEach(function (item) {
stripSpecificProperties(item);
});
return;
}
if (!_.isObject(schema)) {
return;
}
propertiesToStrip.forEach(function (key) {
delete schema[key];
});
_.valuesIn(schema).forEach(stripSpecificProperties);
} | 'use strict';
var _ = require('lodash');
var swagger = require('swagger-spec-express');
var schemaKeys = Object.keys(require('swagger-spec-express/lib/schemas/schema.json').properties);
schemaKeys.push('definitions');
module.exports = function addModel(schema) {
var modelSchema = _.cloneDeep(_.pick(schema, schemaKeys));
filterProperties(modelSchema.properties);
if (modelSchema.definitions) {
Object.keys(modelSchema.definitions).forEach(function (definitionName) {
var definitionValue = modelSchema.definitions[definitionName];
filterProperties(definitionValue.properties);
});
}
swagger.common.addModel(modelSchema, {validation: 'warn'});
};
function filterProperties(properties) {
Object.keys(properties).forEach(function (propertyName) {
var propertyValue = properties[propertyName];
Object.keys(propertyValue).forEach(function (key) {
if (schemaKeys.indexOf(key) < 0) {
delete propertyValue[key];
}
if (key.toLowerCase() === 'properties') {
filterProperties(propertyValue.properties);
}
});
});
} | Fix for stripping properties before adding to swagger. | Fix for stripping properties before adding to swagger.
| JavaScript | mit | eXigentCoder/node-api-seed,eXigentCoder/node-api-seed | ---
+++
@@ -6,23 +6,26 @@
module.exports = function addModel(schema) {
var modelSchema = _.cloneDeep(_.pick(schema, schemaKeys));
- stripSpecificProperties(modelSchema);
+ filterProperties(modelSchema.properties);
+ if (modelSchema.definitions) {
+ Object.keys(modelSchema.definitions).forEach(function (definitionName) {
+ var definitionValue = modelSchema.definitions[definitionName];
+ filterProperties(definitionValue.properties);
+ });
+ }
swagger.common.addModel(modelSchema, {validation: 'warn'});
};
-const propertiesToStrip = ['faker', 'chance'];
-function stripSpecificProperties(schema) {
- if (_.isArray(schema)) {
- schema.forEach(function (item) {
- stripSpecificProperties(item);
+function filterProperties(properties) {
+ Object.keys(properties).forEach(function (propertyName) {
+ var propertyValue = properties[propertyName];
+ Object.keys(propertyValue).forEach(function (key) {
+ if (schemaKeys.indexOf(key) < 0) {
+ delete propertyValue[key];
+ }
+ if (key.toLowerCase() === 'properties') {
+ filterProperties(propertyValue.properties);
+ }
});
- return;
- }
- if (!_.isObject(schema)) {
- return;
- }
- propertiesToStrip.forEach(function (key) {
- delete schema[key];
});
- _.valuesIn(schema).forEach(stripSpecificProperties);
} |
e1cfb2e2b4cc186c7d23c47e9d759d54b7571c80 | src/renderers/canvas/sigma.canvas.nodes.def.js | src/renderers/canvas/sigma.canvas.nodes.def.js | ;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.nodes');
/**
* The default node renderer. It renders the node as a simple disc.
*
* @param {object} node The node object.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.nodes.def = function(node, context, settings) {
var prefix = settings('prefix') || '';
context.fillStyle = node.color || settings('defaultNodeColor');
context.globalAlpha = node.alpha || settings('defaultNodeAlpha') || 1;
context.beginPath();
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'],
0,
Math.PI * 2,
true
);
context.closePath();
context.fill();
};
})();
| ;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.nodes');
/**
* The default node renderer. It renders the node as a simple disc.
*
* @param {object} node The node object.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.nodes.def = function(node, context, settings) {
var prefix = settings('prefix') || '';
context.fillStyle = node.color || settings('defaultNodeColor');
context.globalAlpha = node.alpha || settings('defaultNodeAlpha') || 1;
context.beginPath();
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'],
0,
Math.PI * 2,
true
);
context.closePath();
context.fill();
if (node.hasBorder) {
context.beginPath();
context.strokeStyle = settings('nodeBorderColor') === 'node' ?
(node.color || settings('defaultNodeColor')) :
settings('defaultNodeBorderColor');
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'] + settings('borderSize'),
0,
Math.PI * 2,
true
);
context.closePath();
context.stroke();
}
};
})();
| Add suport for node borders using hasBorder property | Add suport for node borders using hasBorder property
| JavaScript | mit | wesako/sigma.js,wesako/sigma.js | ---
+++
@@ -27,5 +27,22 @@
context.closePath();
context.fill();
+
+ if (node.hasBorder) {
+ context.beginPath();
+ context.strokeStyle = settings('nodeBorderColor') === 'node' ?
+ (node.color || settings('defaultNodeColor')) :
+ settings('defaultNodeBorderColor');
+ context.arc(
+ node[prefix + 'x'],
+ node[prefix + 'y'],
+ node[prefix + 'size'] + settings('borderSize'),
+ 0,
+ Math.PI * 2,
+ true
+ );
+ context.closePath();
+ context.stroke();
+ }
};
})(); |
811b7afd2dd29d36a3fd610ba55a6388ef8e2a47 | lib/assets/javascripts/cartodb3/components/modals/add-analysis/create-analysis-options-models.js | lib/assets/javascripts/cartodb3/components/modals/add-analysis/create-analysis-options-models.js | var AddAnalysisOptionModel = require('./add-analysis-option-model');
module.exports = function (analysisDefinitionNodeModel) {
var models = [];
var areaOfInfluence = _t('components.modals.add-analysis.options.sub-titles.area-of-influence');
// Buffer
models.push(
new AddAnalysisOptionModel({
title: _t('components.modals.add-analysis.options.buffer.title'),
desc: _t('components.modals.add-analysis.options.buffer.desc'),
sub_title: areaOfInfluence,
node_attrs: {
type: 'buffer',
source_id: analysisDefinitionNodeModel.id,
radio: 123
}
})
);
// Trade-area
models.push(
new AddAnalysisOptionModel({
title: _t('components.modals.add-analysis.options.trade-area.title'),
desc: _t('components.modals.add-analysis.options.trade-area.desc'),
sub_title: areaOfInfluence,
node_attrs: {
type: 'trade-area',
source_id: analysisDefinitionNodeModel.id,
kind: 'drive',
time: 300
}
})
);
return models;
};
| var AddAnalysisOptionModel = require('./add-analysis-option-model');
module.exports = function (analysisDefinitionNodeModel) {
var models = [];
var areaOfInfluence = _t('components.modals.add-analysis.options.sub-titles.area-of-influence');
// Buffer
models.push(
new AddAnalysisOptionModel({
title: _t('components.modals.add-analysis.options.buffer.title'),
desc: _t('components.modals.add-analysis.options.buffer.desc'),
sub_title: areaOfInfluence,
node_attrs: {
type: 'buffer',
source_id: analysisDefinitionNodeModel.id,
radio: 300
}
})
);
// Trade-area
models.push(
new AddAnalysisOptionModel({
title: _t('components.modals.add-analysis.options.trade-area.title'),
desc: _t('components.modals.add-analysis.options.trade-area.desc'),
sub_title: areaOfInfluence,
node_attrs: {
type: 'trade-area',
source_id: analysisDefinitionNodeModel.id,
kind: 'drive',
time: 300
}
})
);
return models;
};
| Make the buffer radio be big enough to change points visually | Make the buffer radio be big enough to change points visually
| JavaScript | bsd-3-clause | CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,CartoDB/cartodb,codeandtheory/cartodb,CartoDB/cartodb,codeandtheory/cartodb,splashblot/dronedb,splashblot/dronedb,splashblot/dronedb,CartoDB/cartodb,codeandtheory/cartodb,splashblot/dronedb,codeandtheory/cartodb,codeandtheory/cartodb | ---
+++
@@ -14,7 +14,7 @@
node_attrs: {
type: 'buffer',
source_id: analysisDefinitionNodeModel.id,
- radio: 123
+ radio: 300
}
})
); |
d6f02fe1f7229548de0abf09549786cc9302a315 | createDatabase.js | createDatabase.js | var seq = require('seq');
var args = require('yargs').argv;
var Factory = require('./lib/database/Factory');
var config = require('./lib/configuration');
var fileName = args.filename || null;
var dbOptions = config.database;
if (fileName) {
dbOptions.options.filename = fileName;
}
Factory.create(dbOptions, function(error, db) {
if (error) return console.log(error.message);
seq()
.par(function() {
db.query('create table users (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, createDate datetime default current_timestamp)', [], this);
})
.par(function() {
db.query('create table transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER, createDate datetime default current_timestamp, value REAL)', [], this);
})
.seq(function() {
console.log('database ' + dbOptions.options.filename + ' created');
});
});
| var seq = require('seq');
var args = require('yargs').argv;
var Factory = require('./lib/database/Factory');
var config = require('./lib/configuration');
var fileName = args.filename || null;
var dbOptions = config.database;
if (fileName) {
dbOptions.options.filename = fileName;
}
Factory.create(dbOptions, function(error, db) {
if (error) return console.log(error.message);
seq()
.par(function() {
db.query('CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, createDate DATETIME DEFAULT current_timestamp)', [], this);
})
.par(function() {
db.query('CREATE TABLE transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER, createDate DATETIME DEFAULT current_timestamp, value REAL)', [], this);
})
.seq(function() {
db.query('CREATE INDEX userId ON transactions(userId)', [], this);
})
.seq(function() {
console.log('database ' + dbOptions.options.filename + ' created');
});
});
| Add index on userid to transaction database | Add index on userid to transaction database
| JavaScript | mit | hackerspace-bootstrap/strichliste | ---
+++
@@ -16,10 +16,13 @@
seq()
.par(function() {
- db.query('create table users (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, createDate datetime default current_timestamp)', [], this);
+ db.query('CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, createDate DATETIME DEFAULT current_timestamp)', [], this);
})
.par(function() {
- db.query('create table transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER, createDate datetime default current_timestamp, value REAL)', [], this);
+ db.query('CREATE TABLE transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER, createDate DATETIME DEFAULT current_timestamp, value REAL)', [], this);
+ })
+ .seq(function() {
+ db.query('CREATE INDEX userId ON transactions(userId)', [], this);
})
.seq(function() {
console.log('database ' + dbOptions.options.filename + ' created'); |
9e43aeae0f6ea5333fb41444a7722f5afbd12691 | src/start/WelcomeScreen.js | src/start/WelcomeScreen.js | /* @flow */
import React, { PureComponent } from 'react';
import { View, StyleSheet } from 'react-native';
import connectWithActions from '../connectWithActions';
import type { Actions } from '../types';
import { Screen, ZulipButton } from '../common';
const componentStyles = StyleSheet.create({
divider: {
height: 20,
},
});
type Props = {
actions: Actions,
};
class WelcomeScreen extends PureComponent<Props> {
props: Props;
render() {
const { actions } = this.props;
return (
<Screen title="Welcome!" centerContent padding>
<ZulipButton
text="I have a Zulip account"
onPress={() => actions.navigateToAddNewAccount('')}
/>
<View style={componentStyles.divider} />
<ZulipButton text="I am new to Zulip" onPress={() => actions.navigateToWelcomeHelp()} />
</Screen>
);
}
}
export default connectWithActions()(WelcomeScreen);
| /* @flow */
import React, { PureComponent } from 'react';
import connectWithActions from '../connectWithActions';
import type { Actions } from '../types';
import { Screen, ViewPlaceholder, ZulipButton } from '../common';
type Props = {
actions: Actions,
};
class WelcomeScreen extends PureComponent<Props> {
props: Props;
render() {
const { actions } = this.props;
return (
<Screen title="Welcome!" centerContent padding>
<ZulipButton
text="I have a Zulip account"
onPress={() => actions.navigateToAddNewAccount('')}
/>
<ViewPlaceholder height={20} />
<ZulipButton text="I am new to Zulip" onPress={() => actions.navigateToWelcomeHelp()} />
</Screen>
);
}
}
export default connectWithActions()(WelcomeScreen);
| Use ViewPlaceholder instead of custom code | ui: Use ViewPlaceholder instead of custom code
Instead of using a custom View with custom styles use the
ViewPlaceholder component.
| JavaScript | apache-2.0 | vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile | ---
+++
@@ -1,16 +1,9 @@
/* @flow */
import React, { PureComponent } from 'react';
-import { View, StyleSheet } from 'react-native';
import connectWithActions from '../connectWithActions';
import type { Actions } from '../types';
-import { Screen, ZulipButton } from '../common';
-
-const componentStyles = StyleSheet.create({
- divider: {
- height: 20,
- },
-});
+import { Screen, ViewPlaceholder, ZulipButton } from '../common';
type Props = {
actions: Actions,
@@ -27,7 +20,7 @@
text="I have a Zulip account"
onPress={() => actions.navigateToAddNewAccount('')}
/>
- <View style={componentStyles.divider} />
+ <ViewPlaceholder height={20} />
<ZulipButton text="I am new to Zulip" onPress={() => actions.navigateToWelcomeHelp()} />
</Screen>
); |
e5afbc0d575605db7c52326e1acb1e0af3186f87 | application/layout/app-header.js | application/layout/app-header.js | //Needed components
var Header = require('../header').component;
var Cartridge = require('../cartridge').component;
var ContentBar = require('../content-bar').component;
var Bar = require('../bar').component;
var ContentActions = require('../content-actions').component;
var applicationStore = require('focus').application.builtInStore();
module.exports = React.createClass({
displayName: 'AppHeader',
/** @inheriteddoc */
getInitialState: function getCartridgeInitialState() {
return this._getStateFromStore();
},
/** @inheriteddoc */
componentWillMount: function cartridgeWillMount() {
applicationStore.addModeChangeListener(this._handleModeChange);
},
/** @inheriteddoc */
componentWillUnMount: function cartridgeWillUnMount(){
applicationStore.removeModeChangeListener(this._handleModeChange);
},
_handleModeChange: function(){
this.setState(this._getStateFromStore());
},
_getStateFromStore: function getCartridgeStateFromStore(){
var processMode = applicationStore.getMode();
var mode = 'consult';
if(processMode && processMode.edit && processMode.edit > 0){
mode = 'edit';
}
return {mode: mode};
},
render: function renderApplicationHeader() {
return (
<Header data-focus-mode={this.state.mode}>
<ContentBar>
<Bar appName='FOCUS'/>
<Cartridge />
</ContentBar>
<ContentActions />
</Header>
);
}
});
| //Needed components
var Header = require('../header').component;
var Cartridge = require('../cartridge').component;
var ContentBar = require('../content-bar').component;
var Bar = require('../bar').component;
var ContentActions = require('../content-actions').component;
module.exports = React.createClass({
displayName: 'AppHeader',
render: function renderApplicationHeader() {
return (
<Header>
<ContentBar>
<Bar appName='FOCUS'/>
<Cartridge />
</ContentBar>
<ContentActions />
</Header>
);
}
});
| Remove the application mode and route | [layout] Remove the application mode and route
| JavaScript | mit | JRLK/focus-components,Bernardstanislas/focus-components,Jerom138/focus-components,asimsir/focus-components,Bernardstanislas/focus-components,get-focus/focus-components,sebez/focus-components,sebez/focus-components,JRLK/focus-components,KleeGroup/focus-components,Bernardstanislas/focus-components,anisgh/focus-components,JRLK/focus-components,Ephrame/focus-components,anisgh/focus-components,asimsir/focus-components,KleeGroup/focus-components,JabX/focus-components,JabX/focus-components,Jerom138/focus-components,Ephrame/focus-components,anisgh/focus-components,Ephrame/focus-components,Jerom138/focus-components | ---
+++
@@ -4,36 +4,11 @@
var ContentBar = require('../content-bar').component;
var Bar = require('../bar').component;
var ContentActions = require('../content-actions').component;
-var applicationStore = require('focus').application.builtInStore();
module.exports = React.createClass({
-
displayName: 'AppHeader',
-/** @inheriteddoc */
- getInitialState: function getCartridgeInitialState() {
- return this._getStateFromStore();
- },
- /** @inheriteddoc */
- componentWillMount: function cartridgeWillMount() {
- applicationStore.addModeChangeListener(this._handleModeChange);
- },
- /** @inheriteddoc */
- componentWillUnMount: function cartridgeWillUnMount(){
- applicationStore.removeModeChangeListener(this._handleModeChange);
- },
- _handleModeChange: function(){
- this.setState(this._getStateFromStore());
- },
- _getStateFromStore: function getCartridgeStateFromStore(){
- var processMode = applicationStore.getMode();
- var mode = 'consult';
- if(processMode && processMode.edit && processMode.edit > 0){
- mode = 'edit';
- }
- return {mode: mode};
- },
render: function renderApplicationHeader() {
return (
- <Header data-focus-mode={this.state.mode}>
+ <Header>
<ContentBar>
<Bar appName='FOCUS'/>
<Cartridge /> |
04e12c573399f08472307d2654a46360dc365986 | my-frontend/app/routes/application.js | my-frontend/app/routes/application.js | import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(
ApplicationRouteMixin, {
beforeModel: function () {
return this.csrf.fetchToken();
}
});
| import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(
ApplicationRouteMixin, {
beforeModel: function () {
this._super.apply(this, arguments);
return this.csrf.fetchToken();
}
});
| Call super in beforeModel hook | Call super in beforeModel hook
Use super to call the application routes beforeModel hook so the
ApplicationRouteMixin works.
| JavaScript | unlicense | givanse/ember-cli-simple-auth-devise,bryanwongbh/ember-cli-simple-auth-devise,garth0323/therapy,givanse/ember-cli-simple-auth-devise,garth0323/therapy,givanse/ember-cli-simple-auth-devise,bryanwongbh/ember-cli-simple-auth-devise | ---
+++
@@ -4,6 +4,7 @@
export default Ember.Route.extend(
ApplicationRouteMixin, {
beforeModel: function () {
+ this._super.apply(this, arguments);
return this.csrf.fetchToken();
}
}); |
e503dea58f44ac41fd18cbeaa634c6b373bb5b8d | scripts/build.js | scripts/build.js | const buildBaseCss = require(`./build/base-css.js`);
const buildBaseHtml = require(`./build/base-html.js`);
const buildPackageCss = require(`./build/package-css.js`);
const buildPackageHtml = require(`./build/package-html.js`);
const getDirectories = require(`./lib/get-directories.js`);
const packages = getDirectories(`avalanche/packages`);
const data = {
css: `<link rel="stylesheet" href="/base/css/global.css">`
};
buildBaseHtml(data);
buildBaseCss();
packages.forEach((packageName) => {
data.title = packageName;
data.css = [
`<link rel="stylesheet" href="/base/css/global.css">`,
`<link rel="stylesheet" href="/packages/${packageName}/css/index.css">`
].join(`\n`);
buildPackageHtml(packageName, data);
buildPackageCss(packageName);
});
| const buildBaseCss = require(`./build/base-css.js`);
const buildBaseHtml = require(`./build/base-html.js`);
const buildPackageCss = require(`./build/package-css.js`);
const buildPackageHtml = require(`./build/package-html.js`);
const getDirectories = require(`./lib/get-directories.js`);
const packages = getDirectories(`avalanche/packages`);
const defaultData = {
css: `<link rel="stylesheet" href="/base/css/global.css">`
};
buildBaseHtml(defaultData);
buildBaseCss();
packages.forEach((packageName) => {
const packageData = JSON.parse(JSON.stringify(defaultData));
packageData.title = packageName;
packageData.css = [
`<link rel="stylesheet" href="/base/css/global.css">`,
`<link rel="stylesheet" href="/packages/${packageName}/css/index.css">`
].join(`\n`);
buildPackageHtml(packageName, packageData);
buildPackageCss(packageName);
});
| Clone the default page data for every package to prevent problems with async tasks | Clone the default page data for every package to prevent problems with async tasks
| JavaScript | mit | avalanchesass/avalanche-website,avalanchesass/avalanche-website | ---
+++
@@ -6,21 +6,22 @@
const packages = getDirectories(`avalanche/packages`);
-const data = {
+const defaultData = {
css: `<link rel="stylesheet" href="/base/css/global.css">`
};
-buildBaseHtml(data);
+buildBaseHtml(defaultData);
buildBaseCss();
packages.forEach((packageName) => {
- data.title = packageName;
+ const packageData = JSON.parse(JSON.stringify(defaultData));
+ packageData.title = packageName;
- data.css = [
+ packageData.css = [
`<link rel="stylesheet" href="/base/css/global.css">`,
`<link rel="stylesheet" href="/packages/${packageName}/css/index.css">`
].join(`\n`);
- buildPackageHtml(packageName, data);
+ buildPackageHtml(packageName, packageData);
buildPackageCss(packageName);
}); |
14f18e750480aeac369015f9e9fc25d475689b31 | server/routes.js | server/routes.js | function calcWidth(name) {
return 225 + name.length * 6.305555555555555;
}
WebApp.connectHandlers.use("/package", function(request, response) {
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
var opts = {headers: {'Accept': 'application/json'}};
HTTP.get(url, opts, function(err, res) {
var name = '', version, pubDate, starCount, installYear;
var pl = res.data[0];
if (res.data.length !== 0) {
name = pl.name;
version = pl.latestVersion.version;
pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY');
starCount = pl.starCount || 0;
installYear = pl['installs-per-year'] || 0;
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = calcWidth(name);
var icon = SSR.render('icon', {w: width, totalW: width+2, n: name,
v: version, p: pubDate, s: starCount, i: installYear});
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
});
| WebApp.connectHandlers.use("/package", function(request, response) {
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
var opts = {headers: {'Accept': 'application/json'}};
HTTP.get(url, opts, function(err, res) {
var name = '', version, pubDate, starCount, installYear;
var pl = res.data[0];
if (res.data.length !== 0) {
name = pl.name;
version = pl.latestVersion.version;
pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY');
starCount = pl.starCount || 0;
installYear = pl['installs-per-year'] || 0;
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = 225 + name.length * 6.305555555555555;
var icon = SSR.render('icon', {w: width, totalW: width+2, n: name,
v: version, p: pubDate, s: starCount, i: installYear});
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
});
| Delete a function to save LOC | Delete a function to save LOC
| JavaScript | mit | sungwoncho/meteor-icon,sungwoncho/meteor-icon | ---
+++
@@ -1,7 +1,3 @@
-function calcWidth(name) {
- return 225 + name.length * 6.305555555555555;
-}
-
WebApp.connectHandlers.use("/package", function(request, response) {
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
@@ -19,7 +15,7 @@
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
- var width = calcWidth(name);
+ var width = 225 + name.length * 6.305555555555555;
var icon = SSR.render('icon', {w: width, totalW: width+2, n: name,
v: version, p: pubDate, s: starCount, i: installYear});
|
a8ece3a1f14c850d3eb79c0bb16532a419b91749 | server/server.js | server/server.js | var express = require('express');
var mongoose = require('mongoose');
var app = express();
// connect to mongo database named "bolt"
// uncomment this line to use a local database
// mongoose.connect('mongodb://localhost/bolt');
mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp');
require('./config/middleware.js')(app, express);
require('./config/routes.js')(app, express);
// start listening to requests on port 8000
var port = Number(process.env.PORT || 8000);
app.listen(port, function () {
console.log(`server listening on port ${port}`);
});
// export our app for testing and flexibility, required by index.js
module.exports = app;
//test
| var express = require('express');
var mongoose = require('mongoose');
var app = express();
// connect to mongo database named "bolt"
// uncomment this line to use a local database
// be sure to re-comment this line when submitting PR
// mongoose.connect('mongodb://localhost/bolt');
mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp');
require('./config/middleware.js')(app, express);
require('./config/routes.js')(app, express);
// start listening to requests on port 8000
var port = Number(process.env.PORT || 8000);
app.listen(port, function () {
console.log(`server listening on port ${port}`);
});
// export our app for testing and flexibility, required by index.js
module.exports = app;
//test
| Add reccomendation comment to make sure local DB testing changes dont get pulled | Add reccomendation comment to make sure local DB testing changes dont get pulled
| JavaScript | mit | gm758/Bolt,boisterousSplash/Bolt,thomasRhoffmann/Bolt,elliotaplant/Bolt,elliotaplant/Bolt,boisterousSplash/Bolt,thomasRhoffmann/Bolt,gm758/Bolt | ---
+++
@@ -5,6 +5,7 @@
// connect to mongo database named "bolt"
// uncomment this line to use a local database
+// be sure to re-comment this line when submitting PR
// mongoose.connect('mongodb://localhost/bolt');
mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp');
|
ccf9a08b7ead4552ad22d5a5e07980f1bee3723f | routes/screenshot.js | routes/screenshot.js | const express = require('express');
const router = express.Router();
const puppeteer = require('puppeteer');
router.get('/', function (req, res, next) {
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
const emulation = req.query.emulation || 'mobile';
const defaultWidth = emulation === 'mobile' ? 412 : 1350;
const defaultHeight = emulation === 'mobile' ? 732 : 940;
page.setViewport({
width: req.query.width ? parseInt(req.query.width, 10) : defaultWidth,
height: req.query.heigh ? parseInt(req.query.height, 10) : defaultHeight
});
await page.goto(req.query.url, {timeout: 60000});
const shot = await page.screenshot({});
await browser.close();
res.setHeader('Content-Type', 'image/png');
res.status(200).send(shot);
}).catch(e => {
console.error(e);
res.status(500).send({error: 'Could not take screenshot'});
});
});
module.exports = router;
| const express = require('express');
const router = express.Router();
const puppeteer = require('puppeteer');
router.get('/', function (req, res, next) {
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
const emulation = req.query.emulation || 'mobile';
const defaultWidth = emulation === 'mobile' ? 412 : 1280;
const defaultHeight = emulation === 'mobile' ? 732 : 960;
page.setViewport({
width: req.query.width ? parseInt(req.query.width, 10) : defaultWidth,
height: req.query.heigh ? parseInt(req.query.height, 10) : defaultHeight
});
await page.goto(req.query.url, {timeout: 60000});
const shot = await page.screenshot({});
await browser.close();
res.setHeader('Content-Type', 'image/png');
res.status(200).send(shot);
}).catch(e => {
console.error(e);
res.status(500).send({error: 'Could not take screenshot'});
});
});
module.exports = router;
| Change desktop resolution to 1280x960 | Change desktop resolution to 1280x960 | JavaScript | apache-2.0 | frocher/bnb_probe | ---
+++
@@ -7,8 +7,8 @@
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
const emulation = req.query.emulation || 'mobile';
- const defaultWidth = emulation === 'mobile' ? 412 : 1350;
- const defaultHeight = emulation === 'mobile' ? 732 : 940;
+ const defaultWidth = emulation === 'mobile' ? 412 : 1280;
+ const defaultHeight = emulation === 'mobile' ? 732 : 960;
page.setViewport({
width: req.query.width ? parseInt(req.query.width, 10) : defaultWidth,
height: req.query.heigh ? parseInt(req.query.height, 10) : defaultHeight |
72f17e16ab10d8dce678f8eacf1425d4ca8c9733 | lib/generate.js | lib/generate.js | var fs = require('fs');
var archiver = require('./archiver');
var createServiceFile = require('./service');
var createSpecFile = require('./spec');
var files = require('./files');
function generateServiceFile(root, pkg) {
var serviceFileContents = createServiceFile(pkg);
var serviceFilePath = files.serviceFile(root, pkg);
fs.writeFileSync(serviceFilePath, serviceFileContents);
}
function generateSpecFile(root, pkg, release) {
var specFileContents = createSpecFile(pkg, release);
var specFilePath = files.specFile(root, pkg);
fs.writeFileSync(specFilePath, specFileContents);
}
function addCustomFieldsToPackage(pkg, customName) {
if (customName) {
return Object.assign({}, pkg, { name: customName });
}
return pkg;
}
module.exports = function (root, pkg, release, customName, cb) {
var customPackage = addCustomFieldsToPackage(pkg, customName);
var specsDirectory = files.specsDirectory(root);
var sourcesDirectory = files.sourcesDirectory(root);
var sourcesArchive = files.sourcesArchive(root, customPackage);
fs.mkdirSync(specsDirectory);
fs.mkdirSync(sourcesDirectory);
generateServiceFile(root, customPackage);
generateSpecFile(specsDirectory, customPackage, release);
archiver.compress(root, sourcesArchive, cb);
};
| var _ = require('lodash');
var fs = require('fs');
var archiver = require('./archiver');
var createServiceFile = require('./service');
var createSpecFile = require('./spec');
var files = require('./files');
function generateServiceFile(root, pkg) {
var serviceFileContents = createServiceFile(pkg);
var serviceFilePath = files.serviceFile(root, pkg);
fs.writeFileSync(serviceFilePath, serviceFileContents);
}
function generateSpecFile(root, pkg, release) {
var specFileContents = createSpecFile(pkg, release);
var specFilePath = files.specFile(root, pkg);
fs.writeFileSync(specFilePath, specFileContents);
}
function addCustomFieldsToPackage(pkg, customName) {
if (customName) {
return _.extend({}, pkg, { name: customName });
}
return pkg;
}
module.exports = function (root, pkg, release, customName, cb) {
var customPackage = addCustomFieldsToPackage(pkg, customName);
var specsDirectory = files.specsDirectory(root);
var sourcesDirectory = files.sourcesDirectory(root);
var sourcesArchive = files.sourcesArchive(root, customPackage);
fs.mkdirSync(specsDirectory);
fs.mkdirSync(sourcesDirectory);
generateServiceFile(root, customPackage);
generateSpecFile(specsDirectory, customPackage, release);
archiver.compress(root, sourcesArchive, cb);
};
| Use _.extend instead of Object.assign | Use _.extend instead of Object.assign
| JavaScript | mit | Limess/speculate,Limess/speculate | ---
+++
@@ -1,3 +1,4 @@
+var _ = require('lodash');
var fs = require('fs');
var archiver = require('./archiver');
@@ -21,7 +22,7 @@
function addCustomFieldsToPackage(pkg, customName) {
if (customName) {
- return Object.assign({}, pkg, { name: customName });
+ return _.extend({}, pkg, { name: customName });
}
return pkg; |
a2e2d40c60308104780e1f576fd6be365f463fe8 | routes/index.js | routes/index.js |
/*
* GET home page.
*/
module.exports = function (app, options) {
"use strict";
/*
GET list of routes (index page)
*/
var getIndex = function (req, res) {
// Todo: Add autentication
req.session.userId = "testUserId";
res.render('index', { title: 'Mine turer' });
};
app.get('/', getIndex);
app.get('/index', getIndex);
};
|
/*
* GET home page.
*/
module.exports = function (app, options) {
"use strict";
var connect = options.connect;
/*
GET list of routes (index page)
*/
var getIndex = function (req, res) {
// Todo: Add autentication
req.session.userId = "testUserId";
res.render('index', { title: 'Mine turer' });
};
var getConnect = function (req, res) {
// Check for ?data= query
if (req && req.query && req.query.data) {
try {
var data = client.decryptJSON(req.query.data);
} catch (e) {
// @TODO handle this error propperly
var data = {er_autentisert: false}
}
if (data.er_autentisert === true) {
// User is authenticated
} else {
// User is not authenticated
}
// Initiate DNT Connect signon
} else {
res.redirect(connect.signon('http://localhost:3004/connect'));
}
};
app.get('/', getIndex);
app.get('/index', getIndex);
app.get('/connect', getConnect);
};
| Add initial route provider for DNT Connect signon | Add initial route provider for DNT Connect signon
| JavaScript | mit | Turistforeningen/Turadmin,Turistforeningen/Turadmin,Turistforeningen/Turadmin,Turistforeningen/Turadmin | ---
+++
@@ -3,9 +3,10 @@
* GET home page.
*/
-
module.exports = function (app, options) {
"use strict";
+
+ var connect = options.connect;
/*
GET list of routes (index page)
@@ -16,10 +17,31 @@
res.render('index', { title: 'Mine turer' });
};
+ var getConnect = function (req, res) {
+ // Check for ?data= query
+ if (req && req.query && req.query.data) {
+ try {
+ var data = client.decryptJSON(req.query.data);
+ } catch (e) {
+ // @TODO handle this error propperly
+ var data = {er_autentisert: false}
+ }
+
+ if (data.er_autentisert === true) {
+ // User is authenticated
+ } else {
+ // User is not authenticated
+ }
+
+ // Initiate DNT Connect signon
+ } else {
+ res.redirect(connect.signon('http://localhost:3004/connect'));
+ }
+ };
+
app.get('/', getIndex);
app.get('/index', getIndex);
+ app.get('/connect', getConnect);
};
-
- |
0b094a233b79ef8b5b7e63c65d167e03ee480cff | background.js | background.js | window.addEventListener("load", detect, false);
document.getElementById("webMessengerRecentMessages").addEventListener('DOMNodeInserted', detect, false);
function detect(evt) {
console.log("hello");
//characters for codeblock
var start = "`~ ";
var stop = " ~`";
//main chat only. small chat splits lines into seperate elements...
var chat = document.getElementsByClassName("_38"); //what is the exact meanning of _38???
for (i = 0; i < chat.length; i++) {
text = chat[i].getElementsByTagName("p")[0];
// console.log( text );
words = chat[i].innerText
// console.log(words + "contains lol? : " + words.indexOf( "lol" ) );
var stop_index = words.indexOf(stop);
var start_index = words.indexOf(start);
if (stop_index > start_index && start_index > -1) {
text.className += " code";
text.innerText = words.substr(start_index + 3, stop_index - start_index - 3);
}
}
}
| window.addEventListener("load", monospaceInit, false);
function monospaceInit(evt) {
detect(evt);
document.getElementById(
"webMessengerRecentMessages"
).addEventListener('DOMNodeInserted', detect, false);
}
function detect(evt) {
console.log("hello");
//characters for codeblock
var start = "`~ ";
var stop = " ~`";
//main chat only. small chat splits lines into seperate elements...
var chat = document.getElementsByClassName("_38"); //what is the exact meanning of _38???
for (i = 0; i < chat.length; i++) {
text = chat[i].getElementsByTagName("p")[0];
// console.log( text );
words = chat[i].innerText;
// console.log(words + "contains lol? : " + words.indexOf( "lol" ) );
var stop_index = words.indexOf(stop);
var start_index = words.indexOf(start);
if (stop_index > start_index && start_index > -1) {
text.className += " code";
text.innerText = words.substr(start_index + 3, stop_index - start_index - 3);
}
}
}
| Improve performance: smaller scope, optimization | Improve performance: smaller scope, optimization
Change addEventListener to focus only on the large web chat in Facebook
(id = webMessengerRecentMessages). Also add this event listener only
after the entire page has loaded to prevent a flurry of runs.
Conflicts:
background.js
| JavaScript | mit | tchen01/monospace | ---
+++
@@ -1,5 +1,11 @@
-window.addEventListener("load", detect, false);
-document.getElementById("webMessengerRecentMessages").addEventListener('DOMNodeInserted', detect, false);
+window.addEventListener("load", monospaceInit, false);
+
+function monospaceInit(evt) {
+ detect(evt);
+ document.getElementById(
+ "webMessengerRecentMessages"
+ ).addEventListener('DOMNodeInserted', detect, false);
+}
function detect(evt) {
@@ -13,7 +19,7 @@
for (i = 0; i < chat.length; i++) {
text = chat[i].getElementsByTagName("p")[0];
// console.log( text );
- words = chat[i].innerText
+ words = chat[i].innerText;
// console.log(words + "contains lol? : " + words.indexOf( "lol" ) );
var stop_index = words.indexOf(stop);
var start_index = words.indexOf(start); |
b62469ee1103dd69986570ec314be4c2473639ca | src/app/utils/AffiliationMap.js | src/app/utils/AffiliationMap.js | const map = {
//steemit
ned: 'steemit',
justinw: 'steemit',
elipowell: 'steemit',
vandeberg: 'steemit',
birdinc: 'steemit',
gerbino: 'steemit',
andrarchy: 'steemit',
roadscape: 'steemit',
steemitblog: 'steemit',
steemitdev: 'steemit',
/*
//steem monsters
steemmonsters: 'sm',
'steem.monsters': 'sm',
aggroed: 'sm',
yabapmatt: 'sm',
*/
};
export default map;
| const map = {
//steemit
ned: 'steemit',
justinw: 'steemit',
elipowell: 'steemit',
vandeberg: 'steemit',
gerbino: 'steemit',
andrarchy: 'steemit',
roadscape: 'steemit',
steemitblog: 'steemit',
steemitdev: 'steemit',
/*
//steem monsters
steemmonsters: 'sm',
'steem.monsters': 'sm',
aggroed: 'sm',
yabapmatt: 'sm',
*/
};
export default map;
| Remove birdinc from team list | Remove birdinc from team list | JavaScript | mit | steemit/steemit.com,steemit/steemit.com,TimCliff/steemit.com,TimCliff/steemit.com,TimCliff/steemit.com,steemit/steemit.com | ---
+++
@@ -4,7 +4,6 @@
justinw: 'steemit',
elipowell: 'steemit',
vandeberg: 'steemit',
- birdinc: 'steemit',
gerbino: 'steemit',
andrarchy: 'steemit',
roadscape: 'steemit', |
bad6e9925b177bb4503a3b03d4afc996be128200 | src/components/Weapons/index.js | src/components/Weapons/index.js | import React, { Component } from 'react';
import weapons from './weapons.json';
import './style.css';
class Weapons extends Component {
render() {
return (
<h1>Weapons</h1>
)
}
}
export default Weapons;
| import React, { Component } from 'react';
import weapons from './weapons.json';
import './style.css';
function WeaponsItems() {
const weaponsItems = weapons.map((item) =>
<div className="content-item">
<p>{item.title}</p>
<ul>
{item.items.map((element) => <li>{element}</li>)}
</ul>
</div>
);
return (
<div className="container">{weaponsItems}</div>
);
}
class Weapons extends Component {
render() {
return (
<WeaponsItems/>
)
}
}
export default Weapons;
| Add elements to the menu | wip(weapons): Add elements to the menu
| JavaScript | mit | valsaven/dark-souls-guidebook,valsaven/dark-souls-guidebook | ---
+++
@@ -2,10 +2,24 @@
import weapons from './weapons.json';
import './style.css';
+function WeaponsItems() {
+ const weaponsItems = weapons.map((item) =>
+ <div className="content-item">
+ <p>{item.title}</p>
+ <ul>
+ {item.items.map((element) => <li>{element}</li>)}
+ </ul>
+ </div>
+ );
+ return (
+ <div className="container">{weaponsItems}</div>
+ );
+}
+
class Weapons extends Component {
render() {
return (
- <h1>Weapons</h1>
+ <WeaponsItems/>
)
}
} |
2a885f785488efcaa219e8b9c59d457360564f14 | app/templates/src/gulpfile/tasks/optimize-criticalCss.js | app/templates/src/gulpfile/tasks/optimize-criticalCss.js | /**
* Critical CSS
* @description Generate Inline CSS for the Above the fold optimization
*/
import kc from '../../config.json'
import gulp from 'gulp'
import critical from 'critical'
import yargs from 'yargs'
const args = yargs.argv
const criticalCss = () => {
// Default Build Variable
var generateCritical = args.critical || false;
if(generateCritical) {
kc.cssabove.sources.forEach(function(item) {
return critical.generate({
inline: kc.cssabove.inline,
base: kc.dist.markup,
src: item,
dest: kc.dist.markup + item,
minify: kc.cssabove.minify,
width: kc.cssabove.width,
height: kc.cssabove.height
})
})
}
}
gulp.task('optimize:criticalCss', criticalCss)
module.exports = criticalCss
| /**
* Critical CSS
* @description Generate Inline CSS for the Above the fold optimization
*/
import kc from '../../config.json'
import gulp from 'gulp'
import critical from 'critical'
import yargs from 'yargs'
const args = yargs.argv
const criticalCss = () => {
// Default Build Variable
var generateCritical = args.critical || false;
if(generateCritical) {
kc.cssabove.sources.forEach(function(item) {
return critical.generate({
inline: kc.cssabove.inline,
base: kc.dist.markup,
src: item,
dest: item,
minify: kc.cssabove.minify,
width: kc.cssabove.width,
height: kc.cssabove.height
})
})
}
}
gulp.task('optimize:criticalCss', criticalCss)
module.exports = criticalCss
| Fix Critical CSS Destination Path | Fix Critical CSS Destination Path
| JavaScript | mit | kittn/generator-kittn,kittn/generator-kittn,kittn/generator-kittn,kittn/generator-kittn | ---
+++
@@ -21,7 +21,7 @@
inline: kc.cssabove.inline,
base: kc.dist.markup,
src: item,
- dest: kc.dist.markup + item,
+ dest: item,
minify: kc.cssabove.minify,
width: kc.cssabove.width,
height: kc.cssabove.height |
baebce75ff945946e3803382484c52b73d70ff5e | share/spice/maps/places/maps_places.js | share/spice/maps/places/maps_places.js | // execute dependencies immediately on file parse
nrj("/js/mapbox/mapbox-1.5.2.js",1);
nrc("/js/mapbox/mapbox-1.5.2.css",1);
// the plugin callback by another name
var ddg_spice_maps_places = function (places) {
// sub function where 'places' is always defined
var f2 = function() {
console.log("f2");
// check for the mapbox object
if (!window["L"]) {
console.log("no L");
// wait for it
window.setTimeout(f2, 50);
// could check for a max value here
return;
}
console.log("L found, here we go with places: %o", places);
DDG.maps.renderLocal(places);
};
f2();
};
| // execute dependencies immediately on file parse
nrj("/js/mapbox/mapbox-1.5.2.js",1);
nrc("/js/mapbox/mapbox-1.5.2.css",1);
// the plugin callback by another name
var ddg_spice_maps_places = function (places) {
// sub function where 'places' is always defined
var f2 = function() {
// console.log("f2");
// check for the mapbox object
if (!window["L"]) {
// console.log("no L");
// wait for it
window.setTimeout(f2, 50);
// could check for a max value here
return;
}
// console.log("L found, here we go with places: %o", places);
DDG.maps.renderLocal(places);
};
f2();
};
| Comment out console to merge. | Comment out console to merge.
| JavaScript | apache-2.0 | bdjnk/zeroclickinfo-spice,stennie/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,imwally/zeroclickinfo-spice,levaly/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,imwally/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,stennie/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,lerna/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,sevki/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,P71/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,soleo/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,deserted/zeroclickinfo-spice,ppant/zeroclickinfo-spice,loganom/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,soleo/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,loganom/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,lernae/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,lernae/zeroclickinfo-spice,deserted/zeroclickinfo-spice,soleo/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,P71/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,mayo/zeroclickinfo-spice,lernae/zeroclickinfo-spice,deserted/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,levaly/zeroclickinfo-spice,lerna/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,loganom/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,sevki/zeroclickinfo-spice,levaly/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,stennie/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,P71/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,ppant/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,deserted/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,lernae/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,levaly/zeroclickinfo-spice,levaly/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,lernae/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,mayo/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,mayo/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,P71/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,ppant/zeroclickinfo-spice,lernae/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,ppant/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,echosa/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,sevki/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,soleo/zeroclickinfo-spice,loganom/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,deserted/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,imwally/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,imwally/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,lerna/zeroclickinfo-spice,lerna/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,echosa/zeroclickinfo-spice,echosa/zeroclickinfo-spice,soleo/zeroclickinfo-spice,levaly/zeroclickinfo-spice,imwally/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,lerna/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,mayo/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,stennie/zeroclickinfo-spice,soleo/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,deserted/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,sevki/zeroclickinfo-spice | ---
+++
@@ -9,11 +9,11 @@
// sub function where 'places' is always defined
var f2 = function() {
- console.log("f2");
+// console.log("f2");
// check for the mapbox object
if (!window["L"]) {
- console.log("no L");
+// console.log("no L");
// wait for it
window.setTimeout(f2, 50);
@@ -22,7 +22,7 @@
return;
}
- console.log("L found, here we go with places: %o", places);
+// console.log("L found, here we go with places: %o", places);
DDG.maps.renderLocal(places);
}; |
49af9443e721cf9e68ca3a17eb01d94f7084cd66 | src/coercion/generic.js | src/coercion/generic.js | const getType = require('../typeResolver');
module.exports = {
isCoerced: function(value, typeDescriptor) {
return value instanceof getType(typeDescriptor);
},
coerce(value, typeDescriptor) {
const type = getType(typeDescriptor);
return new type(value);
}
};
| const getType = require('../typeResolver');
module.exports = {
isCoerced(value, typeDescriptor) {
return value instanceof getType(typeDescriptor);
},
coerce(value, typeDescriptor) {
const type = getType(typeDescriptor);
return new type(value);
}
};
| Fix eslint shorthand function assignment | Fix eslint shorthand function assignment
| JavaScript | mit | talyssonoc/structure | ---
+++
@@ -1,7 +1,7 @@
const getType = require('../typeResolver');
module.exports = {
- isCoerced: function(value, typeDescriptor) {
+ isCoerced(value, typeDescriptor) {
return value instanceof getType(typeDescriptor);
},
coerce(value, typeDescriptor) { |
66e535efbbacef95612fbcfe7c469890edc0e239 | client/src/character-animations.js | client/src/character-animations.js | 'use strict';
const
Animation = require('./animation'),
eventBus = require('./event-bus');
const
pacmanNormalColor = 0xffff00,
pacmanFrighteningColor = 0xffffff,
ghostFrightenedColor = 0x5555ff;
class CharacterAnimations {
constructor(gfx) {
this._gfx = gfx;
this._animations = [];
}
start() {
this._handlePause = () => {
for (let animation of this._animations) {
animation.pause();
}
};
eventBus.register('event.pause.begin', this._handlePause);
this._handleResume = () => {
for (let animation of this._animations) {
animation.resume();
}
};
eventBus.register('event.pause.end', this._handleResume);
}
stop() {
eventBus.unregister('event.pause.begin', this._handlePause);
eventBus.unregister('event.pause.end', this._handleResume);
}
createPacManAnimations() {
let animation = new Animation(this._gfx, pacmanNormalColor, pacmanFrighteningColor);
this._animations.push(animation);
return animation;
}
createGhostAnimations(ghostNormalColor) {
let animation = new Animation(this._gfx, ghostNormalColor, ghostFrightenedColor);
this._animations.push(animation);
return animation;
}
}
module.exports = CharacterAnimations; | 'use strict';
const
Animation = require('./animation'),
eventBus = require('./event-bus');
const
pacmanNormalColor = 0xffff00,
pacmanFrighteningColor = 0xffffff,
ghostFrightenedColor = 0x5555ff;
class CharacterAnimations {
constructor(gfx) {
this._gfx = gfx;
this._animations = [];
this._handlePause = () => {
for (let animation of this._animations) {
animation.pause();
}
};
this._handleResume = () => {
for (let animation of this._animations) {
animation.resume();
}
};
}
start() {
eventBus.register('event.pause.begin', this._handlePause);
eventBus.register('event.pause.end', this._handleResume);
}
stop() {
eventBus.unregister('event.pause.begin', this._handlePause);
eventBus.unregister('event.pause.end', this._handleResume);
}
createPacManAnimations() {
let animation = new Animation(this._gfx, pacmanNormalColor, pacmanFrighteningColor);
this._animations.push(animation);
return animation;
}
createGhostAnimations(ghostNormalColor) {
let animation = new Animation(this._gfx, ghostNormalColor, ghostFrightenedColor);
this._animations.push(animation);
return animation;
}
}
module.exports = CharacterAnimations; | Refactor private variable declaration to constructor | Refactor private variable declaration to constructor
| JavaScript | mit | hiddenwaffle/mazing,hiddenwaffle/mazing | ---
+++
@@ -14,21 +14,22 @@
constructor(gfx) {
this._gfx = gfx;
this._animations = [];
- }
- start() {
this._handlePause = () => {
for (let animation of this._animations) {
animation.pause();
}
};
- eventBus.register('event.pause.begin', this._handlePause);
this._handleResume = () => {
for (let animation of this._animations) {
animation.resume();
}
};
+ }
+
+ start() {
+ eventBus.register('event.pause.begin', this._handlePause);
eventBus.register('event.pause.end', this._handleResume);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.