commit
stringlengths 40
40
| old_file
stringlengths 4
236
| new_file
stringlengths 4
236
| old_contents
stringlengths 1
3.26k
| new_contents
stringlengths 16
4.43k
| subject
stringlengths 16
624
| message
stringlengths 17
3.29k
| lang
stringclasses 5
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
|---|---|---|---|---|---|---|---|---|---|
e8e00d643a4c124e87887dfdeb2596ac88285a07
|
src/helpers/buildProps.js
|
src/helpers/buildProps.js
|
import {Map} from 'immutable';
export default function buildProps(propsDefinition, allProps = false) {
const props = {}
Map(propsDefinition).map((data, prop) => {
if (data.defaultValue)
props[prop] = data.defaultValue.computed
? data.defaultValue.value
: eval(`(${data.defaultValue.value})`) // eslint-disable-line no-eval
else if (allProps || data.required || data.type.name === 'func')
props[prop] = calculateProp(data.type, prop)
})
return props
}
function calculateProp(type, prop) {
switch (type.name) {
case 'any': return 'Default ANY'
case 'node': return 'Default NODE'
case 'string': return `Default string ${prop}`
case 'bool': return true
case 'number': return 1
case 'func': return eval(`[function () { document.dispatchEvent(new BluekitEvent('functionTriggered', {detail: {prop: "${prop}"}})) }][0]`) // eslint-disable-line no-eval
case 'enum': return type.value[0].value.replace(/'/g, '')
case 'shape': return Map(type.value)
.map((subType, name) => calculateProp(subType, name))
.toJS()
case 'arrayOf': return [calculateProp(type.value, prop)]
}
return null
}
|
import {Map} from 'immutable';
export default function buildProps(propsDefinition, allProps = false) {
const props = {}
Map(propsDefinition).map((data, prop) => {
if (data.defaultValue)
props[prop] = data.defaultValue.computed
? data.defaultValue.value
: eval(`(${data.defaultValue.value})`) // eslint-disable-line no-eval
else if (allProps || data.required || data.type.name === 'func')
props[prop] = calculateProp(data.type, prop)
})
return props
}
function calculateProp(type, prop) {
switch (type.name) {
case 'any': return `ANY ${prop}`
case 'node': return `NODE ${prop}`
case 'string': return `${prop}`
case 'bool': return true
case 'number': return 1
case 'array': return []
case 'object': return {}
case 'func': return eval(`[function () { document.dispatchEvent(new BluekitEvent('functionTriggered', {detail: {prop: "${prop}"}})) }][0]`) // eslint-disable-line no-eval
case 'enum': return type.value[0].value.replace(/'/g, '')
case 'shape': return Map(type.value)
.map((subType, name) => calculateProp(subType, name))
.toJS()
case 'arrayOf': return [calculateProp(type.value, prop)]
}
return null
}
|
Add some defaults for prop types
|
Add some defaults for prop types
|
JavaScript
|
mit
|
blueberryapps/react-bluekit,blueberryapps/react-bluekit,blueberryapps/react-bluekit,kjg531/react-bluekit,kjg531/react-bluekit
|
2c7c6eb77676ce869d788cba91147ba40af45745
|
WebApp/controllers/index.js
|
WebApp/controllers/index.js
|
'use strict';
var passport = require('passport');
module.exports = function (router) {
router.get('/', function (req, res) {
res.render('index');
});
router.post('/signup', passport.authenticate('local', {
successRedirect : '/home', // redirect to the secure profile section
failureRedirect : '/', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
/*
app.use(function (req,res) {
res.render('404', {url:req.url});
});
*/
};
|
'use strict';
var passport = require('passport');
module.exports = function (router) {
router.get('/', function (req, res) {
res.render('index');
});
router.post('/signup', passport.authenticate('local', {
successRedirect : '/home', // redirect to the secure home section
failureRedirect : '/', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
/*
// - Logout route from application. - //
router.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
*/
/*
// - This is a catch-all for requeste dpages taht don't exist. - //
router.use(function (req,res) {
res.render('404', {url:req.url});
});
*/
};
|
Add logout rout logic and 404 catch route.
|
Add logout rout logic and 404 catch route.
|
JavaScript
|
mit
|
uahengojr/NCA-Web-App,uahengojr/NCA-Web-App
|
4eff36df241f9de8abca1bf5bc5871625b204d48
|
src/forwarded.js
|
src/forwarded.js
|
import { Namespace as NS } from 'xmpp-constants';
export default function (JXT) {
let Forwarded = JXT.define({
name: 'forwarded',
namespace: NS.FORWARD_0,
element: 'forwarded'
});
JXT.extendIQ(Forwarded);
JXT.extendPresence(Forwarded);
JXT.withMessage(function (Message) {
JXT.extend(Message, Forwarded);
JXT.extend(Forwarded, Message);
});
JXT.withDefinition('delay', NS.DELAY, function (Delayed) {
JXT.extend(Forwarded, Delayed);
});
}
|
import { Namespace as NS } from 'xmpp-constants';
export default function (JXT) {
let Forwarded = JXT.define({
name: 'forwarded',
namespace: NS.FORWARD_0,
element: 'forwarded'
});
JXT.withMessage(function (Message) {
JXT.extend(Message, Forwarded);
JXT.extend(Forwarded, Message);
});
JXT.withPresence(function (Presence) {
JXT.extend(Presence, Forwarded);
JXT.extend(Forwarded, Presence);
});
JXT.withIQ(function (IQ) {
JXT.extend(IQ, Forwarded);
JXT.extend(Forwarded, IQ);
});
JXT.withDefinition('delay', NS.DELAY, function (Delayed) {
JXT.extend(Forwarded, Delayed);
});
}
|
Allow presence and iq stanzas in forwards
|
Allow presence and iq stanzas in forwards
|
JavaScript
|
mit
|
otalk/jxt-xmpp
|
ed4aee982efbe639586bb894a7a2a0b06f221c20
|
routes/login.js
|
routes/login.js
|
var express = require('express');
var router = express.Router();
const passport = require('passport')
const FacebookStrategy = require('passport-facebook').Strategy
passport.use(new FacebookStrategy({
clientID: 'fsddf',
clientSecret: 'FACEBOOK_APP_SECRET',
callbackURL: "https://age-guess-api.herokuapp.com"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate(function(err, user) {
if (err) { return done(err); }
done(null, user);
});
}
));
/* GET entries */
router.get('/', function(req, res) {
res.render('login')
});
router.get('/auth/facebook', passport.authenticate('facebook'))
router.get('/auth/facebook/callback',
passport.authenticate('facbeook', {
successRedirect: '/',
failureRedirect: '/login'
})
)
module.exports = router;
|
var express = require('express');
var router = express.Router();
require('dotenv').config()
const passport = require('passport')
const FacebookStrategy = require('passport-facebook').Strategy
passport.use(new FacebookStrategy({
clientID: process.env.APP_ID,
clientSecret: process.env.APP_SECRET,
callbackURL: "https://age-guess-api.herokuapp.com"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate(function(err, user) {
if (err) { return done(err); }
done(null, user);
});
}
));
/* GET entries */
router.get('/', function(req, res) {
res.render('login')
});
router.get('/auth/facebook', passport.authenticate('facebook'))
router.get('/auth/facebook/callback',
passport.authenticate('facbeook', {
successRedirect: '/',
failureRedirect: '/login'
})
)
router.get(
'/auth/facebook/secret',
passport.authenticate('facebook', { failureRedirect: '/login' }),
(req, res) => {
res.send('Hello This is A Secret!')
}
)
module.exports = router;
|
Add routing for facebook auth
|
Add routing for facebook auth
|
JavaScript
|
mit
|
michael-lowe-nz/ageGuessAPI,michael-lowe-nz/ageGuessAPI
|
8523b2a9d123b77d5003434e42fa877b718a9b3c
|
api/policies/isGuacamole.js
|
api/policies/isGuacamole.js
|
/**
* Nanocloud turns any traditional software into a cloud solution, without
* changing or redeveloping existing source code.
*
* Copyright (C) 2016 Nanocloud Software
*
* This file is part of Nanocloud.
*
* Nanocloud is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Nanocloud is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Pass to next middleware only if incoming request comes from Guacamole
* For now we consider a request to originate from Guacamole if req.host is set to
* "localhost:1337" which is the case for guacamole because it directly targets
* the backend without passing through the proxy
*/
module.exports = function(req, res, next) {
if (req.get('host') === 'localhost:1337') {
return next(null);
}
return res.send(401, 'Request did not originate from local network');
};
|
/**
* Nanocloud turns any traditional software into a cloud solution, without
* changing or redeveloping existing source code.
*
* Copyright (C) 2016 Nanocloud Software
*
* This file is part of Nanocloud.
*
* Nanocloud is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Nanocloud is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Pass to next middleware only if incoming request comes from Guacamole
* For now we consider a request to originate from Guacamole if req.host is set to
* "localhost:1337" or "backend:1337" which is the case for guacamole because it directly targets
* the backend without passing through the proxy
*/
module.exports = function(req, res, next) {
let host = req.get('host');
if (host === 'localhost:1337' || host === 'backend:1337') {
return next(null);
}
return res.send(401, 'Request did not originate from local network');
};
|
Fix history and scale down not working in production mode
|
Fix history and scale down not working in production mode
In dev mode guacamole-client targets localhost:1337 for the backend
In production mode guacamole-client targets backend:1337 for the backend
Update isGuacamole policy to take the production setup into account
|
JavaScript
|
agpl-3.0
|
romain-ortega/nanocloud,Gentux/nanocloud,corentindrouet/nanocloud,corentindrouet/nanocloud,dynamiccast/nanocloud,Leblantoine/nanocloud,dynamiccast/nanocloud,romain-ortega/nanocloud,Nanocloud/nanocloud,Nanocloud/nanocloud,romain-ortega/nanocloud,Leblantoine/nanocloud,Nanocloud/nanocloud,Leblantoine/nanocloud,Gentux/nanocloud,Leblantoine/nanocloud,dynamiccast/nanocloud,Gentux/nanocloud,Nanocloud/nanocloud,Nanocloud/nanocloud,romain-ortega/nanocloud,Gentux/nanocloud,Leblantoine/nanocloud,corentindrouet/nanocloud,Nanocloud/nanocloud,Leblantoine/nanocloud,corentindrouet/nanocloud,Nanocloud/nanocloud,corentindrouet/nanocloud,dynamiccast/nanocloud,Leblantoine/nanocloud,romain-ortega/nanocloud,dynamiccast/nanocloud,corentindrouet/nanocloud,romain-ortega/nanocloud,dynamiccast/nanocloud,Nanocloud/nanocloud,romain-ortega/nanocloud,corentindrouet/nanocloud,romain-ortega/nanocloud,Leblantoine/nanocloud,Gentux/nanocloud,Gentux/nanocloud,corentindrouet/nanocloud,Gentux/nanocloud,Gentux/nanocloud
|
8a9ea980ca9e18c2b7760f7927836dd265a3a07f
|
lib/collections/checkID.js
|
lib/collections/checkID.js
|
Meteor.methods({
checkHKID: function (hkid) {
var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/; // HKID format = 1 or 2 letters followed by 6 numbers and 1 checksum digit.
var matchArray = hkid.match(hkidPat);
if(matchArray == null){idError()}
var checkSum = 0;
var charPart = matchArray[1];
var numPart = matchArray[2];
var checkDigit = matchArray[3];
if (charPart.length == 2) {
checkSum += 9 * (charPart.charAt(0).charCodeAt(0) - 55);
checkSum += 8 * (charPart.charAt(1).charCodeAt(0) - 55);
}
else {
checkSum += 8 * (charPart.charCodeAt(0)-55);
checkSum += 324;
}
for (var i = 0, j = 7; i < numPart.length; i++, j--){
checkSum += j * numPart.charAt(i);
}
var remaining = checkSum % 11;
var checkNumber = 11 - remaining;
if(checkDigit == checkNumber) {return("valid")}
function idError () {
throw new Meteor.Error('invalid', 'The HKID entered is invalid')
}
}
});
|
Meteor.methods({
checkHKID: function (hkid) {
var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/; // HKID format = 1 or 2 letters followed by 6 numbers and 1 checksum digit.
var matchArray = hkid.match(hkidPat);
if(matchArray == null){idError()}
var checkSum = 0;
var charPart = matchArray[1];
var numPart = matchArray[2];
var checkDigit = matchArray[3];
if (charPart.length == 2) {
checkSum += 9 * (charPart.charAt(0).charCodeAt(0) - 55);
checkSum += 8 * (charPart.charAt(1).charCodeAt(0) - 55);
}
else {
checkSum += 8 * (charPart.charCodeAt(0)-55);
checkSum += 324;
}
for (var i = 0, j = 7; i < numPart.length; i++, j--){
checkSum += j * numPart.charAt(i);
}
var remaining = checkSum % 11;
var checkNumber = 11 - remaining;
if(checkDigit == checkNumber) {return("valid")}
else {idError()}
function idError () {
throw new Meteor.Error('invalid', 'The HKID entered is invalid')
}
}
});
|
Fix minor error with HKID verification
|
Fix minor error with HKID verification
|
JavaScript
|
agpl-3.0
|
gazhayes/Popvote-HK,gazhayes/Popvote-HK
|
959840f4da79f68cc67b4a994c1b0fed5e5fc217
|
spec/gateway-spec.js
|
spec/gateway-spec.js
|
"use babel";
import gateway from "../lib/gateway";
describe("Gateway", () => {
describe("packagePath", () => {
it("returns path of package installation", () => {
expect(gateway.packagePath()).toContain("exfmt-atom");
});
});
describe("shouldUseLocalExfmt", () => {
it("returns true when exfmtDirectory is blank or '.'", () => {
atom.config.set("exfmt-atom.exfmtDirectory", "");
expect(gateway.shouldUseLocalExfmt()).toBe(true);
atom.config.set("exfmt-atom.exfmtDirectory", ".");
expect(gateway.shouldUseLocalExfmt()).toBe(true);
});
it("returns false when exfmtDirectory isn't blank or '.'", () => {
atom.config.set("exfmt-atom.exfmtDirectory", "/tmp");
expect(gateway.shouldUseLocalExfmt()).toBe(false);
});
});
});
|
"use babel";
import gateway from "../lib/gateway";
import path from "path";
import process from "child_process";
describe("Gateway", () => {
describe("packagePath", () => {
it("returns path of package installation", () => {
expect(gateway.packagePath()).toContain("exfmt-atom");
});
});
describe("runExfmt", () => {
beforeEach(function() {
spyOn(process, "spawnSync").andReturn({});
});
it("invokes runLocalExfmt when exfmtDirectory is undefined", () => {
atom.config.set("exfmt-atom.exfmtDirectory", undefined);
gateway.runExfmt("input text");
expect(process.spawnSync).toHaveBeenCalledWith(
"mix",
["exfmt", "--stdin"],
{
cwd: [atom.project.getPaths()[0]],
input: "input text"
}
);
});
it("invokes runExternalExfmt when exfmtDirectory is set", () => {
atom.config.set("exfmt-atom.exfmtDirectory", "/tmp");
gateway.runExfmt("input text");
expect(process.spawnSync).toHaveBeenCalledWith("bin/exfmt.sh", ["/tmp"], {
cwd: path.join(__dirname, ".."),
input: "input text"
});
});
});
describe("shouldUseLocalExfmt", () => {
it("returns true when exfmtDirectory is blank or '.'", () => {
atom.config.set("exfmt-atom.exfmtDirectory", "");
expect(gateway.shouldUseLocalExfmt()).toBe(true);
atom.config.set("exfmt-atom.exfmtDirectory", ".");
expect(gateway.shouldUseLocalExfmt()).toBe(true);
});
it("returns false when exfmtDirectory isn't blank or '.'", () => {
atom.config.set("exfmt-atom.exfmtDirectory", "/tmp");
expect(gateway.shouldUseLocalExfmt()).toBe(false);
});
});
});
|
Add spec tests for gateway run functions
|
Add spec tests for gateway run functions
|
JavaScript
|
mit
|
rgreenjr/exfmt-atom
|
32dd109b7df05ee3b687baed65381fe1c64da1c2
|
js/home-nav.js
|
js/home-nav.js
|
var navOffset = function () {
$('#content.container').css('margin-top', $('#nav').height() * 0.25);
};
var collapsedMenus = function() {
$('#nav button.navbar-toggle').on('click', function() {
if ($(this).hasClass('collapsed')) {
var collapsedMenuHeight = 323.5;
collapseOffset('#nav', collapsedMenuHeight);
}
});
$('#nav #side-menu > a').on('click', function () {
if ($(this).parent().not('.open')) {
var collapsedSideMenuHeight;
if ($('#nav .navbar-toggle').is(':visible')) {
collapsedSideMenuHeight = 133 + 323.5;
} else {
collapsedSideMenuHeight = 133;
}
collapseOffset('#nav #side-menu > a', collapsedSideMenuHeight);
}
});
};
var collapseOffset = function(selector, size) {
var $window = $(window);
var windowHeight = $window.height();
if ($window.scrollTop() < size) {
var dest = (size < windowHeight) ? size : windowHeight;
$('html, body').animate({
scrollTop: dest
}, 500, 'swing');
}
};
navOffset();
collapsedMenus();
|
var navOffset = function () {
$('#content.container').css('margin-top', $('#nav').height() * 0.25);
};
var collapsedMenus = function() {
$('#nav button.navbar-toggle').on('click', function() {
if ($(this).hasClass('collapsed') &&
!$($(this).data('target')).hasClass('collapsing')) {
var collapsedMenuHeight = 323.5;
collapseOffset('#nav', collapsedMenuHeight);
}
});
$('#nav #side-menu > a').on('click', function () {
if (!$(this).parent().hasClass('open')) {
var collapsedSideMenuHeight;
if ($('#nav .navbar-toggle').is(':visible')) {
collapsedSideMenuHeight = 133 + 323.5;
} else {
collapsedSideMenuHeight = 133;
}
collapseOffset('#nav #side-menu > a', collapsedSideMenuHeight);
}
});
};
var collapseOffset = function(selector, size) {
var $window = $(window);
var windowHeight = $window.height();
if ($window.scrollTop() < size) {
var dest = (size < windowHeight) ? size : windowHeight;
$('html, body').animate({
scrollTop: dest
}, 500, 'swing');
}
};
navOffset();
collapsedMenus();
|
Fix wrong auto-scrolling when opening the menu.
|
Fix wrong auto-scrolling when opening the menu.
Fixed page scrolling down when main menu is closing.
Fixed incorrect logic for scrolling on submenu ("More") scrolling.
JQuery.not() is a filter/selector, not a class detector.
|
JavaScript
|
mit
|
HackNC/fall2015,newmane/PearlHacks17,HackNC/fall2015,newmane/PearlHacks17,madipfaff/PearlHacks16,madipfaff/PearlHacks16
|
2dc52dbbc4f0e01c6f6cd898b2f57f09430675c8
|
js/sideshow.js
|
js/sideshow.js
|
var sideshow = function () {
function hasClass (elem, cls) {
var names = elem.className.split(" ");
for (var i = 0; i < names; i++) {
if (cls == names[i])
return true;
}
return false;
}
function addClass (elem, cls) {
if (!hasClass(elem, cls))
elem.className += " " + cls;
}
function removeClass (elem, cls) {
var names = elem.className.split(" ");
for (var i = 0; i < names.length; i++) {
if (names[i] == cls)
names.splice(i, 1);
}
elem.className = names.join(" ");
}
function init (root) {
var root = document.getElementById(root);
var sections = root.getElementsByTagName("section");
for (var i = 0; i < sections.length; i++) {
addClass(sections[i], "slide");
}
}
return {
init: init,
}
}();
|
var sideshow = function () {
function hasClass (elem, cls) {
var names = elem.className.split(" ");
for (var i = 0; i < names; i++) {
if (cls == names[i])
return true;
}
return false;
}
function addClass (elem, cls) {
var names = elem.className.split(" ");
for (var i = 0; i < names.length; i++) {
if (names[i] == cls)
return;
}
names.push(cls);
elem.className = names.join(" ");
}
function removeClass (elem, cls) {
var names = elem.className.split(" ");
for (var i = 0; i < names.length; i++) {
if (names[i] == cls)
names.splice(i, 1);
}
elem.className = names.join(" ");
}
function init (root) {
var root = document.getElementById(root);
var sections = root.getElementsByTagName("section");
for (var i = 0; i < sections.length; i++) {
addClass(sections[i], "slide");
}
}
return {
init: init,
}
}();
|
Make addClass implementation symmetric with removeClass.
|
Make addClass implementation symmetric with removeClass.
|
JavaScript
|
isc
|
whilp/sideshow
|
057829f108dc1fe04369feeb95deb794adbf154a
|
Cloudy/cloudy.js
|
Cloudy/cloudy.js
|
var Cloudy = {
isPlayerPage: function() {
return $("#audioplayer").length == 1;
},
sendEpisodeToCloudy: function() {
var episodeTitle = $(".titlestack .title").text();
var showTitle = $(".titlestack .caption2").text();
var details = {
"show_title": showTitle,
"episode_title": episodeTitle
};
webkit.messageHandlers.episodeHandler.postMessage(details);
},
installPlaybackHandlers: function() {
var player = $("#audioplayer")[0];
player.addEventListener("play", Cloudy.playerDidPlay);
player.addEventListener("pause", Cloudy.playerDidPause);
},
playerDidPlay: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"playing": true
});
},
playerDidPause: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"playing": false
});
},
togglePlaybackState: function() {
var player = $("#audioplayer")[0];
player.paused ? player.play() : player.pause();
}
};
$(function() {
if (Cloudy.isPlayerPage()) {
Cloudy.installPlaybackHandlers();
Cloudy.sendEpisodeToCloudy();
}
else {
webkit.messageHandlers.episodeHandler.postMessage(null);
}
});
|
var Cloudy = {
isPlayerPage: function() {
return $("#audioplayer").length == 1;
},
sendEpisodeToCloudy: function() {
var episodeTitle = $(".titlestack .title").text();
var showTitle = $(".titlestack .caption2").text();
var details = {
"show_title": showTitle,
"episode_title": episodeTitle
};
webkit.messageHandlers.episodeHandler.postMessage(details);
},
installPlaybackHandlers: function() {
var player = $("#audioplayer")[0];
player.addEventListener("play", Cloudy.playerDidPlay);
player.addEventListener("pause", Cloudy.playerDidPause);
},
playerDidPlay: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"playing": true
});
},
playerDidPause: function() {
webkit.messageHandlers.playbackHandler.postMessage({
"playing": false
});
},
togglePlaybackState: function() {
var player = $("#audioplayer")[0];
player.paused ? player.play() : player.pause();
},
installSpaceHandler: function() {
$(window).keypress(function(event) {
if (event.keyCode == 32) {
event.preventDefault();
Cloudy.togglePlaybackState();
}
});
}
};
$(function() {
if (Cloudy.isPlayerPage()) {
Cloudy.installPlaybackHandlers();
Cloudy.installSpaceHandler();
Cloudy.sendEpisodeToCloudy();
}
else {
webkit.messageHandlers.episodeHandler.postMessage(null);
}
});
|
Use JavaScript to intercept space bar event.
|
Use JavaScript to intercept space bar event.
|
JavaScript
|
mit
|
calebd/cloudy,calebd/cloudy
|
e009e13d0175d933542f2230c220067e2f29f093
|
lib/handlers/tar-stream.js
|
lib/handlers/tar-stream.js
|
/*
* tar-stream.js: Checkout adapter for a tar stream.
*
* (C) 2012 Bradley Meck.
* MIT LICENSE
*
*/
var tar = require('tar');
//
// ### function download (source, callback)
// #### @source {Object} Source checkout options
// #### @callback {function} Continuation to respond to.
// Downloads the tar stream to the specified `source.destination`.
//
exports.download = function (source, callback) {
var done = false;
//
// Respond to the callback once.
//
function finish() {
if (!done) {
done = true;
callback.apply(null, arguments);
}
}
source.stream
.on('error', finish)
.pipe(tar.Extract({ path: source.destination }))
.on('error', finish)
.on('end', finish);
};
|
/*
* tar-stream.js: Checkout adapter for a tar stream.
*
* (C) 2012 Bradley Meck.
* MIT LICENSE
*
*/
var zlib = require('zlib'),
tar = require('tar');
//
// ### function download (source, callback)
// #### @source {Object} Source checkout options
// #### @callback {function} Continuation to respond to.
// Downloads the tar stream to the specified `source.destination`.
//
exports.download = function (source, callback) {
var done = false;
//
// Respond to the callback once.
//
function finish() {
if (!done) {
done = true;
callback.apply(null, arguments);
}
}
if (source.gzip) {
source.stream = source.stream
.on('error', finish)
.pipe(zlib.createGunzip());
}
source.stream
.on('error', finish)
.pipe(tar.Extract({ path: source.destination }))
.on('error', finish)
.on('end', finish);
};
|
Allow for optional gzip encoding.
|
[api] Allow for optional gzip encoding.
|
JavaScript
|
mit
|
indexzero/node-checkout
|
fbbf41efcba79d61feadb9307f1a4a35c65c405b
|
ecplurkbot.js
|
ecplurkbot.js
|
var log4js = require('log4js');
var PlurkClient = require('plurk').PlurkClient;
var nconf = require('nconf');
nconf.file('config', __dirname + '/config/config.json')
.file('keywords', __dirname + '/config/keywords.json');
var logging = nconf.get('log').logging;
var log_path = nconf.get('log').log_path;
if (logging) {
log4js.clearAppenders();
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(log_path), 'BOT_LOG');
}
setInterval(checkTL, 500);
function checkTL() {
}
|
var log4js = require('log4js');
var PlurkClient = require('plurk').PlurkClient;
var nconf = require('nconf');
nconf.file('config', __dirname + '/config/config.json')
.file('keywords', __dirname + '/config/keywords.json');
var logging = nconf.get('log').logging;
var log_path = nconf.get('log').log_path;
if (logging) {
log4js.clearAppenders();
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(log_path), 'BOT_LOG');
}
var logger = log4js.getLogger('BOT_LOG');
var consumerKey = nconf.get('token').consume_key;
var consumerSecret = nconf.get('token').consume_secret;
var accessToken = nconf.get('token').access_token;
var accessTokenSecret = nconf.get('token').access_token_secret;
var client = new PlurkClient(true, consumerKey, consumerSecret, accessToken, accessTokenSecret);
client.startComet(function (err, data, cometUrl) {
if (err) {
logger.error(err);
return;
}
logger.info('Comet channel started.');
});
|
Rewrite with using startComet function of plurk modules
|
Rewrite with using startComet function of plurk modules
|
JavaScript
|
apache-2.0
|
dollars0427/ecplurkbot
|
021d3d985bb6a9965bd69a81897b0bc712578f36
|
src/app/api/utils.js
|
src/app/api/utils.js
|
import notp from 'notp'
import b32 from 'thirty-two'
export function cleanKey (key) {
return key.replace(/[^a-z2-7]+/g, '').slice(0, 32)
}
export function isValidKey (key) {
return /^[a-z2-7]{32}$/.test(cleanKey(key))
}
export function getCode (key) {
return notp.totp.gen(b32.decode(cleanKey(key)), {})
}
|
import notp from 'notp'
import b32 from 'thirty-two'
export function cleanKey (key) {
return key.replace(/[^a-z2-7]+/ig, '').toLowerCase()
}
export function isValidKey (key) {
return /^[a-z2-7]+$/.test(cleanKey(key))
}
export function getCode (key) {
return notp.totp.gen(b32.decode(cleanKey(key)), {})
}
|
Support for larger kind of key
|
fix: Support for larger kind of key
|
JavaScript
|
mit
|
nodys/basicotp,nodys/basicotp,nodys/basicotp
|
ae4e515cffdb87ca856a50f15c7a01b5605b93e4
|
migrations/20200422122956_multi_homefeeds.js
|
migrations/20200422122956_multi_homefeeds.js
|
export async function up(knex) {
await knex.schema
.raw('alter table feeds add column title text')
.raw('alter table feeds add column ord integer')
.raw(`alter table feeds drop constraint feeds_unique_feed_names`)
// Only RiverOfNews feeds can have non-NULL ord or title
.raw(`alter table feeds add constraint feeds_names_chk
check (ord is null and title is null or name = 'RiverOfNews')`)
// User cannot have multiple feeds with same name and ord is NULL
.raw(`create unique index feeds_unique_names_idx on feeds (user_id, name) where ord is null`)
}
export async function down(knex) {
// TODO: move extra subscriptions to main feed?
await knex.schema
// Remove extra RiverOfNews feeds
.raw(`delete from feeds where name = 'RiverOfNews' and ord is not null`)
.raw(`drop index feeds_unique_names_idx`)
.raw('alter table feeds drop constraint feeds_names_chk')
.raw('alter table feeds drop column title')
.raw('alter table feeds drop column ord')
.raw(`alter table feeds add constraint feeds_unique_feed_names unique(user_id, name)`);
}
|
export const up = (knex) => knex.schema.raw(`do $$begin
-- FEEDS TABLE
alter table feeds add column title text;
alter table feeds add column ord integer;
alter table feeds drop constraint feeds_unique_feed_names;
-- Only RiverOfNews feeds can have non-NULL ord or title
alter table feeds add constraint feeds_names_chk
check (ord is null and title is null or name = 'RiverOfNews');
-- User cannot have multiple feeds with same name and ord is NULL
create unique index feeds_unique_names_idx on feeds (user_id, name) where ord is null;
-- HOMEFEED_SUBSCRIPTIONS TABLE
create table homefeed_subscriptions (
homefeed_id uuid not null
references feeds (uid) on delete cascade on update cascade,
target_user_id uuid not null
references users (uid) on delete cascade on update cascade,
primary key (homefeed_id, target_user_id)
);
-- Assign all existing subscriptions to the main users homefeeds
insert into homefeed_subscriptions (homefeed_id, target_user_id)
select h.uid, f.user_id from
subscriptions s
join feeds h on h.user_id = s.user_id and h.name = 'RiverOfNews'
join feeds f on f.uid = s.feed_id and f.name = 'Posts';
end$$`);
export const down = (knex) => knex.schema.raw(`do $$begin
-- HOMEFEED_SUBSCRIPTIONS TABLE
drop table homefeed_subscriptions;
-- FEEDS TABLE
-- Remove extra RiverOfNews feeds
delete from feeds where name = 'RiverOfNews' and ord is not null;
drop index feeds_unique_names_idx;
alter table feeds drop constraint feeds_names_chk;
alter table feeds drop column title;
alter table feeds drop column ord;
alter table feeds add constraint feeds_unique_feed_names unique(user_id, name);
end$$`);
|
Add a homefeed_subscriptions database table
|
Add a homefeed_subscriptions database table
|
JavaScript
|
mit
|
FreeFeed/freefeed-server,FreeFeed/freefeed-server
|
895a59456addea4b43cf283ab9668747a615e392
|
test/data-structures/testDoublyLinkedList.js
|
test/data-structures/testDoublyLinkedList.js
|
/* eslint-env mocha */
const DoublyLinkedList = require('../../src').DataStructures.DoublyLinkedList;
const assert = require('assert');
describe('DoublyLinkedList', () => {
it('should be empty when initialized', () => {
const inst = new DoublyLinkedList();
assert(inst.isEmpty());
assert.equal(inst.length, 0);
});
});
|
/* eslint-env mocha */
const DoublyLinkedList = require('../../src').DataStructures.DoublyLinkedList;
const assert = require('assert');
describe('DoublyLinkedList', () => {
it('should be empty when initialized', () => {
const inst = new DoublyLinkedList();
assert(inst.isEmpty());
assert.equal(inst.length, 0);
});
it('should push node to the front', () => {
const inst = new DoublyLinkedList();
assert(inst.isEmpty());
inst.push(1);
assert.equal(inst.length, 1);
inst.push(2);
assert.equal(inst.length, 2);
assert.equal(inst.toString(), '2 -> 1 -> null');
});
});
|
Test push to the front of the list
|
DoublyLinkedList: Test push to the front of the list
|
JavaScript
|
mit
|
ManrajGrover/algorithms-js
|
7aa46cae7e352fb1bfb6b2453a66e2f58c4f93aa
|
assets/page/___page___/js/script.___page___.js
|
assets/page/___page___/js/script.___page___.js
|
'use strict';
/*
* Use for Async operations before displaying page
*
module.exports.prepare = function() {
this.done({});
};
*/
/*
* Compute Vue parameters
*
module.exports.vue = function() {
return {};
};
*/
/*
* Use as page starting point
*
module.exports.start = function() {
};
*/
|
'use strict';
/*
* Use for Async operations before displaying page
*
module.exports.prepare = function() {
this.done({});
};
*/
/*
* Compute Vue parameters
*
module.exports.vue = function() {
return {};
};
* or
module.exports.vue = {
};
*/
/*
* Use as page starting point
*
module.exports.start = function() {
};
*/
|
Update Layout assets to latest specifications
|
feat: Update Layout assets to latest specifications
|
JavaScript
|
mit
|
quasarframework/quasar-cli,rstoenescu/quasar-cli
|
7a13ef409b8251619771bd1f61a941da522d8830
|
assets/js/components/SpinnerButton.stories.js
|
assets/js/components/SpinnerButton.stories.js
|
/**
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import SpinnerButton from './SpinnerButton';
const Template = ( args ) => <SpinnerButton { ...args } />;
export const DefaultButton = Template.bind( {} );
DefaultButton.storyName = 'Default Button';
DefaultButton.args = {
children: 'Default Button',
onClick() {
return new Promise( ( resolve ) => setTimeout( resolve, 5000 ) );
},
};
export default {
title: 'Components/SpinnerButton',
component: SpinnerButton,
};
|
/**
* Site Kit by Google, Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import SpinnerButton from './SpinnerButton';
const Template = ( args ) => <SpinnerButton { ...args } />;
export const DefaultButton = Template.bind( {} );
DefaultButton.storyName = 'Default Button';
DefaultButton.args = {
children: 'Default Button',
onClick: () => new Promise( ( resolve ) => setTimeout( resolve, 5000 ) ),
};
export default {
title: 'Components/SpinnerButton',
component: SpinnerButton,
};
|
Fix vrt scenario script issue.
|
Fix vrt scenario script issue.
|
JavaScript
|
apache-2.0
|
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
|
86ce4f25d552c9b3538339c53b61abaf1faf860f
|
test/specs/elements/Segment/Segments-test.js
|
test/specs/elements/Segment/Segments-test.js
|
import React from 'react';
import {Segment, Segments} from 'stardust';
describe('Segments', () => {
it('should render children', () => {
const [segmentOne, segmentTwo] = render(
<Segments>
<Segment>Top</Segment>
<Segment>Bottom</Segment>
</Segments>
).scryClass('sd-segment');
segmentOne
.textContent
.should.equal('Top');
segmentTwo
.textContent
.should.equal('Bottom');
});
it('renders expected number of children', () => {
const [component] = render(
<Segments>
<Segment>Top</Segment>
<Segment>Middle</Segment>
<Segment>Bottom</Segment>
</Segments>
).scryClass('sd-segments');
expect(
component.querySelectorAll('.sd-segment').length
).to.equal(3);
});
});
|
import React from 'react';
import {Segment, Segments} from 'stardust';
describe('Segments', () => {
it('should render children', () => {
const [segmentOne, segmentTwo] = render(
<Segments>
<Segment>Top</Segment>
<Segment>Bottom</Segment>
</Segments>
).scryClass('sd-segment');
segmentOne
.textContent
.should.equal('Top');
segmentTwo
.textContent
.should.equal('Bottom');
});
it('renders expected number of children', () => {
render(
<Segments>
<Segment>Top</Segment>
<Segment>Middle</Segment>
<Segment>Bottom</Segment>
</Segments>
)
.scryClass('sd-segment')
.should.have.a.lengthOf(3);
});
});
|
Make use of chai's lengthOf assertion and simplify test
|
Make use of chai's lengthOf assertion and simplify test
|
JavaScript
|
mit
|
Semantic-Org/Semantic-UI-React,jamiehill/stardust,vageeshb/Semantic-UI-React,Semantic-Org/Semantic-UI-React,jcarbo/stardust,ben174/Semantic-UI-React,mohammed88/Semantic-UI-React,clemensw/stardust,koenvg/Semantic-UI-React,aabustamante/Semantic-UI-React,ben174/Semantic-UI-React,Rohanhacker/Semantic-UI-React,koenvg/Semantic-UI-React,vageeshb/Semantic-UI-React,Rohanhacker/Semantic-UI-React,aabustamante/Semantic-UI-React,aabustamante/Semantic-UI-React,clemensw/stardust,mohammed88/Semantic-UI-React
|
3fcff5769179d8b784f10206d8de1c7184843a11
|
background.js
|
background.js
|
(function() {
'use strict';
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('index.html', {
innerBounds: {
width: 960,
height: 600
},
state: 'maximized'
});
});
}());
|
(function() {
'use strict';
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('index.html', {
innerBounds: {
width: 960,
height: 600,
minWidth: 960,
minHeight: 600
},
state: 'maximized'
});
});
}());
|
Add minWidth/Height to Chrome app
|
Add minWidth/Height to Chrome app
|
JavaScript
|
mit
|
nathan/pixie,nathan/pixie,videophonegeek/pixie,videophonegeek/pixie
|
113b5c54802d572ed6d72d7380f5c28dc58760b3
|
background.js
|
background.js
|
(function(window){
window.ITCheck = window.ITCheck || {};
// Get things rolling
chrome.alarms.onAlarm.addListener(ITCheck.getUnreadThreadCount);
chrome.runtime.onStartup.addListener(function () {
chrome.alarms.create("updater", { "periodInMinutes": 1 });
});
chrome.runtime.onInstalled.addListener(function(details) {
chrome.alarms.create("updater", { "periodInMinutes": 1 });
});
// Update number on navigate to a new thread
chrome.webNavigation.onCompleted.addListener(function (details) {
getUnreadThreads(null);
},{url: [{hostSuffix: 'ivorytower.com', pathPrefix: '/IvoryTower/ForumThread.aspx'}]});
})(window);
|
(function(window){
window.ITCheck = window.ITCheck || {};
// Get things rolling
chrome.alarms.onAlarm.addListener(ITCheck.getUnreadThreadCount);
chrome.runtime.onStartup.addListener(function () {
chrome.alarms.create("updater", { "periodInMinutes": 1 });
});
chrome.runtime.onInstalled.addListener(function(details) {
chrome.alarms.create("updater", { "periodInMinutes": 1 });
});
// Update number on navigate to a new thread
chrome.webNavigation.onCompleted.addListener(function (details) {
ITCheck.getUnreadThreadCount(null);
},{url: [{hostSuffix: 'ivorytower.com', pathPrefix: '/IvoryTower/ForumThread.aspx'}]});
})(window);
|
Fix error with navigating to new page
|
Fix error with navigating to new page
|
JavaScript
|
mit
|
CodyJung/itcheck,CodyJung/itcheck
|
36313a2f3350a8af341ca8b427b851b7697d1657
|
models/core/AbuseReport.js
|
models/core/AbuseReport.js
|
// Abuse reports
//
'use strict';
const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;
module.exports = function (N, collectionName) {
let AbuseReport = new Schema({
// _id of reported content
src_id: Schema.ObjectId,
// Content type (FORUM_POST, BLOG_ENTRY, ...)
type: String,
// Report text
text: String,
// User _id
from: Schema.ObjectId
},
{
versionKey: false
});
N.wire.on('init:models', function emit_init_AbuseReport() {
return N.wire.emit('init:models.' + collectionName, AbuseReport);
});
N.wire.on('init:models.' + collectionName, function init_model_AbuseReport(schema) {
N.models[collectionName] = Mongoose.model(collectionName, schema);
});
};
|
// Abuse reports
//
'use strict';
const Mongoose = require('mongoose');
const Schema = Mongoose.Schema;
module.exports = function (N, collectionName) {
let AbuseReport = new Schema({
// _id of reported content
src_id: Schema.ObjectId,
// Content type (FORUM_POST, BLOG_ENTRY, ...)
type: String,
// Report text
text: String,
// Parser options
params_ref: Schema.ObjectId,
// User _id
from: Schema.ObjectId
},
{
versionKey: false
});
N.wire.on('init:models', function emit_init_AbuseReport() {
return N.wire.emit('init:models.' + collectionName, AbuseReport);
});
N.wire.on('init:models.' + collectionName, function init_model_AbuseReport(schema) {
N.models[collectionName] = Mongoose.model(collectionName, schema);
});
};
|
Add parser options to abuse reports
|
Add parser options to abuse reports
|
JavaScript
|
mit
|
nodeca/nodeca.core,nodeca/nodeca.core
|
b14b5c49a76a81fc92c36ba3e2ca0c7c59274cb3
|
modules/components/View.js
|
modules/components/View.js
|
import { createComponent } from 'react-fela'
const View = props => ({
display: props.hidden && 'none',
zIndex: props.zIndex,
position: 'fixed',
top: 0,
left: 0,
bottom: 0,
right: 0
})
export default createComponent(View)
|
import { createComponent } from 'react-fela'
const View = props => ({
display: props.hidden ? 'none' : 'flex',
zIndex: props.zIndex,
position: 'fixed',
top: 0,
left: 0,
bottom: 0,
right: 0
})
export default createComponent(View)
|
Add flex display to view by default
|
Add flex display to view by default
|
JavaScript
|
mit
|
rofrischmann/kilvin
|
55d795f8fbb1d51c9b91c9d56a352fd56becf529
|
index.js
|
index.js
|
module.exports = function stringReplaceAsync(
string,
searchValue,
replaceValue
) {
try {
if (typeof replaceValue === "function") {
// Step 1: Call native `replace` one time to acquire arguments for
// `replaceValue` function
// Step 2: Collect all return values in an array
// Step 3: Run `Promise.all` on collected values to resolve them
// Step 4: Call native `replace` the second time, replacing substrings
// with resolved values in order of occurance!
var promises = [];
String.prototype.replace.call(string, searchValue, function () {
promises.push(replaceValue.apply(undefined, arguments));
return "";
});
return Promise.all(promises).then(function (values) {
return String.prototype.replace.call(string, searchValue, function () {
return values.shift();
});
});
} else {
return Promise.resolve(
String.prototype.replace.call(string, searchValue, replaceValue)
);
}
} catch (error) {
return Promise.reject(error);
}
};
|
module.exports = function stringReplaceAsync(
string,
searchValue,
replaceValue
) {
try {
if (typeof replaceValue === "function") {
// 1. Run fake pass of `replace`, collect values from `replaceValue` calls
// 2. Resolve them with `Promise.all`
// 3. Run `replace` with resolved values
var values = [];
String.prototype.replace.call(string, searchValue, function () {
values.push(replaceValue.apply(undefined, arguments));
return "";
});
return Promise.all(values).then(function (resolvedValues) {
return String.prototype.replace.call(string, searchValue, function () {
return resolvedValues.shift();
});
});
} else {
return Promise.resolve(
String.prototype.replace.call(string, searchValue, replaceValue)
);
}
} catch (error) {
return Promise.reject(error);
}
};
|
Clarify the code a bit
|
Clarify the code a bit
|
JavaScript
|
mit
|
dsblv/string-replace-async
|
b634cda9d411859bcce4d15b9c9a55143ecc7265
|
src/Reporter.js
|
src/Reporter.js
|
// cavy-cli reporter class.
export default class CavyReporter {
// Internal: Creates a websocket connection to the cavy-cli server.
onStart() {
const url = 'ws://127.0.0.1:8082/';
this.ws = new WebSocket(url);
}
// Internal: Send report to cavy-cli over the websocket connection.
onFinish(report) {
// WebSocket.readyState 1 means the web socket connection is OPEN.
if (this.ws.readyState == 1) {
try {
this.ws.send(JSON.stringify(report));
console.log('Cavy test report successfully sent to cavy-cli');
} catch (e) {
console.group('Error sending test results');
console.warn(e.message);
console.groupEnd();
}
} else {
// If cavy-cli is not running, let people know in a friendly way
const message = "Skipping sending test report to cavy-cli - if you'd " +
'like information on how to set up cavy-cli, check out the README ' +
'https://github.com/pixielabs/cavy-cli';
console.log(message);
}
}
}
|
// Internal: CavyReporter is responsible for sending the test results to
// the CLI.
export default class CavyReporter {
// Internal: Creates a websocket connection to the cavy-cli server.
onStart() {
const url = 'ws://127.0.0.1:8082/';
this.ws = new WebSocket(url);
}
// Internal: Send report to cavy-cli over the websocket connection.
onFinish(report) {
// WebSocket.readyState 1 means the web socket connection is OPEN.
if (this.ws.readyState == 1) {
try {
this.ws.send(JSON.stringify(report));
console.log('Cavy test report successfully sent to cavy-cli');
} catch (e) {
console.group('Error sending test results');
console.warn(e.message);
console.groupEnd();
}
} else {
// If cavy-cli is not running, let people know in a friendly way
const message = "Skipping sending test report to cavy-cli - if you'd " +
'like information on how to set up cavy-cli, check out the README ' +
'https://github.com/pixielabs/cavy-cli';
console.log(message);
}
}
}
|
Improve top level class description
|
Improve top level class description
|
JavaScript
|
mit
|
pixielabs/cavy
|
71083a50a6cc900edb272dded2c3578ee5065d2d
|
index.js
|
index.js
|
require('./lib/metro-transit')
// Create the handler that responds to the Alexa Request.
exports.handler = function (event, context) {
// Create an instance of the MetroTransit skill.
var dcMetro = new MetroTransit();
dcMetro.execute(event, context);
};
|
var MetroTransit = require('./lib/metro-transit');
// Create the handler that responds to the Alexa Request.
exports.handler = function (event, context) {
MetroTransit.execute(event, context);
};
|
Update driver file for new module interfaces
|
Update driver file for new module interfaces
|
JavaScript
|
mit
|
pmyers88/dc-metro-echo
|
27e8daf7bf9ab4363314a5af41d9eb5ea4de9fdb
|
src/atoms/TextComponent/index.js
|
src/atoms/TextComponent/index.js
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import styles from './text_component.module.scss';
function setWeight( { semibold, light } ) {
if ( semibold ) return styles.semibold;
if ( light ) return styles.light;
return styles.regular;
}
function TextComponent( props ) {
const {
tag,
children,
type,
className,
} = props;
return React.createElement(
tag,
{ className: classnames(
styles[`typography-${type}`],
setWeight( props ),
className
) },
[ ...children ]
);
}
TextComponent.propTypes = {
/**
* You can use any html element text tag
*/
tag: PropTypes.string,
/**
* determines typography class
*/
type: PropTypes.number,
/**
* Font weight: 300
*/
light: PropTypes.bool,
/**
* Font weight: 400
*/
regular: PropTypes.bool,
/**
* Font weight: 600
*/
semibold: PropTypes.bool,
/**
* adds class name to class set
*/
className: PropTypes.string
};
TextComponent.defaultProps = {
tag: 'p',
type: 6
};
export default TextComponent;
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import styles from './text_component.module.scss';
function setWeight( { semibold, light } ) {
if ( semibold ) return styles.semibold;
if ( light ) return styles.light;
return styles.regular;
}
function TextComponent( props ) {
const {
tag,
children,
type,
className,
} = props;
const kids = typeof(children.type) === "function" ? children.type( children.props ) : [ ...children ];
return React.createElement(
tag,
{ className: classnames(
styles[`typography-${type}`],
setWeight( props ),
className
) },
kids
);
}
TextComponent.propTypes = {
/**
* You can use any html element text tag
*/
tag: PropTypes.string,
/**
* determines typography class
*/
type: PropTypes.number,
/**
* Font weight: 300
*/
light: PropTypes.bool,
/**
* Font weight: 400
*/
regular: PropTypes.bool,
/**
* Font weight: 600
*/
semibold: PropTypes.bool,
/**
* adds class name to class set
*/
className: PropTypes.string
};
TextComponent.defaultProps = {
tag: 'p',
type: 6
};
export default TextComponent;
|
Update Text Component to allow React components to render as child
|
Update Text Component to allow React components to render as child
|
JavaScript
|
mit
|
policygenius/athenaeum,policygenius/athenaeum,policygenius/athenaeum
|
4077314ce800a011121a04828df4da2163604a81
|
index.js
|
index.js
|
'use strict';
var R = require('ramda');
var isEmptyObj = R.pipe(R.keys, R.isEmpty);
function ModelRenderer(model) {
this.modelName = model.modelName;
this.attrs = model.attrs;
}
function attrToString(key, value) {
var output = '- ' + key;
if (R.has('primaryKey', value)) {
output += ' (primaryKey)';
}
return output;
}
ModelRenderer.prototype.toJSON = function toJSON() {
return this;
};
ModelRenderer.prototype.toString = function toString() {
var output = this.modelName;
if (!isEmptyObj(this.attrs)) {
output += ':\n';
output += R.join('\n', R.map(R.apply(attrToString), R.toPairs(this.attrs)));
}
return output;
};
module.exports = ModelRenderer;
|
'use strict';
var R = require('ramda');
var isEmptyObj = R.pipe(R.keys, R.isEmpty);
function ModelRenderer(model) {
this.modelName = model.modelName;
this.attrs = model.attrs;
}
function attrToString(key, value) {
var output = '- ' + key;
if (R.has('primaryKey', value)) {
output += ' (primaryKey)';
}
return output;
}
ModelRenderer.prototype.toJSON = function toJSON() {
return R.mapObj(R.identity, this);
};
ModelRenderer.prototype.toString = function toString() {
var output = this.modelName;
if (!isEmptyObj(this.attrs)) {
output += ':\n';
output += R.join('\n', R.map(R.apply(attrToString), R.toPairs(this.attrs)));
}
return output;
};
module.exports = ModelRenderer;
|
Create plain object in toJSON method
|
Create plain object in toJSON method
Standard deep equality doesn't seem to fail because it doesn't check for
types (i.e. constructor). However, the deep equality that chai uses
takes that into account and seems like a good idea to remove the
prototype in the object to be used for JSON output.
|
JavaScript
|
mit
|
jcollado/modella-render-docs
|
c1a83e68a97eb797d81e900271262840631b5467
|
index.js
|
index.js
|
var app = require('./server/routes');
var server = app.listen(3000, function() {
console.log('Listening on port %d', server.address().port);
});
|
process.title = 'Feedback-App';
var app = require('./server/routes');
var server = app.listen(3000, function() {
console.log('Listening on port %d', server.address().port);
});
/**
* Shutdown the server process
*
* @param {String} signal Signal to send, such as 'SIGINT' or 'SIGHUP'
*/
var close = function(signal) {
console.log('Server shutting down');
process.kill(process.pid, signal);
};
process.stdin.resume();
// Attach event listeners
process.on('SIGINT', function() {
close('SIGINT');
});
process.on('SIGHUP', function() {
close('SIGHUP');
});
process.on('SIGTERM', function() {
close('SIGTERM');
});
|
Add shutdown notification and process title
|
Add shutdown notification and process title
|
JavaScript
|
mit
|
maskedcoder/feedback-app,maskedcoder/feedback-app
|
eeb6e25ba97d0dae3fb1c8ab6a8aec892da25ad3
|
js/util.js
|
js/util.js
|
/**
* Searches the first loaded style sheet for an @keyframes animation by name.
* FYI: If you use "to" or "from" they'll get converted to percentage values, so use them for manipulating rules.
* Source (Optimized for flapper): http://jsfiddle.net/russelluresti/RHhBz/3/.
**/
function findKeyframesRule(name) {
var stylesheet = document.styleSheets[0];
for (var i = 0; i < stylesheet.cssRules.length; i++) {
var cssRule = stylesheet.cssRules[i];
if (cssRule.name == name) return cssRule;
}
return null;
}
/**
* Searches the first loaded style sheet for a CSS rule by name.
**/
function findCSSRule(name) {
var stylesheet = document.styleSheets[0];
console.log("Stylesheet: " + stylesheet);
for (var i = 0; i < stylesheet.cssRules.length; i++) {
var cssRule = stylesheet.cssRules[i];
console.log(`cssRule(${i}): ${cssRule.selectorText}`)
if (cssRule.selectorText == name) {
console.log("Found it");
return cssRule;
}
}
return null;
}
|
/**
* Searches the first loaded style sheet for an @keyframes animation by name.
* FYI: If you use "to" or "from" they'll get converted to percentage values, so use them for manipulating rules.
* Source (Optimized for flapper): http://jsfiddle.net/russelluresti/RHhBz/3/.
**/
function findKeyframesRule(name) {
for (var x = 0; x < document.styleSheets.length; x++) {
var stylesheet = document.styleSheets[x];
for (var i = 0; i < stylesheet.cssRules.length; i++) {
var rule = stylesheet.cssRules[i];
if (rule.name == name) {
return rule;
}
}
}
return null;
}
/**
* Searches the first loaded style sheet for a CSS rule by name.
**/
function findCSSRule(name) {
for (var x = 0; x < document.styleSheets.length; x++) {
var stylesheet = document.styleSheets[x];
for (var i = 0; i < stylesheet.cssRules.length; i++) {
var rule = stylesheet.cssRules[i];
if (rule.selectorText == name) {
return rule;
}
}
}
return null;
}
|
Fix uBlock Origin breaking flapper by injecting CSS stylesheet
|
Fix uBlock Origin breaking flapper by injecting CSS stylesheet
|
JavaScript
|
mpl-2.0
|
ryanwarsaw/flapper,ryanwarsaw/flapper
|
b91384ff9e6adb7d00afb166bb18e1a55e4d7286
|
index.js
|
index.js
|
'use strict';
const semver = require('semver');
const fetch = require('node-fetch');
const url = require('url');
module.exports = pkg => {
if (typeof pkg === 'string') {
pkg = {
name: pkg
}
}
if (!pkg || !pkg.name) {
throw new Error('You must provide a package name');
}
pkg.version = pkg.version || '*';
if (!semver.validRange(pkg.version)) {
throw new Error('That is not a valid package version range');
}
pkg.registry = pkg.registry || 'http://registry.npmjs.com/';
return fetch(url.resolve(pkg.registry, pkg.name))
.then(response => response.json())
.then(data => semver.maxSatisfying(Object.keys(data.versions || {}), pkg.version))
.catch(err => { throw new Error(err); });
}
|
'use strict';
const semver = require('semver');
const fetch = require('node-fetch');
const url = require('url');
module.exports = pkg => {
if (typeof pkg === 'string') {
pkg = {
name: pkg
}
}
if (!pkg || !pkg.name) {
throw new Error('You must provide a package name');
}
pkg.version = pkg.version || '*';
if (!semver.validRange(pkg.version)) {
throw new Error('That is not a valid package version range');
}
pkg.registry = pkg.registry || 'http://registry.npmjs.com/';
return fetch(url.resolve(pkg.registry, pkg.name))
.then(response => response.json())
.then(data => {
let v = semver.maxSatisfying(Object.keys(data.versions || {}), pkg.version);
return (pkg.full) ? data.versions[v] : v;
})
.catch(err => { throw new Error(err); });
}
|
Add 'full' option to get all package details not just version number.
|
Add 'full' option to get all package details not just version number.
|
JavaScript
|
mit
|
sillero/registry-resolve
|
9fe321c8a3f4da36196ac115987c4e7db6642f75
|
index.js
|
index.js
|
var _ = require('underscore');
var utils = require('./lib/utils');
var middleware = require('./lib/middleware');
var fixture = require('./lib/fixture');
var service = require('./lib/service');
var transform = require('./lib/transform');
var view = require('./lib/view');
/**
* Reads in route and service definitions from JSON and configures
* express routes with the appropriate middleware for each.
* @module router
*/
module.exports = function(app, routes, services){
_.each(routes, function(methods, route){
_.each(methods, function(config, method){
app[method](route, utils.loadStack(
config,
middleware,
fixture,
service.bind(null, services),
transform,
view
));
});
});
};
|
require('es6-promise').polyfill();
var _ = require('lodash');
var utils = require('./lib/utils');
/**
* Reads in route and service definitions from JSON and configures
* express routes with the appropriate middleware for each.
* @module router
* @param {object} app - an Express instance
* @param {object} routes - a routes config
* @param {object} services - a services config
*/
module.exports = function(app, routes, services){
_.each(routes, function(methods, route){
_.each(methods, function(configs, method){
app[method.toLowerCase()](route, utils.loadStack(configs, services));
});
});
};
|
Update reducto module to work with new config schema.
|
Update reducto module to work with new config schema.
|
JavaScript
|
mit
|
michaelleeallen/reducto
|
f0c62f3c90f96a29736d5715dc4fdb8f15549ed6
|
lib/react/loading-progress.js
|
lib/react/loading-progress.js
|
'use babel'
import {React} from 'react-for-atom'
export default React.createClass({
propTypes: {
readyCount: React.PropTypes.number,
totalCount: React.PropTypes.number
},
render () {
if (isNaN(this.props.readyCount) || isNaN(this.props.totalCount)) {
return <span />
} else {
return (
<div className='tv-loading-progress' ref='tooltip' onMouseOver={this._onHover}>
<span className='inline-block text-smaller text-subtle'>
Reading {this.props.readyCount} of {this.props.totalCount} notes
</span>
<span className='icon icon-info' />
<progress className='inline-block' max={this.props.totalCount} value={this.props.readyCount} />
</div>)
}
},
_onHover () {
atom.notifications.addInfo('Reading files', {
description: 'This is necesary to populate the search index. It is only necessary the first time, the notes will be cached for next session.',
dismissible: true
})
}
})
|
'use babel'
import {React} from 'react-for-atom'
export default React.createClass({
propTypes: {
readyCount: React.PropTypes.number,
totalCount: React.PropTypes.number
},
render () {
if (isNaN(this.props.readyCount) || isNaN(this.props.totalCount)) {
return <span />
} else {
return (
<div className='tv-loading-progress'>
<span className='inline-block text-smaller text-subtle'>
Reading {this.props.readyCount} of {this.props.totalCount} notes
</span>
<span className='icon icon-info' ref='tooltip' onMouseOver={this._onHover} />
<progress className='inline-block' max={this.props.totalCount} value={this.props.readyCount} />
</div>)
}
},
_onHover () {
atom.notifications.addInfo('Reading files', {
description: 'This is necesary to populate the search index. It is only necessary the first time, the notes will be cached for next session.',
dismissible: true
})
}
})
|
Move tooltip to only show on hovering info-icon
|
:art: Move tooltip to only show on hovering info-icon
|
JavaScript
|
mit
|
viddo/atom-textual-velocity,viddo/atom-textual-velocity,onezoomin/atom-textual-velocity
|
69a4e2ba1022b3215255d13b15d5b35063f46386
|
index.js
|
index.js
|
const request = require('request');
const fs = require('fs');
const thenify = require('thenify').withCallback;
const download = (url, file, callback) => {
const stream = fs.createWriteStream(file);
stream.on('finish', () => {
callback(null, file);
});
stream.on('error', error => {
callback(error);
});
request
.get(url)
.pipe(stream);
};
module.exports = thenify(download);
|
const request = require('request');
const fs = require('fs');
const thenify = require('thenify').withCallback;
const download = (url, file, callback) => {
const stream = fs.createWriteStream(file);
stream.on('finish', () => {
callback(null, file);
});
stream.on('error', error => {
callback(error);
});
request
.get(url)
.on('error', error => {
callback(error);
})
.pipe(stream);
};
module.exports = thenify(download);
|
Handle errors that occure during request
|
Handle errors that occure during request
|
JavaScript
|
mit
|
demohi/co-download
|
1e55d5399e6c6a34f49fa992982fb3b79ad3f9e7
|
index.js
|
index.js
|
module.exports = function (protocol) {
protocol = protocol || 'http';
var url = 'http://vicopo.selfbuild.fr/search/';
switch (protocol) {
case 'https':
url = 'https://www.selfbuild.fr/vicopo/search/';
break;
case 'http':
break;
default:
throw new Error(protocol + ' protocol not supported');
}
var transport = require(protocol);
return function (search, done) {
transport.get(url + encodeURIComponent(search), function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
var result;
try {
result = JSON.parse(data);
} catch(e) {
return done(new Error('Cannot parse Vicopo answear:\n' + e + '\n' + data));
}
if (result.cities) {
done(null, result.cities);
} else {
done(new Error('The answear should contains a cities list:\n' + data));
}
});
})
.on('error', done);
};
};
|
module.exports = function (protocol) {
protocol = protocol || 'http';
var url = 'http://vicopo.selfbuild.fr/search/';
switch (protocol) {
case 'https':
url = 'https://www.selfbuild.fr/vicopo/search/';
break;
case 'http':
break;
default:
throw new Error(protocol + ' protocol not supported');
}
var transport = require(protocol);
return function (search, done) {
transport.get(url + encodeURIComponent(search), function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
var result;
try {
result = JSON.parse(data);
} catch(e) {
return done(new Error('Cannot parse Vicopo answear:\n' + e + '\n' + data));
}
if (result.cities) {
done(null, result.cities);
} else {
done(new Error('The answear should contains a cities list:\n' + data));
}
});
})
.on('error', done);
};
};
|
Make it compatible with older node.js
|
Make it compatible with older node.js
|
JavaScript
|
mit
|
kylekatarnls/vicopo,kylekatarnls/vicopo,kylekatarnls/vicopo,kylekatarnls/vicopo,kylekatarnls/vicopo
|
60689993d75db32701e99f7eb9110ce8eff54610
|
index.js
|
index.js
|
"use strict";
// modified from https://github.com/es-shims/es6-shim
var keys = require('object-keys');
var isObject = function (obj) {
return typeof obj !== 'undefined' && obj !== null;
};
var assignShim = function assign(target, source) {
var s, i, props;
if (!isObject(target)) { throw new TypeError('target must be an object'); }
target = Object(target);
for (s = 1; s < arguments.length; ++s) {
source = arguments[s];
if (!isObject(source)) { throw new TypeError('source ' + s + ' must be an object'); }
props = keys(Object(source));
for (i = 0; i < props.length; ++i) {
target[props[i]] = source[props[i]];
}
}
return target;
};
assignShim.shim = function shimObjectAssign() {
if (!Object.assign) {
Object.assign = assignShim;
}
return Object.assign || assignShim;
};
module.exports = assignShim;
|
"use strict";
// modified from https://github.com/es-shims/es6-shim
var keys = Object.keys || require('object-keys');
var isObject = function (obj) {
return typeof obj !== 'undefined' && obj !== null;
};
var assignShim = function assign(target, source) {
var s, i, props;
if (!isObject(target)) { throw new TypeError('target must be an object'); }
target = Object(target);
for (s = 1; s < arguments.length; ++s) {
source = arguments[s];
if (!isObject(source)) { throw new TypeError('source ' + s + ' must be an object'); }
props = keys(Object(source));
for (i = 0; i < props.length; ++i) {
target[props[i]] = source[props[i]];
}
}
return target;
};
assignShim.shim = function shimObjectAssign() {
if (!Object.assign) {
Object.assign = assignShim;
}
return Object.assign || assignShim;
};
module.exports = assignShim;
|
Use the native Object.keys if it's available.
|
Use the native Object.keys if it's available.
|
JavaScript
|
mit
|
ljharb/object.assign,es-shims/object.assign,reggi/object.assign
|
45bd22346dbd3cfeaedea1a3061ff5cc50b3e9a0
|
index.js
|
index.js
|
"use strict";
module.exports = {
rules: {
"sort-object-props": function(context) {
var ignoreCase = context.options[0].ignoreCase;
var ignoreMethods = context.options[0].ignoreMethods;
var MSG = "Property names in object literals should be sorted";
return {
"ObjectExpression": function(node) {
node.properties.reduce(function(lastProp, prop) {
if (ignoreMethods &&
prop.value.type === "FunctionExpression") {
return prop;
}
var lastPropId, propId;
if (prop.key.type === "Identifier") {
lastPropId = lastProp.key.name;
propId = prop.key.name;
} else if (prop.key.type === "Literal") {
lastPropId = lastProp.key.value;
propId = prop.key.value;
}
if (ignoreCase) {
if (propId == null)
console.log(prop);
lastPropId = lastPropId.toLowerCase();
propId = propId.toLowerCase();
}
if (propId < lastPropId) {
context.report(prop, MSG);
}
return prop;
}, node.properties[0]);
}
};
}
},
rulesConfig: {
"sort-object-props": [ 1, { ignoreCase: true, ignoreMethods: false } ]
}
};
|
"use strict";
module.exports = {
rules: {
"sort-object-props": function(context) {
var caseSensitive = context.options[0].caseSensitive;
var ignoreMethods = context.options[0].ignoreMethods;
var MSG = "Property names in object literals should be sorted";
return {
"ObjectExpression": function(node) {
node.properties.reduce(function(lastProp, prop) {
if (ignoreMethods &&
prop.value.type === "FunctionExpression") {
return prop;
}
var lastPropId, propId;
if (prop.key.type === "Identifier") {
lastPropId = lastProp.key.name;
propId = prop.key.name;
} else if (prop.key.type === "Literal") {
lastPropId = lastProp.key.value;
propId = prop.key.value;
}
if (caseSensitive) {
lastPropId = lastPropId.toLowerCase();
propId = propId.toLowerCase();
}
if (propId < lastPropId) {
context.report(prop, MSG);
}
return prop;
}, node.properties[0]);
}
};
}
},
rulesConfig: {
"sort-object-props": [ 1, { caseSensitive: false, ignoreMethods: false } ]
}
};
|
Rename option to caseSensitive to avoid double negation
|
Rename option to caseSensitive to avoid double negation
|
JavaScript
|
mit
|
shane-tomlinson/eslint-plugin-sorting,jacobrask/eslint-plugin-sorting
|
b2414317832618de90a46fa0115e0903a749b4de
|
index.js
|
index.js
|
// Enable promise error logging
require('promise/lib/rejection-tracking').enable();
var express = require('express');
var app = express();
var certificate = require('./src/certificate')
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(request, response) {
var promise = certificate.getCertificationData();
certificate.getCertificationData().then(function(data) {
responseData = {
certInfo: JSON.stringify(data),
runDate: new Date().toDateString()
}
if(request.headers['content-type'] == 'application/json') {
response.json(responseData);
} else {
response.render('pages/index', responseData);
}
});
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
|
// Enable promise error logging
require('promise/lib/rejection-tracking').enable();
var express = require('express');
var app = express();
var certificate = require('./src/certificate')
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(request, response) {
certificate.getCertificationData().then(function(data) {
responseData = {
certInfo: JSON.stringify(data),
runDate: new Date().toDateString()
}
if(request.headers['content-type'] == 'application/json') {
response.json(responseData);
} else {
response.render('pages/index', responseData);
}
});
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
|
Remove redundant call to getCertificationData()
|
Remove redundant call to getCertificationData()
This was fetching certificate info from every site twice.
|
JavaScript
|
mit
|
JensDebergh/certificate-dashboard,JensDebergh/certificate-dashboard,JensDebergh/certificate-dashboard
|
9260ae76dba730555f71ea839d4c42cfe9d5393e
|
index.js
|
index.js
|
var express = require("express"),
mongoose = require("mongoose"),
app = express();
mongoose.connect("mongodb://localhost/test", function (err) {
if (!err) {
console.log("Connected to MongoDB");
} else {
console.error(err);
}
});
app.get("/", function (req, res) {
res.send("Hey buddy!");
});
var Thing = require("./model");
app.get("/:name", function (req, res) {
Thing.find({ name: req.params.name }, function (err, t) {
if (t.length < 1) {
var thing = new Thing();
thing.name = req.params.name;
thing.save();
res.send("Created a new thing with name " + thing.name);
} else {
res.send(t);
}
});
});
app.listen(3000);
|
var express = require("express"),
mongoose = require("mongoose"),
app = express();
mongoose.connect("mongodb://localhost/test", function (err) {
if (!err) {
console.log("Connected to MongoDB");
} else {
console.error(err);
}
});
app.get("/", function (req, res) {
res.send("Hey buddy!");
});
var Thing = require("./model");
app.get("/:name", function (req, res) {
Thing.find({ name: req.params.name }, function (err, t) {
if (t.length < 1) {
var thing = new Thing();
thing.name = req.params.name;
thing.save(function(err) {
if (err) {
res.send(500);
} else {
res.send("Created a new thing with name " + thing.name);
}
});
} else {
res.send(t);
}
});
});
app.listen(3000);
|
Use callbacks to ensure save is completed before returning a result
|
Use callbacks to ensure save is completed before returning a result
|
JavaScript
|
mit
|
shippableSamples/sample_node_mongo,pranaypareek/sample_node_mongo,samples-org-read/sample_node_mongo,a-murphy/sample_node_mongo,navneetjo/sample_node_mongo,buildsample/sample_node_mongo,a-murphy/sample_node_mongo,vidyar/sample_node_mongo
|
5203a7c14acab3253aff2494f4bbacaa945ff3c3
|
src/controllers/post-controller.js
|
src/controllers/post-controller.js
|
import BlogPost from '../database/models/blog-post';
import log from '../log';
const PUBLIC_API_ATTRIBUTES = [
'id',
'title',
'link',
'description',
'date_updated',
'date_published'
];
const DEFAULT_ORDER = [
['date_published', 'DESC']
];
export function getAll() {
return new Promise((resolve, reject) => {
BlogPost.findAll({
attributes: PUBLIC_API_ATTRIBUTES,
order: DEFAULT_ORDER,
raw: true
})
.then(resolve)
.catch(error => {
log.error({ error }, 'Error getting list of all posts');
reject(error);
});
});
}
export function getById(id) {
return new Promise((resolve, reject) => {
BlogPost.findOne({
attributes: PUBLIC_API_ATTRIBUTES,
where: { id },
raw: true
})
.then(resolve)
.catch(error => {
log.error({ error }, 'Error getting blog post by id');
reject(error);
});
});
}
export function getPage(pageNumber, pageSize) {
return new Promise((resolve, reject) => {
BlogPost.findAll({
attributes: PUBLIC_API_ATTRIBUTES,
order: DEFAULT_ORDER,
offset: pageNumber * pageSize,
limit: pageSize,
raw: true
})
.then(resolve)
.catch(error => {
log.error({ error }, 'Error getting page of posts');
reject(error);
});
});
}
|
import BlogPost from '../database/models/blog-post';
import log from '../log';
const PUBLIC_API_ATTRIBUTES = [
'id',
'title',
'link',
'description',
'date_updated',
'date_published',
'author_id'
];
const DEFAULT_ORDER = [
['date_published', 'DESC']
];
export function getAll() {
return new Promise((resolve, reject) => {
BlogPost.findAll({
attributes: PUBLIC_API_ATTRIBUTES,
order: DEFAULT_ORDER,
raw: true
})
.then(resolve)
.catch(error => {
log.error({ error }, 'Error getting list of all posts');
reject(error);
});
});
}
export function getById(id) {
return new Promise((resolve, reject) => {
BlogPost.findOne({
attributes: PUBLIC_API_ATTRIBUTES,
where: { id },
raw: true
})
.then(resolve)
.catch(error => {
log.error({ error }, 'Error getting blog post by id');
reject(error);
});
});
}
export function getPage(pageNumber, pageSize) {
return new Promise((resolve, reject) => {
BlogPost.findAll({
attributes: PUBLIC_API_ATTRIBUTES,
order: DEFAULT_ORDER,
offset: pageNumber * pageSize,
limit: pageSize,
raw: true
})
.then(resolve)
.catch(error => {
log.error({ error }, 'Error getting page of posts');
reject(error);
});
});
}
|
Allow author_id on public API
|
Allow author_id on public API
|
JavaScript
|
mit
|
csblogs/api-server,csblogs/api-server
|
24792e355734a207bd1c51a43b557867da459cce
|
src/js/directives/participate.js
|
src/js/directives/participate.js
|
'use strict';
angular.module('Teem')
.directive('participate', function() {
return {
controller: [
'$scope', '$element', '$attrs', 'SessionSvc', '$timeout', 'CommunitiesSvc',
function($scope, $element, $attrs, SessionSvc, $timeout, CommunitiesSvc) {
$scope.participateCopyOn = $attrs.participateCopyOn;
$scope.participateCopyOff = $attrs.participateCopyOff;
$element.on('click', function($event) {
SessionSvc.loginRequired($scope, function() {
if ($scope.community.toggleParticipant) {
$timeout(function() {
$scope.community.toggleParticipant();
});
} else {
CommunitiesSvc.find($scope.community.id).then(function(community) {
$timeout(function() {
community.toggleParticipant();
angular.extend($scope.community, community);
});
});
}
});
$event.stopPropagation();
});
}],
templateUrl: 'participate.html'
};
});
|
'use strict';
angular.module('Teem')
.directive('participate', function() {
return {
controller: [
'$scope', '$element', '$attrs', 'SessionSvc', '$timeout', 'CommunitiesSvc',
function($scope, $element, $attrs, SessionSvc, $timeout, CommunitiesSvc) {
$scope.participateCopyOn = $attrs.participateCopyOn;
$scope.participateCopyOff = $attrs.participateCopyOff;
$element.on('click', function($event) {
SessionSvc.loginRequired($scope, function() {
if ($scope.community.toggleParticipant) {
$timeout(function() {
$scope.community.toggleParticipant();
});
} else {
CommunitiesSvc.find($scope.community.id).then(function(community) {
$timeout(function() {
community.toggleParticipant();
$scope.community.participants = community.participants;
});
});
}
});
$event.stopPropagation();
});
}],
templateUrl: 'participate.html'
};
});
|
Copy only the participants list instead of using .extend()
|
Copy only the participants list instead of using .extend()
|
JavaScript
|
agpl-3.0
|
P2Pvalue/teem,P2Pvalue/teem,Grasia/teem,Grasia/teem,Grasia/teem,P2Pvalue/pear2pear,P2Pvalue/pear2pear,P2Pvalue/teem
|
ad7a8ebb6994ad425c8429a052ef0abc91365ada
|
index.js
|
index.js
|
var path = require('path');
var fs = require('fs');
var mime = require('mime');
var pattern = function (file, included) {
return {pattern: file, included: included, served: true, watched: false};
};
var framework = function (files) {
files.push(pattern(path.join(__dirname, 'framework.js'), false));
files.push(pattern(path.join(__dirname, 'runner.js'), true));
};
var createProxyForDirectory = function (directory) {
return function (request, response, next) {
var filePath = path.join(directory, request.url.replace('/base/', ''));
fs.exists(filePath, function (exists) {
if (exists) {
response.writeHead(200, {
"Content-Type": mime.lookup(filePath)
});
fs.createReadStream(filePath).pipe(response);
} else {
next();
}
});
}
};
var proxyBowerComponentsMiddlewareFactory = function () {
return createProxyForDirectory('bower_components');
};
var proxyNodeModulesMiddlewareFactory = function () {
return createProxyForDirectory('node_modules');
};
framework.$inject = ['config.files'];
module.exports = {
'framework:web-components': ['factory', framework],
'middleware:proxy-bower-components': ['factory', proxyBowerComponentsMiddlewareFactory],
'middleware:proxy-node-modules': ['factory', proxyNodeModulesMiddlewareFactory]
};
|
var path = require('path');
var fs = require('fs');
var mime = require('mime');
var pattern = function (file, included) {
return {pattern: file, included: included, served: true, watched: false};
};
var framework = function (files) {
files.push(pattern(path.join(__dirname, 'framework.js'), false));
files.push(pattern(path.join(__dirname, 'runner.js'), true));
};
var createProxyForDirectory = function (directory) {
return function (request, response, next) {
if (!request.url.startsWith('/base/')) {
var filePath = path.join(directory, request.url);
fs.exists(filePath, function (exists) {
if (exists) {
response.writeHead(200, {
"Content-Type": mime.lookup(filePath)
});
fs.createReadStream(filePath).pipe(response);
} else {
next();
}
});
} else {
next();
}
}
};
var proxyBowerComponentsMiddlewareFactory = function () {
return createProxyForDirectory('bower_components');
};
var proxyNodeModulesMiddlewareFactory = function () {
return createProxyForDirectory('node_modules');
};
framework.$inject = ['config.files'];
module.exports = {
'framework:web-components': ['factory', framework],
'middleware:proxy-bower-components': ['factory', proxyBowerComponentsMiddlewareFactory],
'middleware:proxy-node-modules': ['factory', proxyNodeModulesMiddlewareFactory]
};
|
Fix proxy incorrectly proxying requests for files a level deeper than intended
|
Fix proxy incorrectly proxying requests for files a level deeper than intended
|
JavaScript
|
mit
|
jimsimon/karma-web-components,jimsimon/karma-web-components
|
e5ffafb53bdce4fdfca12680175adb6858dacd75
|
index.js
|
index.js
|
var Xray = require('x-ray'),
fs = require('fs')
var x = Xray()
var baseURLPrefix = "http://www.thaischool.in.th/sitemap.php?school_area=&province_id=",
baseURLSuffix = "&schooltype_id=&txtsearch=",
provinces = require('./provinces.json')
function appendObject(obj){
var resultFile = fs.readFileSync('./result/result.json')
var result = JSON.parse(resultFile)
result.push(obj)
var resultJSON = JSON.stringify(result)
fs.writeFileSync('./result/result.json', resultJSON)
}
provinces.map(function(province){
x(baseURLPrefix + province['id'] + baseURLSuffix, 'form', ['td > a'])
.paginate('a[title="Next"]@href')(function(err, arr) {
appendObject({
province: province['name'],
schools: arr
})
})
})
|
var Xray = require('x-ray'),
fs = require('fs')
var x = Xray()
var baseURLPrefix = "http://www.thaischool.in.th/sitemap.php?school_area=&province_id=",
baseURLSuffix = "&schooltype_id=&txtsearch=",
provinces = require('./provinces.json')
function appendObject(obj){
var resultFile = fs.readFileSync('./result/result.json')
var result = JSON.parse(resultFile)
result.push(obj)
var resultJSON = JSON.stringify(result)
fs.writeFileSync('./result/result.json', resultJSON)
}
function appendArray(arr){
var resultFile = fs.readFileSync('./result/schools.json')
var result = JSON.parse(resultFile)
Array.prototype.push.apply(result, obj);
var resultJSON = JSON.stringify(result)
fs.writeFileSync('./result/schools.json', resultJSON)
}
provinces.map(function(province){
x(baseURLPrefix + province['id'] + baseURLSuffix, 'form', ['td > a'])
.paginate('a[title="Next"]@href')(function(err, arr) {
appendObject({
province: province['name'],
schools: arr
})
appendArray(arr)
})
})
|
Save result as array of school name only
|
Save result as array of school name only
|
JavaScript
|
isc
|
lukyth/thailand-school-collector
|
b4f454f3701fd304e9775affc51234847d376918
|
src/Plugin.js
|
src/Plugin.js
|
/**
* Initialize Pattern builder plugin.
*/
;(function ($) {
var pluginName = 'patternMaker',
pluginDefaults = {
palette: []
};
/**
* Constructor.
*
* @param {dom} element Drawing board
* @param {object} options Plugin options
*/
function Plugin(element, options)
{
this.element = element;
this.$element = $(element);
this.options = $.extend({}, pluginDefaults, options);
this.init();
}
/**
* Launch it
*/
Plugin.prototype.init = function()
{
this._palette = new RandomColor(this.options.palette);
};
/**
* Attach to jQuery plugin namespace.
*
* @param {object} options Initialization options
*/
$.fn[pluginName] = function(options) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName);
new Plugin(this, options);
}
});
};
})(jQuery);
|
/**
* Initialize Pattern builder plugin.
*/
;(function () {
var pluginName = 'patternMaker',
pluginDefaults = {
palette: []
};
/**
* Constructor.
*
* @param {dom} element Drawing board
* @param {object} options Plugin options
*/
function Plugin(element, options)
{
this.element = element;
this.$element = $(element);
this.options = $.extend({}, pluginDefaults, options);
this.init();
}
/**
* Launch it
*/
Plugin.prototype.init = function()
{
this._palette = new RandomColor(this.options.palette);
};
/**
* Attach to jQuery plugin namespace.
*
* @param {object} options Initialization options
*/
jQuery.fn[pluginName] = function(options) {
return this.each(function () {
if (!jQuery.data(this, "plugin_" + pluginName)) {
jQuery.data(this, "plugin_" + pluginName);
new Plugin(this, options);
}
});
};
})();
|
Use jQuery directly instead of $ in plugin
|
Use jQuery directly instead of $ in plugin
|
JavaScript
|
mit
|
ivannpaz/PatternMaker
|
f9bb15454fe3d0ec86893fbda7f08d0860cffe6b
|
gulp/watch.js
|
gulp/watch.js
|
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
gulp.task('browser-sync', function () {
browserSync({
server: {
baseDir: './dist'
}
});
});
gulp.task('watch', ['build', 'browser-sync'], function () {
gulp.watch('./app/**/*.html', ['html']);
gulp.watch('./app/**/*.js', ['js']);
gulp.watch('./dist/**/*').on('change', function () {
browserSync.reload();
});
});
|
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
gulp.task('watch', ['build', 'serve'], function () {
gulp.watch('./app/**/*.html', ['html']);
gulp.watch('./app/**/*.js', ['js']);
gulp.watch('./dist/**/*').on('change', function () {
browserSync.reload();
});
});
gulp.task('serve', function () {
browserSync({
server: {
baseDir: './dist'
}
});
});
|
Rename browser-sync task to serve.
|
Rename browser-sync task to serve.
|
JavaScript
|
mpl-2.0
|
learnfwd/learnfwd.com,learnfwd/learnfwd.com,learnfwd/learnfwd.com
|
bc6673cefccf4db6b83742eaafe338d22b2d7310
|
cla_frontend/assets-src/javascripts/modules/moj.Conditional.js
|
cla_frontend/assets-src/javascripts/modules/moj.Conditional.js
|
(function () {
'use strict';
moj.Modules.Conditional = {
el: '.js-Conditional',
init: function () {
var _this = this;
this.cacheEls();
this.bindEvents();
this.$conditionals.each(function () {
_this.toggleEl($(this));
});
},
bindEvents: function () {
var _this = this;
// set focused selector to parent label
this.$conditionals
.on('change', function () {
_this.toggleEl($(this));
// trigger a deselect event
$('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect');
})
.on('deselect', function () {
_this.toggleEl($(this));
});
},
cacheEls: function () {
this.$conditionals = $(this.el);
},
toggleEl: function (el) {
var $el = el,
$conditionalEl = $('#' + $el.data('conditionalEl'));
if ($el.data('conditionalEl')) {
$el.attr('aria-control', $el.data('conditionalEl'));
if($el.is(':checked')){
$conditionalEl.show();
$conditionalEl.attr('aria-expanded', 'true').attr('aria-hidden', 'false');
} else {
$conditionalEl.hide();
$conditionalEl.attr('aria-expanded', 'false').attr('aria-hidden', 'true');
}
}
}
};
}());
|
/* globals _ */
(function () {
'use strict';
moj.Modules.Conditional = {
el: '.js-Conditional',
init: function () {
_.bindAll(this, 'render');
this.cacheEls();
this.bindEvents();
},
bindEvents: function () {
this.$conditionals.on('change deselect', this.toggle);
moj.Events.on('render', this.render);
},
cacheEls: function () {
this.$conditionals = $(this.el);
},
render: function () {
this.$conditionals.each(this.toggle);
},
toggle: function (e) {
var $el = $(this),
$conditionalEl = $('#' + $el.data('conditionalEl'));
// trigger a deselect event if a change event occured
if (e.type === 'change') {
$('input[name="' + $el.attr('name') + '"]').not($el).trigger('deselect');
}
// if a conditional element has been set, run the checks
if ($el.data('conditionalEl')) {
$el.attr('aria-control', $el.data('conditionalEl'));
// if checked show/hide the extra content
if($el.is(':checked')){
$conditionalEl.show();
$conditionalEl.attr('aria-expanded', 'true').attr('aria-hidden', 'false');
} else {
$conditionalEl.hide();
$conditionalEl.attr('aria-expanded', 'false').attr('aria-hidden', 'true');
}
}
}
};
}());
|
Add module for conditional content
|
Add module for conditional content
|
JavaScript
|
mit
|
ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend
|
3c357c4c8043c7867e1abc0a2397735e6a8e6089
|
src/reducers/general.js
|
src/reducers/general.js
|
import * as types from "../actions/types";
import { chooseDisplayComponentFromURL } from "../actions/navigation";
import { hasExtension, getExtension } from "../util/extensions";
/* the store for cross-cutting state -- that is, state
not limited to <App>
*/
const getFirstPageToDisplay = () => {
if (hasExtension("entryPage")) {
return getExtension("entryPage");
}
return chooseDisplayComponentFromURL(window.location.pathname);
};
const general = (state = {
displayComponent: getFirstPageToDisplay(),
errorMessage: undefined,
pathname: window.location.pathname // keep a copy of what the app "thinks" the pathname is
}, action) => {
switch (action.type) {
case types.PAGE_CHANGE:
return Object.assign({}, state, {
pathname: action.path,
displayComponent: action.displayComponent,
errorMessage: action.errorMessage
});
case types.UPDATE_PATHNAME:
return Object.assign({}, state, {
pathname: action.pathname
});
default:
return state;
}
};
export default general;
|
import * as types from "../actions/types";
import { chooseDisplayComponentFromURL } from "../actions/navigation";
import { hasExtension, getExtension } from "../util/extensions";
/* the store for cross-cutting state -- that is, state
not limited to <App>
*/
const getFirstPageToDisplay = () => {
if (hasExtension("entryPage")) {
return getExtension("entryPage");
}
return chooseDisplayComponentFromURL(window.location.pathname);
};
const general = (state = {
displayComponent: getFirstPageToDisplay(),
errorMessage: undefined,
pathname: window.location.pathname // keep a copy of what the app "thinks" the pathname is
}, action) => {
switch (action.type) {
case types.PAGE_CHANGE:
const stateUpdate = {
displayComponent: action.displayComponent,
errorMessage: action.errorMessage
};
if (action.path) {
stateUpdate.pathname = action.path;
}
return Object.assign({}, state, stateUpdate);
case types.UPDATE_PATHNAME:
return Object.assign({}, state, {
pathname: action.pathname
});
default:
return state;
}
};
export default general;
|
Fix bugs in redux state of pathname
|
Fix bugs in redux state of pathname
We were getting bugs due to the redux state of `general.pathname` set to `undefined` when it shouldn't be as a result of `PAGE_CHANGE` actions with no `action.path` data. This resulted in incorrect API requests and the display of results which didn't match the URL.
|
JavaScript
|
agpl-3.0
|
nextstrain/auspice,nextstrain/auspice,nextstrain/auspice
|
80cfc47a1c60e66836fdd7660c944f64c5d4c0c4
|
src/time-segments.js
|
src/time-segments.js
|
var TimeSegments = {
// Segment an array of events by scale
segment(events, scale, options) {
scale = scale || 'weeks';
options = options || {};
_.defaults(options, {
startAttribute: 'start',
endAttribute: 'end'
});
events = _.chain(events).clone().sortBy(options.startAttribute).value();
var segments = {};
// Clone our events so that we're not modifying the original
// objects. Loop through them, inserting the events into the
// corresponding segments
_.each(_.clone(events), function(e) {
// Calculate the duration of the event; this determines
// how many segments it will be in
var startMoment = moment.utc(e[options.startAttribute]).startOf(scale);
var endMoment = moment.utc(e[options.endAttribute]).endOf(scale).add(1, 'milliseconds');
// For each duration, add the event to the corresponding segment
var segmentStart;
for(var i = 0, duration = endMoment.diff(startMoment, scale); i < duration; i++) {
segmentStart = moment.utc(startMoment).add(i, scale).unix();
if (!segments[segmentStart]) { segments[segmentStart] = []; }
segments[segmentStart].push(_.clone(e));
}
});
return segments;
}
};
export default TimeSegments;
|
var TimeSegments = {
// Segment an array of events by scale
segment(events, scale, options) {
scale = scale || 'weeks';
options = options || {};
_.defaults(options, {
startAttribute: 'start',
endAttribute: 'end'
});
events = _.chain(events).clone().sortBy(options.startAttribute).value();
var segments = {};
// Clone our events so that we're not modifying the original
// objects. Loop through them, inserting the events into the
// corresponding segments
_.each(_.clone(events), e => {
// Calculate the duration of the event; this determines
// how many segments it will be in
var startMoment = moment.utc(e[options.startAttribute]).startOf(scale);
var endMoment = moment.utc(e[options.endAttribute]).endOf(scale).add(1, 'milliseconds');
// For each duration, add the event to the corresponding segment
var segmentStart;
for(var i = 0, duration = endMoment.diff(startMoment, scale); i < duration; i++) {
segmentStart = moment.utc(startMoment).add(i, scale).unix();
if (!segments[segmentStart]) { segments[segmentStart] = []; }
segments[segmentStart].push(_.clone(e));
}
});
return segments;
}
};
export default TimeSegments;
|
Refactor source to use more ES6 syntax.
|
Refactor source to use more ES6 syntax.
|
JavaScript
|
mit
|
jmeas/time-segments.js
|
6ee08bdbccec11791f9946d692174739176ffa8e
|
src/common.js
|
src/common.js
|
export const formatURL = (url) => (
url.length ? url.replace(/^https?:\/\//, '') : ''
)
export const getTitle = (data) => (
data.about && data.about.name
? data.about.name
: data.totalItems + " Entries"
)
export default {
getTitle, formatURL
}
|
export const formatURL = (url) => (
url.length ? url.replace(/^https?:\/\//, '') : ''
)
export const getTitle = (data) => (
data.about && (data.about.name || data.about['@id'])
? data.about.name || data.about['@id']
: data.totalItems + " Entries"
)
export default {
getTitle, formatURL
}
|
Fix title of resources without name
|
Fix title of resources without name
|
JavaScript
|
apache-2.0
|
literarymachine/crg-ui
|
089247c62a36e4a2e0c149001bd06ccf562ebc4e
|
src/config.js
|
src/config.js
|
export let baseUrl = 'http://rosettastack.com';
export let sites = [{
name: 'Programmers',
slug: 'programmers',
seUrl: 'http://programmers.stackexchange.com/',
langs: ['en', 'fr'],
db: 'localhost/programmers',
}, {
name: 'Coffee',
slug: 'coffee',
seUrl: 'http://coffee.stackexchange.com/',
langs: ['en', 'fr'],
db: 'localhost/coffee',
}, {
name: 'Server Fault',
slug: 'serverfault',
seUrl: 'http://serverfault.com/',
langs: ['en', 'fr'],
db: 'localhost/serverfault',
}, {
name: 'Super User',
slug: 'superuser',
seUrl: 'http://superuser.com/',
langs: ['en', 'fr'],
db: 'localhost/superuser',
}, {
name: 'Stack Overflow',
slug: 'stackoverflow',
seUrl: 'http://stackoverflow.com/',
langs: ['en', 'fr'],
db: 'localhost/programmers',
}, {
name: 'Android',
slug: 'android',
seUrl: 'http://android.stackexchange.com/',
langs: ['en', 'fr'],
db: 'localhost/android',
}, {
name: 'Tor',
slug: 'tor',
seUrl: 'http://tor.stackexchange.com/',
langs: ['en', 'fr'],
db: 'localhost/tor',
}];
|
export let baseUrl = 'http://rosettastack.com';
export let sites = [{
name: 'Programmers',
slug: 'programmers',
seUrl: 'http://programmers.stackexchange.com/',
langs: ['en', 'fr'],
db: 'localhost/programmers',
}, {
name: 'Coffee',
slug: 'coffee',
seUrl: 'http://coffee.stackexchange.com/',
langs: ['en', 'fr'],
db: 'localhost/coffee',
}, {
name: 'Server Fault',
slug: 'serverfault',
seUrl: 'http://serverfault.com/',
langs: ['en', 'fr'],
db: 'localhost/serverfault',
}, {
name: 'Super User',
slug: 'superuser',
seUrl: 'http://superuser.com/',
langs: ['en', 'fr'],
db: 'localhost/superuser',
}, {
name: 'Stack Overflow',
slug: 'stackoverflow',
seUrl: 'http://stackoverflow.com/',
langs: ['en', 'fr'],
db: 'localhost/stackoverflow',
}, {
name: 'Android',
slug: 'android',
seUrl: 'http://android.stackexchange.com/',
langs: ['en', 'fr'],
db: 'localhost/android',
}, {
name: 'Tor',
slug: 'tor',
seUrl: 'http://tor.stackexchange.com/',
langs: ['en', 'fr'],
db: 'localhost/tor',
}];
|
Fix db ref for SO
|
Fix db ref for SO
|
JavaScript
|
mpl-2.0
|
bbondy/stack-view,bbondy/stack-view,bbondy/stack-view
|
34f2f7d42346f564e4846435fb35ba19d3b5f8f8
|
src/Native/Spruce.js
|
src/Native/Spruce.js
|
// make is a function that takes an instance of the
// elm runtime
// returns an object where:
// keys are names to be accessed in pure Elm
// values are either functions or values
function make(elm) {
// If Native isn't already bound on elm, bind it!
elm.Native = elm.Native || {}
// then the same for our module
elm.Native.Spruce = elm.Native.Spruce || {}
// `values` is where the object returned by make ends up internally
// return if it's already set, since you only want one definition of
// values for speed reasons
if (elm.Native.Spruce.values) return elm.Native.Spruce.values
// return the object of your module's stuff!
return elm.Native.Spruce.values = {
listen(address, server) {
console.log(address, server)
return server
}
}
}
// setup code for Spruce
// Elm.Native.Spruce should be an object with
// a property `make` which is specified above
Elm.Native.Spruce = {};
Elm.Native.Spruce.make = make;
|
var _binary_koan$elm_spruce$Native_Spruce = function() {
function listen(address, program) {
console.log(address)
return program
}
return {
toHtml: F2(listen)
}
}()
|
Update native module to 0.18 style
|
Update native module to 0.18 style
|
JavaScript
|
mit
|
binary-koan/elm-spruce
|
3769ce9f09658a3748209193b6dc29e68c9160dd
|
src/getter.js
|
src/getter.js
|
"use strict";
var
// redis = require("redis"),
// client = redis.createClient(),
_ = require("underscore"),
Fetcher = require("l2b-price-fetchers");
module.exports.getBookDetails = function (isbn, cb) {
var f = new Fetcher();
f.fetch(
{vendor: "foyles", isbn: isbn },
function (err, data) {
if (err) { return cb(err); }
var returnData = _.pick(data, "isbn", "authors", "title");
cb(null, returnData);
}
);
};
|
"use strict";
var
// redis = require("redis"),
// client = redis.createClient(),
_ = require("underscore"),
Fetcher = require("l2b-price-fetchers");
function getBookDetails (isbn, cb) {
fetchFromScrapers(
{vendor: "foyles", isbn: isbn },
function (err, results) {
if (err) { return cb(err); }
var returnData = _.pick(results, "isbn", "authors", "title");
cb(null, returnData);
}
);
}
function fetchFromScrapers (options, cb) {
var f = new Fetcher();
f.fetch(
options,
function (err, data) {
if (err) { return cb(err); }
cb(null, data);
}
);
}
module.exports = {
getBookDetails: getBookDetails,
};
|
Split up the book detail fetching into smaller chunks
|
Split up the book detail fetching into smaller chunks
|
JavaScript
|
agpl-3.0
|
OpenBookPrices/openbookprices-api
|
1daccbf90de27ae2b3a6ac29d448cd78664a0f87
|
src/server.js
|
src/server.js
|
'use strict'
let fs = require('fs')
let dotenv = require('dotenv')
let express = require('express')
let session = require('express-session')
let cookieParser = require('cookie-parser')
let bodyParser = require('body-parser')
let morgan = require('morgan')
let routes = require('./api/routes')
dotenv.config({silent: true})
let port = process.env.PORT || 3000
let host = process.env.HOST || 'localhost'
let app = express()
app.use(morgan('dev'))
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
// Load routes
routes(app)
let server = app.listen(port, () => {
console.log('Mission Control listening at http://%s:%s', host, port)
})
module.exports = server
|
'use strict'
let fs = require('fs')
let dotenv = require('dotenv')
let express = require('express')
let session = require('express-session')
let cookieParser = require('cookie-parser')
let bodyParser = require('body-parser')
let morgan = require('morgan')
let routes = require('./api/routes')
let extensions = require('./extensions/registry')
dotenv.config({silent: true})
let port = process.env.PORT || 3000
let host = process.env.HOST || 'localhost'
let app = express()
app.use(morgan('dev'))
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.locals.ext = extensions.load()
// Load routes
routes(app)
let server = app.listen(port, () => {
console.log('Mission Control listening at http://%s:%s', host, port)
console.log('app locals', app.locals.ext)
})
module.exports = server
|
Load extensions into express app
|
Load extensions into express app
|
JavaScript
|
mit
|
shrunyan/mc-core,shrunyan/mc-core,andyfleming/mc-core,andyfleming/mc-core
|
a0f35993688c09fdb7fa49ec67070384e4a79ee2
|
test/brushModes-test.js
|
test/brushModes-test.js
|
var vows = require('vows'),
assert = require('assert'),
events = require('events'),
load = require('./load'),
suite = vows.describe('brushModes');
function d3Parcoords() {
var promise = new(events.EventEmitter);
load(function(d3) {
promise.emit('success', d3.parcoords());
});
return promise;
}
suite.addBatch({
'd3.parcoords': {
'has by default': {
topic: d3Parcoords(),
'three brush modes': function(pc) {
assert.strictEqual(pc.brushModes().length, 3);
},
'the brush mode "None"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("None"), -1);
},
'the brush mode "1D-axes"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("1D-axes"), -1);
},
'the brush mode "2D-strums"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("2D-strums"), -1);
}
},
}
});
suite.export(module);
|
var vows = require('vows'),
assert = require('assert'),
events = require('events'),
load = require('./load'),
suite = vows.describe('brushModes');
function d3Parcoords() {
var promise = new(events.EventEmitter);
load(function(d3) {
promise.emit('success', d3.parcoords());
});
return promise;
}
suite.addBatch({
'd3.parcoords': {
'has by default': {
topic: d3Parcoords(),
'four brush modes': function(pc) {
assert.strictEqual(pc.brushModes().length, 4);
},
'the brush mode "None"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("None"), -1);
},
'the brush mode "1D-axes"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("1D-axes"), -1);
},
'the brush mode "2D-strums"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("2D-strums"), -1);
},
'the brush mode "angular"': function(pc) {
assert.notStrictEqual(pc.brushModes().indexOf("angular"), -1);
}
},
}
});
suite.export(module);
|
Add angular brush mode to test
|
Add angular brush mode to test
|
JavaScript
|
bsd-3-clause
|
bbroeksema/parallel-coordinates,julianheinrich/parallel-coordinates,julianheinrich/parallel-coordinates,bbroeksema/parallel-coordinates
|
4ec97ddac5fcc131705e5047f4e6057c2abc5cdc
|
package.js
|
package.js
|
Package.describe({
summary: "Login service for VKontakte accounts (https://vk.com)",
version: "0.1.4",
git: "https://github.com/alexpods/meteor-accounts-vk",
name: "mrt:accounts-vk"
});
Package.on_use(function(api) {
api.versionsFrom('METEOR@0.9.0');
api.use('accounts-base', ['client', 'server']);
api.imply('accounts-base', ['client', 'server']);
api.use('accounts-oauth', ['client', 'server']);
api.imply('accounts-oauth', ['client', 'server']);
api.use('oauth2', ['client', 'server']);
api.use('oauth', ['client', 'server']);
api.use('http', ['server']);
api.use('underscore', 'server');
api.use('random', 'client');
api.use('service-configuration', ['client', 'server']);
api.use('templating', 'client');
api.add_files("lib/accounts_vk.js");
api.add_files('lib/vk_client.js', 'client');
api.add_files('lib/vk_server.js', 'server');
api.export('VK');
api.add_files(['lib/vk_configure.html', 'lib/vk_configure.js', 'lib/vk_styles.css'], 'client');
});
|
Package.describe({
summary: "Login service for VKontakte accounts (https://vk.com)",
version: "0.2.0",
git: "https://github.com/alexpods/meteor-accounts-vk",
name: "mrt:accounts-vk"
});
Package.on_use(function(api) {
api.versionsFrom('METEOR@0.9.0');
api.use('accounts-base', ['client', 'server']);
api.imply('accounts-base', ['client', 'server']);
api.use('accounts-oauth', ['client', 'server']);
api.imply('accounts-oauth', ['client', 'server']);
api.use('service-configuration', ['client', 'server']);
api.imply('service-configuration', ['client', 'server']);
api.use('oauth2', ['client', 'server']);
api.use('oauth', ['client', 'server']);
api.use('http', ['server']);
api.use('underscore', 'server');
api.use('random', 'client');
api.use('templating', 'client');
api.add_files("lib/accounts_vk.js");
api.add_files('lib/vk_client.js', 'client');
api.add_files('lib/vk_server.js', 'server');
api.export('VK');
api.add_files(['lib/vk_configure.html', 'lib/vk_configure.js', 'lib/vk_styles.css'], 'client');
});
|
Add 'imply' service-configuration. Increment version number to 0.2.0
|
UPD: Add 'imply' service-configuration. Increment version number to 0.2.0
|
JavaScript
|
mit
|
newsiberian/meteor-accounts-vk,newsiberian/meteor-accounts-vk,alexpods/meteor-accounts-vk,alexpods/meteor-accounts-vk
|
b64a51e136a4bcce3d0c2d5292c53d85c2d0e7de
|
test/data/testrunner.js
|
test/data/testrunner.js
|
jQuery.noConflict(); // Allow the test to run with other libs or jQuery's.
|
jQuery.noConflict(); // Allow the test to run with other libs or jQuery's.
// load testswarm agent
(function() {
var url = window.location.search;
url = decodeURIComponent( url.slice( url.indexOf("swarmURL=") + 9 ) );
if ( !url || url.indexOf("http") !== 0 ) {
return;
}
document.write("<scr" + "ipt src='http://testswarm.com/js/inject.js?" + (new Date).getTime() + "'></scr" + "ipt>");
})();
|
Handle auto-running of the TestSwarm injection script in the test suite.
|
Handle auto-running of the TestSwarm injection script in the test suite.
|
JavaScript
|
mit
|
hoorayimhelping/jquery,eburgos/jquery,isaacs/jquery,gnarf/jquery,mislav/jquery,diracdeltas/jquery,sancao2/jquery,RubyLouvre/jquery,kpozin/jquery-nodom,chitranshi/jquery,hoorayimhelping/jquery,Karyotyper/jquery,demetr84/Jquery,demetr84/Jquery,dtjm/jquery,Karyotyper/jquery,jquery/jquery,npmcomponent/component-jquery,sancao2/jquery,fat/jquery,isaacs/jquery,mislav/jquery,ilyakharlamov/jquery-xul,praveen9102/Shazam,diracdeltas/jquery,jcutrell/jquery,kpozin/jquery-nodom,chitranshi/jquery,npmcomponent/component-jquery,sancao2/jquery,quiaro/request-agent,gnarf/jquery,Karyotyper/jquery,fat/jquery,praveen9102/Shazam,roytoo/jquery,RubyLouvre/jquery,roytoo/jquery,dtjm/jquery,eburgos/jquery,jquery/jquery,rwaldron/jquery,scottjehl/jquery,jquery/jquery,diracdeltas/jquery,roytoo/jquery,jcutrell/jquery,ilyakharlamov/jquery-xul,scottjehl/jquery,rwaldron/jquery,eburgos/jquery
|
2cded40e931866ecf95915ba49719609d1c591e9
|
test/middleware.spec.js
|
test/middleware.spec.js
|
import { createAuthMiddleware } from '../src'
describe('auth middleware', () => {
const middleware = createAuthMiddleware()
const nextHandler = middleware({})
const actionHandler = nextHandler()
test('it returns a function that handles store', () => {
expect(middleware).toBeInstanceOf(Function)
expect(middleware.length).toBe(1)
})
test('store handler returns function that handles next', () => {
expect(nextHandler).toBeInstanceOf(Function)
expect(nextHandler.length).toBe(1)
})
test('action handler returns a function that handles action', () => {
expect(actionHandler).toBeInstanceOf(Function)
expect(actionHandler.length).toBe(1)
})
})
|
import { createAuthMiddleware } from '../src'
describe('auth middleware', () => {
const middleware = createAuthMiddleware()
it('returns a function that handles {getState, dispatch}', () => {
expect(middleware).toBeInstanceOf(Function)
expect(middleware.length).toBe(1)
})
describe('store handler', () => {
it('returns function that handles next', () => {
const nextHandler = middleware({})
expect(nextHandler).toBeInstanceOf(Function)
expect(nextHandler.length).toBe(1)
})
})
describe('action handler', () => {
it('action handler returns a function that handles action', () => {
const nextHandler = middleware({})
const actionHandler = nextHandler()
expect(actionHandler).toBeInstanceOf(Function)
expect(actionHandler.length).toBe(1)
})
})
})
|
Use it instead of test. Small structure change
|
Use it instead of test. Small structure change
|
JavaScript
|
mit
|
jerelmiller/redux-simple-auth
|
ea146316b0f0d854a750ecb913b95df2705d1257
|
autoformat.js
|
autoformat.js
|
#!/usr/bin/env nodejs
// Autoformatter for Turing
const fs = require('fs'),
argv = require('minimist')(process.argv.slice(2), {boolean:true});
var files = argv._;
// Check for flags, and process them
var flags = argv.flags || null;
var format = require('./format.js')(flags);
console.log(argv)
/**
* Main procedure
*/
files.forEach(file => {
fs.readFile(file, 'utf8', (err, data) => {
var ext = (argv.e || argv.extension) || "";
var out = (argv.o || argv.out) || file + ext;
if (err) throw err;
data = format.format(data);
if (argv.s || argv.stdio) {
console.log(data);
} else {
fs.writeFile(out, data, err => {
if (err) throw err;
console.log(out + " has been saved");
});
}
});
});
|
#!/usr/bin/env nodejs
// Autoformatter for Turing
const fs = require('fs'),
argv = require('minimist')(process.argv.slice(2), {boolean:true});
var files = argv._;
// Check for flags, and process them
var flags = argv.flags || null;
var format = require('./format.js')(flags);
/**
* Main procedure
*/
files.forEach(file => {
fs.readFile(file, 'utf8', (err, data) => {
var ext = (argv.e || argv.extension) || "";
var out = (argv.o || argv.out) || file + ext;
if (err) throw err;
data = format.format(data);
if ((argv.e || argv.extension) || (argv.o || argv.out) || (argv.r || argv.replace)) {
fs.writeFile(out, data, err => {
if (err) throw err;
console.log(out + " has been saved");
});
} else {
console.log(data);
}
});
});
|
Change default output behaviour to output to STDIO
|
Change default output behaviour to output to STDIO
|
JavaScript
|
mit
|
tyxchen/turing-autoformat,tyxchen/turing-autoformat
|
d8d45721bd463e59645470604f18e82d5e98e636
|
src/Portal/Portal.js
|
src/Portal/Portal.js
|
import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
class Portal extends React.Component {
componentDidMount() {
this.nodeEl = document.createElement('div');
document.body.appendChild(this.nodeEl);
this.renderChildren(this.props);
}
componentWillUnmount() {
ReactDOM.unmountComponentAtNode(this.nodeEl);
document.body.removeChild(this.nodeEl);
}
componentWillReceiveProps(nextProps) {
this.renderChildren(nextProps);
}
renderChildren(props) {
let {children} = props;
if (children == null) {
children = <div />;
}
ReactDOM.render(children, this.nodeEl, this.props.onRender);
}
render() {
return null;
}
}
Portal.propTypes = {
children: PropTypes.node,
onRender: PropTypes.func
};
module.exports = Portal;
|
import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
class Portal extends React.Component {
componentDidMount() {
this.nodeEl = document.createElement('div');
document.body.appendChild(this.nodeEl);
this.renderChildren(this.props);
}
componentWillUnmount() {
ReactDOM.unmountComponentAtNode(this.nodeEl);
document.body.removeChild(this.nodeEl);
}
componentWillReceiveProps(nextProps) {
this.renderChildren(nextProps);
}
renderChildren(props) {
ReactDOM.render(props.children, this.nodeEl, props.onRender);
}
render() {
return null;
}
}
Portal.propTypes = {
children: PropTypes.node.isRequired,
onRender: PropTypes.func
};
module.exports = Portal;
|
Remove default rendered child element
|
Remove default rendered child element
|
JavaScript
|
apache-2.0
|
mesosphere/reactjs-components,mesosphere/reactjs-components
|
1039b0472ae8427539f1b1034b59596415e981fb
|
src/views/picker-views/base-picker-view.js
|
src/views/picker-views/base-picker-view.js
|
'use strict';
var BaseView = require('../base-view');
function BasePickerView() {
BaseView.apply(this, arguments);
this._initialize();
}
BasePickerView.prototype = Object.create(BaseView.prototype);
BasePickerView.prototype.constructor = BasePickerView;
BasePickerView.prototype._initialize = function () {
this.element = document.createElement('div');
this.element.className = 'braintree-dropin__picker-view';
this.element.setAttribute('tabindex', '0');
this.element.addEventListener('click', this._onSelect.bind(this), false);
this.element.addEventListener('keydown', function (event) {
if (event.which === 13) { this._onSelect(); }
}.bind(this));
};
BasePickerView.prototype._onSelect = function () {};
module.exports = BasePickerView;
|
'use strict';
var BaseView = require('../base-view');
function BasePickerView() {
BaseView.apply(this, arguments);
this._initialize();
}
BasePickerView.prototype = Object.create(BaseView.prototype);
BasePickerView.prototype.constructor = BasePickerView;
BasePickerView.prototype._initialize = function () {
this.element = document.createElement('div');
this.element.className = 'braintree-dropin__picker-view';
this.element.setAttribute('tabindex', '0');
this.element.addEventListener('click', this._onSelect.bind(this), false);
this.element.addEventListener('keydown', function (event) {
if (event.which === 13) { this._onSelect(); }
}.bind(this));
};
module.exports = BasePickerView;
|
Remove _onSelect noop from BasePickerView
|
Remove _onSelect noop from BasePickerView
|
JavaScript
|
mit
|
braintree/braintree-web-drop-in,braintree/braintree-web-drop-in,braintree/braintree-web-drop-in
|
7c9ec3264fcc0f6815028d793b8156d8af216ad0
|
test/helpers/file_helper_test.js
|
test/helpers/file_helper_test.js
|
import { expect } from '../spec_helper'
import jsdom from 'jsdom'
import {
getRestrictedSize,
// orientImage,
} from '../../src/helpers/file_helper'
function getDOMString() {
// 1x1 transparent gif
const src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='
const landscape = `<img class="landscape" src=${src} width=16 height=9 />`
return `<html><body>${landscape}</body></html>`
}
describe('file helpers', () => {
context('#getRestrictedSize', () => {
it('does not restrict the width and height', () => {
const { width, height } = getRestrictedSize(800, 600, 2560, 1440)
expect(width).to.equal(800)
expect(height).to.equal(600)
})
it('restricts the width and height', () => {
// The width/height are double maxWidth/maxHeight to keep ratios simple
const { width, height } = getRestrictedSize(5120, 2880, 2560, 1440)
expect(width).to.equal(2560)
expect(height).to.equal(1440)
})
})
context('#orientImage', () => {
const document = jsdom.jsdom(getDOMString())
const landscapeImage = document.body.querySelector('.landscape')
it('found the correct assets for testing', () => {
expect(landscapeImage.width).to.equal(16)
expect(landscapeImage.height).to.equal(9)
})
it('needs to test orienting of images')
it('needs to test processing of images')
})
})
|
import { expect } from '../spec_helper'
import { getRestrictedSize } from '../../src/helpers/file_helper'
describe('file helpers', () => {
context('#getRestrictedSize', () => {
it('does not restrict the width and height', () => {
const { width, height } = getRestrictedSize(800, 600, 2560, 1440)
expect(width).to.equal(800)
expect(height).to.equal(600)
})
it('restricts the width and height', () => {
// The width/height are double maxWidth/maxHeight to keep ratios simple
const { width, height } = getRestrictedSize(5120, 2880, 2560, 1440)
expect(width).to.equal(2560)
expect(height).to.equal(1440)
})
})
})
|
Remove tests around canvas objects
|
Remove tests around canvas objects
[jsdom doesn’t really handle the canvas element very well](https://github.com/tmpvar/jsdom#canvas). It just treats it just like a div. We can add the canvas package, but that requires a whole slew of other things to do deal with (namely Cairo) which seems like a maintenance nightmare on CI just for some basic tests. If we see problems with it later we can probably deal with it then.
|
JavaScript
|
mit
|
ello/webapp,ello/webapp,ello/webapp
|
142b39b54eb529386ff917c2a6e80ec74abece11
|
js/plugins.js
|
js/plugins.js
|
// http://unheap.com
$(function() {
$('.browsehappy').on('click', function() {
$(this).slideUp('fast');
});
});
|
// http://unheap.com
$(function() {
$('.browsehappy').click(function() {
$(this).slideUp();
});
});
|
Make browse happy slide up cleaner
|
Make browse happy slide up cleaner
|
JavaScript
|
mit
|
kennethwang14/VerticalRhythmDemo,kennethwang14/LostGridExample,kennethwang14/LostGridExample,kennethwang14/TypographyHandbook,kennethwang14/TypographyHandbook,corysimmons/boy,kennethwang14/VerticalRhythmDemo
|
da6b3fc1a9a3ba60dc02310f68d6e58fc109d1b9
|
generators/app/templates/app/scripts/main.js
|
generators/app/templates/app/scripts/main.js
|
import App from './app';
import 'babel-polyfill';
common.app = new App(common);
common.app.start();
|
import App from './app';
common.app = new App(common);
common.app.start();
|
Remove babel-polyfill import in man.js
|
Remove babel-polyfill import in man.js
|
JavaScript
|
mit
|
snphq/generator-sp,snphq/generator-sp,i-suhar/generator-sp,i-suhar/generator-sp,snphq/generator-sp,i-suhar/generator-sp
|
112b74dcbde73c4f35426c24ab51bb10287b9c63
|
karma.conf.js
|
karma.conf.js
|
// Karma configuration
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// testing frameworks to use
frameworks: ['mocha', 'chai', 'sinon'],
// list of files / patterns to load in the browser. order matters!
files: [
// angular source
'client/lib/angular/angular.js',
'client/lib/angular-route/angular-route.js',
'client/lib/angular-mocks/angular-mocks.js',
// our app code
'client/app/**/*.js',
// our spec files - in order of the README
'specs/client/authControllerSpec.js',
'specs/client/servicesSpec.js',
'specs/client/linksControllerSpec.js',
'specs/client/shortenControllerSpec.js',
'specs/client/routingSpec.js'
],
// test results reporter to use
reporters: ['nyan','unicorn'],
// start these browsers. PhantomJS will load up in the background
browsers: ['PhantomJS'],
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// if true, Karma exits after running the tests.
singleRun: true
});
};
|
// Karma configuration
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// testing frameworks to use
frameworks: ['mocha', 'chai', 'sinon'],
// list of files / patterns to load in the browser. order matters!
files: [
// angular source
'client/lib/angular/angular.js',
'client/lib/angular-route/angular-route.js',
'client/lib/angular-mocks/angular-mocks.js',
// our app code
'client/app/**/*.js',
// our spec files - in order of the README
'specs/client/authControllerSpec.js',
'specs/client/routingSpec.js'
],
// test results reporter to use
reporters: ['nyan','unicorn'],
// start these browsers. PhantomJS will load up in the background
browsers: ['PhantomJS'],
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// if true, Karma exits after running the tests.
singleRun: true
});
};
|
Remove untested files from karma
|
Remove untested files from karma
|
JavaScript
|
mit
|
gm758/Bolt,gm758/Bolt,elliotaplant/Bolt,thomasRhoffmann/Bolt,boisterousSplash/Bolt,thomasRhoffmann/Bolt,boisterousSplash/Bolt,elliotaplant/Bolt
|
466e870fc742981be4b178015042285717cdee12
|
test/index.js
|
test/index.js
|
var ACME = require( '..' )
var assert = require( 'assert' )
var nock = require( 'nock' )
suite( 'ACME', function() {
var client = new ACME({
baseUrl: 'https://api.example.com',
})
test( 'throws an error if baseUrl is not a string', function() {
assert.throws( function() { new ACME.Client({ baseUrl: 42 }) })
assert.throws( function() { new ACME.Client({ baseUrl: {} }) })
})
test( '#getDirectory()', function( next ) {
var payload = {
'new-authz': 'https://api.example.com/acme/new-authz',
'new-cert': 'https://api.example.com/acme/new-cert',
'new-reg': 'https://api.example.com/acme/new-reg',
'revoke-cert': 'https://api.example.com/acme/revoke-cert'
}
nock( 'https://api.example.com' )
.get( '/directory' )
.reply( 200, payload )
client.getDirectory( function( error, data ) {
assert.ifError( error )
assert.ok( data )
assert.deepStrictEqual( payload, data )
next()
})
})
})
|
var ACME = require( '..' )
var assert = require( 'assert' )
var nock = require( 'nock' )
var ACME_API_BASE_URL = 'https://api.example.com'
suite( 'ACME', function() {
var client = new ACME.Client({
baseUrl: ACME_API_BASE_URL,
})
test( 'throws an error if baseUrl is not a string', function() {
assert.throws( function() { new ACME.Client({ baseUrl: 42 }) })
assert.throws( function() { new ACME.Client({ baseUrl: {} }) })
})
test( '#getDirectory()', function( next ) {
var payload = {
'new-authz': ACME_API_BASE_URL + '/acme/new-authz',
'new-cert': ACME_API_BASE_URL + '/acme/new-cert',
'new-reg': ACME_API_BASE_URL + '/acme/new-reg',
'revoke-cert': ACME_API_BASE_URL + '/acme/revoke-cert'
}
nock( ACME_API_BASE_URL )
.get( '/directory' )
.reply( 200, payload )
client.getDirectory( function( error, data ) {
assert.ifError( error )
assert.ok( data )
assert.deepStrictEqual( payload, data )
next()
})
})
})
|
Update test: Add `ACME_API_BASE_URL` constant
|
Update test: Add `ACME_API_BASE_URL` constant
|
JavaScript
|
mit
|
jhermsmeier/node-acme-protocol
|
a544b1ae597692ebb60175cf0572376f7d609d90
|
test/index.js
|
test/index.js
|
var chai = require('chai');
var expect = chai.expect;
// var sinon = require('sinon');
var requestToContext = require('../src/requestToContext');
describe('requestToContext', function () {
it('Convert the req to the correct contect', function (done) {
console.log(requestToContext)
done();
});
});
|
'use strict';
var chai = require('chai');
var expect = chai.expect;
var requestToContext = require('../src/requestToContext');
describe('requestToContext', function () {
describe('Converts the request to the correct context', function () {
it('For get requests', function (done) {
var result = requestToContext({
method: 'get',
url: 'http://localhost:9090/?paths=[[%22genrelist%22,{%22from%22:0,%22to%22:5},%22titles%22,{%22from%22:0,%22to%22:5},%22name%22]]&method=get'
});
expect(result).to.deep.equal({
paths: [
[
'genrelist', {
from: 0,
to: 5
},
'titles', {
from: 0,
to: 5
},
'name'
]
],
method: 'get'
});
done();
});
it('For post requests', function (done) {
var result = requestToContext({
method: 'POST',
body: 'jsong={"jsonGraph":{"genrelist":{"0":{"titles":{"0":{"name":"jon"}}}}},"paths":[["genrelist",0,"titles",0,"name"]]}&method=set'
});
expect(result).to.deep.equal({
jsong: '{"jsonGraph":{"genrelist":{"0":{"titles":{"0":{"name":"jon"}}}}},"paths":[["genrelist",0,"titles",0,"name"]]}',
method: 'set'
});
done();
});
});
});
|
Add tests around requestToContext for get and post requests
|
Add tests around requestToContext for get and post requests
|
JavaScript
|
apache-2.0
|
krolow/falcor-express,jmnarloch/falcor-express,jontewks/falcor-express,Netflix/falcor-express
|
b5169369bea5ccdde34b214641f0c8eec09f64dd
|
lib/events.js
|
lib/events.js
|
/**
* Setup the user (DOM) event flow.
*
* @private
* @param {object} The moule instnace.
*/
module.exports = function (instance, template, options, dom, data) {
for (var event in template.events) {
for (var i = 0, l = template.events[event].length; i < l; ++i) {
handleEvent(instance, template, dom, data, event, template.events[event][i]);
}
}
};
function handleEvent (instance, template, dom, data, event, listener) {
// handle element config
if (listener.element) {
listener.selector = "[data-element='" + listener.element + "']";
delete listener.element;
}
var elms = dom.querySelectorAll(listener.selector || listener.sel);
if (elms) {
Array.from(elms).forEach(function (elm) {
elm.addEventListener(listener.on, function (domEvent) {
// dont prevent default browser actions
if (!listener.dontPrevent) {
domEvent.preventDefault();
}
instance.flow(event)[listener.end ? 'end' : 'write'](listener.noDomData ? {} : domEvent);
});
});
}
}
|
/**
* Setup the user (DOM) event flow.
*
* @private
* @param {object} The moule instnace.
*/
module.exports = function (instance, template, options, dom, data) {
for (var event in template.events) {
for (var i = 0, l = template.events[event].length; i < l; ++i) {
handleEvent(instance, template, dom, data, event, template.events[event][i]);
}
}
};
function handleEvent (instance, template, dom, data, event, listener) {
// handle element config
if (listener.element) {
listener.selector = "[data-element='" + listener.element + "']";
delete listener.element;
}
var elms = dom.querySelectorAll(listener.selector || listener.sel);
if (elms) {
Array.from(elms).forEach(function (elm) {
elm.addEventListener(listener.on, function (domEvent) {
// dont prevent default browser actions
if (!listener.dontPrevent) {
domEvent.preventDefault();
}
domEvent.domItem = elm;
instance.flow(event)[listener.end ? 'end' : 'write'](listener.noDomData ? {} : domEvent);
});
});
}
}
|
Append domItem to event data.
|
Append domItem to event data.
|
JavaScript
|
mit
|
adioo/view
|
50714f6b030bddce42d1e3f69be83cb4c9da4188
|
src/notebook/components/transforms/index.js
|
src/notebook/components/transforms/index.js
|
import { displayOrder, transforms } from 'transformime-react';
/**
* Thus begins our path for custom mimetypes and future extensions
*/
import PlotlyTransform from './plotly';
import GeoJSONTransform from './geojson';
const defaultDisplayOrder = displayOrder
.insert(0, PlotlyTransform.MIMETYPE)
.insert(0, GeoJSONTransform.MIMETYPE);
const defaultTransforms = transforms
.set(PlotlyTransform.MIMETYPE, PlotlyTransform)
.set(GeoJSONTransform.MIMETYPE, GeoJSONTransform);
export { defaultDisplayOrder, defaultTransforms };
|
import { displayOrder, transforms } from 'transformime-react';
/**
* Thus begins our path for custom mimetypes and future extensions
*/
import PlotlyTransform from './plotly';
import GeoJSONTransform from './geojson';
// Register custom transforms
const defaultTransforms = transforms
.set(PlotlyTransform.MIMETYPE, PlotlyTransform)
.set(GeoJSONTransform.MIMETYPE, GeoJSONTransform);
// Register our custom transforms as the most rich (front of List)
const defaultDisplayOrder = displayOrder
.insert(0, PlotlyTransform.MIMETYPE)
.insert(0, GeoJSONTransform.MIMETYPE);
export { defaultDisplayOrder, defaultTransforms };
|
Comment on custom transform registration
|
Comment on custom transform registration
|
JavaScript
|
bsd-3-clause
|
jdetle/nteract,0u812/nteract,jdetle/nteract,nteract/composition,captainsafia/nteract,rgbkrk/nteract,0u812/nteract,jdfreder/nteract,captainsafia/nteract,nteract/nteract,rgbkrk/nteract,nteract/nteract,temogen/nteract,temogen/nteract,temogen/nteract,jdfreder/nteract,jdetle/nteract,nteract/composition,nteract/nteract,rgbkrk/nteract,jdfreder/nteract,jdfreder/nteract,0u812/nteract,captainsafia/nteract,nteract/composition,0u812/nteract,rgbkrk/nteract,nteract/nteract,captainsafia/nteract,nteract/nteract,rgbkrk/nteract,jdetle/nteract
|
245e9614db9218ddd4f982ba4b007665ba3627b3
|
applications/desktop/src/main/auto-updater.js
|
applications/desktop/src/main/auto-updater.js
|
/* @flow strict */
import { autoUpdater } from "electron-updater";
export function initAutoUpdater() {
const log = require("electron-log");
log.transports.file.level = "info";
autoUpdater.logger = log;
autoUpdater.checkForUpdatesAndNotify();
}
|
/* @flow strict */
import { autoUpdater } from "electron-updater";
export function initAutoUpdater() {
if (process.env.NTERACT_DESKTOP_DISABLE_AUTO_UPDATE !== "1") {
const log = require("electron-log");
log.transports.file.level = "info";
autoUpdater.logger = log;
autoUpdater.checkForUpdatesAndNotify();
}
}
|
Allow environment variable NTERACT_DESKTOP_DISABLE_AUTO_UPDATE to disable auto-update.
|
Allow environment variable NTERACT_DESKTOP_DISABLE_AUTO_UPDATE to disable auto-update.
Fixes #3517
|
JavaScript
|
bsd-3-clause
|
rgbkrk/nteract,nteract/nteract,nteract/nteract,rgbkrk/nteract,nteract/nteract,rgbkrk/nteract,nteract/composition,nteract/nteract,rgbkrk/nteract,nteract/composition,nteract/composition,rgbkrk/nteract,nteract/nteract
|
3096c29162a5acbf3b98ae1f699e6039976caf19
|
c2cgeoportal/scaffolds/update/+package+/static/mobile/app/model/Query.js
|
c2cgeoportal/scaffolds/update/+package+/static/mobile/app/model/Query.js
|
Ext.define('App.model.Query', {
extend: 'Ext.data.Model',
config: {
fields: [
{
name: 'detail',
mapping: 'properties',
convert: function(value, record) {
var detail = [],
attributes = record.raw.attributes;
detail.push('<table class="detail">');
for (var k in attributes) {
if (attributes.hasOwnProperty(k) && attributes[k]) {
detail = detail.concat([
'<tr>',
'<th>',
OpenLayers.i18n(k),
'</th>',
'<td>',
attributes[k],
'</td>',
'</tr>'
]);
}
}
detail.push('</table>');
return detail.join('');
}
},
{name: 'type'}
]
}
});
Ext.create('Ext.data.Store', {
storeId: 'queryStore',
model: 'App.model.Query',
grouper: {
groupFn: function(record) {
return OpenLayers.i18n(record.get('type'));
}
}
});
|
Ext.define('App.model.Query', {
extend: 'Ext.data.Model',
config: {
fields: [
{
name: 'detail',
mapping: 'properties',
convert: function(value, record) {
var detail = [],
attributes = record.raw.attributes;
detail.push('<table class="detail">');
for (var k in attributes) {
if (attributes.hasOwnProperty(k) && attributes[k]) {
detail = detail.concat([
'<tr>',
'<th>',
OpenLayers.i18n(k),
'</th>',
'<td>',
OpenLayers.String.format(attributes[k], App),
'</td>',
'</tr>'
]);
}
}
detail.push('</table>');
return detail.join('');
}
},
{name: 'type'}
]
}
});
Ext.create('Ext.data.Store', {
storeId: 'queryStore',
model: 'App.model.Query',
grouper: {
groupFn: function(record) {
return OpenLayers.i18n(record.get('type'));
}
}
});
|
Allow using subst variables in layer attributes
|
Allow using subst variables in layer attributes
|
JavaScript
|
bsd-2-clause
|
tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal
|
d2e1ba9dbe878690d33c82025bb12e4e9efd8f65
|
js/scripts.js
|
js/scripts.js
|
var pingPong = function(i) {
if ((i % 3 === 0) || (i % 5 === 0)) {
return true;
} else {
return false;
}
};
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
for (var i = 1; i <= number; i += 1) {
if (i % 15 === 0) {
$('#outputList').append("<li>ping pong</li>");
} else if (i % 3 === 0) {
$('#outputList').append("<li>ping</li>");
} else if (i % 5 === 0) {
$('#outputList').append("<li>pong</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
|
var pingPong = function(i) {
if ((i % 3 === 0) && (i % 5 != 0)) {
return "ping";
} else if ((i % 5 === 0) && (i % 6 != 0)) {
return "pong";
} else if ((i % 3 === 0) && (i % 5 === 0)) {
return "ping pong";
} else {
return false;
}
};
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
for (var i = 1; i <= number; i += 1) {
if (i % 15 === 0) {
$('#outputList').append("<li>ping pong</li>");
} else if ((winner) && (i % 5 != 0)) {
$('#outputList').append("<li>ping</li>");
} else if ((winner) && (i % 3 != 0)) {
$('#outputList').append("<li>pong</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
|
Change spec test code away from true/false; provides ping, pong, and ping pong returns instead
|
Change spec test code away from true/false; provides ping, pong, and ping pong returns instead
|
JavaScript
|
mit
|
kcmdouglas/pingpong,kcmdouglas/pingpong
|
06595b1ea4a93825e22a1221e6c44846e7bde1f8
|
test/e2e/e2e.spec.js
|
test/e2e/e2e.spec.js
|
import { Application } from 'spectron'
import electronPath from 'electron'
import path from 'path'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000
const delay = time => new Promise(resolve => setTimeout(resolve, time))
describe('main window', function spec() {
beforeAll(async () => {
this.app = new Application({
path: electronPath,
args: [path.join(__dirname, '..', '..', 'app')]
})
return this.app.start()
})
afterAll(() => this.app && this.app.isRunning() && this.app.stop())
it('should open window', async () => {
const { client, browserWindow } = this.app
await client.waitUntilWindowLoaded()
await delay(500)
const title = await browserWindow.getTitle()
expect(title).toBe('Zap')
})
it('should haven\'t any logs in console of main window', async () => {
const { client } = this.app
const logs = await client.getRenderProcessLogs()
// Print renderer process logs
logs.forEach((log) => {
console.log(log.message)
console.log(log.source)
console.log(log.level)
})
expect(logs).toHaveLength(0)
})
})
|
import { Application } from 'spectron'
import electronPath from 'electron'
import path from 'path'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000
const delay = time => new Promise(resolve => setTimeout(resolve, time))
describe('main window', function spec() {
beforeAll(async () => {
this.app = new Application({
path: electronPath,
args: [path.join(__dirname, '..', '..', 'app')]
})
return this.app.start()
})
afterAll(() => this.app && this.app.isRunning() && this.app.stop())
it('should open window', async () => {
const { client, browserWindow } = this.app
await client.waitUntilWindowLoaded()
await delay(500)
const title = await browserWindow.getTitle()
expect(title).toBe('Zap')
})
it('should haven\'t any logs in console of main window', async () => {
const { client } = this.app
const logs = await client.getRenderProcessLogs()
expect(logs).toHaveLength(0)
})
})
|
Drop pessimistic printing of logs that shouldn't be there
|
enhance(test): Drop pessimistic printing of logs that shouldn't be there
This test code is unnecessary in the common case and can be revived if the test
fails.
|
JavaScript
|
mit
|
LN-Zap/zap-desktop,LN-Zap/zap-desktop,LN-Zap/zap-desktop
|
e03b40541d8e0843c4585489a2a711ee4183e222
|
cities_light/static/cities_light/autocomplete_light.js
|
cities_light/static/cities_light/autocomplete_light.js
|
$(document).ready(function() {
// autocomplete widget javascript initialization for bootstrap=countrycity
$('.autocomplete_light_widget[data-bootstrap=countrycity]').each(function() {
var country_wrapper = $(this).prev();
var city_wrapper = $(this);
function setup() {
// get the related country deck
var country_deck = country_wrapper.yourlabs_deck();
var country_select = country_deck.valueSelect;
if (country_deck.payload.bootstrap == 'remote') {
// instanciate a RemoteChannelDeck deck for this city
var city_deck = city_wrapper.yourlabs_deck(RemoteChannelDeck);
} else {
// instanciate a deck for this city
var city_deck = city_wrapper.yourlabs_deck();
}
// set country_pk in city autocomplete data when a country is selected
country_select.bind('change', function() {
city_deck.input.yourlabs_autocomplete().data['country__pk'] = $(this).val();
});
// set country_pk in city autocomplete data if a country is initially selected
if (country_select.val())
city_deck.input.yourlabs_autocomplete().data['country__pk'] = country_select.val();
}
// if the country deck is ready: setup the city deck, else wait for country deck to be ready
country_wrapper.data('deckready', 0) ? setup() : country_wrapper.bind('deckready', setup);
});
});
|
$(document).ready(function() {
// autocomplete widget javascript initialization for bootstrap=countrycity
$('.autocomplete_light_widget[data-bootstrap=countrycity]').each(function() {
var country_wrapper = $(this).prev();
var city_wrapper = $(this);
function setup() {
// get the related country deck
var country_deck = country_wrapper.yourlabs_deck();
var country_select = country_deck.valueSelect;
if (country_deck.payload.bootstrap == 'remote') {
// instanciate a RemoteChannelDeck deck for this city
var city_deck = city_wrapper.yourlabs_deck(RemoteChannelDeck);
} else {
// instanciate a deck for this city
var city_deck = city_wrapper.yourlabs_deck();
}
// set country_pk in city autocomplete data when a country is selected
country_select.bind('change', function() {
console.log($(this).val());
if ($(this).val()) {
city_deck.autocomplete.innerContainer.html('');
city_deck.autocomplete.data['country__pk'] = $(this).val();
} else {
city_deck.autocomplete.data['country_pk'] = '';
city_deck.valueSelect.find('option').remove();
city_deck.valueSelect.val('');
city_deck.deck.html('');
city_deck.updateDisplay();
}
});
// set country_pk in city autocomplete data if a country is initially selected
if (country_select.val())
city_deck.input.yourlabs_autocomplete().data['country__pk'] = country_select.val();
}
// if the country deck is ready: setup the city deck, else wait for country deck to be ready
country_wrapper.data('deckready', 0) ? setup() : country_wrapper.bind('deckready', setup);
});
});
|
Clear the city autocomplete when unselecting the country in countrycity widget
|
Clear the city autocomplete when unselecting the country in countrycity widget
|
JavaScript
|
mit
|
max-arnold/django-cities-light,yourlabs/django-cities-light,affan2/django-cities-light,eevol/django-cities-light,gpichot/django-cities-light,eevol/django-cities-light,KevinGrahamFoster/django-cities-light,affan2/django-cities-light,greenday2/django-cities-light,max-arnold/django-cities-light,gpichot/django-cities-light
|
1030f20315b0f661993c7aca33bb3f6fb9753503
|
src/components/InputArea.js
|
src/components/InputArea.js
|
import React, { Component } from 'react';
import TextField from 'material-ui/TextField';
import Card, { CardActions, CardContent } from 'material-ui/Card';
import Button from 'material-ui/Button';
import TaxCalculator from '../libs/TaxCalculator';
class TextFields extends Component {
state = {
income: 0,
expenses: 0
};
calculate() {
const { income, expenses } = this.state;
const taxInfo = TaxCalculator.getTaxInfo(income, expenses);
this.props.handleUpdate(taxInfo);
}
render() {
return (
<Card>
<CardContent>
<div>
<TextField
label="Income"
type="number"
value={this.state.income}
onChange={event => this.setState({ income: event.target.value })}
inputProps={{ min: 0, step: 10000 }}
margin="normal"
style={{ width: '100%' }}
/>
</div>
<div>
<TextField
label="Expenses"
type="number"
value={this.state.expenses}
onChange={event =>
this.setState({ expenses: event.target.value })}
inputProps={{ min: 0, step: 10000 }}
margin="normal"
style={{ width: '100%' }}
/>
</div>
</CardContent>
<CardActions>
<Button onClick={() => this.calculate()}>Calculate</Button>
</CardActions>
</Card>
);
}
}
export default TextFields;
|
import React, { Component } from 'react';
import TextField from 'material-ui/TextField';
import Card, { CardActions, CardContent } from 'material-ui/Card';
import Button from 'material-ui/Button';
import TaxCalculator from '../libs/TaxCalculator';
class TextFields extends Component {
handleSubmit(event) {
event.preventDefault();
const formElement = event.target;
const taxInfo = TaxCalculator.getTaxInfo(
formElement.income.value,
formElement.expenses.value
);
this.props.handleUpdate(taxInfo);
}
render() {
return (
<Card>
<form onSubmit={event => this.handleSubmit(event)}>
<CardContent>
<div>
<TextField
label={TaxCalculator.translate('income')}
name="income"
type="number"
defaultValue="0"
inputProps={{ min: 0, step: 10000 }}
margin="normal"
style={{ width: '100%' }}
/>
</div>
<div>
<TextField
label={TaxCalculator.translate('expenses')}
name="expenses"
type="number"
defaultValue="0"
inputProps={{ min: 0, step: 10000 }}
margin="normal"
style={{ width: '100%' }}
/>
</div>
</CardContent>
<CardActions>
<Button type="submit">Calculate</Button>
</CardActions>
</form>
</Card>
);
}
}
export default TextFields;
|
Delete state and add form.
|
Delete state and add form.
|
JavaScript
|
apache-2.0
|
migutw42/jp-tax-calculator,migutw42/jp-tax-calculator
|
f0c712adc291219c08ea9c1b680e258f6636cddc
|
lib/controllers/catalogs.js
|
lib/controllers/catalogs.js
|
const mongoose = require('mongoose');
const { omit } = require('lodash');
const Catalog = mongoose.model('Catalog');
function formatCatalog(catalog) {
return omit(catalog.toObject({ virtuals: true }), '_metrics');
}
function fetch(req, res, next, id) {
Catalog
.findById(id)
.populate('service', 'location sync')
.exec(function(err, catalog) {
if (err) return next(err);
if (!catalog) return res.sendStatus(404);
req.catalog = catalog;
next();
});
}
function show(req, res) {
res.send(formatCatalog(req.catalog));
}
function list(req, res, next) {
Catalog
.find()
.populate('service', 'location sync')
.exec(function(err, catalogs) {
if (err) return next(err);
res.send(catalogs.map(formatCatalog));
});
}
function metrics(req, res, next) {
req.catalog.computeMetricsAndSave()
.then(catalog => res.send(catalog.metrics))
.catch(next);
}
module.exports = { fetch, list, show, metrics };
|
const mongoose = require('mongoose');
const { omit } = require('lodash');
const Catalog = mongoose.model('Catalog');
function formatCatalog(catalog) {
return omit(catalog.toObject({ virtuals: true, minimize: false }), '_metrics');
}
function fetch(req, res, next, id) {
Catalog
.findById(id)
.populate('service', 'location sync')
.exec(function(err, catalog) {
if (err) return next(err);
if (!catalog) return res.sendStatus(404);
req.catalog = catalog;
next();
});
}
function show(req, res) {
res.send(formatCatalog(req.catalog));
}
function list(req, res, next) {
Catalog
.find()
.populate('service', 'location sync')
.exec(function(err, catalogs) {
if (err) return next(err);
res.send(catalogs.map(formatCatalog));
});
}
function metrics(req, res, next) {
req.catalog.computeMetricsAndSave()
.then(catalog => res.send(catalog.metrics))
.catch(next);
}
module.exports = { fetch, list, show, metrics };
|
Disable minimize for Catalog serialization
|
Disable minimize for Catalog serialization
|
JavaScript
|
agpl-3.0
|
inspireteam/geogw,jdesboeufs/geogw
|
69aa8d49b5a2082d2870d453521194a39a215001
|
lib/append.js
|
lib/append.js
|
/**
* Insert content, specified by the parameter, to the end of each
* element in the set of matched elements.
*/
function append(el) {
var l = this.length, clone = false;
// wrap content
el = this.air(el);
// matched parent elements (targets)
this.each(function(node, index) {
//console.log(index);
//console.log(l);
clone = index < (l - 1);
//console.log(clone);
// content elements to insert
el.each(function(ins) {
// must clone otherwise only the last matched
// element will receive the appended element
node.appendChild(clone ? ins.cloneNode(true) : ins);
})
});
return this;
}
module.exports = function() {
this.append = append;
}
|
/**
* Insert content, specified by the parameter, to the end of each
* element in the set of matched elements.
*/
function append() {
var i, l = this.length, el, args = Array.prototype.slice.call(arguments);
for(i = 0;i < args.length;i++) {
el = args[i];
// wrap content
el = this.air(el);
// matched parent elements (targets)
this.each(function(node, index) {
// content elements to insert
el.each(function(ins) {
ins = (index < (l - 1)) ? ins.cloneNode(true) : ins;
// must clone otherwise only the last matched
// element will receive the appended element
node.appendChild(ins);
})
});
}
return this;
}
module.exports = function() {
this.append = append;
}
|
Append supports multiple content args.
|
Append supports multiple content args.
|
JavaScript
|
mit
|
socialally/air,tmpfs/air,tmpfs/air,socialally/air
|
04bbd69917a604457ce3a3df860f3f5cb1d21c65
|
app/transmute.js
|
app/transmute.js
|
#!/usr/bin/env node
'use strict';
// Load base requirements
const program = require('commander'),
dotenv = require('dotenv').config(),
path = require('path');
// Load our libraries
const utils = require('./libs/utils'),
logger = require('./libs/log'),
i18n = require('./libs/locale'),
queue = require('./libs/queue'),
task = require('./libs/task');
// Create new task
task.create({
"name": "Two Brothers, One Impala",
"directory": path.resolve('test/data/task/metadata'),
"type": "show",
"seasons": [1, 2],
"options": {
"preset": "slow",
"video" : {
"bitrate": 3500,
"quality": 0
}
}
}).then((data) => {
console.log('Task Object:');
console.log(data);
console.log('\n\n');
console.log('Job Object:');
console.log(data.jobs[0]);
process.exit(0);
}).catch((err) => {
console.log(err);
process.exit(0);
});
|
#!/usr/bin/env node
'use strict';
// Load base requirements
const program = require('commander'),
dotenv = require('dotenv').config(),
path = require('path');
// Load our libraries
const utils = require('./libs/utils'),
logger = require('./libs/log'),
i18n = require('./libs/locale'),
queue = require('./libs/queue'),
task = require('./libs/task');
// Create new task
task.create({
"name": "Two Brothers, One Impala",
"directory": path.resolve('test/data/task/metadata'),
"type": "show",
"seasons": [1, 2],
"options": {
"preset": "slow",
"video" : {
"bitrate": 3500,
"quality": 0
}
}
}).then((data) => {
return queue.add(data);
}).catch((err) => {
console.log(err);
process.exit(0);
});
|
Update entry point to use queue
|
Update entry point to use queue
|
JavaScript
|
apache-2.0
|
transmutejs/core
|
7f0176380ad5ade420384d1ae4ea14a5180f05e8
|
tasks/doxdox.js
|
tasks/doxdox.js
|
var doxdox = require('doxdox'),
utils = require('doxdox/lib/utils'),
fs = require('fs'),
path = require('path'),
extend = require('extend');
module.exports = function (grunt) {
grunt.registerMultiTask('doxdox', 'Generate documentation with doxdox.', function () {
var done = this.async(),
input,
output,
config = {
title: '',
description: '',
layout: 'bootstrap'
};
if (this.data.input && this.data.output) {
input = this.data.input;
output = this.data.output;
if (this.data.config) {
config = extend(true, {}, config, this.data.config);
}
if (!config.package) {
config.package = utils.findPackagePath(input);
}
if (fs.existsSync(config.package)) {
config.package = require(config.package);
if (!config.title && config.package.name) {
config.title = config.package.name;
}
if (!config.description && config.package.description) {
config.description = config.package.description;
}
}
if (!config.title) {
config.title = 'Untitled Project';
}
doxdox.parseInput(
path.normalize(path.resolve(input)),
config,
config.package
).then(function (content) {
fs.writeFileSync(output, content, 'utf8');
done();
});
} else {
throw new Error('Valid input and output properties are required.');
}
});
};
|
var doxdox = require('doxdox'),
utils = require('doxdox/lib/utils'),
fs = require('fs'),
path = require('path'),
extend = require('extend');
module.exports = function (grunt) {
grunt.registerMultiTask('doxdox', 'Generate documentation with doxdox.', function () {
var done = this.async(),
input,
output,
config = {
title: '',
description: '',
layout: 'bootstrap'
};
if (this.data.input && this.data.output) {
input = this.data.input;
output = this.data.output;
if (this.data.config) {
config = extend(true, {}, config, this.data.config);
}
if (!config.package) {
config.package = utils.findPackagePath(input);
}
if (fs.existsSync(config.package)) {
config.package = require(config.package);
if (!config.title && config.package.name) {
config.title = config.package.name;
}
if (!config.description && config.package.description) {
config.description = config.package.description;
}
}
if (!config.title) {
config.title = 'Untitled Project';
}
doxdox.parseInput(
path.normalize(path.resolve(input)),
config,
config.package
).then(function (content) {
grunt.file.write(output, content, {encoding: 'utf8'});
done();
});
} else {
throw new Error('Valid input and output properties are required.');
}
});
};
|
Use Grunt API to write file
|
Use Grunt API to write file
This way it guarantees that all the intermediate directories are created.
|
JavaScript
|
mit
|
mmarcon/grunt-doxdox,neogeek/grunt-doxdox
|
b54ae8bc91ae77569048be8af229be058e81d0f8
|
lib/plugins/tag/jsfiddle.js
|
lib/plugins/tag/jsfiddle.js
|
'use strict';
/**
* jsFiddle tag
*
* Syntax:
* {% jsfiddle shorttag [tabs] [skin] [height] [width] %}
*/
function jsfiddleTag(args, content){
var id = args[0];
var tabs = args[1] && args[1] !== 'default' ? args[1] : 'js,resources,html,css,result';
var skin = args[2] && args[2] !== 'default' ? args[2] : 'light';
var width = args[3] && args[3] !== 'default' ? args[3] : '100%';
var height = args[4] && args[4] !== 'default' ? args[4] : '300';
return '<iframe width="' + width + '" height="' + height + '" src="http://jsfiddle.net/' + id + '/embedded/' + tabs + '/' + skin + '" frameborder="0" allowfullscreen></iframe>';
}
module.exports = jsfiddleTag;
|
'use strict';
/**
* jsFiddle tag
*
* Syntax:
* {% jsfiddle shorttag [tabs] [skin] [height] [width] %}
*/
function jsfiddleTag(args, content){
var id = args[0];
var tabs = args[1] && args[1] !== 'default' ? args[1] : 'js,resources,html,css,result';
var skin = args[2] && args[2] !== 'default' ? args[2] : 'light';
var width = args[3] && args[3] !== 'default' ? args[3] : '100%';
var height = args[4] && args[4] !== 'default' ? args[4] : '300';
return '<iframe scrolling="no" width="' + width + '" height="' + height + '" src="http://jsfiddle.net/' + id + '/embedded/' + tabs + '/' + skin + '" frameborder="0" allowfullscreen></iframe>';
}
module.exports = jsfiddleTag;
|
Set scrolling="no" to make iframe responsive
|
Set scrolling="no" to make iframe responsive
the fiddle iframe is not responsive in iOS safari and Chrome. By setting `scrolling="no"` makes it possible to fix this issue, by setting `width=1px; min-width=100%` in CSS. [See StackOverflow](http://stackoverflow.com/questions/23083462/how-to-get-an-iframe-to-be-responsive-in-ios-safari)
|
JavaScript
|
mit
|
amobiz/hexo,hexojs/hexo,zhipengyan/hexo,wangjordy/wangjordy.github.io,wangjordy/wangjordy.github.io,leelynd/tapohuck,noikiy/hexo,kywk/hexi,DevinLow/DevinLow.github.io,hexojs/hexo,DevinLow/DevinLow.github.io,zhipengyan/hexo,ppker/hexo,ppker/hexo,aulphar/hexo,kywk/hexi
|
2a774a58d510bc23eb7216543f0b4f83a5b8b481
|
src/js/components/services-by-gsbpm-phase.js
|
src/js/components/services-by-gsbpm-phase.js
|
import React from 'react'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADED } from 'sparql-connect'
import ServiceList from './service-list'
function ServicesByGSBPMPhase({ loaded, services }) {
if(loaded !== LOADED) return <span>loading......</span>
return <ServiceList
services={services}
msg="No service implements this GSBPM phase"
loaded={loaded === LOADED} />
}
export default
sparqlConnect.servicesByGSBPMPhase(ServicesByGSBPMPhase)
|
import React from 'react'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADED } from 'sparql-connect'
import ServiceList from './service-list'
function ServicesByGSBPMPhase({ loaded, services }) {
return <ServiceList
services={services}
msg="No service implements this GSBPM phase"
loaded={loaded === LOADED} />
}
export default
sparqlConnect.servicesByGSBPMPhase(ServicesByGSBPMPhase)
|
Remove useless check on `loaded`
|
Remove useless check on `loaded`
|
JavaScript
|
mit
|
UNECE/Model-Explorer,UNECE/Model-Explorer
|
91cd5e4293ad2f85c19de4ffe69127b6936fd8ab
|
lib/router.js
|
lib/router.js
|
Router.configure({
layoutTemplate: 'layout'
});
Router.route('/', {
name: 'home',
waitOn: function () {
return Meteor.subscribe('verifiedUsersCount');
},
onBeforeAction: function () {
if (Meteor.user()) {
Router.go('ridesList');
} else {
this.next();
}
}
});
Router.route('/caronas', {
name: 'ridesList',
onBeforeAction: function () {
if (! Meteor.user() && ! Meteor.loggingIn()) {
Router.go('home');
} else {
this.next();
}
},
waitOn: function () {
var userIds = [];
Tracker.autorun(function () {
userIds = _(Rides.find({}, { userId: 1 }).fetch()).pluck('userId');
});
return [Meteor.subscribe('rides'), Meteor.subscribe('users', userIds)];
},
data: function () {
return Rides.find({}, { sort: { departureTime: 1 } });
}
});
Router.route('/perfil', {
name: 'profile'
});
Router.route('/inviteEmails', {
name: 'inviteEmails'
});
|
Router.configure({
layoutTemplate: 'layout'
});
Router.route('/', {
name: 'home',
waitOn: function () {
return Meteor.subscribe('verifiedUsersCount');
},
onBeforeAction: function () {
if (Meteor.user()) {
Router.go('ridesList');
} else {
this.next();
}
}
});
Router.route('/caronas', {
name: 'ridesList',
onBeforeAction: function () {
if (! Meteor.user() && ! Meteor.loggingIn()) {
Router.go('home');
} else {
this.next();
}
},
waitOn: function () {
var userIds = [];
var subscriptions = [];
subscriptions.push(Meteor.subscribe('rides'));
Tracker.autorun(function () {
userIds = _(Rides.find({}, { userId: 1 }).fetch()).pluck('userId');
subscriptions.push(Meteor.subscribe('users', userIds));
});
return [subscriptions];
},
data: function () {
return Rides.find({}, { sort: { departureTime: 1 } });
}
});
Router.route('/perfil', {
name: 'profile'
});
Router.route('/inviteEmails', {
name: 'inviteEmails'
});
|
Make findOne reactive for ride owners subscription.
|
Make findOne reactive for ride owners subscription.
fix #9
|
JavaScript
|
mit
|
obvio171/rideboard,obvio171/rideboard
|
270c333096dbeb495571baed81c5f9debdf7d967
|
lib/server.js
|
lib/server.js
|
'use strict';
const fs = require('fs');
const express = require('express');
const send = require('send');
const morgan = require('morgan');
const errorHandler = require('errorhandler');
const compression = require('compression');
const expressLogStream = fs.createWriteStream('./logs/express.log', { flags: 'a' });
exports.start = function start(config) {
var statsDB = require('./statsdb')(config);
var sender = require('./sender')(config, statsDB);
var api = require('./api')(config, statsDB);
var app = express();
app.use(compression());
app.use(morgan('combined', { stream: expressLogStream }));
if (app.settings.env == 'production') {
app.use(errorHandler());
} else {
app.use(errorHandler({ dumpExceptions: true, showStack: true }));
}
app.get('/api/stats.json', api);
app.get('/*', sender);
return app;
};
|
'use strict';
const fs = require('fs');
const path = require('path');
const express = require('express');
const send = require('send');
const morgan = require('morgan');
const errorHandler = require('errorhandler');
const compression = require('compression');
exports.start = function start(config) {
var statsDB = require('./statsdb')(config);
var sender = require('./sender')(config, statsDB);
var api = require('./api')(config, statsDB);
var app = express();
var logPath = path.join('./logs', app.settings.env + '.log');
var expressLogStream = fs.createWriteStream(logPath, { flags: 'a' });
app.use(compression());
app.use(morgan('combined', { stream: expressLogStream }));
if (app.settings.env == 'production') {
app.use(errorHandler());
} else {
app.use(errorHandler({ dumpExceptions: true, showStack: true }));
}
app.get('/api/stats.json', api);
app.get('/*', sender);
return app;
};
|
Create logs for each environment
|
Create logs for each environment
|
JavaScript
|
mit
|
pfleidi/podslurp
|
cbcd01ba33d3d8b4408d97ddbe3aa80eb22984dc
|
src/inject/inject.js
|
src/inject/inject.js
|
chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
var labels = document.getElementsByClassName('label');
Array.prototype.filter.call(labels, function(label) {
return label.textContent.indexOf('blocked') === 0;
}).forEach(function(label) {
label.style.color = 'rgb(199, 37, 67)';
});
}
}, 4000);
});
|
chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
var colorMapping = {
'blocked': 'rgb(199, 37, 67)',
'needs ': 'rgb(199, 37, 67)'
};
function colorLabelNodes(labels) {
Object.keys(colorMapping).forEach(function(labelKeyword) {
Array.prototype.filter.call(labels, function(label) {
return label.textContent.indexOf(labelKeyword) === 0
}).forEach(function(label) {
label.style.color = colorMapping[labelKeyword];
});
});
}
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
Array.prototype.forEach.call(mutation.addedNodes, function(addedNode) {
if (typeof addedNode.getElementsByClassName !== 'undefined') {
var labels = addedNode.getElementsByClassName('label');
colorLabelNodes(labels);
}
});
});
});
// configuration of the observer:
var config = { childList: true, subtree: true };
observer.observe(document, config);
}
}, 10);
});
|
Set color on all newly-added labels
|
Set color on all newly-added labels
|
JavaScript
|
isc
|
oliverswitzer/wwltw-for-pivotal-tracker,mkenyon/red-labels-for-pivotal-tracker,oliverswitzer/wwltw-for-pivotal-tracker
|
46962ed201abf4e701fb069c02ab1a1751464857
|
information.js
|
information.js
|
'use strict';
var hosts = {
'bbc.co.uk': 'bbc',
'm.bbc.co.uk': 'bbc',
'reddit.com': 'reddit',
'www.reddit.com': 'reddit',
'condenast.co.uk': 'condenast'
};
var organisations = {
'bbc': {
'owner': null,
'info': 'British Broadcasting Corporation'
},
'reddit': {
'owner': 'condenast',
'info': 'Reddit'
},
'condenast': {
'owner': 'advancepublications',
'info': 'Condé Nast'
},
'advancepublications': {
'owner': null,
'info': 'Advance Publications'
}
};
function getInfoString (organisationKey) {
var infoString = '';
for (;;) {
var organisation = organisations[organisationKey];
console.log(organisation);
if (!organisation) { return infoString; }
if (infoString.length) {
infoString += " -> ";
}
infoString += organisation.info;
organisationKey = organisation.owner;
}
};
module.exports = {
getInfo: function (host) {
console.log(host);
var siteKey = hosts[host];
return getInfoString(siteKey);
}
};
|
'use strict';
var hosts = {
'bbc.co.uk': 'bbc',
'm.bbc.co.uk': 'bbc',
'reddit.com': 'reddit',
'www.reddit.com': 'reddit',
'condenast.co.uk': 'condenast'
'tumblr.com' : 'tumblr'
};
var organisations = {
'bbc': {
'owner': null,
'info': 'British Broadcasting Corporation'
},
'reddit': {
'owner': 'condenast',
'info': 'Reddit'
},
'condenast': {
'owner': 'advancepublications',
'info': 'Condé Nast'
},
'advancepublications': {
'owner': null,
'info': 'Advance Publications'
},
'tumblr': {
'owner': 'yahoo',
'info': 'Tumblr'
},
'yahoo': {
'owner': null,
'info': 'Yahoo'
}
};
function getInfoString (organisationKey) {
var infoString = '';
for (;;) {
var organisation = organisations[organisationKey];
console.log(organisation);
if (!organisation) { return infoString; }
if (infoString.length) {
infoString += " -> ";
}
infoString += organisation.info;
organisationKey = organisation.owner;
}
};
module.exports = {
getInfo: function (host) {
console.log(host);
var siteKey = hosts[host];
return getInfoString(siteKey);
}
};
|
Add tumblr->yahoo info for server
|
Add tumblr->yahoo info for server
|
JavaScript
|
mit
|
magicmark/Transparification-Server
|
144eba59227a600aec09ab549c0be840698d191a
|
src/js/utils/_base-view.js
|
src/js/utils/_base-view.js
|
import * as _ from 'underscore';
import * as Backbone from 'backbone';
class BaseView extends Backbone.View {
constructor(options = {}) {
super(options);
this._subviews = null;
}
registerSubView(view) {
this._subviews = this._subviews || [];
this._subviews.push(view);
}
remove() {
_.invoke(this._subviews, 'remove');
Backbone.View.prototype.remove.call(this);
}
}
export default BaseView;
|
import * as _ from 'underscore';
import * as Backbone from 'backbone';
class BaseView extends Backbone.View {
constructor(options = {}) {
super(options);
this._subviews = null;
}
assign(view, selector) {
view.setElement(this.$(selector)).render();
}
registerSubView(view) {
this._subviews = this._subviews || [];
this._subviews.push(view);
}
remove() {
_.invoke(this._subviews, 'remove');
Backbone.View.prototype.remove.call(this);
}
}
export default BaseView;
|
Update base view w/convenience function for rendering subviews
|
Update base view w/convenience function for rendering subviews
See:
http://ianstormtaylor.com/rendering-views-in-backbonejs-isnt-always-simp
le/
|
JavaScript
|
mit
|
trevormunoz/katherine-anne,trevormunoz/katherine-anne,trevormunoz/katherine-anne
|
6dd03089f29ae7cd357f45a929bed8f7e7d6440b
|
src/input/storageHandler.js
|
src/input/storageHandler.js
|
'use strict'
// Code thanks to MDN
export function storageAvailable (type) {
try {
let storage = window[type]
let x = '__storage_test__'
storage.setItem(x, x)
storage.removeItem(x)
return true
} catch (e) {
let storage = window[type]
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage.length !== 0
}
}
export function storagePopulated () {
if (window.localStorage.length !== 0) {
console.log('populated')
return true
}
}
export function populateStorage () {
window.localStorage.setItem('pomodoroTime', document.getElementById('pomodoroInput').value)
window.localStorage.setItem('shortBreakTime', document.getElementById('shortBreakInput').value)
window.localStorage.setItem('longBreakTime', document.getElementById('longBreakInput').value)
}
|
'use strict'
// Code thanks to MDN
export function storageAvailable (type) {
try {
let storage = window[type]
let x = '__storage_test__'
storage.setItem(x, x)
storage.removeItem(x)
return true
} catch (e) {
let storage = window[type]
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage.length !== 0
}
}
export function storagePopulated () {
if (window.localStorage.length !== 0) {
console.log('populated')
return true
}
}
export function populateStorage () {
window.localStorage.setItem('pomodoroTime', document.getElementById('pomodoroInput').value)
window.localStorage.setItem('shortBreakTime', document.getElementById('shortBreakInput').value)
window.localStorage.setItem('longBreakTime', document.getElementById('longBreakInput').value)
window.localStorage.setItem('alarmDropdown', document.getElementById('alarmDropdown').value)
window.localStorage.setItem('ticking', document.getElementById('tickToggle').checked)
window.localStorage.setItem('storageToggle', document.getElementById('storageToggle').checked)
}
|
Add all settings to populateStorage
|
Add all settings to populateStorage
|
JavaScript
|
mit
|
CrowsVeldt/FreeCodeCamp-Pomodoro-Timer
|
ccce0d08bd0a43ba10a5b18470095b0c19bfe18c
|
webpack.client.babel.js
|
webpack.client.babel.js
|
import base from './webpack.base.babel.js';
import path from 'path';
import webpack from 'webpack';
const {WDS_PORT, PORT, APP_WEB_BASE_PATH} = process.env;
export default {
...base,
entry: "./src/app/_client.js",
output: {
path: path.join(__dirname, 'dist', 'static'),
filename: "app.js",
publicPath: `${APP_WEB_BASE_PATH}/`
},
plugins: base.plugins
.concat(process.env.NODE_ENV==="production"
? [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
]
: []
),
devServer: {
publicPath: `${APP_WEB_BASE_PATH}/static`,
contentBase: `http://localhost:${PORT}/static`,
historyApiFallback: true,
progress: false,
stats: 'errors-only',
compress: true,
port: WDS_PORT,
proxy: {
"*": `http://localhost:${PORT}`
}
}
};
|
import base from './webpack.base.babel.js';
import path from 'path';
import webpack from 'webpack';
const {WDS_PORT, PORT, APP_WEB_BASE_PATH} = process.env;
export default {
...base,
entry: "./src/app/_client.js",
output: {
path: path.join(__dirname, 'dist', 'static'),
filename: "app.js",
publicPath: `${APP_WEB_BASE_PATH}/`
},
plugins: base.plugins
.concat(process.env.NODE_ENV==="production"
? [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
]
: []
),
devServer: {
publicPath: '/static/',
contentBase: `http://localhost:${PORT}/static`,
historyApiFallback: true,
progress: false,
stats: 'errors-only',
compress: true,
port: WDS_PORT,
proxy: {
"**": `http://localhost:${PORT}`
}
}
};
|
Fix dev server redirection bug
|
Fix dev server redirection bug
When running `npm run dev` and opening the browser, newer version
of WDS would redirect to the proxied server instead of proxying. Changed
proxy syntax to match `**` instead of `*`
|
JavaScript
|
mit
|
mdjasper/React-Reading-List,tuxsudo/react-starter
|
ba816550e509def9d0d4f3f6d500b80402b0a5c2
|
routes/index.js
|
routes/index.js
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'VoteAnon' });
});
router.route('/create')
.get(function(req, res) {
res.render('create', { title: 'VoteAnon: create poll' });
})
.post(function(req, res) {
res.render('confirm_create', { title: 'VoteAnon: poll created' });
});
module.exports = router;
|
var express = require('express');
var redis = require('redis');
var router = express.Router();
var client = redis.createClient();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'VoteAnon' });
});
router.route('/create')
.get(function(req, res) {
res.render('create', { title: 'VoteAnon: create poll' });
})
.post(function(req, res) {
res.render('confirm_create', { title: 'VoteAnon: poll created' });
});
module.exports = router;
|
Connect to redis on route
|
Connect to redis on route
|
JavaScript
|
mit
|
Pringley/voteanon
|
8a12e4a209c262d5ad446d99a81cd8936a353ab4
|
make-event.js
|
make-event.js
|
'use strict';
let fs = require('fs');
let moment = require('moment');
let parseDate = require('./parse-date');
function maybeParse(value) {
if(value[0] === '@') {
return moment(parseDate(value.slice(1))).format('YYYY-MM-DD HH-mm-ss');
}
try {
return JSON.parse(value);
}
catch(error) {
if(value.indexOf(',') !== -1) {
return value.split(',').map(maybeParse);
}
else {
return value;
}
}
}
module.exports = function(args) {
let dateTime = moment().format('YYYY-MM-DD HH-mm-ss');
let event = {};
event.type = args[0];
args.slice(1).forEach(function(arg) {
var keyValue = /^([^:]+):(.+)$/.exec(arg);
if(keyValue) {
event[keyValue[1]] = maybeParse(keyValue[2]);
}
else {
event.positionals = event.positionals || [];
event.positionals.push(maybeParse(arg));
}
});
fs.writeFileSync(dateTime + '.json', JSON.stringify(event, null, 4));
};
|
'use strict';
let fs = require('fs');
let moment = require('moment');
let parseDate = require('./parse-date');
function maybeParse(value) {
if(value[0] === '@') {
return moment(parseDate(value.slice(1))).format('YYYY-MM-DD HH-mm-ss');
}
try {
return JSON.parse(value);
}
catch(error) {
if(value.indexOf(',') !== -1) {
return value.split(',').map(maybeParse);
}
else {
return value;
}
}
}
module.exports = function(args) {
let event = {};
event.type = args.shift();
let dateTime = (function() {
let dateTime = parseDate(args[0]);
if(dateTime) {
dateTime = moment(dateTime);
args.shift();
}
else {
dateTime = moment();
}
return dateTime;
})();
args.forEach(function(arg) {
var keyValue = /^([^:]+):(.+)$/.exec(arg);
if(keyValue) {
event[keyValue[1]] = maybeParse(keyValue[2]);
}
else {
event.positionals = event.positionals || [];
event.positionals.push(maybeParse(arg));
}
});
fs.writeFileSync(
dateTime.format('YYYY-MM-DD HH-mm-ss') + '.json',
JSON.stringify(event, null, 4)
);
};
|
Allow event date to be overridden.
|
Allow event date to be overridden.
|
JavaScript
|
agpl-3.0
|
n2liquid/ev
|
baa2562e6410e491b9e094ff6b0900fe5ea23d7d
|
ember/tests/acceptance/page-not-found-test.js
|
ember/tests/acceptance/page-not-found-test.js
|
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { visit, currentURL } from '@ember/test-helpers';
import { setupPretender } from 'skylines/tests/helpers/setup-pretender';
module('Acceptance | page-not-found', function(hooks) {
setupApplicationTest(hooks);
setupPretender(hooks);
hooks.beforeEach(async function() {
await visit('/foobar');
});
test('will keep the URL at /foobar', function(assert) {
assert.equal(currentURL(), '/foobar');
});
test('will show "Page not found" error message', function(assert) {
assert.dom('.page-header').containsText('Page not found');
});
});
|
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { visit, currentURL } from '@ember/test-helpers';
import { setupPolly } from 'skylines/tests/helpers/setup-polly';
module('Acceptance | page-not-found', function(hooks) {
setupApplicationTest(hooks);
setupPolly(hooks, { recordIfMissing: false });
hooks.beforeEach(async function() {
await visit('/foobar');
});
test('will keep the URL at /foobar', function(assert) {
assert.equal(currentURL(), '/foobar');
});
test('will show "Page not found" error message', function(assert) {
assert.dom('.page-header').containsText('Page not found');
});
});
|
Use Polly.js instead of Pretender
|
tests/page-not-found: Use Polly.js instead of Pretender
|
JavaScript
|
agpl-3.0
|
RBE-Avionik/skylines,Turbo87/skylines,RBE-Avionik/skylines,Harry-R/skylines,RBE-Avionik/skylines,skylines-project/skylines,Harry-R/skylines,Harry-R/skylines,RBE-Avionik/skylines,Turbo87/skylines,Turbo87/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,Harry-R/skylines,Turbo87/skylines
|
430d0dd3530c83907f9867454fdd3781b05835c9
|
webpack_config/server/webpack.prod.babel.js
|
webpack_config/server/webpack.prod.babel.js
|
import webpack from 'webpack'
import baseWebpackConfig from './webpack.base'
import UglifyJSPlugin from 'uglifyjs-webpack-plugin'
import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer'
import {Plugin as ShakePlugin} from 'webpack-common-shake'
import OptimizeJsPlugin from 'optimize-js-plugin'
const plugins = [
new webpack.ProgressPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new ShakePlugin(),
// NOTE: you can use BabiliPlugin as an alternative to UglifyJSPlugin
// new BabiliPlugin(),
new UglifyJSPlugin({
sourceMap: true,
compress: {
warnings: false,
unused: true,
dead_code: true
// This option removes console.log in production
// drop_console: true
},
output: {
comments: false
}
}),
new OptimizeJsPlugin({
sourceMap: true
})
]
// Do you want to use bundle analyzer?
if (process.env.ANALYZE_BUNDLE) {
plugins.push(new BundleAnalyzerPlugin({analyzerMode: 'static'}))
}
export default Object.assign({}, baseWebpackConfig, {
plugins: baseWebpackConfig.plugins.concat(plugins)
})
|
import webpack from 'webpack'
import baseWebpackConfig from './webpack.base'
import UglifyJSPlugin from 'uglifyjs-webpack-plugin'
import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer'
import {Plugin as ShakePlugin} from 'webpack-common-shake'
import OptimizeJsPlugin from 'optimize-js-plugin'
const analyzePlugins = process.env.ANALYZE_BUNDLE
? [new BundleAnalyzerPlugin({analyzerMode: 'static'})]
: []
const plugins = [
new webpack.ProgressPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new ShakePlugin(),
// NOTE: you can use BabiliPlugin as an alternative to UglifyJSPlugin
// new BabiliPlugin(),
new UglifyJSPlugin({
sourceMap: true,
compress: {
warnings: false,
unused: true,
dead_code: true
// This option removes console.log in production
// drop_console: true
},
output: {
comments: false
}
}),
new OptimizeJsPlugin({
sourceMap: true
}),
...analyzePlugins
]
export default Object.assign({}, baseWebpackConfig, {
plugins: baseWebpackConfig.plugins.concat(plugins)
})
|
Revert "Revert "style(webpack_config/server): rewrite prod conf in functional style""
|
Revert "Revert "style(webpack_config/server): rewrite prod conf in functional style""
This reverts commit e9de3d6da5e3cfc03b6d5e39fe92ede9c110d712.
|
JavaScript
|
apache-2.0
|
Metnew/react-semantic.ui-starter
|
003259602f03821ff6049914d66ecb77692badc2
|
tests/mocks/streams/mock-hot-collections.js
|
tests/mocks/streams/mock-hot-collections.js
|
define([
'inherits',
'streamhub-hot-collections/streams/hot-collections',
'streamhub-hot-collections-tests/mocks/clients/mock-hot-collections-client'],
function (inherits, HotCollections, MockHotCollectionsClient) {
var MockHotCollections = function (opts) {
opts = opts || {};
opts.client = opts.client || new MockHotCollectionsClient();
HotCollections.call(this, opts);
};
inherits(MockHotCollections, HotCollections);
return MockHotCollections;
});
|
define([
'inherits',
'streamhub-hot-collections/streams/hot-collections',
'streamhub-hot-collections-tests/mocks/clients/mock-hot-collections-client',
'streamhub-sdk-tests/mocks/mock-stream'],
function (inherits, HotCollections, MockHotCollectionsClient, MockStream) {
var MockHotCollections = function (opts) {
opts = opts || {};
opts.client = opts.client || new MockHotCollectionsClient();
HotCollections.call(this, opts);
};
inherits(MockHotCollections, HotCollections);
MockHotCollections.prototype.push = function (a) {
if (a !== null) {
var collections = Array.prototype.slice.call(arguments);
for (var i=0; i < collections.length; i++) {
collections[i].createUpdater = function () {
return new MockStream.LivefyreContent();
}
}
}
HotCollections.prototype.push.apply(this, arguments)
};
return MockHotCollections;
});
|
Add mockstream to mock hot collection
|
Add mockstream to mock hot collection
|
JavaScript
|
mit
|
gobengo/streamhub-hot-collections
|
1829b94752a3cf01773d7d360adb2c18e528fcc8
|
src/renderer/mixins/global/readMagnet.js
|
src/renderer/mixins/global/readMagnet.js
|
export default {
mounted () {
document.addEventListener('paste', this.handlePaste)
},
beforeDestroy () {
document.removeEventListener('paste', this.handlePaste)
},
computed: {
isClientPage () {
return this.$route.path === '/torrenting'
}
},
methods: {
handlePaste (e) {
const text = e.clipboardData.getData('text')
if (/magnet:\?/.test(text)) {
if (!this.isClientPage) {
e.preventDefault()
this.$store.dispatch('streaming/play', {
link: text,
isTorrent: true,
name: null,
neighbours: null
})
}
}
}
}
}
|
export default {
mounted () {
document.addEventListener('paste', this.handlePaste)
},
beforeDestroy () {
document.removeEventListener('paste', this.handlePaste)
},
computed: {
isClientPage () {
return this.$route.path === '/torrenting'
}
},
methods: {
/**
* @param {ClipboardEvent} e
*/
handlePaste (e) {
const text = e.clipboardData.getData('text')
if (e.target.tagName.toUpperCase() === 'INPUT') return
if (/magnet:\?/.test(text)) {
if (!this.isClientPage) {
e.preventDefault()
this.$store.dispatch('streaming/play', {
link: text,
isTorrent: true,
name: null,
neighbours: null
})
}
}
}
}
}
|
Fix wrong handling of paste event that would result in streaming from a magnet if pasting into input for download for eg
|
Fix wrong handling of paste event that would result in streaming from a magnet if pasting into input for download for eg
|
JavaScript
|
mit
|
Kylart/KawAnime,Kylart/KawAnime,Kylart/KawAnime
|
e268600106b19b02a8bcfd72f3aa9c59396f8d3d
|
js/src/core.js
|
js/src/core.js
|
// Export a global module.
window.tangelo = {};
(function (tangelo) {
"use strict";
// Tangelo version number.
tangelo.version = function () {
var version = "0.9.0-dev";
return version;
};
// A namespace for plugins.
tangelo.plugin = {};
// Standard way to access a plugin namespace.
tangelo.getPlugin = function (plugin) {
if (tangelo.plugin[plugin] === undefined) {
tangelo.plugin[plugin] = {};
}
return tangelo.plugin[plugin];
};
}(window.tangelo));
|
// Export a global module.
window.tangelo = {};
(function (tangelo) {
"use strict";
// Tangelo version number.
tangelo.version = function () {
var version = "0.9.0-dev";
return version;
};
// A namespace for plugins.
tangelo.plugin = {};
// Create a plugin namespace if it does not exist; otherwise, do nothing.
tangelo.ensurePlugin = function (plugin) {
if (tangelo.plugin[plugin] === undefined) {
tangelo.plugin[plugin] = {};
}
};
// Standard way to access a plugin namespace.
tangelo.getPlugin = function (plugin) {
if (tangelo.plugin[plugin] === undefined) {
tangelo.plugin[plugin] = {};
}
return tangelo.plugin[plugin];
};
}(window.tangelo));
|
Add tangelo.ensurePlugin() function, to replace tangelo.getPlugin() (which is deprecated)
|
Add tangelo.ensurePlugin() function, to replace tangelo.getPlugin() (which is deprecated)
|
JavaScript
|
apache-2.0
|
Kitware/tangelo,Kitware/tangelo,Kitware/tangelo
|
2f9e7e2af6539395656c7a1ae0b375f178b1c156
|
packages/vega-view/src/initialize-handler.js
|
packages/vega-view/src/initialize-handler.js
|
import {offset} from './render-size';
export default function(view, prevHandler, el, constructor) {
var handler = new constructor(view.loader(), view.tooltip())
.scene(view.scenegraph().root)
.initialize(el, offset(view), view);
if (prevHandler) {
prevHandler.handlers().forEach(function(h) {
handler.on(h.type, h.handler);
});
}
return handler;
}
|
import {offset} from './render-size';
export default function(view, prevHandler, el, constructor) {
var handler = new constructor(view.loader(), tooltip(view))
.scene(view.scenegraph().root)
.initialize(el, offset(view), view);
if (prevHandler) {
prevHandler.handlers().forEach(function(h) {
handler.on(h.type, h.handler);
});
}
return handler;
}
// wrap tooltip handler to trap errors
function tooltip(view) {
var handler = view.tooltip(),
tooltip = null;
if (handler) {
tooltip = function() {
try {
handler.apply(this, arguments);
} catch (error) {
view.error(error);
}
};
}
return tooltip;
}
|
Add error trap for tooltip handler.
|
Add error trap for tooltip handler.
|
JavaScript
|
bsd-3-clause
|
vega/vega,vega/vega,lgrammel/vega,vega/vega,vega/vega
|
346fa351b6c0c17c486dad3dbd85f974f48fb4aa
|
src/services/file.js
|
src/services/file.js
|
const { FileService } = require('./file/file.service')
const { BadScriptPermission } = require('./file/bad-script-permission.error')
const { ScriptNotExist } = require('./file/script-not-exist.error')
module.exports = exports = {
FileService,
BadScriptPermission,
ScriptNotExist
}
|
const { FileService } = require('./file/file.service')
const { BadScriptPermission } = require('./file/bad-script-permission.error')
const { ScriptNotExist } = require('./file/script-not-exist.error')
const { TargetFileAlreadyExist } = require('./file/target-file-already-exist.error')
module.exports = exports = {
FileService,
BadScriptPermission,
ScriptNotExist,
TargetFileAlreadyExist
}
|
Declare TargetFileAlreadyExist in service index
|
Declare TargetFileAlreadyExist in service index
|
JavaScript
|
apache-2.0
|
Mindsers/configfile
|
030c68973913fcf45f259a2f0cdd334955d33dac
|
src/util/weak-map.js
|
src/util/weak-map.js
|
export default window.WeakMap || (function () {
let index = 0;
function Wm () {
this.key = `____weak_map_${index++}`;
}
Wm.prototype = {
delete (obj) {
if (obj) {
delete obj[this.key];
}
},
get (obj) {
return obj ? obj[this.key] : null;
},
has (obj) {
return obj ? typeof obj[this.key] !== 'undefined' : false;
},
set (obj, val) {
return obj ? obj[this.key] = val : null;
}
};
return Wm;
}());
|
export default window.WeakMap || (function () {
let index = 0;
function Wm () {
this.key = `____weak_map_${index++}`;
}
Wm.prototype = {
delete (obj) {
if (obj) {
delete obj[this.key];
}
},
get (obj) {
return obj ? obj[this.key] : null;
},
has (obj) {
return obj ? typeof obj[this.key] !== 'undefined' : false;
},
set (obj, val) {
if (obj) {
const key = this.key;
if (typeof obj[key] === 'undefined') {
Object.defineProperty(obj, key, {
configurable: true,
enumerable: false,
value: val
});
} else {
obj[key] = val;
}
}
}
};
return Wm;
}());
|
Make weak map props non-enumerable preventing circular references when traversing props.
|
Make weak map props non-enumerable preventing circular references when traversing props.
|
JavaScript
|
mit
|
skatejs/named-slots
|
40c5111ee6fe0b7c670dc28d66d475be2ff030fc
|
null-prune.js
|
null-prune.js
|
(function (name, definition) {
// AMD
if (typeof define === 'function') {
define(definition);
}
// Node.js
else if (typeof module !== 'undefined' && module.exports) {
module.exports = definition();
}
// Browser
else {
window[name] = definition();
}
})('nullPrune', function () {
function hasOwnProperty(obj, property) {
return Object.prototype.hasOwnProperty.call(obj, property)
}
function isObject (input) {
return input && (typeof input === 'object')
}
function keys (obj) {
const ownKeys = []
for (let key in obj) {
if (hasOwnProperty(obj, key)) {
ownKeys.push(key)
}
}
return ownKeys
}
function nullPrune (inputObject, { objectKey, parentObject }) {
keys(inputObject).forEach(function(key) {
let node = inputObject[key]
if (isObject(node)) {
nullPrune(node, {
objectKey: key,
parentObject: inputObject
})
} else if (node == null) {
delete inputObject[key]
}
})
if (keys(inputObject).length === 0) {
delete parentObject[objectKey]
}
}
return function(inputObject) {
if (!isObject(inputObject)) {
return inputObject
}
nullPrune(inputObject, {})
return inputObject
}
})
|
(function (name, definition) {
if (typeof define === 'function') {
// AMD
define(definition);
} else if (typeof module !== 'undefined' && module.exports) {
// Node.js
module.exports = definition();
} else {
// Browser
window[name] = definition();
}
})('nullPrune', function () {
function hasOwnProperty(obj, property) {
return Object.prototype.hasOwnProperty.call(obj, property)
}
function isObject (input) {
return input && (typeof input === 'object')
}
function keys (obj) {
const ownKeys = []
for (let key in obj) {
if (hasOwnProperty(obj, key)) {
ownKeys.push(key)
}
}
return ownKeys
}
function nullPrune (inputObject, { objectKey, parentObject }) {
keys(inputObject).forEach(function(key) {
let node = inputObject[key]
if (isObject(node)) {
nullPrune(node, {
objectKey: key,
parentObject: inputObject
})
} else if (node == null) {
delete inputObject[key]
}
})
if (keys(inputObject).length === 0) {
delete parentObject[objectKey]
}
}
return function(inputObject) {
if (!isObject(inputObject)) {
return inputObject
}
nullPrune(inputObject, {})
return inputObject
}
})
|
Tidy up indentation of UMD loader
|
Tidy up indentation of UMD loader
|
JavaScript
|
apache-2.0
|
cskeppstedt/null-prune
|
940163051b33e111370fbb292666e4668c519a27
|
test/integration/test-bad-credentials.js
|
test/integration/test-bad-credentials.js
|
var common = require('../common');
var connection = common.createConnection({password: 'INVALID PASSWORD'});
var assert = require('assert');
var err;
connection.connect(function(_err) {
assert.equal(err, undefined);
err = _err;
});
process.on('exit', function() {
assert.ok(/access denied/i.test(err.message));
assert.equal(err.code, 'ER_ACCESS_DENIED_ERROR');
});
|
var common = require('../common');
var connection = common.createConnection({password: 'INVALID PASSWORD'});
var assert = require('assert');
var err;
connection.connect(function(_err) {
assert.equal(err, undefined);
err = _err;
});
process.on('exit', function() {
assert.equal(err.code, 'ER_ACCESS_DENIED_ERROR');
assert.ok(/access denied/i.test(err.message));
});
|
Make test error more useful
|
Make test error more useful
|
JavaScript
|
mit
|
saisai/node-mysql,wxkdesky/node-mysql,1602/node-mysql,bbito/node-mysql,l371559739/node-mysql,yanninho/node-mysql,linalu1/node-mysql,felixge/node-mysql,tempbottle/node-mysql,shipci/node-mysql,apathyjade/node-mysql,yulongge/node-mysql,XiaoLongW/node-mysql,grooverdan/node-mysql,zhhb/node-mysql,chinazhaghai/node-mysql,Jimbly/node-mysql,lukw00/node-mysql,ashwinks/node-mysql,AndersonGitHub/node-mysql,seangarner/node-mysql,yourcaptain/node-mysql,theblackperl/node-mysql,AshWilliams/node-mysql,mysqljs/mysql,mhasan3/node-mysql,acorbi/node-mysql,NikosEfthias/node-mysql,WY08271/node-mysql,yan5845hao/node-mysql-1,danidomi/node-mysql,cgvarela/node-mysql,teng2015/node-mysql,bORm/node-mysql
|
520f37fad8789c5e43e59918b84848b1dea3bf06
|
test/when-adapter.js
|
test/when-adapter.js
|
(function() {
'use strict';
if(typeof exports === 'object') {
var when = require('../when');
exports.fulfilled = when.resolve;
exports.rejected = when.reject;
exports.pending = function () {
var deferred = when.defer();
return {
promise: deferred.promise,
fulfill: deferred.resolve,
reject: deferred.reject
};
};
}
})();
|
(function() {
'use strict';
if(typeof exports === 'object') {
var when = require('../when');
exports.fulfilled = when.resolve;
exports.rejected = when.reject;
exports.pending = function () {
var pending = {};
pending.promise = when.promise(function(resolve, reject) {
pending.fulfill = resolve;
pending.reject = reject;
});
return pending;
};
}
})();
|
Update aplus test adapter to use when.promise
|
Update aplus test adapter to use when.promise
|
JavaScript
|
mit
|
caporta/when,caporta/when,ning-github/when,SourcePointUSA/when,stevage/when,frank-weindel/when,tkirda/when,ning-github/when,mlennon3/when,stevage/when,anthonyvia/when,tkirda/when,petkaantonov/when,SourcePointUSA/when,frank-weindel/when,anthonyvia/when,mlennon3/when,DJDNS/when.js
|
5b15efa2a01ccdb6ed4c92128df362e585bbd868
|
string/startswith.js
|
string/startswith.js
|
module.exports = function (str, query, position) {
return str.substr(position, query.length) === query;
};
|
/**
Does a string start with another string?
@module string/startsWith
@param {string} str The string to search through.
@param {string} query The string to find in `str`.
@param {number} [position=0] The index to start the search. Defaults to the beginning of the string.
@returns {bool} Does the string start with another string?
@example
var startsWith = require('lildash/string/startswith');
startsWith('food', 'foo'); // => true
startsWith('cake', 'foo'); // => false
startsWith('cake', 'k'); // => false
startsWith('cake', 'k', 2); // => true
*/
module.exports = function (str, query, position) {
return str.substr(position, query.length) === query;
};
|
Add JSDoc documentation to string/startsWith
|
Add JSDoc documentation to string/startsWith
|
JavaScript
|
mit
|
EvanHahn/lildash
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.