commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
cb0c64af73d5b4902b84aecb9a27416429ec1d7a
app/import.js
app/import.js
#!/usr/bin/env node /** * Parse and insert all log lines in a path. */ 'use strict'; var program = require('commander'); // Support all attributes normally defined by config.js. program .option('-p, --parser <name>', 'Ex. nginx_access') .option('-P, --path <file>', 'Ex. /var/log/nginx/access.log') .option('-t, --tags [list]', 'Ex. tag1,tag2', function(list) { return list.split(','); }) .option('-T, --timeAttr [name]', 'Ex. logtime') .option('-r, --previewAttr [name]', 'Ex. message') .parse(process.argv); var source = { parser: program.parser, path: program.path, tags: program.tags, timeAttr: program.timeAttr, previewAttr: program.previewAttr }; if (!source.parser || !source.path) { console.error('--parser and --path are required'); process.exit(1); } GLOBAL.helpers = require(__dirname + '/modules/helpers.js'); var parsers = helpers.requireModule('parsers/parsers'); var lazy = require('lazy'); new lazy(require("fs").createReadStream(source.path)) .lines .map(String) .filter(function(line) { // lazy will convert a blank line to "undefined" return line !== 'undefined'; }) .join(function (lines) { parsers.parseAndInsert(source, lines); });
#!/usr/bin/env node /** * Parse and insert all log lines in a path. */ 'use strict'; var program = require('commander'); var splitCsv = function(list) { return list.split(','); } // Support all attributes normally defined by config.js. program .option('-p, --parser <name>', 'Ex. nginx_access') .option('-P, --path <file>', 'Ex. /var/log/nginx/access.log') .option('-t, --tags [list]', 'Ex. tag1,tag2', splitCsv) .option('-T, --timeAttr [name]', 'Ex. logtime') .option('-r, --previewAttr [name]', 'Ex. message', splitCsv) .parse(process.argv); var source = { parser: program.parser, path: program.path, tags: program.tags, timeAttr: program.timeAttr, previewAttr: program.previewAttr }; if (!source.parser || !source.path) { console.error('--parser and --path are required'); process.exit(1); } GLOBAL.helpers = require(__dirname + '/modules/helpers.js'); var parsers = helpers.requireModule('parsers/parsers'); var lazy = require('lazy'); new lazy(require("fs").createReadStream(source.path)) .lines .map(String) .filter(function(line) { // lazy will convert a blank line to "undefined" return line !== 'undefined'; }) .join(function (lines) { parsers.parseAndInsert(source, lines); });
Allow comma-separated values for --previewAttr.
Allow comma-separated values for --previewAttr.
JavaScript
mit
codeactual/mainevent
--- +++ @@ -8,13 +8,17 @@ var program = require('commander'); +var splitCsv = function(list) { + return list.split(','); +} + // Support all attributes normally defined by config.js. program .option('-p, --parser <name>', 'Ex. nginx_access') .option('-P, --path <file>', 'Ex. /var/log/nginx/access.log') - .option('-t, --tags [list]', 'Ex. tag1,tag2', function(list) { return list.split(','); }) + .option('-t, --tags [list]', 'Ex. tag1,tag2', splitCsv) .option('-T, --timeAttr [name]', 'Ex. logtime') - .option('-r, --previewAttr [name]', 'Ex. message') + .option('-r, --previewAttr [name]', 'Ex. message', splitCsv) .parse(process.argv); var source = {
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
--- +++ @@ -17,11 +17,13 @@ function calculateProp(type, prop) { switch (type.name) { - case 'any': return 'Default ANY' - case 'node': return 'Default NODE' - case 'string': return `Default string ${prop}` + 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)
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
--- +++ @@ -10,21 +10,27 @@ }); - - router.post('/signup', passport.authenticate('local', { - successRedirect : '/home', // redirect to the secure profile section + 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 })); - - /* - -app.use(function (req,res) { - res.render('404', {url:req.url}); -}); - */ - +/* + // - 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}); + }); +*/ };
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
--- +++ @@ -10,13 +10,22 @@ }); - JXT.extendIQ(Forwarded); - JXT.extendPresence(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) {
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
--- +++ @@ -1,12 +1,13 @@ 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: 'fsddf', - clientSecret: 'FACEBOOK_APP_SECRET', + clientID: process.env.APP_ID, + clientSecret: process.env.APP_SECRET, callbackURL: "https://age-guess-api.herokuapp.com" }, function(accessToken, refreshToken, profile, done) { @@ -31,4 +32,12 @@ }) ) +router.get( + '/auth/facebook/secret', + passport.authenticate('facebook', { failureRedirect: '/login' }), + (req, res) => { + res.send('Hello This is A Secret!') + } +) + module.exports = router;
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
--- +++ @@ -23,12 +23,14 @@ /* * 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 + * "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) { - if (req.get('host') === 'localhost:1337') { + let host = req.get('host'); + + if (host === 'localhost:1337' || host === 'backend:1337') { return next(null); }
67b587bd6fd5d91c6bb3930cdcdb288a2c4fd073
packages/core/strapi/lib/commands/routes/list.js
packages/core/strapi/lib/commands/routes/list.js
'use strict'; const CLITable = require('cli-table3'); const chalk = require('chalk'); const { toUpper } = require('lodash/fp'); const strapi = require('../../index'); module.exports = async function() { const app = await strapi().load(); const list = app.server.listRoutes(); const infoTable = new CLITable({ head: [chalk.blue('Method'), chalk.blue('Path')], colWidths: [20, 80], }); list .filter(route => route.methods.length) .forEach(route => { infoTable.push([route.methods.map(toUpper).join('|'), route.path]); }); console.log(infoTable.toString()); await app.destroy(); };
'use strict'; const CLITable = require('cli-table3'); const chalk = require('chalk'); const { toUpper } = require('lodash/fp'); const strapi = require('../../index'); module.exports = async function() { const app = await strapi().load(); const list = app.server.listRoutes(); const infoTable = new CLITable({ head: [chalk.blue('Method'), chalk.blue('Path')], colWidths: [20], }); list .filter(route => route.methods.length) .forEach(route => { infoTable.push([route.methods.map(toUpper).join('|'), route.path]); }); console.log(infoTable.toString()); await app.destroy(); };
Make right column width flexible
Make right column width flexible
JavaScript
mit
wistityhq/strapi,wistityhq/strapi
--- +++ @@ -13,7 +13,7 @@ const infoTable = new CLITable({ head: [chalk.blue('Method'), chalk.blue('Path')], - colWidths: [20, 80], + colWidths: [20], }); list
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
--- +++ @@ -21,6 +21,7 @@ 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') }
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
--- +++ @@ -1,11 +1,41 @@ "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" + }); }); });
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
--- +++ @@ -4,14 +4,15 @@ var collapsedMenus = function() { $('#nav button.navbar-toggle').on('click', function() { - if ($(this).hasClass('collapsed')) { + 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().not('.open')) { + if (!$(this).parent().hasClass('open')) { var collapsedSideMenuHeight; if ($('#nav .navbar-toggle').is(':visible')) { collapsedSideMenuHeight = 133 + 323.5;
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
--- +++ @@ -9,8 +9,13 @@ } function addClass (elem, cls) { - if (!hasClass(elem, cls)) - elem.className += " " + 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) {
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
--- +++ @@ -36,12 +36,22 @@ 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 {
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
--- +++ @@ -6,7 +6,8 @@ * */ -var tar = require('tar'); +var zlib = require('zlib'), + tar = require('tar'); // // ### function download (source, callback) @@ -27,6 +28,12 @@ } } + if (source.gzip) { + source.stream = source.stream + .on('error', finish) + .pipe(zlib.createGunzip()); + } + source.stream .on('error', finish) .pipe(tar.Extract({ path: source.destination }))
cb27231417aac868e459ed8bc4792ac69f51220f
lib/helpers/prepareView.js
lib/helpers/prepareView.js
/*jslint node: true, nomen: true, white: true, unparam: true, todo: true*/ /*! * Sitegear3 * Copyright(c) 2014 Ben New, Sitegear.org * MIT Licensed */ (function (_, path, fs) { "use strict"; module.exports = function (app, dirname) { dirname = dirname || path.join(__dirname, '..', 'viewHelpers'); return function (request, response, next) { app.locals.siteName = app.get('site name'); app.locals.baseUrl = request.secure ? app.get('https url') : app.get('http url'); app.locals.now = new Date(); fs.readdir(dirname, function (error, filenames) { // TODO Handle error _.each(filenames, function (filename) { if (/\.js$/.test(filename)) { var name = path.basename(filename, '.js'); app.locals[name] = require('../viewHelpers/' + filename); } }); next(); }); }; }; }(require('lodash'), require('path'), require('fs')));
/*jslint node: true, nomen: true, white: true, unparam: true, todo: true*/ /*! * Sitegear3 * Copyright(c) 2014 Ben New, Sitegear.org * MIT Licensed */ (function (_, path, fs) { "use strict"; module.exports = function (app, dirname) { dirname = dirname || path.join(__dirname, '..', 'viewHelpers'); return function (request, response, next) { app.locals.siteName = app.get('site name'); app.locals.baseUrl = request.secure ? app.get('https url') : app.get('http url'); app.locals.now = new Date(); fs.readdir(dirname, function (error, filenames) { _.each(filenames, function (filename) { if (/\.js$/.test(filename)) { var name = path.basename(filename, '.js'); app.locals[name] = require('../viewHelpers/' + filename); } }); next(error); }); }; }; }(require('lodash'), require('path'), require('fs')));
Handle error in readdir() callback.
Handle error in readdir() callback.
JavaScript
mit
sitegear/sitegear3
--- +++ @@ -16,14 +16,13 @@ app.locals.now = new Date(); fs.readdir(dirname, function (error, filenames) { - // TODO Handle error _.each(filenames, function (filename) { if (/\.js$/.test(filename)) { var name = path.basename(filename, '.js'); app.locals[name] = require('../viewHelpers/' + filename); } }); - next(); + next(error); }); }; };
6289c7bf271efb6f418904de6fbd46a646e7d86e
vendor/ember-cli-qunit/qunit-configuration.js
vendor/ember-cli-qunit/qunit-configuration.js
/* globals jQuery,QUnit */ QUnit.config.urlConfig.push({ id: 'nocontainer', label: 'Hide container'}); QUnit.config.urlConfig.push({ id: 'nojshint', label: 'Disable JSHint'}); QUnit.config.urlConfig.push({ id: 'doccontainer', label: 'Doc test pane'}); QUnit.config.testTimeout = 60000; //Default Test Timeout 60 Seconds if (QUnit.notifications) { QUnit.notifications({ icons: { passed: '/assets/passed.png', failed: '/assets/failed.png' } }); } jQuery(document).ready(function() { var containerVisibility = QUnit.urlParams.nocontainer ? 'hidden' : 'visible'; var containerPosition = QUnit.urlParams.doccontainer ? 'absolute' : 'relative'; document.getElementById('ember-testing-container').style.visibility = containerVisibility; document.getElementById('ember-testing-container').style.position = containerPosition; });
/* globals jQuery,QUnit */ QUnit.config.urlConfig.push({ id: 'nocontainer', label: 'Hide container'}); QUnit.config.urlConfig.push({ id: 'nojshint', label: 'Disable JSHint'}); QUnit.config.urlConfig.push({ id: 'doccontainer', label: 'Dock test pane'}); QUnit.config.testTimeout = 60000; //Default Test Timeout 60 Seconds if (QUnit.notifications) { QUnit.notifications({ icons: { passed: '/assets/passed.png', failed: '/assets/failed.png' } }); } jQuery(document).ready(function() { var containerVisibility = QUnit.urlParams.nocontainer ? 'hidden' : 'visible'; var containerPosition = QUnit.urlParams.doccontainer ? 'absolute' : 'relative'; document.getElementById('ember-testing-container').style.visibility = containerVisibility; document.getElementById('ember-testing-container').style.position = containerPosition; });
Correct "Doc test pane" to "Dock test pane"
Correct "Doc test pane" to "Dock test pane" This PR so far only changes the string displayed in the UI. The rest of the code still refers to this option as `doccontainer`. Should all these instances also be changed to `dockcontainer`? As an aside, it seems to be called a container in one option ("Hide container") but as a test pane in another ("Doc test pane"). Should these be made consistent?
JavaScript
mit
blimmer/ember-cli-qunit,nathanhammond/ember-cli-qunit,ember-cli/ember-cli-qunit,ember-cli/ember-cli-qunit,nathanhammond/ember-cli-qunit,zenefits/ember-cli-qunit,blimmer/ember-cli-qunit,zenefits/ember-cli-qunit
--- +++ @@ -2,7 +2,7 @@ QUnit.config.urlConfig.push({ id: 'nocontainer', label: 'Hide container'}); QUnit.config.urlConfig.push({ id: 'nojshint', label: 'Disable JSHint'}); -QUnit.config.urlConfig.push({ id: 'doccontainer', label: 'Doc test pane'}); +QUnit.config.urlConfig.push({ id: 'doccontainer', label: 'Dock test pane'}); QUnit.config.testTimeout = 60000; //Default Test Timeout 60 Seconds if (QUnit.notifications) {
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
--- +++ @@ -1,7 +1,6 @@ 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'); @@ -14,8 +13,22 @@ log4js.addAppender(log4js.appenders.file(log_path), 'BOT_LOG'); } -setInterval(checkTL, 500); +var logger = log4js.getLogger('BOT_LOG'); -function checkTL() { +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.'); + +});
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
--- +++ @@ -2,11 +2,11 @@ import b32 from 'thirty-two' export function cleanKey (key) { - return key.replace(/[^a-z2-7]+/g, '').slice(0, 32) + return key.replace(/[^a-z2-7]+/ig, '').toLowerCase() } export function isValidKey (key) { - return /^[a-z2-7]{32}$/.test(cleanKey(key)) + return /^[a-z2-7]+$/.test(cleanKey(key)) } export function getCode (key) {
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
--- +++ @@ -1,23 +1,45 @@ -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 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; -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)`); -} + -- 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$$`);
e4912f3076fda14ebfe50250e2061447db1b6281
lib/bggCollectionParser.js
lib/bggCollectionParser.js
module.exports = { "parseResults": function(result) { var xmlItems = result.items && result.items.item; var items = []; if (xmlItems) { for (var i = 0; i < xmlItems.length; i++) { var game = xmlItems[i]; items.push({ "subtype": game.$.subtype, "objectid": game.$.objectid, "collid": game.$.collid, "name": game.name || game.name[0]._, "image": game.image || game.image[0], "thumbnail": game.thumbnail || game.thumbnail[0] }); } } return items; } };
module.exports = { "parseResults": function(result) { var xmlItems = result.items && result.items.item; var items = []; if (xmlItems) { for (var i = 0; i < xmlItems.length; i++) { var game = xmlItems[i]; items.push({ "subtype": game.$.subtype, "objectid": game.$.objectid, "collid": game.$.collid, "name": game.name && game.name[0]._, "image": game.image && game.image[0], "thumbnail": game.thumbnail && game.thumbnail[0] }); } } return items; } };
Fix bad error checking - caused name/image/thumbnail to be arrays
Fix bad error checking - caused name/image/thumbnail to be arrays
JavaScript
apache-2.0
thealah/bgg,thealah/bgg
--- +++ @@ -10,9 +10,9 @@ "subtype": game.$.subtype, "objectid": game.$.objectid, "collid": game.$.collid, - "name": game.name || game.name[0]._, - "image": game.image || game.image[0], - "thumbnail": game.thumbnail || game.thumbnail[0] + "name": game.name && game.name[0]._, + "image": game.image && game.image[0], + "thumbnail": game.thumbnail && game.thumbnail[0] }); } }
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
--- +++ @@ -8,4 +8,17 @@ 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'); + }); });
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
--- +++ @@ -14,6 +14,9 @@ module.exports.vue = function() { return {}; }; + * or +module.exports.vue = { +}; */ /*
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
--- +++ @@ -25,9 +25,7 @@ DefaultButton.storyName = 'Default Button'; DefaultButton.args = { children: 'Default Button', - onClick() { - return new Promise( ( resolve ) => setTimeout( resolve, 5000 ) ); - }, + onClick: () => new Promise( ( resolve ) => setTimeout( resolve, 5000 ) ), }; export default {
f55caf4ed86b4c23e4cb4b5c1f789ac6db28ab64
rollup/rollup.umd.config.js
rollup/rollup.umd.config.js
import babel from 'rollup-plugin-babel'; import mergeBaseConfig from './rollup.merge-base-config.js'; const cjsConfig = { format: 'umd', moduleName: 'knockoutStore', plugins: [ babel({ exclude: 'node_modules/**' }) ], dest: 'dist/knockout-store.js' }; const finalConfig = mergeBaseConfig(cjsConfig); export default finalConfig;
import babel from 'rollup-plugin-babel'; import mergeBaseConfig from './rollup.merge-base-config.js'; const cjsConfig = { format: 'umd', moduleName: 'ko.store', plugins: [ babel({ exclude: 'node_modules/**' }) ], dest: 'dist/knockout-store.js' }; const finalConfig = mergeBaseConfig(cjsConfig); export default finalConfig;
Change umd module name to ko.store.
Change umd module name to ko.store.
JavaScript
mit
Spreetail/knockout-store
--- +++ @@ -3,7 +3,7 @@ const cjsConfig = { format: 'umd', - moduleName: 'knockoutStore', + moduleName: 'ko.store', plugins: [ babel({ exclude: 'node_modules/**'
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
--- +++ @@ -19,16 +19,14 @@ }); it('renders expected number of children', () => { - const [component] = render( + render( <Segments> <Segment>Top</Segment> <Segment>Middle</Segment> <Segment>Bottom</Segment> </Segments> - ).scryClass('sd-segments'); - - expect( - component.querySelectorAll('.sd-segment').length - ).to.equal(3); + ) + .scryClass('sd-segment') + .should.have.a.lengthOf(3); }); });
da023a20791530444e6475e905349881c2267972
app/js/arethusa.context_menu/directives/plugin_context_menu.js
app/js/arethusa.context_menu/directives/plugin_context_menu.js
'use strict'; angular.module('arethusa.contextMenu').directive('pluginContextMenu', function () { return { restrict: 'E', scope: true, replace: true, link: function (scope, element, attrs) { scope.plugin = scope.$eval(attrs.name); }, template: ' <div id="{{ plugin.name }}-context-menu" ng-include="plugin.contextMenuTemplate"> </div> ' }; });
'use strict'; angular.module('arethusa.contextMenu').directive('pluginContextMenu', function () { return { restrict: 'E', scope: true, replace: true, link: function (scope, element, attrs) { scope.plugin = scope.$eval(attrs.name); }, template: '\ <div id="{{ plugin.name }}-context-menu"\ ng-include="plugin.contextMenuTemplate">\ </div>\ ' }; });
Fix multiline string in pluginContextMenu template
Fix multiline string in pluginContextMenu template
JavaScript
mit
PonteIneptique/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,latin-language-toolkit/arethusa,Masoumeh/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa
--- +++ @@ -7,6 +7,10 @@ link: function (scope, element, attrs) { scope.plugin = scope.$eval(attrs.name); }, - template: ' <div id="{{ plugin.name }}-context-menu" ng-include="plugin.contextMenuTemplate"> </div> ' + template: '\ + <div id="{{ plugin.name }}-context-menu"\ + ng-include="plugin.contextMenuTemplate">\ + </div>\ + ' }; });
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
--- +++ @@ -5,7 +5,9 @@ chrome.app.window.create('index.html', { innerBounds: { width: 960, - height: 600 + height: 600, + minWidth: 960, + minHeight: 600 }, state: 'maximized' });
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
--- +++ @@ -12,6 +12,6 @@ // Update number on navigate to a new thread chrome.webNavigation.onCompleted.addListener(function (details) { - getUnreadThreads(null); + ITCheck.getUnreadThreadCount(null); },{url: [{hostSuffix: 'ivorytower.com', pathPrefix: '/IvoryTower/ForumThread.aspx'}]}); })(window);
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
--- +++ @@ -20,6 +20,9 @@ // Report text text: String, + // Parser options + params_ref: Schema.ObjectId, + // User _id from: Schema.ObjectId },
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
--- +++ @@ -1,7 +1,7 @@ import { createComponent } from 'react-fela' const View = props => ({ - display: props.hidden && 'none', + display: props.hidden ? 'none' : 'flex', zIndex: props.zIndex, position: 'fixed', top: 0,
98070f6292954c7190f7aaa52c3f5c86a88fe039
src/constants.es6.js
src/constants.es6.js
export default { TOGGLE_OVER_18: 'toggleOver18', SIDE_NAV_TOGGLE: 'sideNavToggle', TOP_NAV_HAMBURGER_CLICK: 'topNavHamburgerClick', VOTE: 'vote', DROPDOWN_OPEN: 'dropdownOpen', COMPACT_TOGGLE: 'compactToggle', TOP_NAV_HEIGHT: 45, RESIZE: 'resize', SCROLL: 'scroll', ICON_SHRUNK_SIZE: 16, CACHEABLE_COOKIES: ['compact'], DEFAULT_API_TIMEOUT: 5000, };
export default { TOGGLE_OVER_18: 'toggleOver18', SIDE_NAV_TOGGLE: 'sideNavToggle', TOP_NAV_HAMBURGER_CLICK: 'topNavHamburgerClick', VOTE: 'vote', DROPDOWN_OPEN: 'dropdownOpen', COMPACT_TOGGLE: 'compactToggle', TOP_NAV_HEIGHT: 45, RESIZE: 'resize', SCROLL: 'scroll', ICON_SHRUNK_SIZE: 16, CACHEABLE_COOKIES: ['compact'], DEFAULT_API_TIMEOUT: 10000, };
Increase API timeout to 10s
Increase API timeout to 10s Accomodate slow/whoalaned requests, like the google crawler. It was set to 5s previously when we thought that api requests were causing the request queue to back up, which does not appear to be the case.
JavaScript
mit
uzi/reddit-mobile,madbook/reddit-mobile,uzi/reddit-mobile,DogPawHat/reddit-mobile,DogPawHat/reddit-mobile,curioussavage/reddit-mobile,curioussavage/reddit-mobile,madbook/reddit-mobile,madbook/reddit-mobile,uzi/reddit-mobile
--- +++ @@ -10,5 +10,5 @@ SCROLL: 'scroll', ICON_SHRUNK_SIZE: 16, CACHEABLE_COOKIES: ['compact'], - DEFAULT_API_TIMEOUT: 5000, + DEFAULT_API_TIMEOUT: 10000, };
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
--- +++ @@ -5,20 +5,17 @@ ) { 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 = []; + // 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 () { - promises.push(replaceValue.apply(undefined, arguments)); + values.push(replaceValue.apply(undefined, arguments)); return ""; }); - return Promise.all(promises).then(function (values) { + return Promise.all(values).then(function (resolvedValues) { return String.prototype.replace.call(string, searchValue, function () { - return values.shift(); + return resolvedValues.shift(); }); }); } else {
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
--- +++ @@ -1,4 +1,5 @@ -// cavy-cli reporter class. +// 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() {
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
--- +++ @@ -1,8 +1,6 @@ -require('./lib/metro-transit') +var MetroTransit = 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); + MetroTransit.execute(event, context); };
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
--- +++ @@ -18,6 +18,8 @@ className, } = props; + const kids = typeof(children.type) === "function" ? children.type( children.props ) : [ ...children ]; + return React.createElement( tag, { className: classnames( @@ -25,7 +27,7 @@ setWeight( props ), className ) }, - [ ...children ] + kids ); }
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
--- +++ @@ -17,7 +17,7 @@ } ModelRenderer.prototype.toJSON = function toJSON() { - return this; + return R.mapObj(R.identity, this); }; ModelRenderer.prototype.toString = function toString() {
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
--- +++ @@ -1,5 +1,32 @@ +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'); +});
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
--- +++ @@ -4,10 +4,14 @@ * 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; + 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; } @@ -16,14 +20,13 @@ * 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; + 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;
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
--- +++ @@ -14,17 +14,20 @@ 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/'; - + } + + 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)) + .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); }); }
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
--- +++ @@ -1,26 +1,20 @@ -var _ = require('underscore'); +require('es6-promise').polyfill(); + +var _ = require('lodash'); 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 + * @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(config, method){ - app[method](route, utils.loadStack( - config, - middleware, - fixture, - service.bind(null, services), - transform, - view - )); + _.each(methods, function(configs, method){ + app[method.toLowerCase()](route, utils.loadStack(configs, services)); }); }); };
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
--- +++ @@ -14,11 +14,11 @@ return <span /> } else { return ( - <div className='tv-loading-progress' ref='tooltip' onMouseOver={this._onHover}> + <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' /> + <span className='icon icon-info' ref='tooltip' onMouseOver={this._onHover} /> <progress className='inline-block' max={this.props.totalCount} value={this.props.readyCount} /> </div>) }
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
--- +++ @@ -12,6 +12,9 @@ }); request .get(url) + .on('error', error => { + callback(error); + }) .pipe(stream); };
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
--- +++ @@ -15,13 +15,13 @@ transport.get(url + encodeURIComponent(search), function (res) { var data = ''; res.setEncoding('utf8'); - res.on('data', (chunk) => { - data += chunk; - }); - res.on('end', () => { + res.on('data', function (chunk) { + data += chunk; + }); + res.on('end', function () { var result; try { - result = JSON.parse(data); + result = JSON.parse(data); } catch(e) { return done(new Error('Cannot parse Vicopo answear:\n' + e + '\n' + data)); } @@ -30,7 +30,7 @@ } else { done(new Error('The answear should contains a cities list:\n' + data)); } - }); + }); }) .on('error', done); };
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
--- +++ @@ -1,7 +1,7 @@ "use strict"; // modified from https://github.com/es-shims/es6-shim -var keys = require('object-keys'); +var keys = Object.keys || require('object-keys'); var isObject = function (obj) { return typeof obj !== 'undefined' && obj !== null; };
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
--- +++ @@ -3,7 +3,7 @@ module.exports = { rules: { "sort-object-props": function(context) { - var ignoreCase = context.options[0].ignoreCase; + var caseSensitive = context.options[0].caseSensitive; var ignoreMethods = context.options[0].ignoreMethods; var MSG = "Property names in object literals should be sorted"; return { @@ -21,9 +21,7 @@ lastPropId = lastProp.key.value; propId = prop.key.value; } - if (ignoreCase) { - if (propId == null) - console.log(prop); + if (caseSensitive) { lastPropId = lastPropId.toLowerCase(); propId = propId.toLowerCase(); } @@ -37,6 +35,6 @@ } }, rulesConfig: { - "sort-object-props": [ 1, { ignoreCase: true, ignoreMethods: false } ] + "sort-object-props": [ 1, { caseSensitive: false, ignoreMethods: false } ] } };
b99f91a8f9259cf867cd522f4164aed4a83c2e72
index.js
index.js
'use strict'; var Q = require('q'); var request = Q.denodeify(require('request')); var chromecastHomeURL = 'https://clients3.google.com/cast/chromecast/home/v/c9541b08'; var initJSONStateRegex = /(JSON\.parse\(.+'\))/; var parseChromecastHome = function(htmlString) { var JSONParse = htmlString.match(initJSONStateRegex)[1]; var initState = eval(JSONParse); // I don't know why this is ok but JSON.parse fails. var parsedBackgrounds = []; for (var i in initState[1]) { var backgroundEntry = { url: initState[1][i][1], author: initState[1][i][2] }; parsedBackgrounds.push(backgroundEntry); } return parsedBackgrounds; }; module.exports = function() { return request(chromecastHomeURL).then(function(requestResult) { return parseChromecastHome(requestResult[1]); }); };
'use strict'; var Q = require('q'); var request = Q.denodeify(require('request')); var chromecastHomeURL = 'https://clients3.google.com/cast/chromecast/home/v/c9541b08'; var initJSONStateRegex = /(JSON\.parse\(.+'\))/; var parseChromecastHome = function(htmlString) { var JSONParse = htmlString.match(initJSONStateRegex)[1]; var initState = eval(JSONParse); // I don't know why this is ok but JSON.parse fails. var parsedBackgrounds = []; for (var i in initState[0]) { var backgroundEntry = { url: initState[0][i][0], author: initState[0][i][1] }; parsedBackgrounds.push(backgroundEntry); } return parsedBackgrounds; }; module.exports = function() { return request(chromecastHomeURL).then(function(requestResult) { return parseChromecastHome(requestResult[1]); }); };
Fix parsing of initState JSON as noticed by @aawc
Fix parsing of initState JSON as noticed by @aawc
JavaScript
mit
apeddinti/chromecast-backgrounds,dconnolly/chromecast-backgrounds,DKbyo/chromecast-windows-theme,adz/chromecast-backgrounds,Wiseup/chromecast-backgrounds
--- +++ @@ -10,10 +10,10 @@ var JSONParse = htmlString.match(initJSONStateRegex)[1]; var initState = eval(JSONParse); // I don't know why this is ok but JSON.parse fails. var parsedBackgrounds = []; - for (var i in initState[1]) { + for (var i in initState[0]) { var backgroundEntry = { - url: initState[1][i][1], - author: initState[1][i][2] + url: initState[0][i][0], + author: initState[0][i][1] }; parsedBackgrounds.push(backgroundEntry); }
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
--- +++ @@ -13,8 +13,6 @@ app.set('view engine', 'ejs'); app.get('/', function(request, response) { - var promise = certificate.getCertificationData(); - certificate.getCertificationData().then(function(data) { responseData = { certInfo: JSON.stringify(data),
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
--- +++ @@ -21,8 +21,13 @@ 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); + thing.save(function(err) { + if (err) { + res.send(500); + } else { + res.send("Created a new thing with name " + thing.name); + } + }); } else { res.send(t); }
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
--- +++ @@ -7,7 +7,8 @@ 'link', 'description', 'date_updated', - 'date_published' + 'date_published', + 'author_id' ]; const DEFAULT_ORDER = [
244745bf47320a759e403beea0ecb71f178509c6
spec/specs.js
spec/specs.js
describe('pingPong', function() { it("is true for a number that is divisible by 3", function() { expect(pingPong(6)).to.equal(true); }); it("is true for a number that is divisible by 5", function() { expect(pingPong(10)).to.equal(True) } });
describe('pingPong', function() { it("is true for a number that is divisible by 3", function() { expect(pingPong(6)).to.equal(true); }); it("is true for a number that is divisible by 5", function() { expect(pingPong(10)).to.equal(True) }); });
Fix syntax error on previous commit
Fix syntax error on previous commit
JavaScript
mit
kcmdouglas/pingpong,kcmdouglas/pingpong
--- +++ @@ -5,6 +5,6 @@ it("is true for a number that is divisible by 5", function() { expect(pingPong(10)).to.equal(True) - } + }); });
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
--- +++ @@ -19,7 +19,7 @@ CommunitiesSvc.find($scope.community.id).then(function(community) { $timeout(function() { community.toggleParticipant(); - angular.extend($scope.community, community); + $scope.community.participants = community.participants; }); }); }
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
--- +++ @@ -13,17 +13,21 @@ 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(); - } - }); + 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(); + } } };
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
--- +++ @@ -15,6 +15,14 @@ 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) { @@ -22,5 +30,6 @@ province: province['name'], schools: arr }) + appendArray(arr) }) })
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
--- +++ @@ -1,7 +1,7 @@ /** * Initialize Pattern builder plugin. */ -;(function ($) { +;(function () { var pluginName = 'patternMaker', pluginDefaults = { @@ -35,13 +35,13 @@ * * @param {object} options Initialization options */ - $.fn[pluginName] = function(options) { + jQuery.fn[pluginName] = function(options) { return this.each(function () { - if (!$.data(this, "plugin_" + pluginName)) { - $.data(this, "plugin_" + pluginName); + if (!jQuery.data(this, "plugin_" + pluginName)) { + jQuery.data(this, "plugin_" + pluginName); new Plugin(this, options); } }); }; -})(jQuery); +})();
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
--- +++ @@ -3,15 +3,7 @@ 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.task('watch', ['build', 'serve'], function () { gulp.watch('./app/**/*.html', ['html']); gulp.watch('./app/**/*.js', ['js']); @@ -20,3 +12,11 @@ }); }); +gulp.task('serve', function () { + browserSync({ + server: { + baseDir: './dist' + } + }); +}); +
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
--- +++ @@ -1,3 +1,5 @@ +/* globals _ */ + (function () { 'use strict'; @@ -5,43 +7,38 @@ el: '.js-Conditional', init: function () { - var _this = this; - + _.bindAll(this, 'render'); 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)); - }); + this.$conditionals.on('change deselect', this.toggle); + moj.Events.on('render', this.render); }, cacheEls: function () { this.$conditionals = $(this.el); }, - toggleEl: function (el) { - var $el = 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');
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
--- +++ @@ -20,11 +20,14 @@ }, action) => { switch (action.type) { case types.PAGE_CHANGE: - return Object.assign({}, state, { - pathname: action.path, + 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
5d4ce6182c59c0c15aed5646809c39e4d67c839e
enums.spec.js
enums.spec.js
var enums = require("./enum.js"); describe("Enum", function() { it("can have symbols with custom properties", function() { var color = new enums.Enum({ red: { de: "rot" }, green: { de: "grün" }, blue: { de: "blau" }, }); function translate(c) { return c.de; } expect(translate(color.green)).toEqual("grün"); }); it("can check for symbol membership", function() { var color = new enums.Enum("red", "green", "blue"); var fruit = new enums.Enum("apple", "banana"); expect(color.contains(color.red)).toBeTruthy(); expect(color.contains(fruit.apple)).toBeFalsy(); }); });
var enums = require("./enums.js"); describe("Enum", function() { it("can have symbols with custom properties", function() { var color = new enums.Enum({ red: { de: "rot" }, green: { de: "grün" }, blue: { de: "blau" }, }); function translate(c) { return c.de; } expect(translate(color.green)).toEqual("grün"); }); it("can check for symbol membership", function() { var color = new enums.Enum("red", "green", "blue"); var fruit = new enums.Enum("apple", "banana"); expect(color.contains(color.red)).toBeTruthy(); expect(color.contains(fruit.apple)).toBeFalsy(); }); });
Use correct file name to require enums.js
Use correct file name to require enums.js
JavaScript
mit
rauschma/enums
--- +++ @@ -1,4 +1,4 @@ -var enums = require("./enum.js"); +var enums = require("./enums.js"); describe("Enum", function() { it("can have symbols with custom properties", function() {
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
--- +++ @@ -14,7 +14,7 @@ // 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) { + _.each(_.clone(events), e => { // Calculate the duration of the event; this determines // how many segments it will be in
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
--- +++ @@ -3,8 +3,8 @@ ) export const getTitle = (data) => ( - data.about && data.about.name - ? data.about.name + data.about && (data.about.name || data.about['@id']) + ? data.about.name || data.about['@id'] : data.totalItems + " Entries" )
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
--- +++ @@ -28,7 +28,7 @@ slug: 'stackoverflow', seUrl: 'http://stackoverflow.com/', langs: ['en', 'fr'], - db: 'localhost/programmers', + db: 'localhost/stackoverflow', }, { name: 'Android', slug: 'android',
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
--- +++ @@ -1,31 +1,13 @@ -// 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 || {} +var _binary_koan$elm_spruce$Native_Spruce = function() { - // `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 +function listen(address, program) { + console.log(address) - // return the object of your module's stuff! - return elm.Native.Spruce.values = { - listen(address, server) { - console.log(address, server) - - return server - } - } + return program } -// 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; +return { + toHtml: F2(listen) +} + +}()
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
--- +++ @@ -7,15 +7,29 @@ Fetcher = require("l2b-price-fetchers"); -module.exports.getBookDetails = function (isbn, cb) { - - var f = new Fetcher(); - f.fetch( +function getBookDetails (isbn, cb) { + fetchFromScrapers( {vendor: "foyles", isbn: isbn }, - function (err, data) { + function (err, results) { if (err) { return cb(err); } - var returnData = _.pick(data, "isbn", "authors", "title"); + 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, };
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
--- +++ @@ -8,6 +8,7 @@ let bodyParser = require('body-parser') let morgan = require('morgan') let routes = require('./api/routes') +let extensions = require('./extensions/registry') dotenv.config({silent: true}) @@ -22,12 +23,15 @@ 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) })
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
--- +++ @@ -16,8 +16,8 @@ 'd3.parcoords': { 'has by default': { topic: d3Parcoords(), - 'three brush modes': function(pc) { - assert.strictEqual(pc.brushModes().length, 3); + 'four brush modes': function(pc) { + assert.strictEqual(pc.brushModes().length, 4); }, 'the brush mode "None"': function(pc) { assert.notStrictEqual(pc.brushModes().indexOf("None"), -1); @@ -27,6 +27,9 @@ }, '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); } }, }
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
--- +++ @@ -1,6 +1,6 @@ Package.describe({ summary: "Login service for VKontakte accounts (https://vk.com)", - version: "0.1.4", + version: "0.2.0", git: "https://github.com/alexpods/meteor-accounts-vk", name: "mrt:accounts-vk" }); @@ -11,13 +11,14 @@ 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('service-configuration', ['client', 'server']); api.use('templating', 'client'); api.add_files("lib/accounts_vk.js");
4462762d313e3f7e3535101c576488e2e2ae2374
package.js
package.js
Package.describe({ summary: "Reactive bootstrap modals for meteor", version: "1.0.5", git: "https://github.com/jchristman/reactive-modal.git", name: "jchristman:reactive-modal" }); Package.on_use(function (api) { if(api.versionsFrom){ api.versionsFrom('METEOR@1.0'); } api.use(['underscore', 'jquery','templating', 'reactive-var@1.0.6'], 'client'); api.add_files(['lib/reactive-modal.html', 'lib/reactive-modal.js', 'lib/ev.js'], "client"); api.export('ReactiveModal', ['client']); });
Package.describe({ summary: "Reactive bootstrap modals for meteor", version: "1.0.5", git: "https://github.com/jchristman/reactive-modal.git", name: "jchristman:reactive-modal" }); Package.on_use(function (api) { if(api.versionsFrom){ api.versionsFrom('METEOR@1.0'); } api.use(['underscore', 'jquery','templating', 'reactive-var@1.0.5'], 'client'); api.add_files(['lib/reactive-modal.html', 'lib/reactive-modal.js', 'lib/ev.js'], "client"); api.export('ReactiveModal', ['client']); });
Update depedencies and version number
Update depedencies and version number
JavaScript
mit
jchristman/reactive-modal,jchristman/reactive-modal
--- +++ @@ -9,7 +9,7 @@ if(api.versionsFrom){ api.versionsFrom('METEOR@1.0'); } - api.use(['underscore', 'jquery','templating', 'reactive-var@1.0.6'], 'client'); + api.use(['underscore', 'jquery','templating', 'reactive-var@1.0.5'], 'client'); api.add_files(['lib/reactive-modal.html', 'lib/reactive-modal.js', 'lib/ev.js'], "client"); api.export('ReactiveModal', ['client']); });
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
--- +++ @@ -1 +1,11 @@ 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>"); +})();
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
--- +++ @@ -2,21 +2,28 @@ describe('auth middleware', () => { const middleware = createAuthMiddleware() - const nextHandler = middleware({}) - const actionHandler = nextHandler() - test('it returns a function that handles store', () => { + it('returns a function that handles {getState, dispatch}', () => { 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) + describe('store handler', () => { + it('returns function that handles next', () => { + const nextHandler = middleware({}) + + 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) + 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) + }) }) })
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
--- +++ @@ -12,8 +12,6 @@ var format = require('./format.js')(flags); -console.log(argv) - /** * Main procedure */ @@ -26,13 +24,13 @@ data = format.format(data); - if (argv.s || argv.stdio) { - console.log(data); - } else { + 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); } }); });
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
--- +++ @@ -18,13 +18,7 @@ } renderChildren(props) { - let {children} = props; - - if (children == null) { - children = <div />; - } - - ReactDOM.render(children, this.nodeEl, this.props.onRender); + ReactDOM.render(props.children, this.nodeEl, props.onRender); } render() { @@ -33,7 +27,7 @@ } Portal.propTypes = { - children: PropTypes.node, + children: PropTypes.node.isRequired, onRender: PropTypes.func };
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
--- +++ @@ -23,6 +23,4 @@ }.bind(this)); }; -BasePickerView.prototype._onSelect = function () {}; - module.exports = BasePickerView;
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
--- +++ @@ -1,17 +1,5 @@ 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>` -} +import { getRestrictedSize } from '../../src/helpers/file_helper' describe('file helpers', () => { context('#getRestrictedSize', () => { @@ -28,18 +16,5 @@ 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') - }) })
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
--- +++ @@ -1,7 +1,7 @@ // http://unheap.com $(function() { - $('.browsehappy').on('click', function() { - $(this).slideUp('fast'); + $('.browsehappy').click(function() { + $(this).slideUp(); }); });
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
--- +++ @@ -1,4 +1,3 @@ import App from './app'; -import 'babel-polyfill'; common.app = new App(common); common.app.start();
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
--- +++ @@ -21,9 +21,6 @@ // 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' ],
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
--- +++ @@ -2,10 +2,12 @@ var assert = require( 'assert' ) var nock = require( 'nock' ) +var ACME_API_BASE_URL = 'https://api.example.com' + suite( 'ACME', function() { - var client = new ACME({ - baseUrl: 'https://api.example.com', + var client = new ACME.Client({ + baseUrl: ACME_API_BASE_URL, }) test( 'throws an error if baseUrl is not a string', function() { @@ -16,13 +18,13 @@ 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' + '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( 'https://api.example.com' ) + nock( ACME_API_BASE_URL ) .get( '/directory' ) .reply( 200, payload )
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
--- +++ @@ -1,11 +1,49 @@ +'use strict'; + 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(); + 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(); + }); }); });
ad49b5c4e7e355fc7533a62b232bcdb94e3ec152
lib/client.js
lib/client.js
/** * Module dependencies. */ var redis = require('redis'); exports = module.exports = function(settings, logger) { var config = settings.toObject(); if (!config.host) { throw new Error('Redis host not set in config'); } var host = config.host; var port = config.port || 6379; var client = redis.createClient(port, host); // NOTE: By default, if the connection to Redis is closed, the process will // exit. In accordance with a microservices architecture, it is // expected that a higher-level monitor will detect process termination // and restart as necessary. client.on('close', function() { logger.error('Redis connection closed'); process.exit(-1); }); // NOTE: By default, if an error is encountered from Redis it will be // rethrown. This will cause an `uncaughtException` within Node and the // process will exit. In accordance with a microservices architecture, // it is expected that a higher-level monitor will detect process // failures and restart as necessary. client.on('error', function(err) { logger.error('Unexpected error from Redis: %s', err.message); logger.error(err.stack); throw err; }); return client; } /** * Component annotations. */ exports['@singleton'] = true; exports['@require'] = ['settings', 'logger'];
/** * Module dependencies. */ var redis = require('redis'); exports = module.exports = function(settings, logger) { var config = settings.toObject(); if (!config.host) { throw new Error('Redis host not set in config'); } var host = config.host; var port = config.port || 6379; var db = config.db; var client = redis.createClient(port, host); if (db) { logger.debug('Selecting Redis database %d', db); client.select(db); } // NOTE: By default, if the connection to Redis is closed, the process will // exit. In accordance with a microservices architecture, it is // expected that a higher-level monitor will detect process termination // and restart as necessary. client.on('close', function() { logger.error('Redis connection closed'); process.exit(-1); }); // NOTE: By default, if an error is encountered from Redis it will be // rethrown. This will cause an `uncaughtException` within Node and the // process will exit. In accordance with a microservices architecture, // it is expected that a higher-level monitor will detect process // failures and restart as necessary. client.on('error', function(err) { logger.error('Unexpected error from Redis: %s', err.message); logger.error(err.stack); throw err; }); return client; } /** * Component annotations. */ exports['@singleton'] = true; exports['@require'] = ['settings', 'logger'];
Add option to select database by index.
Add option to select database by index.
JavaScript
mit
bixbyjs/bixby-redis
--- +++ @@ -5,12 +5,17 @@ exports = module.exports = function(settings, logger) { - var config = settings.toObject(); - if (!config.host) { throw new Error('Redis host not set in config'); } - var host = config.host; - var port = config.port || 6379; + var config = settings.toObject(); + if (!config.host) { throw new Error('Redis host not set in config'); } + var host = config.host; + var port = config.port || 6379; + var db = config.db; var client = redis.createClient(port, host); + if (db) { + logger.debug('Selecting Redis database %d', db); + client.select(db); + } // NOTE: By default, if the connection to Redis is closed, the process will // exit. In accordance with a microservices architecture, it is
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
--- +++ @@ -31,6 +31,8 @@ domEvent.preventDefault(); } + domEvent.domItem = elm; + instance.flow(event)[listener.end ? 'end' : 'write'](listener.noDomData ? {} : domEvent); }); });
5583da7b0961b3f3d94ff08faf606fa5fbaab5f9
tests.js
tests.js
var logit = require('./main'); var logger = logit({ prefix: 'my app', date: true }); logger.info("Test 1"); logger.debug("Test 2"); logger.warn("Test 3"); logger.error("Test 4"); logger = logit({ prefix: 'my app', date: false }); logger.error("Test 5"); logger = logit({ prefix: 'my new app', date: false }); logger.error("Test 6"); logger = logit(); logger.error("Test 7"); var obj = {"data": "test", "another data": 2}; logger.info(obj); var tab = ["el1", "el2"]; logger.info(tab); logger.info('arg1', 'arg2'); fs = require('fs'); fs.lstat('notexist', function(err) { logger.error(err); });
var logit = require('./main'); var logger = logit({ prefix: 'my app', date: true }); logger.info("Test 1"); logger.debug("Test 2"); logger.warn("Test 3"); logger.error("Test 4"); logger = logit({ prefix: 'my app', date: false }); logger.error("Test 5"); logger = logit({ prefix: 'my new app', date: false }); logger.error("Test 6"); logger = logit(); logger.error("Test 7"); var obj = {"data": "test", "another data": 2}; logger.info(obj); var tab = ["el1", "el2"]; logger.info(tab); logger.info('arg1', 'arg2'); logger.lineBreak(); fs = require('fs'); fs.lstat('notexist', function(err) { logger.error(err); });
Add a test for lineBreak command
Add a test for lineBreak command
JavaScript
mit
cozy/printit,nono/printit
--- +++ @@ -32,6 +32,7 @@ logger.info(tab); logger.info('arg1', 'arg2'); +logger.lineBreak(); fs = require('fs');
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
--- +++ @@ -7,13 +7,14 @@ 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); -const defaultTransforms = transforms - .set(PlotlyTransform.MIMETYPE, PlotlyTransform) - .set(GeoJSONTransform.MIMETYPE, GeoJSONTransform); - export { defaultDisplayOrder, defaultTransforms };
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
--- +++ @@ -2,8 +2,10 @@ import { autoUpdater } from "electron-updater"; export function initAutoUpdater() { - const log = require("electron-log"); - log.transports.file.level = "info"; - autoUpdater.logger = log; - autoUpdater.checkForUpdatesAndNotify(); + if (process.env.NTERACT_DESKTOP_DISABLE_AUTO_UPDATE !== "1") { + const log = require("electron-log"); + log.transports.file.level = "info"; + autoUpdater.logger = log; + autoUpdater.checkForUpdatesAndNotify(); + } }
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
--- +++ @@ -18,7 +18,7 @@ OpenLayers.i18n(k), '</th>', '<td>', - attributes[k], + OpenLayers.String.format(attributes[k], App), '</td>', '</tr>' ]);
60b6dce28eaaa22987acb0000977a7646066cce0
web-test-runner.config.js
web-test-runner.config.js
const {playwrightLauncher} = require('@web/test-runner-playwright'); const defaultBrowsers = [ playwrightLauncher({product: 'chromium'}), playwrightLauncher({product: 'webkit'}), playwrightLauncher({product: 'firefox', concurrency: 1}), ]; const envBrowsers = process.env.BROWSERS && process.env.BROWSERS.split(',').map((product) => playwrightLauncher({product}) ); const browsers = envBrowsers ?? defaultBrowsers; module.exports = { files: `packages/scoped-custom-element-registry/test/**/*.test.(js|html)`, nodeResolve: true, concurrency: 10, browsers, };
const {playwrightLauncher} = require('@web/test-runner-playwright'); const defaultBrowsers = [ playwrightLauncher({product: 'chromium'}), playwrightLauncher({product: 'webkit'}), playwrightLauncher({product: 'firefox', concurrency: 1}), ]; const envBrowsers = process.env.BROWSERS && process.env.BROWSERS.split(',').map((product) => playwrightLauncher({product}) ); const browsers = envBrowsers || defaultBrowsers; module.exports = { files: `packages/scoped-custom-element-registry/test/**/*.test.(js|html)`, nodeResolve: true, concurrency: 10, browsers, };
Fix new JS for old node
Fix new JS for old node
JavaScript
bsd-3-clause
webcomponents/polyfills,webcomponents/polyfills,webcomponents/polyfills
--- +++ @@ -12,7 +12,7 @@ playwrightLauncher({product}) ); -const browsers = envBrowsers ?? defaultBrowsers; +const browsers = envBrowsers || defaultBrowsers; module.exports = { files: `packages/scoped-custom-element-registry/test/**/*.test.(js|html)`,
5650dbb2c03ff9d045782cbb9175403b40d24985
lib/hooks/init/setting_usergroups_fetcher.js
lib/hooks/init/setting_usergroups_fetcher.js
// Register 'usergroups' special setting values fetcher. // Allows to use `values: usergroups` in setting definitions. 'use strict'; var _ = require('lodash'); module.exports = function (N) { N.wire.before('init:settings', function (sandbox) { sandbox.selectionListFetchers['usergroups'] = function fetchUserGroups(callback) { N.models.users.UserGroup .find() .select('_id short_name') .sort('_id') .setOptions({ lean: true }) .exec(function (err, groups) { callback(err, _.map(groups, function (group) { return { name: group.short_name , value: group._id , title: 'admin.users.usergroup_names.' + group.short_name }; })); }); }; }); };
// Register 'usergroups' special setting values fetcher. // Allows to use `values: usergroups` in setting definitions. 'use strict'; var _ = require('lodash'); module.exports = function (N) { N.wire.before('init:__settings', function (sandbox) { sandbox.selectionListFetchers['usergroups'] = function fetchUserGroups(callback) { N.models.users.UserGroup .find() .select('_id short_name') .sort('_id') .setOptions({ lean: true }) .exec(function (err, groups) { callback(err, _.map(groups, function (group) { return { name: group.short_name , value: group._id , title: 'admin.users.usergroup_names.' + group.short_name }; })); }); }; }); };
Rename "init:settings" event to "init:__settings".
Rename "init:settings" event to "init:__settings".
JavaScript
mit
nodeca/nodeca.users
--- +++ @@ -10,7 +10,7 @@ module.exports = function (N) { - N.wire.before('init:settings', function (sandbox) { + N.wire.before('init:__settings', function (sandbox) { sandbox.selectionListFetchers['usergroups'] = function fetchUserGroups(callback) { N.models.users.UserGroup
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
--- +++ @@ -1,6 +1,10 @@ var pingPong = function(i) { - if ((i % 3 === 0) || (i % 5 === 0)) { - return true; + 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; } @@ -15,9 +19,9 @@ for (var i = 1; i <= number; i += 1) { if (i % 15 === 0) { $('#outputList').append("<li>ping pong</li>"); - } else if (i % 3 === 0) { + } else if ((winner) && (i % 5 != 0)) { $('#outputList').append("<li>ping</li>"); - } else if (i % 5 === 0) { + } else if ((winner) && (i % 3 != 0)) { $('#outputList').append("<li>pong</li>"); } else { $('#outputList').append("<li>" + i + "</li>");
7e15fe61c4300ac591adc7a153b32d060a3feff6
karma.conf.js
karma.conf.js
var webpack = require('webpack'); // TODO: use BowerWebpackPlugin // var BowerWebpackPlugin = require('bower-webpack-plugin'); var webpackCommon = require('./webpack.common.config.js'); // Put in separate file? var webpackTestConfig = { devtool: 'inline-source-map', plugins: [ new webpack.ResolverPlugin( new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main']) ), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', 'window.$': 'jquery' }), ], resolve: webpackCommon.resolve, module: { loaders: [ {test: /\.test\.js$/, loader: 'babel-loader'}, ] } }; module.exports = function (config) { config.set({ browsers: ['Chrome'], frameworks: ['mocha', 'sinon'], files: [ // Only need to target one file, which will load all files in tests/ that // match *.test.js 'website/static/js/tests/tests.webpack.js', ], reporters: ['spec'], preprocessors: { // add webpack as preprocessor 'website/static/js/tests/tests.webpack.js': ['webpack', 'sourcemap'], }, webpack: webpackTestConfig, webpackServer: { noInfo: true // don't spam the console }, plugins: [ require('karma-webpack'), require('karma-mocha'), require('karma-sourcemap-loader'), require('karma-chrome-launcher'), require('karma-spec-reporter'), require('karma-sinon') ] }); };
var webpack = require('webpack'); // TODO: use BowerWebpackPlugin // var BowerWebpackPlugin = require('bower-webpack-plugin'); var webpackCommon = require('./webpack.common.config.js'); // Put in separate file? var webpackTestConfig = { devtool: 'inline-source-map', plugins: [ new webpack.ResolverPlugin( new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main']) ), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', 'window.$': 'jquery' }), ], resolve: webpackCommon.resolve, module: { loaders: [ // Assume test files are ES6 {test: /\.test\.js$/, loader: 'babel-loader'}, ] } }; module.exports = function (config) { config.set({ browsers: ['Chrome'], frameworks: ['mocha', 'sinon'], files: [ // Only need to target one file, which will load all files in tests/ that // match *.test.js 'website/static/js/tests/tests.webpack.js', ], reporters: ['spec'], preprocessors: { // add webpack as preprocessor 'website/static/js/tests/tests.webpack.js': ['webpack', 'sourcemap'], }, webpack: webpackTestConfig, webpackServer: { noInfo: true // don't spam the console } }); };
Allow karma to load plugins automatically
Allow karma to load plugins automatically
JavaScript
apache-2.0
samchrisinger/osf.io,cosenal/osf.io,lyndsysimon/osf.io,alexschiller/osf.io,arpitar/osf.io,mluo613/osf.io,crcresearch/osf.io,felliott/osf.io,TomBaxter/osf.io,leb2dg/osf.io,monikagrabowska/osf.io,adlius/osf.io,jeffreyliu3230/osf.io,jeffreyliu3230/osf.io,ticklemepierce/osf.io,Nesiehr/osf.io,zkraime/osf.io,jeffreyliu3230/osf.io,chrisseto/osf.io,mluke93/osf.io,felliott/osf.io,GageGaskins/osf.io,chennan47/osf.io,ticklemepierce/osf.io,kushG/osf.io,caseyrygt/osf.io,aaxelb/osf.io,zachjanicki/osf.io,cwisecarver/osf.io,amyshi188/osf.io,mattclark/osf.io,petermalcolm/osf.io,SSJohns/osf.io,dplorimer/osf,HarryRybacki/osf.io,DanielSBrown/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,himanshuo/osf.io,chrisseto/osf.io,arpitar/osf.io,lamdnhan/osf.io,sbt9uc/osf.io,felliott/osf.io,HarryRybacki/osf.io,haoyuchen1992/osf.io,zkraime/osf.io,wearpants/osf.io,monikagrabowska/osf.io,lyndsysimon/osf.io,petermalcolm/osf.io,mfraezz/osf.io,caseyrollins/osf.io,barbour-em/osf.io,ZobairAlijan/osf.io,zachjanicki/osf.io,ckc6cz/osf.io,danielneis/osf.io,ticklemepierce/osf.io,pattisdr/osf.io,cldershem/osf.io,himanshuo/osf.io,caneruguz/osf.io,hmoco/osf.io,zkraime/osf.io,leb2dg/osf.io,emetsger/osf.io,GageGaskins/osf.io,reinaH/osf.io,GaryKriebel/osf.io,SSJohns/osf.io,barbour-em/osf.io,alexschiller/osf.io,chrisseto/osf.io,petermalcolm/osf.io,jmcarp/osf.io,caseyrygt/osf.io,samanehsan/osf.io,jinluyuan/osf.io,brandonPurvis/osf.io,mluke93/osf.io,adlius/osf.io,pattisdr/osf.io,brandonPurvis/osf.io,mluo613/osf.io,KAsante95/osf.io,abought/osf.io,himanshuo/osf.io,leb2dg/osf.io,danielneis/osf.io,jnayak1/osf.io,reinaH/osf.io,brandonPurvis/osf.io,binoculars/osf.io,dplorimer/osf,bdyetton/prettychart,icereval/osf.io,DanielSBrown/osf.io,lamdnhan/osf.io,HalcyonChimera/osf.io,ckc6cz/osf.io,kwierman/osf.io,njantrania/osf.io,Nesiehr/osf.io,doublebits/osf.io,SSJohns/osf.io,brianjgeiger/osf.io,petermalcolm/osf.io,acshi/osf.io,KAsante95/osf.io,brianjgeiger/osf.io,hmoco/osf.io,TomBaxter/osf.io,caneruguz/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,cosenal/osf.io,billyhunt/osf.io,baylee-d/osf.io,icereval/osf.io,barbour-em/osf.io,crcresearch/osf.io,revanthkolli/osf.io,reinaH/osf.io,himanshuo/osf.io,hmoco/osf.io,laurenrevere/osf.io,revanthkolli/osf.io,jolene-esposito/osf.io,sloria/osf.io,samchrisinger/osf.io,caseyrygt/osf.io,jinluyuan/osf.io,emetsger/osf.io,cslzchen/osf.io,fabianvf/osf.io,jnayak1/osf.io,saradbowman/osf.io,acshi/osf.io,sloria/osf.io,rdhyee/osf.io,caseyrygt/osf.io,cosenal/osf.io,mluke93/osf.io,kushG/osf.io,revanthkolli/osf.io,TomBaxter/osf.io,RomanZWang/osf.io,Ghalko/osf.io,doublebits/osf.io,RomanZWang/osf.io,laurenrevere/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,saradbowman/osf.io,kch8qx/osf.io,brandonPurvis/osf.io,monikagrabowska/osf.io,kch8qx/osf.io,emetsger/osf.io,wearpants/osf.io,kwierman/osf.io,alexschiller/osf.io,jnayak1/osf.io,felliott/osf.io,caseyrollins/osf.io,asanfilippo7/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,Ghalko/osf.io,billyhunt/osf.io,cslzchen/osf.io,arpitar/osf.io,erinspace/osf.io,acshi/osf.io,arpitar/osf.io,zamattiac/osf.io,kushG/osf.io,RomanZWang/osf.io,samanehsan/osf.io,samanehsan/osf.io,amyshi188/osf.io,mluo613/osf.io,samchrisinger/osf.io,amyshi188/osf.io,samchrisinger/osf.io,doublebits/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,mfraezz/osf.io,baylee-d/osf.io,Ghalko/osf.io,abought/osf.io,dplorimer/osf,binoculars/osf.io,alexschiller/osf.io,danielneis/osf.io,MerlinZhang/osf.io,ckc6cz/osf.io,KAsante95/osf.io,haoyuchen1992/osf.io,doublebits/osf.io,zkraime/osf.io,jeffreyliu3230/osf.io,icereval/osf.io,Johnetordoff/osf.io,erinspace/osf.io,fabianvf/osf.io,chennan47/osf.io,jinluyuan/osf.io,Nesiehr/osf.io,sbt9uc/osf.io,brianjgeiger/osf.io,ZobairAlijan/osf.io,RomanZWang/osf.io,acshi/osf.io,mattclark/osf.io,emetsger/osf.io,adlius/osf.io,mfraezz/osf.io,MerlinZhang/osf.io,pattisdr/osf.io,dplorimer/osf,cwisecarver/osf.io,aaxelb/osf.io,aaxelb/osf.io,kch8qx/osf.io,jmcarp/osf.io,mattclark/osf.io,Johnetordoff/osf.io,sbt9uc/osf.io,lamdnhan/osf.io,erinspace/osf.io,monikagrabowska/osf.io,kwierman/osf.io,cldershem/osf.io,SSJohns/osf.io,kch8qx/osf.io,TomHeatwole/osf.io,billyhunt/osf.io,danielneis/osf.io,zamattiac/osf.io,brianjgeiger/osf.io,fabianvf/osf.io,ZobairAlijan/osf.io,caneruguz/osf.io,leb2dg/osf.io,jmcarp/osf.io,amyshi188/osf.io,adlius/osf.io,GaryKriebel/osf.io,kch8qx/osf.io,GageGaskins/osf.io,rdhyee/osf.io,mluke93/osf.io,zachjanicki/osf.io,sbt9uc/osf.io,cldershem/osf.io,cosenal/osf.io,cwisecarver/osf.io,njantrania/osf.io,Ghalko/osf.io,lamdnhan/osf.io,sloria/osf.io,revanthkolli/osf.io,chrisseto/osf.io,asanfilippo7/osf.io,fabianvf/osf.io,billyhunt/osf.io,jnayak1/osf.io,mfraezz/osf.io,abought/osf.io,rdhyee/osf.io,asanfilippo7/osf.io,HarryRybacki/osf.io,TomHeatwole/osf.io,aaxelb/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,haoyuchen1992/osf.io,caseyrollins/osf.io,jinluyuan/osf.io,jmcarp/osf.io,GaryKriebel/osf.io,ckc6cz/osf.io,zamattiac/osf.io,kushG/osf.io,bdyetton/prettychart,wearpants/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,jolene-esposito/osf.io,njantrania/osf.io,haoyuchen1992/osf.io,njantrania/osf.io,Johnetordoff/osf.io,brandonPurvis/osf.io,samanehsan/osf.io,barbour-em/osf.io,ticklemepierce/osf.io,lyndsysimon/osf.io,asanfilippo7/osf.io,bdyetton/prettychart,billyhunt/osf.io,ZobairAlijan/osf.io,doublebits/osf.io,TomHeatwole/osf.io,hmoco/osf.io,zachjanicki/osf.io,alexschiller/osf.io,reinaH/osf.io,mluo613/osf.io,KAsante95/osf.io,HalcyonChimera/osf.io,abought/osf.io,TomHeatwole/osf.io,GaryKriebel/osf.io,Nesiehr/osf.io,cslzchen/osf.io,MerlinZhang/osf.io,lyndsysimon/osf.io,wearpants/osf.io,cldershem/osf.io,DanielSBrown/osf.io,MerlinZhang/osf.io,binoculars/osf.io,bdyetton/prettychart,HarryRybacki/osf.io,acshi/osf.io,jolene-esposito/osf.io,CenterForOpenScience/osf.io,RomanZWang/osf.io,GageGaskins/osf.io,CenterForOpenScience/osf.io,crcresearch/osf.io,caneruguz/osf.io,cslzchen/osf.io,GageGaskins/osf.io,jolene-esposito/osf.io,KAsante95/osf.io,kwierman/osf.io
--- +++ @@ -21,6 +21,7 @@ resolve: webpackCommon.resolve, module: { loaders: [ + // Assume test files are ES6 {test: /\.test\.js$/, loader: 'babel-loader'}, ] } @@ -45,14 +46,6 @@ webpack: webpackTestConfig, webpackServer: { noInfo: true // don't spam the console - }, - plugins: [ - require('karma-webpack'), - require('karma-mocha'), - require('karma-sourcemap-loader'), - require('karma-chrome-launcher'), - require('karma-spec-reporter'), - require('karma-sinon') - ] + } }); };
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
--- +++ @@ -30,12 +30,6 @@ 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) }) })
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
--- +++ @@ -19,7 +19,17 @@ // 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(); + 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
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
--- +++ @@ -6,48 +6,49 @@ import TaxCalculator from '../libs/TaxCalculator'; class TextFields extends Component { - state = { - income: 0, - expenses: 0 - }; + handleSubmit(event) { + event.preventDefault(); - calculate() { - const { income, expenses } = this.state; - const taxInfo = TaxCalculator.getTaxInfo(income, expenses); + const formElement = event.target; + const taxInfo = TaxCalculator.getTaxInfo( + formElement.income.value, + formElement.expenses.value + ); 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> + <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> ); }
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
--- +++ @@ -4,7 +4,7 @@ const Catalog = mongoose.model('Catalog'); function formatCatalog(catalog) { - return omit(catalog.toObject({ virtuals: true }), '_metrics'); + return omit(catalog.toObject({ virtuals: true, minimize: false }), '_metrics'); } function fetch(req, res, next, id) {
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
--- +++ @@ -2,23 +2,23 @@ * 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); - }) - }); +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; }
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
--- +++ @@ -27,16 +27,7 @@ } } }).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); + return queue.add(data); }).catch((err) => { console.log(err);
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
--- +++ @@ -64,7 +64,7 @@ config.package ).then(function (content) { - fs.writeFileSync(output, content, 'utf8'); + grunt.file.write(output, content, {encoding: 'utf8'}); done();
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
--- +++ @@ -13,8 +13,8 @@ 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>'; + + return '<iframe scrolling="no" width="' + width + '" height="' + height + '" src="http://jsfiddle.net/' + id + '/embedded/' + tabs + '/' + skin + '" frameborder="0" allowfullscreen></iframe>'; } module.exports = jsfiddleTag;
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
--- +++ @@ -4,7 +4,6 @@ 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"
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
--- +++ @@ -27,10 +27,13 @@ }, 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 [Meteor.subscribe('rides'), Meteor.subscribe('users', userIds)]; + return [subscriptions]; }, data: function () { return Rides.find({}, { sort: { departureTime: 1 } });
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
--- +++ @@ -1,6 +1,7 @@ 'use strict'; const fs = require('fs'); +const path = require('path'); const express = require('express'); const send = require('send'); @@ -8,7 +9,6 @@ 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); @@ -16,6 +16,8 @@ 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 }));
ac6ffeea337475579d93bb0608f75197e3495b7a
gulp/config.js
gulp/config.js
var dest = './public/dist'; var src = './client'; var bowerComponents = './bower_components'; module.exports = { adminAssets: { src: src + '/admin/**', dest: dest + '/admin/assets' }, bower: { dest: dest + '/', filename: 'libs.min.js', libs: [ bowerComponents + '/modernizr/modernizr.js', bowerComponents + '/threejs/build/three.js', bowerComponents + '/dat-gui/build/dat.gui.js', bowerComponents + '/nprogress/nprogress.js', bowerComponents + '/vivus/dist/vivus.js' ] }, browserSync: { server: { baseDir: 'public/dist', middleware: function(req, res, next) { require('../server')(req, res, next); } } }, fonts: { src: src + '/fonts/**', dest: dest + '/fonts' }, less: { entry: src + '/less/style.less', src: src + '/styles/*.css', dest: dest + '/' }, images: { src: src + '/img/**', dest: dest + '/img' }, browserify: { // A separate bundle will be generated for each // bundle config in the list below bundleConfigs: [{ entries: src + '/js/main.js', dest: dest, outputName: 'main.js' }] }, production: { cssSrc: dest + '/*.css', jsSrc: dest + '/*.js', dest: dest } };
var dest = './public/dist'; var src = './client'; var bowerComponents = './bower_components'; module.exports = { adminAssets: { src: src + '/admin/**', dest: dest + '/admin/assets' }, bower: { dest: dest + '/', filename: 'libs.min.js', libs: [ bowerComponents + '/modernizr/modernizr.js', bowerComponents + '/threejs/build/three.js', bowerComponents + '/dat-gui/build/dat.gui.js', bowerComponents + '/nprogress/nprogress.js', bowerComponents + '/vivus/dist/vivus.js' ] }, browserSync: { server: { baseDir: 'public/dist', middleware: function(req, res, next) { require('../server')(req, res, next); } } }, fonts: { src: src + '/fonts/**', dest: dest + '/fonts' }, less: { entry: src + '/less/style.less', src: src + '/less/**', dest: dest + '/' }, images: { src: src + '/img/**', dest: dest + '/img' }, browserify: { // A separate bundle will be generated for each // bundle config in the list below bundleConfigs: [{ entries: src + '/js/main.js', dest: dest, outputName: 'main.js' }] }, production: { cssSrc: dest + '/*.css', jsSrc: dest + '/*.js', dest: dest } };
Fix gulp live reload for less
Fix gulp live reload for less
JavaScript
mit
risq/dihh,risq/dihh
--- +++ @@ -32,7 +32,7 @@ }, less: { entry: src + '/less/style.less', - src: src + '/styles/*.css', + src: src + '/less/**', dest: dest + '/' }, images: {
cb17adbc69f22307c2d3c4e64adec64c6f200511
src/image-gallery.js
src/image-gallery.js
(function () { var addImageGallery = function(post) { if(post.length && !post.hasClass('smi-img-gallery')) { console.log('POST: ', post); post.addClass('smi-img-gallery'); post.find('img').each(function(){ var img = $(this); var link = img.attr('src'); if(!link || img.closest('a').length){ return; } var a = $('<a class="smi-post-img" data-fancybox="smi-post-images">'); a.attr('href', link); img.replaceWith(a); a.append(img); }); post.find('a.smi-post-img').fancybox({ loop: true }); } }; //TODO: TEMP setInterval(function(){ var post = $('.PostFull__body'); addImageGallery(post); },100); })();
(function () { var addImageGallery = function(post) { if(post.length && !post.hasClass('smi-img-gallery')) { console.log('POST: ', post); post.addClass('smi-img-gallery'); post.find('img').each(function(){ var img = $(this); var link = img.attr('src'); if(!link || img.closest('a').length){ return; } var a = $('<a class="smi-post-img" data-fancybox="smi-post-images">'); a.attr('href', link); img.replaceWith(a); a.append(img); }); var fb = post.find('a.smi-post-img').fancybox({ loop: true, beforeClose: function(instance, current, event){ if(event && event.stopPropagation){ event.stopPropagation(); } } }); } }; //TODO: TEMP setInterval(function(){ var post = $('.PostFull__body'); addImageGallery(post); },100); })();
Fix galley close on esc
Fix galley close on esc
JavaScript
mit
armandocat/steemit-more-info,armandocat/steemit-more-info
--- +++ @@ -20,8 +20,15 @@ a.append(img); }); - post.find('a.smi-post-img').fancybox({ - loop: true + var fb = post.find('a.smi-post-img').fancybox({ + loop: true, + + beforeClose: function(instance, current, event){ + if(event && event.stopPropagation){ + event.stopPropagation(); + } + } + }); }