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 |
|---|---|---|---|---|---|---|---|---|---|---|
6cac446d118154a2e9939f32e7f2d2ef628db82b | server/index.js | server/index.js | // To use it create some files under `routes/`
// e.g. `server/routes/ember-hamsters.js`
//
// module.exports = function(app) {
// app.get('/ember-hamsters', function(req, res) {
// res.send('hello');
// });
// };
module.exports = function(app) {
var globSync = require('glob').sync;
var bodyParser = require('body-parser');
var mocks = globSync('./mocks/**/*.js', { cwd: __dirname }).map(require);
var proxies = globSync('./proxies/**/*.js', { cwd: __dirname }).map(require);
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Uncomment to log proxy requests
// var morgan = require('morgan');
// app.use(morgan('dev'));
mocks.forEach(function(route) { route(app); });
proxies.forEach(function(route) { route(app); });
};
| // To use it create some files under `routes/`
// e.g. `server/routes/ember-hamsters.js`
//
// module.exports = function(app) {
// app.get('/ember-hamsters', function(req, res) {
// res.send('hello');
// });
// };
module.exports = function(app) {
var globSync = require('glob').sync;
var bodyParser = require('body-parser');
var mocks = globSync('./mocks/**/*.js', { cwd: __dirname }).map(require);
var proxies = globSync('./proxies/**/*.js', { cwd: __dirname }).map(require);
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(function(req,res,next){
setTimeout(next,1000);
});
// Uncomment to log proxy requests
// var morgan = require('morgan');
// app.use(morgan('dev'));
mocks.forEach(function(route) { route(app); });
proxies.forEach(function(route) { route(app); });
};
| Add some delay to the dev api to better represent reality | Add some delay to the dev api to better represent reality
| JavaScript | mit | jrjohnson/frontend,gboushey/frontend,ilios/frontend,stopfstedt/frontend,thecoolestguy/frontend,stopfstedt/frontend,djvoa12/frontend,dartajax/frontend,dartajax/frontend,gabycampagna/frontend,djvoa12/frontend,gboushey/frontend,gabycampagna/frontend,ilios/frontend,thecoolestguy/frontend,jrjohnson/frontend | ---
+++
@@ -19,6 +19,9 @@
app.use(bodyParser.urlencoded({
extended: true
}));
+ app.use(function(req,res,next){
+ setTimeout(next,1000);
+ });
// Uncomment to log proxy requests
// var morgan = require('morgan'); |
14620efc5cea0749966d218989592246001a3ab1 | app/soc/content/js.min/templates/modules/gsoc/_survey.js | app/soc/content/js.min/templates/modules/gsoc/_survey.js | (function(){melange.template.survey=function(){};melange.template.survey.prototype=new melange.templates._baseTemplate;melange.template.survey.prototype.constructor=melange.template.survey;melange.template.survey.apply(melange.template.survey,[melange.template.survey,melange.template.survey.prototype.context])})();
| melange.templates.inherit(function(){});
| Add minimized version of updated script. | Add minimized version of updated script.
| JavaScript | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | ---
+++
@@ -1 +1 @@
-(function(){melange.template.survey=function(){};melange.template.survey.prototype=new melange.templates._baseTemplate;melange.template.survey.prototype.constructor=melange.template.survey;melange.template.survey.apply(melange.template.survey,[melange.template.survey,melange.template.survey.prototype.context])})();
+melange.templates.inherit(function(){}); |
abdcfcf3af18dd866023b4b0f4b874435197b015 | src/nyc_trees/js/src/mapUtil.js | src/nyc_trees/js/src/mapUtil.js | "use strict";
var _ZOOM = {
NEIGHBORHOOD: 16,
MIN: 0,
MAX: 19
};
module.exports = {
ZOOM: Object.freeze ? Object.freeze(_ZOOM) : _ZOOM,
setCenterAndZoomLL: function(map, zoom, location) {
// Never zoom out, or try to zoom farther than allowed.
var zoomToApply = Math.max(
map.getZoom(),
Math.min(zoom, map.getMaxZoom()));
map.setView(location, zoomToApply);
}
};
| "use strict";
var _ZOOM = {
NEIGHBORHOOD: 16,
MIN: 8,
MAX: 19
};
module.exports = {
ZOOM: Object.freeze ? Object.freeze(_ZOOM) : _ZOOM,
setCenterAndZoomLL: function(map, zoom, location) {
// Never zoom out, or try to zoom farther than allowed.
var zoomToApply = Math.max(
map.getZoom(),
Math.min(zoom, map.getMaxZoom()));
map.setView(location, zoomToApply);
}
};
| Set a minimum zoom compatible with most viewports | Set a minimum zoom compatible with most viewports
fixes #512 on github
| JavaScript | agpl-3.0 | azavea/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,RickMohr/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees | ---
+++
@@ -2,7 +2,7 @@
var _ZOOM = {
NEIGHBORHOOD: 16,
- MIN: 0,
+ MIN: 8,
MAX: 19
};
|
f26332123823f9295f50ec62899583c4931e3274 | src/javascript/app_2/App/app.js | src/javascript/app_2/App/app.js | import { configure } from 'mobx';
import React from 'react';
import { render } from 'react-dom';
import Client from '_common/base/client_base';
import NetworkMonitor from 'Services/network_monitor';
import RootStore from 'Stores';
import { setStorageEvents } from 'Utils/Events/storage';
import App from './app.jsx';
configure({ enforceActions: true });
const initApp = () => {
Client.init();
setStorageEvents();
const root_store = new RootStore();
NetworkMonitor.init(root_store);
root_store.modules.trade.init();
const app = document.getElementById('binary_app');
if (app) {
render(<App root_store={root_store} />, app);
}
};
export default initApp;
| import { configure } from 'mobx';
import React from 'react';
import { render } from 'react-dom';
import Client from '_common/base/client_base';
import BinarySocket from '_common/base/socket_base';
import NetworkMonitor from 'Services/network_monitor';
import RootStore from 'Stores';
import { setStorageEvents } from 'Utils/Events/storage';
import App from './app.jsx';
configure({ enforceActions: true });
const initApp = () => {
Client.init();
setStorageEvents();
const root_store = new RootStore();
NetworkMonitor.init(root_store);
BinarySocket.wait('authorize').then(() => {
root_store.modules.trade.init();
const app = document.getElementById('binary_app');
if (app) {
render(<App root_store={root_store} />, app);
}
});
};
export default initApp;
| Add a wait to get authorize response before initial trade page | Add a wait to get authorize response before initial trade page
| JavaScript | apache-2.0 | 4p00rv/binary-static,ashkanx/binary-static,binary-com/binary-static,ashkanx/binary-static,kellybinary/binary-static,binary-com/binary-static,4p00rv/binary-static,kellybinary/binary-static,binary-com/binary-static,binary-static-deployed/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static,kellybinary/binary-static,binary-static-deployed/binary-static,4p00rv/binary-static | ---
+++
@@ -2,6 +2,7 @@
import React from 'react';
import { render } from 'react-dom';
import Client from '_common/base/client_base';
+import BinarySocket from '_common/base/socket_base';
import NetworkMonitor from 'Services/network_monitor';
import RootStore from 'Stores';
import { setStorageEvents } from 'Utils/Events/storage';
@@ -18,12 +19,14 @@
NetworkMonitor.init(root_store);
- root_store.modules.trade.init();
+ BinarySocket.wait('authorize').then(() => {
+ root_store.modules.trade.init();
- const app = document.getElementById('binary_app');
- if (app) {
- render(<App root_store={root_store} />, app);
- }
+ const app = document.getElementById('binary_app');
+ if (app) {
+ render(<App root_store={root_store} />, app);
+ }
+ });
};
export default initApp; |
18dbcfa13ba598b97b3396f90bef0833954eb5bb | src/Rectangle.js | src/Rectangle.js | import Shape from 'kittik-shape-basic';
/**
* Implements rectangle shape with text support.
*
* @since 1.0.0
* @version 1.0.0
*/
export default class Rectangle extends Shape {
render(cursor) {
let text = this.getText();
let width = this.getWidth();
let height = this.getHeight();
let x1 = this.getX();
let y1 = this.getY();
let x2 = x1 + width - 1;
let y2 = y1 + height - 1;
let background = this.getBackground();
let foreground = this.getForeground();
let filler = ' '.repeat(width);
if (typeof background !== 'undefined') cursor.background(background);
if (typeof foreground !== 'undefined') cursor.foreground(foreground);
cursor.moveTo(x1, y1);
while (y1 <= y2) {
cursor.write(filler);
cursor.moveTo(x1, ++y1);
}
cursor.moveTo(x1 + (width / 2 - text.length / 2), this.getY() + (height / 2)).write(text);
return this;
}
}
| import Shape from 'kittik-shape-basic';
/**
* Implements rectangle shape with text support.
*
* @since 1.0.0
* @version 1.0.0
*/
export default class Rectangle extends Shape {
render(cursor) {
let text = this.getText();
let width = this.getWidth();
let height = this.getHeight();
let x1 = this.getX();
let y1 = this.getY();
let x2 = x1 + width;
let y2 = y1 + height;
let background = this.getBackground();
let foreground = this.getForeground();
let filler = ' '.repeat(width);
if (typeof background !== 'undefined') cursor.background(background);
if (typeof foreground !== 'undefined') cursor.foreground(foreground);
cursor.moveTo(x1, y1);
for (let y = y1; y <= y2; y++) {
cursor.write(filler);
cursor.moveTo(x1, y);
}
cursor.moveTo(x1 + (width / 2 - text.length / 2), y1 + (height / 2)).write(text);
return this;
}
}
| Simplify logic where calculates coordinates | fix(shape): Simplify logic where calculates coordinates
| JavaScript | mit | kittikjs/shape-rectangle | ---
+++
@@ -13,8 +13,8 @@
let height = this.getHeight();
let x1 = this.getX();
let y1 = this.getY();
- let x2 = x1 + width - 1;
- let y2 = y1 + height - 1;
+ let x2 = x1 + width;
+ let y2 = y1 + height;
let background = this.getBackground();
let foreground = this.getForeground();
let filler = ' '.repeat(width);
@@ -24,12 +24,12 @@
cursor.moveTo(x1, y1);
- while (y1 <= y2) {
+ for (let y = y1; y <= y2; y++) {
cursor.write(filler);
- cursor.moveTo(x1, ++y1);
+ cursor.moveTo(x1, y);
}
- cursor.moveTo(x1 + (width / 2 - text.length / 2), this.getY() + (height / 2)).write(text);
+ cursor.moveTo(x1 + (width / 2 - text.length / 2), y1 + (height / 2)).write(text);
return this;
} |
225b84d3d19c7d4129c13fb7f18c3dd908fefa08 | constants/data.js | constants/data.js | export const GAMES = {
'board1': {
'words': ['one', 'two', 'three'],
'board': [
['o', 'n', 'e', '-', '-', '-'],
['t', 'w', 'o', '-', '-', '-'],
['t', 'h', 'r', 'e', 'e', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
},
'board2': {
'words': ['four', 'five', 'six'],
board: [
['f', 'o', 'u', 'r', '-', '-'],
['f', 'i', 'v', 'e', '-', '-'],
['s', 'i', 'x', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
}
}; | export const GAMES = {
'wordSet1': {
'words': ['one', 'two', 'three', 'four','five','six','seven','eight','nine','ten'],
'board': [
['o', 'n', 'e', '-', '-', '-'],
['t', 'w', 'o', '-', '-', '-'],
['t', 'h', 'r', 'e', 'e', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
},
'wordSet2': {
'words': ['four', 'five', 'six'],
board: [
['f', 'o', 'u', 'r', '-', '-'],
['f', 'i', 'v', 'e', '-', '-'],
['s', 'i', 'x', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
},
'wordSet3': {
'words': ['seven', 'eight', 'nine'],
board: [
['s', 'e', 'n', '-', '-', '-'],
['e', 'i', 'i', '-', '-', '-'],
['v', 'g', 'n', '-', '-', '-'],
['e', 'h', 'e', '-', '-', '-'],
['n', 't', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
}
}; | Refactor of bard identifier names | Refactor of bard identifier names
| JavaScript | apache-2.0 | paulbevis/wordsearch,paulbevis/wordsearch | ---
+++
@@ -1,6 +1,6 @@
export const GAMES = {
- 'board1': {
- 'words': ['one', 'two', 'three'],
+ 'wordSet1': {
+ 'words': ['one', 'two', 'three', 'four','five','six','seven','eight','nine','ten'],
'board': [
['o', 'n', 'e', '-', '-', '-'],
['t', 'w', 'o', '-', '-', '-'],
@@ -11,7 +11,7 @@
]
},
- 'board2': {
+ 'wordSet2': {
'words': ['four', 'five', 'six'],
board: [
['f', 'o', 'u', 'r', '-', '-'],
@@ -21,5 +21,17 @@
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
+ },
+
+ 'wordSet3': {
+ 'words': ['seven', 'eight', 'nine'],
+ board: [
+ ['s', 'e', 'n', '-', '-', '-'],
+ ['e', 'i', 'i', '-', '-', '-'],
+ ['v', 'g', 'n', '-', '-', '-'],
+ ['e', 'h', 'e', '-', '-', '-'],
+ ['n', 't', '-', '-', '-', '-'],
+ ['-', '-', '-', '-', '-', '-']
+ ]
}
}; |
85b7bf880a8ecccdd8c732f79fea73db403d237a | src/Reporter.js | src/Reporter.js | const Report = require('./Report');
const Hipchat = require('./Hipchat');
function Reporter( request, reply ) {
console.log(request.query);
return reply({});
}
module.exports = Reporter;
| const Report = require('./Report');
const Notification = require('./Notification');
async function Reporter( request, reply ) {
const result = await new Report({
k: process.env.WEB_PAGE_TEST_KEY || '',
url: request.query.site,
}).run();
// Set error as default.
let notificationOptions = {
status: 'Error',
description: `There was an error proccesing ${request.query.site}`,
room: request.query.hipchat,
url: request.query.site,
}
// Update notificationOptions if was a success
if ( 'statusCode' in result && result.statusCode === 200 ) {
notificationOptions = Object.assign({}, notificationOptions, {
status: 'Started',
description: 'Your web page performance test has started.',
url: result.data.userUrl,
});
}
const notificationResult = await Notification(notificationOptions);
return reply(notificationResult);
}
module.exports = Reporter;
| Add reporter and notifications setup | Add reporter and notifications setup
| JavaScript | mit | wearenolte/lighthouse-reporter | ---
+++
@@ -1,9 +1,31 @@
const Report = require('./Report');
-const Hipchat = require('./Hipchat');
+const Notification = require('./Notification');
-function Reporter( request, reply ) {
- console.log(request.query);
- return reply({});
+async function Reporter( request, reply ) {
+
+ const result = await new Report({
+ k: process.env.WEB_PAGE_TEST_KEY || '',
+ url: request.query.site,
+ }).run();
+
+ // Set error as default.
+ let notificationOptions = {
+ status: 'Error',
+ description: `There was an error proccesing ${request.query.site}`,
+ room: request.query.hipchat,
+ url: request.query.site,
+ }
+
+ // Update notificationOptions if was a success
+ if ( 'statusCode' in result && result.statusCode === 200 ) {
+ notificationOptions = Object.assign({}, notificationOptions, {
+ status: 'Started',
+ description: 'Your web page performance test has started.',
+ url: result.data.userUrl,
+ });
+ }
+ const notificationResult = await Notification(notificationOptions);
+ return reply(notificationResult);
}
module.exports = Reporter; |
a389a4e8807cabced1a08e4ee3c6798dd4e34ea9 | memory-store.js | memory-store.js | var SortedArray = require('sorted-array')
var compareTime = require('./compare-time')
function compareCreated (a, b) {
return compareTime(b[1].created, a[1].created)
}
function compareAdded (a, b) {
return b[1].added - a[1].added
}
/**
* Simpliest memory-based events store.
*
* It is good for tests, but not for server or client usage,
* because it doesn’t save events to file or localStorage.
*
* @example
* import { MemoryStore } from 'logux-core'
*
* var log = new Log({
* store: new MemoryStore(),
* timer: createTestTimer()
* })
*
* @class
*/
function MemoryStore () {
this.created = new SortedArray([], compareCreated)
this.added = new SortedArray([], compareAdded)
}
MemoryStore.prototype = {
get: function get (order) {
var data = order === 'added' ? this.added : this.created
return Promise.resolve({ data: data.array })
},
add: function add (entry) {
this.created.insert(entry)
this.added.insert(entry)
},
remove: function remove (entry) {
this.created.remove(entry)
this.added.remove(entry)
}
}
module.exports = MemoryStore
| var SortedArray = require('sorted-array')
var compareTime = require('./compare-time')
function compareCreated (a, b) {
return compareTime(b[1].created, a[1].created)
}
/**
* Simpliest memory-based events store.
*
* It is good for tests, but not for server or client usage,
* because it doesn’t save events to file or localStorage.
*
* @example
* import { MemoryStore } from 'logux-core'
*
* var log = new Log({
* store: new MemoryStore(),
* timer: createTestTimer()
* })
*
* @class
*/
function MemoryStore () {
this.created = new SortedArray([], compareCreated)
this.added = []
}
MemoryStore.prototype = {
get: function get (order) {
if (order === 'added') {
return Promise.resolve({ data: this.added })
} else {
return Promise.resolve({ data: this.created.array })
}
},
add: function add (entry) {
this.created.insert(entry)
this.added.unshift(entry)
},
remove: function remove (entry) {
this.created.remove(entry)
for (var i = this.added.length - 1; i >= 0; i--) {
if (compareTime(this.added[i][1].created, entry[1].created) === 0) {
this.added.splice(i, 1)
break
}
}
}
}
module.exports = MemoryStore
| Use simple array for added index in MemoryStore | Use simple array for added index in MemoryStore
| JavaScript | mit | logux/logux-core | ---
+++
@@ -4,10 +4,6 @@
function compareCreated (a, b) {
return compareTime(b[1].created, a[1].created)
-}
-
-function compareAdded (a, b) {
- return b[1].added - a[1].added
}
/**
@@ -28,24 +24,32 @@
*/
function MemoryStore () {
this.created = new SortedArray([], compareCreated)
- this.added = new SortedArray([], compareAdded)
+ this.added = []
}
MemoryStore.prototype = {
get: function get (order) {
- var data = order === 'added' ? this.added : this.created
- return Promise.resolve({ data: data.array })
+ if (order === 'added') {
+ return Promise.resolve({ data: this.added })
+ } else {
+ return Promise.resolve({ data: this.created.array })
+ }
},
add: function add (entry) {
this.created.insert(entry)
- this.added.insert(entry)
+ this.added.unshift(entry)
},
remove: function remove (entry) {
this.created.remove(entry)
- this.added.remove(entry)
+ for (var i = this.added.length - 1; i >= 0; i--) {
+ if (compareTime(this.added[i][1].created, entry[1].created) === 0) {
+ this.added.splice(i, 1)
+ break
+ }
+ }
}
} |
5f468801d91b156d8d04b3a81c7dd234b44173db | index.js | index.js | 'use strict';
var request = require('request');
var symbols = require('log-symbols');
module.exports = function(domain, callback){
var path = 'https://domainr.com/api/json/search?q='+domain+'&client_id=avail';
request(path, function (error, response, body) {
var results = JSON.parse(body);
results = results.results;
results = results.map(function (domain) {
var available;
switch (domain.availability) {
case 'tld':
available = symbols.info;
break;
case 'unavailable':
available = symbols.error;
break;
case 'taken':
available = symbols.error;
break;
case 'available':
available = symbols.success;
break;
}
return domain.domain + domain.path + ' ' + available;
});
callback(results);
});
}
| 'use strict';
var request = require('request');
var symbols = require('log-symbols');
module.exports = function(domain, callback){
var path = 'https://api.domainr.com/v1/api/json/search?q='+domain+'&client_id=avail';
request(path, function (error, response, body) {
var results = JSON.parse(body);
results = results.results;
results = results.map(function (domain) {
var available;
switch (domain.availability) {
case 'tld':
available = symbols.info;
break;
case 'unavailable':
available = symbols.error;
break;
case 'taken':
available = symbols.error;
break;
case 'available':
available = symbols.success;
break;
}
return domain.domain + domain.path + ' ' + available;
});
callback(results);
});
}
| Update to new v1 endpoint | Update to new v1 endpoint
We're moving to a versioned API endpoint. Thanks! | JavaScript | mit | srn/avail | ---
+++
@@ -4,7 +4,7 @@
var symbols = require('log-symbols');
module.exports = function(domain, callback){
- var path = 'https://domainr.com/api/json/search?q='+domain+'&client_id=avail';
+ var path = 'https://api.domainr.com/v1/api/json/search?q='+domain+'&client_id=avail';
request(path, function (error, response, body) {
var results = JSON.parse(body); |
c122d6e2a45c90212a2197da2359fdf2bfc5066e | index.js | index.js | 'use strict';
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const morgan = require('morgan');
const port = 8080;
const router = express.Router();
const routes = require('./routes');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Use morgan to diplay requests from the client
app.use(morgan('dev'));
// Implement the routes
routes(router);
app.use('/api', router);
app.listen(port, function(){
console.log(`Server started on port ${port}`);
});
module.exports = app;
| 'use strict';
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const morgan = require('morgan');
const port = process.env.PORT || 8080;
const router = express.Router();
const routes = require('./routes');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Use morgan to diplay requests from the client
app.use(morgan('dev'));
// Implement the routes
routes(router);
app.use('/api', router);
app.listen(port, function(){
console.log(`Server started on port ${port}`);
});
module.exports = app;
| Add the ability for the port to be set by environment variables | Add the ability for the port to be set by environment variables
| JavaScript | mit | andela-oolutola/document-management-system-api | ---
+++
@@ -4,12 +4,10 @@
const app = express();
const bodyParser = require('body-parser');
const morgan = require('morgan');
-const port = 8080;
-
+const port = process.env.PORT || 8080;
const router = express.Router();
const routes = require('./routes');
-
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); |
da68f92fdbc2d4512b01ac5985f3d221bcd4a6bb | index.js | index.js | module.exports = {
extends: 'stylelint-config-standard',
plugins: ['stylelint-order', 'stylelint-scss'],
rules: {
'at-rule-empty-line-before': [
'always',
{
except: ['inside-block', 'blockless-after-blockless', 'first-nested'],
ignore: ['after-comment']
}
],
'at-rule-no-unknown': [
true,
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return']
}
],
'block-closing-brace-newline-after': [
'always',
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return']
}
],
'color-hex-case': ['lower', { severity: 'warning' }],
indentation: 4,
'order/order': ['custom-properties', 'declarations'],
'order/properties-alphabetical-order': true,
'number-leading-zero': 'never',
'selector-list-comma-newline-after': null,
'scss/at-rule-no-unknown': true
}
};
| module.exports = {
extends: 'stylelint-config-standard',
plugins: ['stylelint-order', 'stylelint-scss'],
rules: {
'at-rule-empty-line-before': [
'always',
{
except: ['inside-block', 'blockless-after-blockless', 'first-nested'],
ignore: ['after-comment']
}
],
'at-rule-no-unknown': [
true,
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return', 'include']
}
],
'block-closing-brace-newline-after': [
'always',
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return', 'include']
}
],
'color-hex-case': ['lower', { severity: 'warning' }],
indentation: 4,
'order/order': ['custom-properties', 'declarations'],
'order/properties-alphabetical-order': true,
'number-leading-zero': 'never',
'selector-list-comma-newline-after': null,
'scss/at-rule-no-unknown': true
}
};
| Add include to be ignored | Add include to be ignored
| JavaScript | mit | italodr/stylelint-config-runroom | ---
+++
@@ -12,13 +12,13 @@
'at-rule-no-unknown': [
true,
{
- ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return']
+ ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return', 'include']
}
],
'block-closing-brace-newline-after': [
'always',
{
- ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return']
+ ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return', 'include']
}
],
'color-hex-case': ['lower', { severity: 'warning' }], |
2cd216ece7d96af562fcf3679d190042a725ff27 | index.js | index.js | var fs = require('fs');
var Jafar = function(opts) {
var that = this;
if (!opts.json || (typeof(opts.json) !== 'object' && typeof(opts.json) !== 'string')) {
throw new Error('You must pass a reference to a valid JSON object/file into Jafar constructor!');
}
this.json = (typeof(opts.json) === 'object') ? opts.json : this.parseJsonFile(opts.json);
};
Jafar.prototype.parseJsonFile = function(input) {
try {
return JSON.parse(fs.readFileSync(input));
}
catch(err) {
throw new Error('Input JSON file could not be read!');
}
};
Jafar.prototype.displayJson = function() {
console.log(this.json);
};
module.exports = Jafar; | var fs = require('fs');
var Jafar = function(opts) {
var that = this,
// TODO: would need error handling to ensure opts exists at all
inputJson = opts.json ? opts.json : null;
if (!inputJson || (typeof(inputJson) !== 'object' && typeof(inputJson) !== 'string')) {
throw new Error('You must pass a reference to a valid JSON object/file into Jafar constructor!');
}
this.json = (typeof(inputJson) === 'object') ? inputJson : this.readJsonFile(inputJson);
};
Jafar.prototype.readJsonFile = function(input) {
try {
return JSON.parse(fs.readFileSync(input));
}
catch(err) {
throw new Error('Input JSON file could not be read!');
}
};
Jafar.prototype.displayJson = function() {
console.log(this.json);
};
module.exports = Jafar; | Reduce redundancy with opts object | Reduce redundancy with opts object
| JavaScript | mit | jkymarsh/jafar | ---
+++
@@ -1,16 +1,18 @@
var fs = require('fs');
var Jafar = function(opts) {
- var that = this;
+ var that = this,
+ // TODO: would need error handling to ensure opts exists at all
+ inputJson = opts.json ? opts.json : null;
- if (!opts.json || (typeof(opts.json) !== 'object' && typeof(opts.json) !== 'string')) {
+ if (!inputJson || (typeof(inputJson) !== 'object' && typeof(inputJson) !== 'string')) {
throw new Error('You must pass a reference to a valid JSON object/file into Jafar constructor!');
}
- this.json = (typeof(opts.json) === 'object') ? opts.json : this.parseJsonFile(opts.json);
+ this.json = (typeof(inputJson) === 'object') ? inputJson : this.readJsonFile(inputJson);
};
-Jafar.prototype.parseJsonFile = function(input) {
+Jafar.prototype.readJsonFile = function(input) {
try {
return JSON.parse(fs.readFileSync(input));
} |
b09e4ffc14571cd9679800f1ba02cc7bc728e687 | index.js | index.js | 'use strict';
var isStream = require('is-stream');
var matchCondition = require('match-condition');
var peekStream = require('peek-stream');
var through = require('through2');
module.exports = function (condition, stream, fn, opts) {
opts = opts || {};
if (fn && !isStream(fn) && typeof fn !== 'function') {
opts = fn;
}
var peek = peekStream(opts, function (data, swap) {
if (!matchCondition(data, condition) && !isStream(fn) && typeof fn !== 'function') {
swap(null, through());
return;
}
if (!matchCondition(data, condition)) {
swap(null, typeof fn === 'function' ? fn() : fn);
return;
}
swap(null, stream());
});
return peek;
};
| 'use strict';
var isStream = require('is-stream');
var matchCondition = require('match-condition');
var peekStream = require('peek-stream');
var through = require('through2');
module.exports = function (condition, stream, fn, opts) {
opts = opts || {};
if (fn && !isStream(fn) && typeof fn !== 'function') {
opts = fn;
}
var peek = peekStream(opts, function (data, swap) {
if (!matchCondition(data, condition) && !isStream(fn) && typeof fn !== 'function') {
swap(null, through());
return;
}
if (!matchCondition(data, condition)) {
swap(null, typeof fn === 'function' ? fn() : fn);
return;
}
swap(null, typeof stream === 'function' ? stream() : stream);
});
return peek;
};
| Check if `stream` is a function | Check if `stream` is a function
| JavaScript | mit | kevva/if-stream | ---
+++
@@ -22,7 +22,7 @@
return;
}
- swap(null, stream());
+ swap(null, typeof stream === 'function' ? stream() : stream);
});
return peek; |
b1e3a3c32000690495bacc4d11189b15aa740932 | client/app.js | client/app.js | (function() {
'use strict';
angular
.module('weatherApp', ['ngRoute'])
.config(config);
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'components/home/home.view.html',
controller: 'HomeCtrl',
controllerAs: 'vm'
})
.when('/forecast', {
templateUrl: 'components/forecast/forecast.view.html',
controller: 'ForecastCtrl',
controllerAs: 'vm'
})
.when('/forecast/:days', {
templateUrl: 'components/forecast/forecast.view.html',
controller: 'ForecastCtrl',
controllerAs: 'vm'
})
.otherwise({redirectTo: '/'});
}
})();
| (function() {
'use strict';
angular
.module('weatherApp', ['ngRoute'])
.config(['$routeProvider'], config);
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'components/home/home.view.html',
controller: 'HomeCtrl',
controllerAs: 'vm'
})
.when('/forecast', {
templateUrl: 'components/forecast/forecast.view.html',
controller: 'ForecastCtrl',
controllerAs: 'vm'
})
.when('/forecast/:days', {
templateUrl: 'components/forecast/forecast.view.html',
controller: 'ForecastCtrl',
controllerAs: 'vm'
})
.otherwise({redirectTo: '/'});
}
})();
| Add inline annotation to config | Add inline annotation to config
| JavaScript | mit | cpanz/Angular_Weather,cpanz/Angular_Weather | ---
+++
@@ -3,7 +3,7 @@
angular
.module('weatherApp', ['ngRoute'])
- .config(config);
+ .config(['$routeProvider'], config);
function config($routeProvider) {
$routeProvider |
60e2a7db670003f8f49b786a69be0b16992993a6 | example/simple.js | example/simple.js | var zmqbus = require('../lib/index.js');
/* simple quote sender/reader.
Run multiple processes to send/receive cluster-wide.
*/
var node = zmqbus.createNode();
node.on('ready', function() {
// subscribe to equity channel
node.subscribe("equity");
setInterval(fakeEquityQuote, 1000);
// uncomment the following to receive temperature readings
// node.subscribe("temp")
setInterval(fakeTemperatureQuote, 2000);
});
node.on('message', function(msg) {
console.log("received " + msg);
});
function fakeEquityQuote() {
// broadcast some fake stock quotes
var stocks = ['AAPL', 'GOOG', 'IBM', 'FB'];
var symbol = stocks[Math.floor(Math.random() * stocks.length)];
var quote = (Math.random() * 100.0 + 25.0).toFixed(2);
node.publish('equity', symbol, quote);
}
function fakeTemperatureQuote() {
// broadcast some fake stock quotes
var cities = ['New York, NY', 'San Francisco, CA', 'Chicago, IL'];
var city = cities[Math.floor(Math.random() * cities.length)];
var quote = (Math.random() * 50.0 + 30.0).toFixed(2);
node.publish('temp', city, quote);
} | var zmqbus = require('zmqbus');
/* simple quote sender/reader.
Run multiple processes to send/receive cluster-wide.
*/
var node = zmqbus.createNode();
node.on('ready', function() {
// subscribe to equity channel
node.subscribe("equity");
setInterval(fakeEquityQuote, 1000);
// uncomment the following to receive temperature readings
// node.subscribe("temp")
setInterval(fakeTemperatureQuote, 2000);
});
node.on('message', function(msg) {
console.log("received " + msg);
});
function fakeEquityQuote() {
// broadcast some fake stock quotes
var stocks = ['AAPL', 'GOOG', 'IBM', 'FB'];
var symbol = stocks[Math.floor(Math.random() * stocks.length)];
var quote = (Math.random() * 100.0 + 25.0).toFixed(2);
node.publish('equity', symbol, quote);
}
function fakeTemperatureQuote() {
// broadcast some fake stock quotes
var cities = ['New York, NY', 'San Francisco, CA', 'Chicago, IL'];
var city = cities[Math.floor(Math.random() * cities.length)];
var quote = (Math.random() * 50.0 + 30.0).toFixed(2);
node.publish('temp', city, quote);
} | Fix example to use the right module name | Fix example to use the right module name
| JavaScript | mit | edwardchoh/zmqbus-node | ---
+++
@@ -1,4 +1,4 @@
-var zmqbus = require('../lib/index.js');
+var zmqbus = require('zmqbus');
/* simple quote sender/reader.
Run multiple processes to send/receive cluster-wide. |
f9df796731fe97fb1c9d6487a25b3dee6a9c7524 | server/server.js | server/server.js | 'use strict';
const express = require('express');
// Constants
const PORT = 8080;
// App
const app = express();
app.get('/', function (req, res) {
res.send('Hello world\n');
});
app.listen(PORT);
console.log('Running on http://localhost:' + PORT); | require('dotenv').config();
const bodyParser = require('body-parser');
const metadata = require('../package.json');
const compression = require('compression');
const express = require('express');
const path = require('path');
const redis = require('redis');
const sharp = require('sharp');
const utils = require('./lib/utilities.js');
const bcrypt = require('bcrypt-nodejs');
const session = require('express-session');
const userController = require('../db/controllers/users.js');
const bookmarkController = require('../db/controllers/bookmarks.js');
const photoController = require('../db/controllers/photos.js');
const likeController = require('../db/controllers/likes.js');
const commentController = require('../db/controllers/comments.js');
const port = process.env.NODE_PORT;
const secret = process.env.SESSION_SECRET;
const AWSaccessKey = process.env.ACCESSKEYID;
const AWSsecretKey = process.env.SECRETACCESSKEY;
// const redisClient = redis.createClient();
const app = express();
app.use(bodyParser.json({limit: '40mb'}));
app.use(compression()); // gzip compress all responses
app.use(session({
secret: secret,
resave: false,
saveUninitialized: true
}));
const routes = ['/'];
for (const route of routes) {
app.get(route, (req, res) => {
if (route === '/') {
res.redirect('/dashboard');
} else {
res.sendFile(path.join(__dirname, '/../client/index.html'));
}
});
}
app.use(express.static(path.join(__dirname, '../client')));
// wildcard route
app.get('*', function(req, res) {
res.status(404).send('Not Found');
});
app.listen(port, () => {
console.log(`🌎 Listening on port ${port} for app ${metadata.name} 🌏`);
}); | Add npm modules and set up middleware | Add npm modules and set up middleware
| JavaScript | mit | francoabaroa/happi,francoabaroa/happi | ---
+++
@@ -1,15 +1,56 @@
-'use strict';
+require('dotenv').config();
+const bodyParser = require('body-parser');
+const metadata = require('../package.json');
+const compression = require('compression');
+const express = require('express');
+const path = require('path');
+const redis = require('redis');
+const sharp = require('sharp');
-const express = require('express');
+const utils = require('./lib/utilities.js');
+const bcrypt = require('bcrypt-nodejs');
+const session = require('express-session');
+const userController = require('../db/controllers/users.js');
+const bookmarkController = require('../db/controllers/bookmarks.js');
+const photoController = require('../db/controllers/photos.js');
+const likeController = require('../db/controllers/likes.js');
+const commentController = require('../db/controllers/comments.js');
-// Constants
-const PORT = 8080;
+const port = process.env.NODE_PORT;
+const secret = process.env.SESSION_SECRET;
+const AWSaccessKey = process.env.ACCESSKEYID;
+const AWSsecretKey = process.env.SECRETACCESSKEY;
-// App
+// const redisClient = redis.createClient();
const app = express();
-app.get('/', function (req, res) {
- res.send('Hello world\n');
+
+app.use(bodyParser.json({limit: '40mb'}));
+app.use(compression()); // gzip compress all responses
+app.use(session({
+ secret: secret,
+ resave: false,
+ saveUninitialized: true
+}));
+
+const routes = ['/'];
+
+for (const route of routes) {
+ app.get(route, (req, res) => {
+ if (route === '/') {
+ res.redirect('/dashboard');
+ } else {
+ res.sendFile(path.join(__dirname, '/../client/index.html'));
+ }
+ });
+}
+
+app.use(express.static(path.join(__dirname, '../client')));
+
+// wildcard route
+app.get('*', function(req, res) {
+ res.status(404).send('Not Found');
});
-app.listen(PORT);
-console.log('Running on http://localhost:' + PORT);
+app.listen(port, () => {
+ console.log(`🌎 Listening on port ${port} for app ${metadata.name} 🌏`);
+}); |
e8306057a65889f384caa24933c71f8c8ec71854 | src/server/boot/root.js | src/server/boot/root.js | module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/', server.loopback.status());
server.use(router);
};
| module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
//router.get('/', server.loopback.status()); // loopback default router, change it to do production work
router.get('/', function(req, res) {
res.sendfile('client/public/index.html');
});
server.use(router);
};
| Change default action of path '/', send index.html file. | Change default action of path '/', send index.html file.
| JavaScript | mit | agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart | ---
+++
@@ -1,6 +1,9 @@
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
- router.get('/', server.loopback.status());
+ //router.get('/', server.loopback.status()); // loopback default router, change it to do production work
+ router.get('/', function(req, res) {
+ res.sendfile('client/public/index.html');
+ });
server.use(router);
}; |
49c652b034e8f2c9238282c67e0c3394e6165382 | public/javascripts/pages/index.js | public/javascripts/pages/index.js | function proceedSignin() {
'use strict';
event.preventDefault();
var emailField = document.getElementById('email'),
passwordField = document.getElementById('password');
var user = {
username: emailField.value,
password: passwordField.value
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (this.status === 200) {
window.location = '/rooms';
}
if (this.status === 401) {
document.getElementById('signin-message').innerHTML = 'Le mot de passe ou le pseudonyme est incorrect. <br /> Avez-vous confirmé votre inscription ?';
}
}
};
xhr.open('POST', '/signin', true);
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.send(JSON.stringify(user));
}
document.addEventListener('DOMContentLoaded', function () {
'use strict';
var signinSubmit = document.getElementById('signin-submit');
signinSubmit.addEventListener('click', proceedSignin, false);
}, false); | function proceedSignin() {
'use strict';
event.preventDefault();
var emailField = document.getElementById('email'),
passwordField = document.getElementById('password');
var user = {
username: emailField.value,
password: passwordField.value
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (this.status === 200) {
window.location = '/rooms';
}
if (this.status === 401) {
document.getElementById('signin-message').innerHTML = 'Le mot de passe ou le pseudonyme est incorrect. <br /> Avez-vous confirmé votre inscription ?';
}
}
};
xhr.open('POST', '/signin', true);
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
xhr.send(JSON.stringify(user));
}
document.addEventListener('DOMContentLoaded', function () {
'use strict';
var signinSubmit = document.getElementById('signin-submit');
signinSubmit.addEventListener('click', proceedSignin, false);
}, false); | Add parameters to /signin (POST) request header | Add parameters to /signin (POST) request header
| JavaScript | mit | sea-battle/sea-battle,sea-battle/sea-battle | ---
+++
@@ -27,6 +27,7 @@
xhr.open('POST', '/signin', true);
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
+ xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
xhr.send(JSON.stringify(user));
}
|
859dbe0e2bc5a322633f7323b1ff9fe638624c9f | app/assets/javascripts/remote_consoles/vnc.js | app/assets/javascripts/remote_consoles/vnc.js | //= require jquery
//= require novnc-rails
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
// noVNC requires an empty canvas item
var canvas = document.createElement('canvas');
$('#remote-console').append(canvas);
var vnc = new RFB({
target: canvas,
encrypt: encrypt,
true_color: true,
local_cursor: true,
shared: true,
view_only: false,
onUpdateState: function(_, state, _, msg) {
if (['normal', 'loaded'].indexOf(state) >= 0) {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
} else if (state === 'disconnected') {
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error('VNC', msg);
}
},
});
$('#ctrlaltdel').click(vnc.sendCtrlAltDel);
vnc.connect(host, port, $('#remote-console').attr('data-secret'), $('#remote-console').attr('data-url'));
});
| //= require jquery
//= require novnc-rails
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
// noVNC requires an empty canvas item
var canvas = document.createElement('canvas');
$('#remote-console').append(canvas);
var vnc = new RFB({
target: canvas,
encrypt: encrypt,
true_color: true,
local_cursor: true,
shared: true,
view_only: false,
onUpdateState: function(_, state, _, msg) {
if (['normal', 'loaded'].indexOf(state) >= 0) {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
} else if (state === 'disconnected') {
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error('VNC', msg);
}
},
});
vnc.connect(host, port, $('#remote-console').attr('data-secret'), $('#remote-console').attr('data-url'));
$('#ctrlaltdel').on('click', function(){
vnc.sendCtrlAltDel();
});
});
| Fix VNC console connection to Windows VMs and Ctrl-Alt-Del button | Fix VNC console connection to Windows VMs and Ctrl-Alt-Del button
https://bugzilla.redhat.com/show_bug.cgi?id=1464152
| JavaScript | apache-2.0 | ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic | ---
+++
@@ -34,6 +34,9 @@
},
});
- $('#ctrlaltdel').click(vnc.sendCtrlAltDel);
vnc.connect(host, port, $('#remote-console').attr('data-secret'), $('#remote-console').attr('data-url'));
+
+ $('#ctrlaltdel').on('click', function(){
+ vnc.sendCtrlAltDel();
+ });
}); |
0a46deb294a7c093997a4cf2d4d7188e9ef02424 | sources/openfisca.js | sources/openfisca.js | <openfisca>
<p>la variable
<input required type="text" name="query" placeholder="al.R1.taux1" value={ opts.value } onchange={ getDescription }>
dans Openfisca ({ description })</p>
<script>
getDescription() {
var url = 'http://api.openfisca.fr/api/1/parameters?name=' + this.query.value;
fetch(url)
.then(function(response) { return response.json() })
.then(function(json) {
this.description = json.parameters[0].description;
this.root.value = url;
this.update();
}.bind(this), console.error.bind(console));
}
</script>
</openfisca>
| <openfisca>
<p>la variable
<input required type="text" name="query" placeholder="nb_pac" value={ opts.value } onchange={ getDescription }>
dans Openfisca ({ description })</p>
<script>
getDescription() {
var url = 'http://api.openfisca.fr/api/1/variables?name=' + this.query.value;
fetch(url)
.then(function(response) { return response.json() })
.then(function(json) {
this.description = json.variables[0].label;
this.root.value = url;
this.update();
}.bind(this), console.error.bind(console));
}
</script>
</openfisca>
| Use variables instead of params | Use variables instead of params
| JavaScript | agpl-3.0 | MattiSG/alignements-loi,MattiSG/alignements-loi | ---
+++
@@ -1,15 +1,15 @@
<openfisca>
<p>la variable
- <input required type="text" name="query" placeholder="al.R1.taux1" value={ opts.value } onchange={ getDescription }>
+ <input required type="text" name="query" placeholder="nb_pac" value={ opts.value } onchange={ getDescription }>
dans Openfisca ({ description })</p>
<script>
getDescription() {
- var url = 'http://api.openfisca.fr/api/1/parameters?name=' + this.query.value;
+ var url = 'http://api.openfisca.fr/api/1/variables?name=' + this.query.value;
fetch(url)
.then(function(response) { return response.json() })
.then(function(json) {
- this.description = json.parameters[0].description;
+ this.description = json.variables[0].label;
this.root.value = url;
this.update();
}.bind(this), console.error.bind(console)); |
a0abf6b63572189fe3e3c06cf6c89e621958cb40 | app/reducers/frontpage.js | app/reducers/frontpage.js | import moment from 'moment-timezone';
import { Frontpage } from 'app/actions/ActionTypes';
import { fetching } from 'app/utils/createEntityReducer';
import { sortBy } from 'lodash';
import { createSelector } from 'reselect';
import { selectArticles } from './articles';
import { selectEvents } from './events';
export default fetching(Frontpage.FETCH);
export const selectFrontpage = createSelector(
selectArticles,
selectEvents,
(articles, events) => {
articles = articles.map(article => ({
...article,
documentType: 'article'
}));
events = events.map(event => ({ ...event, documentType: 'event' }));
return sortBy(articles.concat(events), [
// Always sort pinned items first:
item => !item.pinned,
item => {
// For events we care about when the event starts, whereas for articles
// we look at when it was written:
const timeField = item.eventType ? item.startTime : item.createdAt;
return Math.abs(moment().diff(timeField));
},
item => item.id
]);
}
);
| import moment from 'moment-timezone';
import { Frontpage } from 'app/actions/ActionTypes';
import { fetching } from 'app/utils/createEntityReducer';
import { sortBy } from 'lodash';
import { createSelector } from 'reselect';
import { selectArticles } from './articles';
import { selectEvents } from './events';
export default fetching(Frontpage.FETCH);
export const selectFrontpage = createSelector(
selectArticles,
selectEvents,
(articles, events) => {
articles = articles.map(article => ({
...article,
documentType: 'article'
}));
events = events.map(event => ({ ...event, documentType: 'event' }));
const now = moment();
return sortBy(articles.concat(events), [
// Always sort pinned items first:
item => !item.pinned,
item => {
// For events we care about when the event starts, whereas for articles
// we look at when it was written:
const timeField = item.eventType ? item.startTime : item.createdAt;
return Math.abs(now.diff(timeField));
},
item => item.id
]);
}
);
| Make event sorting stable and deterministic | Make event sorting stable and deterministic
| JavaScript | mit | webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp | ---
+++
@@ -17,6 +17,7 @@
documentType: 'article'
}));
events = events.map(event => ({ ...event, documentType: 'event' }));
+ const now = moment();
return sortBy(articles.concat(events), [
// Always sort pinned items first:
item => !item.pinned,
@@ -24,7 +25,7 @@
// For events we care about when the event starts, whereas for articles
// we look at when it was written:
const timeField = item.eventType ? item.startTime : item.createdAt;
- return Math.abs(moment().diff(timeField));
+ return Math.abs(now.diff(timeField));
},
item => item.id
]); |
4b09a703eecc3f5517dc70e51ee7abf8100fee87 | src/util/update-notification.js | src/util/update-notification.js | const updateNotification = () => {
document.addEventListener('DOMContentLoaded', () => {
if (Notification.permission !== 'granted') {
Notification.requestPermission()
}
})
if (!Notification) {
alert(
'Desktop notifications not available in your browser. Try Chromium.',
)
return
}
if (Notification.permission !== 'granted') {
Notification.requestPermission()
} else {
const notification = new Notification('NEW FEATURE: Tagging', {
icon: '/img/worldbrain-logo-narrow.png',
body: 'Click for more Information',
})
notification.onclick = () => {
window.open('https://worldbrain.helprace.com/i34-feature-tagging')
}
}
}
export default updateNotification
| const updateNotification = () => {
browser.notifications.create({
type: 'basic',
title: 'NEW FEATURE: Tagging',
iconUrl: '/img/worldbrain-logo-narrow.png',
message: 'Click for more Information',
buttons: [{ title: 'Click for more Information' }],
})
browser.notifications.onButtonClicked.addListener((id, index) => {
browser.notifications.clear(id)
window.open('https://worldbrain.helprace.com/i34-feature-tagging')
})
}
export default updateNotification
| Change Notification API when extension updated | Change Notification API when extension updated
| JavaScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -1,28 +1,16 @@
const updateNotification = () => {
- document.addEventListener('DOMContentLoaded', () => {
- if (Notification.permission !== 'granted') {
- Notification.requestPermission()
- }
+ browser.notifications.create({
+ type: 'basic',
+ title: 'NEW FEATURE: Tagging',
+ iconUrl: '/img/worldbrain-logo-narrow.png',
+ message: 'Click for more Information',
+ buttons: [{ title: 'Click for more Information' }],
})
- if (!Notification) {
- alert(
- 'Desktop notifications not available in your browser. Try Chromium.',
- )
- return
- }
- if (Notification.permission !== 'granted') {
- Notification.requestPermission()
- } else {
- const notification = new Notification('NEW FEATURE: Tagging', {
- icon: '/img/worldbrain-logo-narrow.png',
- body: 'Click for more Information',
- })
-
- notification.onclick = () => {
- window.open('https://worldbrain.helprace.com/i34-feature-tagging')
- }
- }
+ browser.notifications.onButtonClicked.addListener((id, index) => {
+ browser.notifications.clear(id)
+ window.open('https://worldbrain.helprace.com/i34-feature-tagging')
+ })
}
export default updateNotification |
3915cb47073b63826a539ef344b1580a4310dcc7 | gatsby-browser.js | gatsby-browser.js | import { anchorate } from "anchorate";
const subRoutes = ["/", "/team", "/work", "/contact"];
const isHomeRoute = route => subRoutes.indexOf(route) !== -1;
exports.onRouteUpdate = props => {
// anchorate({
// scroller: el => el.scrollIntoView({ behavior: 'smooth' })
// })
// if (isHomeRoute(props.location.pathname)) {
// const element = document.getElementById(props.location.pathname.slice(1))
// console.log(props.location.pathname.slice(1), element)
// if(element)
// element.scrollIntoView({ behavior: 'smooth' })
// }
};
// exports.shouldUpdateScroll = ({ prevRouterProps }) => {
// if (!prevRouterProps) return false
// const { history, location } = prevRouterProps
// console.log({
// shouldUpdateScroll: isHomeRoute(history.location.pathname) && isHomeRoute(location.pathname)
// })
// return isHomeRoute(history.location.pathname) && isHomeRoute(location.pathname)
// }
// exports.onClientEntry = () => {
// require("intersection-observer");
// };
| import { anchorate } from "anchorate";
const subRoutes = ["/", "/team", "/work", "/contact"];
const isHomeRoute = route => subRoutes.indexOf(route) !== -1;
exports.onRouteUpdate = props => {
// anchorate({
// scroller: el => el.scrollIntoView({ behavior: 'smooth' })
// })
// if (isHomeRoute(props.location.pathname)) {
// const element = document.getElementById(props.location.pathname.slice(1))
// console.log(props.location.pathname.slice(1), element)
// if(element)
// element.scrollIntoView({ behavior: 'smooth' })
// }
};
// exports.shouldUpdateScroll = ({ prevRouterProps }) => {
// if (!prevRouterProps) return false
// const { history, location } = prevRouterProps
// console.log({
// shouldUpdateScroll: isHomeRoute(history.location.pathname) && isHomeRoute(location.pathname)
// })
// return isHomeRoute(history.location.pathname) && isHomeRoute(location.pathname)
// }
exports.onClientEntry = () => {
require("intersection-observer");
};
| Bring back the IO polyfill. | Bring back the IO polyfill.
| JavaScript | mit | makersden/homepage,makersden/homepage | ---
+++
@@ -28,6 +28,6 @@
// return isHomeRoute(history.location.pathname) && isHomeRoute(location.pathname)
// }
-// exports.onClientEntry = () => {
-// require("intersection-observer");
-// };
+exports.onClientEntry = () => {
+ require("intersection-observer");
+}; |
8906ef023343ac92cdb7eb0b2835acf1d06fbef2 | bin/extract_references.js | bin/extract_references.js | #!/usr/bin/env node
var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
bcv.set_options({
'sequence_combination_strategy': 'separate'
});
bcv.include_apocrypha(true);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
var references = [];
function extract_references (data) {
var res = bcv.parse(data).osis_and_indices();
res.forEach(function(match) {
var ref = {};
ref.original = data.slice(match.indices[0], match.indices[1]);
ref.osis = match.osis;
references.push(ref);
});
}
function output_references () {
var output = JSON.stringify(references, null, ' ');
process.stdout.write(output);
}
rl.on('line', extract_references);
rl.on('close', output_references);
| #!/usr/bin/env node
var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
var formatter = require('bible-reference-formatter/es6/en');
bcv.set_options({
'sequence_combination_strategy': 'separate'
});
bcv.include_apocrypha(true);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
var references = [];
function extract_references (data) {
var res = bcv.parse(data).osis_and_indices();
res.forEach(function(match) {
var ref = {};
ref.original = data.slice(match.indices[0], match.indices[1]);
ref.osis = match.osis;
ref.reformat = formatter('niv-long', match.osis);
references.push(ref);
});
}
function output_references () {
var output = JSON.stringify(references, null, ' ');
process.stdout.write(output);
}
rl.on('line', extract_references);
rl.on('close', output_references);
| Add reformatted (EN) verse references to dump | Add reformatted (EN) verse references to dump
| JavaScript | agpl-3.0 | alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile | ---
+++
@@ -3,6 +3,7 @@
var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
+var formatter = require('bible-reference-formatter/es6/en');
bcv.set_options({
'sequence_combination_strategy': 'separate'
@@ -23,6 +24,7 @@
var ref = {};
ref.original = data.slice(match.indices[0], match.indices[1]);
ref.osis = match.osis;
+ ref.reformat = formatter('niv-long', match.osis);
references.push(ref);
});
} |
104b3f4f49f64fa66ef4bb03f0d01bb36013edfa | app/components/HomePage/ListView/ListViewport.js | app/components/HomePage/ListView/ListViewport.js | import {ToolViewport} from '../Tools';
import styled from 'styled-components';
export default styled(ToolViewport)`
background-color: none;
padding: 0 10px 0 50px;
position: relative;
&::before{
content: ' ';
width: 53px;
height: 1px;
border-bottom: 2px solid;
position: absolute;
top: 0px;
${p=>p.theme.isArabic?'right: 9px;':'left: 50px;'};
}
h3 {
padding-top: 5px;
}
`;
| import {ToolViewport} from '../Tools';
import styled from 'styled-components';
export default styled(ToolViewport)`
background-color: none;
padding: 0;
padding-${props=>props.theme.isArabic?'left':'right'}: 30px;
padding-${props=>props.theme.isArabic?'right':'left'}: 17px;
position: relative;
&::before{
content: ' ';
width: 53px;
height: 1px;
border-bottom: 2px solid;
position: absolute;
top: 0px;
${p=>p.theme.isArabic?'right: 9px;':'left: 17px;'};
}
h3 {
padding-top: 5px;
}
`;
| Fix on List View issues | Fix on List View issues
| JavaScript | mit | BeautifulTrouble/beautifulrising-client,BeautifulTrouble/beautifulrising-client | ---
+++
@@ -2,7 +2,10 @@
import styled from 'styled-components';
export default styled(ToolViewport)`
background-color: none;
- padding: 0 10px 0 50px;
+ padding: 0;
+ padding-${props=>props.theme.isArabic?'left':'right'}: 30px;
+ padding-${props=>props.theme.isArabic?'right':'left'}: 17px;
+
position: relative;
&::before{
@@ -12,7 +15,7 @@
border-bottom: 2px solid;
position: absolute;
top: 0px;
- ${p=>p.theme.isArabic?'right: 9px;':'left: 50px;'};
+ ${p=>p.theme.isArabic?'right: 9px;':'left: 17px;'};
}
h3 { |
1118e45e1a3a9803244eede35f6bf786fa1b65ca | blockblockadblock.user.js | blockblockadblock.user.js | // ==UserScript==
// @name blockblockadblock
// @namespace Mechazawa
// @include https://blockadblock.com/*
// @version 1
// @grant none
// @run-at document-start
// ==/UserScript==
// This is very dirty and should not be used
// I've found a more reliable vuln that I'll be exploiting soon
(function(window) {
var windowKeysDefault = Object.keys(window);
document.addEventListener('DOMContentLoaded', function() {
var windowKeysSuspect = Object.keys(window)
.filter(function(x){return windowKeysDefault.indexOf(x) === -1 && x.length == 12;})
.filter(function(x){return /\D\d\D/.exec(x) !== null;});
for(var i = 0; i < windowKeysSuspect.length; i++) {
delete window[windowKeysSuspect[i]];
}
console.log("Found and deleted suspect keys: " + windowKeysSuspect.join(','));
});
})(window); | // ==UserScript==
// @name blockblockadblock
// @namespace Mechazawa
// @include https://blockadblock.com/*
// @include https://mindgamer.com/*
// @version 1
// @grant none
// @run-at document-start
// ==/UserScript==
// This is very dirty and should not be used
// I've found a more reliable vuln that I'll be exploiting soon
(function(window) {
var windowKeysDefault = Object.keys(window);
var suspects = {};
window.getSuspects = function() { return suspects;}
document.addEventListener('DOMContentLoaded', function() {
var windowKeysSuspect = Object.keys(window)
.filter(function(x){return windowKeysDefault.indexOf(x) === -1 && x.length == 12;});
for(var i = 0; i < windowKeysSuspect.length; i++) {
var suspectName = windowKeysSuspect[i];
var suspect = window[suspectName];
var suspectKeys = Object.keys(suspect);
var found = false;
suspects[suspectName] = suspect;
for(var ii in suspectKeys) {
found = suspect[suspectKeys[ii]].toSource().indexOf('aW5zLmFkc2J5Z29vZ2xl') !== -1;
if(found) break;
}
if(found) {
console.log('Found BlockAdBlock with name ' + suspectName);
delete window[suspectName];
}
}
});
})(window); | Check for identifier in BlockAdBlock source before deleteing | Check for identifier in BlockAdBlock source before deleteing
| JavaScript | unlicense | Mechazawa/BlockBlockAdBlock | ---
+++
@@ -2,6 +2,7 @@
// @name blockblockadblock
// @namespace Mechazawa
// @include https://blockadblock.com/*
+// @include https://mindgamer.com/*
// @version 1
// @grant none
// @run-at document-start
@@ -13,16 +14,32 @@
// I've found a more reliable vuln that I'll be exploiting soon
(function(window) {
var windowKeysDefault = Object.keys(window);
+ var suspects = {};
+
+ window.getSuspects = function() { return suspects;}
document.addEventListener('DOMContentLoaded', function() {
var windowKeysSuspect = Object.keys(window)
- .filter(function(x){return windowKeysDefault.indexOf(x) === -1 && x.length == 12;})
- .filter(function(x){return /\D\d\D/.exec(x) !== null;});
+ .filter(function(x){return windowKeysDefault.indexOf(x) === -1 && x.length == 12;});
for(var i = 0; i < windowKeysSuspect.length; i++) {
- delete window[windowKeysSuspect[i]];
+ var suspectName = windowKeysSuspect[i];
+ var suspect = window[suspectName];
+ var suspectKeys = Object.keys(suspect);
+ var found = false;
+
+
+ suspects[suspectName] = suspect;
+
+ for(var ii in suspectKeys) {
+ found = suspect[suspectKeys[ii]].toSource().indexOf('aW5zLmFkc2J5Z29vZ2xl') !== -1;
+ if(found) break;
+ }
+
+ if(found) {
+ console.log('Found BlockAdBlock with name ' + suspectName);
+ delete window[suspectName];
+ }
}
-
- console.log("Found and deleted suspect keys: " + windowKeysSuspect.join(','));
});
})(window); |
6227f11cf2b3847d8e9b18abf4f449dccdec9009 | postcss.config.js | postcss.config.js | const postcssImport = require('postcss-import');
const nesting = require('postcss-nesting');
const autoprefixer = require('autoprefixer');
const csswring = require('csswring');
module.exports = {
plugins: [
postcssImport(),
nesting(),
autoprefixer({
browsers: [
'last 2 versions',
'not ie <= 11',
'not ie_mob <= 11',
],
}),
csswring(),
],
};
| const postcssImport = require('postcss-import');
const nesting = require('postcss-nesting');
const autoprefixer = require('autoprefixer');
const csswring = require('csswring');
module.exports = {
plugins: [
postcssImport(),
nesting(),
autoprefixer({
browsers: [
'last 1 version',
'not ie <= 11',
'not ie_mob <= 11',
],
}),
csswring(),
],
};
| Set Autoprefixer's targets to 'last 1 version | Set Autoprefixer's targets to 'last 1 version
| JavaScript | mit | nodaguti/word-quiz-generator-webapp,nodaguti/word-quiz-generator-webapp | ---
+++
@@ -9,7 +9,7 @@
nesting(),
autoprefixer({
browsers: [
- 'last 2 versions',
+ 'last 1 version',
'not ie <= 11',
'not ie_mob <= 11',
], |
98548f8330696e009a1e81af2d9b234d950c1d3f | tasks/htmlmin.js | tasks/htmlmin.js | /*
* grunt-contrib-htmlmin
* http://gruntjs.com/
*
* Copyright (c) 2012 Sindre Sorhus, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
var minify = require('html-minifier').minify;
var helper = require('grunt-lib-contrib').init(grunt);
grunt.registerMultiTask('htmlmin', 'Minify HTML', function () {
var options = this.options();
grunt.verbose.writeflags(options, 'Options');
this.files.forEach(function (file) {
var max = file.src.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
})
.map(grunt.file.read)
.join(grunt.util.normalizelf(grunt.util.linefeed));
var min = minify(max, options);
if (min.length < 1) {
grunt.log.warn('Destination not written because minified HTML was empty.');
} else {
grunt.file.write(file.dest, min);
grunt.log.writeln('File ' + file.dest + ' created.');
helper.minMaxInfo(min, max);
}
});
});
};
| /*
* grunt-contrib-htmlmin
* http://gruntjs.com/
*
* Copyright (c) 2012 Sindre Sorhus, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
var minify = require('html-minifier').minify;
var helper = require('grunt-lib-contrib').init(grunt);
grunt.registerMultiTask('htmlmin', 'Minify HTML', function () {
var options = this.options();
grunt.verbose.writeflags(options, 'Options');
this.files.forEach(function (file) {
var min;
var max = file.src.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
})
.map(grunt.file.read)
.join(grunt.util.normalizelf(grunt.util.linefeed));
try {
min = minify(max, options);
} catch (err) {
grunt.warn(file.src + '\n' + err);
}
if (min.length < 1) {
grunt.log.warn('Destination not written because minified HTML was empty.');
} else {
grunt.file.write(file.dest, min);
grunt.log.writeln('File ' + file.dest + ' created.');
helper.minMaxInfo(min, max);
}
});
});
};
| Stop executing when minify throws | Stop executing when minify throws
Fixes #16
| JavaScript | mit | gruntjs/grunt-contrib-htmlmin,gruntjs/grunt-contrib-htmlmin | ---
+++
@@ -17,6 +17,7 @@
grunt.verbose.writeflags(options, 'Options');
this.files.forEach(function (file) {
+ var min;
var max = file.src.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
@@ -29,7 +30,12 @@
.map(grunt.file.read)
.join(grunt.util.normalizelf(grunt.util.linefeed));
- var min = minify(max, options);
+ try {
+ min = minify(max, options);
+ } catch (err) {
+ grunt.warn(file.src + '\n' + err);
+ }
+
if (min.length < 1) {
grunt.log.warn('Destination not written because minified HTML was empty.');
} else { |
49b917705a28898398b388e3398ac95c14636985 | test/compiler.js | test/compiler.js | var should = require('should');
var QueryCompiler = require('../lib/compiler');
describe('QueryCompiler', function () {
describe.only('compile', function () {
it('compile ne null query', function () {
var query = {
attachmentId: { $ne: null }
};
var compiler = new QueryCompiler();
should.doesNotThrow(function () {
compiler.compile(query);
});
});
});
describe('_compilePredicates', function () {
it('compile eq query', function () {
var compiler = new QueryCompiler();
var p = compiler._compilePredicates({age:10});
p[0]({age:10}).should.be.true;
})
});
describe('_subQuery', function () {
it('compile eq query', function () {
var compiler = new QueryCompiler();
var p = compiler._subQuery([{age:10}]);
p[0]({age:10}).should.be.true;
})
});
});
| var should = require('should');
var QueryCompiler = require('../lib/compiler');
describe('QueryCompiler', function () {
describe('compile', function () {
it('compile ne null query', function () {
var query = {
attachmentId: { $ne: null }
};
var compiler = new QueryCompiler();
should.doesNotThrow(function () {
compiler.compile(query);
});
});
});
describe('_compilePredicates', function () {
it('compile eq query', function () {
var compiler = new QueryCompiler();
var p = compiler._compilePredicates({age:10});
p[0]({age:10}).should.be.true;
})
});
describe('_subQuery', function () {
it('compile eq query', function () {
var compiler = new QueryCompiler();
var p = compiler._subQuery([{age:10}]);
p[0]({age:10}).should.be.true;
})
});
});
| Remove .only from test case | Remove .only from test case
| JavaScript | mit | surikaterna/kuery | ---
+++
@@ -2,7 +2,7 @@
var QueryCompiler = require('../lib/compiler');
describe('QueryCompiler', function () {
- describe.only('compile', function () {
+ describe('compile', function () {
it('compile ne null query', function () {
var query = {
attachmentId: { $ne: null } |
a7dbce88aceca898c578a7fee62644feb9e07fd2 | test/examples.js | test/examples.js | var polyline = require( '..' )
var assert = require( 'assert' )
suite( 'Google Polyline Example', function() {
test( 'encode', function() {
var points = [
[ 38.5, -120.2 ],
[ 40.7, -120.95 ],
[ 43.252, -126.453 ]
]
var encoded = polyline.encode( points )
assert.equal( encoded, '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
})
test( 'decode' )
})
| var polyline = require( '..' )
var assert = require( 'assert' )
suite( 'Google Polyline Example', function() {
test( 'encode', function() {
var points = [
[ 38.5, -120.2 ],
[ 40.7, -120.95 ],
[ 43.252, -126.453 ]
]
var encoded = polyline.encode( points )
assert.equal( encoded, '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
})
test( 'decode', function() {
var points = polyline.decode( '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
var decoded = [
[ 38.5, -120.2 ],
[ 40.7, -120.95 ],
[ 43.252, -126.453 ]
]
assert.deepEqual( points, decoded )
})
})
| Update test: Add decoding test | Update test: Add decoding test
| JavaScript | mit | code42day/google-polyline | ---
+++
@@ -17,6 +17,17 @@
})
- test( 'decode' )
+ test( 'decode', function() {
+
+ var points = polyline.decode( '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
+ var decoded = [
+ [ 38.5, -120.2 ],
+ [ 40.7, -120.95 ],
+ [ 43.252, -126.453 ]
+ ]
+
+ assert.deepEqual( points, decoded )
+
+ })
}) |
753359fde8e0868df5a67e79e74c8ea5076c83aa | sort-stack.js | sort-stack.js | "use strict";
// Program that sorts a stack such that smallest items are on top
// create Stack class
function Stack() {
this.top = null;
}
// push value into stack
Stack.prototype.push = function(val) {
this.top = {
data: val,
next: this.top
};
};
// pop value from stack
Stack.prototype.pop = function() {
var top = this.top;
if(top) {
var popData = top.data;
top = top.next;
return popData;
}
return;
};
// sort stack in ascending order (main function in exercise)
Stack.prototype.sort = function() {
var stackTwo = new Stack();
while(this.top) {
var placeHolder = this.pop();
while(stackTwo.top && stackTwo.top.data > placeHolder) {
stackOne.push(stackTwo.pop());
}
stackTwo.push(placeHolder);
}
console.log(stackTwo);
};
| "use strict";
// Program that sorts a stack such that smallest items are on top
// create Stack class
function Stack() {
this.top = null;
}
// push value into stack
Stack.prototype.push = function(val) {
this.top = {
data: val,
next: this.top
};
};
// pop value from stack
Stack.prototype.pop = function() {
var top = this.top;
if(top) {
var popData = top.data;
top = top.next;
return popData;
}
return;
};
// sort stack in ascending order (main function in exercise)
Stack.prototype.sort = function() {
// create output stack
var stackTwo = new Stack();
while(this.top) {
var placeHolder = this.pop();
while(stackTwo.top && stackTwo.top.data > placeHolder) {
// push the top element in output stack (larger value) into original stack
stackOne.push(stackTwo.pop());
}
// push element in placeholder into output stack
stackTwo.push(placeHolder);
}
console.log(stackTwo);
};
| Add comments and pseudocode to sort function | Add comments and pseudocode to sort function
| JavaScript | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -28,14 +28,18 @@
// sort stack in ascending order (main function in exercise)
Stack.prototype.sort = function() {
+ // create output stack
var stackTwo = new Stack();
+
while(this.top) {
var placeHolder = this.pop();
while(stackTwo.top && stackTwo.top.data > placeHolder) {
+ // push the top element in output stack (larger value) into original stack
stackOne.push(stackTwo.pop());
}
+ // push element in placeholder into output stack
stackTwo.push(placeHolder);
}
console.log(stackTwo); |
7cfc6ee461d82c5ccc60d59d07daf99c392eb860 | style.js | style.js | module.exports = {
plugins: [
"filenames",
"prettier"
],
rules: {
// ERRORS
// No more bikeshedding on style; just use prettier
// https://github.com/not-an-aardvark/eslint-plugin-prettier
"prettier/prettier": ["error", { useTabs: true }],
// enforce lowercase kebab case for filenames
// we have had issues in the past with case sensitivity & module resolution
// https://github.com/selaux/eslint-plugin-filenames
"filenames/match-regex": ["error", "^[a-z\-\.]+$"],
// don't concatenate strings like a n00b
// http://eslint.org/docs/rules/prefer-template
"prefer-template": ["error"],
// =======================================================================================
// WARNINGS
// don't write a whole application in one single js file (default 301 lines is too big)
// http://eslint.org/docs/rules/max-lines
"max-lines": ["warn"],
// don't make ridiculous functions that take billions upon billions of arguments
// http://eslint.org/docs/rules/max-params
"max-params": ["warn", { max: 4 }]
}
}; | module.exports = {
plugins: [
"filenames",
"prettier"
],
rules: {
// ERRORS
// No more bikeshedding on style; just use prettier
// https://github.com/not-an-aardvark/eslint-plugin-prettier
"prettier/prettier": ["error", { useTabs: true }],
// enforce lowercase kebab case for filenames
// we have had issues in the past with case sensitivity & module resolution
// https://github.com/selaux/eslint-plugin-filenames
"filenames/match-regex": ["error", "^[a-z\-\.]+$"],
// don't concatenate strings like a n00b
// http://eslint.org/docs/rules/prefer-template
"prefer-template": ["error"],
// put a space after the comment slashes
// http://eslint.org/docs/rules/spaced-comment
"spaced-comment": ["error", "always"],
// =======================================================================================
// WARNINGS
// don't write a whole application in one single js file (default 301 lines is too big)
// http://eslint.org/docs/rules/max-lines
"max-lines": ["warn"],
// don't make ridiculous functions that take billions upon billions of arguments
// http://eslint.org/docs/rules/max-params
"max-params": ["warn", { max: 4 }]
}
}; | Add back missing comment rule | Add back missing comment rule
Prettier doesn't enforce anything in regards to comments
| JavaScript | mit | civicsource/eslint-config-civicsource | ---
+++
@@ -19,6 +19,10 @@
// http://eslint.org/docs/rules/prefer-template
"prefer-template": ["error"],
+ // put a space after the comment slashes
+ // http://eslint.org/docs/rules/spaced-comment
+ "spaced-comment": ["error", "always"],
+
// =======================================================================================
// WARNINGS
|
75af8619cba3e665419965d4a4108e61d202e857 | public/js/main.js | public/js/main.js | var server = io.connect('http://'+window.location.host);
$('#name').on('submit', function(e){
e.preventDefault();
$(this).hide();
$('#chat_form').show();
var name = $('#name_input').val()
server.emit('join', name)
$('#status').text('Status: Connected to chat')
});
$('#chat_form').on('submit', function(e){
e.preventDefault();
var message = $('#chat_input').val();
server.emit('messages', message);
});
server.on('messages', function(data){
insertMessage(data);
})
server.on('addUser', function(name){
insertUser(name)
})
server.on('removeUser', function(name){
$('#'+name).remove()
insertLeaveMessage(name)
})
function insertMessage(data) {
$('#chatbox').append('<p class="messages">'+data.name+data.message+'</p>')
if ($('#chatbox').children().length > 11){
$($('#chatbox').children()[3]).remove()
}
$('#chat_form #chat_input').val('')
}
function insertLeaveMessage(data) {
$('#chatbox').append('<p class="messages">'+data+' has left the chat</p>')
}
function insertUser(data){
$('#current_users').append('<p id='+data+'>'+data+'</p>')
} | var server = io.connect('https://'+window.location.host);
$('#name').on('submit', function(e){
e.preventDefault();
$(this).hide();
$('#chat_form').show();
var name = $('#name_input').val()
server.emit('join', name)
$('#status').text('Status: Connected to chat')
});
$('#chat_form').on('submit', function(e){
e.preventDefault();
var message = $('#chat_input').val();
server.emit('messages', message);
});
server.on('messages', function(data){
insertMessage(data);
})
server.on('addUser', function(name){
insertUser(name)
})
server.on('removeUser', function(name){
$('#'+name).remove()
insertLeaveMessage(name)
})
function insertMessage(data) {
$('#chatbox').append('<p class="messages">'+data.name+data.message+'</p>')
if ($('#chatbox').children().length > 11){
$($('#chatbox').children()[3]).remove()
}
$('#chat_form #chat_input').val('')
}
function insertLeaveMessage(data) {
$('#chatbox').append('<p class="messages">'+data+' has left the chat</p>')
}
function insertUser(data){
$('#current_users').append('<p id='+data+'>'+data+'</p>')
} | Change http back to https | Change http back to https
| JavaScript | mit | lawyu89/Simple_Chatroom,lawyu89/Simple_Chatroom | ---
+++
@@ -1,4 +1,4 @@
-var server = io.connect('http://'+window.location.host);
+var server = io.connect('https://'+window.location.host);
$('#name').on('submit', function(e){
e.preventDefault();
$(this).hide(); |
b3f0e0245ba31e22d21c42852c79ece24e052597 | src/text/Text.js | src/text/Text.js | import React, { PropTypes } from 'react';
import { Text, StyleSheet, Platform } from 'react-native';
import fonts from '../config/fonts';
import normalize from '../helpers/normalizeText';
let styles = {};
const TextElement = ({style, children, h1, h2, h3, h4, fontFamily}) => (
<Text
style={[
styles.text,
h1 && {fontSize: normalize(40)},
h2 && {fontSize: normalize(34)},
h3 && {fontSize: normalize(28)},
h4 && {fontSize: normalize(22)},
h1 && styles.bold,
h2 && styles.bold,
h3 && styles.bold,
h4 && styles.bold,
fontFamily && {fontFamily},
style && style
]}>{children}</Text>
);
TextElement.propTypes = {
style: PropTypes.any,
h1: PropTypes.bool,
h2: PropTypes.bool,
h3: PropTypes.bool,
h4: PropTypes.bool,
fontFamily: PropTypes.string,
children: PropTypes.any,
};
styles = StyleSheet.create({
text: {
...Platform.select({
android: {
...fonts.android.regular
}
})
},
bold: {
...Platform.select({
android: {
...fonts.android.bold
}
})
}
});
export default TextElement;
| import React, { PropTypes } from 'react';
import { Text, StyleSheet, Platform } from 'react-native';
import fonts from '../config/fonts';
import normalize from '../helpers/normalizeText';
TextElement.propTypes = {
style: PropTypes.any,
h1: PropTypes.bool,
h2: PropTypes.bool,
h3: PropTypes.bool,
h4: PropTypes.bool,
fontFamily: PropTypes.string,
children: PropTypes.any,
};
const styles = StyleSheet.create({
text: {
...Platform.select({
android: {
...fonts.android.regular
}
})
},
bold: {
...Platform.select({
android: {
...fonts.android.bold
}
})
}
});
const TextElement = (props) => {
const {
style,
children,
h1,
h2,
h3,
h4,
fontFamily,
...rest,
} = props;
return (
<Text
style={[
styles.text,
h1 && {fontSize: normalize(40)},
h2 && {fontSize: normalize(34)},
h3 && {fontSize: normalize(28)},
h4 && {fontSize: normalize(22)},
h1 && styles.bold,
h2 && styles.bold,
h3 && styles.bold,
h4 && styles.bold,
fontFamily && {fontFamily},
style && style
]}
{...rest}
>{children}</Text>
);
};
export default TextElement;
| Use ES6 spread forf rest of the props | Use ES6 spread forf rest of the props
In reference to #247
| JavaScript | mit | kosiakMD/react-native-elements,martinezguillaume/react-native-elements,react-native-community/React-Native-Elements,kosiakMD/react-native-elements | ---
+++
@@ -2,25 +2,6 @@
import { Text, StyleSheet, Platform } from 'react-native';
import fonts from '../config/fonts';
import normalize from '../helpers/normalizeText';
-
-let styles = {};
-
-const TextElement = ({style, children, h1, h2, h3, h4, fontFamily}) => (
- <Text
- style={[
- styles.text,
- h1 && {fontSize: normalize(40)},
- h2 && {fontSize: normalize(34)},
- h3 && {fontSize: normalize(28)},
- h4 && {fontSize: normalize(22)},
- h1 && styles.bold,
- h2 && styles.bold,
- h3 && styles.bold,
- h4 && styles.bold,
- fontFamily && {fontFamily},
- style && style
- ]}>{children}</Text>
-);
TextElement.propTypes = {
style: PropTypes.any,
@@ -32,7 +13,7 @@
children: PropTypes.any,
};
-styles = StyleSheet.create({
+const styles = StyleSheet.create({
text: {
...Platform.select({
android: {
@@ -49,4 +30,36 @@
}
});
+const TextElement = (props) => {
+ const {
+ style,
+ children,
+ h1,
+ h2,
+ h3,
+ h4,
+ fontFamily,
+ ...rest,
+ } = props;
+
+ return (
+ <Text
+ style={[
+ styles.text,
+ h1 && {fontSize: normalize(40)},
+ h2 && {fontSize: normalize(34)},
+ h3 && {fontSize: normalize(28)},
+ h4 && {fontSize: normalize(22)},
+ h1 && styles.bold,
+ h2 && styles.bold,
+ h3 && styles.bold,
+ h4 && styles.bold,
+ fontFamily && {fontFamily},
+ style && style
+ ]}
+ {...rest}
+ >{children}</Text>
+ );
+};
+
export default TextElement; |
4516a7ced770f11f0febe8aec0615ddbb8f6674b | src/modules/ngSharepoint/app.js | src/modules/ngSharepoint/app.js | angular
.module('ngSharepoint', [])
.run(function($sp, $spLoader) {
if ($sp.getAutoload()) {
if ($sp.getConnectionMode() === 'JSOM') {
$spLoader.loadScripts('SP.Core', ['//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js', 'SP.Runtime.js', 'SP.js']);
}else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken()) {
$spLoader.loadScript('SP.RequestExecutor.js');
}
}
}); | angular
.module('ngSharepoint', [])
.run(function($sp, $spLoader) {
if ($sp.getAutoload()) {
if ($sp.getConnectionMode() === 'JSOM') {
var scripts = [
'//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js',
'SP.Runtime.js',
'SP.js'
];
$spLoader.loadScripts('SP.Core', scripts);
}else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken()) {
$spLoader.loadScript('SP.RequestExecutor.js');
}
}
}); | Define scripts in a array instead of inline | Define scripts in a array instead of inline
| JavaScript | apache-2.0 | maxjoehnk/ngSharepoint | ---
+++
@@ -3,7 +3,12 @@
.run(function($sp, $spLoader) {
if ($sp.getAutoload()) {
if ($sp.getConnectionMode() === 'JSOM') {
- $spLoader.loadScripts('SP.Core', ['//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js', 'SP.Runtime.js', 'SP.js']);
+ var scripts = [
+ '//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js',
+ 'SP.Runtime.js',
+ 'SP.js'
+ ];
+ $spLoader.loadScripts('SP.Core', scripts);
}else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken()) {
$spLoader.loadScript('SP.RequestExecutor.js');
} |
0168687fb0b9e599e5bf1f25627006531624d114 | tests/docker.js | tests/docker.js | var assert = require("assert");
var spawn = require('child_process').spawn;
describe('Start docker container', function () {
it('should show M2 preamble', function (done) {
// ssh localhost
var docker = "docker";
var process = spawn(docker, ["run", "fhinkel/macaulay2", "M2"]);
var encoding = "utf8";
process.stderr.setEncoding(encoding);
process.stderr.on('data', function (data) {
console.log("Preamble: " + data);
assert(data.match(/Macaulay2, version 1\.\d/),
'M2 preamble does not match');
process.kill();
done();
});
process.on('error', function (error) {
assert(false, error);
next();
})
});
});
| var assert = require("assert");
var spawn = require('child_process').spawn;
describe('Start docker container', function () {
it('should show M2 preamble', function (done) {
// ssh localhost
var docker = "docker";
var process = spawn(docker, ["run", "fhinkel/macaulay2", "M2"]);
var encoding = "utf8";
process.stderr.setEncoding(encoding);
var result = "";
process.stderr.on('data', function (data) {
console.log("Preamble: " + data);
result += data;
});
process.on('error', function (error) {
assert(false, error);
next();
});
process.on('close', function() {
assert(result.match(/Macaulay2, version 1\.\d/),
'M2 preamble does not match');
done();
});
});
});
| Fix test to wait for output | Fix test to wait for output
| JavaScript | mit | fhinkel/InteractiveShell,antonleykin/InteractiveShell,antonleykin/InteractiveShell,antonleykin/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell | ---
+++
@@ -10,17 +10,20 @@
var process = spawn(docker, ["run", "fhinkel/macaulay2", "M2"]);
var encoding = "utf8";
process.stderr.setEncoding(encoding);
+ var result = "";
process.stderr.on('data', function (data) {
console.log("Preamble: " + data);
- assert(data.match(/Macaulay2, version 1\.\d/),
- 'M2 preamble does not match');
- process.kill();
- done();
+ result += data;
});
process.on('error', function (error) {
assert(false, error);
next();
- })
+ });
+ process.on('close', function() {
+ assert(result.match(/Macaulay2, version 1\.\d/),
+ 'M2 preamble does not match');
+ done();
+ });
});
}); |
3cd394442a4eb3000c83e2a427e5c544d629e7a7 | client/app/core/config.js | client/app/core/config.js | import { RootReducer } from '../reducers'
var DEVEL_DOMAINS = [
'localhost',
'127.0.0.1',
'[::1]'
]
var isDevel = window._.includes(DEVEL_DOMAINS, window.location.hostname)
const hasDevTools = angular.isDefined(window.__REDUX_DEVTOOLS_EXTENSION__)
/** @ngInject */
export function configure ($logProvider, $compileProvider, $qProvider, $ngReduxProvider) {
$logProvider.debugEnabled(isDevel)
$compileProvider.debugInfoEnabled(isDevel)
$qProvider.errorOnUnhandledRejections(false)
const storeEnhancers = []
if (hasDevTools) {
storeEnhancers.push(window.__REDUX_DEVTOOLS_EXTENSION__())
}
$ngReduxProvider.createStoreWith(RootReducer, [], storeEnhancers)
}
| import { RootReducer } from '../reducers'
var DEVEL_DOMAINS = [
'localhost',
'127.0.0.1',
'[::1]'
]
var isDevel = window._.includes(DEVEL_DOMAINS, window.location.hostname)
const hasDevTools = angular.isDefined(window.__REDUX_DEVTOOLS_EXTENSION__)
/** @ngInject */
export function configure ($logProvider, $compileProvider, $ngReduxProvider) {
$logProvider.debugEnabled(isDevel)
$compileProvider.debugInfoEnabled(isDevel)
const storeEnhancers = []
if (hasDevTools) {
storeEnhancers.push(window.__REDUX_DEVTOOLS_EXTENSION__())
}
$ngReduxProvider.createStoreWith(RootReducer, [], storeEnhancers)
}
| Revert "Disable $q unhandled rejection exceptions" | Revert "Disable $q unhandled rejection exceptions"
This reverts commit abe7f7f7e646781fff0ddc242223da84e0bc38a3.
Using Promise is wrong with angular,
we should get all unhandled rejection errors,
and fix them.
| JavaScript | apache-2.0 | ManageIQ/manageiq-ui-self_service,ManageIQ/manageiq-ui-self_service,ManageIQ/manageiq-ui-service,ManageIQ/manageiq-ui-service,ManageIQ/manageiq-ui-service,ManageIQ/manageiq-ui-self_service | ---
+++
@@ -8,10 +8,9 @@
var isDevel = window._.includes(DEVEL_DOMAINS, window.location.hostname)
const hasDevTools = angular.isDefined(window.__REDUX_DEVTOOLS_EXTENSION__)
/** @ngInject */
-export function configure ($logProvider, $compileProvider, $qProvider, $ngReduxProvider) {
+export function configure ($logProvider, $compileProvider, $ngReduxProvider) {
$logProvider.debugEnabled(isDevel)
$compileProvider.debugInfoEnabled(isDevel)
- $qProvider.errorOnUnhandledRejections(false)
const storeEnhancers = []
if (hasDevTools) {
storeEnhancers.push(window.__REDUX_DEVTOOLS_EXTENSION__()) |
4b1dc538fce1baba33efbc9f3b07ae0af3054eb7 | app/components/query-widget/component.js | app/components/query-widget/component.js | import Ember from 'ember';
export default Ember.Component.extend({
init () {
this._super(...arguments);
this.set("query", this.get("parameters").query);
},
actions: {
transitionToFacet(parameter) {
let queryParams = {};
queryParams["query"] = parameter;
this.attrs.transitionToFacet(this.get('item.facetDash'), queryParams);
}
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
init () {
this._super(...arguments);
this.set("query", this.get("parameters").query);
},
actions: {
transitionToFacet(parameter) {
let queryParams = {};
queryParams["query"] = parameter;
queryParams["page"] = undefined;
this.attrs.transitionToFacet(this.get('item.facetDash'), queryParams);
}
}
});
| Reset query parameter for page when hitting search | Reset query parameter for page when hitting search
| JavaScript | apache-2.0 | caneruguz/share-analytics,caneruguz/share-analytics,caneruguz/share-analytics | ---
+++
@@ -12,6 +12,7 @@
transitionToFacet(parameter) {
let queryParams = {};
queryParams["query"] = parameter;
+ queryParams["page"] = undefined;
this.attrs.transitionToFacet(this.get('item.facetDash'), queryParams);
}
|
2885aa520808d944b76387bc4f2dc8c9896c6dcf | src/transform/negate.js | src/transform/negate.js | var es = require("../es");
function Negate(transform, node) {
var expr = transform(node.expr);
if (typeof node.expr.data === "number") {
var literal = es.Literal(node.loc, node.expr.data);
return es.UnaryExpression(node.loc, true, "-", literal);
} else {
var negate = es.Identifier(node.loc, "$negate");
return es.CallExpression(null, negate, [expr]);
}
}
module.exports = Negate;
| var es = require("../es");
function Negate(transform, node) {
var expr = transform(node.expr);
if (node.expr.type === "Number") {
return es.UnaryExpression(node.loc, true, "-", transform(node.expr));
} else {
var negate = es.Identifier(node.loc, "$negate");
return es.CallExpression(null, negate, [expr]);
}
}
module.exports = Negate;
| Use proper type checking and transform function | Use proper type checking and transform function
As per Brians requests
| JavaScript | mit | wavebeem/squiggle,saikobee/expr-lang,squiggle-lang/squiggle-lang,saikobee/expr-lang,squiggle-lang/squiggle-lang,wavebeem/squiggle,squiggle-lang/squiggle-lang,saikobee/squiggle,saikobee/squiggle,saikobee/expr-lang,wavebeem/squiggle,saikobee/squiggle | ---
+++
@@ -2,9 +2,8 @@
function Negate(transform, node) {
var expr = transform(node.expr);
- if (typeof node.expr.data === "number") {
- var literal = es.Literal(node.loc, node.expr.data);
- return es.UnaryExpression(node.loc, true, "-", literal);
+ if (node.expr.type === "Number") {
+ return es.UnaryExpression(node.loc, true, "-", transform(node.expr));
} else {
var negate = es.Identifier(node.loc, "$negate");
return es.CallExpression(null, negate, [expr]); |
7f0af3ca94e821afe42d0b096c8a7b25d893920a | gulpfile.js | gulpfile.js | 'use strict'
var gulp = require('gulp');
var tsc = require('gulp-typescript');
gulp.task('copy', function () {
gulp.src('src/html/**')
.pipe(gulp.dest('dest/html'));
});
gulp.task('build', [
'copy'
]);
gulp.task('test-build', ['build'], function () {
gulp.src('test/src/ts/**/*.ts')
.pipe(tsc())
.pipe(gulp.dest('test/dest/js'));
});
gulp.task('default', ['build']);
| 'use strict'
var gulp = require('gulp');
var tsc = require('gulp-typescript');
gulp.task('copy', function () {
gulp.src('src/html/**')
.pipe(gulp.dest('dest/html'));
});
gulp.task('build', ['copy'], function () {
gulp.src('src/ts/**/*.ts')
.pipe(tsc())
.pipe(gulp.dest('dest/js'));
});
gulp.task('test-build', ['build'], function () {
gulp.src('test/src/ts/**/*.ts')
.pipe(tsc())
.pipe(gulp.dest('test/dest/js'));
});
gulp.task('default', ['build']);
| Edit task gulp.build: typescript build | Edit task gulp.build: typescript build
| JavaScript | mit | yajamon/freedomWarsPlantSimulator,yajamon/freedomWarsPlantSimulator | ---
+++
@@ -8,9 +8,11 @@
.pipe(gulp.dest('dest/html'));
});
-gulp.task('build', [
- 'copy'
-]);
+gulp.task('build', ['copy'], function () {
+ gulp.src('src/ts/**/*.ts')
+ .pipe(tsc())
+ .pipe(gulp.dest('dest/js'));
+});
gulp.task('test-build', ['build'], function () {
gulp.src('test/src/ts/**/*.ts') |
9a21a130e2ed9ae44ddf00ac367fdb66de81ce18 | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rirmaf = require('rimraf');
var lib = 'lib/**/*.js';
gulp.task('coverage', function(){
return gulp.src(lib)
.pipe($.istanbul());
});
gulp.task('coverage:clean', function(callback){
rirmaf('coverage', callback);
});
gulp.task('mocha', ['coverage'], function(){
return gulp.src('test/index.js')
.pipe($.mocha({
reporter: 'spec'
}))
.pipe($.istanbul.writeReports());
});
gulp.task('jshint', function(){
return gulp.src(lib)
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
});
gulp.task('watch', function(){
gulp.watch(lib, ['mocha', 'jshint']);
gulp.watch(['test/index.js'], ['mocha']);
});
gulp.task('test', ['mocha', 'jshint']);
| var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rirmaf = require('rimraf');
var lib = 'lib/**/*.js';
gulp.task('coverage', function(){
return gulp.src(lib)
.pipe($.istanbul())
.pipe($.istanbul.hookRequire());
});
gulp.task('coverage:clean', function(callback){
rirmaf('coverage', callback);
});
gulp.task('mocha', ['coverage'], function(){
return gulp.src('test/index.js')
.pipe($.mocha({
reporter: 'spec'
}))
.pipe($.istanbul.writeReports());
});
gulp.task('jshint', function(){
return gulp.src(lib)
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
});
gulp.task('watch', function(){
gulp.watch(lib, ['mocha', 'jshint']);
gulp.watch(['test/index.js'], ['mocha']);
});
gulp.task('test', ['mocha', 'jshint']);
| Fix gulp-istanbul 0.5.0 doesn't generate lcov file. | Fix gulp-istanbul 0.5.0 doesn't generate lcov file.
| JavaScript | mit | hexojs/hexo-fs,hexojs/hexo-fs | ---
+++
@@ -1,5 +1,3 @@
-'use strict';
-
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rirmaf = require('rimraf');
@@ -8,7 +6,8 @@
gulp.task('coverage', function(){
return gulp.src(lib)
- .pipe($.istanbul());
+ .pipe($.istanbul())
+ .pipe($.istanbul.hookRequire());
});
gulp.task('coverage:clean', function(callback){ |
f125ca538110ffed462a896e639b86e53d4492de | gulpfile.js | gulpfile.js | ///
var pkg = require("./package.json")
, gulp = require("gulp")
, plumber = require("gulp-plumber")
///
// Lint JS
///
var jshint = require("gulp-jshint")
, jsonFiles = [".jshintrc", "*.json"]
, jsFiles = ["*.js", "src/**/*.js"]
gulp.task("scripts.lint", function() {
gulp.src([].concat(jsonFiles).concat(jsFiles))
.pipe(plumber())
.pipe(jshint(".jshintrc"))
.pipe(jshint.reporter("jshint-stylish"))
})
var jscs = require("gulp-jscs")
gulp.task("scripts.cs", function() {
gulp.src(jsFiles)
.pipe(plumber())
.pipe(jscs())
})
gulp.task("scripts", ["scripts.lint", "scripts.cs"])
gulp.task("watch", function() {
gulp.watch(jsFiles, ["scripts"])
})
gulp.task("default", ["scripts", "watch"])
var buildBranch = require("buildbranch")
gulp.task("publish", function(cb) {
buildBranch({folder: "src"}
, function(err) {
if (err) {
throw err
}
console.log(pkg.name + " published.")
cb()
})
})
| ///
var pkg = require("./package.json")
, gulp = require("gulp")
, plumber = require("gulp-plumber")
///
// Lint JS
///
var jshint = require("gulp-jshint")
, jsonFiles = [".jshintrc", "*.json"]
, jsFiles = ["*.js", "src/**/*.js"]
gulp.task("scripts.lint", function() {
gulp.src([].concat(jsonFiles).concat(jsFiles))
.pipe(plumber())
.pipe(jshint(".jshintrc"))
.pipe(jshint.reporter("jshint-stylish"))
})
var jscs = require("gulp-jscs")
gulp.task("scripts.cs", function() {
gulp.src(jsFiles)
.pipe(plumber())
.pipe(jscs())
})
gulp.task("scripts", ["scripts.lint", "scripts.cs"])
gulp.task("watch", function() {
gulp.watch(jsFiles, ["scripts"])
})
gulp.task("dist", ["scripts"])
gulp.task("test", ["dist"])
gulp.task("default", ["test", "watch"])
var buildBranch = require("buildbranch")
gulp.task("publish", ["test"], function(cb) {
buildBranch({folder: "src"}
, function(err) {
if (err) {
throw err
}
console.log(pkg.name + " published.")
cb()
})
})
| Improve build task to run test before | Improve build task to run test before
| JavaScript | mit | MoOx/parallaxify,MoOx/parallaxify | ---
+++
@@ -29,10 +29,12 @@
gulp.watch(jsFiles, ["scripts"])
})
-gulp.task("default", ["scripts", "watch"])
+gulp.task("dist", ["scripts"])
+gulp.task("test", ["dist"])
+gulp.task("default", ["test", "watch"])
var buildBranch = require("buildbranch")
-gulp.task("publish", function(cb) {
+gulp.task("publish", ["test"], function(cb) {
buildBranch({folder: "src"}
, function(err) {
if (err) { |
b7fca936a31175610262b51bf618465dd72babbb | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var gulpTypescript = require('gulp-typescript');
var typescript = require('typescript');
var header = require('gulp-header');
var merge = require('merge2');
var pkg = require('./package.json');
var headerTemplate = '// <%= pkg.name %> v<%= pkg.version %>\n';
gulp.task('default', tscTask);
function tscTask() {
var tsResult = gulp
.src([
// this solves the 'cannot resolve Promise' issue
'node_modules/@types/core-js/index.d.ts',
'src/**/*.ts'
])
.pipe(gulpTypescript({
typescript: typescript,
module: 'commonjs',
experimentalDecorators: true,
emitDecoratorMetadata: true,
declarationFiles: true,
target: 'es5',
noImplicitAny: true,
noEmitOnError: false
}));
return merge([
tsResult.dts
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib')),
tsResult.js
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib'))
])
}
| var gulp = require('gulp');
var gulpTypescript = require('gulp-typescript');
var typescript = require('typescript');
var header = require('gulp-header');
var merge = require('merge2');
var pkg = require('./package.json');
var headerTemplate = '// <%= pkg.name %> v<%= pkg.version %>\n';
gulp.task('default', tscTask);
function tscTask() {
var tsResult = gulp
.src([
// this solves the 'cannot resolve Promise' issue
'node_modules/@types/core-js/index.d.ts',
'src/**/*.ts'
])
.pipe(gulpTypescript({
typescript: typescript,
module: 'commonjs',
experimentalDecorators: true,
emitDecoratorMetadata: true,
declarationFiles: true,
target: 'es5',
noImplicitAny: true,
noEmitOnError: false,
lib: ["dom","es2015"]
}));
return merge([
tsResult.dts
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib')),
tsResult.js
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib'))
])
}
| Add "lib" to typescript defs | Add "lib" to typescript defs
| JavaScript | mit | ceolter/angular-grid,ceolter/ag-grid,ceolter/angular-grid,ceolter/ag-grid | ---
+++
@@ -24,7 +24,8 @@
declarationFiles: true,
target: 'es5',
noImplicitAny: true,
- noEmitOnError: false
+ noEmitOnError: false,
+ lib: ["dom","es2015"]
}));
return merge([ |
2b57e2cf7ac3b3b20253f27c5adc98f58f77b6af | gulpfile.js | gulpfile.js | var gulp = require('gulp');
//var browserify = require('browserify');
var webpack = require('webpack');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var ENTRY = './src/build.js';
var DIST = './dist';
var FILE = 'math-light.js';
gulp.task('bundle', function (cb) {
var webpackConfig = {
entry: ENTRY,
output: {
library: 'math-light',
libraryTarget: 'commonjs2',
path: DIST,
filename: FILE
},
externals: [
'crypto' // is referenced by decimal.js
],
cache: false
};
var compiler = webpack(webpackConfig);
compiler.run(function (err, stats) {
if (err) {
console.log(err);
}
console.log('bundled');
cb();
});
});
gulp.task('uglify', ['bundle'], function () {
return gulp.src(DIST + '/' + FILE)
.pipe(uglify({
ie_proof: false
}))
.pipe(rename(function (path) {
path.basename += '.min';
}))
.pipe(gulp.dest(DIST));
});
gulp.task('test', function () {
return gulp.src('test/test.js')
.pipe(mocha());
});
gulp.task('default', ['uglify']);
| var gulp = require('gulp');
//var browserify = require('browserify');
var webpack = require('webpack');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var ENTRY = './src/build.js';
var DIST = './dist';
var FILE = 'math-light.js';
// Could be 'amd'
var MODULE_FORMAT = 'commonjs2';
gulp.task('bundle', function (cb) {
var webpackConfig = {
entry: ENTRY,
output: {
library: 'math-light',
libraryTarget: MODULE_FORMAT,
path: DIST,
filename: FILE
},
externals: [
'crypto' // is referenced by decimal.js
],
cache: false
};
var compiler = webpack(webpackConfig);
compiler.run(function (err, stats) {
if (err) {
console.log(err);
}
console.log('bundled');
cb();
});
});
gulp.task('uglify', ['bundle'], function () {
return gulp.src(DIST + '/' + FILE)
.pipe(uglify({
ie_proof: false
}))
.pipe(rename(function (path) {
path.basename += '.min';
}))
.pipe(gulp.dest(DIST));
});
gulp.task('test', function () {
return gulp.src('test/test.js')
.pipe(mocha());
});
gulp.task('default', ['uglify']);
| Make it easier to change the output module format | Make it easier to change the output module format
| JavaScript | apache-2.0 | jtsay362/solveforall-custom-mathjs-build | ---
+++
@@ -10,13 +10,15 @@
var ENTRY = './src/build.js';
var DIST = './dist';
var FILE = 'math-light.js';
+// Could be 'amd'
+var MODULE_FORMAT = 'commonjs2';
gulp.task('bundle', function (cb) {
var webpackConfig = {
entry: ENTRY,
output: {
library: 'math-light',
- libraryTarget: 'commonjs2',
+ libraryTarget: MODULE_FORMAT,
path: DIST,
filename: FILE
},
@@ -52,7 +54,7 @@
gulp.task('test', function () {
return gulp.src('test/test.js')
- .pipe(mocha());
+ .pipe(mocha());
});
gulp.task('default', ['uglify']); |
ebdefd648d4b5d143a25f2d1861de075f43b4fe1 | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var paths = {
js: ['./gulpfile.js', './test/**/*.js'],
scss: ['./stylesheets/_sass-lib.scss'],
test: ['./test/**/*.js']
};
var plumberOpts = {};
gulp.task('js-lint', function () {
return gulp.src(paths.js)
.pipe($.jshint('.jshintrc'))
.pipe($.plumber(plumberOpts))
.pipe($.jscs())
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('scss-lint', function() {
gulp.src(paths.scss)
.pipe($.scssLint())
.pipe($.plumber(plumberOpts));
});
gulp.task('test', function () {
return gulp.src(paths.test)
.pipe($.plumber(plumberOpts))
.pipe($.mocha());
});
gulp.task('lint', ['scss-lint', 'js-lint']);
gulp.task('test', ['lint']);
gulp.task('watch', ['test'], function () {
gulp.watch(paths.js, ['js-lint']);
gulp.watch(paths.scss, ['scss-lint']);
gulp.watch(paths.test, ['test']);
});
gulp.task('default', ['scss-lint', 'js-lint', 'test']);
| 'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var paths = {
js: ['./gulpfile.js', './test/**/*.js'],
scss: ['./stylesheets/_sass-lib.scss'],
test: ['./test/**/*.js']
};
var plumberOpts = {};
gulp.task('js-lint', function () {
return gulp.src(paths.js)
.pipe($.jshint('.jshintrc'))
.pipe($.plumber(plumberOpts))
.pipe($.jscs())
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('scss-lint', function() {
gulp.src(paths.scss)
.pipe($.scssLint())
.pipe($.plumber(plumberOpts));
});
gulp.task('test', function () {
return gulp.src(paths.test, {read: false})
.pipe($.plumber(plumberOpts))
.pipe($.mocha({reporter: 'nyan'}));
});
gulp.task('lint', ['scss-lint', 'js-lint']);
gulp.task('test', ['lint']);
gulp.task('watch', ['test'], function () {
gulp.watch(paths.js, ['js-lint']);
gulp.watch(paths.scss, ['scss-lint']);
gulp.watch(paths.test, ['test']);
});
gulp.task('default', ['scss-lint', 'js-lint', 'test']);
| Fix mocha implementation in test task | Fix mocha implementation in test task
| JavaScript | agpl-3.0 | Bastly/sass-lib | ---
+++
@@ -26,9 +26,9 @@
});
gulp.task('test', function () {
- return gulp.src(paths.test)
+ return gulp.src(paths.test, {read: false})
.pipe($.plumber(plumberOpts))
- .pipe($.mocha());
+ .pipe($.mocha({reporter: 'nyan'}));
});
gulp.task('lint', ['scss-lint', 'js-lint']); |
83743548c1cf5f3db5cf8a1405f2d432c62d7e1d | src/services/helpers/service.js | src/services/helpers/service.js | const randexp = require('randexp');
const promisify = require("es6-promisify");
const nodemailer = require('nodemailer');
module.exports = function(app) {
class MailService {
constructor() {
}
// POST
create({email, subject, content}, params) {
var transporter = nodemailer.createTransport(app.get("secrets").smtp);
var sendMail = promisify(transporter.sendMail, transporter);
return sendMail({
from: 'noreply@schul-cloud.org',
to: email,
subject: subject,
html: content.html,
text: content.text
});
}
}
return MailService;
};
| const randexp = require('randexp');
const promisify = require("es6-promisify");
const nodemailer = require('nodemailer');
module.exports = function(app) {
class MailService {
constructor() {
}
// POST
create({email, subject, content}, params) {
var transporter = nodemailer.createTransport(app.get("secrets").smtp || {});
var sendMail = promisify(transporter.sendMail, transporter);
return sendMail({
from: 'noreply@schul-cloud.org',
to: email,
subject: subject,
html: content.html,
text: content.text
});
}
}
return MailService;
};
| Fix nodemailer relying on unavailable secrets | Fix nodemailer relying on unavailable secrets
| JavaScript | agpl-3.0 | schul-cloud/schulcloud-server,schul-cloud/schulcloud-server,schul-cloud/schulcloud-server | ---
+++
@@ -11,7 +11,7 @@
// POST
create({email, subject, content}, params) {
- var transporter = nodemailer.createTransport(app.get("secrets").smtp);
+ var transporter = nodemailer.createTransport(app.get("secrets").smtp || {});
var sendMail = promisify(transporter.sendMail, transporter);
return sendMail({
from: 'noreply@schul-cloud.org', |
486968a19d4d7f05c33a0039c09f94006f885960 | src/utilities.js | src/utilities.js | import R from 'ramda';
import { NpmConfig, httpsGetPromise } from './helpers';
const addVersionProp = (val, key, obj) => obj[key] = { 'version': removeCaret(val) };
const removeCaret = R.replace(/\^/, '');
const isNotPrivate = R.compose(R.not, R.prop('private'));
const filterPrivate = R.filter(isNotPrivate);
const deeplyMerge = (obj1, obj2) => {
return R.keys(obj1).reduce((result, key) => {
result[key] = R.merge(obj1[key], obj2[key]);
return result;
}, {});
};
export const pickDownloads = (obj) => {
return R.keys(obj).reduce((result, key) => {
result[key] = R.pick(['downloads'], obj[key]);
return result;
}, {});
};
export const addNode = (obj) => {
obj.node = {
name : 'Node.js',
url : 'https://nodejs.org',
version : process.versions.node,
description : 'A JavaScript runtime ✨🐢🚀✨',
downloads : 10000000 // A fake number since Node isn't downloaded on npm
};
return obj;
};
export const curriedMerge = R.curry(deeplyMerge);
export const formatVersionsAndFilterPrivate = R.compose(R.mapObjIndexed(addVersionProp), filterPrivate);
export const getNpmData = R.compose(httpsGetPromise, NpmConfig);
| import R from 'ramda';
import { NpmConfig, httpsGetPromise } from './helpers';
const addVersionProp = (val, key, obj) => obj[key] = { 'version': removeCaret(val) };
const removeCaret = R.replace(/\^/, '');
const isNotPrivate = R.compose(R.not, R.prop('private'));
const filterPrivate = R.filter(isNotPrivate);
const pickProps = R.curry(R.pick);
const deeplyMerge = (obj1, obj2) => {
return R.keys(obj1).reduce((result, key) => {
result[key] = R.merge(obj1[key], obj2[key]);
return result;
}, {});
};
export const addNode = (obj) => {
obj.node = {
name : 'Node.js',
url : 'https://nodejs.org',
version : process.versions.node,
description : 'A JavaScript runtime ✨🐢🚀✨',
downloads : 10000000 // A fake number since Node isn't downloaded on npm
};
return obj;
};
export const pickDownloads = R.map(pickProps(['downloads']));
export const curriedMerge = R.curry(deeplyMerge);
export const formatVersionsAndFilterPrivate = R.compose(R.mapObjIndexed(addVersionProp), filterPrivate);
export const getNpmData = R.compose(httpsGetPromise, NpmConfig);
| Rewrite pickDownloads as Ramda function | refactor: Rewrite pickDownloads as Ramda function
| JavaScript | mit | cachilders/backpat,churchie317/backpat | ---
+++
@@ -5,17 +5,11 @@
const removeCaret = R.replace(/\^/, '');
const isNotPrivate = R.compose(R.not, R.prop('private'));
const filterPrivate = R.filter(isNotPrivate);
+const pickProps = R.curry(R.pick);
const deeplyMerge = (obj1, obj2) => {
return R.keys(obj1).reduce((result, key) => {
result[key] = R.merge(obj1[key], obj2[key]);
- return result;
- }, {});
-};
-
-export const pickDownloads = (obj) => {
- return R.keys(obj).reduce((result, key) => {
- result[key] = R.pick(['downloads'], obj[key]);
return result;
}, {});
};
@@ -31,6 +25,7 @@
return obj;
};
+export const pickDownloads = R.map(pickProps(['downloads']));
export const curriedMerge = R.curry(deeplyMerge);
export const formatVersionsAndFilterPrivate = R.compose(R.mapObjIndexed(addVersionProp), filterPrivate);
export const getNpmData = R.compose(httpsGetPromise, NpmConfig); |
196c268ec7913ce0aba8afb6ec0eb27bc3abd325 | src/promise-array.js | src/promise-array.js | import {Observable} from 'rx';
export function asyncMap(array, selector, maxConcurrency=4) {
return Observable.from(array)
.map((k) =>
Observable.defer(() =>
Observable.fromPromise(selector(k))
.map((v) => ({ k, v }))))
.merge(maxConcurrency)
.reduce((acc, kvp) => {
acc[kvp.k] = kvp.v;
return acc;
}, {})
.toPromise();
}
| import {Observable} from 'rx';
const spawnOg = require('child_process').spawn;
export function asyncMap(array, selector, maxConcurrency=4) {
return Observable.from(array)
.map((k) =>
Observable.defer(() =>
Observable.fromPromise(selector(k))
.map((v) => ({ k, v }))))
.merge(maxConcurrency)
.reduce((acc, kvp) => {
acc[kvp.k] = kvp.v;
return acc;
}, {})
.toPromise();
}
export function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// Public: Maps a process's output into an {Observable}
//
// exe - The program to execute
// params - Arguments passed to the process
// opts - Options that will be passed to child_process.spawn
//
// Returns a {Promise} with a single value, that is the output of the
// spawned process
export function spawn(exe, params, opts=null) {
let spawnObs = Observable.create((subj) => {
let proc = null;
if (!opts) {
proc = spawnOg(exe, params);
} else {
proc = spawnOg(exe, params, opts);
}
let stdout = '';
let bufHandler = (b) => {
let chunk = b.toString();
stdout += chunk;
subj.onNext(chunk);
};
proc.stdout.on('data', bufHandler);
proc.stderr.on('data', bufHandler);
proc.on('error', (e) => subj.onError(e));
proc.on('close', (code) => {
if (code === 0) {
subj.onCompleted();
} else {
subj.onError(new Error(`Failed with exit code: ${code}\nOutput:\n${stdout}`));
}
});
});
return spawnObs.reduce((acc, x) => acc += x, '').toPromise();
}
| Copy over a promise version of spawn and delay | Copy over a promise version of spawn and delay
| JavaScript | mit | surf-build/surf,surf-build/surf,surf-build/surf,surf-build/surf | ---
+++
@@ -1,4 +1,5 @@
import {Observable} from 'rx';
+const spawnOg = require('child_process').spawn;
export function asyncMap(array, selector, maxConcurrency=4) {
return Observable.from(array)
@@ -13,3 +14,51 @@
}, {})
.toPromise();
}
+
+export function delay(ms) {
+ return new Promise((resolve) => {
+ setTimeout(resolve, ms);
+ });
+}
+
+// Public: Maps a process's output into an {Observable}
+//
+// exe - The program to execute
+// params - Arguments passed to the process
+// opts - Options that will be passed to child_process.spawn
+//
+// Returns a {Promise} with a single value, that is the output of the
+// spawned process
+export function spawn(exe, params, opts=null) {
+ let spawnObs = Observable.create((subj) => {
+ let proc = null;
+
+ if (!opts) {
+ proc = spawnOg(exe, params);
+ } else {
+ proc = spawnOg(exe, params, opts);
+ }
+
+ let stdout = '';
+ let bufHandler = (b) => {
+ let chunk = b.toString();
+
+ stdout += chunk;
+ subj.onNext(chunk);
+ };
+
+ proc.stdout.on('data', bufHandler);
+ proc.stderr.on('data', bufHandler);
+ proc.on('error', (e) => subj.onError(e));
+
+ proc.on('close', (code) => {
+ if (code === 0) {
+ subj.onCompleted();
+ } else {
+ subj.onError(new Error(`Failed with exit code: ${code}\nOutput:\n${stdout}`));
+ }
+ });
+ });
+
+ return spawnObs.reduce((acc, x) => acc += x, '').toPromise();
+} |
578bfe10cb2dd434c36e837c0d4b687eb0d2a3ba | lib/autoupdate.js | lib/autoupdate.js | "use strict";
var path = require('path');
/**
* Initializes the crx autoupdate grunt helper
*
* @param {grunt} grunt
* @returns {{buildXML: Function, build: Function}}
*/
exports.init = function(grunt){
/**
* Generates an autoupdate XML file
*
* @todo relocate that to {@link lib/crx.js} as it's totally irrelevant now
* @param {crx} ChromeExtension
* @param {Function} callback
*/
function buildXML(ChromeExtension, callback) {
if (!ChromeExtension.manifest.update_url || !ChromeExtension.codebase){
callback();
}
ChromeExtension.generateUpdateXML();
var dest = path.dirname(ChromeExtension.dest);
var filename = path.join(dest, path.basename(ChromeExtension.manifest.update_url));
grunt.file.write(filename, ChromeExtension.updateXML);
callback();
}
/*
* Blending
*/
return {
"buildXML": buildXML,
/** @deprecated (will be removed in 0.3) */
"build": buildXML
};
}; | "use strict";
var path = require('path');
/**
* Initializes the crx autoupdate grunt helper
*
* @param {grunt} grunt
* @returns {{buildXML: Function, build: Function}}
*/
exports.init = function(grunt){
/**
* Generates an autoupdate XML file
*
* @todo relocate that to {@link lib/crx.js} as it's totally irrelevant now
* @param {crx} ChromeExtension
* @param {Function} callback
*/
function buildXML(ChromeExtension, callback) {
if (!ChromeExtension.manifest.update_url || !ChromeExtension.codebase){
callback();
return;
}
ChromeExtension.generateUpdateXML();
var dest = path.dirname(ChromeExtension.dest);
var filename = path.join(dest, path.basename(ChromeExtension.manifest.update_url));
grunt.file.write(filename, ChromeExtension.updateXML);
callback();
}
/*
* Blending
*/
return {
"buildXML": buildXML,
/** @deprecated (will be removed in 0.3) */
"build": buildXML
};
}; | Fix buildXML() call for extension w/o update_url | Fix buildXML() call for extension w/o update_url
| JavaScript | mit | oncletom/grunt-crx,oncletom/grunt-crx | ---
+++
@@ -19,6 +19,7 @@
function buildXML(ChromeExtension, callback) {
if (!ChromeExtension.manifest.update_url || !ChromeExtension.codebase){
callback();
+ return;
}
ChromeExtension.generateUpdateXML(); |
accc090267f36417b578d1e3254ae2671599a62c | stream-meteor.js | stream-meteor.js | var apiKey = Meteor.settings.public.streamApiKey,
apiAppId = Meteor.settings.public.streamApiAppId;
var settings = _.clone(Config);
settings['apiKey'] = apiKey;
settings['apiAppId'] = apiAppId;
if (Meteor.isServer) {
Stream.stream = Npm.require('getstream');
settings['apiSecret'] = Meteor.settings.streamApiSecret;
}
Stream.feedManager = new FeedManager(settings); | var apiKey = Meteor.settings.public.streamApiKey,
apiAppId = Meteor.settings.public.streamApiAppId;
var settings = _.clone(Config);
if(! apiKey) {
throw new Meteor.Error('misconfig', 'No getstream.io app api key found in your settings.json\n hint: Are you running meteor with --settings settings.json?');
}
if(! apiAppId) {
throw new Meteor.Error('misconfig', 'No getstream.io app id key found in your settings.json\n hint: Are you running meteor with --settings settings.json?');
}
settings['apiKey'] = apiKey;
settings['apiAppId'] = apiAppId;
if (Meteor.isServer) {
Stream.stream = Npm.require('getstream');
if(! Meteor.settings.streamApiSecret) {
throw new Meteor.Error('misconfig', 'No getstream.io private key found in your settings.json\n hint: Are you running meteor with --settings settings.json?');
}
settings['apiSecret'] = Meteor.settings.streamApiSecret;
}
if(Meteor.settings.userFeed) {
settings['userFeed'] = Meteor.settings.userFeed;
}
if(Meteor.settings.notificationFeed) {
settings['notificationFeed'] = Meteor.settings.notificationFeed;
}
if(Meteor.settings.newsFeeds) {
settings['newsFeeds'] = Meteor.settings.newsFeeds;
}
Stream.feedManager = new FeedManager(settings); | Check if correct settings are available | Check if correct settings are available
| JavaScript | bsd-3-clause | GetStream/stream-meteor | ---
+++
@@ -2,6 +2,14 @@
apiAppId = Meteor.settings.public.streamApiAppId;
var settings = _.clone(Config);
+
+if(! apiKey) {
+ throw new Meteor.Error('misconfig', 'No getstream.io app api key found in your settings.json\n hint: Are you running meteor with --settings settings.json?');
+}
+
+if(! apiAppId) {
+ throw new Meteor.Error('misconfig', 'No getstream.io app id key found in your settings.json\n hint: Are you running meteor with --settings settings.json?');
+}
settings['apiKey'] = apiKey;
settings['apiAppId'] = apiAppId;
@@ -9,7 +17,22 @@
if (Meteor.isServer) {
Stream.stream = Npm.require('getstream');
+ if(! Meteor.settings.streamApiSecret) {
+ throw new Meteor.Error('misconfig', 'No getstream.io private key found in your settings.json\n hint: Are you running meteor with --settings settings.json?');
+ }
settings['apiSecret'] = Meteor.settings.streamApiSecret;
}
+if(Meteor.settings.userFeed) {
+ settings['userFeed'] = Meteor.settings.userFeed;
+}
+
+if(Meteor.settings.notificationFeed) {
+ settings['notificationFeed'] = Meteor.settings.notificationFeed;
+}
+
+if(Meteor.settings.newsFeeds) {
+ settings['newsFeeds'] = Meteor.settings.newsFeeds;
+}
+
Stream.feedManager = new FeedManager(settings); |
8bcd61b8cea323f6060b2d90ec94d3e1fb7190f4 | src/add_days.js | src/add_days.js | var parse = require('./parse')
/**
* @category Day Helpers
* @summary Get the day of the month
*
* Add the specified number of days to the given date.
*
* @param {Date|String|Number} date to be changed
* @param {Number} amount of days to be added
* @returns {Date} new date with the days added
*/
var addDays = function(dirtyDate, amount) {
var date = parse(dirtyDate)
date.setDate(date.getDate() + amount)
return date
}
module.exports = addDays
| var parse = require('./parse')
/**
* @category Day Helpers
* @summary Get the day of the month.
*
* Add the specified number of days to the given date.
*
* @param {Date|String|Number} date to be changed
* @param {Number} amount of days to be added
* @returns {Date} new date with the days added
*/
var addDays = function(dirtyDate, amount) {
var date = parse(dirtyDate)
date.setDate(date.getDate() + amount)
return date
}
module.exports = addDays
| Add forgotten dot in addDays JSDoc block | Add forgotten dot in addDays JSDoc block
| JavaScript | mit | js-fns/date-fns,date-fns/date-fns,date-fns/date-fns,date-fns/date-fns,js-fns/date-fns | ---
+++
@@ -2,7 +2,7 @@
/**
* @category Day Helpers
- * @summary Get the day of the month
+ * @summary Get the day of the month.
*
* Add the specified number of days to the given date.
* |
31bd052a42f825f3dbc4b28fcd6d998db558f91e | ui/routes/api.js | ui/routes/api.js | var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('/home/pi/homeauto/backend/temp.db');
/* GET home page. */
router.get('/v1/temperature', function(req, res, next) {
var filter = "WHERE sensor_fk = 1";
if(req.query.starttime && req.query.endtime) {
filter += " AND time >= " + req.query.starttime + " AND time <= " + req.query.endtime;
} else if(req.query.starttime) {
filter += " AND time >= " + req.query.starttime;
} else if(req.query.endtime) {
filter += " AND time <= " + req.query.endtime;
}
var stmt = "SELECT * FROM sensorstream " + filter + " ORDER BY time";
console.log(stmt)
db.all(stmt, function(err, rows) {
res.send(rows);
});
});
router.get('/v1/temperature/current', function(req, res, next) {
db.all("SELECT * FROM sensorstream WHERE sensor_fk = 1 ORDER BY time DESC LIMIT 1", function(err, rows) {
res.send(rows);
});
});
router.get('/v1/sensorstream/:id', function(req, res, next) {
var sensor_id = req.params.id;
console.log("sensor id: " + id)
});
module.exports = router;
| var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('/home/pi/homeauto/backend/temp.db');
/* GET home page. */
router.get('/v1/temperature', function(req, res, next) {
var filter = "WHERE sensor_fk = 1";
if(req.query.starttime && req.query.endtime) {
filter += " AND time >= " + req.query.starttime + " AND time <= " + req.query.endtime;
} else if(req.query.starttime) {
filter += " AND time >= " + req.query.starttime;
} else if(req.query.endtime) {
filter += " AND time <= " + req.query.endtime;
}
var stmt = "SELECT * FROM sensorstream " + filter + " ORDER BY time";
console.log(stmt)
db.all(stmt, function(err, rows) {
res.send(rows);
});
});
router.get('/v1/temperature/current', function(req, res, next) {
db.all("SELECT * FROM sensorstream WHERE sensor_fk = 1 ORDER BY time DESC LIMIT 1", function(err, rows) {
res.send(rows);
});
});
router.get('/v1/sensorstream/:id', function(req, res, next) {
var sensor_id = req.params.id;
console.log("sensor id: " + id)
res.send({})
});
module.exports = router;
| Add response to sensor stream API handler | Add response to sensor stream API handler
| JavaScript | mit | schmidtfx/homeauto,schmidtfx/homeauto,schmidtfx/homeauto | ---
+++
@@ -31,6 +31,7 @@
router.get('/v1/sensorstream/:id', function(req, res, next) {
var sensor_id = req.params.id;
console.log("sensor id: " + id)
+ res.send({})
});
module.exports = router; |
fbfb0324b04b8fd3c82f531dea9552abf1509eb9 | lib/log-writer.js | lib/log-writer.js | var util = require('util');
var stream = require('stream');
var fs = require('fs');
var generateLogName = require('./logname').generate;
module.exports = LogWriter;
function LogWriter(worker, options) {
if (!(this instanceof LogWriter)) return new LogWriter(worker, options);
stream.PassThrough.call(this);
this.template = options.log;
this.worker = {
id: worker.id || 'supervisor',
pid: worker.pid || worker.process.pid
}
this.name = generateLogName(this.template, this.worker);
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
this.pipe(this.sink);
}
util.inherits(LogWriter, stream.PassThrough);
LogWriter.prototype.reOpen = function LogWriterReOpen() {
if (this.sink instanceof fs.WriteStream) {
this.unpipe(this.sink);
this.sink.end();
// lose our reference to previous stream, but it should clean itself up
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
this.pipe(sink);
}
}
| var util = require('util');
var stream = require('stream');
var fs = require('fs');
var spawn = require('child_process').spawn;
var generateLogName = require('./logname').generate;
module.exports = LogWriter;
function LogWriter(worker, options) {
if (!(this instanceof LogWriter)) return new LogWriter(worker, options);
stream.PassThrough.call(this);
this.template = options.log;
this.worker = {
id: worker.id || 'supervisor',
pid: worker.pid || worker.process.pid
}
this.name = generateLogName(this.template, this.worker);
if (/^\|[^\|]/.test(this.name)) {
this.cmd = this.name
.slice(1) // strip leading '|'
.trim()
.split(/\s+/);
this.proc = spawn(this.cmd[0], this.cmd.slice(1),
{ stdio: ['pipe', process.stdout, process.stderr] });
this.sink = this.proc.stdin;
} else {
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
}
this.pipe(this.sink);
}
util.inherits(LogWriter, stream.PassThrough);
LogWriter.prototype.reOpen = function LogWriterReOpen() {
if (this.sink instanceof fs.WriteStream) {
this.unpipe(this.sink);
this.sink.end();
// lose our reference to previous stream, but it should clean itself up
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
this.pipe(sink);
}
}
| Add support for '| cmd' as log name for piping | Add support for '| cmd' as log name for piping
Create a child process as described by the log parameter following the
leading '|' and write all log events to that process's stdin stream.
The command name supports %p and %w replacement for per-worker logging.
If per-worker substitutions are made, each worker gets its own logger
process. If the command does not use per-worker substitutions, all
workers and the supervisor share the same logger process.
| JavaScript | artistic-2.0 | shelbys/strong-supervisor | ---
+++
@@ -1,6 +1,7 @@
var util = require('util');
var stream = require('stream');
var fs = require('fs');
+var spawn = require('child_process').spawn;
var generateLogName = require('./logname').generate;
@@ -17,7 +18,17 @@
pid: worker.pid || worker.process.pid
}
this.name = generateLogName(this.template, this.worker);
- this.sink = fs.createWriteStream(this.name, { flags: 'a'});
+ if (/^\|[^\|]/.test(this.name)) {
+ this.cmd = this.name
+ .slice(1) // strip leading '|'
+ .trim()
+ .split(/\s+/);
+ this.proc = spawn(this.cmd[0], this.cmd.slice(1),
+ { stdio: ['pipe', process.stdout, process.stderr] });
+ this.sink = this.proc.stdin;
+ } else {
+ this.sink = fs.createWriteStream(this.name, { flags: 'a'});
+ }
this.pipe(this.sink);
}
|
7a0813a41afca49b7fe73367a6707f4379353009 | test/findAssets.spec.js | test/findAssets.spec.js | const path = require('path');
const expect = require('chai').expect;
const findAssets = require('../src/config/findAssets');
const mockFs = require('mock-fs');
const dependencies = require('./fixtures/dependencies');
describe('findAssets', () => {
before(() => {
mockFs({ testDir: dependencies });
});
it('should return an array of all files in given folders', () => {
const assets = findAssets(
path.join('testDir', 'withAssets'),
['fonts', 'images']
);
expect(assets).to.be.an('array');
expect(assets.length).to.equal(3);
});
it('should return absoulte paths to assets', () => {
const folder = path.join('testDir', 'withAssets');
const assets = findAssets(
path.join('testDir', 'withAssets'),
['fonts', 'images']
);
assets.forEach(assetPath => expect(assetPath).to.contain(folder));
});
after(() => {
mockFs.restore();
});
});
| const path = require('path');
const expect = require('chai').expect;
const findAssets = require('../src/config/findAssets');
const mockFs = require('mock-fs');
const dependencies = require('./fixtures/dependencies');
describe('findAssets', () => {
before(() => {
mockFs({ testDir: dependencies.withAssets });
});
it('should return an array of all files in given folders', () => {
const assets = findAssets('testDir', ['fonts', 'images']);
expect(assets).to.be.an('array');
expect(assets.length).to.equal(3);
});
it('should return absoulte paths to assets', () => {
const assets = findAssets('testDir', ['fonts', 'images']);
assets.forEach(assetPath => expect(assetPath).to.contain('testDir'));
});
after(() => {
mockFs.restore();
});
});
| Use only fixtures we need | Use only fixtures we need
| JavaScript | mit | rnpm/rnpm | ---
+++
@@ -7,27 +7,20 @@
describe('findAssets', () => {
before(() => {
- mockFs({ testDir: dependencies });
+ mockFs({ testDir: dependencies.withAssets });
});
it('should return an array of all files in given folders', () => {
- const assets = findAssets(
- path.join('testDir', 'withAssets'),
- ['fonts', 'images']
- );
+ const assets = findAssets('testDir', ['fonts', 'images']);
expect(assets).to.be.an('array');
expect(assets.length).to.equal(3);
});
it('should return absoulte paths to assets', () => {
- const folder = path.join('testDir', 'withAssets');
- const assets = findAssets(
- path.join('testDir', 'withAssets'),
- ['fonts', 'images']
- );
+ const assets = findAssets('testDir', ['fonts', 'images']);
- assets.forEach(assetPath => expect(assetPath).to.contain(folder));
+ assets.forEach(assetPath => expect(assetPath).to.contain('testDir'));
});
after(() => { |
b9913a7f583825b76da298d9d2275a5f1565f18e | test/reverse_urlSpec.js | test/reverse_urlSpec.js | (function () {
'use strict';
var reverseUrl, $route;
var routeMock = {};
routeMock.routes = {
'/testRoute1/': {
controller: 'TestController1',
originalPath: '/test-route-1/'
},
'/testRoute1/:params/': {
controller: 'TestController1',
originalPath: '/test-route-1/:param/'
},
'/testRoute2/': {
name: 'TestRoute2',
originalPath: '/test-route-2/'
},
};
describe('Unit: angular-reverse-url', function () {
beforeEach(module('angular-reverse-url', function ($provide) {
$provide.value('$route', routeMock);
}));
describe('reverseUrl filter', function () {
beforeEach(inject(function ($injector) {
$route = $injector.get('$route')
reverseUrl = $injector.get('$filter')('reverseUrl');
}));
it('should correctly match to a basic route by controller', function () {
expect(reverseUrl('TestController1')).toEqual('#/test-route-1/');
});
it('should correctly match to a basic route by name', function () {
expect(reverseUrl('TestRoute2')).toEqual('#/test-route-2/');
});
it('should correctly match to a route with params', function () {
expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/');
});
});
});
}());
| (function () {
'use strict';
var reverseUrl, $route;
var routeMock = {};
routeMock.routes = {
'/testRoute1/': {
controller: 'TestController1',
originalPath: '/test-route-1/'
},
'/testRoute1/:params/': {
controller: 'TestController1',
originalPath: '/test-route-1/:param/'
},
'/testRoute2/': {
name: 'TestRoute2',
originalPath: '/test-route-2/'
},
};
describe('Unit: angular-reverse-url', function () {
beforeEach(module('angular-reverse-url', function ($provide) {
$provide.value('$route', routeMock);
}));
describe('reverseUrl filter', function () {
beforeEach(inject(function ($injector) {
$route = $injector.get('$route')
reverseUrl = $injector.get('$filter')('reverseUrl');
}));
it('should correctly match to a basic route by controller', function () {
expect(reverseUrl('TestController1')).toEqual('#/test-route-1/');
});
it('should correctly match to a basic route by name', function () {
expect(reverseUrl('TestRoute2')).toEqual('#/test-route-2/');
});
it('should correctly match to a route with params', function () {
expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/');
});
it('should log an error if a route is not found');
it('should log an error if params are required and missing');
it('should log an error if params keys are not found');
});
});
}());
| Add assertions for error logging | Add assertions for error logging
| JavaScript | mit | incuna/angular-reverse-url | ---
+++
@@ -45,6 +45,12 @@
expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/');
});
+ it('should log an error if a route is not found');
+
+ it('should log an error if params are required and missing');
+
+ it('should log an error if params keys are not found');
+
});
}); |
b02b438bc187054eaa35d56afc51efdad69a889c | fetch-test.js | fetch-test.js | 'use strict'
const test = require('tape')
const proxyquire = require('proxyquire')
test('fetch', function (t) {
t.plan(3)
const fetch = proxyquire('./fetch', {
'simple-get': function (options, callback) {
t.deepEqual(options, {
url: 'https://host.co/path?page=2',
headers: {
foo: 'bar'
}
})
}
})
t.throws(fetch, /app is required/)
t.throws(fetch.bind(null, {}), /path is required/)
fetch({host: 'host.co', headers: {foo: 'bar'}}, '/path?page=2', function noop () {})
})
| 'use strict'
const test = require('tape')
const proxyquire = require('proxyquire')
test('fetch', function (t) {
t.plan(4)
const fetch = proxyquire('./fetch', {
'simple-get': function (options, callback) {
t.deepEqual(options, {
url: 'https://host.co/path?page=2',
headers: {
foo: 'bar'
}
})
callback()
}
})
t.throws(fetch, /app is required/)
t.throws(fetch.bind(null, {}), /path is required/)
fetch({host: 'host.co', headers: {foo: 'bar'}}, '/path?page=2', t.pass)
})
| Replace noop w/ t.pass to assert call | Replace noop w/ t.pass to assert call
| JavaScript | mit | bendrucker/http-app-router | ---
+++
@@ -4,7 +4,7 @@
const proxyquire = require('proxyquire')
test('fetch', function (t) {
- t.plan(3)
+ t.plan(4)
const fetch = proxyquire('./fetch', {
'simple-get': function (options, callback) {
@@ -14,10 +14,11 @@
foo: 'bar'
}
})
+ callback()
}
})
t.throws(fetch, /app is required/)
t.throws(fetch.bind(null, {}), /path is required/)
- fetch({host: 'host.co', headers: {foo: 'bar'}}, '/path?page=2', function noop () {})
+ fetch({host: 'host.co', headers: {foo: 'bar'}}, '/path?page=2', t.pass)
}) |
53f0ee1ff11a92122bd905d587f88abc696b40de | test/index.js | test/index.js | import co from 'co';
import test from 'blue-tape';
import agent from 'promisify-supertest';
import createApplication from '../src';
const setup = () => {
return agent(createApplication().callback());
};
test('GET /', (sub) => {
sub.test('responds with OK status code', co.wrap(function* (assert) {
const app = setup();
yield app
.get('/')
.expect((response) => {
assert.equal(response.statusCode, 200, 'status code should be 200');
})
.end();
}));
});
| /* eslint-disable func-names, no-use-before-define */
import co from 'co';
import test from 'blue-tape';
import agent from 'promisify-supertest';
import createApplication from '../src';
const setup = () => {
return agent(createApplication().callback());
};
test('GET /', (sub) => {
sub.test('responds with OK status code', co.wrap(function* (assert) {
const app = setup();
yield app
.get('/')
.expect(statusCodeToBeOk)
.end();
function statusCodeToBeOk({statusCode}) {
const okStatusCode = 200;
assert.equal(statusCode, okStatusCode, 'should be status OK');
}
}));
});
| Refactor root route test for readability. | Refactor root route test for readability.
| JavaScript | isc | francisbrito/let-go-hold-on-api | ---
+++
@@ -1,3 +1,5 @@
+/* eslint-disable func-names, no-use-before-define */
+
import co from 'co';
import test from 'blue-tape';
import agent from 'promisify-supertest';
@@ -14,9 +16,13 @@
yield app
.get('/')
- .expect((response) => {
- assert.equal(response.statusCode, 200, 'status code should be 200');
- })
+ .expect(statusCodeToBeOk)
.end();
+
+ function statusCodeToBeOk({statusCode}) {
+ const okStatusCode = 200;
+
+ assert.equal(statusCode, okStatusCode, 'should be status OK');
+ }
}));
}); |
3052a38676e0c1066dfa145cc29370b762d6ea5b | test/rSpec.js | test/rSpec.js | const
r = require('../'),
expect = require('chai').expect;
describe('RemoveTabs', function(){
it('should have not tabs.', function(){
var tests = [
r` remove
tabs`,
r` remove
tabs
tabs`,
r`
remove
tabs`
];
var expected = [
'remove\ntabs',
'remove\n\ttabs\n\t\ttabs',
'remove\ntabs'
];
for(var i = 0 ; i < tests.length ; i++) {
expect(tests[i]).to.equal(expected[i]);
}
})
}) | const
r = require('../'),
expect = require('chai').expect;
describe('RemoveTabs', function(){
it('should have not tabs.', function(){
var tests = [
r` remove
tabs`,
r` remove
tabs
tabs`,
r`
remove
tabs`,
r`
remove
remove
tabs
tabs`,
r`remove${'\r\n\t'}tabs${'\r\n\t\t'}tabs`, //window
r`
${'remove'}
${'tabs'}
${'tabs'}`
];
var expected = [
'remove\ntabs',
'remove\n\ttabs\n\t\ttabs',
'remove\ntabs',
'remove\nremove\n\ttabs\n\t\ttabs',
'remove\n\ttabs\n\t\ttabs',
'remove\n\ttabs\n\t\ttabs',
];
for(var i = 0 ; i < tests.length ; i++) {
expect(tests[i]).to.equal(expected[i]);
}
})
}) | Add test specs for interpolations. | Add test specs for interpolations.
| JavaScript | mit | Wooooo/remove-tabs | ---
+++
@@ -13,17 +13,35 @@
tabs`,
r`
remove
- tabs`
+ tabs`,
+
+ r`
+ remove
+ remove
+ tabs
+ tabs`,
+
+ r`remove${'\r\n\t'}tabs${'\r\n\t\t'}tabs`, //window
+
+ r`
+ ${'remove'}
+ ${'tabs'}
+ ${'tabs'}`
];
var expected = [
'remove\ntabs',
'remove\n\ttabs\n\t\ttabs',
- 'remove\ntabs'
+ 'remove\ntabs',
+ 'remove\nremove\n\ttabs\n\t\ttabs',
+ 'remove\n\ttabs\n\t\ttabs',
+ 'remove\n\ttabs\n\t\ttabs',
];
for(var i = 0 ; i < tests.length ; i++) {
expect(tests[i]).to.equal(expected[i]);
+
+
}
})
}) |
fa2a3f0c689a6cedc86452665c338935a5b95574 | src/javascript/binary/websocket_pages/user/new_account/virtual_acc_opening/virtual_acc_opening.data.js | src/javascript/binary/websocket_pages/user/new_account/virtual_acc_opening/virtual_acc_opening.data.js | var VirtualAccOpeningData = (function(){
"use strict";
function getDetails(password, residence, verificationCode){
var req = {
new_account_virtual: 1,
client_password: password,
residence: residence,
verification_code: verificationCode
};
if ($.cookie('affiliate_tracking')) {
req.affiliate_token = JSON.parse($.cookie('affiliate_tracking')).t;
}
BinarySocket.send(req);
}
return {
getDetails: getDetails
};
}());
| var VirtualAccOpeningData = (function(){
"use strict";
function getDetails(password, residence, verificationCode){
var req = {
new_account_virtual: 1,
client_password: password,
residence: residence,
verification_code: verificationCode
};
// Add AdWords parameters
// NOTE: following lines can be uncommented (Re-check property names)
// once these fields added to this ws call
// var utm_data = AdWords.getData();
// req.source = utm_data.utm_source || utm_data.referrer || 'direct';
// if(utm_data.utm_medium) req.medium = utm_data.utm_medium;
// if(utm_data.utm_campaign) req.campaign = utm_data.utm_campaign;
if ($.cookie('affiliate_tracking')) {
req.affiliate_token = JSON.parse($.cookie('affiliate_tracking')).t;
}
BinarySocket.send(req);
}
return {
getDetails: getDetails
};
}());
| Send source information on virtual account opening | Send source information on virtual account opening
| JavaScript | apache-2.0 | teo-binary/binary-static,binary-com/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static,binary-static-deployed/binary-static,teo-binary/binary-static,binary-com/binary-static,negar-binary/binary-static,kellybinary/binary-static,raunakkathuria/binary-static,fayland/binary-static,teo-binary/binary-static,binary-static-deployed/binary-static,kellybinary/binary-static,fayland/binary-static,4p00rv/binary-static,kellybinary/binary-static,teo-binary/binary-static,negar-binary/binary-static,fayland/binary-static,ashkanx/binary-static,raunakkathuria/binary-static,4p00rv/binary-static,binary-com/binary-static,4p00rv/binary-static,fayland/binary-static,raunakkathuria/binary-static,ashkanx/binary-static,negar-binary/binary-static | ---
+++
@@ -8,6 +8,14 @@
residence: residence,
verification_code: verificationCode
};
+
+ // Add AdWords parameters
+ // NOTE: following lines can be uncommented (Re-check property names)
+ // once these fields added to this ws call
+ // var utm_data = AdWords.getData();
+ // req.source = utm_data.utm_source || utm_data.referrer || 'direct';
+ // if(utm_data.utm_medium) req.medium = utm_data.utm_medium;
+ // if(utm_data.utm_campaign) req.campaign = utm_data.utm_campaign;
if ($.cookie('affiliate_tracking')) {
req.affiliate_token = JSON.parse($.cookie('affiliate_tracking')).t; |
40bb555785978dcf6ac287aa10d6be6c17cf31e4 | tests/src/test/javascript/components/basic/propvalidator.spec.js | tests/src/test/javascript/components/basic/propvalidator.spec.js | import {expect} from 'chai'
import chai from 'chai'
import spies from 'chai-spies'
import {
createAndMountComponent, destroyComponent, onGwtReady,
onNextTick
} from '../../vue-gwt-tests-utils'
describe('@PropValidator', () => {
let component;
beforeEach(() => onGwtReady().then(() => {
chai.use(spies);
chai.spy.on(console, 'error');
component = createAndMountComponent(
'com.axellience.vuegwt.tests.client.components.basic.propvalidator.PropValidatorParentTestComponent');
}));
afterEach(() => {
chai.spy.restore(console);
destroyComponent(component);
});
it('should not fire an error if the value is correct', () => {
component.validatedPropParent = 6;
return onNextTick(() => {
expect(console.error).to.not.have.been.called();
});
});
it('should fire an error if the value is incorrect', () => {
component.validatedPropParent = 106;
return onNextTick(() => {
expect(console.error).to.have.been.called.once;
});
});
}); | import {expect} from 'chai'
import chai from 'chai'
import spies from 'chai-spies'
import {
createAndMountComponent, destroyComponent, onGwtReady,
onNextTick
} from '../../vue-gwt-tests-utils'
describe('@PropValidator', () => {
let component;
beforeEach(() => onGwtReady().then(() => {
chai.use(spies);
chai.spy.on(console, 'error');
component = createAndMountComponent(
'com.axellience.vuegwt.tests.client.components.basic.propvalidator.PropValidatorParentTestComponent');
}));
afterEach(() => {
chai.spy.restore(console);
destroyComponent(component);
});
it('should not fire an error if the value is correct', () => {
component.validatedPropParent = 6;
return onNextTick(() => {
expect(console.error).to.not.have.been.called();
});
});
it('should fire an error if the value is incorrect in dev mode', () => {
if (Vue.config.productionTip === true) {
component.validatedPropParent = 106;
return onNextTick(() => {
expect(console.error).to.have.been.called.once;
});
}
});
it('should not fire an error if the value is incorrect in production mode', () => {
if (Vue.config.productionTip === false) {
component.validatedPropParent = 106;
return onNextTick(() => {
expect(console.error).to.not.have.been.called();
});
}
});
}); | Fix PropValidator test to work with Vue in production mode | Fix PropValidator test to work with Vue in production mode
PropValidator are only used in dev mode so the test should be ignored
when running Vue in production mode.
| JavaScript | mit | Axellience/vue-gwt,Axellience/vue-gwt,Axellience/vue-gwt,Axellience/vue-gwt | ---
+++
@@ -30,10 +30,21 @@
});
});
- it('should fire an error if the value is incorrect', () => {
- component.validatedPropParent = 106;
- return onNextTick(() => {
- expect(console.error).to.have.been.called.once;
- });
+ it('should fire an error if the value is incorrect in dev mode', () => {
+ if (Vue.config.productionTip === true) {
+ component.validatedPropParent = 106;
+ return onNextTick(() => {
+ expect(console.error).to.have.been.called.once;
+ });
+ }
+ });
+
+ it('should not fire an error if the value is incorrect in production mode', () => {
+ if (Vue.config.productionTip === false) {
+ component.validatedPropParent = 106;
+ return onNextTick(() => {
+ expect(console.error).to.not.have.been.called();
+ });
+ }
});
}); |
c218e3ab8e4604b6949ba02deb7a5f1c0b9e32d7 | fun-script.js | fun-script.js | #!/usr/bin/env node
var fs = require('fs')
var max = process.argv[2]
playGame()
function playGame() {
var usedNumbers = []
var number = getRandomNumber(max)
while (!isNewNumber(usedNumbers, number)) {
number = getRandomNumber(max)
}
fs.writeFile(process.cwd() + '/_data/numbers/' + number + '.json', '', function done (err) {
if (err) return
console.log(number)
usedNumbers.push(number)
setTimeout(playGame, 5000)
})
function isNewNumber (usedNumbers, number) {
if (usedNumbers.indexOf(number) === -1 && number != 0) {
return true
}
}
function getRandomNumber(max) {
return Math.round(Math.random() * max)
}
}
| #!/usr/bin/env node
var fs = require('fs')
var max = process.argv[2]
var usedNumbers = []
playGame()
function playGame() {
var number = getRandomNumber(max)
while (!isNewNumber(number)) {
number = getRandomNumber(max)
}
fs.writeFile(process.cwd() + '/_data/numbers/' + number + '.json', '', function done (err) {
if (err) return
console.log(number)
usedNumbers.push(number)
setTimeout(playGame, 5000)
})
function isNewNumber (number) {
if (usedNumbers.indexOf(number) === -1 && number != 0) {
return true
}
}
function getRandomNumber(max) {
return Math.round(Math.random() * max)
}
}
| Fix usedNumber bring resetted back to empty | Fix usedNumber bring resetted back to empty
| JavaScript | mit | muan/bingo-board,jlord/bingo-board,muan/bingo-board,jlord/bingo-board | ---
+++
@@ -2,14 +2,14 @@
var fs = require('fs')
var max = process.argv[2]
+var usedNumbers = []
playGame()
function playGame() {
- var usedNumbers = []
var number = getRandomNumber(max)
- while (!isNewNumber(usedNumbers, number)) {
+ while (!isNewNumber(number)) {
number = getRandomNumber(max)
}
@@ -20,7 +20,7 @@
setTimeout(playGame, 5000)
})
- function isNewNumber (usedNumbers, number) {
+ function isNewNumber (number) {
if (usedNumbers.indexOf(number) === -1 && number != 0) {
return true
} |
879626e9f315dc6069112a82f8b175660e1ff9f7 | src/setupJest.js | src/setupJest.js | window.fetch = require('jest-fetch-mock');
// Mock the Date object and allows us to use Date.now() and get a consistent date back
const mockedCurrentDate = new Date("2017-10-06T13:45:28.975Z");
require('jest-mock-now')(mockedCurrentDate);
// Mock document functions (specifically for the CollectionsController component)
const mockedGetElement = () => ({
getBoundingClientRect: () => ({
top: 0
}),
scrollTop: 0
});
Object.defineProperty(document, 'getElementById', {
value: mockedGetElement,
}); | window.fetch = require('jest-fetch-mock');
// Mock the Date object and allows us to use Date.now() and get a consistent date back
const mockedCurrentDate = new Date("2017-10-06T13:45:28.975Z");
require('jest-mock-now')(mockedCurrentDate);
// Mock document functions (specifically for the CollectionsController component)
const mockedGetElement = () => ({
getBoundingClientRect: () => ({
top: 0
}),
scrollTop: 0,
scrollIntoView: () => {}
});
Object.defineProperty(document, 'getElementById', {
value: mockedGetElement,
}); | Fix breaking unit tests due to missing mock of scrollIntoView function | Fix breaking unit tests due to missing mock of scrollIntoView function
Former-commit-id: fe6fd28df36626f4bb8efab9ba4a8c6c42cb2f5e
Former-commit-id: ddf9c74bc8fa09ec14d3ec518ac7da745cfe3731
Former-commit-id: d14b02918458ccf1d54bb4bcf50faa0b4d487eef | JavaScript | mit | ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence | ---
+++
@@ -9,7 +9,8 @@
getBoundingClientRect: () => ({
top: 0
}),
- scrollTop: 0
+ scrollTop: 0,
+ scrollIntoView: () => {}
});
Object.defineProperty(document, 'getElementById', {
value: mockedGetElement, |
85108314aa89b401d505d047c070f51d5307ccc6 | test/cli/myrmex-cheers.integ.js | test/cli/myrmex-cheers.integ.js | /*eslint-env mocha */
'use strict';
const assert = require('assert');
const icli = require('../../packages/cli/src/bin/myrmex');
const showStdout = !!process.env.MYRMEX_SHOW_STDOUT;
describe('The "cheers" sub-command', () => {
before(() => {
process.chdir(__dirname);
});
beforeEach(() => {
return icli.init();
});
it('should display a beer', () => {
icli.catchPrintStart(showStdout);
return icli.parse('node script.js cheers'.split(' '))
.then(res => {
const stdout = icli.catchPrintStop();
assert.ok(stdout.indexOf('language: ') > -1);
assert.ok(stdout.indexOf('font: ') > -1);
});
});
it('should allow to select a language and a font', () => {
icli.catchPrintStart(showStdout);
return icli.parse('node script.js cheers -l french -f Binary'.split(' '))
.then(res => {
const stdout = icli.catchPrintStop();
assert.ok(stdout.indexOf('language: french') > -1);
assert.ok(stdout.indexOf('font: Binary') > -1);
assert.ok(stdout.indexOf('01010011 01100001 01101110 01110100 01100101') > -1);
});
});
});
| /*eslint-env mocha */
'use strict';
const assert = require('assert');
const icli = require('../../packages/cli/src/bin/myrmex');
const showStdout = !!process.env.MYRMEX_SHOW_STDOUT;
describe('The "cheers" sub-command', () => {
before(() => {
process.chdir(__dirname);
});
beforeEach(() => {
return icli.init();
});
it('should display a beer', () => {
icli.catchPrintStart(showStdout);
return icli.parse('node script.js cheers'.split(' '))
.then(res => {
const stdout = icli.catchPrintStop();
assert.ok(stdout.indexOf('language: ') > -1);
assert.ok(stdout.indexOf('font: ') > -1);
});
});
it('should allow to select a language and a font', () => {
icli.catchPrintStart(showStdout);
return icli.parse('node script.js cheers -l french -f Binary'.split(' '))
.then(res => {
const stdout = icli.catchPrintStop();
assert.ok(stdout.indexOf('language: french') > -1);
assert.ok(stdout.indexOf('font: Binary') > -1);
// Disable assertion because of travis execution context
// assert.ok(stdout.indexOf('01010011 01100001 01101110 01110100 01100101') > -1);
});
});
});
| Fix test for travis execution context | Fix test for travis execution context
| JavaScript | mit | myrmex-org/myrmex,myrmex-org/myrmex,lagerjs/lager,myrmex-org/myrmex,myrmx/myrmex,myrmx/myrmex,lagerjs/lager,myrmx/myrmex,myrmx/myrmex,lagerjs/lager,myrmex-org/myrmex,lagerjs/lager | ---
+++
@@ -32,7 +32,8 @@
const stdout = icli.catchPrintStop();
assert.ok(stdout.indexOf('language: french') > -1);
assert.ok(stdout.indexOf('font: Binary') > -1);
- assert.ok(stdout.indexOf('01010011 01100001 01101110 01110100 01100101') > -1);
+ // Disable assertion because of travis execution context
+ // assert.ok(stdout.indexOf('01010011 01100001 01101110 01110100 01100101') > -1);
});
});
}); |
2c033eb71202c709bdbd45f4a64909b4b83e28be | lib/Avatar.js | lib/Avatar.js | import React, { Component, PropTypes, View, Image } from 'react-native';
import Icon from './Icon';
import { ICON_NAME } from './config';
export default class Avatar extends Component {
static propTypes = {
icon: PropTypes.string,
src: PropTypes.string,
size: PropTypes.number,
color: PropTypes.string,
backgroundColor: PropTypes.string
};
static defaultProps = {
size: 40,
color: '#ffffff',
backgroundColor: '#bdbdbd'
};
render() {
const { icon, src, size, color, backgroundColor } = this.props;
if (src) {
return (
<Image
style={{ width: size, height: size, borderRadius: size / 2, borderColor: 'rgba(0,0,0,.1)', borderWidth: 1 }}
source={{ uri: src }}
/>
);
}
if (icon) {
return (
<View style={{ flex: 1 }}>
<View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: backgroundColor, alignItems:'center' }}>
<Icon name={icon} color={color} size={0.6 * size} style={{ position: 'relative', top: -3 }} />
</View>
</View>
);
}
}
} | import React, { Component, PropTypes, View, Image } from 'react-native';
import Icon from './Icon';
import { getColor } from './helpers';
export default class Avatar extends Component {
static propTypes = {
icon: PropTypes.string,
src: PropTypes.string,
size: PropTypes.number,
color: PropTypes.string,
backgroundColor: PropTypes.string
};
static defaultProps = {
size: 40,
color: '#ffffff',
backgroundColor: getColor('paperGrey500')
};
render() {
const { icon, src, size, color, backgroundColor } = this.props;
if (src) {
return (
<Image
style={{ width: size, height: size, borderRadius: size / 2, borderColor: 'rgba(0,0,0,.1)', borderWidth: 1 }}
source={{ uri: src }}
/>
);
}
if (icon) {
return (
<View style={{ flex: 1 }}>
<View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: getColor(backgroundColor), alignItems:'center' }}>
<Icon
name={icon}
color={color}
size={0.6 * size}
style={{
position: 'relative',
top: -3
}}
/>
</View>
</View>
);
}
}
} | Update default background color & formatting updates | Update default background color & formatting updates
| JavaScript | mit | kenma9123/react-native-material-ui,blovato/sca-mobile-components,xotahal/react-native-material-ui,react-native-material-design/react-native-material-design,xvonabur/react-native-material-ui,thomasooo/react-native-material-design,ajaxangular/react-native-material-ui,mobileDevNativeCross/react-native-material-ui | ---
+++
@@ -1,6 +1,6 @@
import React, { Component, PropTypes, View, Image } from 'react-native';
import Icon from './Icon';
-import { ICON_NAME } from './config';
+import { getColor } from './helpers';
export default class Avatar extends Component {
@@ -15,7 +15,7 @@
static defaultProps = {
size: 40,
color: '#ffffff',
- backgroundColor: '#bdbdbd'
+ backgroundColor: getColor('paperGrey500')
};
render() {
@@ -33,8 +33,16 @@
if (icon) {
return (
<View style={{ flex: 1 }}>
- <View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: backgroundColor, alignItems:'center' }}>
- <Icon name={icon} color={color} size={0.6 * size} style={{ position: 'relative', top: -3 }} />
+ <View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: getColor(backgroundColor), alignItems:'center' }}>
+ <Icon
+ name={icon}
+ color={color}
+ size={0.6 * size}
+ style={{
+ position: 'relative',
+ top: -3
+ }}
+ />
</View>
</View>
); |
6125f7cbbba04208cf4836539ca4f596a6cd6c93 | test/helpers_test.js | test/helpers_test.js | /* vim: ts=4:sw=4
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
describe("Helpers", function() {
describe("ArrayBuffer->String conversion", function() {
it('works', function() {
var b = new ArrayBuffer(3);
var a = new Uint8Array(b);
a[0] = 0;
a[1] = 255;
a[2] = 128;
assert.equal(getString(b), "\x00\xff\x80");
});
});
});
| /* vim: ts=4:sw=4
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
describe("Helpers", function() {
describe("ArrayBuffer->String conversion", function() {
it('works', function() {
var b = new ArrayBuffer(3);
var a = new Uint8Array(b);
a[0] = 0;
a[1] = 255;
a[2] = 128;
assert.equal(getString(b), "\x00\xff\x80");
});
});
describe("toArrayBuffer", function() {
it('returns undefined when passed undefined', function() {
assert.strictEqual(toArrayBuffer(undefined), undefined);
});
it('returns ArrayBuffer when passed ArrayBuffer', function() {
var StaticArrayBufferProto = new ArrayBuffer().__proto__;
var anArrayBuffer = new ArrayBuffer();
assert.strictEqual(toArrayBuffer(anArrayBuffer), anArrayBuffer);
});
it('throws an error when passed a non Stringable thing', function() {
var madeUpObject = function() {};
var notStringable = new madeUpObject();
assert.throw(function() { toArrayBuffer(notStringable) },
Error, /Tried to convert a non-stringable thing/);
});
});
});
| Add basic test coverage of toArrayBuffer function | Add basic test coverage of toArrayBuffer function
| JavaScript | agpl-3.0 | nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop | ---
+++
@@ -27,4 +27,21 @@
assert.equal(getString(b), "\x00\xff\x80");
});
});
+
+ describe("toArrayBuffer", function() {
+ it('returns undefined when passed undefined', function() {
+ assert.strictEqual(toArrayBuffer(undefined), undefined);
+ });
+ it('returns ArrayBuffer when passed ArrayBuffer', function() {
+ var StaticArrayBufferProto = new ArrayBuffer().__proto__;
+ var anArrayBuffer = new ArrayBuffer();
+ assert.strictEqual(toArrayBuffer(anArrayBuffer), anArrayBuffer);
+ });
+ it('throws an error when passed a non Stringable thing', function() {
+ var madeUpObject = function() {};
+ var notStringable = new madeUpObject();
+ assert.throw(function() { toArrayBuffer(notStringable) },
+ Error, /Tried to convert a non-stringable thing/);
+ });
+ });
}); |
0e7fb78882f5b0e78d3f544857d86717fead0cdb | Renderer/canvas-drawer.js | Renderer/canvas-drawer.js | var CanvasDrawer = (function () {
var CanvasDrawer = function (params) {
};
CanvasDrawer.prototype = {
drawPlayer: {
value: function (player) {
}
},
drawDisc :{
value: function (disc) {
}
}
}
}()); | var CanvasDrawer = (function () {
var CanvasDrawer = function (params) {
var canvas = document.getElementById("canvas-field");
this.ctx = canvas.getContext("2d");
this.canvasWidth = canvas.width;
this.canvasHeight = canvas.height;
};
CanvasDrawer.prototype = {
drawPlayer: function (player) {
this.ctx.beginPath();
this.ctx.arc(player.x, player.y, player.radius, 0, 2 * Math.PI);
//this.ctx.drawImage(player.image, player.x - player.image.width / 2,
// player.y - player.radius, this.ctx.canvas.height / 15, this.ctx.canvas.height / 15);
this.ctx.fillStyle = 'red';
this.ctx.fill();
},
clear: function () {
this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
},
drawDisc: function (disc) {
this.ctx.beginPath();
this.ctx.arc(disc.x, disc.y, disc.radius, 0, 2 * Math.PI);
this.ctx.fillStyle = 'yellowgreen';
this.ctx.fill();
this.ctx.strokeStyle = 'black';
this.ctx.stroke();
}
};
return CanvasDrawer;
}()); | Add implement CanvasDrawer witch draw player and disc | Add implement CanvasDrawer witch draw player and disc
| JavaScript | mit | TeamBarracuda-Telerik/JustDiscBattle,TeamBarracuda-Telerik/JustDiscBattle | ---
+++
@@ -1,18 +1,35 @@
var CanvasDrawer = (function () {
var CanvasDrawer = function (params) {
-
+ var canvas = document.getElementById("canvas-field");
+ this.ctx = canvas.getContext("2d");
+ this.canvasWidth = canvas.width;
+ this.canvasHeight = canvas.height;
};
+
+
CanvasDrawer.prototype = {
- drawPlayer: {
- value: function (player) {
+ drawPlayer: function (player) {
+ this.ctx.beginPath();
+ this.ctx.arc(player.x, player.y, player.radius, 0, 2 * Math.PI);
+ //this.ctx.drawImage(player.image, player.x - player.image.width / 2,
+ // player.y - player.radius, this.ctx.canvas.height / 15, this.ctx.canvas.height / 15);
+ this.ctx.fillStyle = 'red';
+ this.ctx.fill();
+ },
+ clear: function () {
+ this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
+ },
+ drawDisc: function (disc) {
+ this.ctx.beginPath();
+ this.ctx.arc(disc.x, disc.y, disc.radius, 0, 2 * Math.PI);
+ this.ctx.fillStyle = 'yellowgreen';
+ this.ctx.fill();
+ this.ctx.strokeStyle = 'black';
+ this.ctx.stroke();
+ }
+ };
- }
- },
- drawDisc :{
- value: function (disc) {
- }
- }
- }
+ return CanvasDrawer;
}()); |
ff58d6e6788382e2468994f9550bcc1e8d103e49 | utils/network-timing.js | utils/network-timing.js | const {hasAdRequestPath, isImplTag} = require('./resource-classification');
const {URL} = require('url');
/**
* Returns end time of tag load (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @return {number}
*/
function getTagEndTime(networkRecords) {
const tagRecord = networkRecords.find(
(record) => isImplTag(new URL(record.url)));
return tagRecord ? tagRecord.endTime : -1;
}
/**
* Returns start time of first ad request (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @return {number}
*/
function getAdStartTime(networkRecords) {
const firstAdRecord = networkRecords.find(
(record) => hasAdRequestPath(new URL(record.url)));
return firstAdRecord ? firstAdRecord.startTime : -1;
}
/**
* Returns start time of page load (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @return {number}
*/
function getPageStartTime(networkRecords) {
const fistSuccessRecord = networkRecords.find(
(record) => record.statusCode == 200);
return fistSuccessRecord ? fistSuccessRecord.startTime : -1;
}
module.exports = {
getTagEndTime,
getAdStartTime,
getPageStartTime,
};
| const {hasAdRequestPath, isImplTag} = require('./resource-classification');
const {URL} = require('url');
/**
* Returns end time of tag load (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @return {number}
*/
function getTagEndTime(networkRecords) {
const tagRecord = networkRecords.find(
(record) => isImplTag(new URL(record.url)));
return tagRecord ? tagRecord.endTime : -1;
}
/**
* Returns start time of first ad request (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @return {number}
*/
function getAdStartTime(networkRecords) {
const firstAdRecord = networkRecords.find(
(record) => hasAdRequestPath(new URL(record.url)));
return firstAdRecord ? firstAdRecord.startTime : -1;
}
/**
* Returns start time of page load (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @param {number=} defaultValue
* @return {number}
*/
function getPageStartTime(networkRecords, defaultValue = -1) {
const fistSuccessRecord = networkRecords.find(
(record) => record.statusCode == 200);
return fistSuccessRecord ? fistSuccessRecord.startTime : defaultValue;
}
module.exports = {
getTagEndTime,
getAdStartTime,
getPageStartTime,
};
| Include defaultValue in getPageStartTime function. | Include defaultValue in getPageStartTime function.
Change-Id: Ib25db9f76263ffcb907f1c04edb90e1c2c65e4cf
| JavaScript | apache-2.0 | googleads/publisher-ads-lighthouse-plugin,googleads/publisher-ads-lighthouse-plugin | ---
+++
@@ -26,12 +26,13 @@
/**
* Returns start time of page load (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
+ * @param {number=} defaultValue
* @return {number}
*/
-function getPageStartTime(networkRecords) {
+function getPageStartTime(networkRecords, defaultValue = -1) {
const fistSuccessRecord = networkRecords.find(
(record) => record.statusCode == 200);
- return fistSuccessRecord ? fistSuccessRecord.startTime : -1;
+ return fistSuccessRecord ? fistSuccessRecord.startTime : defaultValue;
}
module.exports = { |
dd03f8c7fa2499e6d121eea710d3cda9803f94a0 | util/bind/bind.js | util/bind/bind.js | steal('can/util', function (can) {
/**
* @typedef {{bind:function():*,unbind:function():*}} can/util/bind
*
* Provides mixin-able bind and unbind methods. `bind()` calls `this._bindsetup`
* when the first bind happens and. `unbind()` calls `this._bindteardown` when there
* are no more event handlers.
*
*/
// ## Bind helpers
can.bindAndSetup = function () {
// Add the event to this object
can.addEvent.apply(this, arguments);
// If not initializing, and the first binding
// call bindsetup if the function exists.
if (!this._init) {
if (!this._bindings) {
this._bindings = 1;
// setup live-binding
if (this._bindsetup) {
this._bindsetup();
}
} else {
this._bindings++;
}
}
return this;
};
can.unbindAndTeardown = function (ev, handler) {
// Remove the event handler
can.removeEvent.apply(this, arguments);
if (this._bindings === null) {
this._bindings = 0;
} else {
this._bindings--;
}
// If there are no longer any bindings and
// there is a bindteardown method, call it.
if (!this._bindings && this._bindteardown) {
this._bindteardown();
}
return this;
};
return can;
});
| steal('can/util', function (can) {
/**
* @typedef {{bind:function():*,unbind:function():*}} can.util.bind
*
* Provides mixin-able bind and unbind methods. `bind()` calls `this._bindsetup`
* when the first bind happens and. `unbind()` calls `this._bindteardown` when there
* are no more event handlers.
*
*/
// ## Bind helpers
can.bindAndSetup = function () {
// Add the event to this object
can.addEvent.apply(this, arguments);
// If not initializing, and the first binding
// call bindsetup if the function exists.
if (!this._init) {
if (!this._bindings) {
this._bindings = 1;
// setup live-binding
if (this._bindsetup) {
this._bindsetup();
}
} else {
this._bindings++;
}
}
return this;
};
can.unbindAndTeardown = function (ev, handler) {
// Remove the event handler
can.removeEvent.apply(this, arguments);
if (this._bindings === null) {
this._bindings = 0;
} else {
this._bindings--;
}
// If there are no longer any bindings and
// there is a bindteardown method, call it.
if (!this._bindings && this._bindteardown) {
this._bindteardown();
}
return this;
};
return can;
});
| Fix @typedef name to be dot-separated. | Fix @typedef name to be dot-separated.
| JavaScript | mit | whitecolor/canjs,asavoy/canjs,rjgotten/canjs,patrick-steele-idem/canjs,beno/canjs,patrick-steele-idem/canjs,asavoy/canjs,Psykoral/canjs,Psykoral/canjs,gsmeets/canjs,whitecolor/canjs,tracer99/canjs,patrick-steele-idem/canjs,rasjani/canjs,bitovi/canjs,rjgotten/canjs,bitovi/canjs,gsmeets/canjs,Psykoral/canjs,bitovi/canjs,rjgotten/canjs,whitecolor/canjs,beno/canjs,tracer99/canjs,ackl/canjs,ackl/canjs,rjgotten/canjs,bitovi/canjs,ackl/canjs,UXsree/canjs,rasjani/canjs,gsmeets/canjs,tracer99/canjs,rasjani/canjs,Psykoral/canjs,UXsree/canjs,beno/canjs,rasjani/canjs | ---
+++
@@ -1,6 +1,6 @@
steal('can/util', function (can) {
/**
- * @typedef {{bind:function():*,unbind:function():*}} can/util/bind
+ * @typedef {{bind:function():*,unbind:function():*}} can.util.bind
*
* Provides mixin-able bind and unbind methods. `bind()` calls `this._bindsetup`
* when the first bind happens and. `unbind()` calls `this._bindteardown` when there |
8c3335cf84588aa2ccabe78a96bb668be74fd160 | src/lib/mapper.js | src/lib/mapper.js | 'use strict';
const _ = require('lodash');
const log = require('./log');
let nameToId = {};
let mapper = {
/**
* Add light name to identifier mapping.
*
* @param {string} id - Light identifier
* @param {string} name - Light name mapping
*/
add: function addName(id, name) {
if (!id || !name) {
log.error('Could not add light mapping. ID or name not defined!');
return;
}
let key = getKey(name);
nameToId[key] = id;
},
/**
* Get light identifier by name.
*
* @param {string} name - Light name
* @return {string|undefined} - Light identifier or undefined
*/
get: function getId(name) {
if (!name) {
log.error('Could not find light mapping. No name defined!');
return;
}
// value found from nameToId should already be an identifier
if (_.includes(nameToId, name)) {
return name;
}
let id = nameToId[getKey(name)];
if (id) {
return id;
}
log.warn('No light found with name "' + name + '"');
},
/**
* Get list of light names and groups.
*/
getNames: function() {
let names = _.keys(nameToId).sort();
names.push('all');
return names;
}
};
/**
* Use lowercase keys.
*/
function getKey(name) {
return name.toLowerCase();
}
// Expose mapper
module.exports = exports = mapper;
| 'use strict';
const _ = require('lodash');
const log = require('./log');
let nameToId = {};
let mapper = {
/**
* Add light name to identifier mapping.
*
* @param {string} id - Light identifier
* @param {string} name - Light name mapping
*/
add: function addName(id, name) {
if (!id || !name) {
log.error('Could not add light mapping. ID or name not defined!');
return;
}
let key = getKey(name);
nameToId[key] = id;
},
/**
* Get light identifier by name.
*
* @param {string} name - Light name
* @return {string|undefined} - Light identifier or undefined
*/
get: function getId(name) {
if (!name) {
log.error('Could not find light mapping. No name defined!');
return;
}
// value found from nameToId should already be an identifier
if (_.includes(nameToId, name)) {
return name;
}
let id = nameToId[getKey(name)];
if (id) {
return id;
}
log.warn('No light found with name "' + name + '"');
},
/**
* Get list of light names and groups.
*/
getNames: function() {
let names = _.keys(nameToId).sort();
names.push('all');
return names;
}
};
/**
* Use lowercase keys.
*/
function getKey(name) {
return name ? name.toLowerCase() : null;
}
// Expose mapper
module.exports = exports = mapper;
| Fix crash on unknown light name | Fix crash on unknown light name
| JavaScript | mit | ristomatti/lifxsh | ---
+++
@@ -61,7 +61,7 @@
* Use lowercase keys.
*/
function getKey(name) {
- return name.toLowerCase();
+ return name ? name.toLowerCase() : null;
}
// Expose mapper |
8d1a0fd2c8f3bf48b6effdbc656df3e6f904d949 | examples/index.js | examples/index.js | #! /usr/bin/env node
// Ref: http://docopt.org/
/*
Chain commands
Positional arguments
Named arguments
Required arguments
Limit arguments options
Set option type (e.g. string, number)
Set number of options (exact, min, & max)
Nest commands & arguments
*/
'use strict';
(function () {
var jargs = require('../src/index');
var Command = jargs.Command;
var KWArg = jargs.KWArg;
var Arg = jargs.Arg;
var args = jargs.collect([
Command({
name: 'init',
children: [
Arg({
name: 'path',
required: true,
type: 'string'
})
]
}),
Command({
name: 'build',
children: [
KWArg({
name: 'config',
alias: 'c',
type: 'string',
default: 'config.json'
})
]
}),
KWArg({
name: 'help',
alias: 'h',
type: 'boolean',
description: 'Displays help & usage info'
}),
KWArg({
name: 'version',
alias: 'v',
type: 'boolean',
description: 'Displays version number'
})
]);
console.log(args);
})();
| #! /usr/bin/env node
// Ref: http://docopt.org/
/*
Chain commands
Positional arguments
Named arguments
Required arguments
Limit arguments options
Set option type (e.g. string, number)
Set number of options (exact, min, & max)
Nest commands & arguments
*/
'use strict';
(function () {
var jargs = require('../src/index');
var Command = jargs.Command;
var KWArg = jargs.KWArg;
var Arg = jargs.Arg;
var args = jargs.collect([
Command(
'init',
null,
Arg(
'path',
{required: true, type: 'string'}
)
),
Command(
'build',
null,
KWArg(
'config',
{alias: 'c', type: 'string', default: 'config.json'}
)
),
KWArg(
'help',
{alias: 'h', type: 'boolean', description: 'Displays help & usage info'}
),
KWArg(
'version',
{alias: 'v', type: 'boolean', description: 'Displays version number'}
)
]);
console.log(args);
})();
| Adjust API to be more "React-like" | Adjust API to be more "React-like"
| JavaScript | mit | JakeSidSmith/jargs | ---
+++
@@ -25,39 +25,30 @@
var Arg = jargs.Arg;
var args = jargs.collect([
- Command({
- name: 'init',
- children: [
- Arg({
- name: 'path',
- required: true,
- type: 'string'
- })
- ]
- }),
- Command({
- name: 'build',
- children: [
- KWArg({
- name: 'config',
- alias: 'c',
- type: 'string',
- default: 'config.json'
- })
- ]
- }),
- KWArg({
- name: 'help',
- alias: 'h',
- type: 'boolean',
- description: 'Displays help & usage info'
- }),
- KWArg({
- name: 'version',
- alias: 'v',
- type: 'boolean',
- description: 'Displays version number'
- })
+ Command(
+ 'init',
+ null,
+ Arg(
+ 'path',
+ {required: true, type: 'string'}
+ )
+ ),
+ Command(
+ 'build',
+ null,
+ KWArg(
+ 'config',
+ {alias: 'c', type: 'string', default: 'config.json'}
+ )
+ ),
+ KWArg(
+ 'help',
+ {alias: 'h', type: 'boolean', description: 'Displays help & usage info'}
+ ),
+ KWArg(
+ 'version',
+ {alias: 'v', type: 'boolean', description: 'Displays version number'}
+ )
]);
console.log(args); |
b763199fe0d1b6920cd1827f16529ddc1e021422 | gulpfile.babel.js | gulpfile.babel.js | 'use strict';
import gulp from 'gulp';
import babel from 'gulp-babel';
import istanbul from 'gulp-istanbul';
import mocha from 'gulp-mocha';
gulp.task('pre-test', () => {
return gulp.src(['dist/index.js'])
// Covering files
.pipe(istanbul())
// Force `require` to return covered files
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], () => {
return gulp.src(['test/*.js'])
.pipe(mocha())
// Creating the reports after tests ran
.pipe(istanbul.writeReports());
// Enforce a coverage of at least 90%
//.pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } }));
});
gulp.task('default', () => {
return gulp.src([
'index.js'
])
.pipe(babel({
presets: ['es2015', 'stage-0']
}))
.pipe(gulp.dest('dist'));
});
| 'use strict';
import gulp from 'gulp';
import babel from 'gulp-babel';
import istanbul from 'gulp-istanbul';
import mocha from 'gulp-mocha';
gulp.task('pre-test', () => {
return gulp.src(['dist/index.js'])
// Covering files
.pipe(istanbul())
// Force `require` to return covered files
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], () => {
return gulp.src(['test/*.js'])
.pipe(mocha())
// Creating the reports after tests ran
.pipe(istanbul.writeReports())
// Checking coverage against minimum acceptable thresholds
.pipe(istanbul.enforceThresholds({
thresholds: {
global: {
statements: 90,
branches: 60,
functions: 90,
lines: 90
}
}
}));
});
gulp.task('default', () => {
return gulp.src([
'index.js'
])
.pipe(babel({
presets: ['es2015', 'stage-0']
}))
.pipe(gulp.dest('dist'));
});
| Update coverage's minimum acceptable thresholds | Update coverage's minimum acceptable thresholds
| JavaScript | mit | cheton/gcode-parser | ---
+++
@@ -17,9 +17,18 @@
return gulp.src(['test/*.js'])
.pipe(mocha())
// Creating the reports after tests ran
- .pipe(istanbul.writeReports());
- // Enforce a coverage of at least 90%
- //.pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } }));
+ .pipe(istanbul.writeReports())
+ // Checking coverage against minimum acceptable thresholds
+ .pipe(istanbul.enforceThresholds({
+ thresholds: {
+ global: {
+ statements: 90,
+ branches: 60,
+ functions: 90,
+ lines: 90
+ }
+ }
+ }));
});
gulp.task('default', () => { |
b73810201d3ef977e8322bc81594c779914eba10 | examples/console/start.js | examples/console/start.js | const syrup = require('../../');
const _ = require('lodash');
syrup.scenario('array', `${__dirname}/test-array`);
syrup.scenario('object', `${__dirname}/test-object`);
syrup.scenario('save', `${__dirname}/test-save`);
syrup.scenario('get', `${__dirname}/test-get`, ['save']);
syrup.pour(function (error, results) {
console.log(JSON.stringify(results));
}, function (error, results) {
// Do something with the progress update
// Results Example:
//
// {
// array: 'done',
// object: 'done',
// save: 'done',
// get: 'pending'
// }
});
| const syrup = require('../../');
syrup.scenario('array', `${__dirname}/test-array`);
syrup.scenario('object', `${__dirname}/test-object`);
syrup.scenario('save', `${__dirname}/test-save`);
syrup.scenario('get', `${__dirname}/test-get`, ['save']);
syrup.pour(function (error, results) {
console.log(JSON.stringify(results));
}, function (error, results) {
// Do something with the progress update
// Results Example:
//
// {
// array: 'done',
// object: 'done',
// save: 'done',
// get: 'pending'
// }
});
| Remove the unneeded lodash require | Remove the unneeded lodash require
| JavaScript | mpl-2.0 | thejsninja/syrup | ---
+++
@@ -1,5 +1,4 @@
const syrup = require('../../');
-const _ = require('lodash');
syrup.scenario('array', `${__dirname}/test-array`);
syrup.scenario('object', `${__dirname}/test-object`); |
9c02fcfd2c70299d7bb785e9ac2a299320bf83d1 | src/components/ByLine.js | src/components/ByLine.js | /**
* ByLine.js
* Description: view component that makes up a news item preview
* Modules: React and React Native Modules
* Dependencies: styles.js SmallText
* Author: Tiffany Tse
*/
//import modules
import React, { PropTypes } from 'react';
import { StyleSheet, View } from 'react-native';
import SmallText from './SmallText.js';
import * as globalStyles from '../styles/global.js';
const Byline ({date, author, location}) => (
<View>
<View style={style.row}>
<SmallText>
{date.toLocaleDateString()}
</SmallText>
<SmallText>
{author}
</SmallText>
</View>
</View>
{location ? (
<View style={styles.row}>
<SmallText style={styles.location}>
{location}
</SmallText>
</View>
) : null}
);
//define propTypes
Byline.propTypes = {
date: PropTypes.instanceOf(Date).isRequired,
author: PropTypes.string.isRequired,
location: PropTypes.string
};
//define custom styles
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
justifyContent: 'space-between',
marginBottom: 5
},
location: {
color: globalStyles.MUTED_COLOR
}
});
//export Byline
export default Byline; | /**
* ByLine.js
* Description: view component that makes up a news item preview
* Modules: React and React Native Modules
* Dependencies: styles.js SmallText
* Author: Tiffany Tse
*/
//import modules
import React, { PropTypes } from 'react';
import { StyleSheet, View } from 'react-native';
import SmallText from './SmallText.js';
import * as globalStyles from '../styles/global.js';
const Byline ({date, author, location}) => (
<View>
<View style={style.row}>
<SmallText>
{date}
</SmallText>
<SmallText>
{author}
</SmallText>
</View>
</View>
{location ? (
<View style={styles.row}>
<SmallText style={styles.location}>
{location}
</SmallText>
</View>
) : null}
);
//define propTypes
Byline.propTypes = {
date: PropTypes.string.isRequired,
author: PropTypes.string.isRequired,
location: PropTypes.string
};
//define custom styles
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
justifyContent: 'space-between',
marginBottom: 5
},
location: {
color: globalStyles.MUTED_COLOR
}
});
//export Byline
export default Byline; | Refactor date in Byline to use string | Refactor date in Byline to use string
| JavaScript | mit | titse/NYTimes-Clone,titse/NYTimes-Clone,titse/NYTimes-Clone | ---
+++
@@ -15,7 +15,7 @@
<View>
<View style={style.row}>
<SmallText>
- {date.toLocaleDateString()}
+ {date}
</SmallText>
<SmallText>
{author}
@@ -34,7 +34,7 @@
//define propTypes
Byline.propTypes = {
- date: PropTypes.instanceOf(Date).isRequired,
+ date: PropTypes.string.isRequired,
author: PropTypes.string.isRequired,
location: PropTypes.string
}; |
47459be879b85fe9daedb2d57ff43c2619dd3620 | packages/components/containers/domains/DomainsSection.js | packages/components/containers/domains/DomainsSection.js | import React from 'react';
import { c } from 'ttag';
import {
useEventManager,
useOrganization,
useDomains,
SubTitle,
Alert,
PrimaryButton,
Button,
Block,
useModal
} from 'react-components';
import DomainModal from './DomainModal';
import DomainsTable from './DomainsTable';
const DomainsSection = () => {
const [domains, loading] = useDomains();
const [organization] = useOrganization();
const { isOpen, open, close } = useModal();
const { UsedDomains, MaxDomains } = organization;
const { call } = useEventManager(); // TODO: Use event manager or expose a refresh fn in the models?
return (
<>
<SubTitle>{c('Title').t`Domains`}</SubTitle>
<Alert learnMore="todo">
{c('Message')
.t`Add a custom filter to perform actions such as automatically labeling or archiving messages.`}
</Alert>
<Block>
<PrimaryButton onClick={open}>{c('Action').t`Add domain`}</PrimaryButton>
<DomainModal show={isOpen} onClose={close} />
<Button disabled={loading} onClick={call}>{c('Action').t`Refresh status`}</Button>
</Block>
{!loading && !domains.length ? <Alert>{c('Info').t`No domains yet`}</Alert> : null}
{loading ? null : <DomainsTable domains={domains} />}
<Block>
{UsedDomains} / {MaxDomains} {c('Info').t`domains used`}
</Block>
</>
);
};
export default DomainsSection;
| import React from 'react';
import { c } from 'ttag';
import {
useEventManager,
useOrganization,
useDomains,
SubTitle,
Alert,
PrimaryButton,
Button,
Block,
useModal
} from 'react-components';
import DomainModal from './DomainModal';
import DomainsTable from './DomainsTable';
const DomainsSection = () => {
const [domains, loading] = useDomains();
const [organization] = useOrganization();
const { isOpen, open, close } = useModal();
const { UsedDomains, MaxDomains } = organization;
const { call } = useEventManager(); // TODO: Use event manager or expose a refresh fn in the models?
return (
<>
<SubTitle>{c('Title').t`Manage custom domains`}</SubTitle>
<Alert learnMore="https://protonmail.com/support/categories/custom-domains/">
{c('Message')
.t`Add a custom filter to perform actions such as automatically labeling or archiving messages.`}
</Alert>
<Block>
<PrimaryButton onClick={open}>{c('Action').t`Add domain`}</PrimaryButton>
<DomainModal show={isOpen} onClose={close} />
<Button disabled={loading} onClick={call}>{c('Action').t`Refresh status`}</Button>
</Block>
{!loading && !domains.length ? <Alert>{c('Info').t`No domains yet`}</Alert> : null}
{loading ? null : <DomainsTable domains={domains} />}
<Block>
{UsedDomains} / {MaxDomains} {c('Info').t`domains used`}
</Block>
</>
);
};
export default DomainsSection;
| Add link for domains section | Add link for domains section
| JavaScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -24,8 +24,8 @@
return (
<>
- <SubTitle>{c('Title').t`Domains`}</SubTitle>
- <Alert learnMore="todo">
+ <SubTitle>{c('Title').t`Manage custom domains`}</SubTitle>
+ <Alert learnMore="https://protonmail.com/support/categories/custom-domains/">
{c('Message')
.t`Add a custom filter to perform actions such as automatically labeling or archiving messages.`}
</Alert> |
32b688e53c0170f7e4f0c37d38d4b299bbf9cf66 | grunt/scss-lint.js | grunt/scss-lint.js | // Check SCSS for code quality
module.exports = function(grunt) {
grunt.config('scsslint', {
allFiles: [
'scss/**/*.scss',
],
options: {
bundleExec: false,
colorizeOutput: true,
config: '.scss-lint.yml',
exclude: [
'scss/core/_normalize.scss',
'scss/iconfont/*',
'scss/main/_oldie.scss',
'scss/mixins/_type.scss',
'scss/mixins/_units.scss',
'scss/modules/_images.scss'
],
reporterOutput: null
},
});
grunt.loadNpmTasks('grunt-scss-lint');
};
| // Check SCSS for code quality
module.exports = function(grunt) {
grunt.config('scsslint', {
allFiles: [
'scss/**/*.scss',
],
options: {
bundleExec: false,
colorizeOutput: true,
config: '.scss-lint.yml',
exclude: [
'scss/core/_normalize.scss',
'scss/iconfont/*',
'scss/main/_oldie.scss',
'scss/mixins/_type.scss',
'scss/mixins/_units.scss',
'scss/modules/_forms.scss',
'scss/modules/_images.scss'
],
reporterOutput: null
},
});
grunt.loadNpmTasks('grunt-scss-lint');
};
| Exclude forms partial as well. | Exclude forms partial as well.
| JavaScript | mit | yellowled/yl-bp,yellowled/yl-bp | ---
+++
@@ -14,6 +14,7 @@
'scss/main/_oldie.scss',
'scss/mixins/_type.scss',
'scss/mixins/_units.scss',
+ 'scss/modules/_forms.scss',
'scss/modules/_images.scss'
],
reporterOutput: null |
49c7b952bd3db9d192ea3074d773c07ade791869 | ghost/admin/tests/test-helper.js | ghost/admin/tests/test-helper.js | import resolver from './helpers/resolver';
import { setResolver } from 'ember-mocha';
setResolver(resolver);
/* jshint ignore:start */
mocha.setup({
timeout: 5000,
slow: 500
});
/* jshint ignore:end */
| import resolver from './helpers/resolver';
import { setResolver } from 'ember-mocha';
setResolver(resolver);
/* jshint ignore:start */
mocha.setup({
timeout: 15000,
slow: 500
});
/* jshint ignore:end */
| Increase timeout in ember tests | Increase timeout in ember tests
no issue
- increases individual test timeout from 5sec to 15sec
It seems Travis is occasionally _very_ slow and will timeout on heavier acceptance tests resulting in random failures. Hopefully this will reduce the number of random test failures we see.
| JavaScript | mit | TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost | ---
+++
@@ -5,7 +5,7 @@
/* jshint ignore:start */
mocha.setup({
- timeout: 5000,
+ timeout: 15000,
slow: 500
});
/* jshint ignore:end */ |
17f67a15419b45e90498982ba77c9d9083eda189 | knexfile.js | knexfile.js | require('dotenv').config();
module.exports = {
development: {
client: 'postgresql',
connection: {
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PASS,
database : process.env.DB_NAME,
port : process.env.DB_PORT,
ssl : process.env.DB_SSL
},
migrations: {
directory: './server/db/migrations',
tableName: 'migrations'
},
seeds: {
directory: './server/db/seeds'
}
},
production: {
client: 'postgresql',
connection: process.env.DATABASE_PRODUCTION + '?ssl=true',
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'migrations'
}
}
}; | require('dotenv').config();
module.exports = {
development: {
client: 'postgresql',
connection: {
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PASS,
database : process.env.DB_NAME,
port : process.env.DB_PORT,
ssl : process.env.DB_SSL
},
migrations: {
directory: './server/db/migrations',
tableName: 'migrations'
},
seeds: {
directory: './server/db/seeds'
}
},
production: {
client: 'postgresql',
connection: process.env.DATABASE_URL + '?ssl=true',
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'migrations'
}
}
}; | Change config of production server | Change config of production server
| JavaScript | mit | potatowave/escolha,potatowave/escolha | ---
+++
@@ -22,7 +22,7 @@
},
production: {
client: 'postgresql',
- connection: process.env.DATABASE_PRODUCTION + '?ssl=true',
+ connection: process.env.DATABASE_URL + '?ssl=true',
pool: {
min: 2,
max: 10 |
5b204b9a00767a0844ce4e364b989b1adcd03360 | lib/core/src/client/preview/url.js | lib/core/src/client/preview/url.js | import { history, document } from 'global';
import qs from 'qs';
import { toId } from '@storybook/router/utils';
export function pathToId(path) {
const match = (path || '').match(/^\/story\/(.+)/);
if (!match) {
throw new Error(`Invalid path '${path}', must start with '/story/'`);
}
return match[1];
}
export const setPath = ({ storyId, viewMode }) => {
const { path, selectedKind, selectedStory, ...rest } = qs.parse(document.location.search, {
ignoreQueryPrefix: true,
});
const newPath = `${document.location.pathname}?${qs.stringify({
...rest,
id: storyId,
viewMode,
})}`;
history.replaceState({}, '', newPath);
};
export const getIdFromLegacyQuery = ({ path, selectedKind, selectedStory }) =>
(path && pathToId(path)) || (selectedKind && selectedStory && toId(selectedKind, selectedStory));
export const parseQueryParameters = search => {
const { id } = qs.parse(search, { ignoreQueryPrefix: true });
return id;
};
export const initializePath = () => {
const query = qs.parse(document.location.search, { ignoreQueryPrefix: true });
let { id: storyId, viewMode } = query; // eslint-disable-line prefer-const
if (!storyId) {
storyId = getIdFromLegacyQuery(query);
if (storyId) {
setPath({ storyId, viewMode });
}
}
return { storyId };
};
| import { history, document } from 'global';
import qs from 'qs';
import { toId } from '@storybook/router/utils';
export function pathToId(path) {
const match = (path || '').match(/^\/story\/(.+)/);
if (!match) {
throw new Error(`Invalid path '${path}', must start with '/story/'`);
}
return match[1];
}
export const setPath = ({ storyId, viewMode }) => {
const { path, selectedKind, selectedStory, ...rest } = qs.parse(document.location.search, {
ignoreQueryPrefix: true,
});
const newPath = `${document.location.pathname}?${qs.stringify({
...rest,
id: storyId,
viewMode,
})}`;
history.replaceState({}, '', newPath);
};
export const getIdFromLegacyQuery = ({ path, selectedKind, selectedStory }) =>
(path && pathToId(path)) || (selectedKind && selectedStory && toId(selectedKind, selectedStory));
export const parseQueryParameters = search => {
const { id } = qs.parse(search, { ignoreQueryPrefix: true });
return id;
};
export const initializePath = () => {
const query = qs.parse(document.location.search, { ignoreQueryPrefix: true });
let { id: storyId, viewMode } = query; // eslint-disable-line prefer-const
if (!storyId) {
storyId = getIdFromLegacyQuery(query);
if (storyId) {
setPath({ storyId, viewMode });
}
}
return { storyId, viewMode };
};
| Fix initial viewMode parsing typo | Fix initial viewMode parsing typo
| JavaScript | mit | storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook | ---
+++
@@ -39,5 +39,5 @@
setPath({ storyId, viewMode });
}
}
- return { storyId };
+ return { storyId, viewMode };
}; |
1bbdb4ab27bf647f900d5908fab1aa3a6e660a42 | scripts/clients/sonar_client.js | scripts/clients/sonar_client.js | const {
spawn
} = require("child_process");
const options = {
sources: function (path) {
return `-Dsonar.sources="${path}"`;
},
projectName: function (name) {
return `-Dsonar.projectName="${name}"`;
},
projectKey: function (owner, name) {
return `-Dsonar.projectKey="${owner}:${name}"`;
}
}
/**
* Make sure to:
* 1. Have sonar-scanner added to PATH
* 2. Update the global settings to point to your SonarQube server by editing <install_directory>/conf/sonar-scanner.properties.
*/
module.exports = {
startSonar: function (repo, pathToSources) {
spawn("sonar-scanner", [projectKey(repo.owner, repo.name), projectName(repo.name), sources(pathToSources)]);
}
}; | Add sonar scanner client script | Add sonar scanner client script
| JavaScript | mit | ovidiup13/L5-ProjectSource | ---
+++
@@ -0,0 +1,26 @@
+const {
+ spawn
+} = require("child_process");
+
+const options = {
+ sources: function (path) {
+ return `-Dsonar.sources="${path}"`;
+ },
+ projectName: function (name) {
+ return `-Dsonar.projectName="${name}"`;
+ },
+ projectKey: function (owner, name) {
+ return `-Dsonar.projectKey="${owner}:${name}"`;
+ }
+}
+
+/**
+ * Make sure to:
+ * 1. Have sonar-scanner added to PATH
+ * 2. Update the global settings to point to your SonarQube server by editing <install_directory>/conf/sonar-scanner.properties.
+ */
+module.exports = {
+ startSonar: function (repo, pathToSources) {
+ spawn("sonar-scanner", [projectKey(repo.owner, repo.name), projectName(repo.name), sources(pathToSources)]);
+ }
+}; | |
2a2ef17d85f9336799c3e39249f960f75cac7cf6 | src/core-uri-handlers.js | src/core-uri-handlers.js | // Converts a query string parameter for a line or column number
// to a zero-based line or column number for the Atom API.
function getLineColNumber (numStr) {
const num = parseInt(numStr || 0, 10)
return Math.max(num - 1, 0)
}
function openFile (atom, {query}) {
const {filename, line, column} = query
atom.workspace.open(filename, {
initialLine: getLineColNumber(line),
initialColumn: getLineColNumber(column),
searchAllPanes: true
})
}
function windowShouldOpenFile ({query}) {
const {filename} = query
return (win) => win.containsPath(filename)
}
const ROUTER = {
'/open/file': { handler: openFile, getWindowPredicate: windowShouldOpenFile }
}
module.exports = {
create (atomEnv) {
return function coreURIHandler (parsed) {
const config = ROUTER[parsed.pathname]
if (config) {
config.handler(atomEnv, parsed)
}
}
},
windowPredicate (parsed) {
const config = ROUTER[parsed.pathname]
if (config && config.getWindowPredicate) {
return config.getWindowPredicate(parsed)
} else {
return (win) => true
}
}
}
| const fs = require('fs-plus')
// Converts a query string parameter for a line or column number
// to a zero-based line or column number for the Atom API.
function getLineColNumber (numStr) {
const num = parseInt(numStr || 0, 10)
return Math.max(num - 1, 0)
}
function openFile (atom, {query}) {
const {filename, line, column} = query
atom.workspace.open(filename, {
initialLine: getLineColNumber(line),
initialColumn: getLineColNumber(column),
searchAllPanes: true
})
}
function windowShouldOpenFile ({query}) {
const {filename} = query
const stat = fs.statSyncNoException(filename)
return win => win.containsLocation({
pathToOpen: filename,
exists: Boolean(stat),
isFile: stat.isFile(),
isDirectory: stat.isDirectory()
})
}
const ROUTER = {
'/open/file': { handler: openFile, getWindowPredicate: windowShouldOpenFile }
}
module.exports = {
create (atomEnv) {
return function coreURIHandler (parsed) {
const config = ROUTER[parsed.pathname]
if (config) {
config.handler(atomEnv, parsed)
}
}
},
windowPredicate (parsed) {
const config = ROUTER[parsed.pathname]
if (config && config.getWindowPredicate) {
return config.getWindowPredicate(parsed)
} else {
return () => true
}
}
}
| Use containsLocation() for URL handler processing | Use containsLocation() for URL handler processing
| JavaScript | mit | atom/atom,atom/atom,brettle/atom,brettle/atom,brettle/atom,Mokolea/atom,Mokolea/atom,PKRoma/atom,PKRoma/atom,Mokolea/atom,atom/atom,PKRoma/atom | ---
+++
@@ -1,3 +1,5 @@
+const fs = require('fs-plus')
+
// Converts a query string parameter for a line or column number
// to a zero-based line or column number for the Atom API.
function getLineColNumber (numStr) {
@@ -17,7 +19,14 @@
function windowShouldOpenFile ({query}) {
const {filename} = query
- return (win) => win.containsPath(filename)
+ const stat = fs.statSyncNoException(filename)
+
+ return win => win.containsLocation({
+ pathToOpen: filename,
+ exists: Boolean(stat),
+ isFile: stat.isFile(),
+ isDirectory: stat.isDirectory()
+ })
}
const ROUTER = {
@@ -39,7 +48,7 @@
if (config && config.getWindowPredicate) {
return config.getWindowPredicate(parsed)
} else {
- return (win) => true
+ return () => true
}
}
} |
62d9fedc4b56f986d04480f9b342ae2ef5d37f60 | scripts/actions/RepoActionCreators.js | scripts/actions/RepoActionCreators.js | 'use strict';
var AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes'),
RepoAPI = require('../utils/RepoAPI'),
StarredReposByUserStore = require('../stores/StarredReposByUserStore'),
RepoStore = require('../stores/RepoStore');
var RepoActionCreators = {
requestRepo(fullName, fields) {
if (RepoStore.contains(fullName, fields)) {
return;
}
AppDispatcher.handleViewAction({
type: ActionTypes.REQUEST_REPO,
fullName: fullName
});
RepoAPI.requestRepo(fullName);
},
requestStarredReposPage(login, isInitialRequest) {
if (StarredReposByUserStore.isExpectingPage(login) ||
StarredReposByUserStore.isLastPage(login)) {
return;
}
if (isInitialRequest && StarredReposByUserStore.getPageCount(login) > 0) {
return;
}
AppDispatcher.handleViewAction({
type: ActionTypes.REQUEST_STARRED_REPOS_PAGE,
login: login
});
var nextPageUrl = StarredReposByUserStore.getNextPageUrl(login);
RepoAPI.requestStarredReposPage(login, nextPageUrl);
}
};
module.exports = RepoActionCreators; | 'use strict';
var AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes'),
RepoAPI = require('../utils/RepoAPI'),
StarredReposByUserStore = require('../stores/StarredReposByUserStore'),
RepoStore = require('../stores/RepoStore');
var RepoActionCreators = {
requestRepo(fullName, fields) {
if (RepoStore.contains(fullName, fields)) {
return;
}
// Although this action is currently not handled by any store,
// it is fired for consistency. You might want to use it later,
// e.g. to show a spinner or have a more detailed log.
AppDispatcher.handleViewAction({
type: ActionTypes.REQUEST_REPO,
fullName: fullName
});
RepoAPI.requestRepo(fullName);
},
requestStarredReposPage(login, isInitialRequest) {
if (StarredReposByUserStore.isExpectingPage(login) ||
StarredReposByUserStore.isLastPage(login)) {
return;
}
if (isInitialRequest && StarredReposByUserStore.getPageCount(login) > 0) {
return;
}
AppDispatcher.handleViewAction({
type: ActionTypes.REQUEST_STARRED_REPOS_PAGE,
login: login
});
var nextPageUrl = StarredReposByUserStore.getNextPageUrl(login);
RepoAPI.requestStarredReposPage(login, nextPageUrl);
}
};
module.exports = RepoActionCreators;
| Add a comment regarding unused action | Add a comment regarding unused action | JavaScript | mit | stylecoder/flux-react-router-example,AnthonyWhitaker/flux-react-router-example,machnicki/healthunlocked,goatslacker/flux-react-router-example,tiengtinh/flux-react-router-example,machnicki/healthunlocked,keshavnandan/flux-react-router-example,bertomartin/flux-react-router-example,ycavatars/flux-react-router-example,keshavnandan/flux-react-router-example,AnthonyWhitaker/flux-react-router-example,rigorojas/flux-react-router-example,bertomartin/flux-react-router-example,gaearon/flux-react-router-example,faival/wemix,chengliangbuct/flux-react-router-example,goatslacker/flux-react-router-example,nsipplswezey/flux-react-router-example,roth1002/flux-react-router-example,rashidul0405/flux-react-router-example,ycavatars/flux-react-router-example,stylecoder/flux-react-router-example,roth1002/flux-react-router-example,Jonekee/flux-react-router-example,nsipplswezey/flux-react-router-example,rashidul0405/flux-react-router-example,rigorojas/flux-react-router-example,tiengtinh/flux-react-router-example,chengliangbuct/flux-react-router-example,gaearon/flux-react-router-example,doron2402/flux-react-router-example,Jonekee/flux-react-router-example,doron2402/flux-react-router-example,faival/wemix | ---
+++
@@ -11,6 +11,10 @@
if (RepoStore.contains(fullName, fields)) {
return;
}
+
+ // Although this action is currently not handled by any store,
+ // it is fired for consistency. You might want to use it later,
+ // e.g. to show a spinner or have a more detailed log.
AppDispatcher.handleViewAction({
type: ActionTypes.REQUEST_REPO, |
52a7d329dec734129cf130e79f7a1c4929d02ba7 | app/authenticators/api.js | app/authenticators/api.js | import Ember from 'ember';
import Base from 'simple-auth/authenticators/base';
import ENV from 'wordset/config/environment';
export default Base.extend({
restore: function(properties) {
var propertiesObject = Ember.Object.create(properties);
return new Ember.RSVP.Promise(function(resolve, reject) {
if (!Ember.isEmpty(propertiesObject.get("username")) && !Ember.isEmpty(propertiesObject.get("auth_key"))) {
resolve(properties);
} else {
reject();
}
});
},
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var data = {};
data = {
username: credentials.identification,
password: credentials.password
};
_this.makeRequest(data).then(function(response) {
Ember.run(function() {
resolve(response);
});
}, function(xhr) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},
invalidate: function() {
return Ember.RSVP.resolve();
},
makeRequest: function(data) {
return Ember.$.ajax({
url: ENV.api + '/login',
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Accept', settings.accepts.json);
}
});
}
});
| import Ember from 'ember';
import Base from 'simple-auth/authenticators/base';
import ENV from 'wordset/config/environment';
export default Base.extend({
restore: function(properties) {
var propertiesObject = Ember.Object.create(properties);
return new Ember.RSVP.Promise(function(resolve, reject) {
if (!Ember.isEmpty(propertiesObject.get("username")) && !Ember.isEmpty(propertiesObject.get("auth_key"))) {
resolve(properties);
} else {
reject();
}
});
},
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var data = {};
data = {
username: credentials.identification,
password: credentials.password
};
_this.makeRequest(data).then(function(response) {
Ember.run(function() {
resolve(response);
});
}, function(xhr) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},
invalidate: function() {
return Ember.RSVP.resolve();
},
makeRequest: function(data) {
return Ember.$.ajax({
url: ENV.api + '/auth/login',
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Accept', settings.accepts.json);
}
});
}
});
| Use new namespaced auth API methods | Use new namespaced auth API methods
| JavaScript | mit | kaelig/wordset-ui,BryanCode/wordset-ui,wordset/wordset-ui,BryanCode/wordset-ui,wordset/wordset-ui,BryanCode/wordset-ui,kaelig/wordset-ui,wordset/wordset-ui | ---
+++
@@ -38,7 +38,7 @@
},
makeRequest: function(data) {
return Ember.$.ajax({
- url: ENV.api + '/login',
+ url: ENV.api + '/auth/login',
type: 'POST',
data: data,
dataType: 'json', |
002452c5b597e98408e5b28b6658f34e54a66500 | app/public/sa-tracking.js | app/public/sa-tracking.js | 'use strict';
var events = [];
var requestInterval = 5000;
window.addEventListener('click', function(e) {
e = event || window.event;
events.push(processEvent(e));
});
var processEvent = function(e) {
// Event attributes
var eventProps = ['type', 'timeStamp'];
// Event target attributes
var targetProps = ['nodeName', 'innerHTML'];
// Trimmed event
var result = {};
eventProps.forEach(function(prop) {
if (e[prop]) { result[prop] = e[prop]; }
});
if(e.target) {
targetProps.forEach(function(prop) {
if(e.target[prop]) { result[prop] = e.target[prop]; }
});
}
console.log('event result: ' + JSON.stringify(result));
return result;
};
var PostRequest = function() {
var xhr = new XMLHttpRequest();
var url = 'http://sextant-ng-b.herokuapp.com/api/0_0_1/data';
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
return xhr;
};
var request = new PostRequest();
var sendEvents = setInterval(function() {
if (!events.length) return;
request.send(JSON.stringify(events));
events = [];
}, requestInterval); | 'use strict';
var events = [];
var requestInterval = 5000;
window.addEventListener('click', function(e) {
e = event || window.event;
events.push(processEvent(e));
});
var processEvent = function(e) {
// Event attributes
var eventProps = ['type', 'timeStamp'];
// Event target attributes
var targetProps = ['nodeName', 'innerHTML'];
// Trimmed event
var result = {};
eventProps.forEach(function(prop) {
if (e[prop]) { result[prop] = e[prop]; }
});
if(e.target) {
targetProps.forEach(function(prop) {
if(e.target[prop]) { result[prop] = e.target[prop]; }
});
}
console.log('event result: ' + JSON.stringify(result));
return result;
};
var PostRequest = function() {
var xhr = new XMLHttpRequest();
var url = 'http://sextant-ng-b.herokuapp.com/api/0_0_1/data';
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
return xhr;
};
var sendEvents = setInterval(function() {
if (!events.length) return;
var request = new PostRequest();
request.send(JSON.stringify(events));
events = [];
}, requestInterval); | Fix invalid state error by instantiating new XHR with each request | Fix invalid state error by instantiating new XHR with each request
| JavaScript | mit | Sextant-WDB/sextant-ng | ---
+++
@@ -44,11 +44,11 @@
return xhr;
};
-var request = new PostRequest();
var sendEvents = setInterval(function() {
if (!events.length) return;
+ var request = new PostRequest();
request.send(JSON.stringify(events));
events = []; |
0b8920aea121ca1483e9cb32e55d4ba38ba2f4b7 | src/utils/misc.js | src/utils/misc.js | /* @flow strict */
export const caseInsensitiveCompareFunc = (a: string, b: string): number =>
a.toLowerCase().localeCompare(b.toLowerCase());
export const numberWithSeparators = (value: number | string): string =>
value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
export function deeperMerge<K, V>(obj1: { [K]: V }, obj2: { [K]: V }): { [K]: V } {
return Array.from(new Set([...Object.keys(obj1), ...Object.keys(obj2)])).reduce((newObj, key) => {
newObj[key] =
obj1[key] === undefined
? obj2[key]
: obj2[key] === undefined
? obj1[key]
: { ...obj1[key], ...obj2[key] };
return newObj;
}, ({}: { [K]: V }));
}
export const initialsFromString = (name: string): string =>
(name.match(/\S+\s*/g) || []).map(x => x[0].toUpperCase()).join('');
export function groupItemsById<T: { id: number }>(items: T[]): { [id: number]: T } {
return items.reduce((itemsById, item) => {
itemsById[item.id] = item;
return itemsById;
}, {});
}
export const isValidEmailFormat = (email: string = ''): boolean => /\S+@\S+\.\S+/.test(email);
| /* @flow strict */
export const caseInsensitiveCompareFunc = (a: string, b: string): number =>
a.toLowerCase().localeCompare(b.toLowerCase());
export const numberWithSeparators = (value: number | string): string =>
value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
export function deeperMerge<K, V>(obj1: { [K]: V }, obj2: { [K]: V }): { [K]: V } {
return Array.from(new Set([...Object.keys(obj1), ...Object.keys(obj2)])).reduce((newObj, key) => {
newObj[key] =
obj1[key] === undefined
? obj2[key]
: obj2[key] === undefined
? obj1[key]
: { ...obj1[key], ...obj2[key] };
return newObj;
}, ({}: { [K]: V }));
}
export const initialsFromString = (name: string): string =>
(name.match(/\S+\s*/g) || []).map(x => x[0].toUpperCase()).join('');
export function groupItemsById<T: { +id: number }>(items: T[]): { [id: number]: T } {
return items.reduce((itemsById, item) => {
itemsById[item.id] = item;
return itemsById;
}, {});
}
export const isValidEmailFormat = (email: string = ''): boolean => /\S+@\S+\.\S+/.test(email);
| Tweak type to accept read-only objects, too. | groupItemsById: Tweak type to accept read-only objects, too.
| JavaScript | apache-2.0 | vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile | ---
+++
@@ -21,7 +21,7 @@
export const initialsFromString = (name: string): string =>
(name.match(/\S+\s*/g) || []).map(x => x[0].toUpperCase()).join('');
-export function groupItemsById<T: { id: number }>(items: T[]): { [id: number]: T } {
+export function groupItemsById<T: { +id: number }>(items: T[]): { [id: number]: T } {
return items.reduce((itemsById, item) => {
itemsById[item.id] = item;
return itemsById; |
be686e0accb9e8facc652a559b1fb39a8508c97d | awx/ui/client/src/i18n.js | awx/ui/client/src/i18n.js | /* jshint ignore:start */
var sprintf = require('sprintf-js').sprintf;
/**
* @ngdoc method
* @name function:i18n#N_
* @methodOf function:N_
* @description this function marks the translatable string with N_
* for 'grunt nggettext_extract'
*
*/
export function N_(s) {
return s;
}
export default
angular.module('I18N', [])
.factory('I18NInit', ['$window', 'gettextCatalog',
function ($window, gettextCatalog) {
return function() {
var langInfo = $window.navigator.language ||
$window.navigator.userLanguage;
var langUrl = langInfo.replace('-', '_');
//gettextCatalog.debug = true;
gettextCatalog.setCurrentLanguage(langInfo);
gettextCatalog.loadRemote('/static/languages/' + langUrl + '.json');
};
}])
.factory('i18n', ['gettextCatalog',
function (gettextCatalog) {
return {
_: function (s) { return gettextCatalog.getString (s); },
N_: N_,
sprintf: sprintf,
hasTranslation: function () {
return gettextCatalog.strings[gettextCatalog.currentLanguage] !== undefined;
}
};
}]);
| /* jshint ignore:start */
var sprintf = require('sprintf-js').sprintf;
/**
* @ngdoc method
* @name function:i18n#N_
* @methodOf function:N_
* @description this function marks the translatable string with N_
* for 'grunt nggettext_extract'
*
*/
export function N_(s) {
return s;
}
export default
angular.module('I18N', [])
.factory('I18NInit', ['$window', 'gettextCatalog',
function ($window, gettextCatalog) {
return function() {
var langInfo = ($window.navigator.languages || [])[0] ||
$window.navigator.language ||
$window.navigator.userLanguage;
var langUrl = langInfo.replace('-', '_');
//gettextCatalog.debug = true;
gettextCatalog.setCurrentLanguage(langInfo);
gettextCatalog.loadRemote('/static/languages/' + langUrl + '.json');
};
}])
.factory('i18n', ['gettextCatalog',
function (gettextCatalog) {
return {
_: function (s) { return gettextCatalog.getString (s); },
N_: N_,
sprintf: sprintf,
hasTranslation: function () {
return gettextCatalog.strings[gettextCatalog.currentLanguage] !== undefined;
}
};
}]);
| Tweak logic used by UI to detect language | Tweak logic used by UI to detect language
Chromium and WebKit based browsers have the window.navigator.languages attribute, which is an ordered array of preferred languages as configured in the browser’s settings.
Although changing the language in Chrome results in an Accept-Language header being added to requests, window.navigator.language still returns the language specified by the OS.
I’ve tested this with Firefox, Chrome, IE 11, and Edge.
Connect #5360
| JavaScript | apache-2.0 | snahelou/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx | ---
+++
@@ -19,7 +19,8 @@
.factory('I18NInit', ['$window', 'gettextCatalog',
function ($window, gettextCatalog) {
return function() {
- var langInfo = $window.navigator.language ||
+ var langInfo = ($window.navigator.languages || [])[0] ||
+ $window.navigator.language ||
$window.navigator.userLanguage;
var langUrl = langInfo.replace('-', '_');
//gettextCatalog.debug = true; |
d2702efedfda3ffdb944a8118befc5d6409e8741 | lib/visualizer.js | lib/visualizer.js | 'use strict'
const visualizeBoardS = Symbol('visualizeBoard')
const visualizeOrdersS = Symbol('visualizeOrders')
module.exports = class Visualizer {
constructor (mapSvg, visualizeBoard, visualizeOrders) {
this.map = mapSvg
this[visualizeBoardS] = visualizeBoard
this[visualizeOrdersS] = visualizeOrders
}
visualizeBoard (board) {
this[visualizeBoardS](board, this.map)
}
visualizeOrders (orders) {
this[visualizeOrdersS](orders, this.map)
}
addEventListenerForUnits (event, listener) {
const units = this.map.querySelectorAll('.vizdip-unit')
if (units) {
[...units].forEach(u => u.addEventListener(event, listener))
return () => [...units].forEach(u => u.removeEventListener(event, listener))
} else {
return () => {}
}
}
addEventListenerForProvinces (event, listener) {
const provinces = this.map.querySelectorAll('.vizdip-province')
if (provinces) {
[...provinces].forEach(p => p.addEventListener(event, listener))
return () => [...provinces].forEach(p => p.removeEventListener(event, listener))
} else {
return () => {}
}
}
}
| 'use strict'
module.exports = class Visualizer {
constructor (mapSvg, visualizeBoard, visualizeOrders) {
this.map = mapSvg
}
visualizeBoard (board) {
}
visualizeOrders (orders) {
}
addEventListenerForUnits (event, listener) {
const units = this.map.querySelectorAll('.vizdip-unit')
if (units) {
[...units].forEach(u => u.addEventListener(event, listener))
return () => [...units].forEach(u => u.removeEventListener(event, listener))
} else {
return () => {}
}
}
addEventListenerForProvinces (event, listener) {
const provinces = this.map.querySelectorAll('.vizdip-province')
if (provinces) {
[...provinces].forEach(p => p.addEventListener(event, listener))
return () => [...provinces].forEach(p => p.removeEventListener(event, listener))
} else {
return () => {}
}
}
}
| Fix the signature of Visualizer | Fix the signature of Visualizer
ref #1
| JavaScript | mit | KarmaMi/vizdip,KarmaMi/vizdip,KarmaMi/vizdip,KarmaMi/vizdip | ---
+++
@@ -1,20 +1,13 @@
'use strict'
-
-const visualizeBoardS = Symbol('visualizeBoard')
-const visualizeOrdersS = Symbol('visualizeOrders')
module.exports = class Visualizer {
constructor (mapSvg, visualizeBoard, visualizeOrders) {
this.map = mapSvg
- this[visualizeBoardS] = visualizeBoard
- this[visualizeOrdersS] = visualizeOrders
}
visualizeBoard (board) {
- this[visualizeBoardS](board, this.map)
}
visualizeOrders (orders) {
- this[visualizeOrdersS](orders, this.map)
}
addEventListenerForUnits (event, listener) { |
893f7371ae0d2517d4276ab4e868ce03b0cf1dbe | lint/lib/linters/RuboCop.js | lint/lib/linters/RuboCop.js | "use strict";
function RuboCop(opts) {
this.exe = "rubocop";
this.ext = process.platform === 'win32' ? ".bat" : "";
this.path = opts.path;
this.responsePath = "stdout";
this.args = ["-s", "{path}", "-f", "json", "--force-exclusion"] ;
if (opts.lint) this.args.push("-l");
if (opts.only) this.args = this.args.concat("--only", opts.only.join(','));
if (opts.except) this.args = this.args.concat("--except", opts.except.join(','));
if (opts.rails) this.args.push('-R');
if (opts.require) this.args = this.args.concat("-r", opts.require.join(','));
}
RuboCop.prototype.processResult = function (data) {
if (data == '') {
return [];
}
let offenses = JSON.parse(data);
return (offenses.files || [{
offenses: []
}])[0].offenses;
};
module.exports = RuboCop;
| "use strict";
function RuboCop(opts) {
this.exe = "rubocop";
this.ext = process.platform === 'win32' ? ".bat" : "";
this.path = opts.path;
this.responsePath = "stdout";
this.args = ["-s", "{path}", "-f", "json"] ;
if (opts.lint) this.args.push("-l");
if (opts.only) this.args = this.args.concat("--only", opts.only.join(','));
if (opts.except) this.args = this.args.concat("--except", opts.except.join(','));
if (opts.rails) this.args.push('-R');
if (opts.require) this.args = this.args.concat("-r", opts.require.join(','));
}
RuboCop.prototype.processResult = function (data) {
if (data == '') {
return [];
}
let offenses = JSON.parse(data);
return (offenses.files || [{
offenses: []
}])[0].offenses;
};
module.exports = RuboCop;
| Remove force exclusion for rubocop | Remove force exclusion for rubocop
Fixes https://github.com/rubyide/vscode-ruby/issues/175 | JavaScript | mit | rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby | ---
+++
@@ -6,7 +6,7 @@
this.path = opts.path;
this.responsePath = "stdout";
- this.args = ["-s", "{path}", "-f", "json", "--force-exclusion"] ;
+ this.args = ["-s", "{path}", "-f", "json"] ;
if (opts.lint) this.args.push("-l");
if (opts.only) this.args = this.args.concat("--only", opts.only.join(',')); |
8fdece0b1a17c16ad3028befa34adb56d49c4203 | lints/disallowFspathRule.js | lints/disallowFspathRule.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Lint = require("tslint");
class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile) {
return this.applyWithWalker(new NoFsPathWalker(sourceFile, this.getOptions()));
}
}
Rule.FAILURE_STRING = "Do not use Uri.fsPath (or fsPath(document.uri)), use fsPath() instead";
class NoFsPathWalker extends Lint.RuleWalker {
visitPropertyAccessExpression(node) {
if (node.name.text === "fsPath" || node.name.text === "fileName") {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
}
super.visitPropertyAccessExpression(node);
}
}
exports.Rule = Rule;
| "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Lint = require("tslint");
class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile) {
return this.applyWithWalker(new NoFsPathWalker(sourceFile, this.getOptions()));
}
}
Rule.FAILURE_STRING = "Do not use Uri.fsPath or TextDocument.fileName because they lowercase Windows drive letters causing issues with interop with other tools. Use fsPath(uri) instead.";
class NoFsPathWalker extends Lint.RuleWalker {
visitPropertyAccessExpression(node) {
// TODO: Figure out how to get parent type to avoid false positives.
if (node.name.text === "fsPath" || node.name.text === "fileName") {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
}
super.visitPropertyAccessExpression(node);
}
}
exports.Rule = Rule;
| Fix typo and add TODO | Fix typo and add TODO
| JavaScript | mit | Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code,Dart-Code/Dart-Code | ---
+++
@@ -9,10 +9,11 @@
return this.applyWithWalker(new NoFsPathWalker(sourceFile, this.getOptions()));
}
}
-Rule.FAILURE_STRING = "Do not use Uri.fsPath (or fsPath(document.uri)), use fsPath() instead";
+Rule.FAILURE_STRING = "Do not use Uri.fsPath or TextDocument.fileName because they lowercase Windows drive letters causing issues with interop with other tools. Use fsPath(uri) instead.";
class NoFsPathWalker extends Lint.RuleWalker {
visitPropertyAccessExpression(node) {
+ // TODO: Figure out how to get parent type to avoid false positives.
if (node.name.text === "fsPath" || node.name.text === "fileName") {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
} |
18dbfb541960465944971269a393af668ecbb33d | specs/database.js | specs/database.js | var chai = require('chai');
var expect = chai.expect;
var db = require('../server/db/config');
var models = require('../server/db/models');
describe('database storage', function() {
var testData = {
x: 37.783599,
y: -122.408974,
z: 69,
message: 'Brooks was here'
};
var invalidTestData = {
x: 37.783599,
y: -122.408974,
z: 69
};
it('should validate user input', function(done) {
models.insert(invalidTestData, function(msg) {
expect(msg).to.equal('Could not insert new message: invalid input.');
done();
})
});
it('should add messages to the database', function(done) {
models.insert(testData, function(msg) {
expect(msg).to.equal('Successfully inserted new message and mark to database.');
done();
})
});
});
| var chai = require('chai');
var expect = chai.expect;
var db = require('../server/db/config');
var models = require('../server/db/models');
describe('database storage', function() {
var testData = {
x: 37.783599,
y: -122.408974,
z: 69,
message: 'Brooks was here'
};
var invalidTestData = {
x: 37.783599,
y: -122.408974,
z: 69
};
var testLocation = {
x: 37.183549,
y: -122.108974,
};
it('should validate user input', function(done) {
models.insert(invalidTestData, function(msg) {
expect(msg).to.equal('Could not insert new message: invalid input.');
done();
})
});
it('should add messages to the database', function(done) {
models.insert(testData, function(msg) {
expect(msg).to.equal('Successfully inserted new message and mark to database.');
done();
})
});
it('should retrieve messages from the database', function(done) {
models.retrieve(testLocation, function(messages) {
expect(messages).to.be.instanceof(Array);
done();
})
});
});
| Add tests to confirm message retrieval | Add tests to confirm message retrieval
| JavaScript | mit | team-oath/uncovery,team-oath/uncovery,team-oath/uncovery,team-oath/uncovery,scottdixon/uncovery,scottdixon/uncovery,scottdixon/uncovery,scottdixon/uncovery | ---
+++
@@ -15,6 +15,10 @@
y: -122.408974,
z: 69
};
+ var testLocation = {
+ x: 37.183549,
+ y: -122.108974,
+ };
it('should validate user input', function(done) {
models.insert(invalidTestData, function(msg) {
@@ -29,4 +33,11 @@
done();
})
});
+
+ it('should retrieve messages from the database', function(done) {
+ models.retrieve(testLocation, function(messages) {
+ expect(messages).to.be.instanceof(Array);
+ done();
+ })
+ });
}); |
d2adfb4288153b333a0aef69428a0312d163d085 | Kinect2Scratch.js | Kinect2Scratch.js | (function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
['b', '%m.k', 'k', 'heady']
],
menus: {
k: ['headx', 'heady', 'righthandx', 'righthandy']
}
};
ext.my_first_block = function() {
console.log("hello, world.");
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
ext.k = function(m) {
switch(m){
case 'headx': return true;
case 'heady': return true;
case 'righthandx': return false;
case 'righthandy': return false;
}
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({}); | (function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
['r', '%m.k', 'k', 'heady']
],
menus: {
k: ['headx', 'heady', 'righthandx', 'righthandy']
}
};
ext.my_first_block = function() {
console.log("hello, world.");
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
ext.k = function(m) {
switch(m){
case 'headx': return 1;
case 'heady': return 2;
case 'righthandx': return 3;
case 'righthandy': return 4;
}
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({}); | Change boolean to reporter for block with dropdowns | Change boolean to reporter for block with dropdowns
| JavaScript | bsd-3-clause | visor841/SkelScratch,Calvin-CS/SkelScratch | ---
+++
@@ -14,7 +14,7 @@
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
- ['b', '%m.k', 'k', 'heady']
+ ['r', '%m.k', 'k', 'heady']
],
menus: {
@@ -32,10 +32,10 @@
ext.k = function(m) {
switch(m){
- case 'headx': return true;
- case 'heady': return true;
- case 'righthandx': return false;
- case 'righthandy': return false;
+ case 'headx': return 1;
+ case 'heady': return 2;
+ case 'righthandx': return 3;
+ case 'righthandy': return 4;
}
};
|
2b928608f1bad3f1721838afa00dccddb724f48b | util/schemesPreviewGenerator.js | util/schemesPreviewGenerator.js | const nunjucks = require('nunjucks');
const fs = require('fs-promise');
const path = require('path');
const yaml = require('js-yaml');
const Promise = require('bluebird');
const schemesDir = '../db/schemes';
fs
.readdir(schemesDir)
.then(function(schemeFileNames) {
const promises = [];
schemeFileNames.forEach(function(schemeFileName) {
promises.push(fs.readFile(path.join(schemesDir, schemeFileName), 'utf-8'));
});
Promise.all(promises).then(function(yamlSchemes) {
yamlSchemes = yamlSchemes.map(yamlScheme => yaml.load(yamlScheme));
fs
.readFile('./schemesPreview.nunJucks', 'utf-8')
.then(function(templ) {
const preview = nunjucks.renderString(templ, {
schemes: yamlSchemes
});
fs.writeFile('../dist/index.html', preview);
});
});
});
| const nunjucks = require('nunjucks');
const fs = require('fs-promise');
const path = require('path');
const yaml = require('js-yaml');
const Promise = require('bluebird');
const schemesDir = path.join(__dirname, '../db/schemes');
fs
.readdir(schemesDir)
.then(function(schemeFileNames) {
const promises = [];
schemeFileNames.forEach(function(schemeFileName) {
promises.push(fs.readFile(path.join(schemesDir, schemeFileName), 'utf-8'));
});
Promise.all(promises).then(function(yamlSchemes) {
yamlSchemes = yamlSchemes.map(yamlScheme => yaml.load(yamlScheme));
fs
.readFile(path.join(__dirname, './schemesPreview.nunJucks'), 'utf-8')
.then(function(templ) {
const preview = nunjucks.renderString(templ, {
schemes: yamlSchemes
});
fs.writeFile(path.join(__dirname, '../dist/index.html'), preview);
});
});
});
| Read files relative from script's directory | fix(cli): Read files relative from script's directory
| JavaScript | mit | base16-builder/base16-builder,aloisdg/base16-builder,base16-builder/base16-builder,aloisdg/base16-builder,aloisdg/base16-builder,base16-builder/base16-builder | ---
+++
@@ -4,7 +4,7 @@
const yaml = require('js-yaml');
const Promise = require('bluebird');
-const schemesDir = '../db/schemes';
+const schemesDir = path.join(__dirname, '../db/schemes');
fs
.readdir(schemesDir)
@@ -16,12 +16,12 @@
Promise.all(promises).then(function(yamlSchemes) {
yamlSchemes = yamlSchemes.map(yamlScheme => yaml.load(yamlScheme));
fs
- .readFile('./schemesPreview.nunJucks', 'utf-8')
+ .readFile(path.join(__dirname, './schemesPreview.nunJucks'), 'utf-8')
.then(function(templ) {
const preview = nunjucks.renderString(templ, {
schemes: yamlSchemes
});
- fs.writeFile('../dist/index.html', preview);
+ fs.writeFile(path.join(__dirname, '../dist/index.html'), preview);
});
});
}); |
daeb051c4fba5603cad33cc414528052c09a0afd | src/geolocator.js | src/geolocator.js | angular.module('aGeolocator', [])
.factory('Geolocator', ['$http', '$q', function($http, $q){
GEOIP_URL = "https://www.telize.com/geoip"
_getIPLocation = function() {
$http.get(GEOIP_URL).then(function(res) {
return res.data;
}).catch(function(err){
return $q.reject(err.data);
});
};
return {
getIPLocation: _getIPLocation
};
}]);
| angular.module('aGeolocator', [])
.factory('Geolocator', ['$http', '$q', function($http, $q){
var GEOIP_URL = "https://www.telize.com/geoip";
var _getIPLocation = function() {
return $http.get(GEOIP_URL).then(function(res) {
return res.data;
}).catch(function(err){
return $q.reject(err.data);
});
};
return {
getIPLocation: _getIPLocation
};
}]);
| Fix returned result and variable declaration | Fix returned result and variable declaration
| JavaScript | bsd-2-clause | asoesilo/geolocator | ---
+++
@@ -1,9 +1,9 @@
angular.module('aGeolocator', [])
.factory('Geolocator', ['$http', '$q', function($http, $q){
- GEOIP_URL = "https://www.telize.com/geoip"
+ var GEOIP_URL = "https://www.telize.com/geoip";
- _getIPLocation = function() {
- $http.get(GEOIP_URL).then(function(res) {
+ var _getIPLocation = function() {
+ return $http.get(GEOIP_URL).then(function(res) {
return res.data;
}).catch(function(err){
return $q.reject(err.data); |
966a743b8e9dd75cd68fde99686e12c889103e86 | views/components/embed-image.js | views/components/embed-image.js | import React from "react-native";
const {
Dimensions,
Image
} = React;
export default class EmbedImage extends React.Component {
shouldComponentUpdate(nextProps) {
return (
this.props.height !== nextProps.height ||
this.props.width !== nextProps.width ||
this.props.uri !== nextProps.uri
);
}
render() {
const {
height,
width,
uri
} = this.props;
const win = Dimensions.get("window");
const ratio = (height && width) ? (height / width) : 1;
// Determine the optimal height and width
const displayWidth = (height ? Math.min(width, win.width - 56) : 160);
const displayHeight = displayWidth * ratio;
return (
<Image
style={[ {
height: displayHeight,
width: displayWidth
}, this.props.style ]}
source={{ uri }}
/>
);
}
}
EmbedImage.propTypes = {
height: React.PropTypes.number,
width: React.PropTypes.number,
uri: React.PropTypes.string.isRequired
};
| import React from "react-native";
const {
Dimensions,
Image
} = React;
export default class EmbedImage extends React.Component {
shouldComponentUpdate(nextProps) {
return (
this.props.height !== nextProps.height ||
this.props.width !== nextProps.width ||
this.props.uri !== nextProps.uri
);
}
render() {
const {
height,
width,
uri
} = this.props;
const win = Dimensions.get("window");
const ratio = (height && width) ? (height / width) : 1;
// Determine the optimal height and width
const displayWidth = (height ? Math.min(width, win.width - 120) : 160);
const displayHeight = displayWidth * ratio;
return (
<Image
style={[ {
height: displayHeight,
width: displayWidth
}, this.props.style ]}
source={{ uri }}
/>
);
}
}
EmbedImage.propTypes = {
height: React.PropTypes.number,
width: React.PropTypes.number,
uri: React.PropTypes.string.isRequired
};
| Fix image size in chat | Fix image size in chat
| JavaScript | unknown | wesley1001/io.scrollback.neighborhoods,scrollback/io.scrollback.neighborhoods,wesley1001/io.scrollback.neighborhoods,scrollback/io.scrollback.neighborhoods | ---
+++
@@ -25,7 +25,7 @@
const ratio = (height && width) ? (height / width) : 1;
// Determine the optimal height and width
- const displayWidth = (height ? Math.min(width, win.width - 56) : 160);
+ const displayWidth = (height ? Math.min(width, win.width - 120) : 160);
const displayHeight = displayWidth * ratio;
return ( |
227b01b527deab80958e30bd8bf6a194b06317aa | src/components/Admin/Menubar.js | src/components/Admin/Menubar.js | import React from 'react';
import { Link } from 'react-router-dom';
export const Menubar = () => (
<div className="sub-navigation">
<div className="limit-width">
<Link className="sub-navigation__link" to="/admin/profile"><span>Profile</span></Link>
<Link className="sub-navigation__link" to="/admin/socials"><span>Socials</span></Link>
<Link className="sub-navigation__link" to="/admin/sections"><span>Sections</span></Link>
</div>
</div>
);
| import React from 'react';
import { NavLink } from 'react-router-dom';
export const Menubar = () => (
<div className="sub-navigation">
<div className="limit-width">
<NavLink activeClassName="active" className="sub-navigation__link" to="/admin/profile"><span>Profile</span></NavLink>
<NavLink activeClassName="active" className="sub-navigation__link" to="/admin/socials"><span>Socials</span></NavLink>
<NavLink activeClassName="active" className="sub-navigation__link" to="/admin/sections"><span>Sections</span></NavLink>
</div>
</div>
);
| Swap Link to Navlink for settings active class | Swap Link to Navlink for settings active class
| JavaScript | apache-2.0 | nahody/biografia,nahody/biografia | ---
+++
@@ -1,12 +1,12 @@
import React from 'react';
-import { Link } from 'react-router-dom';
+import { NavLink } from 'react-router-dom';
export const Menubar = () => (
<div className="sub-navigation">
<div className="limit-width">
- <Link className="sub-navigation__link" to="/admin/profile"><span>Profile</span></Link>
- <Link className="sub-navigation__link" to="/admin/socials"><span>Socials</span></Link>
- <Link className="sub-navigation__link" to="/admin/sections"><span>Sections</span></Link>
+ <NavLink activeClassName="active" className="sub-navigation__link" to="/admin/profile"><span>Profile</span></NavLink>
+ <NavLink activeClassName="active" className="sub-navigation__link" to="/admin/socials"><span>Socials</span></NavLink>
+ <NavLink activeClassName="active" className="sub-navigation__link" to="/admin/sections"><span>Sections</span></NavLink>
</div>
</div>
); |
d59767ea4bf2e0eeeb8537302d071284dc0459e6 | src/constants/LanguageColors.js | src/constants/LanguageColors.js | const LANGUAGE_COLORS = {
Scala: '#BB0017',
Clojure: '#00AA00',
JS: '#CCAA00',
JavaScript: '#CCAA00',
CoffeeScript: '#CCAA00',
Ruby: '#9B111E',
VB: '#663300',
'C#': '#7600BC',
Go: '#996633',
HTML5: '#FF0032',
Swift: '#FC4831',
Shell: '#03C103',
Python: '#0000CC',
'C++': '#FF0099',
Groovy: '#00CC92',
Java: '#006600',
ObjectiveC: '#FF8C00',
CSS: '#0099FF',
DEFAULT: '#B3B3B3'
};
export default LANGUAGE_COLORS;
| import GITHUBCOLORS from '../config/github-colors.json';
const LANGUAGE_COLORS = GITHUBCOLORS;
LANGUAGE_COLORS.DEFAULT= '#B3B3B3';
export default LANGUAGE_COLORS;
| Add github programming language colrs | Add github programming language colrs
| JavaScript | mit | zalando/zalando.github.io-dev,zalando/zalando.github.io-dev | ---
+++
@@ -1,23 +1,6 @@
-const LANGUAGE_COLORS = {
- Scala: '#BB0017',
- Clojure: '#00AA00',
- JS: '#CCAA00',
- JavaScript: '#CCAA00',
- CoffeeScript: '#CCAA00',
- Ruby: '#9B111E',
- VB: '#663300',
- 'C#': '#7600BC',
- Go: '#996633',
- HTML5: '#FF0032',
- Swift: '#FC4831',
- Shell: '#03C103',
- Python: '#0000CC',
- 'C++': '#FF0099',
- Groovy: '#00CC92',
- Java: '#006600',
- ObjectiveC: '#FF8C00',
- CSS: '#0099FF',
- DEFAULT: '#B3B3B3'
-};
+import GITHUBCOLORS from '../config/github-colors.json';
+
+const LANGUAGE_COLORS = GITHUBCOLORS;
+LANGUAGE_COLORS.DEFAULT= '#B3B3B3';
export default LANGUAGE_COLORS; |
97f346c585a727806718db2b02bed6a9ca5ec5c9 | src/js/cordova.js | src/js/cordova.js | 'use strict';
// Load only within android app: cordova=android
if (window.location.search.search('cordova') > 0) {
(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.src = 'js/cordova/cordova.js';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
}
| 'use strict';
// Load only within android app: cordova=android
if (window.location.search.search('cordova') > 0) {
(function(d, script) {
// When cordova is loaded
function onLoad() {
d.addEventListener('deviceready', onDeviceReady, false);
}
// Device APIs are available
function onDeviceReady() {
d.addEventListener('resume', onResume, false);
}
// When device comes to foreground
function onResume() {
if (window.applicationCache) {
window.applicationCache.update();
}
}
script = d.createElement('script');
script.onload = onLoad;
script.type = 'text/javascript';
script.src = 'js/cordova/cordova.js';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
}
| Update application cache on device resume | Update application cache on device resume
| JavaScript | agpl-3.0 | P2Pvalue/teem,P2Pvalue/pear2pear,Grasia/teem,P2Pvalue/teem,Grasia/teem,Grasia/teem,P2Pvalue/teem,P2Pvalue/pear2pear | ---
+++
@@ -3,7 +3,25 @@
// Load only within android app: cordova=android
if (window.location.search.search('cordova') > 0) {
(function(d, script) {
+ // When cordova is loaded
+ function onLoad() {
+ d.addEventListener('deviceready', onDeviceReady, false);
+ }
+
+ // Device APIs are available
+ function onDeviceReady() {
+ d.addEventListener('resume', onResume, false);
+ }
+
+ // When device comes to foreground
+ function onResume() {
+ if (window.applicationCache) {
+ window.applicationCache.update();
+ }
+ }
+
script = d.createElement('script');
+ script.onload = onLoad;
script.type = 'text/javascript';
script.src = 'js/cordova/cordova.js';
d.getElementsByTagName('head')[0].appendChild(script); |
0448d3651cbf8df005ed20dd05ab1241ae940f76 | app/helpers/moment-calendar.js | app/helpers/moment-calendar.js | export { default, momentCalendar } from 'ember-moment/helpers/moment-calendar';
| import Ember from 'ember';
import config from '../config/environment';
import CalendarHelper from 'ember-moment/helpers/moment-calendar';
export default CalendarHelper.extend({
globalAllowEmpty: !!Ember.get(config, 'moment.allowEmpty')
});
| Extend the CalendarHelper with global allowEmpty from config. | Extend the CalendarHelper with global allowEmpty from config. | JavaScript | mit | exop-group/ember-moment,stefanpenner/ember-moment,exop-group/ember-moment,stefanpenner/ember-moment | ---
+++
@@ -1 +1,7 @@
-export { default, momentCalendar } from 'ember-moment/helpers/moment-calendar';
+import Ember from 'ember';
+import config from '../config/environment';
+import CalendarHelper from 'ember-moment/helpers/moment-calendar';
+
+export default CalendarHelper.extend({
+ globalAllowEmpty: !!Ember.get(config, 'moment.allowEmpty')
+}); |
753171601f3471320ac3ec560b5148f9da687622 | app/scripts/src/content/item.js | app/scripts/src/content/item.js | 'use strict';
/* This was necessary to priorize Star Wars: The Clone Wars (2008) over Star Wars: Clone Wars (2003).
I left this object because it could be useful for other movies/shows */
var fullTitles = {
'Star Wars: The Clone Wars': '"Star Wars: The Clone Wars"',
'The Office (U.S.)': 'The Office (US)'
}
function Item(options) {
this.scrubber = options.scrubber;
this.title = fullTitles[options.title] || options.title;
this.type = options.type;
if (this.type === 'show') {
this.epTitle = options.epTitle;
this.season = options.season;
this.episode = options.episode;
}
}
Item.prototype.getScrubber = function() {
return parseFloat(parseFloat(this.scrubber.style.width).toFixed(2));
};
module.exports = Item; | 'use strict';
/* This was necessary to priorize Star Wars: The Clone Wars (2008) over Star Wars: Clone Wars (2003).
I left this object because it could be useful for other movies/shows */
var fullTitles = {
'Star Wars: The Clone Wars': '"Star Wars: The Clone Wars"',
'The Office (U.S.)': 'The Office (US)',
'The Blind Side': '"The Blind Side"',
'The Avengers': '"The Avengers"'
}
function Item(options) {
this.scrubber = options.scrubber;
this.title = fullTitles[options.title] || options.title;
this.type = options.type;
if (this.type === 'show') {
this.epTitle = options.epTitle;
this.season = options.season;
this.episode = options.episode;
}
}
Item.prototype.getScrubber = function() {
return parseFloat(parseFloat(this.scrubber.style.width).toFixed(2));
};
module.exports = Item;
| Add more fullTitles for Item - The Blind Side was returing Blind Side - The Avengers was returning Avenged | Add more fullTitles for Item
- The Blind Side was returing Blind Side
- The Avengers was returning Avenged
| JavaScript | mit | MrMamen/traktNRK,MrMamen/traktNRK,tegon/traktflix,MrMamen/traktflix,MrMamen/traktflix,tegon/traktflix | ---
+++
@@ -4,7 +4,9 @@
I left this object because it could be useful for other movies/shows */
var fullTitles = {
'Star Wars: The Clone Wars': '"Star Wars: The Clone Wars"',
- 'The Office (U.S.)': 'The Office (US)'
+ 'The Office (U.S.)': 'The Office (US)',
+ 'The Blind Side': '"The Blind Side"',
+ 'The Avengers': '"The Avengers"'
}
function Item(options) { |
15df89b668ce34c7d7e0cec6d44471baf031eb24 | www/js/proj4.js | www/js/proj4.js | var proj4 = require('proj4');
proj4.defs('EPSG:25832', '+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs');
var lat = 59.932624;
var lng = 10.734738;
var xy = proj4('EPSG:25832', { x: lng, y: lat })
console.log(xy);
| var proj4 = require('proj4');
proj4.defs('EPSG:25832', '+proj=utm +zone=32 +ellps=GRS80 +units=m +no_defs');
var lat = 59.932624;
var lng = 10.734738;
var xy = proj4('EPSG:25832', { x: lng, y: lat })
console.log(xy);
// Fetch closest stations: http://reis.ruter.no/reisrest/stop/getcloseststopsbycoordinates/?coordinates=(x=596948,y=6645178)&proposals=7
// NB. xy above must be piped through Math.round before being used in the api request above.
| Add note on how to fetch closest stations from the ruter API | Add note on how to fetch closest stations from the ruter API
| JavaScript | mit | hkwaller/next,hkwaller/next,hkwaller/next,hkwaller/next | ---
+++
@@ -6,3 +6,6 @@
var xy = proj4('EPSG:25832', { x: lng, y: lat })
console.log(xy);
+
+// Fetch closest stations: http://reis.ruter.no/reisrest/stop/getcloseststopsbycoordinates/?coordinates=(x=596948,y=6645178)&proposals=7
+// NB. xy above must be piped through Math.round before being used in the api request above. |
e8ca95728951c633891fe8920f1bd450bf84364d | scripts/footer.js | scripts/footer.js | var months = ["enero", "febrero", "marzo",
"abril", "mayo", "junio",
"julio", "agosto", "septiembre",
"octubre", "noviembre", "diciembre"];
var footer = document.getElementById("footer");
var div = document.createElement("DIV");
var update = new Date(document.lastModified);
var day = update.getDate();
var month = update.getMonth();
var year = update.getFullYear();
div.innerHTML = "<p>ültima actualización: " + day + " de " + month[months] + " de " + year + "</p>"
footer.appendChild(div);
| var months = ["enero", "febrero", "marzo",
"abril", "mayo", "junio",
"julio", "agosto", "septiembre",
"octubre", "noviembre", "diciembre"];
var footer = document.getElementById("footer");
var div = document.createElement("DIV");
var update = new Date(document.lastModified);
var day = update.getDate();
var month = update.getMonth();
var year = update.getFullYear();
div.innerHTML = "<p>ültima actualización: " + day + " de " + months[month] + " de " + year + "</p>"
footer.appendChild(div);
| Fix month of last update | Fix month of last update
| JavaScript | mit | nvdaes/nvdaes.github.io,nvdaes/nvdaes.github.io | ---
+++
@@ -9,5 +9,5 @@
var day = update.getDate();
var month = update.getMonth();
var year = update.getFullYear();
-div.innerHTML = "<p>ültima actualización: " + day + " de " + month[months] + " de " + year + "</p>"
+div.innerHTML = "<p>ültima actualización: " + day + " de " + months[month] + " de " + year + "</p>"
footer.appendChild(div); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.