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 |
|---|---|---|---|---|---|---|---|---|---|---|
09f98cd872a914cfeab6687ab009a145d5b4fbd9 | week-7/group_project_solution.js | week-7/group_project_solution.js | // Release 1: Tests to User Stories
/*
As as user, I want to be able to do three things:
(1) I want to be able to take a list of numbers and find their sum.
(2) I want to be able to take a list of numbers and find their mean.
(3) I want to be able to take a list of numbers and find their median.
*/
// Release 2: Pseudocode
/*
1. create an array for your values
2. set the array to a variable (for now I'll call it List)
SUM
1. create a function for sum with List as arguemt
2. create an empty variable set at index 0 (I'll can it Total)
3. iterate through List and collapse each integer value onto index zero of Total
4. run until the full length of List is reached
5. consol log
MEAN
`1. create function for mean with List as argument
2. either repeat steps 2-4 of SUM, or weave sum into MEAN by changing the argument to contain Total and List
3. var mean = Total/List.length
4. consol log
MEDIAN
`1. create a function for median with List as an argument
2. sort list using (a,b)
3. create variable half
4. set to a math object with a floor rounder for List length divided by 2
- var half = Math.floor(list.length/2)
5. if list.length modululous 2 (the division has no remainder) return list[half]
6. else move down the array and return list[half-1]+list[half]/2.0
7. consol log
*/
function sum(list){
var total = 0
for (var i = 0; i < list.length; i++){
total += list[i]
}
return total;
}
function mean(list) {
var total = sum(list);
var mean = total/list.length;
return mean;
}
// driver code
num_array = [1,2,3,4,5,6,7,8,9];
console.log("total is : " + sum(num_array));
console.log("mean is : " + mean(num_array));
| Add code for sum and mean to 7.8 | Add code for sum and mean to 7.8
| JavaScript | mit | SilverFox70/phase-0,SilverFox70/phase-0,SilverFox70/phase-0 | ---
+++
@@ -0,0 +1,65 @@
+// Release 1: Tests to User Stories
+
+/*
+
+As as user, I want to be able to do three things:
+
+(1) I want to be able to take a list of numbers and find their sum.
+
+(2) I want to be able to take a list of numbers and find their mean.
+
+(3) I want to be able to take a list of numbers and find their median.
+
+*/
+
+// Release 2: Pseudocode
+
+/*
+ 1. create an array for your values
+ 2. set the array to a variable (for now I'll call it List)
+
+SUM
+ 1. create a function for sum with List as arguemt
+ 2. create an empty variable set at index 0 (I'll can it Total)
+ 3. iterate through List and collapse each integer value onto index zero of Total
+ 4. run until the full length of List is reached
+ 5. consol log
+
+MEAN
+`1. create function for mean with List as argument
+ 2. either repeat steps 2-4 of SUM, or weave sum into MEAN by changing the argument to contain Total and List
+ 3. var mean = Total/List.length
+ 4. consol log
+
+MEDIAN
+`1. create a function for median with List as an argument
+ 2. sort list using (a,b)
+ 3. create variable half
+ 4. set to a math object with a floor rounder for List length divided by 2
+ - var half = Math.floor(list.length/2)
+ 5. if list.length modululous 2 (the division has no remainder) return list[half]
+ 6. else move down the array and return list[half-1]+list[half]/2.0
+ 7. consol log
+
+
+*/
+
+function sum(list){
+ var total = 0
+ for (var i = 0; i < list.length; i++){
+ total += list[i]
+ }
+ return total;
+}
+
+function mean(list) {
+ var total = sum(list);
+ var mean = total/list.length;
+ return mean;
+}
+
+
+// driver code
+num_array = [1,2,3,4,5,6,7,8,9];
+console.log("total is : " + sum(num_array));
+console.log("mean is : " + mean(num_array)); | |
75b115d9779d2f8826ad9c33bb73be80f02d8fe0 | public/js/controllers/main.js | public/js/controllers/main.js | 'use strict';
angular.module('velo-app').controller('MainCtrl', ['$scope', 'apiService', function ($scope, apiService) {
$scope.initialize = function () {
var map = L.mapbox.map('map', 'mapbox.streets');
var apiRequest = new XMLHttpRequest();
apiRequest.open('GET', '/api/cities/lyon/stations');
apiRequest.addEventListener('load', function () {
var stations = JSON.parse(this.response);
var stationMarkers = [];
stations.forEach(function (station) {
var stationMarker = L.marker(L.latLng(station.position.lat, station.position.lng));
stationMarkers.push(stationMarker);
});
var group = L.featureGroup(stationMarkers);
group.addTo(map);
map.fitBounds(group.getBounds());
});
apiRequest.send();
};
$scope.initialize();
}]);
| 'use strict';
angular.module('velo-app').controller('MainCtrl', ['$scope', 'apiService', function ($scope, apiService) {
$scope.initialize = function () {
var map = L.mapbox.map('map', 'mapbox.streets');
apiService.getStations().then(
function (response) {
var stations = response.data;
var stationMarkers = [];
stations.forEach(function (station) {
var stationMarker = L.marker(L.latLng(station.position.lat, station.position.lng));
stationMarkers.push(stationMarker);
});
var group = L.featureGroup(stationMarkers);
group.addTo(map);
map.fitBounds(group.getBounds());
},
function (error) {
// TODO handle this error properly.
console.error(error);
}
);
};
$scope.initialize();
}]);
| Use `$http` service to fetch stations data. | Use `$http` service to fetch stations data.
| JavaScript | mit | jordanabderrachid/velo-app,jordanabderrachid/velo-app | ---
+++
@@ -4,28 +4,28 @@
$scope.initialize = function () {
var map = L.mapbox.map('map', 'mapbox.streets');
- var apiRequest = new XMLHttpRequest();
+ apiService.getStations().then(
+ function (response) {
+ var stations = response.data;
- apiRequest.open('GET', '/api/cities/lyon/stations');
+ var stationMarkers = [];
- apiRequest.addEventListener('load', function () {
- var stations = JSON.parse(this.response);
+ stations.forEach(function (station) {
+ var stationMarker = L.marker(L.latLng(station.position.lat, station.position.lng));
- var stationMarkers = [];
+ stationMarkers.push(stationMarker);
+ });
- stations.forEach(function (station) {
- var stationMarker = L.marker(L.latLng(station.position.lat, station.position.lng));
-
- stationMarkers.push(stationMarker);
- });
-
- var group = L.featureGroup(stationMarkers);
- group.addTo(map);
-
- map.fitBounds(group.getBounds());
- });
-
- apiRequest.send();
+ var group = L.featureGroup(stationMarkers);
+ group.addTo(map);
+
+ map.fitBounds(group.getBounds());
+ },
+ function (error) {
+ // TODO handle this error properly.
+ console.error(error);
+ }
+ );
};
$scope.initialize(); |
c07cfefbf1093bfa52a206fae1126b29e29fdc21 | .eslintrc.js | .eslintrc.js | module.exports = {
"root": true,
"env": {
"es6": true,
"browser": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"warn",
"tab",
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"always"
],
"no-console": [
"error",
{
allow: ["warn", "error"]
}
],
"no-unused-vars": [
"error",
{
"args": "none"
}
]
}
};
| module.exports = {
"root": true,
"env": {
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"indent": [
"warn",
"tab",
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"always"
],
"no-console": [
"error",
{
allow: ["warn", "error"]
}
],
"no-unused-vars": [
"error",
{
"args": "none"
}
]
}
};
| Revert "Add browser: true to env map to suppress eslint errors for browser globals" | Revert "Add browser: true to env map to suppress eslint errors for browser globals"
This reverts commit b314d1b8a1c2ec7c26600b4e7f39f83083a1b835.
See commit 79167ab0f855beb6942d576735a19d65f0f503e2.
| JavaScript | mit | to2mbn/skinview3d | ---
+++
@@ -1,8 +1,7 @@
module.exports = {
"root": true,
"env": {
- "es6": true,
- "browser": true
+ "es6": true
},
"extends": "eslint:recommended",
"parserOptions": { |
fbfe04e6f6203394a98a2b246ecc721d8d1f5ec0 | src/gm.typeaheadDropdown.js | src/gm.typeaheadDropdown.js | angular.module('gm.typeaheadDropdown', ['ui.bootstrap'])
.directive('typeaheadDropdown', function() {
return {
templateUrl:'templates/typeaheadDropdown.tpl.html',
scope: {
model:'=ngModel',
getOptions:'&options',
config:'=?',
required:'=?ngRequired'
},
replace:true,
controller: ['$scope', '$q', function($scope, $q) {
$scope.config = angular.extend({
modelLabel:"name",
optionLabel:"name"
}, $scope.config);
$q.when($scope.getOptions())
.then(function(options) {
$scope.options = options;
});
$scope.onSelect = function($item, $model, $label) {
angular.extend($scope.model, $item);
$scope.model[$scope.config.modelLabel] = $item[$scope.config.optionLabel];
}
}]
}
}) | angular.module('gm.typeaheadDropdown', ['ui.bootstrap'])
.directive('typeaheadDropdown', function() {
return {
templateUrl:'templates/typeaheadDropdown.tpl.html',
scope: {
model:'=ngModel',
getOptions:'&options',
config:'=?',
required:'=?ngRequired'
},
replace:true,
controller: ['$scope', '$q', function($scope, $q) {
$scope.config = angular.extend({
modelLabel:"name",
optionLabel:"name"
}, $scope.config);
$q.when($scope.getOptions())
.then(function(options) {
$scope.options = options;
});
$scope.onSelect = function($item, $model, $label) {
if(!$scope.model)
$scope.model = {};
angular.extend($scope.model, $item);
$scope.model[$scope.config.modelLabel] = $item[$scope.config.optionLabel];
}
}]
}
}) | Fix bug if model is initially null. | Fix bug if model is initially null.
| JavaScript | mit | spongessuck/gm.typeaheadDropdown,spongessuck/gm.typeaheadDropdown | ---
+++
@@ -21,6 +21,8 @@
});
$scope.onSelect = function($item, $model, $label) {
+ if(!$scope.model)
+ $scope.model = {};
angular.extend($scope.model, $item);
$scope.model[$scope.config.modelLabel] = $item[$scope.config.optionLabel];
} |
5312be998369de295e0c9a4ea88338f8ca0a558b | lib/main.js | lib/main.js | var Watcher = require('large-watcher');
module.exports = function(codebox) {
var events = codebox.events;
codebox.logger.log("Starting the file watcher");
codebox.workspace.path()
.then(function(path) {
var watcher = Watcher(path, 2).start();
// Handle deleted files
watcher.on('deleted', function(files) {
codebox.events.emit('fs:deleted', files);
});
// Handle modified files
watcher.on('modified', function(files) {
codebox.events.emit('fs:modified', files);
});
// Handle created files
watcher.on('created', function(files) {
codebox.events.emit('fs:created', files);
});
// Handler errors
watcher.on('error', function(err) {
codebox.logger.error(err);
});
codebox.logger.log("File watcher started");
});
};
| var Watcher = require('large-watcher');
module.exports = function(codebox) {
var events = codebox.events;
codebox.logger.log("Starting the file watcher");
var watcher = Watcher(codebox.workspace.root(), 2).start();
// Handle deleted files
watcher.on('deleted', function(files) {
codebox.events.emit('fs:deleted', files);
});
// Handle modified files
watcher.on('modified', function(files) {
codebox.events.emit('fs:modified', files);
});
// Handle created files
watcher.on('created', function(files) {
codebox.events.emit('fs:created', files);
});
// Handler errors
watcher.on('error', function(err) {
codebox.logger.error(err);
});
codebox.logger.log("File watcher started");
};
| Use workspace.root() instead of workspace.path() | Use workspace.root() instead of workspace.path()
| JavaScript | apache-2.0 | etopian/codebox-package-watcher,CodeboxIDE/package-watcher | ---
+++
@@ -6,31 +6,27 @@
codebox.logger.log("Starting the file watcher");
- codebox.workspace.path()
- .then(function(path) {
- var watcher = Watcher(path, 2).start();
+ var watcher = Watcher(codebox.workspace.root(), 2).start();
- // Handle deleted files
- watcher.on('deleted', function(files) {
- codebox.events.emit('fs:deleted', files);
- });
-
- // Handle modified files
- watcher.on('modified', function(files) {
- codebox.events.emit('fs:modified', files);
- });
-
- // Handle created files
- watcher.on('created', function(files) {
- codebox.events.emit('fs:created', files);
- });
-
- // Handler errors
- watcher.on('error', function(err) {
- codebox.logger.error(err);
- });
-
- codebox.logger.log("File watcher started");
+ // Handle deleted files
+ watcher.on('deleted', function(files) {
+ codebox.events.emit('fs:deleted', files);
});
+ // Handle modified files
+ watcher.on('modified', function(files) {
+ codebox.events.emit('fs:modified', files);
+ });
+
+ // Handle created files
+ watcher.on('created', function(files) {
+ codebox.events.emit('fs:created', files);
+ });
+
+ // Handler errors
+ watcher.on('error', function(err) {
+ codebox.logger.error(err);
+ });
+
+ codebox.logger.log("File watcher started");
}; |
ff70ff08b9a1f3c5f5c3bcd3966ff00aa91b8910 | routes/index.js | routes/index.js | var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: "Dito's laboratory" });
});
module.exports = router;
| var express = require('express');
var router = express.Router();
router.post('/postscore', function(req, res, next) {
console.log("posting");
console.log(req);
if (next) next();
});
router.get('/postscore', function(req, res, next) {
console.log("getting");
console.log(req);
if (next) next();
});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: "Dito's laboratory" });
});
module.exports = router;
| Test commit for Unity WWW | Test commit for Unity WWW
| JavaScript | mit | DominikDitoIvosevic/dito.ninja,DominikDitoIvosevic/dito.ninja | ---
+++
@@ -1,9 +1,22 @@
var express = require('express');
var router = express.Router();
+
+router.post('/postscore', function(req, res, next) {
+ console.log("posting");
+ console.log(req);
+ if (next) next();
+});
+
+router.get('/postscore', function(req, res, next) {
+ console.log("getting");
+ console.log(req);
+ if (next) next();
+});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: "Dito's laboratory" });
});
+
module.exports = router; |
ce3a219b04f14d3629bd588ac8a60f004c6b61fd | routes/index.js | routes/index.js | /*
* Controllers
*/
var homeController = require('../controllers/home_controller');
var authController = require('../controllers/authentication_controller');
/*
* Routes
*/
module.exports = function(app, passport){
var authenticate = authController.setUp(authController, passport);
app.get('/', homeController.index);
app.post('/login', authenticate);
app.get('/logout',authController.logout);
};
| /*
* Controllers
*/
var homeController = require('../controllers/home_controller');
var pivotalController = require('../controllers/pivotal_controller');
var authController = require('../controllers/authentication_controller');
/*
* Routes
*/
module.exports = function(app, passport){
var authenticate = authController.setUp(authController, passport);
app.get('/', homeController.index);
app.post('/login', authenticate);
app.get('/logout', authController.logout);
app.get('/api/v1/projects', pivotalController.projects);
};
| Build route for projects api | Build route for projects api
| JavaScript | mit | tangosource/pokerestimate,tangosource/pokerestimate | ---
+++
@@ -2,8 +2,9 @@
* Controllers
*/
-var homeController = require('../controllers/home_controller');
-var authController = require('../controllers/authentication_controller');
+var homeController = require('../controllers/home_controller');
+var pivotalController = require('../controllers/pivotal_controller');
+var authController = require('../controllers/authentication_controller');
/*
* Routes
@@ -16,6 +17,7 @@
app.get('/', homeController.index);
app.post('/login', authenticate);
- app.get('/logout',authController.logout);
+ app.get('/logout', authController.logout);
+ app.get('/api/v1/projects', pivotalController.projects);
}; |
cc5a2f0accc2e878e25066c76189e96f62208bf8 | src/lib/guesstimator/samplers/DistributionBeta.js | src/lib/guesstimator/samplers/DistributionBeta.js | import math from 'mathjs';
import {Sample} from './Sampler.js'
import {jStat} from 'jstat'
export var Sampler = {
sample({hits, total}, n) {
// This treats your entry as a prior, and assumes you are 2 times more confident than
// a raw beta would be. This gives your distribution more of a peak for small numbers.
return { values: Sample(n, () => jStat.beta.sample(2*hits, 2*(total-hits))) }
}
}
| import {simulate} from './Simulator.js'
export var Sampler = {
sample({hits, total}, n) {
// This treats your entry as a prior, and assumes you are 2 times more confident than
// a raw beta would be. This gives your distribution more of a peak for small numbers.
return simulate(`beta(${2*hits},${2*(total-hits)})`, [], n)
}
}
| Fix beta with new sampling logic. | Fix beta with new sampling logic.
| JavaScript | mit | getguesstimate/guesstimate-app | ---
+++
@@ -1,12 +1,10 @@
-import math from 'mathjs';
-import {Sample} from './Sampler.js'
-import {jStat} from 'jstat'
+import {simulate} from './Simulator.js'
export var Sampler = {
sample({hits, total}, n) {
// This treats your entry as a prior, and assumes you are 2 times more confident than
// a raw beta would be. This gives your distribution more of a peak for small numbers.
- return { values: Sample(n, () => jStat.beta.sample(2*hits, 2*(total-hits))) }
+ return simulate(`beta(${2*hits},${2*(total-hits)})`, [], n)
}
}
|
2251da40ce14576b49f05a7de92cf278bf300b1e | src/config/routes.js | src/config/routes.js | // This file defines all routes and function handling these routes.
// All routes are accessible using GET and POST methods.
const routes = {
'/item': require('../controllers/items/byId.js'),
'/item/:id': require('../controllers/items/byId.js'),
'/items': require('../controllers/items/byIds.js'),
'/items/all': require('../controllers/items/all.js'),
'/items/all-prices': require('../controllers/items/allPrices.js'),
'/items/all-values': require('../controllers/items/allValues.js'),
'/items/categories': require('../controllers/items/categories.js'),
'/items/autocomplete': require('../controllers/items/autocomplete.js'),
'/items/by-name': require('../controllers/items/byName.js'),
'/items/by-skin': require('../controllers/items/bySkin.js'),
'/items/query': require('../controllers/items/query.js'),
'/items/:ids': require('../controllers/items/byIds.js'),
'/skins/resolve': require('../controllers/skins/resolve.js'),
'/skins/prices': require('../controllers/skins/prices.js'),
'/recipe/nested/:id': require('../controllers/recipes/nested.js'),
'/gems/history': require('../controllers/gems/history.js')
}
module.exports = routes
| // This file defines all routes and function handling these routes.
// All routes are accessible using GET and POST methods.
const routes = {
'/item': require('../controllers/items/byId.js'),
'/item/:id': require('../controllers/items/byId.js'),
'/items': require('../controllers/items/byIds.js'),
'/items/all': require('../controllers/items/all.js'),
'/items/all-prices': require('../controllers/items/allPrices.js'),
'/items/all-values': require('../controllers/items/allValues.js'),
'/items/categories': require('../controllers/items/categories.js'),
'/items/autocomplete': require('../controllers/items/autocomplete.js'),
'/items/by-name': require('../controllers/items/byName.js'),
'/items/by-skin': require('../controllers/items/bySkin.js'),
'/items/query': require('../controllers/items/query.js'),
'/items/:ids': require('../controllers/items/byIds.js'),
'/skins/resolve': require('../controllers/skins/resolve.js'),
'/skins/prices': require('../controllers/skins/prices.js'),
'/recipe/nested/:ids': require('../controllers/recipes/nested.js'),
'/gems/history': require('../controllers/gems/history.js')
}
module.exports = routes
| Fix route binding for nested recipes | Fix route binding for nested recipes | JavaScript | agpl-3.0 | gw2efficiency/gw2-api.com | ---
+++
@@ -16,7 +16,7 @@
'/items/:ids': require('../controllers/items/byIds.js'),
'/skins/resolve': require('../controllers/skins/resolve.js'),
'/skins/prices': require('../controllers/skins/prices.js'),
- '/recipe/nested/:id': require('../controllers/recipes/nested.js'),
+ '/recipe/nested/:ids': require('../controllers/recipes/nested.js'),
'/gems/history': require('../controllers/gems/history.js')
}
|
edd5d3098b12e6f91c89ffc5dc234b5026f52f51 | lib/parsers/babylon.js | lib/parsers/babylon.js | "use strict";
const babylon = require("babylon");
exports.options = {
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
plugins: [
"*", "flow", "jsx",
// The "*" glob no longer seems to include the following plugins:
"objectRestSpread",
"classProperties",
"exportExtensions",
"dynamicImport",
// Other experimental plugins that we could enable:
// https://github.com/babel/babylon#plugins
],
sourceType: "module",
strictMode: false
};
function parse(code) {
return babylon.parse(code, exports.options);
}
exports.parse = parse;
| "use strict";
const babylon = require("babylon");
exports.options = {
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
plugins: [
"*", "flow", "jsx",
// The "*" glob no longer seems to include the following plugins:
"asyncGenerators",
"classProperties",
"decorators",
"doExpressions",
"dynamicImport",
"exportExtensions",
"functionBind",
"functionSent",
"objectRestSpread",
// Other experimental plugins that we could enable:
// https://github.com/babel/babylon#plugins
],
sourceType: "module",
strictMode: false
};
function parse(code) {
return babylon.parse(code, exports.options);
}
exports.parse = parse;
| Enable the rest of Babylon's experimental plugins, for max tolerance. | Enable the rest of Babylon's experimental plugins, for max tolerance.
| JavaScript | mit | benjamn/reify,benjamn/reify | ---
+++
@@ -8,10 +8,15 @@
plugins: [
"*", "flow", "jsx",
// The "*" glob no longer seems to include the following plugins:
+ "asyncGenerators",
+ "classProperties",
+ "decorators",
+ "doExpressions",
+ "dynamicImport",
+ "exportExtensions",
+ "functionBind",
+ "functionSent",
"objectRestSpread",
- "classProperties",
- "exportExtensions",
- "dynamicImport",
// Other experimental plugins that we could enable:
// https://github.com/babel/babylon#plugins
], |
51bcf356fc5459e9427dc46eb7abddc17f14f7e0 | src/commands/find.js | src/commands/find.js | import moment from 'moment'
import textTable from 'text-table'
const find = (apiWrapper) => (search, options) => {
const {
startdate,
enddate,
businessunitids
} = options
return new Promise((resolve, reject) => {
apiWrapper.getActivities({
startdate,
enddate,
businessunitids
})
.then((response) => {
const searchParam = search.toLowerCase()
const activities = response.activities.activity
const foundActivities = activities.filter((activity) => {
const name = activity.product.name.toLowerCase()
const bookableSlots = parseInt(activity.bookableslots, 10)
return name.indexOf(searchParam) !== -1 && bookableSlots > 0
})
.map((activity) => {
const startTime = activity.start.timepoint.datetime
const dayOfWeek = moment(startTime).format('dddd')
const time = moment(startTime).format('HH:mm')
const formattedStartTime = `${dayOfWeek} ${time}`
return [
activity.id,
formattedStartTime,
activity.product.name,
activity.bookableslots
]
})
if (foundActivities.length === 0) {
resolve('No activities found')
}
const table = textTable(foundActivities)
const spacedTable = `\`\`\`${table.toString()}\`\`\``
resolve(spacedTable)
})
})
}
export default find
| import moment from 'moment'
import textTable from 'text-table'
const find = (apiWrapper) => (search, options) => {
const {
startdate,
enddate,
businessunitids
} = options
return new Promise((resolve, reject) => {
apiWrapper.getActivities({
startdate,
enddate,
businessunitids
})
.then((response) => {
const searchParam = search.toLowerCase()
const activities = response.activities.activity
const foundActivities = activities.filter((activity) => {
const name = activity.product.name.toLowerCase()
const bookableSlots = parseInt(activity.bookableslots, 10)
return name.indexOf(searchParam) !== -1 && bookableSlots > 0
})
.map((activity) => {
const startTime = activity.start.timepoint.datetime
const dayOfWeek = moment(startTime).format('dddd')
const time = moment(startTime).format('HH:mm')
return [
activity.id,
dayOfWeek,
time,
activity.product.name,
activity.bookableslots
]
})
if (foundActivities.length === 0) {
resolve('No activities found')
}
const table = textTable(foundActivities)
const spacedTable = `\`\`\`${table.toString()}\`\`\``
resolve(spacedTable)
})
})
}
export default find
| Put time and day in separate columns | Put time and day in separate columns
| JavaScript | mit | gish/friskis-slack-booking | ---
+++
@@ -26,11 +26,11 @@
const startTime = activity.start.timepoint.datetime
const dayOfWeek = moment(startTime).format('dddd')
const time = moment(startTime).format('HH:mm')
- const formattedStartTime = `${dayOfWeek} ${time}`
return [
activity.id,
- formattedStartTime,
+ dayOfWeek,
+ time,
activity.product.name,
activity.bookableslots
] |
3421372936284eb4e143524e8ce2fcad9cc0d2ac | lib/sheets/comments.js | lib/sheets/comments.js | var utils = require('../utils/httpUtils.js');
var _ = require('underscore');
var constants = require('../utils/constants.js');
exports.create = function(options) {
var optionsToSend = {
accessToken : options.accessToken
};
var getComment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions);
return utils.get(_.extend(optionsToSend, getOptions), callback);
};
var deleteComment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions);
return utils.delete(_.extend(optionsToSend, getOptions), callback);
};
var addCommentUrlAttachment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions) + '/attachments';
return utils.post(_.extend(optionsToSend, getOptions), callback);
};
var addCommentFileAttachment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions) + '/attachments';
return utils.postFile(_.extend(optionsToSend, getOptions), callback);
};
var editComment = function(putOptions, callback) {
optionsToSend.url = buildUrl(putOptions);
return utils.put(_.extend(optionsToSend, putOptions), callback);
};
var buildUrl = function(urlOptions) {
return options.apiUrls.sheets + urlOptions.sheetId + '/comments/' + (urlOptions.commentId || '');
};
return {
getComment : getComment,
deleteComment : deleteComment,
addCommentUrlAttachment : addCommentUrlAttachment,
addCommentFileAttachment : addCommentFileAttachment,
editComment : editComment
};
};
| var utils = require('../utils/httpUtils.js');
var _ = require('underscore');
var constants = require('../utils/constants.js');
exports.create = function(options) {
var optionsToSend = {
accessToken : options.accessToken
};
var getComment = function(getOptions, callback) {
optionsToSend.url = buildUrl(getOptions);
return utils.get(_.extend(optionsToSend, getOptions), callback);
};
var deleteComment = function(deleteOptions, callback) {
optionsToSend.url = buildUrl(deleteOptions);
return utils.delete(_.extend(optionsToSend, deleteOptions), callback);
};
var addCommentUrlAttachment = function(postOptions, callback) {
optionsToSend.url = buildUrl(postOptions) + '/attachments';
return utils.post(_.extend(optionsToSend, postOptions), callback);
};
var addCommentFileAttachment = function(postOptions, callback) {
optionsToSend.url = buildUrl(postOptions) + '/attachments';
return utils.postFile(_.extend(optionsToSend, postOptions), callback);
};
var editComment = function(putOptions, callback) {
optionsToSend.url = buildUrl(putOptions);
return utils.put(_.extend(optionsToSend, putOptions), callback);
};
var buildUrl = function(urlOptions) {
return options.apiUrls.sheets + urlOptions.sheetId + '/comments/' + (urlOptions.commentId || '');
};
return {
getComment : getComment,
deleteComment : deleteComment,
addCommentUrlAttachment : addCommentUrlAttachment,
addCommentFileAttachment : addCommentFileAttachment,
editComment : editComment
};
};
| Fix options param names to match their requests. | Fix options param names to match their requests. | JavaScript | apache-2.0 | smartsheet-platform/smartsheet-javascript-sdk | ---
+++
@@ -12,19 +12,19 @@
return utils.get(_.extend(optionsToSend, getOptions), callback);
};
- var deleteComment = function(getOptions, callback) {
- optionsToSend.url = buildUrl(getOptions);
- return utils.delete(_.extend(optionsToSend, getOptions), callback);
+ var deleteComment = function(deleteOptions, callback) {
+ optionsToSend.url = buildUrl(deleteOptions);
+ return utils.delete(_.extend(optionsToSend, deleteOptions), callback);
};
- var addCommentUrlAttachment = function(getOptions, callback) {
- optionsToSend.url = buildUrl(getOptions) + '/attachments';
- return utils.post(_.extend(optionsToSend, getOptions), callback);
+ var addCommentUrlAttachment = function(postOptions, callback) {
+ optionsToSend.url = buildUrl(postOptions) + '/attachments';
+ return utils.post(_.extend(optionsToSend, postOptions), callback);
};
- var addCommentFileAttachment = function(getOptions, callback) {
- optionsToSend.url = buildUrl(getOptions) + '/attachments';
- return utils.postFile(_.extend(optionsToSend, getOptions), callback);
+ var addCommentFileAttachment = function(postOptions, callback) {
+ optionsToSend.url = buildUrl(postOptions) + '/attachments';
+ return utils.postFile(_.extend(optionsToSend, postOptions), callback);
};
var editComment = function(putOptions, callback) { |
87cf5c61ea9a023d125b59688bd687d1d465d8c3 | src/sagas.js | src/sagas.js | /** @babel */
/** global atom */
import { delay } from 'redux-saga'
import { put, call, select, take, fork } from 'redux-saga/effects'
import { run } from 'node-jq'
import { ACTIONS as ACTION } from './constants'
const ONE_SEC = 1000
// const jq = (filter) => {
// return (dispatch, getState) => {
// const { activePaneItem } = getState()
// return run(filter, activePaneItem.getText(), { input: 'string' }).then(
// output => dispatch(jqFilterSuccess(output)),
// error => dispatch(jqFilterFailure(error))
// )
// }
// }
function * jq () {
while (true) {
const action = yield take(ACTION.JQ_FILTER_REQUEST)
const activePaneItem = yield select(state => state.activePaneItem)
const { payload: { filter } } = action
const filePath = activePaneItem.buffer.file.path
try {
const result = yield run(filter, filePath)
yield call(ACTION.OPEN_MODAL, result)
} catch (e) {
yield call(ACTION.JQ_FILTER_FAILURE)
}
yield call(delay, ONE_SEC)
}
}
export default function * sagas () {
yield [
fork(jq)
]
}
| /** @babel */
/** global atom */
import { delay } from 'redux-saga'
import { put, call, select, take, fork } from 'redux-saga/effects'
import { run } from 'node-jq'
import { ACTIONS as ACTION } from './constants'
const ONE_SEC = 1000
function * jq () {
while (true) {
const action = yield take(ACTION.JQ_FILTER_REQUEST)
const activePaneItem = yield select(state => state.activePaneItem)
const { payload: { filter } } = action
const filePath = activePaneItem.buffer.file.path
try {
const result = yield run(filter, filePath)
yield call(ACTION.OPEN_MODAL, result)
} catch (e) {
yield call(ACTION.JQ_FILTER_FAILURE)
}
yield call(delay, ONE_SEC)
}
}
export default function * sagas () {
yield [
fork(jq)
]
}
| Remove commented thunk code in saga | Remove commented thunk code in saga
| JavaScript | mit | sanack/atom-jq | ---
+++
@@ -7,16 +7,6 @@
import { ACTIONS as ACTION } from './constants'
const ONE_SEC = 1000
-
-// const jq = (filter) => {
-// return (dispatch, getState) => {
-// const { activePaneItem } = getState()
-// return run(filter, activePaneItem.getText(), { input: 'string' }).then(
-// output => dispatch(jqFilterSuccess(output)),
-// error => dispatch(jqFilterFailure(error))
-// )
-// }
-// }
function * jq () {
while (true) { |
e1490ca31e8b47ebcf0c8480d6fbc758a81abe2e | packages/truffle-events/EventManager.js | packages/truffle-events/EventManager.js | const SubscriberAggregator = require("./SubscriberAggregator");
const Emittery = require("emittery");
class EventManager {
constructor(eventManagerOptions) {
const { logger, muteReporters, globalConfig } = eventManagerOptions;
// Keep a reference to these so it can be cloned
// if necessary in truffle-config
this.initializationOptions = eventManagerOptions;
this.emitter = new Emittery();
const initializationOptions = {
emitter: this.emitter,
globalConfig,
logger,
muteReporters
};
this.initializeSubscribers(initializationOptions);
}
emit(event, data) {
this.emitter.emit(event, data);
}
initializeSubscribers(initializationOptions) {
new SubscriberAggregator(initializationOptions);
}
}
module.exports = EventManager;
| const SubscriberAggregator = require("./SubscriberAggregator");
const Emittery = require("emittery");
class EventManager {
constructor(eventManagerOptions) {
const { logger, muteReporters, globalConfig } = eventManagerOptions;
// Keep a reference to these so it can be cloned
// if necessary in truffle-config
this.initializationOptions = eventManagerOptions;
this.emitter = new Emittery();
const initializationOptions = {
emitter: this.emitter,
globalConfig,
logger,
muteReporters
};
this.initializeSubscribers(initializationOptions);
}
emit(event, data) {
return this.emitter.emit(event, data);
}
initializeSubscribers(initializationOptions) {
new SubscriberAggregator(initializationOptions);
}
}
module.exports = EventManager;
| Return the result of calling emit on emittery | Return the result of calling emit on emittery
| JavaScript | mit | ConsenSys/truffle | ---
+++
@@ -20,7 +20,7 @@
}
emit(event, data) {
- this.emitter.emit(event, data);
+ return this.emitter.emit(event, data);
}
initializeSubscribers(initializationOptions) { |
e88e85110242e88aefa3e02d36737c09205c1253 | lib/args.js | lib/args.js | "use strict";
/**
* Handle arguments for backwards compatibility
* @param {Object} args
* @returns {{config: {}, cb: *}}
*/
module.exports = function (args) {
var config = {};
var cb;
switch (args.length) {
case 1 :
if (isFilesArg(args[0])) {
config.files = args[0];
} else if (typeof args[0] === "function") {
cb = args[0];
} else {
config = args[0];
}
break;
case 2 :
// if second is a function, first MUST be config
if (typeof args[1] === "function") {
config = args[0] || {};
cb = args[1];
} else {
config = args[1] || {};
if (!config.files) {
config.files = args[0];
}
}
break;
case 3 :
config = args[1] || {};
if (!config.files) {
config.files = args[0];
}
cb = args[2];
}
function isFilesArg (arg) {
return Array.isArray(arg) || typeof arg === "string";
}
return {
config: config,
cb: cb
};
};
| "use strict";
function isFilesArg (arg) {
return Array.isArray(arg) || typeof arg === "string";
}
/**
* Handle arguments for backwards compatibility
* @param {Object} args
* @returns {{config: {}, cb: *}}
*/
module.exports = function (args) {
var config = {};
var cb;
switch (args.length) {
case 1 :
if (isFilesArg(args[0])) {
config.files = args[0];
} else if (typeof args[0] === "function") {
cb = args[0];
} else {
config = args[0];
}
break;
case 2 :
// if second is a function, first MUST be config
if (typeof args[1] === "function") {
config = args[0] || {};
cb = args[1];
} else {
config = args[1] || {};
if (!config.files) {
config.files = args[0];
}
}
break;
case 3 :
config = args[1] || {};
if (!config.files) {
config.files = args[0];
}
cb = args[2];
}
return {
config: config,
cb: cb
};
};
| Move function out of the scope | Move function out of the scope
| JavaScript | apache-2.0 | chengky/browser-sync,nothiphop/browser-sync,pmq20/browser-sync,chengky/browser-sync,portned/browser-sync,schmod/browser-sync,schmod/browser-sync,pepelsbey/browser-sync,BrowserSync/browser-sync,pepelsbey/browser-sync,zhelezko/browser-sync,beni55/browser-sync,lookfirst/browser-sync,guiquanz/browser-sync,BrowserSync/browser-sync,zhelezko/browser-sync,Teino1978-Corp/Teino1978-Corp-browser-sync,felixdae/browser-sync,Iced-Tea/browser-sync,stevemao/browser-sync,d-g-h/browser-sync,guiquanz/browser-sync,markcatley/browser-sync,portned/browser-sync,Iced-Tea/browser-sync,felixdae/browser-sync,Plou/browser-sync,shelsonjava/browser-sync,mcanthony/browser-sync,beni55/browser-sync,BrowserSync/browser-sync,nitinsurana/browser-sync,harmoney-nikr/browser-sync,stevemao/browser-sync,pmq20/browser-sync,syarul/browser-sync,michaelgilley/browser-sync,cnbin/browser-sync,naoyak/browser-sync,naoyak/browser-sync,syarul/browser-sync,Plou/browser-sync,michaelgilley/browser-sync,shelsonjava/browser-sync,BrowserSync/browser-sync,nothiphop/browser-sync,EdwonLim/browser-sync,nitinsurana/browser-sync,EdwonLim/browser-sync,d-g-h/browser-sync,Teino1978-Corp/Teino1978-Corp-browser-sync,harmoney-nikr/browser-sync,mnquintana/browser-sync,mcanthony/browser-sync | ---
+++
@@ -1,4 +1,8 @@
"use strict";
+
+function isFilesArg (arg) {
+ return Array.isArray(arg) || typeof arg === "string";
+}
/**
* Handle arguments for backwards compatibility
@@ -60,10 +64,6 @@
cb = args[2];
}
- function isFilesArg (arg) {
- return Array.isArray(arg) || typeof arg === "string";
- }
-
return {
config: config,
cb: cb |
51dc7616671e8bcfcab0c8067fc3d6364debdfa9 | lib/init.js | lib/init.js | var copy = require("./copy");
var path = require("path");
var temp = require("temp").track();
var Config = require("./config");
var Init = function(destination, callback) {
var example_directory = path.resolve(path.join(__dirname, "..", "example"));
copy(example_directory, destination, callback);
}
Init.sandbox = function(callback) {
var self = this;
temp.mkdir("truffle-sandbox-", function(err, dirPath) {
if (err) return callback(err);
Init(dirPath, function(err) {
if (err) return callback(err);
var config = Config.load(path.join(dirPath, "truffle.js"));
callback(null, config);
});
});
};
module.exports = Init;
| var copy = require("./copy");
var path = require("path");
var temp = require("temp").track();
var Config = require("./config");
var Init = function(destination, callback) {
var example_directory = path.resolve(path.join(__dirname, "..", "example"));
copy(example_directory, destination, callback);
}
Init.sandbox = function(extended_config, callback) {
var self = this;
extended_config = extended_config || {}
temp.mkdir("truffle-sandbox-", function(err, dirPath) {
if (err) return callback(err);
Init(dirPath, function(err) {
if (err) return callback(err);
var config = Config.load(path.join(dirPath, "truffle.js"), extended_config);
callback(null, config);
});
});
};
module.exports = Init;
| Make Init.sandbox() take an input configuration. | Make Init.sandbox() take an input configuration.
| JavaScript | mit | DigixGlobal/truffle,prashantpawar/truffle | ---
+++
@@ -8,15 +8,17 @@
copy(example_directory, destination, callback);
}
-Init.sandbox = function(callback) {
+Init.sandbox = function(extended_config, callback) {
var self = this;
+ extended_config = extended_config || {}
+
temp.mkdir("truffle-sandbox-", function(err, dirPath) {
if (err) return callback(err);
Init(dirPath, function(err) {
if (err) return callback(err);
- var config = Config.load(path.join(dirPath, "truffle.js"));
+ var config = Config.load(path.join(dirPath, "truffle.js"), extended_config);
callback(null, config);
});
}); |
cd6a769dc0c6343047632179c2e6c34ea50768e7 | lib/util.js | lib/util.js | 'use strict';
/* global -Promise */
var Promise = require('bluebird');
var _ = require('underscore');
var glob = require('glob');
var getFileList = function getFileList (files) {
var fileList = [];
return new Promise(function (resolve, reject) {
if (_.isString(files)) {
glob(files, function (err, files) {
if (err) {
reject(err);
}
fileList = files;
resolve(fileList);
});
} else if (_.isArray(files)) {
// TODO
} else {
throw new Error('You can only provide a String or an Array of filenames');
}
});
};
var getSupportedBrowserList = function getUnsupportedBrowserList (browsers) {
return {
ie: ['6']
};
};
module.exports = {
getFileList: getFileList,
getSupportedBrowserList: getSupportedBrowserList
};
| 'use strict';
/* global -Promise */
var Promise = require('bluebird');
var _ = require('underscore');
var glob = Promise.promisify(require("glob"));;
var getFileList = function getFileList (files) {
if (_.isString(files)) {
return glob(files);
} else if (_.isArray(files)) {
var fileSubLists = _.map(files, function (fileSubList) {
return glob(fileSubList);
});
return Promise.reduce(fileSubLists, function(fileList, subList) {
return fileList.concat(subList);
}, []);
}
throw new Error('You can only provide a String or an Array of filenames');
};
var getSupportedBrowserList = function getUnsupportedBrowserList (browsers) {
return {
ie: ['6']
};
};
module.exports = {
getFileList: getFileList,
getSupportedBrowserList: getSupportedBrowserList
};
| Use Promisify and add ability to get String/Array of globs in api | Use Promisify and add ability to get String/Array of globs in api
| JavaScript | mit | caniuse-js/caniuse-js | ---
+++
@@ -2,27 +2,24 @@
/* global -Promise */
var Promise = require('bluebird');
+
var _ = require('underscore');
-var glob = require('glob');
+var glob = Promise.promisify(require("glob"));;
var getFileList = function getFileList (files) {
- var fileList = [];
+ if (_.isString(files)) {
+ return glob(files);
+ } else if (_.isArray(files)) {
+ var fileSubLists = _.map(files, function (fileSubList) {
+ return glob(fileSubList);
+ });
- return new Promise(function (resolve, reject) {
- if (_.isString(files)) {
- glob(files, function (err, files) {
- if (err) {
- reject(err);
- }
- fileList = files;
- resolve(fileList);
- });
- } else if (_.isArray(files)) {
- // TODO
- } else {
- throw new Error('You can only provide a String or an Array of filenames');
- }
- });
+ return Promise.reduce(fileSubLists, function(fileList, subList) {
+ return fileList.concat(subList);
+ }, []);
+ }
+
+ throw new Error('You can only provide a String or an Array of filenames');
};
var getSupportedBrowserList = function getUnsupportedBrowserList (browsers) { |
863071cc834c0c9e3b17d668c37f4886da5bd932 | test/specs/component/TextSpec.js | test/specs/component/TextSpec.js | import ReactDOM from 'react-dom';
import React from 'react';
import { shallow, render } from 'enzyme';
import { expect } from 'chai';
import { Text } from 'recharts';
describe('<Text />', () => {
it('Does not wrap long text if enough width', () => {
const wrapper = shallow(
<Text width={144}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(1);
});
it('Wraps long text if not enough width', () => {
const wrapper = shallow(
<Text width={143}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(2);
});
it('Wraps long text if styled and not enough room', () => {
const wrapper = shallow(
<Text width={144} style={{ fontWeight: 900 }}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(2);
});
it('Does not perform word length calculation if width or fit props not set', () => {
const wrapper = shallow(
<Text>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(1);
expect(wrapper.instance().state.wordsByLines[0].width).to.equal(undefined);
});
});
| import ReactDOM from 'react-dom';
import React from 'react';
import { shallow, render } from 'enzyme';
import { expect } from 'chai';
import { Text } from 'recharts';
describe('<Text />', () => {
it('Does not wrap long text if enough width', () => {
const wrapper = shallow(
<Text width={200}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(1);
});
it('Wraps long text if not enough width', () => {
const wrapper = shallow(
<Text width={100}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(2);
});
it('Wraps long text if styled and not enough room', () => {
const wrapper = shallow(
<Text width={200} style={{ fontSize: '2em' }}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(2);
});
it('Does not perform word length calculation if width or fit props not set', () => {
const wrapper = shallow(
<Text>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(1);
expect(wrapper.instance().state.wordsByLines[0].width).to.equal(undefined);
});
});
| Update <Text> tests so they are not as particular about browser differences | Update <Text> tests so they are not as particular about browser differences
| JavaScript | mit | recharts/recharts,recharts/recharts,sdoomz/recharts,sdoomz/recharts,thoqbk/recharts,recharts/recharts,recharts/recharts,thoqbk/recharts,sdoomz/recharts,thoqbk/recharts | ---
+++
@@ -7,7 +7,7 @@
describe('<Text />', () => {
it('Does not wrap long text if enough width', () => {
const wrapper = shallow(
- <Text width={144}>This is really long text</Text>
+ <Text width={200}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(1);
@@ -15,7 +15,7 @@
it('Wraps long text if not enough width', () => {
const wrapper = shallow(
- <Text width={143}>This is really long text</Text>
+ <Text width={100}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(2);
@@ -23,7 +23,7 @@
it('Wraps long text if styled and not enough room', () => {
const wrapper = shallow(
- <Text width={144} style={{ fontWeight: 900 }}>This is really long text</Text>
+ <Text width={200} style={{ fontSize: '2em' }}>This is really long text</Text>
);
expect(wrapper.instance().state.wordsByLines.length).to.equal(2); |
00a1e98c52d51b07a0c051dba6107bc6e99e8916 | server/api/geometry/routes.js | server/api/geometry/routes.js | /* eslint-disable new-cap */
const router = require('express').Router();
const jsonParser = require('body-parser').json();
const handlers = require('./handlers');
// Geometry tools
router.post('/', jsonParser, handlers.getInEverySystem);
router.post('/parse', jsonParser, handlers.parseCoordinates);
module.exports = router;
| /* eslint-disable new-cap */
const router = require('express').Router();
const jsonParser = require('body-parser').json();
const handlers = require('./handlers');
// Geometry tools
router.post('/', jsonParser, handlers.getInEverySystem);
router.get('/parse', handlers.parseCoordinates);
module.exports = router;
| Use GET method to parse coordinates | Use GET method to parse coordinates
| JavaScript | mit | axelpale/tresdb,axelpale/tresdb | ---
+++
@@ -8,6 +8,6 @@
// Geometry tools
router.post('/', jsonParser, handlers.getInEverySystem);
-router.post('/parse', jsonParser, handlers.parseCoordinates);
+router.get('/parse', handlers.parseCoordinates);
module.exports = router; |
a3c781ff7ad00536ee3b70e93b5832ea4145b7aa | tools/build.conf.js | tools/build.conf.js | ({
mainConfigFile: '../requirejs.conf.js',
paths: {
almond: 'lib/almond/almond'
},
baseUrl: '..',
name: "streamhub-permalink",
include: [
'almond',
'streamhub-permalink/default-permalink-content-renderer'
],
stubModules: ['text', 'hgn', 'json'],
out: "../dist/streamhub-permalink.min.js",
buildCSS: true,
separateCSS: true,
pragmasOnSave: {
excludeHogan: true
},
cjsTranslate: true,
optimize: "none",
preserveLicenseComments: false,
uglify2: {
compress: {
unsafe: true
},
mangle: true
},
generateSourceMaps: true,
wrap: {
startFile: 'wrap-start.frag',
endFile: 'wrap-end.frag'
},
onBuildRead: function(moduleName, path, contents) {
switch (moduleName) {
case "jquery":
// case "base64":
contents = "define([], function(require, exports, module) {" + contents + "});";
}
return contents;
}
})
| ({
mainConfigFile: '../requirejs.conf.js',
paths: {
almond: 'lib/almond/almond'
},
baseUrl: '..',
name: "streamhub-permalink",
include: [
'almond',
'streamhub-permalink/default-permalink-content-renderer'
],
stubModules: ['text', 'hgn', 'json'],
out: "../dist/streamhub-permalink.min.js",
buildCSS: true,
separateCSS: true,
pragmasOnSave: {
excludeHogan: true
},
cjsTranslate: true,
optimize: "uglify2",
preserveLicenseComments: false,
uglify2: {
compress: {
unsafe: true
},
mangle: true
},
generateSourceMaps: true,
wrap: {
startFile: 'wrap-start.frag',
endFile: 'wrap-end.frag'
},
onBuildRead: function(moduleName, path, contents) {
switch (moduleName) {
case "jquery":
// case "base64":
contents = "define([], function(require, exports, module) {" + contents + "});";
}
return contents;
}
})
| Add uglify2 minification to build | Add uglify2 minification to build
| JavaScript | mit | Livefyre/streamhub-permalink,Livefyre/streamhub-permalink | ---
+++
@@ -17,7 +17,7 @@
excludeHogan: true
},
cjsTranslate: true,
- optimize: "none",
+ optimize: "uglify2",
preserveLicenseComments: false,
uglify2: {
compress: { |
c26eeac896b9a96a51a8ec9b6bb57ab429abda76 | src/js/actions/asset-actions.js | src/js/actions/asset-actions.js |
//note must be set in gulp .sh config.
const ServiceURL = process.env.ASSET_PROCESSING_SERVICE
const Endpoints = {
imageTagging: ServiceURL + "/image/tags/"
}
var AssetActions = {
getSuggestedTags(mediaObject, callback) {
switch(mediaObject.type) {
case "image":
fetchSuggestedImageTags(mediaObject, callback);
break;
default:
callback();
break;
};
//todo could implement video tags through AWS and text through a NLP service? need to look at adding timecode to video tags
return
},
}
//functions that should not be user callable
function fetchSuggestedImageTags(mediaObject, callback) {
console.log(Endpoints.imageTagging + encodeURIComponent(mediaObject.url))
fetch(Endpoints.imageTagging + encodeURIComponent(mediaObject.url))
.then(response => {return response.json()})
.then(json => {
var tags = [];
json[0].forEach(fullTag => {
tags.push(fullTag.tag); //NB: fulltag includes confidence/mid etc but we don't have anywhere to put this yet.
});
callback(tags);
})
.catch(function (err) {console.log("Error fetching from image processing service", err)})
return
}
module.exports = AssetActions; |
//note must be set in gulp .sh config.
const ServiceURL = process.env.ASSET_PROCESSING_SERVICE
const Endpoints = {
imageTagging: ServiceURL + "/image/tags/"
}
var AssetActions = {
getSuggestedTags(mediaObject, callback) {
switch(mediaObject.type) {
case "image":
fetchSuggestedImageTags(mediaObject, callback);
break;
default:
callback([]);
break;
};
//todo could implement video tags through AWS and text through a NLP service? need to look at adding timecode to video tags
return
},
}
//functions that should not be user callable
function fetchSuggestedImageTags(mediaObject, callback) {
console.log(Endpoints.imageTagging + encodeURIComponent(mediaObject.url))
fetch(Endpoints.imageTagging + encodeURIComponent(mediaObject.url))
.then(response => {return response.json()})
.then(json => {
var tags = [];
json[0].forEach(fullTag => {
tags.push(fullTag.tag); //NB: fulltag includes confidence/mid etc but we don't have anywhere to put this yet.
});
callback(tags);
})
.catch(function (err) {console.log("Error fetching from image processing service", err)})
return
}
module.exports = AssetActions; | Fix for automatic tagging, needs to return an empty list instead of null. | Fix for automatic tagging, needs to return an empty list instead of null.
| JavaScript | mit | UoSMediaFrameworks/uos-media-playback-framework-legacy,UoSMediaFrameworks/uos-media-playback-framework-legacy,UoSMediaFrameworks/uos-media-playback-framework-legacy | ---
+++
@@ -14,7 +14,7 @@
fetchSuggestedImageTags(mediaObject, callback);
break;
default:
- callback();
+ callback([]);
break;
};
//todo could implement video tags through AWS and text through a NLP service? need to look at adding timecode to video tags |
c3001938537b7f5590d71e536653ebfd083ffa52 | packages/react-native-codegen/src/generators/modules/Utils.js | packages/react-native-codegen/src/generators/modules/Utils.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
import type {ObjectTypeAliasTypeShape} from '../../CodegenSchema';
function getTypeAliasTypeAnnotation(
name: string,
aliases: $ReadOnly<{[aliasName: string]: ObjectTypeAliasTypeShape, ...}>,
): $ReadOnly<ObjectTypeAliasTypeShape> {
const typeAnnotation = aliases[name];
if (!typeAnnotation) {
throw Error(`No type annotation found for "${name}" in schema`);
}
if (typeAnnotation.type === 'ObjectTypeAnnotation') {
if (typeAnnotation.properties) {
return typeAnnotation;
}
throw new Error(
`Unsupported type for "${name}". Please provide properties.`,
);
}
// $FlowFixMe[incompatible-type]
if (typeAnnotation.type === 'TypeAliasTypeAnnotation') {
return getTypeAliasTypeAnnotation(typeAnnotation.name, aliases);
}
throw Error(
`Unsupported type annotation in alias "${name}", found: ${typeAnnotation.type}`,
);
}
module.exports = {
getTypeAliasTypeAnnotation,
};
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
'use strict';
import type {
SchemaType,
NativeModuleAliasMap,
Required,
NativeModuleObjectTypeAnnotation,
NativeModuleSchema,
} from '../../CodegenSchema';
const invariant = require('invariant');
export type AliasResolver = (
aliasName: string,
) => Required<NativeModuleObjectTypeAnnotation>;
function createAliasResolver(aliasMap: NativeModuleAliasMap): AliasResolver {
return (aliasName: string) => {
const alias = aliasMap[aliasName];
invariant(alias != null, `Unable to resolve type alias '${aliasName}'.`);
return alias;
};
}
function getModules(
schema: SchemaType,
): $ReadOnly<{|[moduleName: string]: NativeModuleSchema|}> {
return Object.keys(schema.modules)
.map<?{+[string]: NativeModuleSchema}>(
moduleName => schema.modules[moduleName].nativeModules,
)
.filter(Boolean)
.reduce<{+[string]: NativeModuleSchema}>(
(acc, modules) => ({...acc, ...modules}),
{},
);
}
module.exports = {
createAliasResolver,
getModules,
};
| Create utilities for module generators | Create utilities for module generators
Summary:
There are two operations we do in every NativeModule generator:
- We convert the `SchemaType` into a map of NativeModule schemas
- If the type-annotation is a TypeAliasTypeAnnotation, we resolve it by doing a lookup on the NativeModuleAliasMap. This is usually followed by an invariant to assert that the lookup didn't fail.
Both procedures have been translated into utilities for use across our generators. I also deleted `getTypeAliasTypeAnnotation` which will no longer be used.
Changelog: [Internal]
Reviewed By: hramos
Differential Revision: D23667249
fbshipit-source-id: 4e34078980e2caa4daed77c38b1168bfc161c31c
| JavaScript | mit | pandiaraj44/react-native,pandiaraj44/react-native,janicduplessis/react-native,arthuralee/react-native,facebook/react-native,pandiaraj44/react-native,javache/react-native,arthuralee/react-native,arthuralee/react-native,janicduplessis/react-native,facebook/react-native,janicduplessis/react-native,myntra/react-native,pandiaraj44/react-native,pandiaraj44/react-native,myntra/react-native,myntra/react-native,javache/react-native,javache/react-native,javache/react-native,myntra/react-native,facebook/react-native,myntra/react-native,myntra/react-native,pandiaraj44/react-native,myntra/react-native,facebook/react-native,janicduplessis/react-native,pandiaraj44/react-native,facebook/react-native,arthuralee/react-native,javache/react-native,myntra/react-native,arthuralee/react-native,facebook/react-native,javache/react-native,javache/react-native,facebook/react-native,janicduplessis/react-native,javache/react-native,janicduplessis/react-native,myntra/react-native,facebook/react-native,pandiaraj44/react-native,facebook/react-native,janicduplessis/react-native,javache/react-native,janicduplessis/react-native | ---
+++
@@ -10,35 +10,43 @@
'use strict';
-import type {ObjectTypeAliasTypeShape} from '../../CodegenSchema';
+import type {
+ SchemaType,
+ NativeModuleAliasMap,
+ Required,
+ NativeModuleObjectTypeAnnotation,
+ NativeModuleSchema,
+} from '../../CodegenSchema';
-function getTypeAliasTypeAnnotation(
- name: string,
- aliases: $ReadOnly<{[aliasName: string]: ObjectTypeAliasTypeShape, ...}>,
-): $ReadOnly<ObjectTypeAliasTypeShape> {
- const typeAnnotation = aliases[name];
- if (!typeAnnotation) {
- throw Error(`No type annotation found for "${name}" in schema`);
- }
- if (typeAnnotation.type === 'ObjectTypeAnnotation') {
- if (typeAnnotation.properties) {
- return typeAnnotation;
- }
+const invariant = require('invariant');
- throw new Error(
- `Unsupported type for "${name}". Please provide properties.`,
+export type AliasResolver = (
+ aliasName: string,
+) => Required<NativeModuleObjectTypeAnnotation>;
+
+function createAliasResolver(aliasMap: NativeModuleAliasMap): AliasResolver {
+ return (aliasName: string) => {
+ const alias = aliasMap[aliasName];
+ invariant(alias != null, `Unable to resolve type alias '${aliasName}'.`);
+ return alias;
+ };
+}
+
+function getModules(
+ schema: SchemaType,
+): $ReadOnly<{|[moduleName: string]: NativeModuleSchema|}> {
+ return Object.keys(schema.modules)
+ .map<?{+[string]: NativeModuleSchema}>(
+ moduleName => schema.modules[moduleName].nativeModules,
+ )
+ .filter(Boolean)
+ .reduce<{+[string]: NativeModuleSchema}>(
+ (acc, modules) => ({...acc, ...modules}),
+ {},
);
- }
- // $FlowFixMe[incompatible-type]
- if (typeAnnotation.type === 'TypeAliasTypeAnnotation') {
- return getTypeAliasTypeAnnotation(typeAnnotation.name, aliases);
- }
-
- throw Error(
- `Unsupported type annotation in alias "${name}", found: ${typeAnnotation.type}`,
- );
}
module.exports = {
- getTypeAliasTypeAnnotation,
+ createAliasResolver,
+ getModules,
}; |
e1123e2de6d9542950967a4128e616ddcbad7259 | src/react-chayns-openingtimes/utils/parseTimeString.js | src/react-chayns-openingtimes/utils/parseTimeString.js | export default function parseTimeString(str) {
const regexRes = new RegExp('[0-9]{0,2}:[0-9]{0,2}').exec(str);
let hours = null;
let minutes = null;
if (regexRes) {
const parts = regexRes[0].split(':');
hours = parseInt(parts[0], 10) || 0;
minutes = parseInt(parts[1], 10) || 0;
}
return {
hours,
minutes,
};
}
| const TIME_STRING_REGEX = /([0-9]{0,2}):([0-9]{0,2})/;
export default function parseTimeString(str) {
const regexRes = TIME_STRING_REGEX.exec(str);
let hours = null;
let minutes = null;
if (regexRes) {
hours = parseInt(regexRes[1], 10) || 0;
minutes = parseInt(regexRes[2], 10) || 0;
}
return {
hours,
minutes,
};
}
| Use regex for parsing TimeString | :recycle: Use regex for parsing TimeString
| JavaScript | mit | TobitSoftware/chayns-components,TobitSoftware/chayns-components,TobitSoftware/chayns-components | ---
+++
@@ -1,12 +1,13 @@
+const TIME_STRING_REGEX = /([0-9]{0,2}):([0-9]{0,2})/;
+
export default function parseTimeString(str) {
- const regexRes = new RegExp('[0-9]{0,2}:[0-9]{0,2}').exec(str);
+ const regexRes = TIME_STRING_REGEX.exec(str);
let hours = null;
let minutes = null;
+
if (regexRes) {
- const parts = regexRes[0].split(':');
-
- hours = parseInt(parts[0], 10) || 0;
- minutes = parseInt(parts[1], 10) || 0;
+ hours = parseInt(regexRes[1], 10) || 0;
+ minutes = parseInt(regexRes[2], 10) || 0;
}
return { |
a1d7933c578882aa73b5855961ff8622119c4141 | ui/src/data_explorer/components/RawQueryEditor.js | ui/src/data_explorer/components/RawQueryEditor.js | import React, {PropTypes} from 'react'
const ENTER = 13
const ESCAPE = 27
const RawQueryEditor = React.createClass({
propTypes: {
query: PropTypes.shape({
rawText: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
}).isRequired,
onUpdate: PropTypes.func.isRequired,
},
getInitialState() {
return {
value: this.props.query.rawText,
}
},
componentWillReceiveProps(nextProps) {
if (nextProps.query.rawText !== this.props.query.rawText) {
this.setState({value: nextProps.query.rawText})
}
},
handleKeyDown(e) {
e.preventDefault()
if (e.keyCode === ENTER) {
this.handleUpdate();
} else if (e.keyCode === ESCAPE) {
this.setState({value: this.props.query.rawText}, () => {
this.editor.blur()
})
}
},
handleChange() {
this.setState({
value: this.editor.value,
})
},
handleUpdate() {
this.props.onUpdate(this.state.value)
},
render() {
const {value} = this.state
return (
<div className="raw-text">
<textarea
className="raw-text--field"
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
onBlur={this.handleUpdate}
ref={(editor) => this.editor = editor}
value={value}
placeholder="Blank query"
/>
</div>
)
},
})
export default RawQueryEditor
| import React, {PropTypes} from 'react'
const ENTER = 13
const ESCAPE = 27
const RawQueryEditor = React.createClass({
propTypes: {
query: PropTypes.shape({
rawText: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
}).isRequired,
onUpdate: PropTypes.func.isRequired,
},
getInitialState() {
return {
value: this.props.query.rawText,
}
},
componentWillReceiveProps(nextProps) {
if (nextProps.query.rawText !== this.props.query.rawText) {
this.setState({value: nextProps.query.rawText})
}
},
handleKeyDown(e) {
if (e.keyCode === ENTER) {
e.preventDefault()
this.handleUpdate();
} else if (e.keyCode === ESCAPE) {
this.setState({value: this.props.query.rawText}, () => {
this.editor.blur()
})
}
},
handleChange() {
this.setState({
value: this.editor.value,
})
},
handleUpdate() {
this.props.onUpdate(this.state.value)
},
render() {
const {value} = this.state
return (
<div className="raw-text">
<textarea
className="raw-text--field"
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
onBlur={this.handleUpdate}
ref={(editor) => this.editor = editor}
value={value}
placeholder="Blank query"
/>
</div>
)
},
})
export default RawQueryEditor
| Allow user to type :) | Allow user to type :)
| JavaScript | mit | nooproblem/influxdb,li-ang/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdata/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdata/influxdb | ---
+++
@@ -24,9 +24,8 @@
},
handleKeyDown(e) {
- e.preventDefault()
-
if (e.keyCode === ENTER) {
+ e.preventDefault()
this.handleUpdate();
} else if (e.keyCode === ESCAPE) {
this.setState({value: this.props.query.rawText}, () => { |
1d1fdcb0bd822a1b30d9f76c1a37b529216293f2 | src/client/react/admin/AdminNavbar/MainNavigation.js | src/client/react/admin/AdminNavbar/MainNavigation.js | import React from 'react';
class MainNavigation extends React.Component {
render() {
return (
<div>
</div>
);
}
}
export default MainNavigation;
| import React from 'react';
import { Link } from 'react-router-dom';
const linkStyle = 'pt-button pt-minimal';
class MainNavigation extends React.Component {
render() {
return (
<div>
<a className={linkStyle + ' pt-icon pt-icon-key-escape'} href='/'>Visit site</a>
</div>
);
}
}
export default MainNavigation;
| Add visit site link to navbar | [ADD] Add visit site link to navbar
| JavaScript | mit | bwyap/ptc-amazing-g-race,bwyap/ptc-amazing-g-race | ---
+++
@@ -1,10 +1,15 @@
import React from 'react';
+import { Link } from 'react-router-dom';
+const linkStyle = 'pt-button pt-minimal';
+
class MainNavigation extends React.Component {
+
render() {
return (
<div>
+ <a className={linkStyle + ' pt-icon pt-icon-key-escape'} href='/'>Visit site</a>
</div>
);
} |
40d2bf71e8515d16866ab1a6f77d562d81bf5c6c | src/readFiles.js | src/readFiles.js | 'use strict';
const fs = require('fs-extra');
const marked = require('marked');
const parser = require('./littlePostParser');
module.exports = function readFiles(path) {
const posts = [];
fs.ensureDirSync(path);
fs.readdirSync(path).forEach(file => {
let date = file.match(/^(\d{4})-(\d\d?)-(\d\d?)-(.+)\.(md|markdown|html)$/);
if (!date)
return;
const post = parser(path + '/' + file);
const name = date[4];
const Post = Object.assign(post, { main: marked(post.main), name: name });
posts.push(Post);
});
return posts;
};
| 'use strict';
const fs = require('fs-extra');
const marked = require('marked');
const parser = require('./littlePostParser');
module.exports = function readFiles(path) {
const posts = [];
fs.ensureDirSync(path);
fs.readdirSync(path).forEach(file => {
let date = file.match(/^(\d{4})-(\d\d?)-(\d\d?)-(.+)\.(md|markdown|html)$/);
if (!date) {
return;
}
const d = `${date[3]}.${date[2]}.${date[1]}`
const post = parser(path + '/' + file);
const name = date[4];
const Post = Object.assign(post, { main: marked(post.main), name: name, date: d });
posts.push(Post);
});
return posts;
};
| Add `date` to post meta-date-uh 😆 | Add `date` to post meta-date-uh 😆
| JavaScript | mit | corderophilosophy/tickle-js-ssg,corderophilosophy/tickle-js-ssg | ---
+++
@@ -8,11 +8,13 @@
fs.ensureDirSync(path);
fs.readdirSync(path).forEach(file => {
let date = file.match(/^(\d{4})-(\d\d?)-(\d\d?)-(.+)\.(md|markdown|html)$/);
- if (!date)
+ if (!date) {
return;
+ }
+ const d = `${date[3]}.${date[2]}.${date[1]}`
const post = parser(path + '/' + file);
const name = date[4];
- const Post = Object.assign(post, { main: marked(post.main), name: name });
+ const Post = Object.assign(post, { main: marked(post.main), name: name, date: d });
posts.push(Post);
});
return posts; |
9abe60c45aa83fbbf12553ea4af089ed685da08f | lib/GitterBot.js | lib/GitterBot.js | var Gitter = require('node-gitter');
var fs = require('fs');
var config = fs.existsSync('../config/local.js') ? require('../config/local.js') : {};
/**
* Create new instance of GitterBot
* @param {String} key Your API key
* @constructor
*/
function GitterBot(key) {
this.setApiKey(key);
}
GitterBot.prototype = {
/**
* Set API key to GitterBot instance
* @param {String} key New API key
* @returns {GitterBot}
*/
setApiKey: function (key) {
this._apiKey = key || process.env['GITTER_API_KEY'];
return this;
},
/**
* Get current API key
* @returns {String}
*/
getApiKey: function () {
return this._apiKey;
}
};
module.exports = GitterBot;
| var Gitter = require('node-gitter');
/**
* Create new instance of GitterBot
* @param {String} config Configuration object with `apiKey` and `room` properties
* @constructor
*/
function GitterBot(config) {
config = config || {};
this.setApiKey(config.apiKey);
this.setRoom(config.room);
this.connect();
}
GitterBot.prototype = {
/**
* Set API key to GitterBot instance
* @param {String} key New API key
* @returns {GitterBot}
*/
setApiKey: function (key) {
this._apiKey = key || process.env['GITTER_API_KEY'];
return this;
},
/**
* Get current API key
* @returns {String}
*/
getApiKey: function () {
return this._apiKey;
},
/**
* Set room to which bot will connect
* @param {String} room Which room you want to listen
* @returns {GitterBot}
*/
setRoom: function (room) {
this._room = room || 'ghaiklor/uwcua-vii';
return this;
},
/**
* Get current room which bot is listen
* @returns {String}
*/
getRoom: function () {
return this._room;
},
/**
* Update gitter client
* @returns {GitterBot}
*/
connect: function () {
this._gitter = new Gitter(this.getApiKey());
return this;
},
/**
* Start bot for listening messages
* @returns {GitterBot}
*/
start: function () {
this._gitter.rooms.join(this.getRoom()).then(function (room) {
var events = room.listen();
room.send("Hey, I've start listening this room");
events.on('message', function (message) {
if (/^calc /.test(message)) {
// TODO: implement eval
console.log(message);
}
});
});
return this;
},
/**
* Stop bot for listening messages
* @returns {GitterBot}
*/
stop: function () {
// TODO: implement this
return this;
}
};
module.exports = GitterBot;
| Add creating gitter client and listen message | Add creating gitter client and listen message
| JavaScript | mit | ghaiklor/uwcua-vii | ---
+++
@@ -1,14 +1,16 @@
var Gitter = require('node-gitter');
-var fs = require('fs');
-var config = fs.existsSync('../config/local.js') ? require('../config/local.js') : {};
/**
* Create new instance of GitterBot
- * @param {String} key Your API key
+ * @param {String} config Configuration object with `apiKey` and `room` properties
* @constructor
*/
-function GitterBot(key) {
- this.setApiKey(key);
+function GitterBot(config) {
+ config = config || {};
+
+ this.setApiKey(config.apiKey);
+ this.setRoom(config.room);
+ this.connect();
}
GitterBot.prototype = {
@@ -28,6 +30,62 @@
*/
getApiKey: function () {
return this._apiKey;
+ },
+
+ /**
+ * Set room to which bot will connect
+ * @param {String} room Which room you want to listen
+ * @returns {GitterBot}
+ */
+ setRoom: function (room) {
+ this._room = room || 'ghaiklor/uwcua-vii';
+ return this;
+ },
+
+ /**
+ * Get current room which bot is listen
+ * @returns {String}
+ */
+ getRoom: function () {
+ return this._room;
+ },
+
+ /**
+ * Update gitter client
+ * @returns {GitterBot}
+ */
+ connect: function () {
+ this._gitter = new Gitter(this.getApiKey());
+ return this;
+ },
+
+ /**
+ * Start bot for listening messages
+ * @returns {GitterBot}
+ */
+ start: function () {
+ this._gitter.rooms.join(this.getRoom()).then(function (room) {
+ var events = room.listen();
+
+ room.send("Hey, I've start listening this room");
+ events.on('message', function (message) {
+ if (/^calc /.test(message)) {
+ // TODO: implement eval
+ console.log(message);
+ }
+ });
+ });
+
+ return this;
+ },
+
+ /**
+ * Stop bot for listening messages
+ * @returns {GitterBot}
+ */
+ stop: function () {
+ // TODO: implement this
+ return this;
}
};
|
0bebc89c61b01f40587ac0820c0c3cbf80b63f6e | src/scripts/app/activities/sentences/editSentence.js | src/scripts/app/activities/sentences/editSentence.js | 'use strict';
module.exports =
/*@ngInject*/
function EditSentence(
$scope, SentenceWritingService, $state, _
) {
SentenceWritingService.getSentenceWriting($state.params.id)
.then(function(s) {
s.category = _.findWhere($scope.availableCategories, function(o) {
return o.$id == s.categoryId;
});
var tempList = _.chain(s.rules)
.pluck('ruleId')
.toArray()
.map(function(s) {
return String(s);
})
.value();
s.rules = _.filter($scope.availableRules, function(r) {
return _.contains(tempList, String(r.$id));
});
s.flag = _.findWhere($scope.flags, function(f) {
return f.$id == s.flagId;
});
$scope.editSentence = s;
});
};
| 'use strict';
module.exports =
/*@ngInject*/
function EditSentence(
$scope, SentenceWritingService, $state, _
) {
SentenceWritingService.getSentenceWriting($state.params.id)
.then(function(s) {
s.category = _.findWhere($scope.availableCategories, function(o) {
return o.$id == s.categoryId;
});
var tempList = _.chain(s.rules)
.pluck('ruleId')
.toArray()
.map(function(s) {
return String(s);
})
.value();
s.rules = _.chain($scope.availableRules)
.filter(function(r) {
return _.contains(tempList, String(r.$id));
})
.map(function(r) {
r.quantity = _.findWhere(s.rules, {ruleId: r.$id}).quantity;
return r;
})
.value();
s.flag = _.findWhere($scope.flags, function(f) {
return f.$id == s.flagId;
});
$scope.editSentence = s;
});
};
| Add quantity into edit rules. | Add quantity into edit rules.
| JavaScript | agpl-3.0 | empirical-org/Quill-Grammar,ddmck/Quill-Grammar,empirical-org/Quill-Grammar,empirical-org/Quill-Grammar,ddmck/Quill-Grammar,ddmck/Quill-Grammar | ---
+++
@@ -18,9 +18,15 @@
return String(s);
})
.value();
- s.rules = _.filter($scope.availableRules, function(r) {
- return _.contains(tempList, String(r.$id));
- });
+ s.rules = _.chain($scope.availableRules)
+ .filter(function(r) {
+ return _.contains(tempList, String(r.$id));
+ })
+ .map(function(r) {
+ r.quantity = _.findWhere(s.rules, {ruleId: r.$id}).quantity;
+ return r;
+ })
+ .value();
s.flag = _.findWhere($scope.flags, function(f) {
return f.$id == s.flagId;
}); |
d16d986edec59eed0a73490e4587efd5455e7b28 | src/api/emit.js | src/api/emit.js | const CustomEvent = ((Event) => {
if (Event) {
try {
new Event(); // eslint-disable-line no-new
} catch (e) {
return undefined;
}
}
return Event;
})(window.CustomEvent);
function createCustomEvent(name, opts = {}) {
let e;
if (Event) {
e = new Event(name, opts);
if (opts.detail) {
Object.defineProperty(e, 'detail', { value: opts.detail });
}
} else {
e = document.createEvent('CustomEvent');
e.initCustomEvent(name, opts.bubbles, opts.cancelable, opts.detail);
}
return e;
}
export default function (elem, name, opts = {}) {
if (opts.bubbles === undefined) {
opts.bubbles = true;
}
if (opts.cancelable === undefined) {
opts.cancelable = true;
}
if (opts.composed === undefined) {
opts.composed = true;
}
return elem.dispatchEvent(createCustomEvent(name, opts));
}
| const CustomEvent = ((Event) => {
if (Event) {
try {
new Event(); // eslint-disable-line no-new
} catch (e) {
return undefined;
}
}
return Event;
})(window.CustomEvent);
function createCustomEvent(name, opts = {}) {
let e;
if (Event) {
e = new Event(name, opts);
if ('detail' in opts) {
Object.defineProperty(e, 'detail', { value: opts.detail });
}
} else {
e = document.createEvent('CustomEvent');
e.initCustomEvent(name, opts.bubbles, opts.cancelable, opts.detail);
}
return e;
}
export default function (elem, name, opts = {}) {
if (opts.bubbles === undefined) {
opts.bubbles = true;
}
if (opts.cancelable === undefined) {
opts.cancelable = true;
}
if (opts.composed === undefined) {
opts.composed = true;
}
return elem.dispatchEvent(createCustomEvent(name, opts));
}
| Allow detail to be falsy | Allow detail to be falsy
| JavaScript | mit | chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs | ---
+++
@@ -13,7 +13,7 @@
let e;
if (Event) {
e = new Event(name, opts);
- if (opts.detail) {
+ if ('detail' in opts) {
Object.defineProperty(e, 'detail', { value: opts.detail });
}
} else { |
2b8b8b78926aae2dc3c4a2140893f81a1ce9fb46 | test/sapi.js | test/sapi.js | var bag = require('bagofholding'),
sandbox = require('sandboxed-module'),
should = require('should'),
checks, mocks,
sapi;
describe('sapi', function () {
function create(checks, mocks) {
return sandbox.require('../lib/sapi', {
requires: mocks ? mocks.requires : {},
globals: {}
});
}
beforeEach(function () {
checks = {};
mocks = {};
});
describe('bar', function () {
it('should foo when bar', function () {
});
});
});
| var bag = require('bagofholding'),
sandbox = require('sandboxed-module'),
should = require('should'),
checks, mocks,
sapi;
describe('sapi', function () {
function create(checks, mocks) {
return sandbox.require('../lib/sapi', {
requires: mocks ? mocks.requires : {},
globals: {}
});
}
beforeEach(function () {
checks = {};
mocks = {};
});
describe('sapi', function () {
it('should set key and default url when url is not provided', function () {
sapi = new (create(checks, mocks))('somekey');
sapi.params.key.should.equal('somekey');
sapi.url.should.equal('http://api.sensis.com.au/ob-20110511/test');
});
it('should set specified key and url when provided', function () {
sapi = new (create(checks, mocks))('somekey', 'http://someurl');
sapi.params.key.should.equal('somekey');
sapi.url.should.equal('http://someurl');
});
it('should pass error to callback when an error occurs while sending request', function (done) {
mocks.request_err = new Error('someerror');
mocks.requires = {
request: bag.mock.request(checks, mocks)
};
sapi = new (create(checks, mocks))();
sapi.search(function cb(err, result) {
checks.sapi_search_err = err;
checks.sapi_search_result = result;
done();
});
checks.sapi_search_err.message.should.equal('someerror');
should.not.exist(checks.sapi_search_result);
});
});
describe('proxy', function () {
it('should set proxy', function () {
sapi = new (create(checks, mocks))('somekey');
sapi.proxy('http://someproxy');
sapi._proxy.should.equal('http://someproxy');
});
it('should allow chainable proxy setting', function () {
sapi = new (create(checks, mocks))('somekey').proxy('http://someproxy');
sapi._proxy.should.equal('http://someproxy');
});
});
});
| Add constructor and error callback tests. | Add constructor and error callback tests.
| JavaScript | mit | cliffano/sapi | ---
+++
@@ -18,9 +18,47 @@
mocks = {};
});
- describe('bar', function () {
+ describe('sapi', function () {
- it('should foo when bar', function () {
+ it('should set key and default url when url is not provided', function () {
+ sapi = new (create(checks, mocks))('somekey');
+ sapi.params.key.should.equal('somekey');
+ sapi.url.should.equal('http://api.sensis.com.au/ob-20110511/test');
+ });
+
+ it('should set specified key and url when provided', function () {
+ sapi = new (create(checks, mocks))('somekey', 'http://someurl');
+ sapi.params.key.should.equal('somekey');
+ sapi.url.should.equal('http://someurl');
+ });
+
+ it('should pass error to callback when an error occurs while sending request', function (done) {
+ mocks.request_err = new Error('someerror');
+ mocks.requires = {
+ request: bag.mock.request(checks, mocks)
+ };
+ sapi = new (create(checks, mocks))();
+ sapi.search(function cb(err, result) {
+ checks.sapi_search_err = err;
+ checks.sapi_search_result = result;
+ done();
+ });
+ checks.sapi_search_err.message.should.equal('someerror');
+ should.not.exist(checks.sapi_search_result);
+ });
+ });
+
+ describe('proxy', function () {
+
+ it('should set proxy', function () {
+ sapi = new (create(checks, mocks))('somekey');
+ sapi.proxy('http://someproxy');
+ sapi._proxy.should.equal('http://someproxy');
+ });
+
+ it('should allow chainable proxy setting', function () {
+ sapi = new (create(checks, mocks))('somekey').proxy('http://someproxy');
+ sapi._proxy.should.equal('http://someproxy');
});
});
}); |
d7024ba7638a738d8e730a8663c5b474c16b2b00 | components/typography/Text.js | components/typography/Text.js | import React, { PureComponent } from 'react';
import Box from '../box';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';
const factory = (baseType, type, defaultElement) => {
class Text extends PureComponent {
render() {
const { children, className, color, element, ...others } = this.props;
const classNames = cx(theme[baseType], theme[type], theme[color], className);
const Element = element || defaultElement;
return (
<Box className={classNames} data-teamleader-ui={baseType} element={Element} {...others}>
{children}
</Box>
);
}
}
Text.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
color: PropTypes.oneOf(['white', 'neutral', 'mint', 'teal', 'violet', 'ruby', 'gold', 'aqua']),
element: PropTypes.node,
};
Text.defaultProps = {
color: 'teal',
element: null,
};
return Text;
};
export { factory as textFactory };
| import React, { PureComponent } from 'react';
import Box from '../box';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { COLORS } from '../../constants';
import theme from './theme.css';
const factory = (baseType, type, defaultElement) => {
class Text extends PureComponent {
render() {
const { children, className, color, element, ...others } = this.props;
const classNames = cx(theme[baseType], theme[type], theme[color], className);
const Element = element || defaultElement;
return (
<Box className={classNames} data-teamleader-ui={baseType} element={Element} {...others}>
{children}
</Box>
);
}
}
Text.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
color: PropTypes.oneOf(COLORS),
element: PropTypes.node,
};
Text.defaultProps = {
color: 'teal',
element: null,
};
return Text;
};
export { factory as textFactory };
| Use our new colors constant for the 'color' prop type | Use our new colors constant for the 'color' prop type
| JavaScript | mit | teamleadercrm/teamleader-ui | ---
+++
@@ -2,6 +2,7 @@
import Box from '../box';
import PropTypes from 'prop-types';
import cx from 'classnames';
+import { COLORS } from '../../constants';
import theme from './theme.css';
const factory = (baseType, type, defaultElement) => {
@@ -24,7 +25,7 @@
Text.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
- color: PropTypes.oneOf(['white', 'neutral', 'mint', 'teal', 'violet', 'ruby', 'gold', 'aqua']),
+ color: PropTypes.oneOf(COLORS),
element: PropTypes.node,
};
|
f19d140732d9ab951849efdcd51b1fd3c3446226 | models/index.js | models/index.js | var Sequelize = require('sequelize');
var inflection = require('inflection');
$config.database.logging = $config.database.log ? console.log : false;
var sequelize = new Sequelize($config.database.name,
$config.database.user,
$config.database.pass,
$config.database);
var self = module.exports = {};
var models = require('node-require-directory')(__dirname);
Object.keys(models).forEach(function(key) {
var modelName = inflection.classify(key);
var modelInstance = sequelize.import(modelName , function(sequelize, DataTypes) {
var definition = [modelName].concat(models[key](DataTypes));
return sequelize.define.apply(sequelize, definition);
});
self[modelName] = modelInstance;
});
self.User.hasMany(self.Team);
self.Team.hasMany(self.User);
self.Project.hasMany(self.Team, { through: self.ProjectTeam });
self.Team.hasMany(self.Project, { through: self.ProjectTeam });
self.sequelize = self.DB = sequelize;
| var Sequelize = require('sequelize');
var inflection = require('inflection');
$config.database.logging = $config.database.log ? console.log : false;
var sequelize = new Sequelize($config.database.name,
$config.database.user,
$config.database.pass,
$config.database);
var self = module.exports = {};
var models = require('node-require-directory')(__dirname);
Object.keys(models).forEach(function(key) {
var modelName = inflection.classify(key);
var modelInstance = sequelize.import(modelName , function(sequelize, DataTypes) {
var definition = [modelName].concat(models[key](DataTypes));
if (sequelize.options.dialect === 'mysql') {
DataTypes.LONGTEXT = 'LONGTEXT';
} else {
DataTypes.LONGTEXT = 'TEXT';
}
return sequelize.define.apply(sequelize, definition);
});
self[modelName] = modelInstance;
});
self.User.hasMany(self.Team);
self.Team.hasMany(self.User);
self.Project.hasMany(self.Team, { through: self.ProjectTeam });
self.Team.hasMany(self.Project, { through: self.ProjectTeam });
self.sequelize = self.DB = sequelize;
| Add LONGTEXT type for MySQL | Add LONGTEXT type for MySQL
| JavaScript | mit | wikilab/wikilab-api | ---
+++
@@ -14,6 +14,11 @@
var modelName = inflection.classify(key);
var modelInstance = sequelize.import(modelName , function(sequelize, DataTypes) {
var definition = [modelName].concat(models[key](DataTypes));
+ if (sequelize.options.dialect === 'mysql') {
+ DataTypes.LONGTEXT = 'LONGTEXT';
+ } else {
+ DataTypes.LONGTEXT = 'TEXT';
+ }
return sequelize.define.apply(sequelize, definition);
});
self[modelName] = modelInstance; |
d1adefd5d3b4dd86afff010c3199864e61275bdb | app/js/arethusa.morph/directives/form_selector.js | app/js/arethusa.morph/directives/form_selector.js | 'use strict';
angular.module('arethusa.morph').directive('formSelector', function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var id = scope.id;
function action(event) {
event.stopPropagation();
scope.$apply(function() {
if (scope.form.selected) {
scope.plugin.unsetState(id);
} else {
scope.plugin.setState(id, scope.form);
}
});
}
scope.$watch('form.selected', function(newVal, oldVal) {
scope.text = newVal ? 'D' : 'S';
});
element.bind('click', action);
},
template: '\
<span\
class="button micro radius"\
ng-class="{ success: form.selected }">\
{{ text }}\
</span>\
'
};
});
| 'use strict';
angular.module('arethusa.morph').directive('formSelector', function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var id = scope.id;
function action(event) {
event.stopPropagation();
scope.$apply(function() {
if (scope.form.selected) {
scope.plugin.unsetState(id);
} else {
scope.plugin.setState(id, scope.form);
}
});
}
scope.$watch('form.selected', function(newVal, oldVal) {
scope.iconClass = newVal ? 'minus' : 'plus';
scope.title = newVal ? 'deselect' : 'select';
});
element.bind('click', action);
},
template: '\
<span\
class="button micro radius"\
title="{{ title }}"\
ng-class="{ success: form.selected }">\
<i class="fi-{{ iconClass }}"></i>\
</span>\
'
};
});
| Use icons and titles in formSelector | Use icons and titles in formSelector
| JavaScript | mit | Masoumeh/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,PonteIneptique/arethusa,latin-language-toolkit/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa | ---
+++
@@ -17,7 +17,8 @@
}
scope.$watch('form.selected', function(newVal, oldVal) {
- scope.text = newVal ? 'D' : 'S';
+ scope.iconClass = newVal ? 'minus' : 'plus';
+ scope.title = newVal ? 'deselect' : 'select';
});
element.bind('click', action);
@@ -25,8 +26,9 @@
template: '\
<span\
class="button micro radius"\
+ title="{{ title }}"\
ng-class="{ success: form.selected }">\
- {{ text }}\
+ <i class="fi-{{ iconClass }}"></i>\
</span>\
'
}; |
7d5e3d2f00c57856c5f1364d238e2ab7c3fe81dd | test/package.js | test/package.js | import fs from 'fs';
import test from 'ava';
import pify from 'pify';
import index from '../';
test('every rule should defined in the index file and recommended settings', async t => {
const files = await pify(fs.readdir, Promise)('../rules/');
const rules = files.filter(file => file.indexOf('.js') === file.length - 3);
rules.forEach(file => {
const name = file.slice(0, -3);
t.truthy(index.rules[name], `'${name}' is not exported in 'index.js'`);
t.truthy(index.configs.recommended.rules[`fp/${name}`], `'${name}' is not set in the recommended config`);
});
t.is(Object.keys(index.rules).length, rules.length,
'There are more exported rules than rule files.');
});
test('no-var should be turned on in the recommended settings', async t => {
t.true(index.configs.recommended.rules['no-var'] === 'error');
});
| import fs from 'fs';
import test from 'ava';
import pify from 'pify';
import index from '../';
test('every rule should defined in the index file and recommended settings', async t => {
const files = await pify(fs.readdir, Promise)('../rules/');
const rules = files.filter(file => file.indexOf('.js') === file.length - 3);
rules.forEach(file => {
const name = file.slice(0, -3);
t.truthy(index.rules[name], `'${name}' is not exported in 'index.js'`);
t.truthy(index.rules[name].meta.docs.description, `'${name}' does not have a description`);
t.truthy(index.rules[name].meta.docs.recommended, `'${name}' does not have a recommended setting`);
t.truthy(index.configs.recommended.rules[`fp/${name}`], `'${name}' is not set in the recommended config`);
});
t.is(Object.keys(index.rules).length, rules.length,
'There are more exported rules than rule files.');
});
test('no-var should be turned on in the recommended settings', async t => {
t.true(index.configs.recommended.rules['no-var'] === 'error');
});
| Add tests to make sure each rule has a recommended setting and a description | Add tests to make sure each rule has a recommended setting and a description
| JavaScript | mit | eslint-plugin-cleanjs/eslint-plugin-cleanjs,jfmengels/eslint-plugin-fp | ---
+++
@@ -10,6 +10,8 @@
rules.forEach(file => {
const name = file.slice(0, -3);
t.truthy(index.rules[name], `'${name}' is not exported in 'index.js'`);
+ t.truthy(index.rules[name].meta.docs.description, `'${name}' does not have a description`);
+ t.truthy(index.rules[name].meta.docs.recommended, `'${name}' does not have a recommended setting`);
t.truthy(index.configs.recommended.rules[`fp/${name}`], `'${name}' is not set in the recommended config`);
});
|
89ee84da83644dbdf1984da6f728ac549170d604 | src/node/cable.js | src/node/cable.js | import EventEmitter from 'events';
const cable = {
__proto__: EventEmitter.prototype,
init(websocket) {
if (this._websocket) {
this._websocket.terminate();
}
this._websocket = websocket;
this.emit('ready');
},
get websocket() {
return new Promise((resolve, reject) => {
if (this._websocket) {
resolve(this._websocket);
} else {
this.on('ready', () => resolve(this._websocket));
}
});
}
};
const cp = async (msg, comment, opts) => (await cable.websocket).
send(JSON.stringify({msg, comment, opts}));
export {
cable,
cp
};
| import EventEmitter from 'events';
const cable = {
__proto__: EventEmitter.prototype,
// Call as early as possible on new client connecting
/* e.g. in a pre-routing http get middleware
httpRouter.get('/', (ctx, next) => {
peek42.cable.init0();
next();
});
*/
init0() {
this.init(null);
},
// Between init0 and init calls, any cp call will
// wait for the websocket promise to resolve.
// (If init0 is not called, there will be a dead zone during
// which cp calls will use the previous (probably stale)
// peek42 websocket)
// Call as soon as peek42 websocket is available
/* e.g. in the peek42 websocket get middleware
wsRouter.get('/peek42', ctx => {
peek42.cable.init(ctx.websocket);
});
*/
init(websocket) {
if (this._websocket) {
this._websocket.terminate();
}
if (!websocket) {
this._websocket = null;
} else {
this._websocket = websocket;
this.emit('ready');
}
},
get websocket() {
return new Promise((resolve, reject) => {
if (this._websocket) {
resolve(this._websocket);
} else {
this.on('ready', () => resolve(this._websocket));
}
});
}
};
const cp = async (msg, comment, opts) => (await cable.websocket).
send(JSON.stringify({msg, comment, opts}));
export {
cable,
cp
};
| Tweak peek42 websocket node init code | Tweak peek42 websocket node init code | JavaScript | mit | rpeev/konsole,rpeev/konsole | ---
+++
@@ -3,12 +3,42 @@
const cable = {
__proto__: EventEmitter.prototype,
+ // Call as early as possible on new client connecting
+ /* e.g. in a pre-routing http get middleware
+ httpRouter.get('/', (ctx, next) => {
+ peek42.cable.init0();
+
+ next();
+ });
+ */
+ init0() {
+ this.init(null);
+ },
+
+ // Between init0 and init calls, any cp call will
+ // wait for the websocket promise to resolve.
+ // (If init0 is not called, there will be a dead zone during
+ // which cp calls will use the previous (probably stale)
+ // peek42 websocket)
+
+ // Call as soon as peek42 websocket is available
+ /* e.g. in the peek42 websocket get middleware
+ wsRouter.get('/peek42', ctx => {
+ peek42.cable.init(ctx.websocket);
+ });
+ */
init(websocket) {
if (this._websocket) {
this._websocket.terminate();
}
- this._websocket = websocket;
- this.emit('ready');
+
+ if (!websocket) {
+ this._websocket = null;
+ } else {
+ this._websocket = websocket;
+
+ this.emit('ready');
+ }
},
get websocket() { |
97929daf840393df65574980362f235af4946545 | src/main.js | src/main.js | /* ---------- Electron init ------------------------------------------------- */
import { app, BrowserWindow } from 'electron'
/* ---------- Requires ------------------------------------------------------ */
import { host, port } from '../scripts/config'
import { isDev } from '../scripts/env'
import path from 'path'
/* ---------- Refs for garbage collection ----------------------------------- */
let window
/* -------------------------------------------------------------------------- */
if (isDev())
require('electron-reload')(__dirname)
function createBrowserWindow () {
// Init Window
window = new BrowserWindow({
width: 1024,
height: 700,
frame: true,
})
// Load template file
window.loadURL(`http://${host}:${port}`)
// Open the DevTools.
if (isDev())
window.webContents.openDevTools()
// Emitted when the window is closed.
window.on('closed', () => {
process.exit(0)
window = null
})
}
app.on('ready', createBrowserWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (window === null) {
createBrowserWindow()
}
})
| /* ---------- Electron init ------------------------------------------------- */
import { app, BrowserWindow } from 'electron'
/* ---------- Requires ------------------------------------------------------ */
import { host, port } from '../scripts/config'
import { isDev } from '../scripts/env'
import path from 'path'
/* ---------- Refs for garbage collection ----------------------------------- */
let window
/* -------------------------------------------------------------------------- */
if (isDev())
require('electron-reload')(__dirname)
function createBrowserWindow () {
// Init Window
window = new BrowserWindow({
width: 1024,
height: 700,
frame: true,
})
// Load template file
window.loadURL(`http://${host}:${port}`)
// Open the DevTools.
if (isDev())
window.webContents.openDevTools()
// Emitted when the window is closed.
window.on('closed', () => {
window = null
})
}
app.on('ready', createBrowserWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (window === null) {
createBrowserWindow()
}
})
| Remove process.exit(0) when windows is closed | Remove process.exit(0) when windows is closed
| JavaScript | mit | guillaumearm/react-redux-functional-boilerplate,guillaumearm/react-redux-functional-boilerplate | ---
+++
@@ -28,7 +28,6 @@
// Emitted when the window is closed.
window.on('closed', () => {
- process.exit(0)
window = null
})
} |
ed2256078319137956d4d90296a6b530115bf592 | src/routes/api.js | src/routes/api.js | import express from 'express';
import eventsGetAll from '../middleware/api/eventsGetAll';
const router = express.Router();
router.get('/', (request, response) => {
response.json({success: true});
});
// TODO
// - Add GET for all data /data - return data + 200
router.get('/events', eventsGetAll);
//router.get('/data/:id', dataGetById);
// - Add POST to add new data /data - return 201
// - Add GET for single data element /data/:id -200 / 404
// - Add PUT to update single data element /data/:id - 200/204 (no content)/4040
// - Add DELETE to delete single data element /data/:id - 200/404
// - Add authentication - basic auth - 'auth' -> 'key:' (no password) + base64 encoded - 401 if failed
export default router;
| import express from 'express';
import eventsGetAll from '../middleware/api/eventsGetAll';
const router = express.Router();
router.get('/', (request, response) => {
response.json({success: true});
});
// TODO
// - Add GET for all data /events - return data + 200
router.get('/events', eventsGetAll);
//router.get('/events/:id', dataGetById);
// - Add POST to add new data /events - return 201
// - Add GET for single data element /events/:id -200 / 404
// - Add PUT to update single data element /events/:id - 200/204 (no content)/4040
// - Add DELETE to delete single data element /events/:id - 200/404
// - Add authentication - basic auth - 'auth' -> 'key:' (no password) + base64 encoded - 401 if failed
export default router;
| Refactor API names for future use | Refactor API names for future use
| JavaScript | mit | MarcL/js-unit-testing-examples | ---
+++
@@ -8,14 +8,14 @@
});
// TODO
-// - Add GET for all data /data - return data + 200
+// - Add GET for all data /events - return data + 200
router.get('/events', eventsGetAll);
-//router.get('/data/:id', dataGetById);
+//router.get('/events/:id', dataGetById);
-// - Add POST to add new data /data - return 201
-// - Add GET for single data element /data/:id -200 / 404
-// - Add PUT to update single data element /data/:id - 200/204 (no content)/4040
-// - Add DELETE to delete single data element /data/:id - 200/404
+// - Add POST to add new data /events - return 201
+// - Add GET for single data element /events/:id -200 / 404
+// - Add PUT to update single data element /events/:id - 200/204 (no content)/4040
+// - Add DELETE to delete single data element /events/:id - 200/404
// - Add authentication - basic auth - 'auth' -> 'key:' (no password) + base64 encoded - 401 if failed
export default router; |
324cffb9348053a54a5572fb008a38a934ab5aac | src/snake-case.js | src/snake-case.js | import R from 'ramda';
import spaceCase from './space-case.js';
import uncapitalize from './uncapitalize.js';
// a -> a
const snakeCase = R.compose(
uncapitalize,
R.join('_'),
R.split(' '),
spaceCase
);
export default snakeCase;
| import R from 'ramda';
import compose from './util/compose.js';
import spaceCase from './space-case.js';
import uncapitalize from './uncapitalize.js';
// a -> a
const snakeCase = compose(
uncapitalize,
R.join('_'),
R.split(' '),
spaceCase
);
export default snakeCase;
| Refactor snakeCase function to use custom compose function | Refactor snakeCase function to use custom compose function
| JavaScript | mit | restrung/restrung-js | ---
+++
@@ -1,9 +1,10 @@
import R from 'ramda';
+import compose from './util/compose.js';
import spaceCase from './space-case.js';
import uncapitalize from './uncapitalize.js';
// a -> a
-const snakeCase = R.compose(
+const snakeCase = compose(
uncapitalize,
R.join('_'),
R.split(' '), |
e426e9d0073b6e6fc0a79aacb9147bcb30bb3016 | src/components/buttons/AuiButton.js | src/components/buttons/AuiButton.js | export default {
render(createComponent) {
const attrs = {
disabled: this.disabled,
href: this.href
};
const elementType = this.href ? 'a' : 'button'
return createComponent(elementType, {
class: this.classObject,
attrs
}, this.$slots.default)
},
props: {
compact: Boolean,
disabled: Boolean,
href: String,
light: Boolean,
subtle: Boolean,
type: {
type: String,
validator(value) {
return 'primary' === value
|| 'link' === value
}
},
},
computed: {
classObject() {
return {
'aui-button': true,
'aui-button-primary': this.type === 'primary',
'aui-button-link': this.type === 'link',
'aui-button-light': this.light,
'aui-button-subtle': this.subtle,
'aui-button-compact': this.compact,
}
}
},
}
| export default {
render(createComponent) {
const attrs = {
disabled: this.disabled,
href: this.href,
target: this.target
};
const elementType = this.href ? 'a' : 'button'
return createComponent(elementType, {
class: this.classObject,
attrs
}, this.$slots.default)
},
props: {
compact: Boolean,
disabled: Boolean,
href: String,
light: Boolean,
subtle: Boolean,
target: String,
type: {
type: String,
validator(value) {
return 'primary' === value
|| 'link' === value
}
},
},
computed: {
classObject() {
return {
'aui-button': true,
'aui-button-primary': this.type === 'primary',
'aui-button-link': this.type === 'link',
'aui-button-light': this.light,
'aui-button-subtle': this.subtle,
'aui-button-compact': this.compact,
}
}
},
}
| Add target to aui-button links | Add target to aui-button links
| JavaScript | mit | spartez/vue-aui,spartez/vue-aui | ---
+++
@@ -3,7 +3,8 @@
render(createComponent) {
const attrs = {
disabled: this.disabled,
- href: this.href
+ href: this.href,
+ target: this.target
};
const elementType = this.href ? 'a' : 'button'
return createComponent(elementType, {
@@ -18,6 +19,7 @@
href: String,
light: Boolean,
subtle: Boolean,
+ target: String,
type: {
type: String,
validator(value) { |
0768c7bb8d211d2e7e63e91e553df0f2d796a92e | src/ti-console.js | src/ti-console.js | var util = require("util");
var assert = require("assert");
var now = require("date-now");
var _console = {};
var times = {};
var functions = [
['log','info'],
['info','info'],
['warn','warn'],
['error','error']
];
functions.forEach(function(tuple) {
_console[tuple[0]] = function() {
Ti.API[tuple[1]](util.format.apply(util, arguments));
};
});
_console.time = function(label) {
times[label] = now();
};
_console.timeEnd = function(label) {
var time = times[label];
if (!time) {
throw new Error("No such label: " + label);
}
var duration = now() - time;
console.log(label + ": " + duration + "ms");
};
_console.trace = function() {
var err = new Error();
err.name = "Trace";
err.message = util.format.apply(null, arguments);
console.error(err.stack);
};
_console.dir = function(object) {
console.log(util.inspect(object) + "\n");
};
_console.assert = function(expression) {
if (!expression) {
var arr = Array.prototype.slice.call(arguments, 1);
assert.ok(false, util.format.apply(null, arr));
}
};
module.exports = _console;
| var util = require("util");
var assert = require("assert");
var now = require("date-now");
var _console = {};
var times = {};
var functions = [
['log','info'],
['info','info'],
['warn','warn'],
['error','error']
];
functions.forEach(function(tuple) {
_console[tuple[0]] = function() {
Ti.API[tuple[1]](util.format.apply(util, arguments));
};
});
_console.time = function(label) {
times[label] = now();
};
_console.timeEnd = function(label) {
var time = times[label];
if (!time) {
throw new Error("No such label: " + label);
}
var duration = now() - time;
_console.log(label + ": " + duration + "ms");
};
_console.trace = function() {
var err = new Error();
err.name = "Trace";
err.message = util.format.apply(null, arguments);
_console.error(err.stack);
};
_console.dir = function(object) {
_console.log(util.inspect(object) + "\n");
};
_console.assert = function(expression) {
if (!expression) {
var arr = Array.prototype.slice.call(arguments, 1);
assert.ok(false, util.format.apply(null, arr));
}
};
module.exports = _console;
| Use `_console` instead of `console` | Use `_console` instead of `console`
So that we don’t have to rely on external `console.log` presence. | JavaScript | mit | tonylukasavage/ti-console | ---
+++
@@ -29,18 +29,18 @@
}
var duration = now() - time;
- console.log(label + ": " + duration + "ms");
+ _console.log(label + ": " + duration + "ms");
};
_console.trace = function() {
var err = new Error();
err.name = "Trace";
err.message = util.format.apply(null, arguments);
- console.error(err.stack);
+ _console.error(err.stack);
};
_console.dir = function(object) {
- console.log(util.inspect(object) + "\n");
+ _console.log(util.inspect(object) + "\n");
};
_console.assert = function(expression) { |
e4486f4c175353f4a204fe7d3f57216cbc573985 | src/ws-proxy.js | src/ws-proxy.js | import assign from 'lodash.assign'
import createDebug from 'debug'
import WebSocket from 'ws'
const debug = createDebug('xo:wsProxy')
const defaults = {
// Automatically close the client connection when the remote close.
autoClose: true
}
// Proxy a WebSocket `client` to a remote server which has `url` as
// address.
export default function wsProxy (client, url, opts) {
opts = assign({}, defaults, opts)
const autoClose = !!opts.autoClose
delete opts.autoClose
function onClientSendError (error) {
debug('client send error', error)
}
function onRemoteSendError (error) {
debug('remote send error', error)
}
const remote = new WebSocket(url, opts).once('open', function () {
debug('connected to %s', url)
}).once('close', function () {
debug('remote closed')
if (autoClose) {
client.close()
}
}).once('error', function (error) {
debug('remote error: %s', error)
}).on('message', function (message) {
client.send(message, onClientSendError)
})
client.once('close', function () {
debug('client closed')
remote.close()
}).on('message', function (message) {
remote.send(message, onRemoteSendError)
})
}
| import assign from 'lodash.assign'
import createDebug from 'debug'
import WebSocket from 'ws'
const debug = createDebug('xo:wsProxy')
const defaults = {
// Automatically close the client connection when the remote close.
autoClose: true
}
// Proxy a WebSocket `client` to a remote server which has `url` as
// address.
export default function wsProxy (client, url, opts) {
opts = assign({}, defaults, opts)
const autoClose = !!opts.autoClose
delete opts.autoClose
function onClientSend (error) {
if (error) {
debug('client send error', error)
}
}
function onRemoteSend (error) {
if (error) {
debug('remote send error', error)
}
}
const remote = new WebSocket(url, opts).once('open', function () {
debug('connected to %s', url)
}).once('close', function () {
debug('remote closed')
if (autoClose) {
client.close()
}
}).once('error', function (error) {
debug('remote error: %s', error)
}).on('message', function (message) {
client.send(message, onClientSend)
})
client.once('close', function () {
debug('client closed')
remote.close()
}).on('message', function (message) {
remote.send(message, onRemoteSend)
})
}
| Fix send error messages in wsProxy. | Fix send error messages in wsProxy.
| JavaScript | agpl-3.0 | lmcro/xo-web,lmcro/xo-web,vatesfr/xo-web,lmcro/xo-web,vatesfr/xo-web | ---
+++
@@ -16,11 +16,15 @@
const autoClose = !!opts.autoClose
delete opts.autoClose
- function onClientSendError (error) {
- debug('client send error', error)
+ function onClientSend (error) {
+ if (error) {
+ debug('client send error', error)
+ }
}
- function onRemoteSendError (error) {
- debug('remote send error', error)
+ function onRemoteSend (error) {
+ if (error) {
+ debug('remote send error', error)
+ }
}
const remote = new WebSocket(url, opts).once('open', function () {
@@ -34,13 +38,13 @@
}).once('error', function (error) {
debug('remote error: %s', error)
}).on('message', function (message) {
- client.send(message, onClientSendError)
+ client.send(message, onClientSend)
})
client.once('close', function () {
debug('client closed')
remote.close()
}).on('message', function (message) {
- remote.send(message, onRemoteSendError)
+ remote.send(message, onRemoteSend)
})
} |
fb93c3f778bb021d2047138091082c6a0788398d | webapplication/indexing/transformations/split-tags.js | webapplication/indexing/transformations/split-tags.js | 'use strict';
const fields = [
'tags',
'tags_vision',
'tags_verified'
]
module.exports = metadata => {
fields.forEach(field => {
const value = metadata[field];
if(typeof(value) === 'string' && value !== '') {
metadata[field] = value.split(',');
} else {
metadata[field] = [];
}
});
return metadata;
};
| 'use strict';
const fields = [
'tags',
'tags_verified'
]
module.exports = metadata => {
fields.forEach(field => {
const value = metadata[field];
if(typeof(value) === 'string' && value !== '') {
metadata[field] = value.split(',');
} else {
metadata[field] = [];
}
});
return metadata;
};
| Remove tags_vision field from splitting of tags -- as it is empty it will have no effect | Remove tags_vision field from splitting of tags -- as it is empty it will have no effect
| JavaScript | mit | CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder | ---
+++
@@ -2,7 +2,6 @@
const fields = [
'tags',
- 'tags_vision',
'tags_verified'
]
|
2f36d03cda77a74fda5bd1883c0e7a2a7cb2ab36 | api/services/formatter-service.js | api/services/formatter-service.js | let Config = require('../../config');
let url = require('url');
let webHook = url.resolve(Config.app.url, '/codeship/');
class FormatterService {
format(type, build) {
return defaultFormat(build)
}
getStartMessage(chatId) {
let hook = this.getWebHook(chatId);
return `${FormatterService.EMOJI.ship} Hi! I see you want to receive Codeship notifications.
Just add this URL as a Webhook to your Codeship notification settings to receive notifications in this conversation.
To receive <b>only failing builds</b> (and the recovering builds)
${hook}
To receive <b>all builds</b> (succeeding and failing)
${hook}?mode=all
@codeship_bot by @dominic0`;
}
getWebHook(chatId) {
return url.resolve(webHook, `${chatId}`);
}
}
FormatterService.EMOJI = {
ship: '\u{1F6A2}',
success: '\u{2705}',
error: '\u{274C}'
};
function defaultFormat(build) {
return `${FormatterService.EMOJI.ship} <b>${build.project_name}</b> - <code>${build.branch}</code> ${FormatterService.EMOJI[build.status] || ''}
<b>${build.committer}</b>: ${build.message}
<a href="${build.build_url}">Open on Codeship</a>`;
}
module.exports = new FormatterService(); | let Config = require('../../config');
let url = require('url');
let webHook = url.resolve(Config.app.url, '/codeship/');
class FormatterService {
format(type, build) {
return defaultFormat(build)
}
getStartMessage(chatId) {
let hook = this.getWebHook(chatId);
return `${FormatterService.EMOJI.ship} Hi! I see you want to receive Codeship notifications.
Just add this URL as a Webhook to your Codeship notification settings to receive notifications in this conversation.
To receive <b>only failing builds</b> (and the recovering builds)
${hook}
To receive <b>all builds</b> (succeeding and failing)
${hook}?mode=all
@codeship_bot by @dominic0`;
}
getWebHook(chatId) {
return url.resolve(webHook, `${chatId}`);
}
}
FormatterService.EMOJI = {
ship: '\u{1F6A2}',
success: '\u{2705}',
error: '\u{274C}'
};
function defaultFormat(build) {
return `${FormatterService.EMOJI[build.status] || ''} <b>${build.project_name}</b> - <code>${build.branch}</code>
<b>${build.committer}</b>: ${build.message}
<a href="${build.build_url}">Open on Codeship</a>`;
}
module.exports = new FormatterService(); | Move build status to beginning of message | Move build status to beginning of message
| JavaScript | mit | freshfox/codeship-telegram-bot,freshfox/codeship-telegram-bot | ---
+++
@@ -35,7 +35,7 @@
};
function defaultFormat(build) {
- return `${FormatterService.EMOJI.ship} <b>${build.project_name}</b> - <code>${build.branch}</code> ${FormatterService.EMOJI[build.status] || ''}
+ return `${FormatterService.EMOJI[build.status] || ''} <b>${build.project_name}</b> - <code>${build.branch}</code>
<b>${build.committer}</b>: ${build.message}
<a href="${build.build_url}">Open on Codeship</a>`;
} |
7f8ac834b5ac9e07f1624883cc399d62974b7226 | website/src/app/models/api/public-tags-api.service.js | website/src/app/models/api/public-tags-api.service.js | class PublicTagsAPIService {
constructor(publicAPIRoute) {
this.publicAPIRoute = publicAPIRoute;
}
getPopularTags() {
return this.publicAPIRoute('tags').one('popular').getList().then(
(tags) => tags.plain()
);
}
}
angular.module('materialscommons').service('publicTagsAPI', PublicTagsAPIService);
| class PublicTagsAPIService {
constructor(Restangular) {
this.Restangular = Restangular;
}
getPopularTags() {
return this.Restangular.one('v3').one('getPopularTagsForPublishedDatasets').customPOST().then(
(tags) => tags.plain().data
);
}
}
angular.module('materialscommons').service('publicTagsAPI', PublicTagsAPIService);
| Switch to actionhero based API | Switch to actionhero based API
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -1,11 +1,11 @@
class PublicTagsAPIService {
- constructor(publicAPIRoute) {
- this.publicAPIRoute = publicAPIRoute;
+ constructor(Restangular) {
+ this.Restangular = Restangular;
}
getPopularTags() {
- return this.publicAPIRoute('tags').one('popular').getList().then(
- (tags) => tags.plain()
+ return this.Restangular.one('v3').one('getPopularTagsForPublishedDatasets').customPOST().then(
+ (tags) => tags.plain().data
);
}
} |
c6d10301951acdc6f49cb91b57dc29760b432d3e | types/secret.js | types/secret.js | 'use strict';
const crypto = require('crypto');
const Network = require('./network');
const Witness = require('./witness');
const MAX_MEMORY = Math.pow(2, 21) + (64 * 1000);
class Secret extends EncryptedPromise {
constructor (settings = {}) {
super(settings);
// assign internal secret
this._secret = (typeof settings === 'string') ? settings : JSON.stringify(settings);
// TODO: check and document upstream pattern
this.load();
}
}
module.exports = EncryptedPromise; | 'use strict';
const EncryptedPromise = require('./promise');
class Secret extends EncryptedPromise {
constructor (settings = {}) {
super(settings);
// assign internal secret
this._secret = (typeof settings === 'string') ? settings : JSON.stringify(settings);
// TODO: check and document upstream pattern
this.load();
}
}
module.exports = EncryptedPromise; | Add upstream EncryptedPromise class to Secret | Add upstream EncryptedPromise class to Secret
| JavaScript | mit | martindale/fabric,martindale/fabric,martindale/fabric | ---
+++
@@ -1,9 +1,6 @@
'use strict';
-const crypto = require('crypto');
-const Network = require('./network');
-const Witness = require('./witness');
-const MAX_MEMORY = Math.pow(2, 21) + (64 * 1000);
+const EncryptedPromise = require('./promise');
class Secret extends EncryptedPromise {
constructor (settings = {}) { |
cd365cca6365d2f3aea0f244d3276c0d5f8a6df1 | syntax/index.js | syntax/index.js | var assign = require('lodash.assign');
var testrunner = require('../lib/testrunner').testRunner;
var es2015 = require('./es2015.json');
var es2016 = require('./es2016.json');
var es2017 = require('./es2017.json');
function syntax() {
var es2015Test = testrunner(es2015, 'es2015');
var es2016Test = testrunner(es2016, 'es2015');
var es2017Test = testrunner(es2017, 'es2015');
var result = assign({
es2015: es2015Test,
es2016: es2016Test,
es2017: es2017Test
}, es2015Test, es2016Test, es2017Test);
result.__all = es2015Test.__all && es2016Test.__all && es2017Test.__all;
return result;
}
module.exports = { syntax: syntax };
| var testrunner = require('../lib/testrunner').testRunner;
var assign = require('../lib/assign');
var es2015 = require('./es2015.json');
var es2016 = require('./es2016.json');
var es2017 = require('./es2017.json');
function syntax() {
var es2015Test = testrunner(es2015, 'es2015');
var es2016Test = testrunner(es2016, 'es2015');
var es2017Test = testrunner(es2017, 'es2015');
var result = assign({
es2015: es2015Test,
es2016: es2016Test,
es2017: es2017Test
}, es2015Test, es2016Test, es2017Test);
result.__all = es2015Test.__all && es2016Test.__all && es2017Test.__all;
return result;
}
module.exports = { syntax: syntax };
| Use new assign method instead of lodash | Syntax: Use new assign method instead of lodash
| JavaScript | mit | Tokimon/es-feature-detection,Tokimon/es-feature-detection,Tokimon/es-feature-detection | ---
+++
@@ -1,5 +1,5 @@
-var assign = require('lodash.assign');
var testrunner = require('../lib/testrunner').testRunner;
+var assign = require('../lib/assign');
var es2015 = require('./es2015.json');
var es2016 = require('./es2016.json'); |
be3bd7187ed33c14b590107198da71e6fba7aeef | app/presenters/taxon-presenter.js | app/presenters/taxon-presenter.js | var taxonHelpers = require('../helpers/taxon-helpers.js');
var filterHelpers = require('../helpers/filter-helpers.js');
function TaxonPresenter (taxonSlug, request) {
this.taxonSlug = taxonSlug; // the slug of the taxon in the Content Store
this.selectedTab = request.query.tab;
if (this.selectedTab == undefined) { this.selectedTab = 'guidance' }; //default view
this.pageTitle = taxonHelpers.fetchCurrentTaxonTitle(this.taxonSlug);
// Fetch appropriate taxonomy data
this.childTaxons = taxonHelpers.fetchChildTaxons(this.taxonSlug);
this.parentTaxon = taxonHelpers.fetchParentTaxon(this.taxonSlug);
this.allContent = taxonHelpers.fetchTaggedItems(this.taxonSlug);
this.determineContentList = function () {
switch (this.selectedTab) {
case 'all':
return this.allContent; break;
default:
return filterHelpers.sectionFilter(this.allContent, this.selectedTab);
}
};
this.contentListToRender = this.determineContentList();
this.curatedContent = this.contentListToRender.slice(0,6);
this.latestContent = this.contentListToRender.slice(0,3);
}
module.exports = TaxonPresenter;
| var taxonHelpers = require('../helpers/taxon-helpers.js');
var filterHelpers = require('../helpers/filter-helpers.js');
function TaxonPresenter (taxonSlug, request) {
this.taxonSlug = taxonSlug; // the slug of the taxon in the Content Store
this.selectedTab = request.query.tab;
if (this.selectedTab == undefined) { this.selectedTab = 'guidance' }; //default view
this.pageTitle = taxonHelpers.fetchCurrentTaxonTitle(this.taxonSlug);
// Fetch appropriate taxonomy data
this.childTaxons = taxonHelpers.fetchChildTaxons(this.taxonSlug);
this.parentTaxon = taxonHelpers.fetchParentTaxon(this.taxonSlug);
this.allContent = taxonHelpers.fetchTaggedItems(this.taxonSlug);
this.determineContentList = function () {
switch (this.selectedTab) {
case 'all':
return this.allContent; break;
default:
return filterHelpers.sectionFilter(this.allContent, this.selectedTab);
}
};
this.contentListToRender = this.determineContentList();
this.curatedContent = this.contentListToRender.slice(0,6);
this.latestContent = this.contentListToRender.slice(0,3);
this.resolveViewTemplateName = function () {
return request.path.replace(this.taxonSlug, '').replace(/^\//, '') + this.selectedTab;
};
this.viewTemplateName = this.resolveViewTemplateName();
}
module.exports = TaxonPresenter;
| Add function to TaxonPresenter to resolve view template path from request | Add function to TaxonPresenter to resolve view template path from request
Still uses the selected tab for the template name, but now looks for the
template in a directory names after the base path.
e.g. - '/taxons/:taxonSlug' will render templates from 'app/views/taxons'
| JavaScript | mit | alphagov/govuk-navigation-prototype,alphagov/govuk-navigation-prototype,alphagov/govuk-navigation-prototype,alphagov/govuk-navigation-prototype | ---
+++
@@ -24,6 +24,11 @@
this.curatedContent = this.contentListToRender.slice(0,6);
this.latestContent = this.contentListToRender.slice(0,3);
+
+ this.resolveViewTemplateName = function () {
+ return request.path.replace(this.taxonSlug, '').replace(/^\//, '') + this.selectedTab;
+ };
+ this.viewTemplateName = this.resolveViewTemplateName();
}
module.exports = TaxonPresenter; |
475c73ef704c672965f8efad70334e202e483db0 | src/js/index.js | src/js/index.js | "use strict";
var LocalStorageUtils = require("./utils/LocalStorageUtils");
var StateIds = require("./states/States");
var InitializeState = require("./states/InitializeState");
var MenuState = require("./states/MenuState");
var SettingsState = require("./states/SettingsState");
var LoadingState = require("./states/LoadingState");
var GameState = require("./states/GameState")
var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.CANVAS, 'phaser-example');
window.Game = game;
window.onresize = function() {
Game.scale.setGameSize(window.innerWidth, window.innerHeight);
}
game.state.add(StateIds.INITIALIZE_STATE_ID, new InitializeState(game), true);
game.state.add(StateIds.MENU_STATE_ID, new MenuState(game));
game.state.add(StateIds.SETTINGS_STATE_ID, new SettingsState(game));
game.state.add(StateIds.LOADING_STATE_ID, new LoadingState(game));
game.state.add(StateIds.LOADING_STATE_ID, new GameState(game)); | "use strict";
var LocalStorageUtils = require("./utils/LocalStorageUtils");
var StateIds = require("./states/States");
var InitializeState = require("./states/InitializeState");
var MenuState = require("./states/MenuState");
var SettingsState = require("./states/SettingsState");
var LoadingState = require("./states/LoadingState");
var GameState = require("./states/GameState")
var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.CANVAS, 'phaser-example');
window.Game = game;
window.onresize = function() {
Game.scale.setGameSize(window.innerWidth, window.innerHeight);
}
game.state.add(StateIds.INITIALIZE_STATE_ID, new InitializeState(game), true);
game.state.add(StateIds.MENU_STATE_ID, new MenuState(game));
game.state.add(StateIds.SETTINGS_STATE_ID, new SettingsState(game));
game.state.add(StateIds.LOADING_STATE_ID, new LoadingState(game));
game.state.add(StateIds.GAME_STATE_ID, new GameState(game)); | Fix passed id of state add | Fix passed id of state add
| JavaScript | mit | Morathil/ranggln,Morathil/ranggln,Morathil/ranggln,Morathil/ranggln | ---
+++
@@ -20,4 +20,4 @@
game.state.add(StateIds.MENU_STATE_ID, new MenuState(game));
game.state.add(StateIds.SETTINGS_STATE_ID, new SettingsState(game));
game.state.add(StateIds.LOADING_STATE_ID, new LoadingState(game));
-game.state.add(StateIds.LOADING_STATE_ID, new GameState(game));
+game.state.add(StateIds.GAME_STATE_ID, new GameState(game)); |
29e565d176c2a2cff221909fdb4c1fd566a0ddf3 | test/spec/test_captcha.js | test/spec/test_captcha.js | /**
* Created by sonja on 10/29/16.
*/
| describe("The constructor is supposed a proper Captcha object", function() {
it('Constructor Captcha exists', function(){
expect(Captcha).toBeDefined();
});
});
| Add first javascript test and make the test pass | Add first javascript test and make the test pass
| JavaScript | mit | sonjahohlfeld/Captcha-Generator,sonjahohlfeld/Captcha-Generator | ---
+++
@@ -1,3 +1,5 @@
-/**
- * Created by sonja on 10/29/16.
- */
+describe("The constructor is supposed a proper Captcha object", function() {
+ it('Constructor Captcha exists', function(){
+ expect(Captcha).toBeDefined();
+ });
+}); |
ccdb86e55c3dbfb673344e141bc068b83056c782 | test/spec/test_captcha.js | test/spec/test_captcha.js | describe("The constructor is supposed a proper Captcha object", function() {
it('Constructor Captcha exists', function(){
expect(Captcha).toBeDefined();
});
var captcha = new Captcha();
it("Captcha object is not null", function(){
expect(captcha).not.toBeNull();
});
});
| describe("The constructor is supposed a proper Captcha object", function() {
it('Constructor Captcha exists', function(){
expect(Captcha).toBeDefined();
});
var captcha = new Captcha();
it("Captcha object is not null", function(){
expect(captcha).not.toBeNull();
});
it('captcha object should be an instance of Captcha class', function(){
expect(captcha instanceof Captcha).toBeTruthy();
});
});
| Add test if captcha is instance of Captcha class | Add test if captcha is instance of Captcha class
| JavaScript | mit | sonjahohlfeld/Captcha-Generator,sonjahohlfeld/Captcha-Generator | ---
+++
@@ -6,4 +6,7 @@
it("Captcha object is not null", function(){
expect(captcha).not.toBeNull();
});
+ it('captcha object should be an instance of Captcha class', function(){
+ expect(captcha instanceof Captcha).toBeTruthy();
+ });
}); |
c60b623bc4941fce71c1594db7a554d5ba42a5d4 | webapp/src/components/molecules/highcharts/themes.js | webapp/src/components/molecules/highcharts/themes.js | export default {
standard: {
credits: { enabled: false },
chart: {
style: {
fontFamily: "'proxima', 'Helvetica', sans-serif' "
}
},
title: ''
}
}
| export default {
standard: {
credits: { enabled: false },
chart: {
style: {
fontFamily: "'proxima', 'Helvetica', sans-serif' ",
paddingTop: '20px' // Make room for buttons
}
},
exporting: {
buttons: {
contextButton: {
symbol: null,
text: 'Export',
x: -20,
y: -30,
theme: {
style: {
color: '#039',
textDecoration: 'underline'
}
}
}
}
},
title: ''
}
}
| Move export button in all Highcharts | Move export button in all Highcharts
| JavaScript | agpl-3.0 | unicef/rhizome,unicef/rhizome,unicef/rhizome,unicef/rhizome | ---
+++
@@ -3,7 +3,24 @@
credits: { enabled: false },
chart: {
style: {
- fontFamily: "'proxima', 'Helvetica', sans-serif' "
+ fontFamily: "'proxima', 'Helvetica', sans-serif' ",
+ paddingTop: '20px' // Make room for buttons
+ }
+ },
+ exporting: {
+ buttons: {
+ contextButton: {
+ symbol: null,
+ text: 'Export',
+ x: -20,
+ y: -30,
+ theme: {
+ style: {
+ color: '#039',
+ textDecoration: 'underline'
+ }
+ }
+ }
}
},
title: '' |
156200098a3e7feada08a41ea7c4da14f049f86d | src/desktop/apps/categories/components/FeaturedGenes.js | src/desktop/apps/categories/components/FeaturedGenes.js | import React from "react"
import PropTypes from "prop-types"
import styled from "styled-components"
import FeaturedGene from "./FeaturedGene"
const propTypes = {
featuredGeneLinks: PropTypes.array,
}
const Layout = styled.div`
display: none;
@media (min-width: 768px) {
display: block;
padding-top: 1em;
column-count: 3;
column-gap: 2em;
}
`
const FeaturedGenes = ({ featuredGeneLinks }) => {
return (
<Layout>
{featuredGeneLinks &&
featuredGeneLinks.length > 0 &&
featuredGeneLinks
.map(featuredGene => (
<FeaturedGene key={featuredGene.id} {...featuredGene} />
))
.slice(0, 3)}
</Layout>
)
}
FeaturedGenes.propTypes = propTypes
export default FeaturedGenes
| import React from "react"
import PropTypes from "prop-types"
import styled from "styled-components"
import FeaturedGene from "./FeaturedGene"
const propTypes = {
featuredGeneLinks: PropTypes.array,
}
const Layout = styled.div`
display: none;
@media (min-width: 768px) {
display: block;
padding-top: 1em;
column-count: 3;
column-gap: 2em;
}
`
const FeaturedGenes = ({ featuredGeneLinks }) => {
return (
<Layout>
{featuredGeneLinks &&
featuredGeneLinks.length > 0 &&
featuredGeneLinks
.map(featuredGene => (
<FeaturedGene key={featuredGene.href} {...featuredGene} />
))
.slice(0, 3)}
</Layout>
)
}
FeaturedGenes.propTypes = propTypes
export default FeaturedGenes
| Add valid key for .map'd FeaturedGene components | Add valid key for .map'd FeaturedGene components
| JavaScript | mit | joeyAghion/force,oxaudo/force,artsy/force-public,artsy/force,eessex/force,eessex/force,oxaudo/force,joeyAghion/force,joeyAghion/force,artsy/force-public,artsy/force,oxaudo/force,eessex/force,joeyAghion/force,eessex/force,artsy/force,artsy/force,oxaudo/force | ---
+++
@@ -26,7 +26,7 @@
featuredGeneLinks.length > 0 &&
featuredGeneLinks
.map(featuredGene => (
- <FeaturedGene key={featuredGene.id} {...featuredGene} />
+ <FeaturedGene key={featuredGene.href} {...featuredGene} />
))
.slice(0, 3)}
</Layout> |
f92a511cd9e63e66bb92a1b68c9882ce567e5d11 | src/reducers/PrescriptionReducer.js | src/reducers/PrescriptionReducer.js | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { ROUTES } from '../navigation/constants';
import { UIDatabase } from '../database';
import { PRESCRIPTION_ACTIONS } from '../actions/PrescriptionActions';
const initialState = () => ({
currentTab: 0,
transaction: null,
items: UIDatabase.objects('Item'),
itemSearchTerm: '',
commentModalOpen: false,
});
export const PrescriptionReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case 'Navigation/NAVIGATE': {
const { routeName, params } = action;
if (routeName !== ROUTES.PRESCRIPTION) return state;
const { transaction } = params;
return { ...state, transaction };
}
case PRESCRIPTION_ACTIONS.REFRESH: {
return { ...state };
}
case PRESCRIPTION_ACTIONS.FILTER: {
const { payload } = action;
const { itemSearchTerm } = payload;
return { ...state, itemSearchTerm };
}
case PRESCRIPTION_ACTIONS.OPEN_COMMENT_MODAL: {
return { ...state, commentModalOpen: true };
}
case PRESCRIPTION_ACTIONS.CLOSE_COMMENT_MODAL: {
return { ...state, commentModalOpen: false };
}
case PRESCRIPTION_ACTIONS.DELETE:
return { ...state, transaction: null };
default: {
return state;
}
}
};
| /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { ROUTES } from '../navigation/constants';
import { UIDatabase } from '../database';
import { PRESCRIPTION_ACTIONS } from '../actions/PrescriptionActions';
const initialState = () => ({
currentTab: 0,
transaction: null,
items: UIDatabase.objects('Item').filtered('isVaccine != true'),
itemSearchTerm: '',
commentModalOpen: false,
});
export const PrescriptionReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case 'Navigation/NAVIGATE': {
const { routeName, params } = action;
if (routeName !== ROUTES.PRESCRIPTION) return state;
const { transaction } = params;
return { ...state, transaction };
}
case PRESCRIPTION_ACTIONS.REFRESH: {
return { ...state };
}
case PRESCRIPTION_ACTIONS.FILTER: {
const { payload } = action;
const { itemSearchTerm } = payload;
return { ...state, itemSearchTerm };
}
case PRESCRIPTION_ACTIONS.OPEN_COMMENT_MODAL: {
return { ...state, commentModalOpen: true };
}
case PRESCRIPTION_ACTIONS.CLOSE_COMMENT_MODAL: {
return { ...state, commentModalOpen: false };
}
case PRESCRIPTION_ACTIONS.DELETE:
return { ...state, transaction: null };
default: {
return state;
}
}
};
| Remove vaccines from normal dispensing window | Remove vaccines from normal dispensing window
| JavaScript | mit | sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile | ---
+++
@@ -10,7 +10,7 @@
const initialState = () => ({
currentTab: 0,
transaction: null,
- items: UIDatabase.objects('Item'),
+ items: UIDatabase.objects('Item').filtered('isVaccine != true'),
itemSearchTerm: '',
commentModalOpen: false,
}); |
ed781120958633b55223525533b287964393dc49 | plugins/wired.js | plugins/wired.js | var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Wired',
version:'0.1',
prepareImgLinks:function (callback) {
var res = [];
hoverZoom.urlReplace(res,
'img',
/-\d+x\d+\./,
'.'
);
hoverZoom.urlReplace(res,
'img[src*="/thumbs/"]',
'thumbs/thumbs_',
''
);
hoverZoom.urlReplace(res,
'img[src*="_w"]',
/_wd?\./,
'_bg.'
);
callback($(res));
}
});
| var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Wired',
version:'0.2',
prepareImgLinks:function (callback) {
var res = [];
hoverZoom.urlReplace(res,
'img',
/-\d+x\d+\./,
'.'
);
hoverZoom.urlReplace(res,
'img[src*="/thumbs/"]',
'thumbs/thumbs_',
''
);
hoverZoom.urlReplace(res,
'img[src*="_w"]',
/_wd?\./,
'_bg.'
);
$('img[src]').each(function() {
var url = this.src;
try {
// decode ASCII characters, for instance: '%2C' -> ','
// NB: this operation mustbe try/catched because url might not be well-formed
var fullsizeUrl = decodeURIComponent(url);
fullsizeUrl = fullsizeUrl.replace(/\/1:1(,.*?)?\//, '/').replace(/\/16:9(,.*?)?\//, '/').replace(/\/[wW]_?\d+(,.*?)?\//, '/').replace(/\/[hH]_?\d+(,.*?)?\//, '/').replace(/\/[qQ]_?\d+(,.*?)?\//, '/').replace(/\/q_auto(,.*?)?\//, '/').replace(/\/c_limit(,.*?)?\//, '/').replace(/\/c_scale(,.*?)?\//, '/').replace(/\/c_fill(,.*?)?\//, '/').replace(/\/f_auto(,.*?)?\//, '/');
if (fullsizeUrl != url) {
var link = $(this);
if (link.data().hoverZoomSrc == undefined) { link.data().hoverZoomSrc = [] }
if (link.data().hoverZoomSrc.indexOf(fullsizeUrl) == -1) {
link.data().hoverZoomSrc.unshift(fullsizeUrl);
res.push(link);
}
}
}
catch(e) {}
});
callback($(res), this.name);
}
});
| Update for plug-in : WiReD | Update for plug-in : WiReD
| JavaScript | mit | extesy/hoverzoom,extesy/hoverzoom | ---
+++
@@ -1,24 +1,47 @@
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Wired',
- version:'0.1',
+ version:'0.2',
prepareImgLinks:function (callback) {
var res = [];
+
hoverZoom.urlReplace(res,
'img',
/-\d+x\d+\./,
'.'
);
+
hoverZoom.urlReplace(res,
'img[src*="/thumbs/"]',
'thumbs/thumbs_',
''
);
+
hoverZoom.urlReplace(res,
'img[src*="_w"]',
/_wd?\./,
'_bg.'
);
- callback($(res));
+
+ $('img[src]').each(function() {
+ var url = this.src;
+ try {
+ // decode ASCII characters, for instance: '%2C' -> ','
+ // NB: this operation mustbe try/catched because url might not be well-formed
+ var fullsizeUrl = decodeURIComponent(url);
+ fullsizeUrl = fullsizeUrl.replace(/\/1:1(,.*?)?\//, '/').replace(/\/16:9(,.*?)?\//, '/').replace(/\/[wW]_?\d+(,.*?)?\//, '/').replace(/\/[hH]_?\d+(,.*?)?\//, '/').replace(/\/[qQ]_?\d+(,.*?)?\//, '/').replace(/\/q_auto(,.*?)?\//, '/').replace(/\/c_limit(,.*?)?\//, '/').replace(/\/c_scale(,.*?)?\//, '/').replace(/\/c_fill(,.*?)?\//, '/').replace(/\/f_auto(,.*?)?\//, '/');
+ if (fullsizeUrl != url) {
+ var link = $(this);
+ if (link.data().hoverZoomSrc == undefined) { link.data().hoverZoomSrc = [] }
+ if (link.data().hoverZoomSrc.indexOf(fullsizeUrl) == -1) {
+ link.data().hoverZoomSrc.unshift(fullsizeUrl);
+ res.push(link);
+ }
+ }
+ }
+ catch(e) {}
+ });
+
+ callback($(res), this.name);
}
}); |
f22843697d00cc4bf1c660b9a89fc8f136845d5c | src/views/loggedin/loggedin-view.js | src/views/loggedin/loggedin-view.js | import { View, __, Sidebar, ViewManager, NavBar } from 'erste';
import MainView from '../main-view';
class LoggedInView extends View {
constructor() {
super();
this.navBar = new NavBar({
title: __('Welcome to beveteran'),
hasMenuButton: true,
hasBackButton: true
});
}
onActivation() {
if (cfg.PLATFORM == 'device')
StatusBar.styleDefault();
}
finderButtonTap(e) {
var finderView = new FinderView();
finderView.vm = this.vm;
this.vm.pull(finderView, true);
};
hiderButtonTap(e) {
var hinderView = new HinderView();
hinderView.vm = this.vm;
this.vm.pull(hinderView, true);
};
get events() {
return {
'tap': {
'.finder': this.finderButtonTap,
'.hider': this.hiderButtonTap,
}
}
}
template() {
return `
<view>
${this.navBar}
<div class="logedin">
<div class="imgcontainer">
<img src="static/img/logo.png" alt="Avatar" class="logo">
</div>
<div class="buttons">
<button type="button" class="hider"> be a hider verteran</button>
<button type="button" class="finder"> be a finder verteran</button>
</div>
</div>
</view>
`;
}
}
module.exports = LoggedInView; | import { View, __, Sidebar, ViewManager, NavBar } from 'erste';
import MainView from '../main-view';
class LoggedInView extends View {
constructor() {
super();
this.navBar = new NavBar({
title: __('Welcome to beveteran'),
hasMenuButton: true,
hasBackButton: true
});
this.hasSidebar = true;
}
onActivation() {
if (cfg.PLATFORM == 'device')
StatusBar.styleDefault();
}
finderButtonTap(e) {
var finderView = new FinderView();
finderView.vm = this.vm;
this.vm.pull(finderView, true);
};
hiderButtonTap(e) {
var hinderView = new HinderView();
hinderView.vm = this.vm;
this.vm.pull(hinderView, true);
};
get events() {
return {
'tap': {
'.finder': this.finderButtonTap,
'.hider': this.hiderButtonTap,
}
}
}
template() {
return `
<view>
${this.navBar}
<div class="logedin">
<div class="imgcontainer">
<img src="static/img/logo.png" alt="Avatar" class="logo">
</div>
<div class="buttons">
<button type="button" class="hider"> be a hider verteran</button>
<button type="button" class="finder"> be a finder verteran</button>
</div>
</div>
</view>
`;
}
}
module.exports = LoggedInView; | Add hasSidebar to LoggedInView to use the drag gesture to reveal the menu | Add hasSidebar to LoggedInView to use the drag gesture to reveal the menu
| JavaScript | mit | korayguney/veteranteam_project,zekicelik/veteranteam_project,zekicelik/veteranteam_project,korayguney/veteranteam_project | ---
+++
@@ -11,6 +11,7 @@
hasBackButton: true
});
+ this.hasSidebar = true;
}
onActivation() { |
9733b718f083bf0d82ea0c75d957b81301ea8666 | test/drag/drag.js | test/drag/drag.js | steal("../../browser/jquery", "jquerypp/index.js", function($){
window.jQuery = $;
var hoveredOnce = false;
$(".over").bind('mouseover',function(){
if (!hoveredOnce) {
$(this).addClass('hover')
$(document.body).append("<input type='text' id='typer' />")
hoveredOnce = true;
}
})
$('#drag')
.on("draginit", function(){})
$('#drop')
.on("dropover", function(){
$(document.body).append("<a href='#' id='clicker'>click</a>")
$("#clicker").click(function(){
$(".status").html("dragged")
})
})
})
| steal("jquerypp/index.js", function($){
window.jQuery = $;
var hoveredOnce = false;
$(".over").bind('mouseover',function(){
if (!hoveredOnce) {
$(this).addClass('hover')
$(document.body).append("<input type='text' id='typer' />")
hoveredOnce = true;
}
})
$('#drag')
.on("draginit", function(){})
$('#drop')
.on("dropover", function(){
$(document.body).append("<a href='#' id='clicker'>click</a>")
$("#clicker").click(function(){
$(".status").html("dragged")
})
})
})
| Fix the funcunit-syn integration “Drag To” test | Fix the funcunit-syn integration “Drag To” test
Dragging & dropping works because of jQuery++, so its version of jQuery had to be referenced instead of the `browser/jquery` import.
| JavaScript | mit | bitovi/funcunit,bitovi/funcunit,bitovi/funcunit | ---
+++
@@ -1,4 +1,4 @@
-steal("../../browser/jquery", "jquerypp/index.js", function($){
+steal("jquerypp/index.js", function($){
window.jQuery = $;
var hoveredOnce = false; |
44e38454ad1412a798f1e25a56155458f788c953 | test/lint-test.js | test/lint-test.js | import 'lint-tests'; // eslint-disable-line
| import 'lint-tests'; // eslint-disable-line
import assert from 'assert';
import Client from '../src/client';
suite('manual-lint-test', () => {
const config = {
domain: 'sendmecats.myshopify.com',
storefrontAccessToken: 'abc123'
};
test('it ensures that all Connections include pageInfo', () => {
const client = Client.buildClient(config);
const objectTypes = client.graphQLClient.typeBundle.types;
for (const key in objectTypes) {
if (objectTypes.hasOwnProperty(key) && key.includes('Connection')) {
assert.equal(objectTypes[key].fieldBaseTypes.pageInfo, 'PageInfo');
}
}
});
});
| Validate that all Connections include PageInfo | Validate that all Connections include PageInfo
| JavaScript | mit | Shopify/js-buy-sdk,Shopify/js-buy-sdk | ---
+++
@@ -1 +1,22 @@
import 'lint-tests'; // eslint-disable-line
+
+import assert from 'assert';
+import Client from '../src/client';
+
+suite('manual-lint-test', () => {
+ const config = {
+ domain: 'sendmecats.myshopify.com',
+ storefrontAccessToken: 'abc123'
+ };
+
+ test('it ensures that all Connections include pageInfo', () => {
+ const client = Client.buildClient(config);
+ const objectTypes = client.graphQLClient.typeBundle.types;
+
+ for (const key in objectTypes) {
+ if (objectTypes.hasOwnProperty(key) && key.includes('Connection')) {
+ assert.equal(objectTypes[key].fieldBaseTypes.pageInfo, 'PageInfo');
+ }
+ }
+ });
+}); |
af4d63748c74c4d6105de099b3d7ff88af708d1b | src/app/modules/source-converter/source-converter.js | src/app/modules/source-converter/source-converter.js | define([
'marked',
'to-markdown'
], function (
marked,
tomarkdown
) {
'use strict';
return (function() {
var toHTML = function(src) {
marked.setOptions({
breaks: true,
table: false
});
return marked(src);
};
var toMarkdown = function(src) {
return tomarkdown(src);
};
return {
toHTML : toHTML,
toMarkdown : toMarkdown
};
})();
});
| define([
'marked',
'to-markdown'
], function (
marked,
tomarkdown
) {
'use strict';
return (function() {
var toHTML = function(src) {
marked.setOptions({
breaks: true,
tables: false
});
return marked(src);
};
var toMarkdown = function(src) {
return tomarkdown(src);
};
return {
toHTML : toHTML,
toMarkdown : toMarkdown
};
})();
});
| Fix marked table options setting | Fix marked table options setting
| JavaScript | mit | moneyadviceservice/cms-editor,moneyadviceservice/cms-editor | ---
+++
@@ -10,7 +10,7 @@
var toHTML = function(src) {
marked.setOptions({
breaks: true,
- table: false
+ tables: false
});
return marked(src);
}; |
6ebf3b012f41bc222ef96b22cb55b8398db313d5 | route/index.js | route/index.js | 'use strict';
module.exports = defineRoute;
// Define the route
function defineRoute (server, opts) {
server.route({
method: 'GET',
path: '/',
handler: handler,
config: {
jsonp: 'callback',
validate: {
query: {},
payload: false
}
}
});
function handler (req) {
req.reply({
endpoints: [
{
method: 'GET',
endpoint: '/' + opts.plural,
description: 'Get all ' + opts.plural
},
{
method: 'GET',
endpoint: '/' + opts.plural + '/{id}',
description: 'Get a single ' + opts.singular + ' by id'
},
{
method: 'GET',
endpoint: '/random',
description: 'Get a random ' + opts.singular
},
{
method: 'GET',
endpoint: '/bomb?count={n}',
description: 'Get multiple random ' + opts.plural
}
]
});
}
}
| 'use strict';
module.exports = defineRoute;
// Define the route
function defineRoute (server, opts) {
server.route({
method: 'GET',
path: '/',
handler: handler,
config: {
jsonp: 'callback',
validate: {
query: {},
payload: false
}
}
});
function handler (req) {
var host = req.info.host;
var exampleId = (opts.things[0] ? opts.things[0].id : 1);
req.reply({
endpoints: [
{
method: 'GET',
endpoint: '/' + opts.plural,
description: 'Get all ' + opts.plural,
example: 'http://' + host + '/' + opts.plural
},
{
method: 'GET',
endpoint: '/' + opts.plural + '/{id}',
description: 'Get a single ' + opts.singular + ' by id',
example: 'http://' + host + '/' + opts.plural + '/' + exampleId
},
{
method: 'GET',
endpoint: '/random',
description: 'Get a random ' + opts.singular,
example: 'http://' + host + '/random'
},
{
method: 'GET',
endpoint: '/bomb?count={n}',
description: 'Get multiple random ' + opts.plural,
example: 'http://' + host + '/bomb?count=3'
}
]
});
}
}
| Add examples to the endpoint documentation | Add examples to the endpoint documentation
| JavaScript | mit | rowanmanning/thingme | ---
+++
@@ -19,27 +19,33 @@
});
function handler (req) {
+ var host = req.info.host;
+ var exampleId = (opts.things[0] ? opts.things[0].id : 1);
req.reply({
endpoints: [
{
method: 'GET',
endpoint: '/' + opts.plural,
- description: 'Get all ' + opts.plural
+ description: 'Get all ' + opts.plural,
+ example: 'http://' + host + '/' + opts.plural
},
{
method: 'GET',
endpoint: '/' + opts.plural + '/{id}',
- description: 'Get a single ' + opts.singular + ' by id'
+ description: 'Get a single ' + opts.singular + ' by id',
+ example: 'http://' + host + '/' + opts.plural + '/' + exampleId
},
{
method: 'GET',
endpoint: '/random',
- description: 'Get a random ' + opts.singular
+ description: 'Get a random ' + opts.singular,
+ example: 'http://' + host + '/random'
},
{
method: 'GET',
endpoint: '/bomb?count={n}',
- description: 'Get multiple random ' + opts.plural
+ description: 'Get multiple random ' + opts.plural,
+ example: 'http://' + host + '/bomb?count=3'
}
]
}); |
a187f52b79e62b1d657bfa314c6c32847881f7a1 | routes/item.js | routes/item.js | var Item = require('../models/item').Item;
var ItemTypes = require('../models/item').ItemTypes;
var ItemStates = require('../models/item').ItemStates;
var ItemTypeIcons = require('../models/item').ItemTypeIcons;
exports.changeState = function(req, res) {
Item.findById(req.query.id, function(err, item) {
if (err) {
res.redirect('/error', { error: err });
} else {
item.state = req.query.state; //TODO vulnerability (validate)
if (item.state === ItemStates.finished)
item.planNextCheck(0); /// Cancel next check, if any.
else
item.planNextCheck(1);
item.save(function(err) {
if (err) {
console.log(err);
res.redirect('/error', { error: err });
}
}); //TODO log
res.redirect('/list');
}
});
};
| var notifier = require('./notifier');
var xbmc = require('../notifiers/xbmc');
notifier.use(xbmc);
var Item = require('../models/item').Item;
var ItemTypes = require('../models/item').ItemTypes;
var ItemStates = require('../models/item').ItemStates;
var ItemTypeIcons = require('../models/item').ItemTypeIcons;
exports.changeState = function(req, res) {
Item.findById(req.query.id, function(err, item) {
if (err) {
res.redirect('/error', { error: err });
} else {
item.state = req.query.state; //TODO vulnerability (validate)
if (item.state === ItemStates.finished) {
item.planNextCheck(0); /// Cancel next check, if any.
notifier.updateLibrary(item);
} else {
item.planNextCheck(1);
}
item.save(function(err) {
if (err) {
console.log(err);
res.redirect('/error', { error: err });
}
}); //TODO log
res.redirect('/list');
}
});
};
| Update library on finish state manual set. | Update library on finish state manual set. | JavaScript | mit | ziacik/lumus,ziacik/lumus,ziacik/lumus | ---
+++
@@ -1,3 +1,8 @@
+var notifier = require('./notifier');
+var xbmc = require('../notifiers/xbmc');
+
+notifier.use(xbmc);
+
var Item = require('../models/item').Item;
var ItemTypes = require('../models/item').ItemTypes;
var ItemStates = require('../models/item').ItemStates;
@@ -10,10 +15,12 @@
} else {
item.state = req.query.state; //TODO vulnerability (validate)
- if (item.state === ItemStates.finished)
+ if (item.state === ItemStates.finished) {
item.planNextCheck(0); /// Cancel next check, if any.
- else
+ notifier.updateLibrary(item);
+ } else {
item.planNextCheck(1);
+ }
item.save(function(err) {
if (err) { |
ca92ad2e97cde2a9e939abc7a12aa914970e0d9b | tests/helper.js | tests/helper.js | var bs = require('../lib/beanstalk_client');
var net = require('net');
var port = process.env.BEANSTALK_PORT || 11333;
var mock = process.env.BEANSTALKD !== '1';
var mock_server;
var connection;
module.exports = {
bind : function (fn, closeOnEnd) {
if(!mock) {
return false;
}
mock_server = net.createServer(function(conn) {
connection = conn;
connection.on('data', function (data) {
fn.call(mock_server, connection, data);
});
if(closeOnEnd === true) {
closeOnEnd = function () {
mock_server.close();
}
}
if(closeOnEnd) {
connection.on('end', function () {
closeOnEnd.call(mock_server);
});
}
});
mock_server.listen(port);
},
getClient : function () {
return bs.Client('127.0.0.1:' + port);
}
} | var bs = require('../lib/beanstalk_client');
var net = require('net');
var port = process.env.BEANSTALK_PORT || 11333;
var mock = process.env.BEANSTALKD !== '1';
var mock_server;
var connection;
module.exports = {
bind : function (fn, closeOnEnd) {
if(!mock) {
return false;
}
mock_server = net.createServer(function(conn) {
connection = conn;
connection.on('data', function (data) {
fn.call(mock_server, connection, data);
});
if(closeOnEnd === true) {
closeOnEnd = function () {
mock_server.close();
}
}
if(closeOnEnd) {
connection.on('end', function () {
closeOnEnd.call(mock_server);
});
}
});
mock_server.listen(port);
},
getClient : function () {
return bs.Client('127.0.0.1:' + port);
},
activateDebug : function() {
bs.Debug.activate();
}
} | Add switch to activate debug in tests | Add switch to activate debug in tests
Helpful in developing tests
| JavaScript | mit | pascalopitz/nodestalker | ---
+++
@@ -39,5 +39,8 @@
},
getClient : function () {
return bs.Client('127.0.0.1:' + port);
+ },
+ activateDebug : function() {
+ bs.Debug.activate();
}
} |
1bbd54e1fbedeb337fd33610ead89d81e6ecf2c9 | text/boolean.js | text/boolean.js | 'use strict';
var d = require('es5-ext/lib/Object/descriptor')
, Db = require('dbjs')
, DOMText = require('./_text')
, getValue = Object.getOwnPropertyDescriptor(DOMText.prototype, 'value').get
, Base = Db.Base
, Text;
Text = function (document, ns) {
this.document = document;
this.ns = ns;
this.text = new DOMText(document, Base);
this.dom = this.text.dom;
};
Text.prototype = Object.create(DOMText.prototype, {
constructor: d(Text),
value: d.gs(getValue, function (value) {
if (value == null) {
this.text.dismiss();
this.text.value = value;
return;
}
this.ns[value.valueOf() ? '_trueLabel' : '_falseLabel']
.assignDOMText(this.text);
})
});
module.exports = Object.defineProperty(Db.Boolean, 'DOMText', d(Text));
| 'use strict';
var d = require('es5-ext/lib/Object/descriptor')
, Db = require('dbjs')
, DOMText = require('./_text')
, getValue = Object.getOwnPropertyDescriptor(DOMText.prototype, 'value').get
, Base = Db.Base
, Text;
Text = function (document, ns, options) {
this.document = document;
this.ns = ns;
this.relation = options && options.relation;
this.text = new DOMText(document, Base);
this.dom = this.text.dom;
};
Text.prototype = Object.create(DOMText.prototype, {
constructor: d(Text),
value: d.gs(getValue, function (value) {
var rel;
if (value == null) {
this.text.dismiss();
this.text.value = value;
return;
}
if (value.valueOf()) {
rel = (this.relation && this.relation.__trueLabel.__value) ?
this.relation._trueLabel : this.ns._trueLabel;
} else {
rel = (this.relation && this.relation.__falseLabel.__value) ?
this.relation._falseLabel : this.ns._falseLabel;
}
rel.assignDOMText(this.text);
})
});
module.exports = Object.defineProperty(Db.Boolean, 'DOMText', d(Text));
| Use labels definied on relation if available | Use labels definied on relation if available
| JavaScript | mit | medikoo/dbjs-dom | ---
+++
@@ -8,9 +8,10 @@
, Base = Db.Base
, Text;
-Text = function (document, ns) {
+Text = function (document, ns, options) {
this.document = document;
this.ns = ns;
+ this.relation = options && options.relation;
this.text = new DOMText(document, Base);
this.dom = this.text.dom;
};
@@ -18,13 +19,20 @@
Text.prototype = Object.create(DOMText.prototype, {
constructor: d(Text),
value: d.gs(getValue, function (value) {
+ var rel;
if (value == null) {
this.text.dismiss();
this.text.value = value;
return;
}
- this.ns[value.valueOf() ? '_trueLabel' : '_falseLabel']
- .assignDOMText(this.text);
+ if (value.valueOf()) {
+ rel = (this.relation && this.relation.__trueLabel.__value) ?
+ this.relation._trueLabel : this.ns._trueLabel;
+ } else {
+ rel = (this.relation && this.relation.__falseLabel.__value) ?
+ this.relation._falseLabel : this.ns._falseLabel;
+ }
+ rel.assignDOMText(this.text);
})
});
|
21c51b43e81696fd90510a8690b0d86d2e03999f | app/users/user-links.directive.js | app/users/user-links.directive.js | {
angular
.module('meganote.users')
.directive('userLinks', [
'CurrentUser',
(CurrentUser) => {
class UserLinksController {
user() {
return CurrentUser.get();
}
signedIn() {
return CurrentUser.signedIn();
}
}
return {
scope: {},
controller: UserLinksController,
controllerAs: 'vm',
bindToController: true,
template: `
<div class="user-links" ng-show="vm.signedIn()">
Signed in as {{ vm.user().name }}
</div>`,
};
}]);
}
| {
angular
.module('meganote.users')
.directive('userLinks', [
'CurrentUser',
(CurrentUser) => {
class UserLinksController {
user() {
return CurrentUser.get();
}
signedIn() {
return CurrentUser.signedIn();
}
}
return {
scope: {},
controller: UserLinksController,
controllerAs: 'vm',
bindToController: true,
template: `
<div class="user-links">
<span ng-show="vm.signedIn()">
Signed in as {{ vm.user().name }}
</span>
<span ng-hide="vm.signedIn()">
<a ui-sref="sign-up">Sign up for Meganote today!</a>
</span>
</div>`,
};
}]);
}
| Add sign up link that shows if no user is signed in | Add sign up link that shows if no user is signed in
| JavaScript | mit | sbaughman/meganote,sbaughman/meganote | ---
+++
@@ -22,8 +22,13 @@
controllerAs: 'vm',
bindToController: true,
template: `
- <div class="user-links" ng-show="vm.signedIn()">
- Signed in as {{ vm.user().name }}
+ <div class="user-links">
+ <span ng-show="vm.signedIn()">
+ Signed in as {{ vm.user().name }}
+ </span>
+ <span ng-hide="vm.signedIn()">
+ <a ui-sref="sign-up">Sign up for Meganote today!</a>
+ </span>
</div>`,
};
}]); |
2ab9cc689d2c32c15565ea8a46d5ad8841ea5942 | tests/plugins/markdown.js | tests/plugins/markdown.js | import test from 'ava';
import {fromString} from '../helpers/pipe';
import markdown from '../../lib/plugins/markdown';
test('Compiles Markdown - .md', t => {
const input = '# Hello World';
const expected = '<h1>Hello World</h1>\n';
return fromString(input, 'markdown/hello.md', markdown)
.then(output => {
t.is(output, expected, 'Markdown compiles as expected');
});
});
test('Compiles Markdown - .markdown', t => {
const input = '# Hello World';
const expected = '<h1>Hello World</h1>\n';
return fromString(input, 'markdown/hello.markdown', markdown)
.then(output => {
t.is(output, expected, 'Markdown compiles as expected');
});
});
test('No Compile - .html', t => {
const input = '# Hello World';
const expected = '# Hello World';
return fromString(input, 'markdown/hello.html', markdown)
.then(output => {
t.is(output, expected, 'Markdown compiles as expected');
});
});
| import test from 'ava';
import {fromString, fromNull, fromStream} from '../helpers/pipe';
import markdown from '../../lib/plugins/markdown';
test('Compiles Markdown - .md', t => {
const input = '# Hello World';
const expected = '<h1>Hello World</h1>\n';
return fromString(input, 'markdown/hello.md', markdown)
.then(output => {
t.is(output, expected, 'Markdown compiles as expected');
});
});
test('Compiles Markdown - .markdown', t => {
const input = '# Hello World';
const expected = '<h1>Hello World</h1>\n';
return fromString(input, 'markdown/hello.markdown', markdown)
.then(output => {
t.is(output, expected, 'Markdown compiles as expected');
});
});
test('Compiles Markdown with Custom Plugin', t => {
const input = '@[Taylor Swift - Shake it Off](https://www.youtube.com/watch?v=nfWlot6h_JM)';
const expected = `<p><div class=\"flexible-video\"><iframe src=\"https://www.youtube.com/embed/nfWlot6h_JM\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen></iframe></div></p>\n`;
return fromString(input, 'shake/it/off.md', markdown)
.then(output => {
t.is(output, expected, 'Markdown compiles as expected');
});
});
test('No Compile - .html', t => {
const input = '# Hello World';
const expected = '# Hello World';
return fromString(input, 'markdown/hello.html', markdown)
.then(output => {
t.is(output, expected, 'Markdown compiles as expected');
});
});
test('No Compile - null', t => {
return fromNull(markdown)
.then(output => {
t.is(output, '', 'No output');
});
});
test('Error - is stream', t => {
t.throws(fromStream(markdown));
});
| Add Custom Plugin and No Compile | :white_check_mark: Add Custom Plugin and No Compile
* Make sure custom plugins are used when rendering Markdown
* Add test for null file
* Add test for streams that throw errors
| JavaScript | mit | kellychurchill/gulp-armadillo,Snugug/gulp-armadillo | ---
+++
@@ -1,5 +1,5 @@
import test from 'ava';
-import {fromString} from '../helpers/pipe';
+import {fromString, fromNull, fromStream} from '../helpers/pipe';
import markdown from '../../lib/plugins/markdown';
test('Compiles Markdown - .md', t => {
@@ -22,6 +22,17 @@
});
});
+test('Compiles Markdown with Custom Plugin', t => {
+ const input = '@[Taylor Swift - Shake it Off](https://www.youtube.com/watch?v=nfWlot6h_JM)';
+ const expected = `<p><div class=\"flexible-video\"><iframe src=\"https://www.youtube.com/embed/nfWlot6h_JM\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen></iframe></div></p>\n`;
+
+ return fromString(input, 'shake/it/off.md', markdown)
+ .then(output => {
+ t.is(output, expected, 'Markdown compiles as expected');
+ });
+});
+
+
test('No Compile - .html', t => {
const input = '# Hello World';
const expected = '# Hello World';
@@ -31,3 +42,14 @@
t.is(output, expected, 'Markdown compiles as expected');
});
});
+
+test('No Compile - null', t => {
+ return fromNull(markdown)
+ .then(output => {
+ t.is(output, '', 'No output');
+ });
+});
+
+test('Error - is stream', t => {
+ t.throws(fromStream(markdown));
+}); |
468fb779830bd727aef77d55e85942ee288fd0d9 | src/components/Badge/index.js | src/components/Badge/index.js | import { h, Component } from 'preact';
import style from './style';
import Icon from '../Icon';
export default class Badge extends Component {
render() {
const { artist, event, small } = this.props;
if (!event && !artist) {
return;
}
if (artist && artist.onTourUntil) {
return (
<span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeOnTour}`}>
<Icon name="calendar" /> On tour
</span>
);
}
if (event.cancelled) {
return (
<span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeCancelled}`}>
<Icon name="close" /> Cancelled
</span>
);
}
if (event.reason.attendance) {
if (event.reason.attendance === 'im_going') {
return (
<span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeGoing}`}>
<Icon name="check" /> Going
</span>
);
} else if (event.reason.attendance === 'i_might_go') {
return (
<span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeMaybe}`}>
<Icon name="bookmark" /> Maybe
</span>
);
}
} else if (event.type && event.type === 'festival') {
return (
<span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeFestival}`}>
<Icon name="star" /> Festival
</span>
);
}
return;
}
}
| import { h, Component } from 'preact';
import style from './style';
import Icon from '../Icon';
export default class Badge extends Component {
render() {
const { event, small } = this.props;
if (!event) {
return;
}
if (event.cancelled) {
return (
<span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeCancelled}`}>
<Icon name="close" /> Cancelled
</span>
);
}
if (event.reason.attendance) {
if (event.reason.attendance === 'im_going') {
return (
<span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeGoing}`}>
<Icon name="check" /> Going
</span>
);
} else if (event.reason.attendance === 'i_might_go') {
return (
<span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeMaybe}`}>
<Icon name="bookmark" /> Maybe
</span>
);
}
} else if (event.type && event.type === 'festival') {
return (
<span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeFestival}`}>
<Icon name="star" /> Festival
</span>
);
}
return;
}
}
| Remove some artist code in Badge component | Remove some artist code in Badge component
| JavaScript | mit | zaccolley/songkick.pink,zaccolley/songkick.pink | ---
+++
@@ -5,18 +5,10 @@
export default class Badge extends Component {
render() {
- const { artist, event, small } = this.props;
+ const { event, small } = this.props;
- if (!event && !artist) {
+ if (!event) {
return;
- }
-
- if (artist && artist.onTourUntil) {
- return (
- <span class={`${style.badge} ${small ? style.badgeSmall : {}} ${style.badgeOnTour}`}>
- <Icon name="calendar" /> On tour
- </span>
- );
}
if (event.cancelled) { |
fc03f5f65d40405c6b322c19114479bcc3e3cf12 | website/addons/dropbox/static/dropboxFangornConfig.js | website/addons/dropbox/static/dropboxFangornConfig.js | 'use strict';
var m = require('mithril');
var Fangorn = require('js/fangorn');
function _fangornLazyLoadError (item) {
item.notify.update('Dropbox couldn\'t load, please try again later.', 'deleting', undefined, 3000);
return true;
}
Fangorn.config.dropbox = {
lazyLoadError : _fangornLazyLoadError
};
| 'use strict';
var m = require('mithril');
var Fangorn = require('js/fangorn');
Fangorn.config.dropbox = {};
| Remove notify from dropbox fangorn | Remove notify from dropbox fangorn [skip ci]
| JavaScript | apache-2.0 | KAsante95/osf.io,jmcarp/osf.io,reinaH/osf.io,cldershem/osf.io,ZobairAlijan/osf.io,abought/osf.io,danielneis/osf.io,wearpants/osf.io,cldershem/osf.io,emetsger/osf.io,brandonPurvis/osf.io,sloria/osf.io,ticklemepierce/osf.io,samchrisinger/osf.io,brandonPurvis/osf.io,icereval/osf.io,ticklemepierce/osf.io,haoyuchen1992/osf.io,cslzchen/osf.io,abought/osf.io,mfraezz/osf.io,binoculars/osf.io,danielneis/osf.io,caseyrygt/osf.io,rdhyee/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,cldershem/osf.io,adlius/osf.io,doublebits/osf.io,ZobairAlijan/osf.io,chennan47/osf.io,sloria/osf.io,amyshi188/osf.io,Nesiehr/osf.io,aaxelb/osf.io,emetsger/osf.io,mattclark/osf.io,HarryRybacki/osf.io,jnayak1/osf.io,MerlinZhang/osf.io,binoculars/osf.io,brandonPurvis/osf.io,jolene-esposito/osf.io,wearpants/osf.io,haoyuchen1992/osf.io,zachjanicki/osf.io,TomBaxter/osf.io,doublebits/osf.io,HalcyonChimera/osf.io,reinaH/osf.io,doublebits/osf.io,acshi/osf.io,chrisseto/osf.io,jolene-esposito/osf.io,amyshi188/osf.io,GageGaskins/osf.io,mattclark/osf.io,danielneis/osf.io,brianjgeiger/osf.io,cldershem/osf.io,crcresearch/osf.io,ZobairAlijan/osf.io,caneruguz/osf.io,mluke93/osf.io,jmcarp/osf.io,icereval/osf.io,rdhyee/osf.io,sloria/osf.io,brianjgeiger/osf.io,wearpants/osf.io,arpitar/osf.io,erinspace/osf.io,brianjgeiger/osf.io,billyhunt/osf.io,billyhunt/osf.io,acshi/osf.io,hmoco/osf.io,arpitar/osf.io,lyndsysimon/osf.io,kwierman/osf.io,HarryRybacki/osf.io,mluo613/osf.io,arpitar/osf.io,abought/osf.io,DanielSBrown/osf.io,caseyrollins/osf.io,mluke93/osf.io,amyshi188/osf.io,arpitar/osf.io,SSJohns/osf.io,acshi/osf.io,chennan47/osf.io,mluke93/osf.io,njantrania/osf.io,MerlinZhang/osf.io,kch8qx/osf.io,cwisecarver/osf.io,dplorimer/osf,cwisecarver/osf.io,HarryRybacki/osf.io,Nesiehr/osf.io,brandonPurvis/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,aaxelb/osf.io,RomanZWang/osf.io,pattisdr/osf.io,samchrisinger/osf.io,caseyrygt/osf.io,lyndsysimon/osf.io,caneruguz/osf.io,wearpants/osf.io,petermalcolm/osf.io,petermalcolm/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,cslzchen/osf.io,abought/osf.io,cwisecarver/osf.io,billyhunt/osf.io,Nesiehr/osf.io,jnayak1/osf.io,RomanZWang/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,lyndsysimon/osf.io,crcresearch/osf.io,samanehsan/osf.io,hmoco/osf.io,SSJohns/osf.io,zamattiac/osf.io,sbt9uc/osf.io,ckc6cz/osf.io,TomBaxter/osf.io,RomanZWang/osf.io,samanehsan/osf.io,saradbowman/osf.io,alexschiller/osf.io,felliott/osf.io,Nesiehr/osf.io,KAsante95/osf.io,ckc6cz/osf.io,Ghalko/osf.io,cosenal/osf.io,reinaH/osf.io,haoyuchen1992/osf.io,GageGaskins/osf.io,TomBaxter/osf.io,danielneis/osf.io,mfraezz/osf.io,acshi/osf.io,Ghalko/osf.io,cslzchen/osf.io,mluo613/osf.io,zamattiac/osf.io,dplorimer/osf,laurenrevere/osf.io,mluo613/osf.io,cwisecarver/osf.io,kwierman/osf.io,CenterForOpenScience/osf.io,reinaH/osf.io,SSJohns/osf.io,ticklemepierce/osf.io,TomHeatwole/osf.io,SSJohns/osf.io,alexschiller/osf.io,jmcarp/osf.io,DanielSBrown/osf.io,mluo613/osf.io,monikagrabowska/osf.io,TomHeatwole/osf.io,samanehsan/osf.io,crcresearch/osf.io,hmoco/osf.io,billyhunt/osf.io,emetsger/osf.io,jnayak1/osf.io,leb2dg/osf.io,baylee-d/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,TomHeatwole/osf.io,samchrisinger/osf.io,GageGaskins/osf.io,cosenal/osf.io,sbt9uc/osf.io,zamattiac/osf.io,Johnetordoff/osf.io,chennan47/osf.io,aaxelb/osf.io,binoculars/osf.io,chrisseto/osf.io,haoyuchen1992/osf.io,leb2dg/osf.io,RomanZWang/osf.io,laurenrevere/osf.io,jolene-esposito/osf.io,caseyrollins/osf.io,felliott/osf.io,monikagrabowska/osf.io,TomHeatwole/osf.io,dplorimer/osf,hmoco/osf.io,samchrisinger/osf.io,amyshi188/osf.io,dplorimer/osf,kch8qx/osf.io,Ghalko/osf.io,asanfilippo7/osf.io,baylee-d/osf.io,kwierman/osf.io,DanielSBrown/osf.io,ckc6cz/osf.io,zachjanicki/osf.io,CenterForOpenScience/osf.io,KAsante95/osf.io,CenterForOpenScience/osf.io,sbt9uc/osf.io,adlius/osf.io,adlius/osf.io,aaxelb/osf.io,zachjanicki/osf.io,njantrania/osf.io,HarryRybacki/osf.io,GageGaskins/osf.io,mfraezz/osf.io,KAsante95/osf.io,kch8qx/osf.io,njantrania/osf.io,rdhyee/osf.io,samanehsan/osf.io,DanielSBrown/osf.io,jolene-esposito/osf.io,njantrania/osf.io,ckc6cz/osf.io,Ghalko/osf.io,RomanZWang/osf.io,KAsante95/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io,petermalcolm/osf.io,petermalcolm/osf.io,HalcyonChimera/osf.io,zachjanicki/osf.io,ZobairAlijan/osf.io,asanfilippo7/osf.io,caseyrygt/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,ticklemepierce/osf.io,chrisseto/osf.io,cosenal/osf.io,pattisdr/osf.io,saradbowman/osf.io,alexschiller/osf.io,leb2dg/osf.io,pattisdr/osf.io,leb2dg/osf.io,jmcarp/osf.io,caneruguz/osf.io,sbt9uc/osf.io,caseyrygt/osf.io,kch8qx/osf.io,asanfilippo7/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,doublebits/osf.io,mattclark/osf.io,jnayak1/osf.io,rdhyee/osf.io,brandonPurvis/osf.io,emetsger/osf.io,acshi/osf.io,mluo613/osf.io,erinspace/osf.io,doublebits/osf.io,kch8qx/osf.io,cosenal/osf.io,icereval/osf.io,erinspace/osf.io,caneruguz/osf.io,felliott/osf.io,mluke93/osf.io,lyndsysimon/osf.io,kwierman/osf.io,felliott/osf.io,caseyrollins/osf.io,GageGaskins/osf.io,MerlinZhang/osf.io,zamattiac/osf.io,MerlinZhang/osf.io,baylee-d/osf.io,alexschiller/osf.io | ---
+++
@@ -3,11 +3,4 @@
var m = require('mithril');
var Fangorn = require('js/fangorn');
-function _fangornLazyLoadError (item) {
- item.notify.update('Dropbox couldn\'t load, please try again later.', 'deleting', undefined, 3000);
- return true;
-}
-
-Fangorn.config.dropbox = {
- lazyLoadError : _fangornLazyLoadError
-};
+Fangorn.config.dropbox = {}; |
e7364f42d49f0e5cccef7da49d109418fe8b5c89 | chrome-extension/mooch.js | chrome-extension/mooch.js | var MoochSentinel = {
render: function(status) {
document.getElementById("status").innerText = status.okay? "Okay!" : "Blocked";
},
requestStatus: function() {
var user = localStorage['moochLogin'];
if (!user) {
document.getElementById("status").innerText = "Please, set user login on options page";
return;
}
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://mooch.co.vu:5000/status/" + user, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var status = JSON.parse(xhr.responseText);
MoochSentinel.render(status);
}
}
xhr.send();
}
}
document.addEventListener("DOMContentLoaded", function() {
MoochSentinel.requestStatus();
});
| var MoochSentinel = {
render: function(status) {
if (status.okay) {
var msg = "Okay";
var color = [255, 0, 0, 0];
} else {
var msg = "Blocked";
var color = [0, 255, 0, 0];
}
document.getElementById("status").innerText = msg;
chrome.browserAction.setBadgeText({text: msg});
chrome.browserAction.setBadgeColor({color: color});
},
requestStatus: function() {
var user = localStorage['moochLogin'];
if (!user) {
document.getElementById("status").innerText = "Please, set user login on options page";
return;
}
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://mooch.co.vu:5000/status/" + user, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var status = JSON.parse(xhr.responseText);
MoochSentinel.render(status);
}
}
xhr.send();
}
}
document.addEventListener("DOMContentLoaded", function() {
MoochSentinel.requestStatus();
});
| Print status at the extension's badge | Print status at the extension's badge
| JavaScript | mit | asivokon/mooch-sentinel,asivokon/mooch-sentinel,asivokon/mooch-sentinel,asivokon/mooch-sentinel | ---
+++
@@ -1,7 +1,17 @@
var MoochSentinel = {
render: function(status) {
- document.getElementById("status").innerText = status.okay? "Okay!" : "Blocked";
+ if (status.okay) {
+ var msg = "Okay";
+ var color = [255, 0, 0, 0];
+ } else {
+ var msg = "Blocked";
+ var color = [0, 255, 0, 0];
+ }
+
+ document.getElementById("status").innerText = msg;
+ chrome.browserAction.setBadgeText({text: msg});
+ chrome.browserAction.setBadgeColor({color: color});
},
requestStatus: function() { |
8be3fbee9a972a580058973ec7860d10492db38e | lib/asset.js | lib/asset.js | var fs = require('fs'),
__bind = require('./helpers').bindFunctionToScope,
escapeRegExp = require('./helpers').escapeRegExp,
AssetDirectives = require('./asset_directives').AssetDirectives;
/*
* @class Asset
*/
exports.Asset = (function () {
function Asset ( file_path, directory ) {
/*
* Initialize instance variables
*/
if ( !fs.existsSync( file_path ) || !fs.statSync( file_path ).isFile() ) {
throw new Error( "Invalid file path: " + JSON.stringify( file_path ) );
}
this.directory = directory;
this.dir_path = directory.path;
this.path = file_path;
// `name` is the path relative to the asset root minus the file extension
relative_path = file_path.replace(new RegExp("^" + escapeRegExp( directory.root.path ) + "/?"), '')
this.name = relative_path.replace(/(\/?[^.]+)\..*$/, "$1")
this.directives = new AssetDirectives( this );
/*
* Bind scope of instance methods
*/
this.isAssetDirectory = __bind( this.isAssetDirectory, this );
/*
* Return instance
*/
return this;
}
Asset.prototype.isAssetDirectory = function () {
return false;
}
return Asset;
})();
| var fs = require('fs'),
__bind = require('./helpers').bindFunctionToScope,
escapeRegExp = require('./helpers').escapeRegExp,
AssetDirectives = require('./asset_directives').AssetDirectives;
/*
* @class Asset
*/
exports.Asset = (function () {
function Asset ( file_path, directory ) {
/*
* Initialize instance variables
*/
if ( !fs.existsSync( file_path ) || !fs.statSync( file_path ).isFile() ) {
throw new Error( "Invalid file path: " + JSON.stringify( file_path ) );
}
this.directory = directory;
this.dir_path = directory.path;
this.path = file_path;
// `name` is the path relative to the asset root minus the file extension
relative_path = file_path.replace(new RegExp("^" + escapeRegExp( directory.root.path ) + "/?"), '')
this.name = relative_path.replace(/(\/?[^.]+)\..*$/, "$1")
this.mapping = directory.mapping;
this.directives = new AssetDirectives( this );
/*
* Bind scope of instance methods
*/
this.isAssetDirectory = __bind( this.isAssetDirectory, this );
/*
* Return instance
*/
return this;
}
Asset.prototype.isAssetDirectory = function () {
return false;
}
return Asset;
})();
| Add Asset mapping property (inherits from directory.mapping) | Add Asset mapping property (inherits from directory.mapping)
| JavaScript | bsd-3-clause | jvatic/node-assets | ---
+++
@@ -28,6 +28,8 @@
relative_path = file_path.replace(new RegExp("^" + escapeRegExp( directory.root.path ) + "/?"), '')
this.name = relative_path.replace(/(\/?[^.]+)\..*$/, "$1")
+ this.mapping = directory.mapping;
+
this.directives = new AssetDirectives( this );
/* |
3c109311a9cc2839e50f07cc5f31b1dfd599811e | examples/minimal.js | examples/minimal.js | var Connection = require('../lib/tedious').Connection;
var Request = require('../lib/tedious').Request;
var config = {
server: '192.168.1.212',
userName: 'test',
password: 'test'
/*
,options: {
debug: {
packet: true,
data: true,
payload: true,
token: false,
log: true
}
}
*/
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to go...
executeStatement();
}
);
connection.on('debug', function(text) {
//console.log(text);
}
);
function executeStatement() {
request = new Request("select 42, 'hello world'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
connection.close();
});
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(column.value);
}
});
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
// In SQL Server 2000 you may need: connection.execSqlBatch(request);
connection.execSql(request);
}
| var Connection = require('../lib/tedious').Connection;
var Request = require('../lib/tedious').Request;
var config = {
server: '192.168.1.212',
userName: 'test',
password: 'test'
/*
,options: {
debug: {
packet: true,
data: true,
payload: true,
token: false,
log: true
},
database: 'DBName',
encrypt: true // for Azure users
}
*/
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to go...
executeStatement();
}
);
connection.on('debug', function(text) {
//console.log(text);
}
);
function executeStatement() {
request = new Request("select 42, 'hello world'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
connection.close();
});
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(column.value);
}
});
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
// In SQL Server 2000 you may need: connection.execSqlBatch(request);
connection.execSql(request);
}
| Clarify that options takes a database parameter | Clarify that options takes a database parameter
Hi,
First, many thanks for putting this together.
I just got (stupidly) stuck on this for a bit until I read the docs a bit more closely and realized that the DB name is part of the options object. I figured I would add a couple of lines to this to clarify even further for developers down the road. Many thanks! | JavaScript | mit | arthurschreiber/tedious,spanditcaa/tedious,LeanKit-Labs/tedious,pekim/tedious,tediousjs/tedious,tediousjs/tedious,Sage-ERP-X3/tedious | ---
+++
@@ -13,7 +13,9 @@
payload: true,
token: false,
log: true
- }
+ },
+ database: 'DBName',
+ encrypt: true // for Azure users
}
*/
}; |
73de73292533946a06f81af04727a4fade0a4a73 | client/protractor-conf.js | client/protractor-conf.js | 'use strict';
//var ScreenShotReporter = require('protractor-screenshot-reporter');
exports.config = {
allScriptsTimeout: 30000,
baseUrl: 'http://localhost:9090',
params: {
baseBackendUrl: 'http://localhost:5000/api/',
username: 'admin',
password: 'admin'
},
specs: ['spec/setup.js', 'spec/**/*[Ss]pec.js'],
capabilities: {
browserName: 'chrome',
chromeOptions: {
args: ['--no-sandbox']
}
},
restartBrowserBetweenTests: process.env.bamboo_working_directory || false, // any bamboo env var will do
directConnect: true,
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 180000
},
/* global jasmine */
onPrepare: function() {
/*
jasmine.getEnv().addReporter(new ScreenShotReporter({
baseDirectory: './screenshots',
pathBuilder:
function pathBuilder(spec, descriptions, results, capabilities) {
return results.passed() + '_' + descriptions.reverse().join('-');
},
takeScreenShotsOnlyForFailedSpecs: true
}));
*/
require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmine.JUnitXmlReporter('e2e-test-results', true, true)
);
}
};
| 'use strict';
//var ScreenShotReporter = require('protractor-screenshot-reporter');
exports.config = {
allScriptsTimeout: 30000,
baseUrl: 'http://localhost:9090',
params: {
baseBackendUrl: 'http://localhost:5000/api/',
username: 'admin',
password: 'admin'
},
specs: ['spec/setup.js', 'spec/**/*[Ss]pec.js'],
capabilities: {
browserName: 'chrome',
chromeOptions: {
args: ['--no-sandbox']
}
},
restartBrowserBetweenTests: process.env.bamboo_working_directory || false, // any bamboo env var will do
directConnect: true,
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 120000
},
/* global jasmine */
onPrepare: function() {
/*
jasmine.getEnv().addReporter(new ScreenShotReporter({
baseDirectory: './screenshots',
pathBuilder:
function pathBuilder(spec, descriptions, results, capabilities) {
return results.passed() + '_' + descriptions.reverse().join('-');
},
takeScreenShotsOnlyForFailedSpecs: true
}));
*/
require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmine.JUnitXmlReporter('e2e-test-results', true, true)
);
}
};
| Revert "fix(client: spec): change jasmine timeout from 120 to 180 s" | Revert "fix(client: spec): change jasmine timeout from 120 to 180 s"
This reverts commit a5f8f6d08b31d20dfec1cd89ada0b1b0b23c5b36.
| JavaScript | agpl-3.0 | plamut/superdesk,liveblog/superdesk,marwoodandrew/superdesk,mdhaman/superdesk,darconny/superdesk,sjunaid/superdesk,superdesk/superdesk,verifiedpixel/superdesk,superdesk/superdesk-ntb,akintolga/superdesk,marwoodandrew/superdesk,amagdas/superdesk,liveblog/superdesk,thnkloud9/superdesk,sivakuna-aap/superdesk,akintolga/superdesk,fritzSF/superdesk,superdesk/superdesk,gbbr/superdesk,pavlovicnemanja/superdesk,superdesk/superdesk-ntb,verifiedpixel/superdesk,liveblog/superdesk,mugurrus/superdesk,amagdas/superdesk,ioanpocol/superdesk-ntb,mdhaman/superdesk,petrjasek/superdesk-ntb,sjunaid/superdesk,vied12/superdesk,ioanpocol/superdesk,hlmnrmr/superdesk,hlmnrmr/superdesk,marwoodandrew/superdesk,mdhaman/superdesk,ancafarcas/superdesk,liveblog/superdesk,ioanpocol/superdesk-ntb,marwoodandrew/superdesk,akintolga/superdesk-aap,marwoodandrew/superdesk-aap,mdhaman/superdesk-aap,marwoodandrew/superdesk-aap,ioanpocol/superdesk,amagdas/superdesk,mdhaman/superdesk-aap,marwoodandrew/superdesk,petrjasek/superdesk-ntb,plamut/superdesk,sivakuna-aap/superdesk,petrjasek/superdesk,mugurrus/superdesk,akintolga/superdesk-aap,fritzSF/superdesk,thnkloud9/superdesk,darconny/superdesk,mugurrus/superdesk,ioanpocol/superdesk,Aca-jov/superdesk,akintolga/superdesk-aap,sivakuna-aap/superdesk,verifiedpixel/superdesk,petrjasek/superdesk,fritzSF/superdesk,mdhaman/superdesk-aap,darconny/superdesk,petrjasek/superdesk-ntb,mdhaman/superdesk-aap,vied12/superdesk,superdesk/superdesk,petrjasek/superdesk,liveblog/superdesk,superdesk/superdesk,vied12/superdesk,verifiedpixel/superdesk,pavlovicnemanja/superdesk,sjunaid/superdesk,amagdas/superdesk,Aca-jov/superdesk,superdesk/superdesk-aap,superdesk/superdesk-aap,akintolga/superdesk,akintolga/superdesk,pavlovicnemanja92/superdesk,superdesk/superdesk-ntb,akintolga/superdesk,amagdas/superdesk,verifiedpixel/superdesk,hlmnrmr/superdesk,marwoodandrew/superdesk-aap,plamut/superdesk,vied12/superdesk,fritzSF/superdesk,ioanpocol/superdesk-ntb,sivakuna-aap/superdesk,sivakuna-aap/superdesk,pavlovicnemanja92/superdesk,gbbr/superdesk,marwoodandrew/superdesk-aap,petrjasek/superdesk-ntb,superdesk/superdesk-aap,plamut/superdesk,pavlovicnemanja/superdesk,superdesk/superdesk-aap,akintolga/superdesk-aap,plamut/superdesk,pavlovicnemanja92/superdesk,pavlovicnemanja92/superdesk,ancafarcas/superdesk,gbbr/superdesk,pavlovicnemanja92/superdesk,thnkloud9/superdesk,ancafarcas/superdesk,petrjasek/superdesk,vied12/superdesk,superdesk/superdesk-ntb,Aca-jov/superdesk,fritzSF/superdesk,pavlovicnemanja/superdesk | ---
+++
@@ -24,7 +24,7 @@
showColors: true,
isVerbose: true,
includeStackTrace: true,
- defaultTimeoutInterval: 180000
+ defaultTimeoutInterval: 120000
},
/* global jasmine */
onPrepare: function() { |
87122e3056721999402f8b7cc9408b86de4719b1 | client/src/utils/index.js | client/src/utils/index.js | export function diffObjects(prev, cur) {
let newValues = Object.assign({}, prev, cur);
let diff = {};
for (const [key, value] of Object.entries(newValues)) {
if (prev[key] !== value) {
diff[key] = value;
}
}
return diff;
}
export function cloneObject(obj) {
return Object.assign({}, obj);
}
| import React from 'react';
import { FormGroup, ControlLabel, FormControl, Col } from 'react-bootstrap';
export function diffObjects(prev, cur) {
let newValues = Object.assign({}, prev, cur);
let diff = {};
for (const [key, value] of Object.entries(newValues)) {
if (prev[key] !== value) {
diff[key] = value;
}
}
return diff;
}
export function cloneObject(obj) {
return Object.assign({}, obj);
}
export function FieldGroup({ id, label, ...props }) {
return (
<FormGroup controlId={id}>
<Col componentClass={ControlLabel} md={4}>{label}</Col>
<Col md={6}><FormControl {...props} /></Col>
</FormGroup>
);
}
| Add method to render label + input | Add method to render label + input
| JavaScript | mit | DjLeChuck/recalbox-manager,DjLeChuck/recalbox-manager,DjLeChuck/recalbox-manager | ---
+++
@@ -1,3 +1,6 @@
+import React from 'react';
+import { FormGroup, ControlLabel, FormControl, Col } from 'react-bootstrap';
+
export function diffObjects(prev, cur) {
let newValues = Object.assign({}, prev, cur);
let diff = {};
@@ -14,3 +17,12 @@
export function cloneObject(obj) {
return Object.assign({}, obj);
}
+
+export function FieldGroup({ id, label, ...props }) {
+ return (
+ <FormGroup controlId={id}>
+ <Col componentClass={ControlLabel} md={4}>{label}</Col>
+ <Col md={6}><FormControl {...props} /></Col>
+ </FormGroup>
+ );
+} |
8b172631f2960b85d936f3b2c6b6e0c05b476830 | lib/index.js | lib/index.js | var fs = require('fs')
var documents = {}
module.exports = {
init: (config, callback) => {
var directories = fs.readdirSync('.')
if (directories.indexOf(config.directory) === -1) {
fs.mkdirSync(config.directory)
config.documents.forEach(document => {
fs.writeFileSync(`${config.directory}/${document}.db`, '{}')
documents[document] = {}
})
return true
}
config.documents.forEach(document => {
if (!fs.existsSync(`${config.directory}/${document}.db`)) {
fs.writeFileSync(`${config.directory}/${document}.db`, '{}')
}
var file = fs.readFileSync(`${config.directory}/${document}.db`)
documents[document] = JSON.parse(file.toString())
})
var keys = Object.keys(documents)
setInterval(() => {
keys.forEach((key) => {
fs.writeFile(`${config.directory}/${key}.db`, JSON.stringify(documents[key]), (err) => {
if (err) console.log(err)
})
})
}, 10000)
return true
},
get: (document, key) => {
return documents[document][key]
},
set: (document, key, value) => {
documents[document][key] = value
return true
},
test: () => {
// console.log('test')
}
}
| var fs = require('fs')
var documents = {}
module.exports = {
init: (config, callback) => {
var directories = fs.readdirSync('.')
if (directories.indexOf(config.directory) === -1) {
fs.mkdirSync(config.directory)
config.documents.forEach(document => {
fs.writeFileSync(`${config.directory}/${document}.db`, '{}')
documents[document] = {}
})
return true
}
config.documents.forEach(document => {
if (!fs.existsSync(`${config.directory}/${document}.db`)) {
fs.writeFileSync(`${config.directory}/${document}.db`, '{}')
}
var file = fs.readFileSync(`${config.directory}/${document}.db`)
documents[document] = JSON.parse(file.toString())
})
if (config.save !== false) {
var keys = Object.keys(documents)
setInterval(() => {
keys.forEach((key) => {
fs.writeFile(`${config.directory}/${key}.db`, JSON.stringify(documents[key]), (err) => {
if (err) console.log(err)
})
})
}, config.save)
}
return true
},
get: (document, key) => {
return documents[document][key]
},
set: (document, key, value) => {
documents[document][key] = value
return true
},
test: () => {
// console.log('test')
}
}
| Save parameter in init function | Save parameter in init function
| JavaScript | mit | ItsJimi/store-data | ---
+++
@@ -20,14 +20,16 @@
var file = fs.readFileSync(`${config.directory}/${document}.db`)
documents[document] = JSON.parse(file.toString())
})
- var keys = Object.keys(documents)
- setInterval(() => {
- keys.forEach((key) => {
- fs.writeFile(`${config.directory}/${key}.db`, JSON.stringify(documents[key]), (err) => {
- if (err) console.log(err)
+ if (config.save !== false) {
+ var keys = Object.keys(documents)
+ setInterval(() => {
+ keys.forEach((key) => {
+ fs.writeFile(`${config.directory}/${key}.db`, JSON.stringify(documents[key]), (err) => {
+ if (err) console.log(err)
+ })
})
- })
- }, 10000)
+ }, config.save)
+ }
return true
},
get: (document, key) => { |
c5751e5933bce2ef2ac80527970868c2ed7fc71e | lib/index.js | lib/index.js | 'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');
var pkg = require('../package.json');
var url = 'https://raw.githubusercontent.com/imagemin/gifsicle-bin/' + pkg.version + '/vendor/';
module.exports = new BinWrapper()
.src(url + 'osx/gifsicle', 'darwin')
.src(url + 'linux/x86/gifsicle', 'linux', 'x86')
.src(url + 'linux/x64/gifsicle', 'linux', 'x64')
.src(url + 'freebsd/x86/gifsicle', 'freebsd', 'x86')
.src(url + 'freebsd/x64/gifsicle', 'freebsd', 'x64')
.src(url + 'win/x86/gifsicle.exe', 'win32', 'x86')
.src(url + 'win/x64/gifsicle.exe', 'win32', 'x64')
.dest(path.join(__dirname, '../vendor'))
.use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');
| 'use strict';
var path = require('path');
var BinWrapper = require('bin-wrapper');
var pkg = require('../package.json');
var url = 'https://raw.githubusercontent.com/imagemin/gifsicle-bin/v' + pkg.version + '/vendor/';
module.exports = new BinWrapper()
.src(url + 'osx/gifsicle', 'darwin')
.src(url + 'linux/x86/gifsicle', 'linux', 'x86')
.src(url + 'linux/x64/gifsicle', 'linux', 'x64')
.src(url + 'freebsd/x86/gifsicle', 'freebsd', 'x86')
.src(url + 'freebsd/x64/gifsicle', 'freebsd', 'x64')
.src(url + 'win/x86/gifsicle.exe', 'win32', 'x86')
.src(url + 'win/x64/gifsicle.exe', 'win32', 'x64')
.dest(path.join(__dirname, '../vendor'))
.use(process.platform === 'win32' ? 'gifsicle.exe' : 'gifsicle');
| Use git tags prepended with v | Use git tags prepended with v
This makes the script behave like other imagemin binary projects.
Pull Request URL:
https://github.com/imagemin/gifsicle-bin/pull/56
| JavaScript | mit | imagemin/gifsicle-bin,jihchi/giflossy-bin | ---
+++
@@ -3,7 +3,7 @@
var path = require('path');
var BinWrapper = require('bin-wrapper');
var pkg = require('../package.json');
-var url = 'https://raw.githubusercontent.com/imagemin/gifsicle-bin/' + pkg.version + '/vendor/';
+var url = 'https://raw.githubusercontent.com/imagemin/gifsicle-bin/v' + pkg.version + '/vendor/';
module.exports = new BinWrapper()
.src(url + 'osx/gifsicle', 'darwin') |
edcb529531029187b2a3a001fa2c631fd9693316 | lib/index.js | lib/index.js | "use strict";
var sass = require("node-sass");
var through = require("through");
var path = require("path");
var extend = require('util')._extend;
module.exports = function (fileName, globalOptions) {
if (!/(\.scss|\.css)$/i.test(fileName)) {
return through();
}
var inputString = "";
return through(
function (chunk) {
inputString += chunk;
},
function () {
var options, css, moduleBody;
// new copy of globalOptions for each file
options = extend({}, globalOptions || {});
options.includePaths = extend([], (globalOptions ? globalOptions.includePaths : {}) || []);
options.data = inputString;
options.includePaths.unshift(path.dirname(fileName));
try {
css = sass.renderSync(options);
} catch (err) {
this.emit('error', err);
return;
}
var escapedCSS = JSON.stringify(css)
moduleBody = "var css = " + escapedCSS + ";" +
"(require('sassify'))(css); module.exports = css;";
this.queue(moduleBody);
this.queue(null);
}
);
};
| "use strict";
var sass = require("node-sass");
var through = require("through");
var path = require("path");
var extend = require('util')._extend;
module.exports = function (fileName, globalOptions) {
if (!/(\.scss|\.css)$/i.test(fileName)) {
return through();
}
var inputString = "";
return through(
function (chunk) {
inputString += chunk;
},
function () {
var options, css, moduleBody;
// new copy of globalOptions for each file
options = extend({}, globalOptions || {});
options.includePaths = extend([], (globalOptions ? globalOptions.includePaths : {}) || []);
// Resolve include paths to baseDir
if(options.baseDir) {
options.includePaths = options.includePaths.map(function (p) { return path.dirname(path.resolve(options.baseDir, p)); });
}
options.data = inputString;
options.includePaths.unshift(path.dirname(fileName));
try {
css = sass.renderSync(options);
} catch (err) {
this.emit('error', err);
return;
}
var escapedCSS = JSON.stringify(css)
moduleBody = "var css = " + escapedCSS + ";" +
"(require('sassify'))(css); module.exports = css;";
this.queue(moduleBody);
this.queue(null);
}
);
};
| Handle baseDir option to resolve include paths before rendering; | Handle baseDir option to resolve include paths before rendering;
| JavaScript | mit | davidguttman/sassify,oncletom/sassify | ---
+++
@@ -23,6 +23,11 @@
options = extend({}, globalOptions || {});
options.includePaths = extend([], (globalOptions ? globalOptions.includePaths : {}) || []);
+ // Resolve include paths to baseDir
+ if(options.baseDir) {
+ options.includePaths = options.includePaths.map(function (p) { return path.dirname(path.resolve(options.baseDir, p)); });
+ }
+
options.data = inputString;
options.includePaths.unshift(path.dirname(fileName));
|
9d098f474ea4b39133d4ce422e725519498339c6 | js/menu.js | js/menu.js | (function() {
'use strict';
program.prompt([
'Hello—I\'m Prompt.'
]);
}());
| (function() {
'use strict';
const stdin = document.getElementById('stdin');
let lastKey;
program.scrollBottom();
setTimeout(() => {
program.prompt([
'Hello—I\'m Prompt.'
]);
setTimeout(() => {
program.prompt([
'I don\'t do anything yet, so you can send me messages and I won\'t reply to you!'
]);
}, 1500);
}, 1000);
function finalMsg () {
const e = event;
const code = e.keyCode || e.which;
if (lastKey !== 13) {
if (code === 13) { // Enter keycode
setTimeout(() => {
if (program.history.length === 1) {
setTimeout(() => {
program.prompt([
'Actually, I do keep scrolling when you return things, but that\'s it.'
]);
}, 600);
} else if (program.history.length === 2) {
setTimeout(() => {
program.prompt([
'Have fun typing to no one.'
]);
}, 600);
}
}, 50);
}
}
lastKey = code;
}
stdin.addEventListener('keyup', finalMsg );
}());
| Add personality (like a homepage) | Add personality (like a homepage)
| JavaScript | mit | jsejcksn/prompt,jsejcksn/prompt | ---
+++
@@ -1,8 +1,46 @@
(function() {
'use strict';
- program.prompt([
- 'Hello—I\'m Prompt.'
- ]);
+ const stdin = document.getElementById('stdin');
+ let lastKey;
+
+ program.scrollBottom();
+ setTimeout(() => {
+ program.prompt([
+ 'Hello—I\'m Prompt.'
+ ]);
+ setTimeout(() => {
+ program.prompt([
+ 'I don\'t do anything yet, so you can send me messages and I won\'t reply to you!'
+ ]);
+ }, 1500);
+ }, 1000);
+
+ function finalMsg () {
+ const e = event;
+ const code = e.keyCode || e.which;
+ if (lastKey !== 13) {
+ if (code === 13) { // Enter keycode
+ setTimeout(() => {
+ if (program.history.length === 1) {
+ setTimeout(() => {
+ program.prompt([
+ 'Actually, I do keep scrolling when you return things, but that\'s it.'
+ ]);
+ }, 600);
+ } else if (program.history.length === 2) {
+ setTimeout(() => {
+ program.prompt([
+ 'Have fun typing to no one.'
+ ]);
+ }, 600);
+ }
+ }, 50);
+ }
+ }
+ lastKey = code;
+ }
+
+ stdin.addEventListener('keyup', finalMsg );
}()); |
a73231ebed92a3f5409d033e59e9af20816e35b2 | Gruntfile.js | Gruntfile.js | var path = require("path");
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-gitbook');
grunt.loadNpmTasks('grunt-gh-pages');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.initConfig({
'gitbook': {
development: {
input: "./",
github: "daikeren/django_tutorial"
}
},
'gh-pages': {
options: {
base: '_book',
silent: true
},
src: ['**']
},
'clean': {
files: '.grunt'
}
});
grunt.registerTask('publish', [
'gitbook',
'gh-pages',
'clean'
]);
grunt.registerTask('default', 'gitbook');
};
| var path = require("path");
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-gitbook');
grunt.loadNpmTasks('grunt-gh-pages');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.initConfig({
'gitbook': {
development: {
input: "./",
github: "daikeren/django_tutorial"
}
},
'gh-pages': {
options: {
base: '_book'
},
src: ['**']
},
'clean': {
files: '.grunt'
}
});
grunt.registerTask('publish', [
'gitbook',
'gh-pages',
'clean'
]);
grunt.registerTask('default', 'gitbook');
};
| Remove silence to see what happen... | Remove silence to see what happen...
| JavaScript | mit | daikeren/django_tutorial | ---
+++
@@ -14,8 +14,7 @@
},
'gh-pages': {
options: {
- base: '_book',
- silent: true
+ base: '_book'
},
src: ['**'] |
c21952e22109bc466cadf821bad3e3988b5653e7 | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
var allSassFiles = [];
var path = require('path');
grunt.file.recurse(
"./stylesheets/",
function(abspath, rootdir, subdir, filename) {
if (filename.match(/\.scss/)) {
allSassFiles.push("@import '" + abspath + "';");
}
}
);
grunt.file.write(
"./spec/stylesheets/test.scss",
allSassFiles.join("\n")
);
grunt.initConfig({
clean: {
sass: ["spec/stylesheets/test*css"]
},
jasmine: {
javascripts: {
src: [
'node_modules/jquery-browser/lib/jquery.js',
'javascripts/**/*.js'
],
options: {
specs: 'spec/unit/*Spec.js',
helpers: 'spec/unit/*Helper.js'
}
}
},
sass: {
development: {
files: {
'./spec/stylesheets/test-out.css': './spec/stylesheets/test.scss'
},
options: {
loadPath: [
'./stylesheets'
],
style: 'nested',
}
},
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.registerTask('test', ['sass', 'clean', 'jasmine']);
grunt.registerTask('default', ['test']);
};
| module.exports = function(grunt) {
var allSassFiles = [];
var path = require('path');
grunt.file.recurse(
"./stylesheets/",
function(abspath, rootdir, subdir, filename) {
if(typeof subdir !== 'undefined'){
var relpath = subdir + '/' + filename;
} else {
var relpath = filename;
}
if (filename.match(/\.scss/)) {
allSassFiles.push("@import '" + relpath + "';");
}
}
);
grunt.file.write(
"./spec/stylesheets/test.scss",
allSassFiles.join("\n")
);
grunt.initConfig({
clean: {
sass: ["spec/stylesheets/test*css"]
},
jasmine: {
javascripts: {
src: [
'node_modules/jquery-browser/lib/jquery.js',
'javascripts/**/*.js'
],
options: {
specs: 'spec/unit/*Spec.js',
helpers: 'spec/unit/*Helper.js'
}
}
},
sass: {
development: {
files: {
'./spec/stylesheets/test-out.css': './spec/stylesheets/test.scss'
},
options: {
loadPath: [
'./stylesheets'
],
style: 'nested',
}
},
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.registerTask('test', ['sass', 'clean', 'jasmine']);
grunt.registerTask('default', ['test']);
};
| Make `@import` paths relative to `./stylesheets` | Make `@import` paths relative to `./stylesheets`
The Load path is set to
`govuk_frontend_toolkit/stylesheets`
so having the `@import` paths relative to
`govuk_frontend_toolkit`
is breaking the tests.
| JavaScript | mit | quis/govuk_frontend_toolkit,TFOH/govuk_frontend_toolkit,quis/govuk_frontend_toolkit,quis/govuk_frontend_toolkit,TFOH/govuk_frontend_toolkit,TFOH/govuk_frontend_toolkit,quis/govuk_frontend_toolkit,alphagov/govuk_frontend_toolkit,alphagov/govuk_frontend_toolkit,alphagov/govuk_frontend_toolkit,TFOH/govuk_frontend_toolkit,alphagov/govuk_frontend_toolkit | ---
+++
@@ -6,8 +6,13 @@
grunt.file.recurse(
"./stylesheets/",
function(abspath, rootdir, subdir, filename) {
+ if(typeof subdir !== 'undefined'){
+ var relpath = subdir + '/' + filename;
+ } else {
+ var relpath = filename;
+ }
if (filename.match(/\.scss/)) {
- allSassFiles.push("@import '" + abspath + "';");
+ allSassFiles.push("@import '" + relpath + "';");
}
}
); |
0170d8a7d0969c0e594aceb0c4dffb9c898db6ef | src/app/components/BookList/BookList.js | src/app/components/BookList/BookList.js | import styles from './BookList.css';
import classes from 'classnames';
export default ({title, zebra, children, className}) => (
<div>
{title ? <h3 className={styles.listTitle}>{title}</h3> : ''}
<ul className={classes(styles.bookList, className, zebra ? styles.alternating : "")}>
{children}
</ul>
</div>
);
| import styles from './BookList.css';
import classes from 'join-classnames';
export default ({title, zebra, children, className}) => (
<div>
{title ? <h3 className={styles.listTitle}>{title}</h3> : ''}
<ul className={classes(styles.bookList, className, zebra ? styles.alternating : "")}>
{children}
</ul>
</div>
);
| Fix improper import of join-classnames | Fix improper import of join-classnames
| JavaScript | mit | mdjasper/React-Reading-List | ---
+++
@@ -1,5 +1,5 @@
import styles from './BookList.css';
-import classes from 'classnames';
+import classes from 'join-classnames';
export default ({title, zebra, children, className}) => (
<div> |
c4273c8ba589e57a36e1023229b229ee79c66e92 | lib/App.js | lib/App.js | /*
* boilerplate-redux-react
*
* Copyright(c) 2015 André König <andre.koenig@posteo.de>
* MIT Licensed
*
*/
/**
* @author André König <andre.koenig@posteo.de>
*
*/
import React, {Component} from 'react';
import {Provider} from 'react-redux';
import {createStore} from './store';
import {Welcome} from './containers';
const store = createStore();
class App extends Component {
render() {
return (
<Provider store={store}>
<Welcome />
</Provider>
);
}
}
export default App;
| /*
* boilerplate-redux-react
*
* Copyright(c) 2015 André König <andre.koenig@posteo.de>
* MIT Licensed
*
*/
/**
* @author André König <andre.koenig@posteo.de>
*
*/
import React from 'react';
import {Provider} from 'react-redux';
import {createStore} from './store';
import {Welcome} from './containers';
const store = createStore();
export default () =>
<Provider store={store}>
<Welcome />
</Provider>;
| Convert app component to function | [TASK] Convert app component to function
| JavaScript | mit | akoenig/boilerplate-redux-react,akoenig/boilerplate-redux-react | ---
+++
@@ -11,7 +11,7 @@
*
*/
-import React, {Component} from 'react';
+import React from 'react';
import {Provider} from 'react-redux';
import {createStore} from './store';
@@ -20,16 +20,7 @@
const store = createStore();
-class App extends Component {
-
- render() {
- return (
- <Provider store={store}>
- <Welcome />
- </Provider>
- );
- }
-
-}
-
-export default App;
+export default () =>
+ <Provider store={store}>
+ <Welcome />
+ </Provider>; |
028d511f2f663685999c8d6a7bbcb9ff5af865e9 | library.js | library.js | "use strict";
var user = module.parent.require('./user'),
db = module.parent.require('./database'),
plugin = {};
plugin.init = function(params, callback) {
var app = params.router,
middleware = params.middleware,
controllers = params.controllers;
app.get('/admin/custom-topics', middleware.admin.buildHeader, renderAdmin);
app.get('/api/admin/custom-topics', renderAdmin);
callback();
};
plugin.addAdminNavigation = function(header, callback) {
header.plugins.push({
route: '/custom-topics',
icon: 'fa-tint',
name: 'Custom Topics'
});
callback(null, header);
};
plugin.onTopicCreate = function(data, callback) {
console.log("Topic created!");
// data.topic, this is the topic that will be saved to the database
// data.data, this is the data that is submitted from the client side
// Now all you have to do is validate `data.myCustomField` and set it in data.topic.
if (data.data.age) {
data.topic.age = data.data.age;
}
console.dir(data);
callback(null, data);
};
function renderAdmin(req, res, next) {
res.render('admin/custom-topics', {});
}
module.exports = plugin;
| "use strict";
var user = module.parent.require('./user'),
db = module.parent.require('./database'),
plugin = {};
plugin.init = function(params, callback) {
var app = params.router,
middleware = params.middleware,
controllers = params.controllers;
app.get('/admin/custom-topics', middleware.admin.buildHeader, renderAdmin);
app.get('/api/admin/custom-topics', renderAdmin);
callback();
};
plugin.addAdminNavigation = function(header, callback) {
header.plugins.push({
route: '/custom-topics',
icon: 'fa-tint',
name: 'Custom Topics'
});
callback(null, header);
};
plugin.onTopicCreate = function(data, callback) {
console.log("Topic created!");
// data.topic, this is the topic that will be saved to the database
// data.data, this is the data that is submitted from the client side
// Now all you have to do is validate `data.myCustomField` and set it in data.topic.
if (data.data.age) {
data.data.content += '<b>Age: </b>' + data.data.age + '</br>';
}
console.dir(data);
callback(null, data);
};
function renderAdmin(req, res, next) {
res.render('admin/custom-topics', {});
}
module.exports = plugin;
| Add ‘age’ to post content | Add ‘age’ to post content
| JavaScript | bsd-2-clause | btw6391/nodebb-plugin-custom-topics | ---
+++
@@ -33,7 +33,7 @@
// Now all you have to do is validate `data.myCustomField` and set it in data.topic.
if (data.data.age) {
- data.topic.age = data.data.age;
+ data.data.content += '<b>Age: </b>' + data.data.age + '</br>';
}
console.dir(data); |
86d0647a7daece3a28919b60ce71ea25bba6da4c | src/js/main.js | src/js/main.js | import * as Backbone from 'backbone';
import AppRouter from './routers/app-router';
let router = new AppRouter();
Backbone.history.start({pushState: true});
| import * as Backbone from 'backbone';
import AppRouter from './routers/app-router';
new AppRouter();
Backbone.history.start({pushState: true});
| Remove unused variable name for router | Remove unused variable name for router
| JavaScript | mit | trevormunoz/katherine-anne,trevormunoz/katherine-anne,trevormunoz/katherine-anne | ---
+++
@@ -1,5 +1,5 @@
import * as Backbone from 'backbone';
import AppRouter from './routers/app-router';
-let router = new AppRouter();
+new AppRouter();
Backbone.history.start({pushState: true}); |
2b5eaa2603849fb41838621fdc274e9c22f11dad | webpack.config.js | webpack.config.js | var path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
}
};
| var path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass'],
}
]
},
sassLoader: {
includePath: [path.resolve(__dirname, './styles')]
}
};
| Add scss loader to webpack | Add scss loader to webpack
| JavaScript | mit | dotKom/glowing-fortnight,dotKom/glowing-fortnight | ---
+++
@@ -12,7 +12,14 @@
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
+ },
+ {
+ test: /\.scss$/,
+ loaders: ['style', 'css', 'sass'],
}
]
+ },
+ sassLoader: {
+ includePath: [path.resolve(__dirname, './styles')]
}
}; |
2b245f47e110f4191cd394e32a7933ffc991152f | assets/javascripts/toc.js | assets/javascripts/toc.js | $(document).ready(function() {
var $toc = $('#toc');
function format (title) {
var $title = $(title),
txt = $title.text(),
id = $title.attr('id');
return "<li> <a href=#" + id + ">" + txt + "</a></li>";
}
// return;
if($toc.length) {
var $h3s = $('.container .col-md-9 :header');
var titles = $h3s.map(function () {
return format(this);
}).get().join('');
$toc.html(titles);
}
$("#toc").affix();
});
| $(document).ready(function() {
var $toc = $('#toc');
function format (item) {
if (item.children && item.children.length > 0) {
return "<li> <a href=#" + item.id + ">" + item.title + "</a><ul class='nav'>"
+ item.children.map(format).join('')
+ "</ul></li>";
} else {
return "<li> <a href=#" + item.id + ">" + item.title + "</a></li>";
}
}
// return;
if($toc.length) {
var $h3s = $('.container .col-md-9 :header');
var tocTree = [];
var lastRoot;
$h3s.each(function(i, el) {
var $el = $(el);
var id = $el.attr('id');
var title = $el.text();
var depth = parseInt($el.prop("tagName")[1]);
if(depth > 3)
return;
if (lastRoot && depth > lastRoot.depth) {
lastRoot.children.push({id: id, title: title });
} else {
lastRoot = {depth: depth,
title: title,
id: id,
children: []};
tocTree.push(lastRoot);
}
});
var titles = tocTree.map(format).join('');
$toc.html(titles);
}
$("#toc").affix();
$('#side-navigation').on('activate.bs.scrollspy', function (e) {
var parent = $(e.target).parent().parent()[0];
if (parent.tagName == "LI") {
$(parent).addClass("active")
}
})
});
| Fix problem with TOC and nested tags | Fix problem with TOC and nested tags
| JavaScript | epl-1.0 | jbtv/sparkling,chrisbetz/sparkling,cswaroop/sparkling,cswaroop/sparkling,gorillalabs/sparkling,chrisbetz/sparkling,antonoal/sparkling,chrisbetz/sparkling,cswaroop/sparkling,jbtv/sparkling,gorillalabs/sparkling,gorillalabs/sparkling,antonoal/sparkling,jbtv/sparkling,gorillalabs/sparkling,antonoal/sparkling,chrisbetz/sparkling,jbtv/sparkling,gorillalabs/sparkling,cswaroop/sparkling,antonoal/sparkling | ---
+++
@@ -1,22 +1,58 @@
$(document).ready(function() {
var $toc = $('#toc');
- function format (title) {
- var $title = $(title),
- txt = $title.text(),
- id = $title.attr('id');
- return "<li> <a href=#" + id + ">" + txt + "</a></li>";
+ function format (item) {
+ if (item.children && item.children.length > 0) {
+ return "<li> <a href=#" + item.id + ">" + item.title + "</a><ul class='nav'>"
+ + item.children.map(format).join('')
+ + "</ul></li>";
+ } else {
+ return "<li> <a href=#" + item.id + ">" + item.title + "</a></li>";
+ }
}
// return;
if($toc.length) {
var $h3s = $('.container .col-md-9 :header');
- var titles = $h3s.map(function () {
- return format(this);
- }).get().join('');
+
+ var tocTree = [];
+ var lastRoot;
+
+ $h3s.each(function(i, el) {
+ var $el = $(el);
+ var id = $el.attr('id');
+ var title = $el.text();
+ var depth = parseInt($el.prop("tagName")[1]);
+
+ if(depth > 3)
+ return;
+
+ if (lastRoot && depth > lastRoot.depth) {
+ lastRoot.children.push({id: id, title: title });
+ } else {
+ lastRoot = {depth: depth,
+ title: title,
+ id: id,
+ children: []};
+ tocTree.push(lastRoot);
+ }
+ });
+
+ var titles = tocTree.map(format).join('');
+
$toc.html(titles);
}
$("#toc").affix();
+ $('#side-navigation').on('activate.bs.scrollspy', function (e) {
+ var parent = $(e.target).parent().parent()[0];
+
+
+ if (parent.tagName == "LI") {
+ $(parent).addClass("active")
+ }
+
+ })
+
}); |
4f906a4c1713ec52e27f3b499d7893642e51af02 | analytics_dashboard/static/apps/learners/app/router.js | analytics_dashboard/static/apps/learners/app/router.js | define(function (require) {
'use strict';
var Marionette = require('marionette'),
LearnersRouter;
LearnersRouter = Marionette.AppRouter.extend({
// Routes intended to show a page in the app should map to method names
// beginning with "show", e.g. 'showLearnerRosterPage'.
appRoutes: {
'(/)(?*queryString)': 'showLearnerRosterPage',
':username(/)(?*queryString)': 'showLearnerDetailPage',
'*notFound': 'showNotFoundPage'
},
onRoute: function (routeName) {
if (routeName.indexOf('show') === 0) {
this.options.controller.triggerMethod('showPage');
}
},
initialize: function (options) {
this.options = options || {};
this.learnerCollection = options.controller.options.learnerCollection;
this.listenTo(this.learnerCollection, 'sync', this.updateUrl);
Marionette.AppRouter.prototype.initialize.call(this, options);
},
// Called on LearnerCollection update. Converts the state of the collection (including any filters, searchers,
// sorts, or page numbers) into a url and then navigates the router to that url.
updateUrl: function () {
this.navigate(this.learnerCollection.getQueryString());
},
});
return LearnersRouter;
});
| define(function (require) {
'use strict';
var Marionette = require('marionette'),
LearnersRouter;
LearnersRouter = Marionette.AppRouter.extend({
// Routes intended to show a page in the app should map to method names
// beginning with "show", e.g. 'showLearnerRosterPage'.
appRoutes: {
'(/)(?*queryString)': 'showLearnerRosterPage',
':username(/)(?*queryString)': 'showLearnerDetailPage',
'*notFound': 'showNotFoundPage'
},
onRoute: function (routeName) {
if (routeName.indexOf('show') === 0) {
this.options.controller.triggerMethod('showPage');
}
},
initialize: function (options) {
this.options = options || {};
this.learnerCollection = options.controller.options.learnerCollection;
this.listenTo(this.learnerCollection, 'sync', this.updateUrl);
Marionette.AppRouter.prototype.initialize.call(this, options);
},
// Called on LearnerCollection update. Converts the state of the collection (including any filters, searchers,
// sorts, or page numbers) into a url and then navigates the router to that url.
updateUrl: function () {
this.navigate(this.learnerCollection.getQueryString(), {replace: true});
},
});
return LearnersRouter;
});
| Replace browser history on roster filter update | Replace browser history on roster filter update
| JavaScript | agpl-3.0 | edx/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,edx/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,edx/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,edx/edx-analytics-dashboard | ---
+++
@@ -30,7 +30,7 @@
// Called on LearnerCollection update. Converts the state of the collection (including any filters, searchers,
// sorts, or page numbers) into a url and then navigates the router to that url.
updateUrl: function () {
- this.navigate(this.learnerCollection.getQueryString());
+ this.navigate(this.learnerCollection.getQueryString(), {replace: true});
},
}); |
850d0f710336b0bdc91ca5d3440aaa8d499dc7ac | src/plugins.js | src/plugins.js | if (process.env.NODE_ENV !== 'production') {
// we're importing script and styles from given plugin
// this method should be only used in development
// for production specify your plugin in package.json
require('epl-plugin/dev');
require('epl-plugin/dev/style.css');
// add plugins in development mode here
// require('epl-plugin/dev');
// require('epl-plugin/dev/style.css');
}
// plugin handlers
const plugins = Object.keys(window)
.filter(key => {
return key.match(/^__EPL_/);
})
.map(key => console.log('Loaded:', key.replace('__EPL_', '')) || window[key]);
console.log(plugins);
export default plugins;
| if (process.env.NODE_ENV !== 'production') {
// we're importing script and styles from given plugin
// this method should be only used in development
// for production specify your plugin in package.json
// require('epl-plugin/dev');
// require('epl-plugin/dev/style.css');
}
// plugin handlers
const plugins = Object.keys(window)
.filter(key => {
return key.match(/^__EPL_/);
})
.map(key => console.log('Loaded:', key.replace('__EPL_', '')) || window[key]);
console.log(plugins);
export default plugins;
| Remove epl-plugin in development mode | Remove epl-plugin in development mode
| JavaScript | apache-2.0 | mkacper/erlangpl,Baransu/erlangpl,erlanglab/erlangpl-ui,Hajto/erlangpl,erlanglab/erlangpl,Baransu/erlangpl,erlanglab/erlangpl,Hajto/erlangpl,Hajto/erlangpl,mkacper/erlangpl,erlanglab/erlangpl-ui,erlanglab/erlangpl,Baransu/erlangpl,mkacper/erlangpl | ---
+++
@@ -2,10 +2,6 @@
// we're importing script and styles from given plugin
// this method should be only used in development
// for production specify your plugin in package.json
- require('epl-plugin/dev');
- require('epl-plugin/dev/style.css');
-
- // add plugins in development mode here
// require('epl-plugin/dev');
// require('epl-plugin/dev/style.css');
} |
dbcec2cbd00580ac81a3c3b9340da7cafb895928 | next.config.js | next.config.js | const { join } = require('path')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
module.exports = {
webpack: function (config, { dev }) {
if (!dev) {
config.plugins.push(new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
reportFilename: join(__dirname, 'reports/bundles.html'),
defaultSizes: 'gzip'
}))
}
return config
}
}
| const webpack = require('webpack')
const { join } = require('path')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
module.exports = {
webpack: function (config, { dev }) {
config.plugins.push(
new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /fr/)
)
if (!dev) {
config.plugins.push(new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
reportFilename: join(__dirname, 'reports/bundles.html'),
defaultSizes: 'gzip'
}))
}
return config
}
}
| Remove useless locales from moment | Remove useless locales from moment
| JavaScript | mit | sgmap/inspire,sgmap/inspire | ---
+++
@@ -1,8 +1,13 @@
+const webpack = require('webpack')
const { join } = require('path')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
module.exports = {
webpack: function (config, { dev }) {
+ config.plugins.push(
+ new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /fr/)
+ )
+
if (!dev) {
config.plugins.push(new BundleAnalyzerPlugin({
analyzerMode: 'static', |
6b9bfebcb7dd5759b19451a2f99a816388c86dfc | vector_2d.js | vector_2d.js | // Copyright 2013, odanielson@github.com
// MIT-license
var Norm = function(v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
}
var Normalize = function(v) {
var norm = Norm(v);
return [v[0] / norm, v[1] / norm];
}
var Subtract = function(a, b) {
return [a[0] - b[0], a[1] - b[1]];
}
var Add = function(a, b) {
return [a[0] + b[0], a[1] + b[1]];
}
var Multiply = function(v, k) {
return [v[0] * k, v[1] * k];
}
var ComplexMultiply = function(v1, v2) {
return [ (v1[0] * v2[0]) - (v1[1] * v2[1]), (v1[0] * v2[1]) + (v2[0] * v1[1]) ];
}
var RotateLeft = function(v) {
return ComplexMultiply(v, [0,-1]);
}
| // https://github.com/odanielson/vector_2d.js
// Copyright 2013, odanielson@github.com
// MIT-license
var Norm = function(v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
}
var Normalize = function(v) {
var norm = Norm(v);
return [v[0] / norm, v[1] / norm];
}
var Subtract = function(a, b) {
return [a[0] - b[0], a[1] - b[1]];
}
var Add = function(a, b) {
return [a[0] + b[0], a[1] + b[1]];
}
var Multiply = function(v, k) {
return [v[0] * k, v[1] * k];
}
var ComplexMultiply = function(v1, v2) {
return [ (v1[0] * v2[0]) - (v1[1] * v2[1]), (v1[0] * v2[1]) + (v2[0] * v1[1]) ];
}
var RotateLeft = function(v) {
return ComplexMultiply(v, [0,-1]);
}
| Add git src at top. | Add git src at top.
| JavaScript | mit | odanielson/vector_2d.js | ---
+++
@@ -1,3 +1,4 @@
+// https://github.com/odanielson/vector_2d.js
// Copyright 2013, odanielson@github.com
// MIT-license
|
d383cf564507d9b6c166f56321527e46b2fd732e | routes/index.js | routes/index.js | var express = require('express'),
router = express.Router(),
bcrypt = require('bcrypt'),
db = require('../models/db'),
index = {};
index.all = function(oauth){
/* GET home page. */
router.get('/', oauth.authorise(), function(req, res) {
res.render('index', { title: 'Express' });
});
return router;
};
module.exports = index;
| var express = require('express'),
router = express.Router(),
bcrypt = require('bcrypt'),
db = require('../models/db'),
index = {};
index.all = function(oauth){
/* GET home page. */
router.get('/', oauth.authorise(), function(req, res) {
res.render('index', { title: 'Express' });
});
/* GET Register new user redirects to users/new. */
router.get('/register', function(req, res) {
res.redirect('/users/new');
});
return router;
};
module.exports = index;
| Add /register route to redirect to users/new | Add /register route to redirect to users/new
| JavaScript | apache-2.0 | tessel/oauth,tessel/oauth,tessel/oauth | ---
+++
@@ -10,6 +10,11 @@
res.render('index', { title: 'Express' });
});
+ /* GET Register new user redirects to users/new. */
+ router.get('/register', function(req, res) {
+ res.redirect('/users/new');
+ });
+
return router;
};
|
75aabb93187c47d412f415f50671d72ea54ecbd6 | app/views/lib/Charts/CanvasChart/__tests__/CanvasChart.spec.js | app/views/lib/Charts/CanvasChart/__tests__/CanvasChart.spec.js | import expect from 'expect';
import I from 'immutable';
import {Note} from '../../../../../reducers/chart';
import {NOTE_HEIGHT} from '../..//constants';
import {
WIDTH,
HEIGHT,
renderNotes,
} from '../';
class MockContext {
constructor() {
this.canvas = {
width: WIDTH,
height: HEIGHT,
};
this.fillRect = expect.createSpy();
this.strokeRect = expect.createSpy();
}
}
describe('<CanvasChart>', () => {
it('renders notes on the judgement line when the scroll offset matches the note offset', () => {
const offsetPositionYPercent = 0.9;
const offset = 20 * 24 + 12;
const note = new Note({
col: 0,
totalOffset: offset,
});
const ctx = new MockContext();
const offsetBarY = (1 - offsetPositionYPercent) * HEIGHT;
renderNotes(ctx, {
notes: I.Set([note]),
beatSpacing: 160,
offset,
offsetBarY,
});
expect(ctx.fillRect.calls.length).toEqual(1);
expect(ctx.fillRect.calls[0].arguments[1]).toEqual(offsetBarY - (NOTE_HEIGHT / 2));
});
});
| import expect from 'expect';
import I from 'immutable';
import {Note} from '../../../../../reducers/chart';
import {NOTE_HEIGHT} from '../../constants';
import {playerColors} from '../../../../../config/constants';
import {
WIDTH,
HEIGHT,
renderNotes,
} from '../';
class MockContext {
constructor() {
this.canvas = {
width: WIDTH,
height: HEIGHT,
};
this.fillRect = expect.createSpy();
this.strokeRect = expect.createSpy();
}
}
describe('<CanvasChart>', () => {
it('renders notes on the judgement line when the scroll offset matches the note offset', () => {
const offsetPositionYPercent = 0.9;
const offset = 20 * 24 + 12;
const note = new Note({
col: 0,
totalOffset: offset,
});
const ctx = new MockContext();
const offsetBarY = (1 - offsetPositionYPercent) * HEIGHT;
renderNotes(ctx, {
colors: playerColors,
notes: I.Set([note]),
beatSpacing: 160,
offset,
offsetBarY,
});
expect(ctx.fillRect.calls.length).toEqual(1);
expect(ctx.fillRect.calls[0].arguments[1]).toEqual(offsetBarY - (NOTE_HEIGHT / 2));
});
});
| Fix canvas chart test missing colors | Fix canvas chart test missing colors
| JavaScript | mit | thomasboyt/bipp,thomasboyt/bipp | ---
+++
@@ -2,7 +2,8 @@
import I from 'immutable';
import {Note} from '../../../../../reducers/chart';
-import {NOTE_HEIGHT} from '../..//constants';
+import {NOTE_HEIGHT} from '../../constants';
+import {playerColors} from '../../../../../config/constants';
import {
WIDTH,
@@ -37,6 +38,7 @@
const offsetBarY = (1 - offsetPositionYPercent) * HEIGHT;
renderNotes(ctx, {
+ colors: playerColors,
notes: I.Set([note]),
beatSpacing: 160,
offset, |
1e2295629b93eb5a3fec43541afe31dfeca417b2 | public/script.js | public/script.js | function init() {
test();
}
function test() {
const divObject = document.getElementById('content');
// create database reference
const dbRefObject = firebase.database().ref().child('object');
// sync object data
dbRefObject.on('value', snap => console.log(snap.val()));
} | function init() {
test();
}
function test() {
const divObject = document.getElementById('content');
// create database reference
const dbRefObject = firebase.database().ref().child('object');
// sync object data
dbRefObject.on('value', snap => {
divObject.innerHTML = JSON.stringify(snap.val(), null, 3);
});
} | Write object data to div element as a JSON string. | Write object data to div element as a JSON string.
| JavaScript | apache-2.0 | googleinterns/step14-2020,googleinterns/step14-2020,googleinterns/step14-2020,googleinterns/step14-2020 | ---
+++
@@ -9,5 +9,7 @@
const dbRefObject = firebase.database().ref().child('object');
// sync object data
- dbRefObject.on('value', snap => console.log(snap.val()));
+ dbRefObject.on('value', snap => {
+ divObject.innerHTML = JSON.stringify(snap.val(), null, 3);
+ });
} |
36e5b580ba633a978ee24c92b70b170deee83d5c | client/templates/bookmark/bookmarks_list.js | client/templates/bookmark/bookmarks_list.js | Template.bookmarksList.helpers({
bookmarks: function() {
if (Meteor.user()) {
var searchTags = document.getElementById("tagSearch").value;
if (searchTags != undefined) {
return Bookmarks.find({
tags: searchTags
}, {
sort: {
dateCreated: -1
}
})
} else {
return (Bookmarks.find({
userId: Meteor.user()._id
}))
}
}
}
}); | Template.bookmarksList.helpers({
bookmarks: function() {
if (Meteor.user()) {
return (Bookmarks.find({
userId: Meteor.user()._id
}))
}
}
}); | Fix bug of the last commit | Fix bug of the last commit
| JavaScript | mit | blumug/georges,blumug/georges,blumug/georges | ---
+++
@@ -1,20 +1,9 @@
Template.bookmarksList.helpers({
bookmarks: function() {
if (Meteor.user()) {
- var searchTags = document.getElementById("tagSearch").value;
- if (searchTags != undefined) {
- return Bookmarks.find({
- tags: searchTags
- }, {
- sort: {
- dateCreated: -1
- }
- })
- } else {
- return (Bookmarks.find({
- userId: Meteor.user()._id
- }))
- }
+ return (Bookmarks.find({
+ userId: Meteor.user()._id
+ }))
}
}
}); |
83442c6ae8861702fdc49e286dd0afd4f8e86cf5 | species-explorer/app/services/species.service.js | species-explorer/app/services/species.service.js | /* global angular */
angular
.module('speciesApp')
.factory('SpeciesService', [
'API_BASE_URL',
'$resource',
SpeciesService
])
function SpeciesService (API_BASE_URL, $resource) {
return $resource(
API_BASE_URL,
null,
{
getKingdoms: {
method: 'GET',
isArray: false,
params: {
op: 'getkingdomnames'
}
},
getClasses: {
method: 'GET',
isArray: false,
params: {
op: 'getclassnames'
}
}
}
)
}
| /* global angular */
angular
.module('speciesApp')
.factory('SpeciesService', [
'API_BASE_URL',
'$resource',
SpeciesService
])
function SpeciesService (API_BASE_URL, $resource) {
return $resource(
API_BASE_URL,
null,
{
getKingdoms: {
method: 'GET',
isArray: false,
params: {
op: 'getkingdomnames'
}
},
getClasses: {
method: 'GET',
isArray: false,
params: {
op: 'getclassnames'
}
},
getFamilies: {
method: 'GET',
isArray: false,
params: {
op: 'getfamilynames'
}
}
}
)
}
| Add an action to get family names by class and kingdom | Add an action to get family names by class and kingdom
| JavaScript | mit | stivaliserna/scripts,stivaliserna/scripts | ---
+++
@@ -26,6 +26,13 @@
params: {
op: 'getclassnames'
}
+ },
+ getFamilies: {
+ method: 'GET',
+ isArray: false,
+ params: {
+ op: 'getfamilynames'
+ }
}
}
) |
237db234a37b364a4271b9d87687985af0a11acc | server/index.js | server/index.js | // Main starting point of the application
const express = require('express');
const path = require('path')
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
const router = require('./router');
const mongoose = require('mongoose');
const cors = require('cors');
// DB Setup
mongoose.connect('mongodb://localhost:auth/auth');
// App Setup
app.use(morgan('combined'));
app.use(cors());
app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.use(bodyParser.json({ limit: '5mb' }));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: true }));
router(app);
// Server Setup
const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
console.log('Server listening on:', port);
| // Main starting point of the application
const express = require('express');
const path = require('path')
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
const router = require('./router');
const mongoose = require('mongoose');
const cors = require('cors');
// DB Setup
mongoose.connect(process.env.MONGODB_URI);
// App Setup
app.use(morgan('combined'));
app.use(cors());
app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.use(bodyParser.json({ limit: '5mb' }));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: true }));
router(app);
// Server Setup
const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
console.log('Server listening on:', port);
| Change mongodb uri to be an env var. | Change mongodb uri to be an env var.
| JavaScript | apache-2.0 | ryanthomas30/AudioNimbus,ryanthomas30/AudioNimbus | ---
+++
@@ -10,7 +10,7 @@
const cors = require('cors');
// DB Setup
-mongoose.connect('mongodb://localhost:auth/auth');
+mongoose.connect(process.env.MONGODB_URI);
// App Setup
app.use(morgan('combined')); |
00cbe3a1649cb06d07157384ec5e9fbd52dfc2aa | server/index.js | server/index.js | require('babel-core/register');
require('dotenv').load();
const serverConfig = require('./config');
// To ignore webpack custom loaders on server.
serverConfig.webpackStylesExtensions.forEach((ext) => {
require.extensions[`.${ext}`] = () => {};
});
require('./main');
| require('babel-core/register');
const path = require('path');
require('dotenv').load({ path: path.resolve(__dirname, '../.env') });
const serverConfig = require('./config');
// To ignore webpack custom loaders on server.
serverConfig.webpackStylesExtensions.forEach((ext) => {
require.extensions[`.${ext}`] = () => {};
});
require('./main');
| Use absolute path to .env file just in case | Use absolute path to .env file just in case
| JavaScript | mit | fastmonkeys/respa-ui | ---
+++
@@ -1,5 +1,7 @@
require('babel-core/register');
-require('dotenv').load();
+
+const path = require('path');
+require('dotenv').load({ path: path.resolve(__dirname, '../.env') });
const serverConfig = require('./config');
|
bb3d0364b782e9534b845981586d75d844918eba | src/model/scenario/state/pieces/TextExtractor.js | src/model/scenario/state/pieces/TextExtractor.js | /**@class A matcher piece that calls `compare` on its element's text.
*/
var TextExtractor = new Class( /** @lends matchers.TextExtractor# */ {
/** The attribute that should be extracted from the element.
* If not defined, defaults to using this class' `type` property.
*
*@type {String}
*/
attribute: null,
onElementFound: function(element) {
element.getText().then(this.compare, this.fail);
}
});
module.exports = TextExtractor; // CommonJS export
| /**@class A matcher piece that calls `compare` on its element's text.
*/
var TextExtractor = new Class( /** @lends matchers.TextExtractor# */ {
/** The attribute that should be extracted from the element.
* If not defined, defaults to using this class' `type` property.
*
*@type {String}
*/
attribute: null,
onElementFound: function(element) {
element.text().then(this.compare, this.fail);
}
});
module.exports = TextExtractor; // CommonJS export
| Update text accessors for WD Pass all tests | Update text accessors for WD
Pass all tests | JavaScript | agpl-3.0 | MattiSG/Watai,MattiSG/Watai | ---
+++
@@ -9,7 +9,7 @@
attribute: null,
onElementFound: function(element) {
- element.getText().then(this.compare, this.fail);
+ element.text().then(this.compare, this.fail);
}
});
|
a363aecf61ea49d67c3e3f74baa949e7e3e9f458 | src/plots/frame_attributes.js | src/plots/frame_attributes.js | /**
* Copyright 2012-2021, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
_isLinkedToArray: 'frames_entry',
group: {
valType: 'string',
description: [
'An identifier that specifies the group to which the frame belongs,',
'used by animate to select a subset of frames.'
].join(' ')
},
name: {
valType: 'string',
description: 'A label by which to identify the frame'
},
traces: {
valType: 'any',
description: [
'A list of trace indices that identify the respective traces in the',
'data attribute'
].join(' ')
},
baseframe: {
valType: 'string',
description: [
'The name of the frame into which this frame\'s properties are merged',
'before applying. This is used to unify properties and avoid needing',
'to specify the same values for the same properties in multiple frames.'
].join(' ')
},
data: {
valType: 'any',
role: 'object',
description: [
'A list of traces this frame modifies. The format is identical to the',
'normal trace definition.'
].join(' ')
},
layout: {
valType: 'any',
role: 'object',
description: [
'Layout properties which this frame modifies. The format is identical',
'to the normal layout definition.'
].join(' ')
}
};
| /**
* Copyright 2012-2021, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
_isLinkedToArray: 'frames_entry',
group: {
valType: 'string',
description: [
'An identifier that specifies the group to which the frame belongs,',
'used by animate to select a subset of frames.'
].join(' ')
},
name: {
valType: 'string',
description: 'A label by which to identify the frame'
},
traces: {
valType: 'any',
description: [
'A list of trace indices that identify the respective traces in the',
'data attribute'
].join(' ')
},
baseframe: {
valType: 'string',
description: [
'The name of the frame into which this frame\'s properties are merged',
'before applying. This is used to unify properties and avoid needing',
'to specify the same values for the same properties in multiple frames.'
].join(' ')
},
data: {
valType: 'any',
description: [
'A list of traces this frame modifies. The format is identical to the',
'normal trace definition.'
].join(' ')
},
layout: {
valType: 'any',
description: [
'Layout properties which this frame modifies. The format is identical',
'to the normal layout definition.'
].join(' ')
}
};
| Revert "revert data and layout role to be object" | Revert "revert data and layout role to be object"
This reverts commit 655508a7309da2bd89265c1ab469bae7034a56a4.
| JavaScript | mit | plotly/plotly.js,plotly/plotly.js,plotly/plotly.js,etpinard/plotly.js,etpinard/plotly.js,plotly/plotly.js,etpinard/plotly.js | ---
+++
@@ -39,7 +39,6 @@
},
data: {
valType: 'any',
- role: 'object',
description: [
'A list of traces this frame modifies. The format is identical to the',
'normal trace definition.'
@@ -47,7 +46,6 @@
},
layout: {
valType: 'any',
- role: 'object',
description: [
'Layout properties which this frame modifies. The format is identical',
'to the normal layout definition.' |
28a1190d8232a73ada8da4f4b6d25658d71c74e0 | update.local.js | update.local.js | var fs = require('fs');
var moment = require('moment');
var rank = require('librank').rank;
// data backup path
var data_path = "./data/talks/";
// read all files in the database
var res = fs.readdirSync(data_path);
// current timestamp
var now = moment();
// calculate difference of hours between two timestamps
function countHours(start, end) {
var duration = moment.duration(end.diff(start));
var hours = duration.asHours();
return hours;
}
// calculate ranking for all elements in the database
res.forEach(function(element) {
// full fs file path
var talk_path = data_path + element;
// get its data
var talk = require(talk_path);
// points
var points = talk.voteCount + 1;
// hours
var hours = countHours(talk.created, now);
// gravity
var gravity = 1.8;
// ranking calculation
var score = rank.rank(points, hours, gravity);
console.log(score, " - ", talk.title);
});
| var fs = require('fs');
var moment = require('moment');
var rank = require('librank').rank;
// data backup path
var data_path = "./data/talks/";
// read all files in the database
var res = fs.readdirSync(data_path);
// current timestamp
var now = moment();
// calculate difference of hours between two timestamps
function countHours(start, end) {
var duration = moment.duration(end.diff(start));
var hours = duration.asHours();
return hours;
}
// calculate ranking for all elements in the database
res.forEach(function(element) {
/*
// full fs file path
var talk_path = data_path + element;
// get its data
var talk = require(talk_path);
// points
var points = talk.voteCount + 1;
// hours
var hours = countHours(talk.created, now);
// gravity
var gravity = 1.8;
// ranking calculation
var score = rank.rank(points, hours, gravity);
console.log(score, " - ", talk.title);
*/
});
| Remove logic on update remote | Remove logic on update remote
| JavaScript | mit | tlksio/db | ---
+++
@@ -20,6 +20,7 @@
// calculate ranking for all elements in the database
res.forEach(function(element) {
+ /*
// full fs file path
var talk_path = data_path + element;
// get its data
@@ -33,4 +34,5 @@
// ranking calculation
var score = rank.rank(points, hours, gravity);
console.log(score, " - ", talk.title);
+ */
}); |
20147f80e8e917312f2f5961c1052c5ee17c0761 | engines/quickjs/extract.js | engines/quickjs/extract.js | // Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// <https://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');
const unzip = require('../../shared/unzip.js');
const { Installer } = require('../../shared/installer.js');
const extract = ({ filePath, binary, os }) => {
return new Promise(async (resolve, reject) => {
const tmpPath = path.dirname(filePath);
await unzip({
from: filePath,
to: tmpPath,
});
const installer = new Installer({
engine: binary,
path: tmpPath,
});
switch (os) {
case 'linux64': {
installer.installBinary({ 'qjsbn': binary });
break;
}
}
resolve();
});
};
module.exports = extract;
| // Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the “License”);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// <https://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');
const unzip = require('../../shared/unzip.js');
const { Installer } = require('../../shared/installer.js');
const extract = ({ filePath, binary, os }) => {
return new Promise(async (resolve, reject) => {
const tmpPath = path.dirname(filePath);
await unzip({
from: filePath,
to: tmpPath,
});
const installer = new Installer({
engine: binary,
path: tmpPath,
});
switch (os) {
case 'linux64': {
installer.installBinary({ 'qjs': binary });
break;
}
}
resolve();
});
};
module.exports = extract;
| Update quickjs installer per latest upstream changes | Update quickjs installer per latest upstream changes
Closes #87.
| JavaScript | apache-2.0 | GoogleChromeLabs/jsvu | ---
+++
@@ -32,7 +32,7 @@
});
switch (os) {
case 'linux64': {
- installer.installBinary({ 'qjsbn': binary });
+ installer.installBinary({ 'qjs': binary });
break;
}
} |
262c982ce8734ce52df072a0ad536365d6f68924 | js/copy.js | js/copy.js | $(function () {
ZeroClipboard.config({swfPath: $('[data-swf-path]').data('swf-path')});
$('pre').each(function () {
if (!$(this).find('code').length) {
var code = $(this).html();
$(this).html('');
$('<code></code>').html(code).appendTo($(this));
}
}).append('<div class="plugin-zclip" title="Click to copy me.">Copy</div>');
$('.plugin-zclip').each(function () {
var $this = $(this),
client = new ZeroClipboard($this[0]);
client.on( "ready", function() {
client.on('copy', function () {
ZeroClipboard.clearData();
var $code = $this.parent().find('code').clone();
$code.find('.line-numbers').remove();
ZeroClipboard.setData('text/plain', $code.text());
$this.text('Copied!');
});
});
});
});
| (function ($) {
$(function () {
ZeroClipboard.config({swfPath: $('[data-swf-path]').data('swf-path')});
$('pre').each(function () {
if (!$(this).find('code').length) {
var code = $(this).html();
$(this).html('');
$('<code></code>').html(code).appendTo($(this));
}
}).append('<div class="plugin-zclip" title="Click to copy me.">Copy</div>');
$('.plugin-zclip').each(function () {
var $this = $(this),
client = new ZeroClipboard($this[0]);
client.on( "ready", function() {
client.on('copy', function () {
ZeroClipboard.clearData();
var $code = $this.parent().find('code').clone();
$code.find('.line-numbers').remove();
ZeroClipboard.setData('text/plain', $code.text());
$this.text('Copied!');
});
});
});
});
})(jQuery.noConflict());
| Fix conflict with jQuery and prototype | Fix conflict with jQuery and prototype
| JavaScript | mit | wenzhixin/redmine-chrome,wenzhixin/redmine-chrome,wenzhixin/redmine-chrome | ---
+++
@@ -1,26 +1,29 @@
-$(function () {
- ZeroClipboard.config({swfPath: $('[data-swf-path]').data('swf-path')});
+(function ($) {
- $('pre').each(function () {
- if (!$(this).find('code').length) {
- var code = $(this).html();
- $(this).html('');
- $('<code></code>').html(code).appendTo($(this));
- }
- }).append('<div class="plugin-zclip" title="Click to copy me.">Copy</div>');
-
- $('.plugin-zclip').each(function () {
- var $this = $(this),
- client = new ZeroClipboard($this[0]);
+ $(function () {
+ ZeroClipboard.config({swfPath: $('[data-swf-path]').data('swf-path')});
- client.on( "ready", function() {
- client.on('copy', function () {
- ZeroClipboard.clearData();
- var $code = $this.parent().find('code').clone();
- $code.find('.line-numbers').remove();
- ZeroClipboard.setData('text/plain', $code.text());
- $this.text('Copied!');
+ $('pre').each(function () {
+ if (!$(this).find('code').length) {
+ var code = $(this).html();
+ $(this).html('');
+ $('<code></code>').html(code).appendTo($(this));
+ }
+ }).append('<div class="plugin-zclip" title="Click to copy me.">Copy</div>');
+
+ $('.plugin-zclip').each(function () {
+ var $this = $(this),
+ client = new ZeroClipboard($this[0]);
+
+ client.on( "ready", function() {
+ client.on('copy', function () {
+ ZeroClipboard.clearData();
+ var $code = $this.parent().find('code').clone();
+ $code.find('.line-numbers').remove();
+ ZeroClipboard.setData('text/plain', $code.text());
+ $this.text('Copied!');
+ });
});
});
});
-});
+})(jQuery.noConflict()); |
0141c2d96b8aa65dc58e739ffe90dcf3b73f964f | ember/app/components/plane-label-overlay.js | ember/app/components/plane-label-overlay.js | import Component from '@ember/component';
import $ from 'jquery';
import ol from 'openlayers';
export default class PlaneLabelOverlay extends Component {
tagName = '';
map = null;
flight = null;
position = null;
overlay = null;
init() {
super.init(...arguments);
let badgeStyle = `display: inline-block; text-align: center; background: ${this.get('flight.color')}`;
let id = this.getWithDefault('flight.competition_id', '') || this.getWithDefault('flight.registration', '');
let badge = $(`<span class="badge plane_marker" style="${badgeStyle}">
${id}
</span>`);
this.set(
'overlay',
new ol.Overlay({
element: badge.get(0),
}),
);
}
didReceiveAttrs() {
super.didReceiveAttrs(...arguments);
this.overlay.setPosition(this.position);
}
didInsertElement() {
super.didInsertElement(...arguments);
let overlay = this.overlay;
this.map.addOverlay(overlay);
let width = $(overlay.getElement()).width();
overlay.setOffset([-width / 2, -40]);
}
willDestroyElement() {
super.willDestroyElement(...arguments);
let overlay = this.overlay;
this.map.removeOverlay(overlay);
}
}
| import Component from '@ember/component';
import $ from 'jquery';
import ol from 'openlayers';
export default class PlaneLabelOverlay extends Component {
tagName = '';
map = null;
flight = null;
position = null;
overlay = null;
init() {
super.init(...arguments);
let badgeStyle = `display: inline-block; text-align: center; background: ${this.get('flight.color')}`;
let id = this.getWithDefault('flight.competition_id', '') || this.getWithDefault('flight.registration', '');
let badge = $(`<span class="badge plane_marker" style="${badgeStyle}">
${id}
</span>`);
this.set(
'overlay',
new ol.Overlay({
element: badge.get(0),
}),
);
}
didReceiveAttrs() {
super.didReceiveAttrs(...arguments);
this.overlay.setPosition(this.position);
}
didInsertElement() {
super.didInsertElement(...arguments);
let overlay = this.overlay;
this.map.addOverlay(overlay);
let width = overlay.getElement().offsetWidth;
overlay.setOffset([-width / 2, -40]);
}
willDestroyElement() {
super.willDestroyElement(...arguments);
let overlay = this.overlay;
this.map.removeOverlay(overlay);
}
}
| Use `offsetWidth` instead of jQuery | PlaneLabelOverlay: Use `offsetWidth` instead of jQuery
| JavaScript | agpl-3.0 | skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines | ---
+++
@@ -39,7 +39,7 @@
let overlay = this.overlay;
this.map.addOverlay(overlay);
- let width = $(overlay.getElement()).width();
+ let width = overlay.getElement().offsetWidth;
overlay.setOffset([-width / 2, -40]);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.