commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
ae78fc5de9f85dd9e13412f626b643314799e487 | lib/runner/request-helpers-postsend.js | lib/runner/request-helpers-postsend.js | var AuthLoader = require('../authorizer/index').AuthLoader,
createAuthInterface = require('../authorizer/auth-interface'),
util = require('../authorizer/util');
module.exports = [
// Post authorization.
function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
// bail out if interactive mode is disabled
if (!util.isInteractiveForAuth(run.options, context.auth.type)) { return done(); }
var auth = context.auth,
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
if (err) { return done(err); }
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true});
});
}
];
| var _ = require('lodash'),
AuthLoader = require('../authorizer/index').AuthLoader,
createAuthInterface = require('../authorizer/auth-interface'),
util = require('../authorizer/util');
module.exports = [
// Post authorization.
function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
// bail out if interactive mode is disabled
if (!util.isInteractiveForAuth(run.options, context.auth.type)) { return done(); }
var auth = context.auth,
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
if (err) { return done(err); }
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true});
});
}
];
| Fix missing import in merge conflict resolution | Fix missing import in merge conflict resolution
| JavaScript | apache-2.0 | postmanlabs/postman-runtime,postmanlabs/postman-runtime |
4bac6994b83e1ae64a01bb25e060a3730571df38 | lib/index.js | lib/index.js | 'use strict';
var child_process = require('child_process');
var fs = require('fs');
var Module = require('module');
var path = require('path');
var _ = require('lodash');
var originalRequire = module.require;
module.require = function(pth) {
if(path.extname(pth) === '.git') return loadGit(pth);
return originalRequire;
};
function loadGit(url) {
var nodeModulesPath = path.join(process.cwd(), 'node_modules');
var oldModules = fs.readdirSync(nodeModulesPath);
child_process.execSync('npm install --save ' + url + ' ');
var newModules = fs.readdirSync(nodeModulesPath);
var added = _.difference(oldModules, newModules)[0];
if(added) return originalRequire(added);
else return undefined;
}
exports = module.exports = loadGit;
console.log(require('git://github.com/yamadapc/mocha-spec-cov-alt.git'));
| 'use strict';
var child_process = require('child_process');
var fs = require('fs');
var Module = require('module');
var path = require('path');
var _ = require('lodash');
require.extensions['.git'] = loadGit;
function loadGit(url, save) {
var nodeModulesPath = path.join(process.cwd(), 'node_modules');
var oldModules = fs.readdirSync(nodeModulesPath);
var command = 'npm install ' + (save ? '--save' : '') + ' ' + url + ' ';
child_process.execSync(command, {
stdio: 'ignore',
});
var newModules = fs.readdirSync(nodeModulesPath);
var added = _.difference(oldModules, newModules)[0];
if(added) return originalRequire(added);
else return undefined;
}
exports = module.exports = loadGit;
| Make the implementation much more elegant | Make the implementation much more elegant
| JavaScript | mit | yamadapc/nrequire |
7fdc72722c0bd39d485382a0df199e933c87b9c0 | lib/index.js | lib/index.js | // Dependencies
var Typpy = require("typpy")
, NodeElm = require("./composition/node")
, Composition = require("./composition")
, Enny = require("enny")
;
function Parser(input, appService, moduleInfo, callback) {
// Add the instances
var comp = new Composition({
instances: input
, appService: appService
, moduleInfo: moduleInfo
})
comp.parseFlow();
comp.addConnections();
callback(null, comp);
}
module.exports = Parser;
| // Dependencies
var Typpy = require("typpy")
, NodeElm = require("./composition/node")
, Composition = require("./composition")
, Enny = require("enny")
;
function Parser(input, appService, moduleInfo, callback) {
// Add the instances
var comp = new Composition({
instances: input
, appService: appService
, moduleInfo: moduleInfo
})
comp.parseFlow();
comp.addConnections();
callback(null, comp);
}
if (typeof window === "object") {
window.EngineParser = Parser;
}
module.exports = Parser;
| Create a global when running in browser | Create a global when running in browser
| JavaScript | mit | jillix/engine-builder |
8290936c560abc56ee43635ff7c90b14ea3042d2 | lib/redis.js | lib/redis.js | 'use strict';
const async = require('async');
const redis = require('redis').createClient(6379, 'redis');
module.exports = redis;
module.exports.jenkinsChanged = function(nodes, cb) {
async.filter(nodes, function(node, cb) {
const key = `node:${node.displayName}`;
node.offline = !!(node.offline || node.temporarilyOffline) + 0;
redis.hget(key, 'offline', function(err, offline) {
if (err) { return cb(err); }
offline = parseInt(offline || 0, 10);
redis.hset(key, 'offline', node.offline, function(err) {
if (err) { return cb(err); }
cb(!!(node.offline ^ offline));
});
});
}, function(nodes) {
cb(null, nodes);
});
};
| 'use strict';
const async = require('async');
const redis = require('redis').createClient(6379, 'redis');
module.exports = redis;
module.exports.jenkinsChanged = function(nodes, cb) {
async.filter(nodes, function(node, cb) {
const key = `node:${node.name || node.displayName}`;
node.offline = !!(node.offline || node.temporarilyOffline) + 0;
redis.hget(key, 'offline', function(err, offline) {
if (err) { return cb(err); }
offline = parseInt(offline || 0, 10);
redis.hset(key, 'offline', node.offline, function(err) {
if (err) { return cb(err); }
cb(!!(node.offline ^ offline));
});
});
}, function(nodes) {
cb(null, nodes);
});
};
| Add support for alternative Jenkins node name | Add support for alternative Jenkins node name
| JavaScript | mit | Starefossen/jenkins-monitor |
fac6e93a0fe817fb3315f1f0806004c0e07cf64c | frontend/src/contexts/UiProvider.js | frontend/src/contexts/UiProvider.js | import React, { createContext, useState } from 'react';
import PropTypes from 'prop-types';
const UiContext = createContext({
uiDarkMode: false,
uiIsLoading: false,
uiIsAnimating: false,
});
const UiProvider = ({ children }) => {
const [uiDarkMode, setUiDarkMode] = useState(false);
const [uiIsLoading, setUiIsLoading] = useState(false);
const [uiIsAnimating, setUiIsAnimating] = useState(false);
return (
<UiContext.Provider
value={{
uiDarkMode,
setUiDarkMode,
uiIsLoading,
setUiIsLoading,
uiIsAnimating,
setUiIsAnimating,
}}
>
{children}
</UiContext.Provider>
);
};
UiProvider.propTypes = {
children: PropTypes.node,
};
export { UiContext, UiProvider };
| import React, { createContext, useState } from 'react';
import PropTypes from 'prop-types';
const UiContext = createContext({
uiDarkMode: true,
uiIsLoading: false,
uiIsAnimating: false,
});
const UiProvider = ({ children }) => {
const [uiDarkMode, setUiDarkMode] = useState(true);
const [uiIsLoading, setUiIsLoading] = useState(false);
const [uiIsAnimating, setUiIsAnimating] = useState(false);
return (
<UiContext.Provider
value={{
uiDarkMode,
setUiDarkMode,
uiIsLoading,
setUiIsLoading,
uiIsAnimating,
setUiIsAnimating,
}}
>
{children}
</UiContext.Provider>
);
};
UiProvider.propTypes = {
children: PropTypes.node,
};
export { UiContext, UiProvider };
| Enable 'dark mode' by default | :crescent_moon: Enable 'dark mode' by default
| JavaScript | mit | dreamyguy/gitinsight,dreamyguy/gitinsight,dreamyguy/gitinsight |
1b73b33858db20c9cfdc171a406d12c1bcfa590f | src/util/logger/serializers.js | src/util/logger/serializers.js | /**
* @param {import('discord.js').Guild} guild
*/
function guild (guild) {
return `${guild.id}, ${guild.name}`
}
/**
* @param {import('discord.js').TextChannel} channel
*/
function channel (channel) {
return `(${channel.guild.id}) ${channel.id}, ${channel.name}`
}
/**
* @param {import('discord.js').User} user
*/
function user (user) {
return `${user.id}, ${user.username}`
}
module.exports = {
guild,
channel,
user
}
| /**
* @param {import('discord.js').Guild} guild
*/
function guild (guild) {
return `${guild.id}, ${guild.name}`
}
/**
* @param {import('discord.js').TextChannel} channel
*/
function channel (channel) {
return `${channel.id}, ${channel.name}`
}
/**
* @param {import('discord.js').User} user
*/
function user (user) {
return `${user.id}, ${user.username}`
}
module.exports = {
guild,
channel,
user
}
| Remove dupe info in channel log serializer | Remove dupe info in channel log serializer
| JavaScript | mit | synzen/Discord.RSS,synzen/Discord.RSS |
fde26acaffdb416751ff17c391f3a411e8d9207b | 404/main.js | 404/main.js | // 404 page using mapbox to show cities around the world.
// Helper to generate the kind of coordinate pairs I'm using to store cities
function bounds() {
var center = map.getCenter();
return {lat: center.lat, lng: center.lng, zoom: map.getZoom()};
}
L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg";
var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false});
function go(city) {
var placenames = Object.keys(places);
city = city || placenames[Math.floor(Math.random() * placenames.length)];
var pos = places[city];
map.setView(
[pos.lat, pos.lng],
pos.zoom
);
}
go();
| // 404 page using mapbox to show cities around the world.
// Helper to generate the kind of coordinate pairs I'm using to store cities
function bounds() {
var center = map.getCenter();
return {lat: center.lat, lng: center.lng, zoom: map.getZoom()};
}
L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg";
var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false});
function go(city) {
var placenames = Object.keys(places);
city = city || placenames[Math.floor(Math.random() * placenames.length)];
var pos = places[city];
map.setView(
[pos.lat, pos.lng],
pos.zoom
);
}
if (places[window.location.search.substring(1)]) {
go(window.location.search.substring(1));
} else {
go();
}
| Allow direct linking to cities | Allow direct linking to cities
| JavaScript | mit | controversial/controversial.io,controversial/controversial.io,controversial/controversial.io |
4acee6d5936b15656ea280b24b98de6771849497 | src/js/utils/allowed-upload-file-extensions.js | src/js/utils/allowed-upload-file-extensions.js | 'use strict';
// APEP capital cases are also provided. Apple devices tend to provide uppercase file extensions and this conflicts with a known bug
// APEP See : https://github.com/Artear/ReactResumableJS/issues/20
var imageFileTypes = ["png", "PNG", "jpg", "JPG","JPEG","jpeg", "webp", "WEBP", "gif", "GIF", "svg", "SVG"];
var videoFileTypes = ["mov", "MOV", 'mp4', "MP4", "webm", "WEBM", "flv", "FLV", "wmv", "WMV", "avi", "AVI",
"ogg", "OGG", "ogv", "OGV", "qt", "QT", "asf", "ASF", "mpg", "MPG", "3gp", "3GP"];
var audioFileTypes = ["mp3", "MP3", "wav", "WAV"];
var allFileTypes = imageFileTypes.concat(videoFileTypes);
allFileTypes = allFileTypes.concat(audioFileTypes);
module.exports = {
IMAGE_FILE_TYPES: imageFileTypes,
VIDEO_FILE_TYPES: videoFileTypes,
AUDIO_FILE_TYPES: audioFileTypes,
ALL_FILE_TYPES: allFileTypes
};
| 'use strict';
// APEP capital cases are also provided. Apple devices tend to provide uppercase file extensions and this conflicts with a known bug
// APEP See : https://github.com/Artear/ReactResumableJS/issues/20
var imageFileTypes = ["png", "PNG", "jpg", "JPG","JPEG","jpeg", "webp", "WEBP", "gif", "GIF", "svg", "SVG"];
var videoFileTypes = ["mov", "MOV", 'mp4', "MP4", "webm", "WEBM", "flv", "FLV", "wmv", "WMV", "avi", "AVI",
"ogg", "OGG", "ogv", "OGV", "qt", "QT", "asf", "ASF", "mpg", "MPG", "3gp", "3GP"];
var audioFileTypes = ["mp3", "MP3", "wav", "WAV", "m4a", "M4A"];
var allFileTypes = imageFileTypes.concat(videoFileTypes);
allFileTypes = allFileTypes.concat(audioFileTypes);
module.exports = {
IMAGE_FILE_TYPES: imageFileTypes,
VIDEO_FILE_TYPES: videoFileTypes,
AUDIO_FILE_TYPES: audioFileTypes,
ALL_FILE_TYPES: allFileTypes
};
| Allow m4a audio files to be uploaded. | Allow m4a audio files to be uploaded.
Again, the resumable.js bug, where the capital file extensions are an issue, and require explicit declaration of file types.
| JavaScript | mit | UoSMediaFrameworks/uos-media-playback-framework-legacy,UoSMediaFrameworks/uos-media-playback-framework-legacy,UoSMediaFrameworks/uos-media-playback-framework-legacy |
def7c0fcb0c0c2adbd66d530d0634d6a6e53f0d7 | virun.js | virun.js | var virus = document.querySelector("div");
var x = 1;
var y = 0;
var vy = 0;
var ay = 0;
var vx = .1; // px per millisecond
var startTime = Date.now();
var clickTime;
timer = setInterval(function animate() {
var t = Date.now() - startTime;
x = vx * t;
y = vy * t + 400;
virus.style.left = x + "px";
virus.style.top = y + "px";
if ( x > document.body.clientWidth) {
startTime = Date.now();
}
if (ay >= .001) {
var t = Date.now() - clickTime;
vy = ay * t;
}
},20); // ms | 1000/20 = 50 frames per second (50 fps)
virus.addEventListener("click", function onclick(event) {
ay = .001;
clickTime = Date.now();
});
| var virus = document.querySelector("div");
var x = 1;
var y = 0;
var vy = 0;
var ay = 0;
var vx = .1; // px per millisecond
var startTime = Date.now();
var clickTime;
timer = setInterval(function animate() {
var t = Date.now() - startTime;
x = vx * t;
y = vy * t + 400;
virus.style.left = x + "px";
virus.style.top = y + "px";
if ( x > document.body.clientWidth) {
startTime = Date.now();
}
if (ay >= .001) {
var t = Date.now() - clickTime;
vy = ay * t;
}
//if ( y > document.body.clientHeight && x > document.body.clientWidth) {
// console.log("hello");
// startTime = Date.now();
//}
if (y > screen.height){
console.log("hello");
startTime = Date.now();
vy = 0;
ay = 0;
}
//if ( y > document.body.clientHeight && x > document.body.clientWidth) {
// console.log("second if");
// vy = 0;
// ay = 0;
//}
},20); // ms | 1000/20 = 50 frames per second (50 fps)
virus.addEventListener("click", function onclick(event) {
ay = .001;
clickTime = Date.now();
});
| Add property screen.height, so that the ufo, once it is shot and falls, returns to start position and flies the same horizontal line like in the beginning | Add property screen.height, so that the ufo, once it is shot and falls, returns to start position and flies the same horizontal line like in the beginning
| JavaScript | mit | BOZ2323/virun,BOZ2323/virun |
d0f07c2bdcf3b282555ab86c47c19e953b3f9715 | test/client/tab_broker_test.js | test/client/tab_broker_test.js | var Q = require('q');
var tabBroker = require('../../src/js/client/tab_broker');
exports.query = {
setUp: function(cb) {
var chrome = {
runtime: {
sendMessage: function(opts, callback) {
callback({tabs: [{id: 2}, {id: 1}, {id: 3}], lastActive: 2});
}
}
};
this.api = tabBroker(chrome);
cb();
},
getsTabsInOrderFromServer: function(test) {
this.api.query('', false)
.then(function(tabs) {
test.deepEqual(tabs, [{id: 2}, {id: 1}, {id: 3}]);
test.done();
});
}
};
exports.switchTo = {
setUp: function(cb) {
var chrome = this.chrome = {
runtime: {
sendMessage: function(opts) {
if (!chrome.runtime.sendMessage.calls) chrome.runtime.sendMessage.calls = [];
chrome.runtime.sendMessage.calls.push(opts)
}
}
};
this.api = tabBroker(this.chrome);
cb();
},
sendsMessageToChangeTabs: function(test) {
this.api.switchTo({id: 123});
test.deepEqual(this.chrome.runtime.sendMessage.calls[0], {switchToTabId: 123});
test.done();
}
};
| var Q = require('q');
var tabBroker = require('../../src/js/client/tab_broker');
exports.query = {
setUp: function(cb) {
var chrome = {
runtime: {
sendMessage: function(opts, callback) {
callback({tabs: [{id: 1}, {id: 2}, {id: 3}], lastActive: 2});
}
}
};
this.api = tabBroker(chrome);
cb();
},
getsTabsInOrderFromServer: function(test) {
this.api.query('', false)
.then(function(tabs) {
test.deepEqual(tabs, [{id: 2}, {id: 1}, {id: 3}]);
test.done();
});
}
};
exports.switchTo = {
setUp: function(cb) {
var chrome = this.chrome = {
runtime: {
sendMessage: function(opts) {
if (!chrome.runtime.sendMessage.calls) chrome.runtime.sendMessage.calls = [];
chrome.runtime.sendMessage.calls.push(opts)
}
}
};
this.api = tabBroker(this.chrome);
cb();
},
sendsMessageToChangeTabs: function(test) {
this.api.switchTo({id: 123});
test.deepEqual(this.chrome.runtime.sendMessage.calls[0], {switchToTabId: 123});
test.done();
}
};
| Change tabBroker test to test ordering | Change tabBroker test to test ordering
| JavaScript | mit | findjashua/chrome-fast-tab-switcher,eanplatter/chrome-fast-tab-switcher,eanplatter/chrome-fast-tab-switcher,BinaryMuse/chrome-fast-tab-switcher,modulexcite/chrome-fast-tab-switcher,alubling/chrome-fast-tab-switcher,BinaryMuse/chrome-fast-tab-switcher,billychan/chrome-fast-tab-switcher,eanplatter/chrome-fast-tab-switcher,findjashua/chrome-fast-tab-switcher,BinaryMuse/chrome-fast-tab-switcher,billychan/chrome-fast-tab-switcher,modulexcite/chrome-fast-tab-switcher,alubling/chrome-fast-tab-switcher,alubling/chrome-fast-tab-switcher,billychan/chrome-fast-tab-switcher,findjashua/chrome-fast-tab-switcher,modulexcite/chrome-fast-tab-switcher |
b834bacb099306bac030b37477fbee0b4a3324de | Gulpfile.js | Gulpfile.js | var gulp = require("gulp"),
util = require("gulp-util"),
minifyHtml = require("gulp-minify-html"),
less = require("gulp-less"),
minifyCss = require("gulp-minify-css"),
minifyJs = require("gulp-uglify");
gulp.task("html", function() {
util.log("Minifying...");
gulp.src("src/html/*.html")
.pipe(minifyHtml({}))
.pipe(gulp.dest("public/"));
util.log("Done!");
});
gulp.task("less", function() {
util.log("Compiling and minifying...");
gulp.src("src/less/*.less")
.pipe(less())
.pipe(minifyCss({cache: false}))
.pipe(gulp.dest("public/css/"));
util.log("Done!");
});
gulp.task("js", function() {
util.log("Minifying...");
gulp.src("src/js/*.js")
.pipe(minifyJs({mangle: false}))
.pipe(gulp.dest("public/js/"));
util.log("Done!");
});
gulp.task("watch", function() {
gulp.watch("src/html/*.html", ["html"]);
gulp.watch("src/less/**/*.less", ["less"]);
gulp.watch("src/js/*.js", ["js"]);
});
gulp.task("default", ["html", "less", "js", "watch"], function() {
util.log("Done!");
});
| var gulp = require("gulp"),
util = require("gulp-util"),
minifyHtml = require("gulp-minify-html"),
less = require("gulp-less"),
minifyCss = require("gulp-minify-css"),
minifyJs = require("gulp-uglify");
gulp.task("html", function() {
util.log("Minifying...");
gulp.src("src/html/*.html")
.pipe(minifyHtml({}))
.pipe(gulp.dest("public/"));
util.log("Done!");
});
gulp.task("less", function() {
util.log("Compiling and minifying...");
gulp.src("src/less/*.less")
.pipe(less())
.pipe(minifyCss({cache: false}))
.pipe(gulp.dest("public/css/"));
util.log("Done!");
});
gulp.task("js", function() {
util.log("Minifying...");
gulp.src("src/js/*.js")
.pipe(minifyJs({mangle: false, compress: false}))
.pipe(gulp.dest("public/js/"));
util.log("Done!");
});
gulp.task("watch", function() {
gulp.watch("src/html/*.html", ["html"]);
gulp.watch("src/less/**/*.less", ["less"]);
gulp.watch("src/js/*.js", ["js"]);
});
gulp.task("default", ["html", "less", "js", "watch"], function() {
util.log("Done!");
});
| Add compress: false for proper results. | Add compress: false for proper results.
| JavaScript | mit | bound1ess/todo-app,bound1ess/todo-app,bound1ess/todo-app |
1d8cc9075091f1fe31e4d1d3a47a61abaefcd6f5 | lib/services/apimanagement/lib/models/requestReportCollection.js | lib/services/apimanagement/lib/models/requestReportCollection.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Paged Report records list representation.
*/
class RequestReportCollection extends Array {
/**
* Create a RequestReportCollection.
* @member {number} [count] Total record count number across all pages.
*/
constructor() {
super();
}
/**
* Defines the metadata of RequestReportCollection
*
* @returns {object} metadata of RequestReportCollection
*
*/
mapper() {
return {
required: false,
serializedName: 'RequestReportCollection',
type: {
name: 'Composite',
className: 'RequestReportCollection',
modelProperties: {
value: {
required: false,
serializedName: '',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'RequestReportRecordContractElementType',
type: {
name: 'Composite',
className: 'RequestReportRecordContract'
}
}
}
}
count: {
required: false,
serializedName: 'count',
type: {
name: 'Number'
}
}
}
}
};
}
}
module.exports = RequestReportCollection;
| /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Paged Report records list representation.
*/
class RequestReportCollection extends Array {
/**
* Create a RequestReportCollection.
* @member {number} [count] Total record count number across all pages.
*/
constructor() {
super();
}
/**
* Defines the metadata of RequestReportCollection
*
* @returns {object} metadata of RequestReportCollection
*
*/
mapper() {
return {
required: false,
serializedName: 'RequestReportCollection',
type: {
name: 'Composite',
className: 'RequestReportCollection',
modelProperties: {
value: {
required: false,
serializedName: '',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'RequestReportRecordContractElementType',
type: {
name: 'Composite',
className: 'RequestReportRecordContract'
}
}
}
},
count: {
required: false,
serializedName: 'count',
type: {
name: 'Number'
}
}
}
}
};
}
}
module.exports = RequestReportCollection;
| Add missing comma in apimanagement mapper | Add missing comma in apimanagement mapper
| JavaScript | mit | xingwu1/azure-sdk-for-node,xingwu1/azure-sdk-for-node,Azure/azure-sdk-for-node,xingwu1/azure-sdk-for-node,Azure/azure-sdk-for-node,Azure/azure-sdk-for-node |
a7cde01856ed053477d1edf907f4236ae2dbb23e | trex/static/js/controllers.js | trex/static/js/controllers.js | var trexControllers = angular.module('trexControllers', []);
trexControllers.controller('ProjectListCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get('/api/1/projects/').success(function(data) {
$scope.projects = data;
});
$scope.order = "name";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
trexControllers.controller('ProjectDetailCtrl',
['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$http.get('/api/1/projects/' + $routeParams.id).success(function(data) {
$scope.project = data;
});
$http.get('/api/1/projects/' + $routeParams.id + "/entries").success(
function(data) {
$scope.entries = data;
});
$scope.order = "name";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
| var trexControllers = angular.module('trexControllers', []);
trexControllers.controller('ProjectListCtrl', ['$scope', 'Project',
function($scope, Project) {
$scope.projects = Project.query();
$scope.order = "name";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
trexControllers.controller('ProjectDetailCtrl',
['$scope', '$routeParams', 'Project',
function($scope, $routeParams, Project) {
$scope.project = Project.get({projectId: $routeParams.id});
$scope.entries = Project.entries({projectId: $routeParams.id});
// $http.get('/api/1/projects/' + $routeParams.id + "/entries").success(
// function(data) {
// });
$scope.order = "id";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
| Use new services for retreiving the Project and Entry | Use new services for retreiving the Project and Entry
| JavaScript | mit | bjoernricks/trex,bjoernricks/trex |
dd950e957c2acc4b12160c0d64721506cab0348f | Gulpfile.js | Gulpfile.js | var gulp = require('gulp'),
$ = require('gulp-load-plugins')();
gulp.task('styles', function() {
gulp.src('app/**/*.scss')
.pipe($.watch(function(files) {
files.pipe($.sass())
.pipe($.autoprefixer())
.pipe($.minifyCss())
.pipe(gulp.dest('./dist'))
.pipe($.livereload());
}));
});
gulp.task('copy', function() {
gulp.src('app/**/*.html')
.pipe($.watch())
.pipe($.embedlr())
.pipe(gulp.dest('./dist'))
});
gulp.task('serve', $.serve({
root: ['dist', 'app'],
port: 9000
}));
gulp.task('default', ['styles', 'copy', 'serve']);
| var gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
browserSync = require('browser-sync'),
reload = browserSync.reload,
config = {
// destinations
tmp: '.tmp',
app: 'app',
dist: 'dist',
// globs
sass: 'app/**/*.scss',
};
gulp.task('copy', function() {
gulp.src('app/**/*.html')
.pipe($.watch())
.pipe(gulp.dest('./dist'))
});
gulp.task('sass', function() {
return gulp.src(config.sass)
.pipe($.plumber())
.pipe($.sass())
.pipe($.autoprefixer())
/*.pipe($.minifyCss())*/
.pipe(gulp.dest(config.tmp))
.pipe(reload({stream: true}));
});
gulp.task('browser-sync', function() {
return browserSync({
server: {
baseDir: [config.tmp, config.app]
}
})
});
gulp.task('watch', function() {
$.watch({glob: config.sass, name: 'Sass'}, ['sass']);
});
gulp.task('default', ['sass', 'copy', 'watch', 'browser-sync']);
| Update intensely to be much better. | Update intensely to be much better.
| JavaScript | mit | SevereOverfl0w/generator-buymilk |
3411cef46121ed8f27468275a6149ee1a55fd717 | SmartyFace.js | SmartyFace.js | // ==UserScript==
// @name SmartyFace
// @description Text Prediction on facepunch
// @author benjojo
// @namespace http://facepunch.com
// @include http://facepunch.com/*
// @include http://www.facepunch.com/*
// @include https://facepunch.com/*
// @include https://www.facepunch.com/*
// @version 1
// ==/UserScript==
var endPoint = "http://text.nsa.me.uk/pose";
function findTextBoxes (argument) {
var boxes = $('textarea');
var parent = boxes[2].parentNode;
$(parent).prepend("<i id=\"SmartyFace\" style=\"pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\">This is a test wow. such test</i>");
var textarea = boxes[2];
$(boxes[2]).keypress(function(a) {
var text = $(textarea).val();
$.post( endPoint, { post: text })
.done(function( data ) {
$('#SmartyFace').html($(textarea).val()+data);
});
// $('#SmartyFace').html($(textarea).val());
});
}
findTextBoxes(); | // ==UserScript==
// @name SmartyFace
// @description Text Prediction on facepunch
// @author benjojo
// @namespace http://facepunch.com
// @include http://facepunch.com/*
// @include http://www.facepunch.com/*
// @include https://facepunch.com/*
// @include https://www.facepunch.com/*
// @version 1
// ==/UserScript==
var endPoint = "http://text.nsa.me.uk/pose";
function findTextBoxes (argument) {
var boxes = $('textarea');
var parent = boxes[2].parentNode;
$(parent).prepend("<i id=\"SmartyFace\" style=\"pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\">Type Reply Here</i>");
var textarea = boxes[2];
$(boxes[2]).keypress(function(a) {
var text = $(textarea).val();
$.post( endPoint, { post: text })
.done(function( data ) {
$('#SmartyFace').html($(textarea).val()+data);
});
// $('#SmartyFace').html($(textarea).val());
});
}
findTextBoxes(); | Make the starting text more sane | Make the starting text more sane
| JavaScript | mit | benjojo/SmartyFace |
f98f6b4660110f1421eae1f484d9242b62b0697d | src/swagger/add-model.js | src/swagger/add-model.js | 'use strict';
var _ = require('lodash');
var swagger = require('swagger-spec-express');
var schemaKeys = Object.keys(require('swagger-spec-express/lib/schemas/schema.json').properties);
schemaKeys.push('definitions');
module.exports = function addModel(schema) {
var modelSchema = _.cloneDeep(_.pick(schema, schemaKeys));
stripSpecificProperties(modelSchema);
swagger.common.addModel(modelSchema, {validation: 'warn'});
};
const propertiesToStrip = ['faker', 'chance'];
function stripSpecificProperties(schema) {
if (_.isArray(schema)) {
schema.forEach(function (item) {
stripSpecificProperties(item);
});
return;
}
if (!_.isObject(schema)) {
return;
}
propertiesToStrip.forEach(function (key) {
delete schema[key];
});
_.valuesIn(schema).forEach(stripSpecificProperties);
} | 'use strict';
var _ = require('lodash');
var swagger = require('swagger-spec-express');
var schemaKeys = Object.keys(require('swagger-spec-express/lib/schemas/schema.json').properties);
schemaKeys.push('definitions');
module.exports = function addModel(schema) {
var modelSchema = _.cloneDeep(_.pick(schema, schemaKeys));
filterProperties(modelSchema.properties);
if (modelSchema.definitions) {
Object.keys(modelSchema.definitions).forEach(function (definitionName) {
var definitionValue = modelSchema.definitions[definitionName];
filterProperties(definitionValue.properties);
});
}
swagger.common.addModel(modelSchema, {validation: 'warn'});
};
function filterProperties(properties) {
Object.keys(properties).forEach(function (propertyName) {
var propertyValue = properties[propertyName];
Object.keys(propertyValue).forEach(function (key) {
if (schemaKeys.indexOf(key) < 0) {
delete propertyValue[key];
}
if (key.toLowerCase() === 'properties') {
filterProperties(propertyValue.properties);
}
});
});
} | Fix for stripping properties before adding to swagger. | Fix for stripping properties before adding to swagger.
| JavaScript | mit | eXigentCoder/node-api-seed,eXigentCoder/node-api-seed |
e1cfb2e2b4cc186c7d23c47e9d759d54b7571c80 | src/renderers/canvas/sigma.canvas.nodes.def.js | src/renderers/canvas/sigma.canvas.nodes.def.js | ;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.nodes');
/**
* The default node renderer. It renders the node as a simple disc.
*
* @param {object} node The node object.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.nodes.def = function(node, context, settings) {
var prefix = settings('prefix') || '';
context.fillStyle = node.color || settings('defaultNodeColor');
context.globalAlpha = node.alpha || settings('defaultNodeAlpha') || 1;
context.beginPath();
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'],
0,
Math.PI * 2,
true
);
context.closePath();
context.fill();
};
})();
| ;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.nodes');
/**
* The default node renderer. It renders the node as a simple disc.
*
* @param {object} node The node object.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.nodes.def = function(node, context, settings) {
var prefix = settings('prefix') || '';
context.fillStyle = node.color || settings('defaultNodeColor');
context.globalAlpha = node.alpha || settings('defaultNodeAlpha') || 1;
context.beginPath();
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'],
0,
Math.PI * 2,
true
);
context.closePath();
context.fill();
if (node.hasBorder) {
context.beginPath();
context.strokeStyle = settings('nodeBorderColor') === 'node' ?
(node.color || settings('defaultNodeColor')) :
settings('defaultNodeBorderColor');
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'] + settings('borderSize'),
0,
Math.PI * 2,
true
);
context.closePath();
context.stroke();
}
};
})();
| Add suport for node borders using hasBorder property | Add suport for node borders using hasBorder property
| JavaScript | mit | wesako/sigma.js,wesako/sigma.js |
811b7afd2dd29d36a3fd610ba55a6388ef8e2a47 | lib/assets/javascripts/cartodb3/components/modals/add-analysis/create-analysis-options-models.js | lib/assets/javascripts/cartodb3/components/modals/add-analysis/create-analysis-options-models.js | var AddAnalysisOptionModel = require('./add-analysis-option-model');
module.exports = function (analysisDefinitionNodeModel) {
var models = [];
var areaOfInfluence = _t('components.modals.add-analysis.options.sub-titles.area-of-influence');
// Buffer
models.push(
new AddAnalysisOptionModel({
title: _t('components.modals.add-analysis.options.buffer.title'),
desc: _t('components.modals.add-analysis.options.buffer.desc'),
sub_title: areaOfInfluence,
node_attrs: {
type: 'buffer',
source_id: analysisDefinitionNodeModel.id,
radio: 123
}
})
);
// Trade-area
models.push(
new AddAnalysisOptionModel({
title: _t('components.modals.add-analysis.options.trade-area.title'),
desc: _t('components.modals.add-analysis.options.trade-area.desc'),
sub_title: areaOfInfluence,
node_attrs: {
type: 'trade-area',
source_id: analysisDefinitionNodeModel.id,
kind: 'drive',
time: 300
}
})
);
return models;
};
| var AddAnalysisOptionModel = require('./add-analysis-option-model');
module.exports = function (analysisDefinitionNodeModel) {
var models = [];
var areaOfInfluence = _t('components.modals.add-analysis.options.sub-titles.area-of-influence');
// Buffer
models.push(
new AddAnalysisOptionModel({
title: _t('components.modals.add-analysis.options.buffer.title'),
desc: _t('components.modals.add-analysis.options.buffer.desc'),
sub_title: areaOfInfluence,
node_attrs: {
type: 'buffer',
source_id: analysisDefinitionNodeModel.id,
radio: 300
}
})
);
// Trade-area
models.push(
new AddAnalysisOptionModel({
title: _t('components.modals.add-analysis.options.trade-area.title'),
desc: _t('components.modals.add-analysis.options.trade-area.desc'),
sub_title: areaOfInfluence,
node_attrs: {
type: 'trade-area',
source_id: analysisDefinitionNodeModel.id,
kind: 'drive',
time: 300
}
})
);
return models;
};
| Make the buffer radio be big enough to change points visually | Make the buffer radio be big enough to change points visually
| JavaScript | bsd-3-clause | CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,CartoDB/cartodb,codeandtheory/cartodb,CartoDB/cartodb,codeandtheory/cartodb,splashblot/dronedb,splashblot/dronedb,splashblot/dronedb,CartoDB/cartodb,codeandtheory/cartodb,splashblot/dronedb,codeandtheory/cartodb,codeandtheory/cartodb |
d6f02fe1f7229548de0abf09549786cc9302a315 | createDatabase.js | createDatabase.js | var seq = require('seq');
var args = require('yargs').argv;
var Factory = require('./lib/database/Factory');
var config = require('./lib/configuration');
var fileName = args.filename || null;
var dbOptions = config.database;
if (fileName) {
dbOptions.options.filename = fileName;
}
Factory.create(dbOptions, function(error, db) {
if (error) return console.log(error.message);
seq()
.par(function() {
db.query('create table users (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, createDate datetime default current_timestamp)', [], this);
})
.par(function() {
db.query('create table transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER, createDate datetime default current_timestamp, value REAL)', [], this);
})
.seq(function() {
console.log('database ' + dbOptions.options.filename + ' created');
});
});
| var seq = require('seq');
var args = require('yargs').argv;
var Factory = require('./lib/database/Factory');
var config = require('./lib/configuration');
var fileName = args.filename || null;
var dbOptions = config.database;
if (fileName) {
dbOptions.options.filename = fileName;
}
Factory.create(dbOptions, function(error, db) {
if (error) return console.log(error.message);
seq()
.par(function() {
db.query('CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, createDate DATETIME DEFAULT current_timestamp)', [], this);
})
.par(function() {
db.query('CREATE TABLE transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER, createDate DATETIME DEFAULT current_timestamp, value REAL)', [], this);
})
.seq(function() {
db.query('CREATE INDEX userId ON transactions(userId)', [], this);
})
.seq(function() {
console.log('database ' + dbOptions.options.filename + ' created');
});
});
| Add index on userid to transaction database | Add index on userid to transaction database
| JavaScript | mit | hackerspace-bootstrap/strichliste |
9e43aeae0f6ea5333fb41444a7722f5afbd12691 | src/start/WelcomeScreen.js | src/start/WelcomeScreen.js | /* @flow */
import React, { PureComponent } from 'react';
import { View, StyleSheet } from 'react-native';
import connectWithActions from '../connectWithActions';
import type { Actions } from '../types';
import { Screen, ZulipButton } from '../common';
const componentStyles = StyleSheet.create({
divider: {
height: 20,
},
});
type Props = {
actions: Actions,
};
class WelcomeScreen extends PureComponent<Props> {
props: Props;
render() {
const { actions } = this.props;
return (
<Screen title="Welcome!" centerContent padding>
<ZulipButton
text="I have a Zulip account"
onPress={() => actions.navigateToAddNewAccount('')}
/>
<View style={componentStyles.divider} />
<ZulipButton text="I am new to Zulip" onPress={() => actions.navigateToWelcomeHelp()} />
</Screen>
);
}
}
export default connectWithActions()(WelcomeScreen);
| /* @flow */
import React, { PureComponent } from 'react';
import connectWithActions from '../connectWithActions';
import type { Actions } from '../types';
import { Screen, ViewPlaceholder, ZulipButton } from '../common';
type Props = {
actions: Actions,
};
class WelcomeScreen extends PureComponent<Props> {
props: Props;
render() {
const { actions } = this.props;
return (
<Screen title="Welcome!" centerContent padding>
<ZulipButton
text="I have a Zulip account"
onPress={() => actions.navigateToAddNewAccount('')}
/>
<ViewPlaceholder height={20} />
<ZulipButton text="I am new to Zulip" onPress={() => actions.navigateToWelcomeHelp()} />
</Screen>
);
}
}
export default connectWithActions()(WelcomeScreen);
| Use ViewPlaceholder instead of custom code | ui: Use ViewPlaceholder instead of custom code
Instead of using a custom View with custom styles use the
ViewPlaceholder component.
| JavaScript | apache-2.0 | vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile |
e5afbc0d575605db7c52326e1acb1e0af3186f87 | application/layout/app-header.js | application/layout/app-header.js | //Needed components
var Header = require('../header').component;
var Cartridge = require('../cartridge').component;
var ContentBar = require('../content-bar').component;
var Bar = require('../bar').component;
var ContentActions = require('../content-actions').component;
var applicationStore = require('focus').application.builtInStore();
module.exports = React.createClass({
displayName: 'AppHeader',
/** @inheriteddoc */
getInitialState: function getCartridgeInitialState() {
return this._getStateFromStore();
},
/** @inheriteddoc */
componentWillMount: function cartridgeWillMount() {
applicationStore.addModeChangeListener(this._handleModeChange);
},
/** @inheriteddoc */
componentWillUnMount: function cartridgeWillUnMount(){
applicationStore.removeModeChangeListener(this._handleModeChange);
},
_handleModeChange: function(){
this.setState(this._getStateFromStore());
},
_getStateFromStore: function getCartridgeStateFromStore(){
var processMode = applicationStore.getMode();
var mode = 'consult';
if(processMode && processMode.edit && processMode.edit > 0){
mode = 'edit';
}
return {mode: mode};
},
render: function renderApplicationHeader() {
return (
<Header data-focus-mode={this.state.mode}>
<ContentBar>
<Bar appName='FOCUS'/>
<Cartridge />
</ContentBar>
<ContentActions />
</Header>
);
}
});
| //Needed components
var Header = require('../header').component;
var Cartridge = require('../cartridge').component;
var ContentBar = require('../content-bar').component;
var Bar = require('../bar').component;
var ContentActions = require('../content-actions').component;
module.exports = React.createClass({
displayName: 'AppHeader',
render: function renderApplicationHeader() {
return (
<Header>
<ContentBar>
<Bar appName='FOCUS'/>
<Cartridge />
</ContentBar>
<ContentActions />
</Header>
);
}
});
| Remove the application mode and route | [layout] Remove the application mode and route
| JavaScript | mit | JRLK/focus-components,Bernardstanislas/focus-components,Jerom138/focus-components,asimsir/focus-components,Bernardstanislas/focus-components,get-focus/focus-components,sebez/focus-components,sebez/focus-components,JRLK/focus-components,KleeGroup/focus-components,Bernardstanislas/focus-components,anisgh/focus-components,JRLK/focus-components,Ephrame/focus-components,anisgh/focus-components,asimsir/focus-components,KleeGroup/focus-components,JabX/focus-components,JabX/focus-components,Jerom138/focus-components,Ephrame/focus-components,anisgh/focus-components,Ephrame/focus-components,Jerom138/focus-components |
04e12c573399f08472307d2654a46360dc365986 | my-frontend/app/routes/application.js | my-frontend/app/routes/application.js | import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(
ApplicationRouteMixin, {
beforeModel: function () {
return this.csrf.fetchToken();
}
});
| import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(
ApplicationRouteMixin, {
beforeModel: function () {
this._super.apply(this, arguments);
return this.csrf.fetchToken();
}
});
| Call super in beforeModel hook | Call super in beforeModel hook
Use super to call the application routes beforeModel hook so the
ApplicationRouteMixin works.
| JavaScript | unlicense | givanse/ember-cli-simple-auth-devise,bryanwongbh/ember-cli-simple-auth-devise,garth0323/therapy,givanse/ember-cli-simple-auth-devise,garth0323/therapy,givanse/ember-cli-simple-auth-devise,bryanwongbh/ember-cli-simple-auth-devise |
e503dea58f44ac41fd18cbeaa634c6b373bb5b8d | scripts/build.js | scripts/build.js | const buildBaseCss = require(`./build/base-css.js`);
const buildBaseHtml = require(`./build/base-html.js`);
const buildPackageCss = require(`./build/package-css.js`);
const buildPackageHtml = require(`./build/package-html.js`);
const getDirectories = require(`./lib/get-directories.js`);
const packages = getDirectories(`avalanche/packages`);
const data = {
css: `<link rel="stylesheet" href="/base/css/global.css">`
};
buildBaseHtml(data);
buildBaseCss();
packages.forEach((packageName) => {
data.title = packageName;
data.css = [
`<link rel="stylesheet" href="/base/css/global.css">`,
`<link rel="stylesheet" href="/packages/${packageName}/css/index.css">`
].join(`\n`);
buildPackageHtml(packageName, data);
buildPackageCss(packageName);
});
| const buildBaseCss = require(`./build/base-css.js`);
const buildBaseHtml = require(`./build/base-html.js`);
const buildPackageCss = require(`./build/package-css.js`);
const buildPackageHtml = require(`./build/package-html.js`);
const getDirectories = require(`./lib/get-directories.js`);
const packages = getDirectories(`avalanche/packages`);
const defaultData = {
css: `<link rel="stylesheet" href="/base/css/global.css">`
};
buildBaseHtml(defaultData);
buildBaseCss();
packages.forEach((packageName) => {
const packageData = JSON.parse(JSON.stringify(defaultData));
packageData.title = packageName;
packageData.css = [
`<link rel="stylesheet" href="/base/css/global.css">`,
`<link rel="stylesheet" href="/packages/${packageName}/css/index.css">`
].join(`\n`);
buildPackageHtml(packageName, packageData);
buildPackageCss(packageName);
});
| Clone the default page data for every package to prevent problems with async tasks | Clone the default page data for every package to prevent problems with async tasks
| JavaScript | mit | avalanchesass/avalanche-website,avalanchesass/avalanche-website |
14f18e750480aeac369015f9e9fc25d475689b31 | server/routes.js | server/routes.js | function calcWidth(name) {
return 225 + name.length * 6.305555555555555;
}
WebApp.connectHandlers.use("/package", function(request, response) {
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
var opts = {headers: {'Accept': 'application/json'}};
HTTP.get(url, opts, function(err, res) {
var name = '', version, pubDate, starCount, installYear;
var pl = res.data[0];
if (res.data.length !== 0) {
name = pl.name;
version = pl.latestVersion.version;
pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY');
starCount = pl.starCount || 0;
installYear = pl['installs-per-year'] || 0;
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = calcWidth(name);
var icon = SSR.render('icon', {w: width, totalW: width+2, n: name,
v: version, p: pubDate, s: starCount, i: installYear});
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
});
| WebApp.connectHandlers.use("/package", function(request, response) {
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
var opts = {headers: {'Accept': 'application/json'}};
HTTP.get(url, opts, function(err, res) {
var name = '', version, pubDate, starCount, installYear;
var pl = res.data[0];
if (res.data.length !== 0) {
name = pl.name;
version = pl.latestVersion.version;
pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY');
starCount = pl.starCount || 0;
installYear = pl['installs-per-year'] || 0;
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = 225 + name.length * 6.305555555555555;
var icon = SSR.render('icon', {w: width, totalW: width+2, n: name,
v: version, p: pubDate, s: starCount, i: installYear});
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
});
| Delete a function to save LOC | Delete a function to save LOC
| JavaScript | mit | sungwoncho/meteor-icon,sungwoncho/meteor-icon |
a8ece3a1f14c850d3eb79c0bb16532a419b91749 | server/server.js | server/server.js | var express = require('express');
var mongoose = require('mongoose');
var app = express();
// connect to mongo database named "bolt"
// uncomment this line to use a local database
// mongoose.connect('mongodb://localhost/bolt');
mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp');
require('./config/middleware.js')(app, express);
require('./config/routes.js')(app, express);
// start listening to requests on port 8000
var port = Number(process.env.PORT || 8000);
app.listen(port, function () {
console.log(`server listening on port ${port}`);
});
// export our app for testing and flexibility, required by index.js
module.exports = app;
//test
| var express = require('express');
var mongoose = require('mongoose');
var app = express();
// connect to mongo database named "bolt"
// uncomment this line to use a local database
// be sure to re-comment this line when submitting PR
// mongoose.connect('mongodb://localhost/bolt');
mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp');
require('./config/middleware.js')(app, express);
require('./config/routes.js')(app, express);
// start listening to requests on port 8000
var port = Number(process.env.PORT || 8000);
app.listen(port, function () {
console.log(`server listening on port ${port}`);
});
// export our app for testing and flexibility, required by index.js
module.exports = app;
//test
| Add reccomendation comment to make sure local DB testing changes dont get pulled | Add reccomendation comment to make sure local DB testing changes dont get pulled
| JavaScript | mit | gm758/Bolt,boisterousSplash/Bolt,thomasRhoffmann/Bolt,elliotaplant/Bolt,elliotaplant/Bolt,boisterousSplash/Bolt,thomasRhoffmann/Bolt,gm758/Bolt |
ccf9a08b7ead4552ad22d5a5e07980f1bee3723f | routes/screenshot.js | routes/screenshot.js | const express = require('express');
const router = express.Router();
const puppeteer = require('puppeteer');
router.get('/', function (req, res, next) {
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
const emulation = req.query.emulation || 'mobile';
const defaultWidth = emulation === 'mobile' ? 412 : 1350;
const defaultHeight = emulation === 'mobile' ? 732 : 940;
page.setViewport({
width: req.query.width ? parseInt(req.query.width, 10) : defaultWidth,
height: req.query.heigh ? parseInt(req.query.height, 10) : defaultHeight
});
await page.goto(req.query.url, {timeout: 60000});
const shot = await page.screenshot({});
await browser.close();
res.setHeader('Content-Type', 'image/png');
res.status(200).send(shot);
}).catch(e => {
console.error(e);
res.status(500).send({error: 'Could not take screenshot'});
});
});
module.exports = router;
| const express = require('express');
const router = express.Router();
const puppeteer = require('puppeteer');
router.get('/', function (req, res, next) {
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
const emulation = req.query.emulation || 'mobile';
const defaultWidth = emulation === 'mobile' ? 412 : 1280;
const defaultHeight = emulation === 'mobile' ? 732 : 960;
page.setViewport({
width: req.query.width ? parseInt(req.query.width, 10) : defaultWidth,
height: req.query.heigh ? parseInt(req.query.height, 10) : defaultHeight
});
await page.goto(req.query.url, {timeout: 60000});
const shot = await page.screenshot({});
await browser.close();
res.setHeader('Content-Type', 'image/png');
res.status(200).send(shot);
}).catch(e => {
console.error(e);
res.status(500).send({error: 'Could not take screenshot'});
});
});
module.exports = router;
| Change desktop resolution to 1280x960 | Change desktop resolution to 1280x960 | JavaScript | apache-2.0 | frocher/bnb_probe |
72f17e16ab10d8dce678f8eacf1425d4ca8c9733 | lib/generate.js | lib/generate.js | var fs = require('fs');
var archiver = require('./archiver');
var createServiceFile = require('./service');
var createSpecFile = require('./spec');
var files = require('./files');
function generateServiceFile(root, pkg) {
var serviceFileContents = createServiceFile(pkg);
var serviceFilePath = files.serviceFile(root, pkg);
fs.writeFileSync(serviceFilePath, serviceFileContents);
}
function generateSpecFile(root, pkg, release) {
var specFileContents = createSpecFile(pkg, release);
var specFilePath = files.specFile(root, pkg);
fs.writeFileSync(specFilePath, specFileContents);
}
function addCustomFieldsToPackage(pkg, customName) {
if (customName) {
return Object.assign({}, pkg, { name: customName });
}
return pkg;
}
module.exports = function (root, pkg, release, customName, cb) {
var customPackage = addCustomFieldsToPackage(pkg, customName);
var specsDirectory = files.specsDirectory(root);
var sourcesDirectory = files.sourcesDirectory(root);
var sourcesArchive = files.sourcesArchive(root, customPackage);
fs.mkdirSync(specsDirectory);
fs.mkdirSync(sourcesDirectory);
generateServiceFile(root, customPackage);
generateSpecFile(specsDirectory, customPackage, release);
archiver.compress(root, sourcesArchive, cb);
};
| var _ = require('lodash');
var fs = require('fs');
var archiver = require('./archiver');
var createServiceFile = require('./service');
var createSpecFile = require('./spec');
var files = require('./files');
function generateServiceFile(root, pkg) {
var serviceFileContents = createServiceFile(pkg);
var serviceFilePath = files.serviceFile(root, pkg);
fs.writeFileSync(serviceFilePath, serviceFileContents);
}
function generateSpecFile(root, pkg, release) {
var specFileContents = createSpecFile(pkg, release);
var specFilePath = files.specFile(root, pkg);
fs.writeFileSync(specFilePath, specFileContents);
}
function addCustomFieldsToPackage(pkg, customName) {
if (customName) {
return _.extend({}, pkg, { name: customName });
}
return pkg;
}
module.exports = function (root, pkg, release, customName, cb) {
var customPackage = addCustomFieldsToPackage(pkg, customName);
var specsDirectory = files.specsDirectory(root);
var sourcesDirectory = files.sourcesDirectory(root);
var sourcesArchive = files.sourcesArchive(root, customPackage);
fs.mkdirSync(specsDirectory);
fs.mkdirSync(sourcesDirectory);
generateServiceFile(root, customPackage);
generateSpecFile(specsDirectory, customPackage, release);
archiver.compress(root, sourcesArchive, cb);
};
| Use _.extend instead of Object.assign | Use _.extend instead of Object.assign
| JavaScript | mit | Limess/speculate,Limess/speculate |
a2e2d40c60308104780e1f576fd6be365f463fe8 | routes/index.js | routes/index.js |
/*
* GET home page.
*/
module.exports = function (app, options) {
"use strict";
/*
GET list of routes (index page)
*/
var getIndex = function (req, res) {
// Todo: Add autentication
req.session.userId = "testUserId";
res.render('index', { title: 'Mine turer' });
};
app.get('/', getIndex);
app.get('/index', getIndex);
};
|
/*
* GET home page.
*/
module.exports = function (app, options) {
"use strict";
var connect = options.connect;
/*
GET list of routes (index page)
*/
var getIndex = function (req, res) {
// Todo: Add autentication
req.session.userId = "testUserId";
res.render('index', { title: 'Mine turer' });
};
var getConnect = function (req, res) {
// Check for ?data= query
if (req && req.query && req.query.data) {
try {
var data = client.decryptJSON(req.query.data);
} catch (e) {
// @TODO handle this error propperly
var data = {er_autentisert: false}
}
if (data.er_autentisert === true) {
// User is authenticated
} else {
// User is not authenticated
}
// Initiate DNT Connect signon
} else {
res.redirect(connect.signon('http://localhost:3004/connect'));
}
};
app.get('/', getIndex);
app.get('/index', getIndex);
app.get('/connect', getConnect);
};
| Add initial route provider for DNT Connect signon | Add initial route provider for DNT Connect signon
| JavaScript | mit | Turistforeningen/Turadmin,Turistforeningen/Turadmin,Turistforeningen/Turadmin,Turistforeningen/Turadmin |
0b094a233b79ef8b5b7e63c65d167e03ee480cff | background.js | background.js | window.addEventListener("load", detect, false);
document.getElementById("webMessengerRecentMessages").addEventListener('DOMNodeInserted', detect, false);
function detect(evt) {
console.log("hello");
//characters for codeblock
var start = "`~ ";
var stop = " ~`";
//main chat only. small chat splits lines into seperate elements...
var chat = document.getElementsByClassName("_38"); //what is the exact meanning of _38???
for (i = 0; i < chat.length; i++) {
text = chat[i].getElementsByTagName("p")[0];
// console.log( text );
words = chat[i].innerText
// console.log(words + "contains lol? : " + words.indexOf( "lol" ) );
var stop_index = words.indexOf(stop);
var start_index = words.indexOf(start);
if (stop_index > start_index && start_index > -1) {
text.className += " code";
text.innerText = words.substr(start_index + 3, stop_index - start_index - 3);
}
}
}
| window.addEventListener("load", monospaceInit, false);
function monospaceInit(evt) {
detect(evt);
document.getElementById(
"webMessengerRecentMessages"
).addEventListener('DOMNodeInserted', detect, false);
}
function detect(evt) {
console.log("hello");
//characters for codeblock
var start = "`~ ";
var stop = " ~`";
//main chat only. small chat splits lines into seperate elements...
var chat = document.getElementsByClassName("_38"); //what is the exact meanning of _38???
for (i = 0; i < chat.length; i++) {
text = chat[i].getElementsByTagName("p")[0];
// console.log( text );
words = chat[i].innerText;
// console.log(words + "contains lol? : " + words.indexOf( "lol" ) );
var stop_index = words.indexOf(stop);
var start_index = words.indexOf(start);
if (stop_index > start_index && start_index > -1) {
text.className += " code";
text.innerText = words.substr(start_index + 3, stop_index - start_index - 3);
}
}
}
| Improve performance: smaller scope, optimization | Improve performance: smaller scope, optimization
Change addEventListener to focus only on the large web chat in Facebook
(id = webMessengerRecentMessages). Also add this event listener only
after the entire page has loaded to prevent a flurry of runs.
Conflicts:
background.js
| JavaScript | mit | tchen01/monospace |
b62469ee1103dd69986570ec314be4c2473639ca | src/app/utils/AffiliationMap.js | src/app/utils/AffiliationMap.js | const map = {
//steemit
ned: 'steemit',
justinw: 'steemit',
elipowell: 'steemit',
vandeberg: 'steemit',
birdinc: 'steemit',
gerbino: 'steemit',
andrarchy: 'steemit',
roadscape: 'steemit',
steemitblog: 'steemit',
steemitdev: 'steemit',
/*
//steem monsters
steemmonsters: 'sm',
'steem.monsters': 'sm',
aggroed: 'sm',
yabapmatt: 'sm',
*/
};
export default map;
| const map = {
//steemit
ned: 'steemit',
justinw: 'steemit',
elipowell: 'steemit',
vandeberg: 'steemit',
gerbino: 'steemit',
andrarchy: 'steemit',
roadscape: 'steemit',
steemitblog: 'steemit',
steemitdev: 'steemit',
/*
//steem monsters
steemmonsters: 'sm',
'steem.monsters': 'sm',
aggroed: 'sm',
yabapmatt: 'sm',
*/
};
export default map;
| Remove birdinc from team list | Remove birdinc from team list | JavaScript | mit | steemit/steemit.com,steemit/steemit.com,TimCliff/steemit.com,TimCliff/steemit.com,TimCliff/steemit.com,steemit/steemit.com |
bad6e9925b177bb4503a3b03d4afc996be128200 | src/components/Weapons/index.js | src/components/Weapons/index.js | import React, { Component } from 'react';
import weapons from './weapons.json';
import './style.css';
class Weapons extends Component {
render() {
return (
<h1>Weapons</h1>
)
}
}
export default Weapons;
| import React, { Component } from 'react';
import weapons from './weapons.json';
import './style.css';
function WeaponsItems() {
const weaponsItems = weapons.map((item) =>
<div className="content-item">
<p>{item.title}</p>
<ul>
{item.items.map((element) => <li>{element}</li>)}
</ul>
</div>
);
return (
<div className="container">{weaponsItems}</div>
);
}
class Weapons extends Component {
render() {
return (
<WeaponsItems/>
)
}
}
export default Weapons;
| Add elements to the menu | wip(weapons): Add elements to the menu
| JavaScript | mit | valsaven/dark-souls-guidebook,valsaven/dark-souls-guidebook |
2a885f785488efcaa219e8b9c59d457360564f14 | app/templates/src/gulpfile/tasks/optimize-criticalCss.js | app/templates/src/gulpfile/tasks/optimize-criticalCss.js | /**
* Critical CSS
* @description Generate Inline CSS for the Above the fold optimization
*/
import kc from '../../config.json'
import gulp from 'gulp'
import critical from 'critical'
import yargs from 'yargs'
const args = yargs.argv
const criticalCss = () => {
// Default Build Variable
var generateCritical = args.critical || false;
if(generateCritical) {
kc.cssabove.sources.forEach(function(item) {
return critical.generate({
inline: kc.cssabove.inline,
base: kc.dist.markup,
src: item,
dest: kc.dist.markup + item,
minify: kc.cssabove.minify,
width: kc.cssabove.width,
height: kc.cssabove.height
})
})
}
}
gulp.task('optimize:criticalCss', criticalCss)
module.exports = criticalCss
| /**
* Critical CSS
* @description Generate Inline CSS for the Above the fold optimization
*/
import kc from '../../config.json'
import gulp from 'gulp'
import critical from 'critical'
import yargs from 'yargs'
const args = yargs.argv
const criticalCss = () => {
// Default Build Variable
var generateCritical = args.critical || false;
if(generateCritical) {
kc.cssabove.sources.forEach(function(item) {
return critical.generate({
inline: kc.cssabove.inline,
base: kc.dist.markup,
src: item,
dest: item,
minify: kc.cssabove.minify,
width: kc.cssabove.width,
height: kc.cssabove.height
})
})
}
}
gulp.task('optimize:criticalCss', criticalCss)
module.exports = criticalCss
| Fix Critical CSS Destination Path | Fix Critical CSS Destination Path
| JavaScript | mit | kittn/generator-kittn,kittn/generator-kittn,kittn/generator-kittn,kittn/generator-kittn |
baebce75ff945946e3803382484c52b73d70ff5e | share/spice/maps/places/maps_places.js | share/spice/maps/places/maps_places.js | // execute dependencies immediately on file parse
nrj("/js/mapbox/mapbox-1.5.2.js",1);
nrc("/js/mapbox/mapbox-1.5.2.css",1);
// the plugin callback by another name
var ddg_spice_maps_places = function (places) {
// sub function where 'places' is always defined
var f2 = function() {
console.log("f2");
// check for the mapbox object
if (!window["L"]) {
console.log("no L");
// wait for it
window.setTimeout(f2, 50);
// could check for a max value here
return;
}
console.log("L found, here we go with places: %o", places);
DDG.maps.renderLocal(places);
};
f2();
};
| // execute dependencies immediately on file parse
nrj("/js/mapbox/mapbox-1.5.2.js",1);
nrc("/js/mapbox/mapbox-1.5.2.css",1);
// the plugin callback by another name
var ddg_spice_maps_places = function (places) {
// sub function where 'places' is always defined
var f2 = function() {
// console.log("f2");
// check for the mapbox object
if (!window["L"]) {
// console.log("no L");
// wait for it
window.setTimeout(f2, 50);
// could check for a max value here
return;
}
// console.log("L found, here we go with places: %o", places);
DDG.maps.renderLocal(places);
};
f2();
};
| Comment out console to merge. | Comment out console to merge.
| JavaScript | apache-2.0 | bdjnk/zeroclickinfo-spice,stennie/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,imwally/zeroclickinfo-spice,levaly/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,imwally/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,stennie/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,lerna/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,sevki/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,P71/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,soleo/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,deserted/zeroclickinfo-spice,ppant/zeroclickinfo-spice,loganom/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,soleo/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,loganom/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,lernae/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,lernae/zeroclickinfo-spice,deserted/zeroclickinfo-spice,soleo/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,P71/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,mayo/zeroclickinfo-spice,lernae/zeroclickinfo-spice,deserted/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,levaly/zeroclickinfo-spice,lerna/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,loganom/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,sevki/zeroclickinfo-spice,levaly/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,stennie/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,P71/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,ppant/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,deserted/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,lernae/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,levaly/zeroclickinfo-spice,levaly/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,lernae/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,mayo/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,mayo/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,P71/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,ppant/zeroclickinfo-spice,lernae/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,ppant/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,echosa/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,sevki/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,soleo/zeroclickinfo-spice,loganom/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,deserted/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,imwally/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,imwally/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,timeanddate/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,lerna/zeroclickinfo-spice,lerna/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,echosa/zeroclickinfo-spice,echosa/zeroclickinfo-spice,soleo/zeroclickinfo-spice,levaly/zeroclickinfo-spice,imwally/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,lerna/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,mayo/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,stennie/zeroclickinfo-spice,soleo/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,deserted/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,sevki/zeroclickinfo-spice |
49af9443e721cf9e68ca3a17eb01d94f7084cd66 | src/coercion/generic.js | src/coercion/generic.js | const getType = require('../typeResolver');
module.exports = {
isCoerced: function(value, typeDescriptor) {
return value instanceof getType(typeDescriptor);
},
coerce(value, typeDescriptor) {
const type = getType(typeDescriptor);
return new type(value);
}
};
| const getType = require('../typeResolver');
module.exports = {
isCoerced(value, typeDescriptor) {
return value instanceof getType(typeDescriptor);
},
coerce(value, typeDescriptor) {
const type = getType(typeDescriptor);
return new type(value);
}
};
| Fix eslint shorthand function assignment | Fix eslint shorthand function assignment
| JavaScript | mit | talyssonoc/structure |
66e535efbbacef95612fbcfe7c469890edc0e239 | client/src/character-animations.js | client/src/character-animations.js | 'use strict';
const
Animation = require('./animation'),
eventBus = require('./event-bus');
const
pacmanNormalColor = 0xffff00,
pacmanFrighteningColor = 0xffffff,
ghostFrightenedColor = 0x5555ff;
class CharacterAnimations {
constructor(gfx) {
this._gfx = gfx;
this._animations = [];
}
start() {
this._handlePause = () => {
for (let animation of this._animations) {
animation.pause();
}
};
eventBus.register('event.pause.begin', this._handlePause);
this._handleResume = () => {
for (let animation of this._animations) {
animation.resume();
}
};
eventBus.register('event.pause.end', this._handleResume);
}
stop() {
eventBus.unregister('event.pause.begin', this._handlePause);
eventBus.unregister('event.pause.end', this._handleResume);
}
createPacManAnimations() {
let animation = new Animation(this._gfx, pacmanNormalColor, pacmanFrighteningColor);
this._animations.push(animation);
return animation;
}
createGhostAnimations(ghostNormalColor) {
let animation = new Animation(this._gfx, ghostNormalColor, ghostFrightenedColor);
this._animations.push(animation);
return animation;
}
}
module.exports = CharacterAnimations; | 'use strict';
const
Animation = require('./animation'),
eventBus = require('./event-bus');
const
pacmanNormalColor = 0xffff00,
pacmanFrighteningColor = 0xffffff,
ghostFrightenedColor = 0x5555ff;
class CharacterAnimations {
constructor(gfx) {
this._gfx = gfx;
this._animations = [];
this._handlePause = () => {
for (let animation of this._animations) {
animation.pause();
}
};
this._handleResume = () => {
for (let animation of this._animations) {
animation.resume();
}
};
}
start() {
eventBus.register('event.pause.begin', this._handlePause);
eventBus.register('event.pause.end', this._handleResume);
}
stop() {
eventBus.unregister('event.pause.begin', this._handlePause);
eventBus.unregister('event.pause.end', this._handleResume);
}
createPacManAnimations() {
let animation = new Animation(this._gfx, pacmanNormalColor, pacmanFrighteningColor);
this._animations.push(animation);
return animation;
}
createGhostAnimations(ghostNormalColor) {
let animation = new Animation(this._gfx, ghostNormalColor, ghostFrightenedColor);
this._animations.push(animation);
return animation;
}
}
module.exports = CharacterAnimations; | Refactor private variable declaration to constructor | Refactor private variable declaration to constructor
| JavaScript | mit | hiddenwaffle/mazing,hiddenwaffle/mazing |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.