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
aafe773244155b0630eed62ae72014d8a471b001
template/test/index.js
template/test/index.js
import glob from 'glob'; glob.sync('**/*-test.js', {realpath: true, cwd: __dirname}).forEach(require);
'use strict'; require('react-component-template/test');
Use test runner from react-component-template
Use test runner from react-component-template
JavaScript
mit
nkbt/cf-react-component-template
--- +++ @@ -1,4 +1,4 @@ -import glob from 'glob'; +'use strict'; -glob.sync('**/*-test.js', {realpath: true, cwd: __dirname}).forEach(require); +require('react-component-template/test');
a49043204b258ae6e04038c69c40a4bb16ca18e8
server/config/routes.js
server/config/routes.js
const userController = require('./users/userController.js'); const listingController = require('./listings/listingController.js'); module.exports = (app, db) => { // Routes for all users app.get('/api/users', userController.getAll); app.post('/api/users', userController.createOne); // Routes for specific user app.get('api/users/:id', userController.getOne); app.patch('api/users/:id', userController.patchOne); app.delete('api/users/:id', userController.deleteOne); // Routes for all listings belonging to a specific user app.get('api/users/:id/listings', listingController.getAll); app.post('api/users/:id/listings', listingController.createOne); // Routes for a specific listing app.get('api/listings/:listId', listingController.getOne); app.patch('api/listings/:listId', listingController.patchOne); app.delete('api/listings/:listId', listingController.deleteOne); // Routes for a specific listing's photos app.get('api/listings/:listId/photos', listingController.getAllPhotos); app.post('api/listings/:listId/photos', listingController.createOnePhoto); // Routes for a specific listing's specific photo app.patch('api/listings/:listId/photos/:id', listingController.patchOnePhoto); app.delete('api/listings/:listId/photos/:id', listingController.deleteOnePhoto); }
const userController = require('./users/userController.js'); const listingController = require('./listings/listingController.js'); module.exports = (app, db, path, rootPath) => { // Routes for all users app.get('/api/users', userController.getAll); app.post('/api/users', userController.createOne); // Routes for specific user app.get('/api/users/:id', userController.getOne); app.patch('/api/users/:id', userController.patchOne); app.delete('/api/users/:id', userController.deleteOne); // Routes for all listings belonging to a specific user app.get('/api/users/:id/listings', listingController.getAll); app.post('/api/users/:id/listings', listingController.createOne); // Routes for a specific listing app.get('/api/listings/:listId', listingController.getOne); app.patch('/api/listings/:listId', listingController.patchOne); app.delete('/api/listings/:listId', listingController.deleteOne); // Routes for a specific listing's photos app.get('/api/listings/:listId/photos', listingController.getAllPhotos); app.post('/api/listings/:listId/photos', listingController.createOnePhoto); // Routes for a specific listing's specific photo app.patch('/api/listings/:listId/photos/:id', listingController.patchOnePhoto); app.delete('/api/listings/:listId/photos/:id', listingController.deleteOnePhoto); // Catch-all route to allow reloading app.get('*', (req, res) => { res.sendFile(path.resolve(rootPath + '/index.html')); }); }
Add catch-all route to allow page refreshing
Add catch-all route to allow page refreshing
JavaScript
mit
bwuphan/raptor-ads,Darkrender/raptor-ads,bwuphan/raptor-ads,wolnewitz/raptor-ads,Velocies/raptor-ads,Darkrender/raptor-ads,Velocies/raptor-ads,wolnewitz/raptor-ads
--- +++ @@ -1,32 +1,36 @@ const userController = require('./users/userController.js'); const listingController = require('./listings/listingController.js'); -module.exports = (app, db) => { +module.exports = (app, db, path, rootPath) => { // Routes for all users app.get('/api/users', userController.getAll); app.post('/api/users', userController.createOne); // Routes for specific user - app.get('api/users/:id', userController.getOne); - app.patch('api/users/:id', userController.patchOne); - app.delete('api/users/:id', userController.deleteOne); + app.get('/api/users/:id', userController.getOne); + app.patch('/api/users/:id', userController.patchOne); + app.delete('/api/users/:id', userController.deleteOne); // Routes for all listings belonging to a specific user - app.get('api/users/:id/listings', listingController.getAll); - app.post('api/users/:id/listings', listingController.createOne); + app.get('/api/users/:id/listings', listingController.getAll); + app.post('/api/users/:id/listings', listingController.createOne); // Routes for a specific listing - app.get('api/listings/:listId', listingController.getOne); - app.patch('api/listings/:listId', listingController.patchOne); - app.delete('api/listings/:listId', listingController.deleteOne); + app.get('/api/listings/:listId', listingController.getOne); + app.patch('/api/listings/:listId', listingController.patchOne); + app.delete('/api/listings/:listId', listingController.deleteOne); // Routes for a specific listing's photos - app.get('api/listings/:listId/photos', listingController.getAllPhotos); - app.post('api/listings/:listId/photos', listingController.createOnePhoto); + app.get('/api/listings/:listId/photos', listingController.getAllPhotos); + app.post('/api/listings/:listId/photos', listingController.createOnePhoto); // Routes for a specific listing's specific photo - app.patch('api/listings/:listId/photos/:id', listingController.patchOnePhoto); - app.delete('api/listings/:listId/photos/:id', listingController.deleteOnePhoto); + app.patch('/api/listings/:listId/photos/:id', listingController.patchOnePhoto); + app.delete('/api/listings/:listId/photos/:id', listingController.deleteOnePhoto); + // Catch-all route to allow reloading + app.get('*', (req, res) => { + res.sendFile(path.resolve(rootPath + '/index.html')); + }); }
1eb7f32e8bb7097cfca068dda7b339aca4691938
components/message/Message.js
components/message/Message.js
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import { ButtonGroup } from '../button'; import cx from 'classnames'; import theme from './theme.css'; class Message extends PureComponent { static propTypes = { className: PropTypes.string, children: PropTypes.any.isRequired, image: PropTypes.element, imagePositioning: PropTypes.oneOf(['center', 'left', 'right']), button: PropTypes.element, link: PropTypes.element, }; static defaultProps = { imagePositioning: 'left', }; render() { const { className, children, image, imagePositioning, button, link, ...others } = this.props; const classNames = cx(theme['message'], theme[`is-image-${imagePositioning}`], className); const hasAction = Boolean(button || link); return ( <Box data-teamleader-ui="message" className={classNames} {...others}> {image && <div className={theme['image']}>{image}</div>} <div className={theme['content']}> {children} {hasAction && ( <ButtonGroup className={theme['actions']} marginTop={4}> {button && <span className={theme['button']}>{button}</span>} {link} </ButtonGroup> )} </div> </Box> ); } } export default Message;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import { ButtonGroup } from '../button'; import cx from 'classnames'; import theme from './theme.css'; class Message extends PureComponent { static propTypes = { className: PropTypes.string, children: PropTypes.any.isRequired, image: PropTypes.element, imagePositioning: PropTypes.oneOf(['center', 'left', 'right']), button: PropTypes.element, link: PropTypes.element, }; static defaultProps = { imagePositioning: 'left', }; render() { const { className, children, image, imagePositioning, button, link, ...others } = this.props; const classNames = cx(theme['message'], theme[`is-image-${imagePositioning}`], className); const hasAction = Boolean(button || link); return ( <Box data-teamleader-ui="message" className={classNames} {...others}> {image && <div className={theme['image']}>{image}</div>} <div className={theme['content']}> {children} {hasAction && ( <ButtonGroup className={theme['actions']} marginTop={4}> {button && React.cloneElement(button, { className: theme['button'] })} {link} </ButtonGroup> )} </div> </Box> ); } } export default Message;
Drop the wrapper, clone the element and apply the class instead
Drop the wrapper, clone the element and apply the class instead
JavaScript
mit
teamleadercrm/teamleader-ui
--- +++ @@ -32,7 +32,7 @@ {children} {hasAction && ( <ButtonGroup className={theme['actions']} marginTop={4}> - {button && <span className={theme['button']}>{button}</span>} + {button && React.cloneElement(button, { className: theme['button'] })} {link} </ButtonGroup> )}
de314b6ba5fcc799090d328e379002e04e8fc10f
lib/conditions/index.js
lib/conditions/index.js
const express = require('express'); const logger = require('../logger').policy; const schemas = require('../schemas'); const predefined = require('./predefined'); const conditions = {}; function register ({ name, handler, schema }) { const validate = schemas.register('condition', name, schema); conditions[name] = (req, config) => { const validationResult = validate(config); if (validationResult.isValid) { return handler(req, config); } logger.error(`Condition ${name} config validation failed`, validationResult.error); throw new Error(`Condition ${name} config validation failed`); }; } function init () { predefined.forEach(register); // extending express.request express.request.matchEGCondition = function (conditionConfig) { logger.debug('matchEGCondition for %o', conditionConfig); const func = conditions[conditionConfig.name]; if (!func) { logger.debug(`warning: condition not found for ${conditionConfig.name}`); return null; } return func(this, conditionConfig); }; return { register }; } module.exports = { init };
const express = require('express'); const logger = require('../logger').policy; const schemas = require('../schemas'); const predefined = require('./predefined'); const conditions = {}; function register ({ name, handler, schema }) { const validate = schemas.register('condition', name, schema); conditions[name] = (req, config) => { const validationResult = validate(config); if (validationResult.isValid) { return handler(req, config); } logger.error(`Condition ${name} config validation failed`, validationResult.error); throw new Error(`Condition ${name} config validation failed`); }; } function init () { predefined.forEach(register); // extending express.request express.request.matchEGCondition = function (conditionConfig) { logger.debug('matchEGCondition for %o', conditionConfig); const func = conditions[conditionConfig.name]; if (!func) { logger.warn(`Condition not found for ${conditionConfig.name}`); return null; } return func(this, conditionConfig); }; return { register }; } module.exports = { init };
Use log.warn instead of debug and claim it's a warn
Use log.warn instead of debug and claim it's a warn
JavaScript
apache-2.0
ExpressGateway/express-gateway
--- +++ @@ -26,7 +26,7 @@ logger.debug('matchEGCondition for %o', conditionConfig); const func = conditions[conditionConfig.name]; if (!func) { - logger.debug(`warning: condition not found for ${conditionConfig.name}`); + logger.warn(`Condition not found for ${conditionConfig.name}`); return null; }
6ff68041de291f09753ef50f1c6d9b2b1f40b976
lib/less/tree/extend.js
lib/less/tree/extend.js
(function (tree) { tree.Extend = function Extend(selector, option, index) { this.selector = selector; this.option = option; this.index = index; switch(option) { case "all": this.allowBefore = true; this.allowAfter = true; break; default: this.allowBefore = false; this.allowAfter = false; break; } }; tree.Extend.prototype = { type: "Extend", accept: function (visitor) { this.selector = visitor.visit(this.selector); }, eval: function (env) { return new(tree.Extend)(this.selector.eval(env), this.option, this.index); }, clone: function (env) { return new(tree.Extend)(this.selector, this.option, this.index); }, findSelfSelectors: function (selectors) { var selfElements = [], i, selectorElements; for(i = 0; i < selectors.length; i++) { selectorElements = selectors[i].elements; // duplicate the logic in genCSS function inside the selector node. // future TODO - move both logics into the selector joiner visitor if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") { selectorElements[0].combinator.value = ' '; } selfElements = selfElements.concat(selectors[i].elements); } this.selfSelectors = [{ elements: selfElements }]; } }; })(require('../tree'));
(function (tree) { tree.Extend = function Extend(selector, option, index) { this.selector = selector; this.option = option; this.index = index; this.object_id = tree.Extend.next_id++; this.parent_ids = [this.object_id]; switch(option) { case "all": this.allowBefore = true; this.allowAfter = true; break; default: this.allowBefore = false; this.allowAfter = false; break; } }; tree.Extend.next_id = 0; tree.Extend.prototype = { type: "Extend", accept: function (visitor) { this.selector = visitor.visit(this.selector); }, eval: function (env) { return new(tree.Extend)(this.selector.eval(env), this.option, this.index); }, clone: function (env) { return new(tree.Extend)(this.selector, this.option, this.index); }, findSelfSelectors: function (selectors) { var selfElements = [], i, selectorElements; for(i = 0; i < selectors.length; i++) { selectorElements = selectors[i].elements; // duplicate the logic in genCSS function inside the selector node. // future TODO - move both logics into the selector joiner visitor if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") { selectorElements[0].combinator.value = ' '; } selfElements = selfElements.concat(selectors[i].elements); } this.selfSelectors = [{ elements: selfElements }]; } }; })(require('../tree'));
Set object id and initiate parent_ids array
Set object id and initiate parent_ids array
JavaScript
apache-2.0
mcanthony/less.js,wjb12/less.js,demohi/less.js,PUSEN/less.js,nolanlawson/less.js,jjj117/less.js,wjb12/less.js,less/less.js,PUSEN/less.js,angeliaz/less.js,Nastarani1368/less.js,MrChen2015/less.js,bammoo/less.js,dyx/less.js,Nastarani1368/less.js,paladox/less.js,SomMeri/less-rhino.js,NaSymbol/less.js,seven-phases-max/less.js,deciament/less.js,xiaoyanit/less.js,mishal/less.js,royriojas/less.js,arusanov/less.js,aichangzhi123/less.js,egg-/less.js,Synchro/less.js,idreamingreen/less.js,foresthz/less.js,bammoo/less.js,seven-phases-max/less.js,ahutchings/less.js,Synchro/less.js,chenxiaoxing1992/less.js,dyx/less.js,thinkDevDM/less.js,cgvarela/less.js,sqliang/less.js,featurist/less-vars,huzion/less.js,ridixcr/less.js,SomMeri/less-rhino.js,chenxiaoxing1992/less.js,christer155/less.js,lincome/less.js,christer155/less.js,less/less.js,SkReD/less.js,cgvarela/less.js,nolanlawson/less.js,bendroid/less.js,angeliaz/less.js,huzion/less.js,telerik/less.js,ahstro/less.js,pkdevbox/less.js,sqliang/less.js,NaSymbol/less.js,less/less.js,featurist/less-vars,gencer/less.js,lvpeng/less.js,HossainKhademian/LessJs,egg-/less.js,lvpeng/less.js,telerik/less.js,mishal/less.js,cypher0x9/less.js,jdan/less.js,demohi/less.js,evocateur/less.js,pkdevbox/less.js,AlexMeliq/less.js,ahstro/less.js,SkReD/less.js,NirViaje/less.js,wyfyyy818818/less.js,MrChen2015/less.js,cypher0x9/less.js,waiter/less.js,aichangzhi123/less.js,royriojas/less.js,lincome/less.js,NirViaje/less.js,mcanthony/less.js,deciament/less.js,mtscout6/less.js,idreamingreen/less.js,arusanov/less.js,xiaoyanit/less.js,miguel-serrano/less.js,thinkDevDM/less.js,yuhualingfeng/less.js,yuhualingfeng/less.js,gencer/less.js,bhavyaNaveen/project1,jdan/less.js,AlexMeliq/less.js,wyfyyy818818/less.js,ahutchings/less.js,bendroid/less.js,miguel-serrano/less.js,waiter/less.js,jjj117/less.js,paladox/less.js,foresthz/less.js,ridixcr/less.js,bhavyaNaveen/project1,evocateur/less.js
--- +++ @@ -4,6 +4,8 @@ this.selector = selector; this.option = option; this.index = index; + this.object_id = tree.Extend.next_id++; + this.parent_ids = [this.object_id]; switch(option) { case "all": @@ -16,6 +18,7 @@ break; } }; +tree.Extend.next_id = 0; tree.Extend.prototype = { type: "Extend",
eaa3fa7e5224932ccbcefdd26db81b384b3155fc
n3-composer/server/api/decisions.js
n3-composer/server/api/decisions.js
import { Router } from 'express' import bodyParser from 'body-parser' import Decision from './classes/Decision.js' var router = Router() router.use(bodyParser.urlencoded({ extended: true })) router.post('/createDecision', function(req, res) { // TODO These 4 fields (IUN, Version, unitIds, organizationId) should be set // by the current implementation of Diavgeia new Decision(req.body,'60Β3ΩΡΙ-ΒΝ3','b4ae1411-f81d-437b-9c63-a8b7d4ed866b',['6105'],'93302').generateN3() }) export default router
import { Router } from 'express' import bodyParser from 'body-parser' import Decision from './classes/Decision.js' var router = Router() router.use(bodyParser.urlencoded({ extended: true })) router.post('/createDecision', function(req, res) { // TODO These 4 fields (IUN, Version, unitIds, organizationId) should be set // by the current implementation of Diavgeia new Decision(req.body,'60Β3ΩΡΙ-ΒΝ3','b4ae1411-f81d-437b-9c63-a8b7d4ed866b',['6105'],'93302').generateN3() res.redirect('/?success'); }) export default router
Return success param on successful decision upload
Return success param on successful decision upload
JavaScript
mit
eellak/gsoc17-diavgeia,eellak/gsoc17-diavgeia,eellak/gsoc17-diavgeia,eellak/gsoc17-diavgeia
--- +++ @@ -9,6 +9,7 @@ // TODO These 4 fields (IUN, Version, unitIds, organizationId) should be set // by the current implementation of Diavgeia new Decision(req.body,'60Β3ΩΡΙ-ΒΝ3','b4ae1411-f81d-437b-9c63-a8b7d4ed866b',['6105'],'93302').generateN3() + res.redirect('/?success'); }) export default router
caedc16fc57aec421d711dbdac3ebc37ebfb3283
src/index.js
src/index.js
import React, { PropTypes } from 'react'; import markdownIt from 'markdown-it'; import ast from './util/ast'; import renderTokens from './util/renderTokens'; import components from './components'; const md = new markdownIt(); /** * Renders React components from a Markdown string. * @todo Allow for custom markdown-it instance. * @todo Allow for custom components. */ export default function Markdown({ input }) { const { nodes } = ast(md.parse(input)); return ( <div> {renderTokens(nodes, components)} </div> ); } /** * Props that can be passed to `<Markdown />`. * @type Object * @prop {String} input - Markdown string. */ Markdown.propTypes = { input: PropTypes.string.isRequired, }
import React, { PropTypes } from 'react'; import markdownIt from 'markdown-it'; import ast from './util/ast'; import renderTokens from './util/renderTokens'; import components from './components'; /** * Renders React components from a Markdown string. * @todo Allow for custom components. */ export default function Markdown({ input, renderer }) { const { nodes } = ast(renderer.parse(input)); return ( <div> {renderTokens(nodes, components)} </div> ); } /** * Props that can be passed to `<Markdown />`. * @type Object * @prop {String} input - Markdown string. * @prop {Object} [renderer] - markdown-it instance. */ Markdown.propTypes = { input: PropTypes.string.isRequired, renderer: PropTypes.object, } /** * Default props for `<Markdown />`. * @type Object */ Markdown.defaultProps = { renderer: markdownIt(), }
Allow custom markdown-it instance to be passed to the <Markdown /> component
Allow custom markdown-it instance to be passed to the <Markdown /> component
JavaScript
mit
gakimball/meact,gakimball/meact
--- +++ @@ -4,15 +4,12 @@ import renderTokens from './util/renderTokens'; import components from './components'; -const md = new markdownIt(); - /** * Renders React components from a Markdown string. - * @todo Allow for custom markdown-it instance. * @todo Allow for custom components. */ -export default function Markdown({ input }) { - const { nodes } = ast(md.parse(input)); +export default function Markdown({ input, renderer }) { + const { nodes } = ast(renderer.parse(input)); return ( <div> @@ -25,7 +22,17 @@ * Props that can be passed to `<Markdown />`. * @type Object * @prop {String} input - Markdown string. + * @prop {Object} [renderer] - markdown-it instance. */ Markdown.propTypes = { input: PropTypes.string.isRequired, + renderer: PropTypes.object, } + +/** + * Default props for `<Markdown />`. + * @type Object + */ +Markdown.defaultProps = { + renderer: markdownIt(), +}
190e5fb8e549493841b9bb9ffd7820ddb00e6d85
src/index.js
src/index.js
function FakeStorage() { this.clear(); } FakeStorage.prototype = { key(index) { // sanitise index as int index = parseInt(index); // return early if index isn't a positive number or larger than length if (isNaN(index) || index < 0 || index >= this.length) { return null; } // loop through data object until at nth key let i = 0; for (const key in this._data) { if (this._data.hasOwnProperty(key)) { if (i === index) { return key; } i++; } } // otherwise return null return null; }, getItem(key) { // only get if there's something to get return this._data.hasOwnProperty(key) ? this._data[key] : null; }, setItem(key, value) { // if we're adding a new item, increment the length if (!this._data.hasOwnProperty(key)) { this.length++; } // always store the value as a string this._data[key] = value.toString(); }, removeItem(key) { // only remove if there's something to remove if (this._data.hasOwnProperty(key)) { delete this._data[key]; this.length--; } }, clear() { this._data = {}; this.length = 0; }, }; export default FakeStorage;
class FakeStorage { #data = {}; get length() { return Object.keys(this.#data).length; } key(n) { return Object.keys(this.#data)[Number.parseInt(n, 10)] ?? null; } getItem(key) { const _data = this.#data; const _key = `${key}`; return Object.prototype.hasOwnProperty.call(_data, _key) ? _data[_key] : null; } setItem(key, value) { return (this.#data[`${key}`] = `${value}`); } removeItem(key, value) { const _data = this.#data; const _key = `${key}`; if (Object.prototype.hasOwnProperty.call(_data, _key)) { delete _data[_key]; } } clear(key, value) { this.#data = {}; } } export default FakeStorage;
Rewrite using modern JavaScript features
Rewrite using modern JavaScript features
JavaScript
mit
jacobbuck/fake-storage
--- +++ @@ -1,55 +1,37 @@ -function FakeStorage() { - this.clear(); +class FakeStorage { + #data = {}; + + get length() { + return Object.keys(this.#data).length; + } + + key(n) { + return Object.keys(this.#data)[Number.parseInt(n, 10)] ?? null; + } + + getItem(key) { + const _data = this.#data; + const _key = `${key}`; + return Object.prototype.hasOwnProperty.call(_data, _key) + ? _data[_key] + : null; + } + + setItem(key, value) { + return (this.#data[`${key}`] = `${value}`); + } + + removeItem(key, value) { + const _data = this.#data; + const _key = `${key}`; + if (Object.prototype.hasOwnProperty.call(_data, _key)) { + delete _data[_key]; + } + } + + clear(key, value) { + this.#data = {}; + } } -FakeStorage.prototype = { - key(index) { - // sanitise index as int - index = parseInt(index); - // return early if index isn't a positive number or larger than length - if (isNaN(index) || index < 0 || index >= this.length) { - return null; - } - // loop through data object until at nth key - let i = 0; - for (const key in this._data) { - if (this._data.hasOwnProperty(key)) { - if (i === index) { - return key; - } - i++; - } - } - // otherwise return null - return null; - }, - - getItem(key) { - // only get if there's something to get - return this._data.hasOwnProperty(key) ? this._data[key] : null; - }, - - setItem(key, value) { - // if we're adding a new item, increment the length - if (!this._data.hasOwnProperty(key)) { - this.length++; - } - // always store the value as a string - this._data[key] = value.toString(); - }, - - removeItem(key) { - // only remove if there's something to remove - if (this._data.hasOwnProperty(key)) { - delete this._data[key]; - this.length--; - } - }, - - clear() { - this._data = {}; - this.length = 0; - }, -}; - export default FakeStorage;
3ca2c46fef9c7b2339ca8df5e64044736f166ed0
src/index.js
src/index.js
/** * __ _ __ ____ * / / | |/ // __ \ * / / | // / / / * / /___/ |/ /_/ / * /_____/_/|_/_____/ * * @author Alan Doherty (BattleCrate Ltd.) * @license MIT */ // requires var Client = require('./classes/Client'); /** * Creates a new client at the specified host, if none * is provided the client will use the local domain socket. * @param {string?} host * @param {object?} authentication * @param {string?} authentication.pem * @param {string?} authentication.password * @returns Client */ function lxd(host, authentication) { return new Client(host, authentication); } // exports module.exports = lxd;
/** * __ _ __ ____ * / / | |/ // __ \ * / / | // / / / * / /___/ |/ /_/ / * /_____/_/|_/_____/ * * @author Alan Doherty (BattleCrate Ltd.) * @license MIT */ // requires var Client = require('./classes/Client'); /** * Creates a new client at the specified host, if none * is provided the client will use the local domain socket. * @param {string?} host * @param {object?} authentication * @param {string?} authentication.cert * @param {string?} authentication.key * @param {string?} authentication.password * @returns Client */ function lxd(host, authentication) { return new Client(host, authentication); } // exports module.exports = lxd;
Change js2doc fields in lxd init function
Change js2doc fields in lxd init function
JavaScript
mit
alandoherty/node-lxd
--- +++ @@ -17,7 +17,8 @@ * is provided the client will use the local domain socket. * @param {string?} host * @param {object?} authentication - * @param {string?} authentication.pem + * @param {string?} authentication.cert + * @param {string?} authentication.key * @param {string?} authentication.password * @returns Client */
0c9d564d3733fa5807c36cb992e13026c0ec21c7
src/loading_bar_middleware.js
src/loading_bar_middleware.js
import { showLoading, hideLoading } from './loading_bar_ducks' const defaultTypeSuffixes = ['PENDING', 'FULFILLED', 'REJECTED'] export default function loadingBarMiddleware(config = {}) { const promiseTypeSuffixes = config.promiseTypeSuffixes || defaultTypeSuffixes return ({ dispatch }) => next => action => { next(action) if (action.type === undefined) { return } const [PENDING, FULFILLED, REJECTED] = promiseTypeSuffixes const isPending = `_${PENDING}` const isFulfilled = `_${FULFILLED}` const isRejected = `_${REJECTED}` if (action.type.indexOf(isPending) !== -1) { dispatch(showLoading()) } else if (action.type.indexOf(isFulfilled) !== -1 || action.type.indexOf(isRejected) !== -1) { dispatch(hideLoading()) } } }
import { showLoading, hideLoading } from './loading_bar_ducks' const defaultTypeSuffixes = ['PENDING', 'FULFILLED', 'REJECTED'] export default function loadingBarMiddleware(config = {}) { const promiseTypeSuffixes = config.promiseTypeSuffixes || defaultTypeSuffixes return ({ dispatch }) => next => action => { next(action) if (action.type === undefined) { return } const [PENDING, FULFILLED, REJECTED] = promiseTypeSuffixes const isPending = new RegExp(`${PENDING}$`, 'g') const isFulfilled = new RegExp(`${FULFILLED}$`, 'g') const isRejected = new RegExp(`${REJECTED}$`, 'g') if (!!action.type.match(isPending)) { dispatch(showLoading()) } else if (!!action.type.match(isFulfilled) || !!action.type.match(isRejected)) { dispatch(hideLoading()) } } }
Update the way we identify suffixes to be more precise
Update the way we identify suffixes to be more precise
JavaScript
mit
mironov/react-redux-loading-bar
--- +++ @@ -14,14 +14,14 @@ const [PENDING, FULFILLED, REJECTED] = promiseTypeSuffixes - const isPending = `_${PENDING}` - const isFulfilled = `_${FULFILLED}` - const isRejected = `_${REJECTED}` + const isPending = new RegExp(`${PENDING}$`, 'g') + const isFulfilled = new RegExp(`${FULFILLED}$`, 'g') + const isRejected = new RegExp(`${REJECTED}$`, 'g') - if (action.type.indexOf(isPending) !== -1) { + if (!!action.type.match(isPending)) { dispatch(showLoading()) - } else if (action.type.indexOf(isFulfilled) !== -1 || - action.type.indexOf(isRejected) !== -1) { + } else if (!!action.type.match(isFulfilled) || + !!action.type.match(isRejected)) { dispatch(hideLoading()) } }
a2d2e80470b4d054424c00060c9ad4fe8c312fb8
src/model.js
src/model.js
/* Where is defined the DB connection. * * We got the following collections (cf. schema.js): * - User * - Client * - Grant * */ require.paths.unshift(__dirname + "/../vendors/rest-mongo/src") var events = require('events') , rest_mongo = require("rest-mongo/core") , mongo_backend = require("rest-mongo/mongo_backend") , config = require('./lib/config_loader').get_config() , schema = require('./schema').schema , server_schema = require('./server_schema').schema ; var backend = mongo_backend.get_backend(config.db); exports.RFactory = rest_mongo.getRFactory(schema, backend, { additional_schema: server_schema }); // The RFactory to serve public data: exports.RFactoryPublic = rest_mongo.getRFactory(schema, backend); // Ensure indexes are created: backend.db.createIndex('User', 'email', true, function(){}); // email is unique // To ensure DB concistency: var emitter = exports.emitter = new events.EventEmitter(); // When removing a client, remove its authorizations emitter.on('DELETE:Client', function(ids) { var R = RFactory(); R.Authorization.remove({query: { client: {'$in': ids.map(function(id){return {id: id}})} }}); });
/* Where is defined the DB connection. * * We got the following collections (cf. schema.js): * - User * - Client * - Grant * */ require.paths.unshift(__dirname + "/../vendors/rest-mongo/src") var events = require('events') , rest_mongo = require("rest-mongo/core") , mongo_backend = require("rest-mongo/mongo_backend") , config = require('./lib/config_loader').get_config() , schema = require('./schema').schema , server_schema = require('./server_schema').schema ; var backend = mongo_backend.get_backend(config.db); exports.RFactory = rest_mongo.getRFactory(schema, backend, { additional_schema: server_schema }); // The RFactory to serve public data: exports.RFactoryPublic = rest_mongo.getRFactory(schema, backend); // Ensure indexes are created: backend.db.createIndex('User', 'email', true, function(){}); // email is unique // To ensure DB concistency: var emitter = exports.emitter = new events.EventEmitter(); // When removing a client, remove its authorizations emitter.on('DELETE:Client', function(ids) { var R = exports.RFactory(); R.Authorization.remove({query: { client: {'$in': ids.map(function(id){return {id: id}})} }}); });
Fix delete client: authorizations should be removed.
Fix delete client: authorizations should be removed. Signed-off-by: François de Metz <4073ce8ed0c8af431a3bf625d935cc2c9542ae9c@af83.com> Signed-off-by: Virtuo <ff019a5748a52b5641624af88a54a2f0e46a9fb5@ruyssen.fr>
JavaScript
agpl-3.0
AF83/auth_server
--- +++ @@ -36,7 +36,7 @@ // When removing a client, remove its authorizations emitter.on('DELETE:Client', function(ids) { - var R = RFactory(); + var R = exports.RFactory(); R.Authorization.remove({query: { client: {'$in': ids.map(function(id){return {id: id}})} }});
977b87be2bd6d05ee626e09b5ec7faff0edf888b
src/proxy.js
src/proxy.js
var http = require('http'); exports.proxy = function(proxy_port, proxy_host, client_req, client_resp) { var proxy_req = http.createClient(proxy_port, proxy_host).request( client_req.method, client_req.url, client_req.headers); client_req.setEncoding('binary'); proxy_req.setEncoding('binary'); proxy_req.addListener('response', function (proxy_resp) { client_resp.writeHeader(proxy_resp.statusCode, proxy_resp.headers); proxy_resp.addListener('data', function (chunk) { client_resp.write(chunk, 'binary'); }); proxy_resp.addListener('end', function () { client_resp.end(); }); }); client_req.addListener('data', function (chunk) { proxy_req.write(chunk, 'binary'); }); client_req.addListener('end', function() { proxy_req.end(); }); };
var http = require('http'); exports.proxy = function(proxy_port, proxy_host, client_req, client_resp) { var proxy_req = http.createClient(proxy_port, proxy_host).request( client_req.method, client_req.url, client_req.headers); client_req.setEncoding('binary'); proxy_req.addListener('response', function (proxy_resp) { client_resp.writeHeader(proxy_resp.statusCode, proxy_resp.headers); proxy_resp.addListener('data', function (chunk) { client_resp.write(chunk, 'binary'); }); proxy_resp.addListener('end', function () { client_resp.end(); }); }); client_req.addListener('data', function (chunk) { proxy_req.write(chunk, 'binary'); }); client_req.addListener('end', function() { proxy_req.end(); }); };
Revert "more encoding settings." because it's stupid.
Revert "more encoding settings." because it's stupid. This reverts commit ccb99882a11a9edd301de8c6e42bf9700e6f8bf5.
JavaScript
apache-2.0
tilgovi/lode,tilgovi/lode
--- +++ @@ -4,7 +4,6 @@ var proxy_req = http.createClient(proxy_port, proxy_host).request( client_req.method, client_req.url, client_req.headers); client_req.setEncoding('binary'); - proxy_req.setEncoding('binary'); proxy_req.addListener('response', function (proxy_resp) { client_resp.writeHeader(proxy_resp.statusCode, proxy_resp.headers); proxy_resp.addListener('data', function (chunk) {
8de119d3bf8d14d30b71efe3af5a1bf41eaca220
src/responseBuilderHandler.js
src/responseBuilderHandler.js
'use strict'; var ResponseBuilder = require('./ResponseBuilder'); module.exports = function(promiseReturningHandlerFn, request, cb, CustomRespBuilderClass) { promiseReturningHandlerFn() .then(function(respBuilder) { // eslint-disable-next-line no-console console.log('completed with %s millis left', request.getContext().getRemainingTimeInMillis()); cb(undefined, respBuilder.toResponse(request)); }) .catch(function(err) { var RB = CustomRespBuilderClass || ResponseBuilder, respBuilder = new RB().serverError().rb(); // eslint-disable-next-line no-console console.log('ERROR:', err, err.stack); cb(undefined, respBuilder.toResponse(request)); }) .done(); };
'use strict'; var ResponseBuilder = require('./ResponseBuilder'); /** * In our APIs, we often have errors that are several promises deep, and without this, * it's hard to tell where the error actually originated (especially with AWS calls, etc). * This will generally make error stack traces much more helpful to us, so we are making * it a default. */ require('q').longStackSupport = true; module.exports = function(promiseReturningHandlerFn, request, cb, CustomRespBuilderClass) { promiseReturningHandlerFn() .then(function(respBuilder) { // eslint-disable-next-line no-console console.log('completed with %s millis left', request.getContext().getRemainingTimeInMillis()); cb(undefined, respBuilder.toResponse(request)); }) .catch(function(err) { var RB = CustomRespBuilderClass || ResponseBuilder, respBuilder = new RB().serverError().rb(); // eslint-disable-next-line no-console console.log('ERROR:', err, err.stack); cb(undefined, respBuilder.toResponse(request)); }) .done(); };
Enable Q's long stack support by default
Enable Q's long stack support by default Since the response builder handler is often one of the first things created in our APIs, it provides a convenient place to enable the long stack support in Q.
JavaScript
mit
silvermine/apigateway-utils
--- +++ @@ -1,6 +1,14 @@ 'use strict'; var ResponseBuilder = require('./ResponseBuilder'); + +/** + * In our APIs, we often have errors that are several promises deep, and without this, + * it's hard to tell where the error actually originated (especially with AWS calls, etc). + * This will generally make error stack traces much more helpful to us, so we are making + * it a default. + */ +require('q').longStackSupport = true; module.exports = function(promiseReturningHandlerFn, request, cb, CustomRespBuilderClass) { promiseReturningHandlerFn()
2c3f63b6cc372fac32cc0a917100d381f82743be
ui/js/dashboard/nco.js
ui/js/dashboard/nco.js
'use strict'; module.exports = { template: require('./nco.html'), data: function () { return { region : 12907, campaign: true, // Trick with-indicator into loading without a campaign overview: [{ title : 'Influencer', indicators: [164,165,166,167], chart : 'chart-bar' }, { title : 'Information Source', indicators: [164,165,166,167], chart : 'chart-bar' }, { title : 'Reasons for Missed', indicators: [164,165,166,167], chart : 'chart-bar' }, { title : 'Reasons for Absence', indicators: [164,165,166,167], chart : 'chart-bar' }, { title : 'Reasons for NC', indicators: [164,165,166,167], chart : 'chart-bar' }, { title : 'NC Resolved by', indicators: [164,165,166,167], chart : 'chart-bar' }] }; }, components: { } };
'use strict'; module.exports = { template: require('./nco.html'), data: function () { return { region : null, campaign: null, overview: [{ title : 'Influencer', indicators: [164,165,166,167], chart : 'chart-bar' }, { title : 'Information Source', indicators: [164,165,166,167], chart : 'chart-bar' }, { title : 'Reasons for Missed', indicators: [164,165,166,167], chart : 'chart-bar' }, { title : 'Reasons for Absence', indicators: [164,165,166,167], chart : 'chart-bar' }, { title : 'Reasons for NC', indicators: [164,165,166,167], chart : 'chart-bar' }, { title : 'NC Resolved by', indicators: [164,165,166,167], chart : 'chart-bar' }] }; }, components: { } };
Set campaign and region to null by default
Set campaign and region to null by default Campaign and region are getting passed down by the dashboard view from the dropdowns, so there is no need to provide defaults in the NCO dashboard component.
JavaScript
agpl-3.0
unicef/polio,unicef/polio,unicef/polio,unicef/polio,unicef/rhizome,SeedScientific/polio,unicef/rhizome,unicef/rhizome,SeedScientific/polio,SeedScientific/polio,SeedScientific/polio,SeedScientific/polio,unicef/rhizome
--- +++ @@ -5,8 +5,8 @@ data: function () { return { - region : 12907, - campaign: true, // Trick with-indicator into loading without a campaign + region : null, + campaign: null, overview: [{ title : 'Influencer',
6972b64ab05f7b66af8e512067a83cba0e0be917
jakefile.js
jakefile.js
/*global desc, task, jake, fail, complete */ (function() { "use strict"; task("default", ["lint"]); desc("Lint everything"); task("lint", [], function() { var lint = require("./build/lint/lint_runner.js"); var files = new jake.FileList(); files.include("**/*.js"); files.exclude("node_modules"); var options = nodeLintOptions(); lint.validateFileList(files.toArray(), options, {}); }); function nodeLintOptions() { return { bitwise:true, curly:false, eqeqeq:true, forin:true, immed:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, regexp:true, undef:true, strict:true, trailing:true, node:true }; } }());
/*global desc, task, jake, fail, complete */ (function() { "use strict"; desc("Build and test"); task("default", ["lint"]); desc("Lint everything"); task("lint", [], function() { var lint = require("./build/lint/lint_runner.js"); var files = new jake.FileList(); files.include("**/*.js"); files.exclude("node_modules"); var options = nodeLintOptions(); lint.validateFileList(files.toArray(), options, {}); }); desc("Integrate"); task("integrate", ["default"], function() { console.log("1. Make sure 'git status' is clean."); console.log("2. Build on the integration box."); console.log(" a. Walk over to integration box."); console.log(" b. 'git pull'"); console.log(" c. 'jake'"); console.log("3. 'git checkout integration'"); console.log("4. 'git merge master --no-ff --log'"); console.log("5. 'git checkout master'"); }); function nodeLintOptions() { return { bitwise:true, curly:false, eqeqeq:true, forin:true, immed:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, regexp:true, undef:true, strict:true, trailing:true, node:true }; } }());
Set up continuous integration script
Set up continuous integration script
JavaScript
mit
kyroskoh/lets_code_javascript,kyroskoh/lets_code_javascript,halcwb/lets_code_javascript,halcwb/lets_code_javascript,halcwb/lets_code_javascript,kyroskoh/lets_code_javascript
--- +++ @@ -2,6 +2,7 @@ (function() { "use strict"; + desc("Build and test"); task("default", ["lint"]); desc("Lint everything"); @@ -13,6 +14,18 @@ files.exclude("node_modules"); var options = nodeLintOptions(); lint.validateFileList(files.toArray(), options, {}); + }); + + desc("Integrate"); + task("integrate", ["default"], function() { + console.log("1. Make sure 'git status' is clean."); + console.log("2. Build on the integration box."); + console.log(" a. Walk over to integration box."); + console.log(" b. 'git pull'"); + console.log(" c. 'jake'"); + console.log("3. 'git checkout integration'"); + console.log("4. 'git merge master --no-ff --log'"); + console.log("5. 'git checkout master'"); }); function nodeLintOptions() {
d5c4e9fe858c226b163114f6d9f5e2636c8a5589
spec/strong-api-spec.js
spec/strong-api-spec.js
describe('strong-api', function(){ var StrongAPI = require('../lib/strong-api'); var api; beforeEach(function () { api = new StrongAPI(); }); it('should translate in the default default locale', function() { expect(api.translate('everything')).toEqual('I am a translated string for locale: en'); }); it('should translate in the recently set default locale', function() { api.default_locale = 'de'; expect(api.translate('everything')).toEqual('I am a translated string for locale: de'); }); it('should translate in the current locale', function() { api.default_locale = 'de'; api.locale = 'en'; expect(api.translate('everything')).toEqual('I am a translated string for locale: en'); }); it('should translate in the option-specified locale', function() { api.default_locale = 'de'; api.locale = 'en'; expect(api.translate('everything', { locale: 'es' })).toEqual('I am a translated string for locale: es'); }); });
describe('strong-api', function(){ var StrongAPI = require('../lib/strong-api'); var api; beforeEach(function () { api = new StrongAPI(); }); it('should translate in the default default locale', function() { expect(api.translate('everything')).toEqual('I am a translated string for locale: en'); }); it('should translate in the recently set default locale', function() { api.default_locale = 'de'; expect(api.translate('everything')).toEqual('I am a translated string for locale: de'); }); it('should translate in the current locale', function() { api.default_locale = 'de'; api.locale = 'en'; expect(api.translate('everything')).toEqual('I am a translated string for locale: en'); }); it('should translate in the option-specified locale', function() { api.default_locale = 'de'; api.locale = 'en'; expect(api.translate('everything', { locale: 'es' })).toEqual('I am a translated string for locale: es'); }); // Interpolation it('should use named arguments as substitutions', function() { // Setup the test case, assuming you have this string var fake_back = { 'en': { '.hello': 'Hello, %(name)' } }; // Make sure you can toss variables at it var user = {'name': 'Johnny'}; var result = api.translate( '.hello', user ); expect(result).toEqual( 'Hello, Johnny' ); }); });
Write a failing test to show variable substitution
Write a failing test to show variable substitution I plan to just use sprintf's support for this. http://www.diveintojavascript.com/projects/javascript-sprintf
JavaScript
mit
fs-webdev/strong,timshadel/strong
--- +++ @@ -27,4 +27,15 @@ expect(api.translate('everything', { locale: 'es' })).toEqual('I am a translated string for locale: es'); }); + // Interpolation + it('should use named arguments as substitutions', function() { + // Setup the test case, assuming you have this string + var fake_back = { 'en': { '.hello': 'Hello, %(name)' } }; + + // Make sure you can toss variables at it + var user = {'name': 'Johnny'}; + var result = api.translate( '.hello', user ); + expect(result).toEqual( 'Hello, Johnny' ); + }); + });
65942a18a3050a4572a1200bbe69a0d146251c15
test/components/MenuScreen/MenuScreen.spec.js
test/components/MenuScreen/MenuScreen.spec.js
import React from "react"; import ReactTestUtils from "react-addons-test-utils"; import MenuScreen from "src/components/MenuScreen/MenuScreen.js"; describe("MenuScreen", () => { it("should exist", () => { MenuScreen.should.exist; }); it("should be react element", () => { ReactTestUtils.isElement(<MenuScreen />).should.be.ok; }); });
import React from "react"; import ReactTestUtils from "react-addons-test-utils"; import jsdom from "mocha-jsdom"; import MenuScreen from "src/components/MenuScreen/MenuScreen.js"; import Button from "src/components/Shared/Button.js"; import setCurrentScreenAction from "src/actions/ScreenActions.js"; import { GAME_SCREEN } from "src/actions/ScreenActions.js"; import {setGameModeAction} from "src/actions/GameActions.js"; import {VS_HUMAN, EASY, MEDIUM, HARD} from "src/reducers/Game.js"; describe("MenuScreen", () => { jsdom(); it("should exist", () => { MenuScreen.should.exist; }); it("should be react element", () => { ReactTestUtils.isElement(<MenuScreen />).should.be.ok; }); describe("Buttons", () => { let actions = [], dispatch = (action) => actions.push(action), gameModes = [VS_HUMAN, EASY, MEDIUM, HARD]; function testButtonNumber(i) { it("Button should dispatch proper actions on click", () => { const menuScreen = ReactTestUtils.renderIntoDocument( <MenuScreen dispatch={dispatch} /> ); var buttons = ReactTestUtils.scryRenderedComponentsWithType( menuScreen, Button ); var node = ReactTestUtils .findRenderedDOMComponentWithTag(buttons[i], "button"); ReactTestUtils.Simulate.click(node); actions[0].should.be.eql(setCurrentScreenAction(GAME_SCREEN)); actions[1].should.be.eql(setGameModeAction(gameModes[i])); actions = []; }); } for (let i = 0; i < 4; i++) { testButtonNumber(i); } }); });
Add tests for menu buttons
Add tests for menu buttons
JavaScript
mit
Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React
--- +++ @@ -1,9 +1,19 @@ import React from "react"; import ReactTestUtils from "react-addons-test-utils"; +import jsdom from "mocha-jsdom"; import MenuScreen from "src/components/MenuScreen/MenuScreen.js"; +import Button from "src/components/Shared/Button.js"; + +import setCurrentScreenAction from "src/actions/ScreenActions.js"; +import { GAME_SCREEN } from "src/actions/ScreenActions.js"; + +import {setGameModeAction} from "src/actions/GameActions.js"; +import {VS_HUMAN, EASY, MEDIUM, HARD} from "src/reducers/Game.js"; describe("MenuScreen", () => { + + jsdom(); it("should exist", () => { MenuScreen.should.exist; @@ -13,4 +23,36 @@ ReactTestUtils.isElement(<MenuScreen />).should.be.ok; }); + describe("Buttons", () => { + + let actions = [], + dispatch = (action) => actions.push(action), + gameModes = [VS_HUMAN, EASY, MEDIUM, HARD]; + + function testButtonNumber(i) { + it("Button should dispatch proper actions on click", () => { + const menuScreen = ReactTestUtils.renderIntoDocument( + <MenuScreen dispatch={dispatch} /> + ); + var buttons = ReactTestUtils.scryRenderedComponentsWithType( + menuScreen, + Button + ); + var node = ReactTestUtils + .findRenderedDOMComponentWithTag(buttons[i], "button"); + + ReactTestUtils.Simulate.click(node); + + actions[0].should.be.eql(setCurrentScreenAction(GAME_SCREEN)); + actions[1].should.be.eql(setGameModeAction(gameModes[i])); + actions = []; + }); + } + + for (let i = 0; i < 4; i++) { + testButtonNumber(i); + } + + }); + });
fa1180e20689c88f6e5db4023770cb51ba9d3e9a
utils/elementToText.js
utils/elementToText.js
import { isValidElement } from 'react' const whitespacesRe = /\s+/g const _format = (str = '') => str.replace(whitespacesRe, ' ') const elementToTextRec = x => { if (Array.isArray(x)) { return x.map(elementToTextRec).join('') } else if (isValidElement(x)) { return elementToTextRec(x.props.children) } else if (typeof x === 'string') { return x || '' } return '' } const elementToText = node => _format(elementToTextRec(node)).trim() export default elementToText
import { isValidElement } from 'react' const whitespacesRe = /\s+/g const _format = (str = '') => str.trim().replace(whitespacesRe, ' ') const elementToTextRec = x => { if (Array.isArray(x)) { return x.map(elementToTextRec).join('') } else if (isValidElement(x)) { return elementToTextRec(x.props.children) } else if (typeof x === 'string') { return x || '' } return '' } const elementToText = node => _format(elementToTextRec(node)) export default elementToText
Move trim into more sensible place
Move trim into more sensible place
JavaScript
mit
styled-components/styled-components-website,styled-components/styled-components-website
--- +++ @@ -1,7 +1,7 @@ import { isValidElement } from 'react' const whitespacesRe = /\s+/g -const _format = (str = '') => str.replace(whitespacesRe, ' ') +const _format = (str = '') => str.trim().replace(whitespacesRe, ' ') const elementToTextRec = x => { if (Array.isArray(x)) { @@ -15,6 +15,6 @@ return '' } -const elementToText = node => _format(elementToTextRec(node)).trim() +const elementToText = node => _format(elementToTextRec(node)) export default elementToText
a5fd7493788a20e1175d66f23dde1fdde6ff7fd2
src/article/shared/BlockQuoteComponent.js
src/article/shared/BlockQuoteComponent.js
import { NodeComponent } from '../../kit' export default class BlockQuoteComponent extends NodeComponent { render ($$) { let node = this.props.node let el = $$('div') .addClass('sc-block-quote') .attr('data-id', node.id) el.append( this._renderValue($$, 'content').ref('content'), this._renderValue($$, 'attrib').ref('attrib') ) return el } }
import { NodeComponent } from '../../kit' export default class BlockQuoteComponent extends NodeComponent { render ($$) { let node = this.props.node let el = $$('div') .addClass('sc-block-quote') .attr('data-id', node.id) el.append( this._renderValue($$, 'content', { container: true }).ref('content'), this._renderValue($$, 'attrib').ref('attrib') ) return el } }
Make BlockQuote.content editable as container.
Make BlockQuote.content editable as container.
JavaScript
mit
substance/texture,substance/texture
--- +++ @@ -8,7 +8,7 @@ .attr('data-id', node.id) el.append( - this._renderValue($$, 'content').ref('content'), + this._renderValue($$, 'content', { container: true }).ref('content'), this._renderValue($$, 'attrib').ref('attrib') ) return el
62e6ed3baa6183897b1af121269d1dee9edb2704
js/popup.js
js/popup.js
// Filename: popup.js // Date: July 2017 // Authors: Evgeni Dobranov & Thomas Binu // Purpose: Defines extension UI and functional behavior // Entry point into app functionality function onPopupLoad(){ // Immediately inject script to get page content chrome.tabs.executeScript(null, { file: "js/contentscript.js" }, function(response) { if (chrome.runtime.lastError) { console.log("Chrome runtime error: ", chrome.runtime.lastError.message); } }); // Listener for communication with contentscript.js chrome.runtime.onMessage.addListener(function(request, sender) { if (request.action == "getSource") { var pageContent = (request.source).toString(); var pageContentCleaned = pageContent.replace(/[^a-zA-Z\s]/gi, '').replace(/(\r\n|\n|\r)/gm,''); var places = main(pageContentCleaned); console.log(places) // places = ['Seattle', 'Miami', 'Chicago', 'Moscow', 'Tahiti', 'Hawaii', 'Fiji', 'Bulgaria', 'India', 'Belgium', 'France', 'Brussels', 'Madrid'] renderEsriMap(places); $('#splash').hide() } }); } window.onload = onPopupLoad;
// Filename: popup.js // Date: July 2017 // Authors: Evgeni Dobranov & Thomas Binu // Purpose: Defines extension UI and functional behavior // Entry point into app functionality function onPopupLoad(){ // Immediately inject script to get page content chrome.tabs.executeScript(null, { file: "js/contentscript.js" }, function(response) { if (chrome.runtime.lastError) { console.log("Chrome runtime error: ", chrome.runtime.lastError.message); } }); // Listener for communication with contentscript.js chrome.runtime.onMessage.addListener(function(request, sender) { if (request.action == "getSource") { var pageContent = (request.source).toString(); var pageContentCleaned = pageContent.replace(/[^a-zA-Z0-9.,:;'\s]/gi, '').replace(/(\r\n|\n|\r)/gm,' ')//.replace(/(?:[A-Z]+[a-z]{2,}(?:and|of|is|to|the|a|from|in|out)*[ A-za-z\&,-:]*){4,}/, ''); var places = main(pageContentCleaned); // places = ['Seattle', 'Miami', 'Chicago', 'Moscow', 'Tahiti', 'Hawaii', 'Fiji', 'Bulgaria', 'India', 'Belgium', 'France', 'Brussels', 'Madrid'] renderEsriMap(places); $('#splash').hide() } }); } window.onload = onPopupLoad;
Update regex that cleans page content
Update regex that cleans page content Regex no longer removes common punctuation. Line breaks are replaced with a space.
JavaScript
apache-2.0
our-sinc-topo/visable-marketplace,our-sinc-topo/visable-marketplace
--- +++ @@ -19,9 +19,8 @@ if (request.action == "getSource") { var pageContent = (request.source).toString(); - var pageContentCleaned = pageContent.replace(/[^a-zA-Z\s]/gi, '').replace(/(\r\n|\n|\r)/gm,''); + var pageContentCleaned = pageContent.replace(/[^a-zA-Z0-9.,:;'\s]/gi, '').replace(/(\r\n|\n|\r)/gm,' ')//.replace(/(?:[A-Z]+[a-z]{2,}(?:and|of|is|to|the|a|from|in|out)*[ A-za-z\&,-:]*){4,}/, ''); var places = main(pageContentCleaned); - console.log(places) // places = ['Seattle', 'Miami', 'Chicago', 'Moscow', 'Tahiti', 'Hawaii', 'Fiji', 'Bulgaria', 'India', 'Belgium', 'France', 'Brussels', 'Madrid'] renderEsriMap(places);
8c8317d74cd996a2ea6d4fb014d51199108dbe01
src/components/Page/styles/Actions.css.js
src/components/Page/styles/Actions.css.js
// @flow import baseStyles from '../../../styles/resets/baseStyles.css.js' import styled from '../../styled' export const config = { marginBottom: 100, padding: '12px 0', spacing: 5, } export const ActionsUI = styled('div')` ${baseStyles} display: flex; flex-direction: row-reverse; margin-left: -${config.spacing}px; margin-right: -${config.spacing}px; margin-bottom: ${config.marginBottom}px; padding: ${config.padding}; &.is-left { flex-direction: row; } &.is-right { flex-direction: row-reverse; } ` export const ActionsItemUI = styled('div')` min-width: 0; margin: 0 ${config.spacing}px; ` export const ActionsBlockUI = styled('div')` flex: 1; max-width: 100%; min-width: 0; ` export default ActionsUI
// @flow import baseStyles from '../../../styles/resets/baseStyles.css.js' import styled from '../../styled' export const config = { marginBottom: 100, padding: '12px 0', spacing: 10, } export const ActionsUI = styled('div')` ${baseStyles} display: flex; flex-direction: row-reverse; margin-left: -${config.spacing}px; margin-right: -${config.spacing}px; margin-bottom: ${config.marginBottom}px; padding: ${config.padding}; &.is-left { flex-direction: row; } &.is-right { flex-direction: row-reverse; } ` export const ActionsItemUI = styled('div')` min-width: 0; margin: 0 ${config.spacing}px; ` export const ActionsBlockUI = styled('div')` flex: 1; max-width: 100%; min-width: 0; ` export default ActionsUI
Adjust spacing between Page.Actions items
Adjust spacing between Page.Actions items
JavaScript
mit
helpscout/blue,helpscout/blue,helpscout/blue
--- +++ @@ -5,7 +5,7 @@ export const config = { marginBottom: 100, padding: '12px 0', - spacing: 5, + spacing: 10, } export const ActionsUI = styled('div')`
1a0c26c08f4c61db23fe5ad990b69e1da7579d16
test/transformer.spec.js
test/transformer.spec.js
var tape = require('tape'); tape.test('transformer - should be a function', function (assert) { assert.equals(typeof require('../lib/transformer'), 'function'); assert.end(); }); tape.test('transformer - should return a templating function', function (assert) { assert.equals(typeof require('../lib/transformer')(), 'function'); assert.end(); }); tape.test('transformer - should return unmodified file without a template', function (assert) { var transformer = require('../lib/transformer')(); assert.equals(transformer('path/to/file.txt'), 'path/to/file.txt'); assert.end(); }); tape.test('transformer - should modify the filename based on the template with variables', function (assert) { var transformer = require('../lib/transformer')('{basename}.{extname}.old'); assert.equals(transformer('path/to/file.txt'), 'path/to/file.txt.old'); assert.end(); }); tape.test('transformer - should modify the filename based on the template', function (assert) { var transformer = require('../lib/transformer')('different.name'); assert.equals(transformer('path/to/file.txt'), 'path/to/different.name'); assert.end(); });
var tape = require('tape'); tape.test('transformer - should be a function', function (assert) { assert.equals(typeof require('../lib/transformer'), 'function'); assert.end(); }); tape.test('transformer - should return a templating function', function (assert) { assert.equals(typeof require('../lib/transformer')(), 'function'); assert.end(); }); tape.test('transformer - should return unmodified file without a template', function (assert) { var transformer = require('../lib/transformer')(); assert.equals(transformer('path/to/file.txt'), 'path/to/file.txt'); assert.end(); }); tape.test('transformer - should modify the filename based on the template with variables', function (assert) { var transformer = require('../lib/transformer')('{basename}.{extname}.old'); assert.equals(transformer('path/to/file.txt'), 'path/to/file.txt.old'); assert.end(); }); tape.test('transformer - should modify the filename based on the template', function (assert) { var transformer = require('../lib/transformer')('different.name'); assert.equals(transformer('path/to/file.txt'), 'path/to/different.name'); assert.end(); }); tape.test('transformer - should replace the {index} parameter', function (assert) { var transformer = require('../lib/transformer')('{index}.foo'); assert.equals(transformer('path/to/file.txt', 100), 'path/to/100.foo'); assert.end(); });
Add tests for the {index} placeholder
Add tests for the {index} placeholder
JavaScript
mit
nsand/newid
--- +++ @@ -27,3 +27,9 @@ assert.equals(transformer('path/to/file.txt'), 'path/to/different.name'); assert.end(); }); + +tape.test('transformer - should replace the {index} parameter', function (assert) { + var transformer = require('../lib/transformer')('{index}.foo'); + assert.equals(transformer('path/to/file.txt', 100), 'path/to/100.foo'); + assert.end(); +});
53a9b2e2afbd83c76d007dacdb8bfc1491e6d34e
tests/helperfunctions.js
tests/helperfunctions.js
function getMap(){ var map = new OpenLayers.Map({ layers: [ new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", { layers: "basic" } ) ] }); return map; } function getMapPanel(opts) { var map = getMap(); var options = Ext.apply(opts || {}); if (!opts || !opts.map) { options.map = map; } var mappanel = Ext.create('GXM.Map', options); return mappanel; } function getLazyMapPanel(opts) { var options = Ext.apply(opts || {}, { xtype: 'gxm_mappanel' }); options.map = ( opts && opts.map ) ? opts.map : getMap(); var mappanel = options; var panel = Ext.create('Ext.Panel', { fullscreen: true, items:[ mappanel ] }); return panel.items.get(0); }
function getMap(){ var map = new OpenLayers.Map({ layers: [ new OpenLayers.Layer.WMS( "OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", { layers: "basic" } ) ] }); return map; } function getMapPanel(opts) { var map = getMap(); var options = Ext.apply(opts || {}); if (!opts || !opts.map) { options.map = map; } var mappanel = Ext.create('GXM.Map', options); return mappanel; } function getLazyMapPanel(opts) { var options = Ext.apply(opts || {}, { xtype: 'gxm_map' }); options.map = ( opts && opts.map ) ? opts.map : getMap(); var mappanel = options; var panel = Ext.create('Ext.Panel', { fullscreen: true, items:[ mappanel ] }); return panel.items.get(0); }
Adjust the helperfunction for a lazy map component to use the correct xtype.
Adjust the helperfunction for a lazy map component to use the correct xtype.
JavaScript
bsd-3-clause
geoext/GXM,geoext/GXM
--- +++ @@ -24,7 +24,7 @@ } function getLazyMapPanel(opts) { - var options = Ext.apply(opts || {}, { xtype: 'gxm_mappanel' }); + var options = Ext.apply(opts || {}, { xtype: 'gxm_map' }); options.map = ( opts && opts.map ) ? opts.map : getMap(); var mappanel = options;
da1be2ea51c8afa987e237216154f436fe0fa867
lib/compolib.build.js
lib/compolib.build.js
'use strict' // var util = require('util') var console = require('better-console') // var renderNav = require('./compolib.renderNav') var filetreeToJSON = require('./compolib.filetreeToJSON') var components = require('./compolib.components') var ncp = require('ncp').ncp module.exports = function build (opts) { // copy assets to public folder ncp('node_modules/component-library-core/doc-template/assets', opts.location.dest + '/assets', function (err) { if (err) { return console.error(err) } }) // TODO make sure that there are no components in dest folder before creating new // could be the situation when .json files are missing/deleted, but dest component folder is still there opts.components = [] // before build, reset components opts.treeStructure['data'] = filetreeToJSON(opts, opts.location.src, true) // renderNav(opts) // create simple list of components // Saves data in opts.searchableItems components.generateSearch(opts) // render all components // - ( component.html & raw.component.html ) + navigation // - enrich components array with new data (style, info, data file locations) // Saves data in opts.components components.renderAll(opts) components.renderDashboard(opts) // console.log(util.inspect(opts.searchableItems, {showHidden: false, depth: null})) console.log('[CL] ' + opts.components.length + ' components rendered (' + opts.location.src + ')') }
'use strict' // var util = require('util') var console = require('better-console') // var renderNav = require('./compolib.renderNav') var filetreeToJSON = require('./compolib.filetreeToJSON') var components = require('./compolib.components') var ncp = require('ncp').ncp module.exports = function build (opts) { // copy assets to public folder ncp(opts.location.styleguide + '/assets', opts.location.dest + '/assets', function (err) { if (err) { return console.error(err) } }) // TODO make sure that there are no components in dest folder before creating new // could be the situation when .json files are missing/deleted, but dest component folder is still there opts.components = [] // before build, reset components opts.treeStructure['data'] = filetreeToJSON(opts, opts.location.src, true) // renderNav(opts) // create simple list of components // Saves data in opts.searchableItems components.generateSearch(opts) // render all components // - ( component.html & raw.component.html ) + navigation // - enrich components array with new data (style, info, data file locations) // Saves data in opts.components components.renderAll(opts) components.renderDashboard(opts) // console.log(util.inspect(opts.searchableItems, {showHidden: false, depth: null})) console.log('[CL] ' + opts.components.length + ' components rendered (' + opts.location.src + ')') }
Add non-hardcoded variable that leads to styleguide assets folder
Add non-hardcoded variable that leads to styleguide assets folder
JavaScript
mit
karlisup/chewingum,karlisup/chewingum
--- +++ @@ -9,7 +9,7 @@ module.exports = function build (opts) { // copy assets to public folder - ncp('node_modules/component-library-core/doc-template/assets', opts.location.dest + '/assets', function (err) { + ncp(opts.location.styleguide + '/assets', opts.location.dest + '/assets', function (err) { if (err) { return console.error(err) }
493bfd49c7a7d45bb723a4108889c27afc6bddff
examples/artwork-of-selection.js
examples/artwork-of-selection.js
var iTunes = require('../') , conn = null iTunes.createConnection(onConn); function onConn (err, c) { if (err) throw err; conn = c; conn.selection( onSelection ); } function onSelection (err, selection) { if (err) throw err; if (selection.length > 0) { var track = selection[0]; track.artworks(onArtworks); } else { console.log('There are no tracks currently selected...'); } } function onArtworks (err, artworks) { if (err) throw err; if (artworks.length > 0) { console.log(artworks); artworks[0].data(function (err, data) { if (err) throw err; console.log(data.constructor.name); console.log(data.length); }); } else { console.log('The selected track does not have any album artwork...'); } }
var iTunes = require('../') , conn = null iTunes.createConnection(onConn); function onConn (err, c) { if (err) throw err; conn = c; conn.selection( onSelection ); } function onSelection (err, selection) { if (err) throw err; if (selection.length > 0) { var track = selection[0]; track.artworks(onArtworks); } else { console.log('There are no tracks currently selected...'); } } function onArtworks (err, artworks) { if (err) throw err; if (artworks.length > 0) { console.log(artworks); artworks[0].data(function (err, data) { if (err) throw err; console.log(data.constructor.name); console.log(data.length); // A test to make sure that gargabe collecting one of the Buffers doesn't // cause a seg fault. Invoke node with '--expose_gc' to force garbage coll data = null; setTimeout(function() { if (typeof gc != 'undefined') { console.log('invoking gc()'); gc(); } }, 1000); setTimeout(function() { console.log("Done!"); }, 10000); }); } else { console.log('The selected track does not have any album artwork...'); } }
Add a test case to ensure that the memory leak is fixed.
Add a test case to ensure that the memory leak is fixed.
JavaScript
mit
TooTallNate/node-iTunes,TooTallNate/node-iTunes,TooTallNate/node-iTunes
--- +++ @@ -27,6 +27,17 @@ if (err) throw err; console.log(data.constructor.name); console.log(data.length); + + // A test to make sure that gargabe collecting one of the Buffers doesn't + // cause a seg fault. Invoke node with '--expose_gc' to force garbage coll + data = null; + setTimeout(function() { + if (typeof gc != 'undefined') { + console.log('invoking gc()'); + gc(); + } + }, 1000); + setTimeout(function() { console.log("Done!"); }, 10000); }); } else { console.log('The selected track does not have any album artwork...');
eb4c550d39d3231873e5dc059a062c052d3707de
webpack/plugins/commonsChunk.js
webpack/plugins/commonsChunk.js
const { optimize: { CommonsChunkPlugin }, } = require('webpack'); function isCss({ resource }) { return resource && resource.match(/\.(css|sss)$/); } function isVendor({ resource }) { return resource && resource.indexOf('node_modules') >= 0 && resource.match(/\.js$/); } module.exports = (config) => { config.plugins = [ ...config.plugins, new CommonsChunkPlugin({ name: 'vendor', minChunks: (module) => { if (isCss(module)) return false; return isVendor(module); }, }), new CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity, }), ]; return config; };
const { optimize: { CommonsChunkPlugin }, } = require('webpack'); function isCss({ resource }) { return resource && resource.match(/\.(css|sss)$/); } function isVendor({ resource }) { return resource && resource.indexOf('node_modules') >= 0 && resource.match(/\.js$/); } module.exports = (config) => { config.plugins = [ ...config.plugins, new CommonsChunkPlugin({ name: 'vendor', minChunks: (module) => { if (isCss(module)) return false; return isVendor(module); }, }), new CommonsChunkPlugin({ name: 'runtime', minChunks: Infinity, }), ]; return config; };
Rename common chunk "manifest" to "runtime"
Rename common chunk "manifest" to "runtime"
JavaScript
mit
AlexMasterov/webpack-kit,AlexMasterov/webpack-kit
--- +++ @@ -24,7 +24,7 @@ }, }), new CommonsChunkPlugin({ - name: 'manifest', + name: 'runtime', minChunks: Infinity, }), ];
e204f56c778711d707589a96b0aff021f2efeda3
tickle-frontend/src/errorReporting.js
tickle-frontend/src/errorReporting.js
// This should be the only file aware that we use Opbeat for error reporting. import { opbeatAppId, opbeatOrgId } from './settings' const init = () => { window._opbeat('config', { orgId: opbeatOrgId, appId: opbeatAppId }) } const setExtraContext = (extraContext) => { window._opbeat('setExtraContext', extraContext) } const capture = (err, extraContext) => { if (extraContext) setExtraContext(extraContext) window._opbeat('captureException', err) } const setUserContext = ({id, email}) => { window._opbeat('setUserContext', { is_authenticated: !!id, id: id, email: email, username: email }) } export { init, capture, setExtraContext, setUserContext }
// This should be the only file aware that we use Opbeat for error reporting. import { opbeatAppId, opbeatOrgId } from './settings' const init = () => { window._opbeat('config', { orgId: opbeatOrgId, appId: opbeatAppId }) } const setExtraContext = (extraContext) => { window._opbeat('setExtraContext', extraContext) } const capture = (err, extraContext) => { if (err.extra) setExtraContext(err.extra) if (extraContext) setExtraContext(extraContext) window._opbeat('captureException', err) } const setUserContext = ({id, email}) => { window._opbeat('setUserContext', { is_authenticated: !!id, id: id, email: email, username: email }) } export { init, capture, setExtraContext, setUserContext }
Use extra context from error object
Use extra context from error object
JavaScript
mit
ovidner/bitket,ovidner/bitket,ovidner/bitket,ovidner/bitket
--- +++ @@ -13,6 +13,7 @@ } const capture = (err, extraContext) => { + if (err.extra) setExtraContext(err.extra) if (extraContext) setExtraContext(extraContext) window._opbeat('captureException', err) }
9d8b30591611a56c2d6410eab501fcdb5997f3c3
test/decoder/decode.js
test/decoder/decode.js
import test from 'ava'; import { decoder } from '../../src'; import base from '../base'; test('should be able to compose decoder functions', t => { t.deepEqual( decoder.decode( [].concat( base.latLngBytes, base.unixtimeBytes, base.uint16Bytes, base.tempBytes, base.uint8Bytes, base.humidityBytes, base.rawFloatBytes, base.bitmapBytes ), [ decoder.latLng, decoder.unixtime, decoder.uint16, decoder.temperature, decoder.uint8, decoder.humidity, decoder.rawfloat, decoder.bitmap, ] ), { 0: base.latLng, 1: base.unixtime, 2: base.uint16, 3: base.temp, 4: base.uint8, 5: base.rawFloat, 6: base.bitmap, } ); t.pass(); }); test('should yell at you if mask is longer than input', t => { t.throws(() => decoder.decode([1, 2, 3, 4, 5, 6, 7], [decoder.latLng]), /Mask/i); t.pass(); }); test('should be able to take names', t => { t.deepEqual( decoder.decode(base.unixtimeBytes, [decoder.unixtime], ['time']), { time: base.unixtime } ); t.pass(); });
import test from 'ava'; import { decoder } from '../../src'; import base from '../base'; test('should be able to compose decoder functions', t => { t.deepEqual( decoder.decode( [].concat( base.latLngBytes, base.unixtimeBytes, base.uint16Bytes, base.tempBytes, base.uint8Bytes, base.humidityBytes, base.rawFloatBytes, base.bitmapBytes ), [ decoder.latLng, decoder.unixtime, decoder.uint16, decoder.temperature, decoder.uint8, decoder.humidity, decoder.rawfloat, decoder.bitmap, ] ), { 0: base.latLng, 1: base.unixtime, 2: base.uint16, 3: base.temp, 4: base.uint8, 5: base.humidity, 5: base.rawFloat, 6: base.bitmap, } ); t.pass(); }); test('should yell at you if mask is longer than input', t => { t.throws(() => decoder.decode([1, 2, 3, 4, 5, 6, 7], [decoder.latLng]), /Mask/i); t.pass(); }); test('should be able to take names', t => { t.deepEqual( decoder.decode(base.unixtimeBytes, [decoder.unixtime], ['time']), { time: base.unixtime } ); t.pass(); });
Fix copy-paste typo in unit test.
Fix copy-paste typo in unit test.
JavaScript
mit
thesolarnomad/lora-serialization,thesolarnomad/lora-serialization,thesolarnomad/lora-serialization,thesolarnomad/lora-serialization,thesolarnomad/lora-serialization,thesolarnomad/lora-serialization
--- +++ @@ -31,6 +31,7 @@ 2: base.uint16, 3: base.temp, 4: base.uint8, + 5: base.humidity, 5: base.rawFloat, 6: base.bitmap, }
99057f25b5c98fb4ff89090f96dbcb112ab93c86
dropbox_client.js
dropbox_client.js
DropboxOAuth = {}; // Request dropbox credentials for the user // @param options {optional} // @param callback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. DropboxOAuth.requestCredential = function (options, callback) { // support both (options, callback) and (callback). if (!callback && typeof options === 'function') { callback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'dropbox'}); if (!config) { callback && callback(new ServiceConfiguration.ConfigError("Service not configured")); return; } var credentialToken = Random.secret(); var loginStyle = OAuth._loginStyle('dropbox', config, options); var loginUrl = 'https://www.dropbox.com/1/oauth2/authorize' + '?response_type=code' + '&client_id=' + config.clientId + '&redirect_uri=' + OAuth._redirectUri('dropbox', config, {}, {secure: true}) + '&state=' + OAuth._stateParam(loginStyle, credentialToken).replace('?close&', '?close=true&'); OAuth.launchLogin({ loginService: "dropbox", loginStyle: loginStyle, loginUrl: loginUrl, credentialRequestCompleteCallback: callback, credentialToken: credentialToken, popupOptions: { height: 600 } }); };
DropboxOAuth = {}; // Request dropbox credentials for the user // @param options {optional} // @param callback {Function} Callback function to call on // completion. Takes one argument, credentialToken on success, or Error on // error. DropboxOAuth.requestCredential = function (options, callback) { // support both (options, callback) and (callback). if (!callback && typeof options === 'function') { callback = options; options = {}; } var config = ServiceConfiguration.configurations.findOne({service: 'dropbox'}); if (!config) { callback && callback(new ServiceConfiguration.ConfigError("Service not configured")); return; } var credentialToken = Random.secret(); var loginStyle = OAuth._loginStyle('dropbox', config, options); var loginUrl = 'https://www.dropbox.com/1/oauth2/authorize' + '?response_type=code' + '&client_id=' + config.clientId + '&redirect_uri=' + OAuth._redirectUri('dropbox', config, {}, {secure: true}) + '&state=' + OAuth._stateParam(loginStyle, credentialToken); loginUrl = loginUrl.replace('?close&', '?close=true&'); OAuth.launchLogin({ loginService: "dropbox", loginStyle: loginStyle, loginUrl: loginUrl, credentialRequestCompleteCallback: callback, credentialToken: credentialToken, popupOptions: { height: 600 } }); };
Undo code for client logic
Undo code for client logic
JavaScript
mit
gcampax/meteor-dropbox-oauth,gcampax/meteor-dropbox-oauth
--- +++ @@ -27,7 +27,8 @@ '?response_type=code' + '&client_id=' + config.clientId + '&redirect_uri=' + OAuth._redirectUri('dropbox', config, {}, {secure: true}) + - '&state=' + OAuth._stateParam(loginStyle, credentialToken).replace('?close&', '?close=true&'); + '&state=' + OAuth._stateParam(loginStyle, credentialToken); + loginUrl = loginUrl.replace('?close&', '?close=true&'); OAuth.launchLogin({ loginService: "dropbox",
f2264fa5eab081f13ba87bf79eae1e1a6c64bf8f
test/sugar_dom_test.js
test/sugar_dom_test.js
/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/ /*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/ /*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/ (function(el, document) { test('is awesome', 1, function() { ok(el('p').nodeName.match(/p/i), 'should be thoroughly awesome'); }); }(el, document));
/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/ /*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/ /*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/ (function(el, document) { test('creating plain DOM elements', function() { ok( el('p').nodeName.match(/p/i), 'can create classic elements' ); ok( el('div').nodeName.match(/div/i), 'can create classic elements' ); ok( el('video').nodeName.match(/video/i), 'can create HTML5 elements' ); }); }(el, document));
Add more basic tests for creating elements
Add more basic tests for creating elements
JavaScript
mit
webmat/sugar_dom
--- +++ @@ -3,8 +3,10 @@ /*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/ (function(el, document) { - test('is awesome', 1, function() { - ok(el('p').nodeName.match(/p/i), 'should be thoroughly awesome'); + test('creating plain DOM elements', function() { + ok( el('p').nodeName.match(/p/i), 'can create classic elements' ); + ok( el('div').nodeName.match(/div/i), 'can create classic elements' ); + ok( el('video').nodeName.match(/video/i), 'can create HTML5 elements' ); }); }(el, document));
5c67a13bd8167183720cb8d39ff9e5630d8398e3
src/js/api.js
src/js/api.js
import ApiEvents from './events/ApiEvents'; import { firebaseRef } from './appconfig'; var ref = firebaseRef.child('notes'); var API = { start() { ref.on('child_added', (snapshot) => { var noteName = snapshot.key(); var note = snapshot.val(); ApiEvents.noteAdded(noteName, note); }); ref.on('child_removed', (snapshot) => { var noteName = snapshot.key(); ApiEvents.noteRemoved(noteName); }); ref.on('child_changed', (snapshot) => { var noteName = snapshot.key(); var note = snapshot.val(); ApiEvents.noteChanged(noteName, note); }); }, stop() { ref.off('child_added'); ref.off('child_removed'); ref.off('child_changed'); }, createNote(data) { ref.push(data); }, deleteNote(name) { ref.child(name).remove(); }, updateNote(name, data) { ref.child(name).update(data); }, }; export default API;
import ApiEvents from './events/ApiEvents'; import { firebaseRef } from './appconfig'; var noteRef = firebaseRef.child('notes'); var API = { start() { noteRef.on('child_added', (snapshot) => { var noteName = snapshot.key(); var note = snapshot.val(); ApiEvents.noteAdded(noteName, note); }); noteRef.on('child_removed', (snapshot) => { var noteName = snapshot.key(); ApiEvents.noteRemoved(noteName); }); noteRef.on('child_changed', (snapshot) => { var noteName = snapshot.key(); var note = snapshot.val(); ApiEvents.noteChanged(noteName, note); }); }, stop() { noteRef.off('child_added'); noteRef.off('child_removed'); noteRef.off('child_changed'); }, createNote(data) { noteRef.push(data); }, deleteNote(name) { noteRef.child(name).remove(); }, updateNote(name, data) { noteRef.child(name).update(data); }, }; export default API;
Rename ref to noteRef in API
Rename ref to noteRef in API Will need ref to ref the base ref.
JavaScript
mit
kentor/notejs-react,kentor/notejs-react,kentor/notejs-react
--- +++ @@ -1,22 +1,22 @@ import ApiEvents from './events/ApiEvents'; import { firebaseRef } from './appconfig'; -var ref = firebaseRef.child('notes'); +var noteRef = firebaseRef.child('notes'); var API = { start() { - ref.on('child_added', (snapshot) => { + noteRef.on('child_added', (snapshot) => { var noteName = snapshot.key(); var note = snapshot.val(); ApiEvents.noteAdded(noteName, note); }); - ref.on('child_removed', (snapshot) => { + noteRef.on('child_removed', (snapshot) => { var noteName = snapshot.key(); ApiEvents.noteRemoved(noteName); }); - ref.on('child_changed', (snapshot) => { + noteRef.on('child_changed', (snapshot) => { var noteName = snapshot.key(); var note = snapshot.val(); ApiEvents.noteChanged(noteName, note); @@ -24,21 +24,21 @@ }, stop() { - ref.off('child_added'); - ref.off('child_removed'); - ref.off('child_changed'); + noteRef.off('child_added'); + noteRef.off('child_removed'); + noteRef.off('child_changed'); }, createNote(data) { - ref.push(data); + noteRef.push(data); }, deleteNote(name) { - ref.child(name).remove(); + noteRef.child(name).remove(); }, updateNote(name, data) { - ref.child(name).update(data); + noteRef.child(name).update(data); }, };
a012312485095fd894806b4070164f859bcab523
minechat.js
minechat.js
var readline = require('readline'); var mineflayer = require('mineflayer'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); var bot = mineflayer.createBot({ host: "hostname", username: "user@email.com", password: "password" }); rl.on('line', function(line) { bot.chat(line); }); bot.on('chat', function(username, message) { console.log(username + ": " + message); });
var readline = require('readline'); var mineflayer = require('mineflayer'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); function print_help() { console.log("usage: node minechat.js <hostname> <user> <password>"); } if (process.argv.length < 5) { console.log("Too few arguments!"); print_help(); process.exit(1); } process.argv.forEach(function(val, index, array) { if (val == "-h") { print_help(); process.exit(0); } }); var bot = mineflayer.createBot({ host: process.argv[2], username: process.argv[3], password: process.argv[4] }); rl.on('line', function(line) { bot.chat(line); }); bot.on('chat', function(username, message) { console.log(username + ": " + message); });
Read host, user and passwd from arglist
Read host, user and passwd from arglist
JavaScript
mit
ut7/minechat,llbit/minechat
--- +++ @@ -7,10 +7,27 @@ terminal: false }); +function print_help() { + console.log("usage: node minechat.js <hostname> <user> <password>"); +} + +if (process.argv.length < 5) { + console.log("Too few arguments!"); + print_help(); + process.exit(1); +} + +process.argv.forEach(function(val, index, array) { + if (val == "-h") { + print_help(); + process.exit(0); + } +}); + var bot = mineflayer.createBot({ - host: "hostname", - username: "user@email.com", - password: "password" + host: process.argv[2], + username: process.argv[3], + password: process.argv[4] }); rl.on('line', function(line) {
dbd02d4ae342e0b5797dc2cd4b7092daf20a1e73
js/select_place.js
js/select_place.js
var Place = {}; $(document).on('pageshow', '#select-place', function() { $('#select-place-map').css('height', 500); utils.getCurrentLocation().done(function(location) { Place.map = Map.createMap('select-place-map', location.latitude, location.longitude, 12); Place.currentLocation = Map.createMarker(Place.map, 'Current Location', location.latitude, location.longitude, true); Place.setPostLocation(); google.maps.event.addListener(Place.currentLocation, 'dragend', function() { Place.setPostLocation(); }); }); }); Place.getMarkerLocation = function() { var pos = Place.currentLocation.getPosition(); var lat = pos.lat(); var lng = pos.lng(); return {"latitude": lat, "longitude": lng}; }; Place.setPostLocation = function() { var location = Place.getMarkerLocation(); $('#post-lat').val(location.latitude); $('#post-lng').val(location.longitude); };
var Place = {}; $(document).on('pageshow', '#select-place', function() { $('#select-place-map').css('height', 450); var pos = Map.map.getCenter(); Place.map = Map.createMap('select-place-map', pos.lat(), pos.lng(), 8); // kutc Place.currentLocation = Map.createMarker(Place.map, 'Current Location', pos.lat(), pos.lng(), true); Place.setPostLocation(); google.maps.event.addListener(Place.currentLocation, 'dragend', function() { Place.setPostLocation(); }); }); Place.getMarkerLocation = function() { var pos = Place.currentLocation.getPosition(); var lat = pos.lat(); var lng = pos.lng(); return {"latitude": lat, "longitude": lng}; }; Place.setPostLocation = function() { var location = Place.getMarkerLocation(); $('#post-lat').val(location.latitude); $('#post-lng').val(location.longitude); };
Set select place marker latlng based on main map center latlng
Set select place marker latlng based on main map center latlng
JavaScript
mit
otknoy/michishiki
--- +++ @@ -1,19 +1,17 @@ var Place = {}; $(document).on('pageshow', '#select-place', function() { - $('#select-place-map').css('height', 500); + $('#select-place-map').css('height', 450); - utils.getCurrentLocation().done(function(location) { - Place.map = Map.createMap('select-place-map', - location.latitude, location.longitude, 12); - Place.currentLocation = Map.createMarker(Place.map, 'Current Location', - location.latitude, location.longitude, true); + var pos = Map.map.getCenter(); + Place.map = Map.createMap('select-place-map', pos.lat(), pos.lng(), 8); // kutc + Place.currentLocation = Map.createMarker(Place.map, 'Current Location', + pos.lat(), pos.lng(), true); + Place.setPostLocation(); + + google.maps.event.addListener(Place.currentLocation, 'dragend', function() { Place.setPostLocation(); - - google.maps.event.addListener(Place.currentLocation, 'dragend', function() { - Place.setPostLocation(); - }); }); });
d0cf2ffa9ed5613bd6bb34c7cd6049d8b6304b27
test/cypress/plugins/index.js
test/cypress/plugins/index.js
/* eslint-disable */ require('dotenv').config() module.exports = (on, config) => { if (config.testingType === 'component') { require('@cypress/react/plugins/load-webpack')(on, config, {webpackFilename: './webpack.config.js'}) return config } require('@cypress/code-coverage/task')(on, config) on('file:preprocessor', require('@cypress/code-coverage/use-babelrc')) on("task", { log(message) { console.log(message) return null }, }) config.env.sandbox_url = process.env.API_ROOT return config }
/* eslint-disable */ require('dotenv').config() module.exports = (on, config) => { if (config.testingType === 'component') { require('@cypress/react/plugins/load-webpack')(on, config, { webpackFilename: './webpack.config.js' }) return config } require('@cypress/code-coverage/task')(on, config) on('file:preprocessor', require('@cypress/code-coverage/use-babelrc')) on("task", { log(message) { console.log(message) return null }, }) config.env.sandbox_url = process.env.API_ROOT config.env.one_list_email = process.env.ONE_LIST_EMAIL return config }
Fix formatting in plugins file
Fix formatting in plugins file
JavaScript
mit
uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2
--- +++ @@ -3,17 +3,21 @@ module.exports = (on, config) => { if (config.testingType === 'component') { - require('@cypress/react/plugins/load-webpack')(on, config, {webpackFilename: './webpack.config.js'}) + require('@cypress/react/plugins/load-webpack')(on, config, { webpackFilename: './webpack.config.js' }) return config } require('@cypress/code-coverage/task')(on, config) on('file:preprocessor', require('@cypress/code-coverage/use-babelrc')) - on("task", { log(message) { + on("task", { + log(message) { console.log(message) return null }, }) + config.env.sandbox_url = process.env.API_ROOT + config.env.one_list_email = process.env.ONE_LIST_EMAIL + return config }
b3aa0298d5bdccd24a614f7a1194fae0762e4685
js/forum/src/components/DiscussionRenamedPost.js
js/forum/src/components/DiscussionRenamedPost.js
import EventPost from 'flarum/components/EventPost'; /** * The `DiscussionRenamedPost` component displays a discussion event post * indicating that the discussion has been renamed. * * ### Props * * - All of the props for EventPost */ export default class DiscussionRenamedPost extends EventPost { icon() { return 'pencil'; } descriptionKey() { return 'core.discussion_renamed_post'; } descriptionData() { const post = this.props.post; const oldTitle = post.content()[0]; const newTitle = post.content()[1]; return { old: <strong className="DiscussionRenamedPost-old">{oldTitle}</strong>, new: <strong className="DiscussionRenamedPost-new">{newTitle}</strong> }; } }
import EventPost from 'flarum/components/EventPost'; /** * The `DiscussionRenamedPost` component displays a discussion event post * indicating that the discussion has been renamed. * * ### Props * * - All of the props for EventPost */ export default class DiscussionRenamedPost extends EventPost { icon() { return 'pencil'; } descriptionKey() { return 'core.discussion_renamed_post'; } descriptionData() { const post = this.props.post; const oldTitle = post.content()[0]; const newTitle = post.content()[1]; return { 'old': <strong className="DiscussionRenamedPost-old">{oldTitle}</strong>, 'new': <strong className="DiscussionRenamedPost-new">{newTitle}</strong> }; } }
Fix use of "new" keyword making eslint angry
Fix use of "new" keyword making eslint angry
JavaScript
mit
Albert221/core,flarum/core,malayladu/core,falconchen/core,renyuneyun/core,vuthaihoc/core,Luceos/core,flarum/core,dungphanxuan/core,datitisev/core,zaksoup/core,falconchen/core,datitisev/core,Albert221/core,Onyx47/core,Luceos/core,zaksoup/core,datitisev/core,Albert221/core,renyuneyun/core,kirkbushell/core,kidaa/core,zaksoup/core,vuthaihoc/core,falconchen/core,flarum/core,Albert221/core,dungphanxuan/core,kirkbushell/core,kirkbushell/core,Onyx47/core,renyuneyun/core,Luceos/core,malayladu/core,kidaa/core,malayladu/core,billmn/core,kirkbushell/core,vuthaihoc/core,datitisev/core,dungphanxuan/core,billmn/core,Luceos/core,renyuneyun/core,billmn/core,Onyx47/core,malayladu/core,kidaa/core
--- +++ @@ -23,8 +23,8 @@ const newTitle = post.content()[1]; return { - old: <strong className="DiscussionRenamedPost-old">{oldTitle}</strong>, - new: <strong className="DiscussionRenamedPost-new">{newTitle}</strong> + 'old': <strong className="DiscussionRenamedPost-old">{oldTitle}</strong>, + 'new': <strong className="DiscussionRenamedPost-new">{newTitle}</strong> }; } }
762e01365545b5eb2638fbe8efd9753fef907d92
app.js
app.js
function Dialogue(title,contents,buttons) { var Title; var Contents; var Buttons; /** Setters */ function SetTitle(){ } function SetButtons(){ } function SetContents(){ } function SetID(){ } /** Getters */ function GetTitle(){ } function GetButtons(){ } function GetContents(){ } function GetID(){ } /** Functionals */ function Init(){ SetTitle(title); SetContents(contents); SetButtons(buttons); SetID(); } Init(); /** Publicly Exposed Methods */ return { show: function(){ alert("Showing Dialogue"); }, hide: function(){ alert("Hiding Dialogue"); } } } var dialogue = new Dialogue("Help", "Some random help text", ["close", "ok", "cancel"]);
function App(){ return { assert: function(a, b, message) { if (a !== b) { throw message || "Assertion Failed"; } } } } function Dialogue(title,contents,buttons){ var Title; var Contents; var Buttons; var ID; var app = new App(); /** Setters */ function SetTitle(title){ Title = title; app.assert(Title, title, "Title not set correctly."); } function SetButtons(){ } function SetContents(){ } function SetID(){ } /** Getters */ function GetTitle(){ } function GetButtons(){ } function GetContents(){ } function GetID(){ } /** Functionals */ function Init(){ SetTitle(title); SetContents(contents); SetButtons(buttons); SetID(); } Init(); /** Publicly Exposed Methods */ return { show: function(){ alert("Showing Dialogue"); }, hide: function(){ alert("Hiding Dialogue"); } } } var dialogue = new Dialogue("Help", "Some random help text", ["close", "ok", "cancel"]);
Add assert as part of App();
Add assert as part of App();
JavaScript
mit
lgoldstien/legacy.JS
--- +++ @@ -1,12 +1,25 @@ -function Dialogue(title,contents,buttons) { +function App(){ + return { + assert: function(a, b, message) { + if (a !== b) { + throw message || "Assertion Failed"; + } + } + } +} + +function Dialogue(title,contents,buttons){ var Title; var Contents; var Buttons; + var ID; + var app = new App(); /** Setters */ - function SetTitle(){ - + function SetTitle(title){ + Title = title; + app.assert(Title, title, "Title not set correctly."); } function SetButtons(){ @@ -41,6 +54,7 @@ } Init(); + /** Publicly Exposed Methods */ return { show: function(){
69100f5362709045ef496caad23a464921dc63ba
frontend/app/base/directives/editable_link.js
frontend/app/base/directives/editable_link.js
angular.module('app.directives').directive('editableLink', editableLink); function editableLink() { return { restrict: 'E', scope: { viewModel: '=', type: '@', field: '@', object: '=?', socialMediaName: '@?', }, templateUrl: 'base/directives/editable_link.html', controller: EditableLinkController, controllerAs: 'el', transclude: true, bindToController: true, }; } EditableLinkController.$inject = []; function EditableLinkController() { var el = this; el.updateViewModel = updateViewModel; activate(); ///// function activate() { if (!el.object) { if (!el.socialMediaName) { el.object = el.viewModel[el.type.toLowerCase()]; } } } function updateViewModel($data) { var patchPromise; var args = {}; if (el.object) { args = { id: el.object.id, }; } args[el.field] = $data; if (el.socialMediaName) { args.name = el.socialMediaName; patchPromise = el.viewModel.updateModel(args, el.socialMediaName); } else { patchPromise = el.viewModel.updateModel(args).$promise; } return patchPromise; } }
angular.module('app.directives').directive('editableLink', editableLink); function editableLink() { return { restrict: 'E', scope: { viewModel: '=', type: '@', field: '@', object: '=?', socialMediaName: '@?', }, templateUrl: 'base/directives/editable_link.html', controller: EditableLinkController, controllerAs: 'el', transclude: true, bindToController: true, }; } EditableLinkController.$inject = []; function EditableLinkController() { var el = this; el.updateViewModel = updateViewModel; activate(); ///// function activate() { if (!el.object) { if (!el.socialMediaName) { el.object = el.viewModel[el.type.toLowerCase()]; } } } function updateViewModel($data) { var patchPromise; var args = {}; if (el.object) { args = { id: el.object.id, }; } args[el.field] = $data; if (el.socialMediaName) { if ($data) { args.name = el.socialMediaName; } else { args.is_deleted = true; } patchPromise = el.viewModel.updateModel(args, el.socialMediaName); } else { patchPromise = el.viewModel.updateModel(args).$promise; } return patchPromise; } }
Allow clearing of social media fields with inline editing
LILY-2266: Allow clearing of social media fields with inline editing
JavaScript
agpl-3.0
HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily
--- +++ @@ -50,7 +50,12 @@ args[el.field] = $data; if (el.socialMediaName) { - args.name = el.socialMediaName; + if ($data) { + args.name = el.socialMediaName; + } else { + args.is_deleted = true; + } + patchPromise = el.viewModel.updateModel(args, el.socialMediaName); } else { patchPromise = el.viewModel.updateModel(args).$promise;
120096cd116a7dcd910ea5d887a6e969b206b53d
controller.js
controller.js
'use strict'; const Foxx = require('org/arangodb/foxx'); const schema = require('./schema'); const graphql = require('graphql-sync').graphql; const ctrl = new Foxx.Controller(applicationContext); // This is a regular Foxx HTTP API endpoint. ctrl.post('/graphql', function (req, res) { // By just passing the raw body string to graphql // we let the GraphQL library take care of making // sure the query is well-formed and valid. // Our HTTP API doesn't have to know anything about // GraphQL to handle it. const result = graphql(schema, req.rawBody(), null, req.parameters); console.log(req.parameters); if (result.errors) { res.status(400); res.json({ errors: result.errors }); } else { res.json(result); } }) .summary('GraphQL endpoint') .notes('GraphQL endpoint for the Star Wars GraphQL example.');
'use strict'; const Foxx = require('org/arangodb/foxx'); const schema = require('./schema'); const graphql = require('graphql-sync').graphql; const formatError = require('graphql-sync').formatError; const ctrl = new Foxx.Controller(applicationContext); // This is a regular Foxx HTTP API endpoint. ctrl.post('/graphql', function (req, res) { // By just passing the raw body string to graphql // we let the GraphQL library take care of making // sure the query is well-formed and valid. // Our HTTP API doesn't have to know anything about // GraphQL to handle it. const result = graphql(schema, req.rawBody(), null, req.parameters); console.log(req.parameters); if (result.errors) { res.status(400); res.json({ errors: result.errors.map(function (error) { return formatError(error); }) }); } else { res.json(result); } }) .summary('GraphQL endpoint') .notes('GraphQL endpoint for the Star Wars GraphQL example.');
Use formatError to expose errors
Use formatError to expose errors
JavaScript
apache-2.0
arangodb-foxx/demo-graphql
--- +++ @@ -2,6 +2,7 @@ const Foxx = require('org/arangodb/foxx'); const schema = require('./schema'); const graphql = require('graphql-sync').graphql; +const formatError = require('graphql-sync').formatError; const ctrl = new Foxx.Controller(applicationContext); @@ -17,7 +18,9 @@ if (result.errors) { res.status(400); res.json({ - errors: result.errors + errors: result.errors.map(function (error) { + return formatError(error); + }) }); } else { res.json(result);
67eb630c11fe5ef0578411745d9734714ae39022
util/debug.js
util/debug.js
var browserify = require('browserify'); var cssify = require('cssify'); var watchify = require('watchify'); var through = require('through'); var fs = require('fs'); var path = require('path'); var cp = require('child_process'); function globalOl(file) { var data = ''; function write(buf) { data += buf; } function end() { this.queue(data.replace(/require\(["']openlayers['"]\)/g, 'window.ol')); this.queue(null); } return through(write, end); } var b = browserify({ entries: ['./src/index.js'], debug: true, plugin: [watchify], cache: {}, packageCache: {} }).transform(globalOl).transform(cssify, {global: true}); b.on('update', function bundle(onError) { var stream = b.bundle(); if (onError) { stream.on('error', function(err) { console.log(err.message); process.exit(1); }); } stream.pipe(fs.createWriteStream('./_index.js')); }); b.bundle(function(err, buf) { if (err) { console.error(err.message); process.exit(1); } else { fs.writeFile('./_index.js', buf, 'utf-8'); cp.fork(path.join(path.dirname(require.resolve('openlayers')), '../tasks/serve-lib.js'), []); } });
var browserify = require('browserify'); var cssify = require('cssify'); var watchify = require('watchify'); var through = require('through'); var fs = require('fs'); var path = require('path'); var cp = require('child_process'); function globalOl(file) { var data = ''; function write(buf) { data += buf; } function end() { this.queue(data.replace(/require\(["']openlayers['"]\)/g, 'window.ol')); this.queue(null); } return through(write, end); } var b = browserify({ entries: ['./src/index.js'], debug: true, plugin: [watchify], cache: {}, packageCache: {} }).transform(globalOl).transform(cssify, {global: true}); b.on('update', function() { b.bundle().pipe(fs.createWriteStream('./_index.js')); }); b.bundle(function(err, buf) { if (err) { console.error(err.message); process.exit(1); } else { fs.writeFile('./_index.js', buf, 'utf-8'); cp.fork(path.join(path.dirname(require.resolve('openlayers')), '../tasks/serve-lib.js'), []); } });
Remove accidently added error handler from update listener
Remove accidently added error handler from update listener
JavaScript
bsd-2-clause
ahocevar/openlayers-app,ahocevar/openlayers-app
--- +++ @@ -24,15 +24,8 @@ packageCache: {} }).transform(globalOl).transform(cssify, {global: true}); -b.on('update', function bundle(onError) { - var stream = b.bundle(); - if (onError) { - stream.on('error', function(err) { - console.log(err.message); - process.exit(1); - }); - } - stream.pipe(fs.createWriteStream('./_index.js')); +b.on('update', function() { + b.bundle().pipe(fs.createWriteStream('./_index.js')); }); b.bundle(function(err, buf) {
26b3b8c32d8fd9a51e374f4cdd278a5fcec92daf
project/static/js/authors/friend-requests.js
project/static/js/authors/friend-requests.js
$(function() { var $friend_request_button = $("#send-friend-request-button"); var $friend_request_sent_message = $("#friend-request-sent-message"); $friend_request_button.on('click', function () { var $that = $(this); $.post($that.data('url'), function () { $that.hide(); $friend_request_sent_message.show() }); }); });
$(function() { var $friend_request_button = $("#send-friend-request-button"); var $friend_request_sent_message = $("#friend-request-sent-message"); var $follow_button = $("#follow-button"); var $unfollow_button = $("#unfollow-button"); $friend_request_button.on('click', function () { var $that = $(this); $.post($that.data('url'), function () { $that.hide(); $follow_button.hide(); $friend_request_sent_message.show() $unfollow_button.show(); }); }); });
Update UI to represent that author is also followed when you send a friend request
Update UI to represent that author is also followed when you send a friend request
JavaScript
apache-2.0
TeamAADGT/CMPUT404-project-socialdistribution,TeamAADGT/CMPUT404-project-socialdistribution,TeamAADGT/CMPUT404-project-socialdistribution
--- +++ @@ -1,12 +1,16 @@ $(function() { var $friend_request_button = $("#send-friend-request-button"); var $friend_request_sent_message = $("#friend-request-sent-message"); + var $follow_button = $("#follow-button"); + var $unfollow_button = $("#unfollow-button"); $friend_request_button.on('click', function () { var $that = $(this); $.post($that.data('url'), function () { $that.hide(); + $follow_button.hide(); $friend_request_sent_message.show() + $unfollow_button.show(); }); }); });
5de73ce2cf93631bf48fee2ae5ae7c54bd500fba
src/values/PropertyDescriptor.js
src/values/PropertyDescriptor.js
"use strict"; /* @flow */ const Value = require('../Value'); let serial = 0; //TODO: We should call this a PropertyDescriptor, not a variable. class PropertyDescriptor { constructor(value) { this.value = value; this.serial = serial++; this.configurable = true; this.enumerable = true; this.writeable = true; } set(value) { if ( !this.writeable ) return; this.value = value; } *getValue(thiz) { thiz = thiz || Value.null; if ( this.getter ) { return yield * this.getter.call(thiz, []); } return this.value; } *setValue(thiz, to) { if ( !this.writeable ) return; thiz = thiz || Value.null; if ( this.getter ) { return yield * this.setter.call(thiz, [to]); } this.value = to; return this.value; } } module.exports = PropertyDescriptor;
"use strict"; /* @flow */ const Value = require('../Value'); let serial = 0; //TODO: We should call this a PropertyDescriptor, not a variable. class PropertyDescriptor { constructor(value) { this.value = value; this.serial = serial++; this.configurable = true; this.enumerable = true; this.writeable = true; } set(value) { if ( !this.writeable ) return; this.value = value; } *getValue(thiz) { thiz = thiz || Value.null; if ( this.getter ) { return yield * this.getter.call(thiz, []); } return this.value; } *setValue(thiz, to) { thiz = thiz || Value.null; if ( this.getter ) { return yield * this.setter.call(thiz, [to]); } if ( !this.writeable ) return this.value; this.value = to; return this.value; } } module.exports = PropertyDescriptor;
Call setter even if object isn't writable.
Call setter even if object isn't writable.
JavaScript
mit
codecombat/esper.js,codecombat/esper.js,codecombat/esper.js
--- +++ @@ -30,11 +30,11 @@ } *setValue(thiz, to) { - if ( !this.writeable ) return; thiz = thiz || Value.null; if ( this.getter ) { return yield * this.setter.call(thiz, [to]); } + if ( !this.writeable ) return this.value; this.value = to; return this.value; }
66d7acce7bf82ddc0a0afa5e1fae8e6a13214c47
Chapter_2/app.js
Chapter_2/app.js
var http = require('http'); var os = require('os'); var handler = function(request, response) { response.writeHead(200); response.end("You've hit " + os.hostname()); } var www = http.createServer(handler); www.listen(8080);
var http = require('http'); var os = require('os'); var handler = function(request, response) { response.writeHead(200); response.end("You've hit " + os.hostname() + "\n"); } var www = http.createServer(handler); www.listen(8080);
Add a new line character
Add a new line character
JavaScript
mit
Evalle/k8s-in-action,Evalle/k8s-in-action
--- +++ @@ -3,7 +3,7 @@ var handler = function(request, response) { response.writeHead(200); - response.end("You've hit " + os.hostname()); + response.end("You've hit " + os.hostname() + "\n"); } var www = http.createServer(handler);
0fb6b78a3f59152405c0f6e5a81adcd939c1fc01
src/commands/tick-rm.js
src/commands/tick-rm.js
export default rm import Entry from '../entry' import PouchDB from 'pouchdb' import {write} from './output' import chalk from 'chalk' import conf from '../config' let db = new PouchDB(conf.db) function rm (yargs) { let argv = yargs .usage('tick rm entryid') .argv db.get(argv._[1]) .then(removeEntry) } function removeEntry (doc) { const e = Entry.fromJSON(doc) write(e) return db.remove(doc).then(result => { console.log(chalk.bgRed('removed')) }) }
export default rm import Entry from '../entry' import PouchDB from 'pouchdb' import {write} from './output' import chalk from 'chalk' import conf from '../config' let db = new PouchDB(conf.db) function rm (yargs) { let argv = yargs .usage('Usage: tick rm [options] <entryid ...>') .help('h') .alias('h', 'help') .argv db.get(argv._[1]) .then(removeEntry) } function removeEntry (doc) { const e = Entry.fromJSON(doc) write(e) return db.remove(doc).then(result => { console.log(chalk.bgRed('removed')) }) }
Clean up tick rm usage and add help
Clean up tick rm usage and add help
JavaScript
agpl-3.0
jonotron/tickbin,tickbin/tickbin,chadfawcett/tickbin
--- +++ @@ -10,8 +10,10 @@ function rm (yargs) { let argv = yargs - .usage('tick rm entryid') - .argv + .usage('Usage: tick rm [options] <entryid ...>') + .help('h') + .alias('h', 'help') + .argv db.get(argv._[1]) .then(removeEntry)
c02374368a35d3780d67d88c79e8bfef139fae80
ckeditor/static/ckeditor/ckeditor/config.js
ckeditor/static/ckeditor/ckeditor/config.js
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; // CKEDITOR.config.contentsCss = '/static/admin/blog/css/ckeditor_content.css'; };
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; // Disable the CKEditor right-click menu and // the SCAYT dictionary plugin. // This will allow the native spell-checker to work config.removePlugins = 'scayt,menubutton,contextmenu'; config.disableNativeSpellChecker = false; };
Disable the SCAYT and context menu CKEditor plugins so we can use the native browser / OS spell-checker instead.
Disable the SCAYT and context menu CKEditor plugins so we can use the native browser / OS spell-checker instead.
JavaScript
bsd-3-clause
ZG-Tennis/django-ckeditor,ZG-Tennis/django-ckeditor,ZG-Tennis/django-ckeditor,ZG-Tennis/django-ckeditor,ZG-Tennis/django-ckeditor
--- +++ @@ -8,5 +8,10 @@ // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; - // CKEDITOR.config.contentsCss = '/static/admin/blog/css/ckeditor_content.css'; + + // Disable the CKEditor right-click menu and + // the SCAYT dictionary plugin. + // This will allow the native spell-checker to work + config.removePlugins = 'scayt,menubutton,contextmenu'; + config.disableNativeSpellChecker = false; };
623b9508b89f243f7f0652d01cf18f79c7604405
snippets/base/static/js/templateChooserWidget.js
snippets/base/static/js/templateChooserWidget.js
;$(function() { 'use strict'; if ($('.inline-template').length > 1) { $('.inline-template').hide(); $('#id_template_chooser').change(function() { let template = $(this).val(); $('.inline-template').hide(); if (template) { $inline = $('.' + template).show(); } }); } });
;$(function() { 'use strict'; function showTemplate() { let value = $('#id_template_chooser').val(); if (value) { $('.inline-template').hide(); $('.' + value).show(); } } if ($('.inline-template').length > 1) { $('.inline-template').hide(); // Show correct template on load showTemplate(); // Show correct template on change $('#id_template_chooser').change(function() { showTemplate(); }); } });
Fix template chooser on save error.
Fix template chooser on save error.
JavaScript
mpl-2.0
glogiotatidis/snippets-service,mozmar/snippets-service,mozilla/snippets-service,mozmar/snippets-service,mozilla/snippets-service,mozmar/snippets-service,glogiotatidis/snippets-service,mozmar/snippets-service,mozilla/snippets-service,glogiotatidis/snippets-service,mozilla/snippets-service,glogiotatidis/snippets-service
--- +++ @@ -1,14 +1,23 @@ ;$(function() { 'use strict'; + function showTemplate() { + let value = $('#id_template_chooser').val(); + if (value) { + $('.inline-template').hide(); + $('.' + value).show(); + } + } + if ($('.inline-template').length > 1) { $('.inline-template').hide(); + + // Show correct template on load + showTemplate(); + + // Show correct template on change $('#id_template_chooser').change(function() { - let template = $(this).val(); - $('.inline-template').hide(); - if (template) { - $inline = $('.' + template).show(); - } + showTemplate(); }); } });
b1416f9fabc1a6c17436eb443050ec8e997abc1a
app/js/arethusa.core/arethusa_local_storage.js
app/js/arethusa.core/arethusa_local_storage.js
"use strict"; /** * @ngdoc service * @name arethusa.core.arethusaLocalStorage * * @description * Arethusa's API to communicate with `localStorage`. All values stored are * prefixed with `arethusa.`. * * Performs type coercion upon retrieval for Booleans, so that `true`, `false` * and `null` can be used properly. * * @requires localStorageService */ angular.module('arethusa.core').service('arethusaLocalStorage', [ 'localStorageService', function(localStorageService) { /** * @ngdoc function * @name arethusa.core.arethusaLocalStorage#get * @methodOf arethusa.core.arethusaLocalStorage * * @param {String} key The key * @returns {*} The stored value */ this.get = function(key) { return coerce(localStorageService.get(key)); }; /** * @ngdoc function * @name arethusa.core.arethusaLocalStorage#set * @methodOf arethusa.core.arethusaLocalStorage * * @param {String} key The key * @param {*} value The value */ this.set = localStorageService.set; var JSONBooleans = ['true', 'false', 'null']; function coerce(value) { if (JSONBooleans.indexOf(value) === -1) { return value; } else { return JSON.parse(value); } } } ]);
"use strict"; /** * @ngdoc service * @name arethusa.core.arethusaLocalStorage * * @description * Arethusa's API to communicate with `localStorage`. All values stored are * prefixed with `arethusa.`. * * Performs type coercion upon retrieval for Booleans, so that `true`, `false` * and `null` can be used properly. * * @requires localStorageService */ angular.module('arethusa.core').service('arethusaLocalStorage', [ 'localStorageService', function(localStorageService) { /** * @ngdoc function * @name arethusa.core.arethusaLocalStorage#get * @methodOf arethusa.core.arethusaLocalStorage * * @param {String} key The key * @returns {*} The stored value */ this.get = function(key) { return coerce(localStorageService.get(key)); }; /** * @ngdoc function * @name arethusa.core.arethusaLocalStorage#set * @methodOf arethusa.core.arethusaLocalStorage * * @param {String} key The key * @param {*} value The value */ this.set = localStorageService.set; this.keys = localStorageService.keys; var JSONBooleans = ['true', 'false', 'null']; function coerce(value) { if (JSONBooleans.indexOf(value) === -1) { return value; } else { return JSON.parse(value); } } } ]);
Add delegator for keys() in arethusaLocalStorage
Add delegator for keys() in arethusaLocalStorage
JavaScript
mit
Masoumeh/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa
--- +++ @@ -38,6 +38,8 @@ */ this.set = localStorageService.set; + this.keys = localStorageService.keys; + var JSONBooleans = ['true', 'false', 'null']; function coerce(value) { if (JSONBooleans.indexOf(value) === -1) {
8d479ed64e6e21445cfa8e5c60f46605bd8eea5a
lib/components/completeBlock/completeBlock.js
lib/components/completeBlock/completeBlock.js
import CompleteBlock from './completeBlock.html'; import './completeBlock.scss'; class CompleteBlock { static detailsComponent() { return { templateUrl: CompleteBlock, bindings: { headerImg: '@', headerTitle: '@', headerPicto: '@', headerColor: '@', headerBackgroundColor: '@', bodyBackgroundColor: '@', bodyTitle: '@', bodyText: '@' } }; } } export default CompleteBlock.detailsComponent();
import TemplateCompleteBlock from './completeBlock.html'; import './completeBlock.scss'; class CompleteBlock { static detailsComponent() { return { templateUrl: TemplateCompleteBlock, bindings: { headerImg: '@', headerTitle: '@', headerPicto: '@', headerColor: '@', headerBackgroundColor: '@', bodyBackgroundColor: '@', bodyTitle: '@', bodyText: '@' } }; } } export default CompleteBlock.detailsComponent();
Rename variable because the template and the class has the same name
fix: Rename variable because the template and the class has the same name
JavaScript
mit
kevincaradant/web-template-webpack,kevincaradant/web-template-webpack
--- +++ @@ -1,10 +1,10 @@ -import CompleteBlock from './completeBlock.html'; +import TemplateCompleteBlock from './completeBlock.html'; import './completeBlock.scss'; class CompleteBlock { static detailsComponent() { return { - templateUrl: CompleteBlock, + templateUrl: TemplateCompleteBlock, bindings: { headerImg: '@', headerTitle: '@',
46c3ec4c3eb99e3a8812e6674ce6940f4f15a5aa
test/client/ui-saucelabs.conf.js
test/client/ui-saucelabs.conf.js
exports.config = { specs: ['ui/**/*.spec.js'], sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, baseUrl: 'http://localhost:3000', capabilities: { 'browserName': 'firefox', 'platform': 'Linux', 'version': '32', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'AgileJS Training Repo' } };
exports.config = { specs: ['ui/**/*.spec.js'], sauceUser: process.env.SAUCE_USERNAME, sauceKey: process.env.SAUCE_ACCESS_KEY, baseUrl: 'http://localhost:3000', capabilities: { 'browserName': 'firefox', 'platform': 'Windows 7', 'version': '32', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER, 'name': 'AgileJS Training Repo' } };
Use Windows on Sauce to avoid unsupported platform combinations
Use Windows on Sauce to avoid unsupported platform combinations
JavaScript
mit
agilejs/2014-10-code-red
--- +++ @@ -5,7 +5,7 @@ baseUrl: 'http://localhost:3000', capabilities: { 'browserName': 'firefox', - 'platform': 'Linux', + 'platform': 'Windows 7', 'version': '32', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, 'build': process.env.TRAVIS_BUILD_NUMBER,
efbef4f393cd571b593b5aafb7cd3465f1102e62
src/components/utils.js
src/components/utils.js
export function asyncHandler(handler) { return function(req, res, next) { if (!handler) { throw new Error(`Invalid handler ${handler}, it must be a function.`); } handler(req, res, next) .then(function(response) { if (response) { res.send(response); } }) .catch(function(err) { let message = err.message; let status = 500; if (message.match(/^[\d]{3}:/)) { message = message.substring(4).trim(); const code = parseInt(message.substr(0, 3), 10); if (!isNaN(code)) { status = code; } } res.status(status).json({ error: message }); if (status >= 500) { console.error(err.stack); } }); }; }
export function asyncHandler(handler) { return function(req, res, next) { if (!handler) { throw new Error(`Invalid handler ${handler}, it must be a function.`); } handler(req, res, next) .then(function(response) { if (response) { res.send(response); } }) .catch(function(err) { let message = err.message; let status = 500; if (message.match(/^[\d]{3}:/)) { status = parseInt(message.substr(0, 3), 10); message = message.substring(4).trim(); } res.status(status).json({ error: message }); if (status >= 500) { console.error(err.stack); } }); }; }
Fix incorrect extraction of error code
Fix incorrect extraction of error code
JavaScript
mit
arkakkar/electron-update-api,TakeN0/squirrel-updates-server,Aluxian/squirrel-updates-server
--- +++ @@ -15,11 +15,8 @@ let status = 500; if (message.match(/^[\d]{3}:/)) { + status = parseInt(message.substr(0, 3), 10); message = message.substring(4).trim(); - const code = parseInt(message.substr(0, 3), 10); - if (!isNaN(code)) { - status = code; - } } res.status(status).json({
a1e25a3e10cc2ce7cbf9c07284981cd2cc5b85eb
app/assets/javascripts/application.js
app/assets/javascripts/application.js
//= require jquery //= require jquery_ujs //= require jquery.remotipart //= require select2 //= require cocoon //= require dropzone //= require govuk/selection-buttons //= require moj //= require modules/moj.cookie-message.js //= require_tree . (function () { 'use strict'; delete moj.Modules.devs; $('#fixed-fees, #misc-fees, #expenses, #documents').on('cocoon:after-insert', function (e, insertedItem) { $(insertedItem).find('.select2').select2(); }); $('.select2').select(); //Stops the form from submitting when the user presses 'Enter' key $('#claim-form, #claim-status').on('keypress', function(e) { if (e.keyCode === 13) { return false; } }); var selectionButtons = new GOVUK.SelectionButtons("label input[type='radio'], label input[type='checkbox']"); moj.init(); }());
//= require jquery //= require jquery_ujs //= require jquery.remotipart //= require select2 //= require cocoon //= require dropzone //= require vendor/polyfills/bind //= require govuk/selection-buttons //= require moj //= require modules/moj.cookie-message.js //= require_tree . (function () { 'use strict'; delete moj.Modules.devs; $('#fixed-fees, #misc-fees, #expenses, #documents').on('cocoon:after-insert', function (e, insertedItem) { $(insertedItem).find('.select2').select2(); }); $('.select2').select(); //Stops the form from submitting when the user presses 'Enter' key $('#claim-form, #claim-status').on('keypress', function(e) { if (e.keyCode === 13) { return false; } }); var selectionButtons = new GOVUK.SelectionButtons("label input[type='radio'], label input[type='checkbox']"); moj.init(); }());
Fix issue with PhantomJS and Function.prototype.bind support
Fix issue with PhantomJS and Function.prototype.bind support
JavaScript
mit
ministryofjustice/advocate-defence-payments,ministryofjustice/advocate-defence-payments,ministryofjustice/advocate-defence-payments,ministryofjustice/advocate-defence-payments
--- +++ @@ -4,6 +4,7 @@ //= require select2 //= require cocoon //= require dropzone +//= require vendor/polyfills/bind //= require govuk/selection-buttons //= require moj //= require modules/moj.cookie-message.js
97b56dd8f09dbc18f4c57652fd665f325aec6bcb
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require_self //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree .
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . //= require ./jquery.min.js //= require ./jquery.wookmark.js
Remove require_self and back to require ./wookmark...
Remove require_self and back to require ./wookmark...
JavaScript
mit
ninabreznik/RefugeesWork,ninabreznik/RefugeesWork,ninabreznik/RefugeesWork
--- +++ @@ -10,8 +10,9 @@ // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // -//= require_self //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . +//= require ./jquery.min.js +//= require ./jquery.wookmark.js
15732c641dfbd0d814dff0bb6cfdc9c0d4293d2a
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require jquery-ui //= require Scrollify //= require turbolinks //= require_tree .
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require jquery-ui //= require turbolinks //= require_tree .
Remove loading of scrollify, not using
Remove loading of scrollify, not using
JavaScript
mit
fma2/cfe-money,fma2/cfe-money,fma2/cfe-money
--- +++ @@ -13,6 +13,5 @@ //= require jquery //= require jquery_ujs //= require jquery-ui -//= require Scrollify //= require turbolinks //= require_tree .
650f4373a69a4af57def67ce53356ef8093e603b
test/specs/component/TextSpec.js
test/specs/component/TextSpec.js
import ReactDOM from 'react-dom'; import React from 'react'; import { shallow, render } from 'enzyme'; import { expect } from 'chai'; import { Text } from 'recharts'; describe('<Text />', () => { it('Does not wrap long text if enough width', () => { const wrapper = shallow( <Text width={200}>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(1); }); it('Wraps long text if not enough width', () => { const wrapper = shallow( <Text width={125}>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(2); }); it('Wraps long text if styled and not enough room', () => { const wrapper = shallow( <Text width={200} style={{ fontSize: '32px' }}>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(2); }); it('Does not perform word length calculation if width or fit props not set', () => { const wrapper = shallow( <Text>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(1); expect(wrapper.instance().state.wordsByLines[0].width).to.equal(undefined); }); });
import ReactDOM from 'react-dom'; import React from 'react'; import { shallow, render } from 'enzyme'; import { expect } from 'chai'; import { Text } from 'recharts'; describe('<Text />', () => { it('Does not wrap long text if enough width', () => { const wrapper = shallow( <Text width={300} style={{ fontFamily: 'Courier' }}>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(1); }); it('Wraps long text if not enough width', () => { const wrapper = shallow( <Text width={200} style={{ fontFamily: 'Courier' }}>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(2); }); it('Wraps long text if styled but would have had enough room', () => { const wrapper = shallow( <Text width={300} style={{ fontSize: '2em', fontFamily: 'Courier' }}>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(2); }); it('Does not perform word length calculation if width or fit props not set', () => { const wrapper = shallow( <Text>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(1); expect(wrapper.instance().state.wordsByLines[0].width).to.equal(undefined); }); });
Set fontFamily on <Text> tests to guarantee consistent regardless of environment (hopefully fix failures in CI)
Set fontFamily on <Text> tests to guarantee consistent regardless of environment (hopefully fix failures in CI)
JavaScript
mit
recharts/recharts,sdoomz/recharts,recharts/recharts,sdoomz/recharts,thoqbk/recharts,thoqbk/recharts,sdoomz/recharts,recharts/recharts,recharts/recharts,thoqbk/recharts
--- +++ @@ -7,7 +7,7 @@ describe('<Text />', () => { it('Does not wrap long text if enough width', () => { const wrapper = shallow( - <Text width={200}>This is really long text</Text> + <Text width={300} style={{ fontFamily: 'Courier' }}>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(1); @@ -15,15 +15,15 @@ it('Wraps long text if not enough width', () => { const wrapper = shallow( - <Text width={125}>This is really long text</Text> + <Text width={200} style={{ fontFamily: 'Courier' }}>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(2); }); - it('Wraps long text if styled and not enough room', () => { + it('Wraps long text if styled but would have had enough room', () => { const wrapper = shallow( - <Text width={200} style={{ fontSize: '32px' }}>This is really long text</Text> + <Text width={300} style={{ fontSize: '2em', fontFamily: 'Courier' }}>This is really long text</Text> ); expect(wrapper.instance().state.wordsByLines.length).to.equal(2);
dbe6cea973ff30b9b5ca61f09b34b61b8cf5295d
src/elements/element.js
src/elements/element.js
import TYPES from 'types'; function isMember(element) { if (element.element) { return element.element === TYPES.MEMBER; } return element === TYPES.MEMBER; } function getValueType({element, content}) { if (isMember(element)) { return content.value.element; } return element; } function getType(element) { if (isMember(element.element)) { return getValueType(element); } return element.element; } function isObject(element) { if (!element) { return false; } if (element.element) { return getType(element) === TYPES.OBJECT; } return element === TYPES.OBJECT; } function isArray(element) { if (!element) { return false; } if (element.element) { return getType(element) === TYPES.ARRAY; } return element === TYPES.ARRAY; } function isEnum(element) { if (element.element) { return getType(element) === TYPES.ARRAY; } return element === TYPES.ENUM; } function isNestedObject(element) { return isObject(element) || isArray(element) || isEnum(element); function hasSamples(element) { const attributes = element.attributes; let samples = null; if (attributes) { return !!attributes.samples; } else { return false; } } } export { getValueType, getType, isMember, isEnum, isObject, isArray, isNestedObject, hasSamples, };
import TYPES from 'types'; function isMember(element) { if (element.element) { return element.element === TYPES.MEMBER; } return element === TYPES.MEMBER; } function getValueType({element, content}) { if (isMember(element)) { return content.value.element; } return element; } function getType(element) { if (isMember(element.element)) { return getValueType(element); } return element.element; } function isObject(element) { if (!element) { return false; } if (element.element) { return getType(element) === TYPES.OBJECT; } return element === TYPES.OBJECT; } function isArray(element) { if (!element) { return false; } if (element.element) { return getType(element) === TYPES.ARRAY; } return element === TYPES.ARRAY; } function isEnum(element) { if (element.element) { return getType(element) === TYPES.ARRAY; } return element === TYPES.ENUM; } function isObjectOrArray(element) { return isObject(element) || isArray(element); } function hasSamples(element) { const attributes = element.attributes; let samples = null; if (attributes) { return !!attributes.samples; } else { return false; } } } export { getValueType, getType, isMember, isEnum, isObject, isArray, isObjectOrArray, hasSamples, };
Remove the ‘isNestedObject’ helper, no longer used.
Element: Remove the ‘isNestedObject’ helper, no longer used.
JavaScript
mit
apiaryio/attributes-kit,apiaryio/attributes-kit,apiaryio/attributes-kit
--- +++ @@ -56,8 +56,10 @@ return element === TYPES.ENUM; } -function isNestedObject(element) { - return isObject(element) || isArray(element) || isEnum(element); +function isObjectOrArray(element) { + return isObject(element) || isArray(element); +} + function hasSamples(element) { const attributes = element.attributes; @@ -78,6 +80,6 @@ isEnum, isObject, isArray, - isNestedObject, + isObjectOrArray, hasSamples, };
4ffa7245d7f0cb5e053ff3219d8b586c62938819
src/js/pebble-js-app.js
src/js/pebble-js-app.js
var initialized = false; var options = {}; Pebble.addEventListener("ready", function() { console.log("ready called!"); initialized = true; }); Pebble.addEventListener("showConfiguration", function() { console.log("showing configuration"); Pebble.openURL('http://assets.getpebble.com.s3-website-us-east-1.amazonaws.com/pebble-js/configurable.html?'+encodeURIComponent(JSON.stringify(options))); }); Pebble.addEventListener("webviewclosed", function(e) { console.log("configuration closed"); // webview closed if (e.response != "{}") { options = JSON.parse(decodeURIComponent(e.response)); console.log("Options = " + JSON.stringify(options)); } else { console.log("Cancelled"); } });
var initialized = false; var options = {}; Pebble.addEventListener("ready", function() { console.log("ready called!"); initialized = true; }); Pebble.addEventListener("showConfiguration", function() { console.log("showing configuration"); Pebble.openURL('http://assets.getpebble.com.s3-website-us-east-1.amazonaws.com/pebble-js/configurable.html?'+encodeURIComponent(JSON.stringify(options))); }); Pebble.addEventListener("webviewclosed", function(e) { console.log("configuration closed"); // webview closed //Using primitive JSON validity and non-empty check if (e.response.charAt(0) == "{" && e.response.slice(-1) == "}" && e.response.length > 5) { options = JSON.parse(decodeURIComponent(e.response)); console.log("Options = " + JSON.stringify(options)); } else { console.log("Cancelled"); } });
Improve robustness of cancellation detection.
Improve robustness of cancellation detection.
JavaScript
mit
pebble-hacks/js-configure-demo,pebble-hacks/js-configure-demo,pebble-hacks/js-configure-demo,pebble-hacks/js-configure-demo
--- +++ @@ -14,7 +14,8 @@ Pebble.addEventListener("webviewclosed", function(e) { console.log("configuration closed"); // webview closed - if (e.response != "{}") { + //Using primitive JSON validity and non-empty check + if (e.response.charAt(0) == "{" && e.response.slice(-1) == "}" && e.response.length > 5) { options = JSON.parse(decodeURIComponent(e.response)); console.log("Options = " + JSON.stringify(options)); } else {
5b3e52464bb32c64ba3c08a705c166a064fc537a
lib/transform/transform-space.js
lib/transform/transform-space.js
import Promise from 'bluebird' import { omit, defaults } from 'lodash/object' import { partialRight } from 'lodash/partialRight' import * as defaultTransformers from './transformers' const spaceEntities = [ 'contentTypes', 'entries', 'assets', 'locales', 'webhooks' ] /** * Run transformer methods on each item for each kind of entity, in case there * is a need to transform data when copying it to the destination space */ export default function ( sourceSpace, destinationSpace, customTransformers, entities = spaceEntities ) { const transformers = defaults(customTransformers, defaultTransformers) const newSpace = omit(sourceSpace, ...entities) // Use bluebird collection methods to support async transforms. return Promise.reduce(entities, (newSpace, type) => { const transformer = transformers[type] const sourceEntities = sourceSpace[type] const destinationEntities = destinationSpace[type] const typeTransform = partialRight(applyTransformer, transformer, destinationEntities, destinationSpace) return Promise.map(sourceEntities, typeTransform).then((entities) => { newSpace[type] = entities return newSpace }) }, newSpace) } function applyTransformer (entity, transformer, destinationEntities, destinationSpace) { return Promise.props({ original: entity, transformed: transformer(entity, destinationEntities, destinationSpace) }) }
import Promise from 'bluebird' import { omit, defaults } from 'lodash/object' import * as defaultTransformers from './transformers' const spaceEntities = [ 'contentTypes', 'entries', 'assets', 'locales', 'webhooks' ] /** * Run transformer methods on each item for each kind of entity, in case there * is a need to transform data when copying it to the destination space */ export default function ( space, destinationSpace, customTransformers, entities = spaceEntities ) { const transformers = defaults(customTransformers, defaultTransformers) // TODO maybe we don't need promises here at all const newSpace = omit(space, ...entities) return Promise.reduce(entities, (newSpace, type) => { return Promise.map( space[type], (entity) => Promise.resolve({ original: entity, transformed: transformers[type](entity, destinationSpace[type]) }) ) .then((entities) => { newSpace[type] = entities return newSpace }) }, newSpace) }
Revert Enable async entity transforms
fix(transformers): Revert Enable async entity transforms This reverts commit 6dcad860e5fc67fabcebeee762aad42d06e029e9.
JavaScript
mit
contentful/contentful-batch-libs
--- +++ @@ -1,6 +1,5 @@ import Promise from 'bluebird' import { omit, defaults } from 'lodash/object' -import { partialRight } from 'lodash/partialRight' import * as defaultTransformers from './transformers' const spaceEntities = [ @@ -12,28 +11,22 @@ * is a need to transform data when copying it to the destination space */ export default function ( - sourceSpace, destinationSpace, customTransformers, entities = spaceEntities + space, destinationSpace, customTransformers, entities = spaceEntities ) { const transformers = defaults(customTransformers, defaultTransformers) - const newSpace = omit(sourceSpace, ...entities) - // Use bluebird collection methods to support async transforms. + // TODO maybe we don't need promises here at all + const newSpace = omit(space, ...entities) return Promise.reduce(entities, (newSpace, type) => { - const transformer = transformers[type] - const sourceEntities = sourceSpace[type] - const destinationEntities = destinationSpace[type] - const typeTransform = partialRight(applyTransformer, transformer, - destinationEntities, destinationSpace) - - return Promise.map(sourceEntities, typeTransform).then((entities) => { - newSpace[type] = entities - return newSpace - }) + return Promise.map( + space[type], + (entity) => Promise.resolve({ + original: entity, + transformed: transformers[type](entity, destinationSpace[type]) + }) + ) + .then((entities) => { + newSpace[type] = entities + return newSpace + }) }, newSpace) } - -function applyTransformer (entity, transformer, destinationEntities, destinationSpace) { - return Promise.props({ - original: entity, - transformed: transformer(entity, destinationEntities, destinationSpace) - }) -}
e4594662b73173fae86d3ad64351828421aae962
src/palettes/nearest.js
src/palettes/nearest.js
// @flow import { RANGE } from "constants/controlTypes"; import type { ColorRGBA } from "types"; const optionTypes = { levels: { type: RANGE, range: [1, 256], default: 2 } }; const defaults = { levels: optionTypes.levels.default }; // Gets nearest color const getColor = ( color: ColorRGBA, options: { levels: number } = defaults ): ColorRGBA => { const step = 255 / (options.levels - 1); // $FlowFixMe return color.map(c => { const bucket = Math.round(c / step); return Math.round(bucket * step); }); }; export default { name: "nearest", getColor, options: defaults, optionTypes, defaults };
// @flow import { RANGE } from "constants/controlTypes"; import type { ColorRGBA } from "types"; const optionTypes = { levels: { type: RANGE, range: [1, 256], default: 2 } }; const defaults = { levels: optionTypes.levels.default }; // Gets nearest color const getColor = ( color: ColorRGBA, options: { levels: number } = defaults ): ColorRGBA => { if (options.levels >= 256) { return color; } const step = 255 / (options.levels - 1); // $FlowFixMe return color.map(c => { const bucket = Math.round(c / step); return Math.round(bucket * step); }); }; export default { name: "nearest", getColor, options: defaults, optionTypes, defaults };
Return early if full colour
Nearest: Return early if full colour
JavaScript
mit
gyng/ditherer,gyng/ditherer,gyng/ditherer
--- +++ @@ -17,6 +17,10 @@ color: ColorRGBA, options: { levels: number } = defaults ): ColorRGBA => { + if (options.levels >= 256) { + return color; + } + const step = 255 / (options.levels - 1); // $FlowFixMe
9fe2fb9aed4fb4c8833443a4df400591d18976da
dangerfile.js
dangerfile.js
import { danger, warn } from 'danger'; const packageChanged = danger.git.modified_files.includes('package.json'); const lockfileChanged = danger.git.modified_files.includes('package-lock.json'); if (packageChanged && !lockfileChanged) { warn(`Changes were made to package.json, but not to package-lock.json. Perhaps you need to run \`rm package-lock.json && npm install\`. Make sure you’re using npm 5+.`); }
import { danger, warn } from 'danger'; const packageChanged = danger.git.modified_files.includes('package.json'); const lockfileChanged = danger.git.modified_files.includes('package-lock.json'); if (packageChanged && !lockfileChanged) { warn(`Changes were made to package.json, but not to package-lock.json. Perhaps you need to run \`npm install\` and commit changes in package-lock.json.. Make sure you’re using npm 5+.`); }
Update message when package-lock.json should be updated
Chore: Update message when package-lock.json should be updated No need to remove lock file anymore.
JavaScript
mit
styleguidist/react-styleguidist,sapegin/react-styleguidist,sapegin/react-styleguidist,styleguidist/react-styleguidist,bluetidepro/react-styleguidist,styleguidist/react-styleguidist
--- +++ @@ -5,5 +5,5 @@ if (packageChanged && !lockfileChanged) { warn(`Changes were made to package.json, but not to package-lock.json. -Perhaps you need to run \`rm package-lock.json && npm install\`. Make sure you’re using npm 5+.`); +Perhaps you need to run \`npm install\` and commit changes in package-lock.json.. Make sure you’re using npm 5+.`); }
fdedf38a1ccc570ca5ce30e4bf72a0927fa119b1
scripts/tasks/download.js
scripts/tasks/download.js
'use strict' var github = require('octonode') var client = github.client() var evRepo = client.repo('nodejs/evangelism') var https = require('https') var path = require('path') var fs = require('fs') /* Currently proof-of-concept work. Outstanding: * ================ * - [ ] gulpify * - [ ] add to local boot process or trigger at key times * - [ ] support other content patterns (meeting notes, release notes, etc.) * - [ ] support similar patterns for other locales * - [ ] prepend predictable markdown metadata on download */ function checkOrFetchFile (file) { let name = file.name let downloadUrl = file.download_url let localPath = path.join(__dirname, '..', '..', 'locale', 'en', 'blog', 'weekly-updates', name) if (fs.existsSync(localPath)) { console.log(`Weekly Update ${name} exists. (No SHA check, yet.)`) return } console.log(`Weekly Update ${name} does not exist. Downloading.`) var outputFile = fs.createWriteStream(localPath) https.get(downloadUrl, function (response) { response.pipe(outputFile) }) } evRepo.contents('weekly-updates', function (err, files) { if (err) { throw err } files.forEach(checkOrFetchFile) })
'use strict' const github = require('octonode') const https = require('https') const path = require('path') const fs = require('fs') const basePath = path.join(__dirname, '..', '..', 'locale', 'en', 'blog', 'weekly-updates') const repo = github.client().repo('nodejs/evangelism') /* Currently proof-of-concept work. Outstanding: * ================ * - [ ] gulpify * - [ ] add to local boot process or trigger at key times * - [ ] support other content patterns (meeting notes, release notes, etc.) * - [ ] support similar patterns for other locales * - [ ] prepend predictable markdown metadata on download */ function checkOrFetchFile (file) { const filePath = path.join(basePath, file.name) fs.access(filePath, function (err) { if (!err) { console.log(`Weekly Update ${filePath} exists. (No SHA check, yet.)`) return } console.log(`Weekly Update ${filePath} does not exist. Downloading.`) https.get(file.download_url, function (response) { console.log(`Weekly Update ${filePath} downloaded.`) response.pipe(fs.createWriteStream(filePath)) }) }) } repo.contents('weekly-updates', function (err, files) { if (err) { throw err } files.forEach(checkOrFetchFile) })
Use `fs.access` instead of `fs.existsSync`
Use `fs.access` instead of `fs.existsSync`
JavaScript
mit
strawbrary/nodejs.org,marocchino/new.nodejs.org,abdelrahmansaeedhassan/yuri,boneskull/new.nodejs.org,nodejs/new.nodejs.org,rnsloan/new.nodejs.org,yous/new.nodejs.org,matthewloring/new.nodejs.org,rnsloan/new.nodejs.org,boneskull/new.nodejs.org,yous/new.nodejs.org,nodejs/new.nodejs.org,strawbrary/nodejs.org,phillipj/new.nodejs.org,abdelrahmansaeedhassan/yuri,phillipj/new.nodejs.org,matthewloring/new.nodejs.org,marocchino/new.nodejs.org
--- +++ @@ -1,12 +1,12 @@ 'use strict' -var github = require('octonode') -var client = github.client() -var evRepo = client.repo('nodejs/evangelism') +const github = require('octonode') +const https = require('https') +const path = require('path') +const fs = require('fs') -var https = require('https') -var path = require('path') -var fs = require('fs') +const basePath = path.join(__dirname, '..', '..', 'locale', 'en', 'blog', 'weekly-updates') +const repo = github.client().repo('nodejs/evangelism') /* Currently proof-of-concept work. Outstanding: * ================ @@ -18,24 +18,24 @@ */ function checkOrFetchFile (file) { - let name = file.name - let downloadUrl = file.download_url + const filePath = path.join(basePath, file.name) - let localPath = path.join(__dirname, '..', '..', 'locale', 'en', 'blog', 'weekly-updates', name) - if (fs.existsSync(localPath)) { - console.log(`Weekly Update ${name} exists. (No SHA check, yet.)`) - return - } + fs.access(filePath, function (err) { + if (!err) { + console.log(`Weekly Update ${filePath} exists. (No SHA check, yet.)`) + return + } - console.log(`Weekly Update ${name} does not exist. Downloading.`) + console.log(`Weekly Update ${filePath} does not exist. Downloading.`) - var outputFile = fs.createWriteStream(localPath) - https.get(downloadUrl, function (response) { - response.pipe(outputFile) + https.get(file.download_url, function (response) { + console.log(`Weekly Update ${filePath} downloaded.`) + response.pipe(fs.createWriteStream(filePath)) + }) }) } -evRepo.contents('weekly-updates', function (err, files) { +repo.contents('weekly-updates', function (err, files) { if (err) { throw err } files.forEach(checkOrFetchFile) })
9df9040dfbb5004a3a3ff90287caed2d03c77c3f
simplayer.js
simplayer.js
#!/usr/bin/env node 'use strict'; var childProcess = require('child_process'); /** * play * To run the process to match the platform. * @param {string} filepath * @param {function} callback * @return {Object} childProcess */ function play(filepath, callback) { var mediaSoundPlayer = '(New-Object System.Media.SoundPlayer "' + filepath + '").Play()'; var player = process.platform === 'darwin' ? 'afplay' : 'aplay'; if (typeof filepath === 'string') { filepath = [filepath]; } if (! callback) { callback = function(error) { if (error) throw error; } } return process.platform === 'win32' ? childProcess.exec('powershell.exe -NoExit ' + mediaSoundPlayer, callback) : childProcess.execFile(player, filepath, callback); } module.exports = play; if (require.main && require.main.id === module.id) { play(process.argv.slice(2)); }
#!/usr/bin/env node 'use strict'; var childProcess = require('child_process'); /** * play * To run the process to match the platform. * @param {string} filepath * @param {function} callback * @return {Object} childProcess */ function play(filepath, callback) { var mediaSoundPlayer = '"(New-Object System.Media.SoundPlayer "' + filepath + '").Play(); exit $LASTEXITCODE"'; var player = process.platform === 'darwin' ? 'afplay' : 'aplay'; if (typeof filepath === 'string') { filepath = [filepath]; } if (! callback) { callback = function(error) { if (error) throw error; } } return process.platform === 'win32' ? childProcess.exec('powershell.exe -NoExit ' + mediaSoundPlayer, callback) : childProcess.execFile(player, filepath, callback); } module.exports = play; if (require.main && require.main.id === module.id) { play(process.argv.slice(2)); }
Fix no exit to the powershell in windows
Fix no exit to the powershell in windows
JavaScript
mit
MaxMEllon/simplayer
--- +++ @@ -12,7 +12,7 @@ * @return {Object} childProcess */ function play(filepath, callback) { - var mediaSoundPlayer = '(New-Object System.Media.SoundPlayer "' + filepath + '").Play()'; + var mediaSoundPlayer = '"(New-Object System.Media.SoundPlayer "' + filepath + '").Play(); exit $LASTEXITCODE"'; var player = process.platform === 'darwin' ? 'afplay' : 'aplay'; if (typeof filepath === 'string') {
22935d8ed0181fba9910f01d00a8c148de4be021
src/app/result/result.controller.js
src/app/result/result.controller.js
class ResultController { constructor(SocketService, GameService, toastr, _, GameFactory) { 'ngInject'; this._ = _; this.GameService = GameService; this.players = GameService.players; this.toastr = toastr; SocketService.extendedHandler = (message) => { if(message.type === 'player_create') { this.handlePlayerCreate(message.player); } else if(message.type === 'player_select') { this.handlePlayerSelect(message); } } } handlePlayerCreate(playerId) { const player = this._.find(this.GameService.players, (n) => n.id === playerId); this.toastr.info(player + ' is creating a new game.'); } handlePlayerSelect(message) { const mode_id = message.mode_id; this.GameFactory.createGame(mode_id).then((result) => { this.toastr.info('Moving to lobby'); this.GameService.storeGameData(result.data); this.GameService.retrieveAssets(); const player = this._.find(this.GameService.players, (n) => n.id === message.player); this.GameService.players = [{ name: player.name, id: player.id, score: 0, lastAnswer: null }]; this.$state.go('lobby'); }, (error) => { this.$log.log(error); }); } } export default ResultController;
class ResultController { constructor(SocketService, GameService, toastr, _, GameFactory) { 'ngInject'; this._ = _; this.GameService = GameService; this.players = GameService.players; this.toastr = toastr; SocketService.extendedHandler = (message) => { if(message.type === 'player_create') { this.handlePlayerCreate(message.player); } else if(message.type === 'player_select') { this.handlePlayerSelect(message); } } } handlePlayerCreate(playerId) { const player = this._.find(this.GameService.players, (n) => n.id === playerId); this.toastr.info(player.name + ' is creating a new game.'); } handlePlayerSelect(message) { const mode_id = message.mode_id; this.GameFactory.createGame(mode_id).then((result) => { this.toastr.info('Moving to lobby'); this.GameService.storeGameData(result.data); this.GameService.retrieveAssets(); const player = this._.find(this.GameService.players, (n) => n.id === message.player); this.GameService.players = [{ name: player.name, id: player.id, score: 0, lastAnswer: null }]; this.$state.go('lobby'); }, (error) => { this.$log.log(error); }); } } export default ResultController;
Fix toast not showing player name
Fix toast not showing player name
JavaScript
mit
hendryl/Famous-Places-Web,hendryl/Famous-Places-Web
--- +++ @@ -19,7 +19,7 @@ handlePlayerCreate(playerId) { const player = this._.find(this.GameService.players, (n) => n.id === playerId); - this.toastr.info(player + ' is creating a new game.'); + this.toastr.info(player.name + ' is creating a new game.'); } handlePlayerSelect(message) {
f273fe7f02f95698fbb139aa63b9ceccf65ba8db
lib/clifton-smtp.js
lib/clifton-smtp.js
//@Authors: Oliver Barnwell(ob6160) Harry Dalton(Hoolean) //Requires var net = require("net"); var util = require("util"); var EventEmitter = require("event").EventEmitter; //Exports module.exports = function(options) { return new clifton-smtp(options); } function clifton-smtp(options) { EventEmitter.call(this); this.server = net.createServer(function(s) { //Bind event handlers here }.bind(this)); } clifton-smtp.prototype.listen = function(port, options, callback) { this.server.listen(port, function() { }) } util.Inherits(clifton-smtp, EventEmitter);
Add cliffton-server object & some base functionality
Add cliffton-server object & some base functionality
JavaScript
mit
CliftonJS/clifton-smtp
--- +++ @@ -0,0 +1,27 @@ +//@Authors: Oliver Barnwell(ob6160) Harry Dalton(Hoolean) + +//Requires +var net = require("net"); +var util = require("util"); +var EventEmitter = require("event").EventEmitter; + +//Exports +module.exports = function(options) { + return new clifton-smtp(options); +} + + +function clifton-smtp(options) { + EventEmitter.call(this); + this.server = net.createServer(function(s) { + //Bind event handlers here + }.bind(this)); +} + +clifton-smtp.prototype.listen = function(port, options, callback) { + this.server.listen(port, function() { }) + +} + +util.Inherits(clifton-smtp, EventEmitter); +
3d94482d5e8a9be898cb707f4ceccf1c90b9c068
lib/EventService.js
lib/EventService.js
const P = require('bluebird'); const preq = require('preq'); const uuid = require('cassandra-uuid').TimeUuid; function getResourceChangeEvent(resourceUri, domain) { return { meta: { topic: 'resource_change', uri: resourceUri, id: uuid.now().toString(), dt: new Date().toISOString(), domain, }, tags: ['tilerator'], }; } class EventService { constructor(eventBusUri, domain, sources, logger) { this.eventBusUri = eventBusUri; this.domain = domain; this.sources = sources; this.logger = logger; this.emitEvents = (events) => { P.try(() => preq.post({ uri: this.eventBusUri, headers: { 'content-type': 'application/json' }, body: events, })).catch(e => this.logger.log('error/events/emit', e)).thenReturn({ status: 200 }); }; // eslint-disable-next-line max-len this.emitResourceChangeEvents = uris => this.emitEvents(uris.map(uri => getResourceChangeEvent(uri, this.domain))); this.notifyTileChanged = (z, x, y) => { this.emitResourceChangeEvents(this.sources.map(s => `//${this.domain}/${s}/${z}/${x}/${y}.png`)); }; } } module.exports = EventService;
const P = require('bluebird'); const preq = require('preq'); const uuid = require('cassandra-uuid').TimeUuid; function getResourceChangeEvent(resourceUri, domain) { return { meta: { topic: 'resource_change', uri: resourceUri, id: uuid.now().toString(), dt: new Date().toISOString(), domain, }, tags: ['tilerator'], }; } class EventService { constructor(eventBusUri, domain, sources, logger, protocol = 'https') { this.eventBusUri = eventBusUri; this.domain = domain; this.sources = sources; this.logger = logger; this.protocol = protocol; this.emitEvents = (events) => { P.try(() => preq.post({ uri: this.eventBusUri, headers: { 'content-type': 'application/json' }, body: events, })).catch(e => this.logger.log('error/events/emit', e)).thenReturn({ status: 200 }); }; // eslint-disable-next-line max-len this.emitResourceChangeEvents = uris => this.emitEvents(uris.map(uri => getResourceChangeEvent(uri, this.domain))); this.notifyTileChanged = (z, x, y) => { this.emitResourceChangeEvents(this.sources.map(s => `${this.protocol}://${this.domain}/${s}/${z}/${x}/${y}.png`)); }; } } module.exports = EventService;
Add protocol to resource_change event URIs
Add protocol to resource_change event URIs
JavaScript
apache-2.0
kartotherian/tilerator,kartotherian/tilerator,kartotherian/tilerator
--- +++ @@ -16,11 +16,12 @@ } class EventService { - constructor(eventBusUri, domain, sources, logger) { + constructor(eventBusUri, domain, sources, logger, protocol = 'https') { this.eventBusUri = eventBusUri; this.domain = domain; this.sources = sources; this.logger = logger; + this.protocol = protocol; this.emitEvents = (events) => { P.try(() => preq.post({ @@ -34,7 +35,7 @@ this.emitResourceChangeEvents = uris => this.emitEvents(uris.map(uri => getResourceChangeEvent(uri, this.domain))); this.notifyTileChanged = (z, x, y) => { - this.emitResourceChangeEvents(this.sources.map(s => `//${this.domain}/${s}/${z}/${x}/${y}.png`)); + this.emitResourceChangeEvents(this.sources.map(s => `${this.protocol}://${this.domain}/${s}/${z}/${x}/${y}.png`)); }; } }
a62988bb0fd8f72faac3ed409eac105e06bf565f
demo/index.js
demo/index.js
require('./lib/seed')() const { compose } = require('ramda') const http = require('http') const util = require('util') const { logger, methods, mount, parseJson, redirect, routes, static } = require('..') const { createCourse, fetchCourse, fetchCourses, updateCourse } = require('./api/courses') const { home } = require('./api/pages') const port = 3000 const listening = err => err ? console.error(err) : console.info(`Listening on port: ${port}`) const endpoints = routes({ '/': methods({ GET: home }), '/public/:path+': static({ root: 'demo/public' }), '/courses': methods({ GET: fetchCourses, POST: createCourse }), '/courses/:id': methods({ GET: fetchCourse, PATCH: updateCourse, PUT: updateCourse }), '/error': () => { throw new Error('this code is broken') }, '/old-courses': () => redirect('/courses') }) const app = compose(endpoints, parseJson) const opts = { errLogger: logger, logger } http.createServer(mount(app, opts)).listen(port, listening)
require('./lib/seed')() const { compose } = require('ramda') const http = require('http') const util = require('util') const { logger, methods, mount, parseJson, redirect, routes, static } = require('..') const { createCourse, fetchCourse, fetchCourses, updateCourse } = require('./api/courses') const { home } = require('./api/pages') const port = process.env.PORT || 3000 const listening = err => err ? console.error(err) : console.info(`Listening on port: ${port}`) const endpoints = routes({ '/': methods({ GET: home }), '/public/:path+': static({ root: 'demo/public' }), '/courses': methods({ GET: fetchCourses, POST: createCourse }), '/courses/:id': methods({ GET: fetchCourse, PATCH: updateCourse, PUT: updateCourse }), '/error': () => { throw new Error('this code is broken') }, '/old-courses': () => redirect('/courses') }) const app = compose(endpoints, parseJson) const opts = { errLogger: logger, logger } http.createServer(mount(app, opts)).listen(port, listening)
Use PORT env var for heroku demo
Use PORT env var for heroku demo
JavaScript
mit
articulate/paperplane
--- +++ @@ -15,7 +15,7 @@ const { home } = require('./api/pages') -const port = 3000 +const port = process.env.PORT || 3000 const listening = err => err ? console.error(err) : console.info(`Listening on port: ${port}`)
b05972b6d8695469c655f89235773cea751e7410
src/star_constructor.js
src/star_constructor.js
function chart(selection) { // Merging the various user params vars.user_vars = vistk.utils.merge(vars.user_vars, vars._user_vars); // Merging with current charts parameters set by the user in the HTML file vars = vistk.utils.merge(vars, vars.user_vars); // Create the top level element conaining the visualization if(!vars.svg) { if(vars.type !== "table") { vars.svg = d3.select(vars.container).append("svg") .attr("width", vars.width) .attr("height", vars.height) .append("g") .attr("transform", "translate(" + vars.margin.left + "," + vars.margin.top + ")"); } else { // HTML Container for table vars.svg = d3.select(vars.container).append("div") .style({height: vars.height+"px", width: vars.width+"px", overflow: "scroll"}); } }
function chart(selection) { // Merging the various user params vars.user_vars = vistk.utils.merge(vars.user_vars, vars._user_vars); // Merging with current charts parameters set by the user in the HTML file vars = vistk.utils.merge(vars, vars.user_vars); // Create the top level element conaining the visualization if(!vars.svg) { if(vars.type !== "table") { vars.svg = d3.select(vars.container).append("svg") .attr("width", vars.width) .attr("height", vars.height) .style('overflow', 'visible') .style('z-index', 0) .append("g") .attr("transform", "translate(" + vars.margin.left + "," + vars.margin.top + ")"); } else { // HTML Container for table vars.svg = d3.select(vars.container).append("div") .style({height: vars.height+"px", width: vars.width+"px", overflow: "scroll"}); } }
Allow elements within SVG to overflow
Allow elements within SVG to overflow
JavaScript
mit
cid-harvard/vis-toolkit,cid-harvard/vis-toolkit
--- +++ @@ -13,6 +13,8 @@ vars.svg = d3.select(vars.container).append("svg") .attr("width", vars.width) .attr("height", vars.height) + .style('overflow', 'visible') + .style('z-index', 0) .append("g") .attr("transform", "translate(" + vars.margin.left + "," + vars.margin.top + ")");
d31eb501d5ffaad8900e1a91e7c28b97a4c75f78
src/Ractive/prototype/shared/makeArrayMethod.js
src/Ractive/prototype/shared/makeArrayMethod.js
import { isArray } from 'utils/is'; import { getKeypath, normalise } from 'shared/keypaths'; import runloop from 'global/runloop'; import getNewIndices from 'shared/getNewIndices'; var arrayProto = Array.prototype; export default function ( methodName ) { return function ( keypath, ...args ) { var array, newIndices = [], len, promise, result; keypath = getKeypath( normalise( keypath ) ); array = this.viewmodel.get( keypath ); len = array.length; if ( !isArray( array ) ) { throw new Error( 'Called ractive.' + methodName + '(\'' + keypath + '\'), but \'' + keypath + '\' does not refer to an array' ); } newIndices = getNewIndices( array, methodName, args ); result = arrayProto[ methodName ].apply( array, args ); promise = runloop.start( this, true ).then( () => result ); if ( !!newIndices ) { this.viewmodel.smartUpdate( keypath, array, newIndices ); } else { this.viewmodel.mark( keypath ); } runloop.end(); return promise; }; }
import { isArray } from 'utils/is'; import { getKeypath, normalise } from 'shared/keypaths'; import runloop from 'global/runloop'; import getNewIndices from 'shared/getNewIndices'; var arrayProto = Array.prototype; export default function ( methodName ) { return function ( keypath, ...args ) { var array, newIndices = [], len, promise, result; keypath = getKeypath( normalise( keypath ) ); array = this.viewmodel.get( keypath ); len = array.length; if ( !isArray( array ) ) { throw new Error( 'Called ractive.' + methodName + '(\'' + keypath.str + '\'), but \'' + keypath.str + '\' does not refer to an array' ); } newIndices = getNewIndices( array, methodName, args ); result = arrayProto[ methodName ].apply( array, args ); promise = runloop.start( this, true ).then( () => result ); if ( !!newIndices ) { this.viewmodel.smartUpdate( keypath, array, newIndices ); } else { this.viewmodel.mark( keypath ); } runloop.end(); return promise; }; }
Use keypath.str property to prevent coercion erros
Use keypath.str property to prevent coercion erros
JavaScript
mit
thomsbg/ractive,thomsbg/ractive,Rich-Harris/ractive,ISNIT0/ractive,dyx/ractive,heavyk/ractive,marcalexiei/ractive,dyx/ractive,aliprogrammer69/ractive,aliprogrammer69/ractive,JonDum/ractive,pingjiang/ractive,heavyk/ractive,Rich-Harris/ractive,squaredup/ractive,cgvarela/ractive,JonDum/ractive,JonDum/ractive,ractivejs/ractive,squaredup/ractive,ndimas/ractive,cgvarela/ractive,magicdawn/ractive,magicdawn/ractive,dyx/ractive,ISNIT0/ractive,marcalexiei/ractive,cgvarela/ractive,heavyk/ractive,pingjiang/ractive,squaredup/ractive,magicdawn/ractive,ISNIT0/ractive,ndimas/ractive,thomsbg/ractive,ractivejs/ractive,marcalexiei/ractive,aliprogrammer69/ractive,ndimas/ractive,ractivejs/ractive,pingjiang/ractive,Rich-Harris/ractive
--- +++ @@ -15,7 +15,7 @@ len = array.length; if ( !isArray( array ) ) { - throw new Error( 'Called ractive.' + methodName + '(\'' + keypath + '\'), but \'' + keypath + '\' does not refer to an array' ); + throw new Error( 'Called ractive.' + methodName + '(\'' + keypath.str + '\'), but \'' + keypath.str + '\' does not refer to an array' ); } newIndices = getNewIndices( array, methodName, args );
e49c8ea16ed78ed1246905f4139aac9674122b83
src/components/toolbar/models/SelectStateModel.js
src/components/toolbar/models/SelectStateModel.js
import SelectStateItemsCollection from '../collections/SelectStateItemsCollection'; import meta from '../meta'; export default Backbone.Model.extend({ initialize() { const items = this.get('items'); const itemsCollection = new SelectStateItemsCollection(items); this.listenTo(itemsCollection, 'select:one', model => this.set('iconClass', model.get('iconClass'))); this.set('items', itemsCollection); const firstNotHeadlineModel = itemsCollection.find(model => model.get('type') !== meta.toolbarItemType.HEADLINE); itemsCollection.select(firstNotHeadlineModel); this.__addDropdownClass(); }, __addDropdownClass() { const dropdownClass = this.get('dropdownClass'); let SelectStateDropdownClass = 'toolbar-panel_container__select-state'; dropdownClass && (SelectStateDropdownClass = `${dropdownClass} ${SelectStateDropdownClass}`); this.set('dropdownClass', SelectStateDropdownClass); } });
import SelectStateItemsCollection from '../collections/SelectStateItemsCollection'; import meta from '../meta'; export default Backbone.Model.extend({ initialize() { const items = this.get('items'); const itemsCollection = new SelectStateItemsCollection(items); this.listenTo(itemsCollection, 'select:one', model => this.set('iconClass', model.get('iconClass'))); this.set('items', itemsCollection); this.__selectDefaultModel(itemsCollection); this.__addDropdownClass(); }, __addDropdownClass() { const dropdownClass = this.get('dropdownClass'); let SelectStateDropdownClass = 'toolbar-panel_container__select-state'; dropdownClass && (SelectStateDropdownClass = `${dropdownClass} ${SelectStateDropdownClass}`); this.set('dropdownClass', SelectStateDropdownClass); }, __selectDefaultModel(itemsCollection) { let firstNotHeadlineModel = null; firstNotHeadlineModel = itemsCollection.find(model => model.get('type') !== meta.toolbarItemType.HEADLINE && model.get('default')); if (!firstNotHeadlineModel) { firstNotHeadlineModel = itemsCollection.find(model => model.get('type') !== meta.toolbarItemType.HEADLINE); } itemsCollection.select(firstNotHeadlineModel); } });
Add default selected state to toolbar selections.
Add default selected state to toolbar selections.
JavaScript
mit
comindware/core-ui,comindware/core-ui,comindware/core-ui,comindware/core-ui
--- +++ @@ -8,9 +8,7 @@ this.listenTo(itemsCollection, 'select:one', model => this.set('iconClass', model.get('iconClass'))); this.set('items', itemsCollection); - const firstNotHeadlineModel = itemsCollection.find(model => model.get('type') !== meta.toolbarItemType.HEADLINE); - itemsCollection.select(firstNotHeadlineModel); - + this.__selectDefaultModel(itemsCollection); this.__addDropdownClass(); }, @@ -19,5 +17,17 @@ let SelectStateDropdownClass = 'toolbar-panel_container__select-state'; dropdownClass && (SelectStateDropdownClass = `${dropdownClass} ${SelectStateDropdownClass}`); this.set('dropdownClass', SelectStateDropdownClass); + }, + + __selectDefaultModel(itemsCollection) { + let firstNotHeadlineModel = null; + + firstNotHeadlineModel = itemsCollection.find(model => model.get('type') !== meta.toolbarItemType.HEADLINE && model.get('default')); + + if (!firstNotHeadlineModel) { + firstNotHeadlineModel = itemsCollection.find(model => model.get('type') !== meta.toolbarItemType.HEADLINE); + } + + itemsCollection.select(firstNotHeadlineModel); } });
11290de91c78b3e5c98c96723b8bd4935be2b2a4
ghost/admin/app/session-stores/application.js
ghost/admin/app/session-stores/application.js
import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive'; export default AdaptiveStore.extend({ localStorageKey: 'ghost:session', cookieName: 'ghost:session' });
import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive'; import ghostPaths from 'ghost/utils/ghost-paths'; const paths = ghostPaths(); const keyName = `ghost${(paths.subdir.indexOf('/') === 0 ? `-${paths.subdir.substr(1)}` : ``) }:session`; export default AdaptiveStore.extend({ localStorageKey: keyName, cookieName: keyName });
Set localStorage key based on subdir
Set localStorage key based on subdir closes #6326
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
--- +++ @@ -1,6 +1,10 @@ import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive'; +import ghostPaths from 'ghost/utils/ghost-paths'; + +const paths = ghostPaths(); +const keyName = `ghost${(paths.subdir.indexOf('/') === 0 ? `-${paths.subdir.substr(1)}` : ``) }:session`; export default AdaptiveStore.extend({ - localStorageKey: 'ghost:session', - cookieName: 'ghost:session' + localStorageKey: keyName, + cookieName: keyName });
83c643c19035a44d74b8aeccfe279dc2c7ce3367
lib/config/index.js
lib/config/index.js
'use strict'; const readConfig = require('restore-server-config'); // singleton let config; /** * Loads the configuration and stores it in the config singleton. * @param {string} baseDir Directory which contains the folder cfg with the config files. * @param [Logger] logger */ function load(baseDir, logger) { return (cb) => { readConfig(baseDir, logger, (cfg) => { config = cfg; cb(null, cfg); }); }; } /** * Get config from singleton. * If singelton is undefined load id from current working directory. * @param [Logger] logger * @return {Object} nconf configuration object */ module.exports.get = function* get(logger) { if (config) { return config; } yield load(process.cwd(), logger); return config; }; module.exports.load = load;
'use strict'; const readConfig = require('restore-server-config'); // singleton let config; /** * Loads the configuration and stores it in the config singleton. * @param {string} baseDir Directory which contains the folder cfg with the config files. * @param [Logger] logger */ function load(baseDir, logger) { return (cb) => { readConfig(baseDir, logger, (err, cfg) => { if (err) { cb(err, cfg); } else { config = cfg; cb(null, cfg); } }); }; } /** * Get config from singleton. * If singelton is undefined load id from current working directory. * @param [Logger] logger * @return {Object} nconf configuration object */ module.exports.get = function* get(logger) { if (config) { return config; } yield load(process.cwd(), logger); return config; }; module.exports.load = load;
Replace config load callback wrapper
Replace config load callback wrapper
JavaScript
mit
restorecommerce/chassis-srv,restorecommerce/chassis-srv
--- +++ @@ -12,9 +12,13 @@ */ function load(baseDir, logger) { return (cb) => { - readConfig(baseDir, logger, (cfg) => { - config = cfg; - cb(null, cfg); + readConfig(baseDir, logger, (err, cfg) => { + if (err) { + cb(err, cfg); + } else { + config = cfg; + cb(null, cfg); + } }); }; }
bc85619117de88c6248f7652bb82a9396f35adc9
app/assets/javascripts/web.js
app/assets/javascripts/web.js
//= require jquery //= require leaflet //= require leaflet-ajax //= require leaflet-routing-machine //= require osmtogeojson //= require maps $("#agua").change(function () { if (this.checked) { showWindsLayer(); } else { hideWindsLayer(); } }) $("#lluvia").change(function () { if (this.checked) { showWeatherLayer(); } else { hideWeatherLayer(); } }) $("#bosque").change(function () { if (this.checked) { showForestLayer(); } else { hideForestLayer(); } })
//= require jquery //= require leaflet //= require leaflet-ajax //= require leaflet-routing-machine //= require osmtogeojson //= require maps $( document ).ready(function() { $("#agua").change(function () { if (this.checked) { showWindsLayer(); } else { hideWindsLayer(); } }) $("#lluvia").change(function () { if (this.checked) { showWeatherLayer(); } else { hideWeatherLayer(); } }) $("#bosque").change(function () { if (this.checked) { showForestLayer(); } else { hideForestLayer(); } }) }
Add checkbox event listeners after document load.
Add checkbox event listeners after document load.
JavaScript
mit
ForestGuardian/ForestGuardianBackend,ForestGuardian/ForestGuardianBackend,ForestGuardian/ForestGuardianBackend,ForestGuardian/ForestGuardianBackend,ForestGuardian/ForestGuardianBackend
--- +++ @@ -5,27 +5,30 @@ //= require osmtogeojson //= require maps +$( document ).ready(function() { -$("#agua").change(function () { - if (this.checked) { - showWindsLayer(); - } else { - hideWindsLayer(); - } -}) + $("#agua").change(function () { + if (this.checked) { + showWindsLayer(); + } else { + hideWindsLayer(); + } + }) -$("#lluvia").change(function () { - if (this.checked) { - showWeatherLayer(); - } else { - hideWeatherLayer(); - } -}) + $("#lluvia").change(function () { + if (this.checked) { + showWeatherLayer(); + } else { + hideWeatherLayer(); + } + }) -$("#bosque").change(function () { - if (this.checked) { - showForestLayer(); - } else { - hideForestLayer(); - } -}) + $("#bosque").change(function () { + if (this.checked) { + showForestLayer(); + } else { + hideForestLayer(); + } + }) + +}
8e8f489721dead1c9cecc9cc4934865633bea258
config.js
config.js
/* * Copyright (c) 2014 Giovanni Capuano <webmaster@giovannicapuano.net> * Released under the MIT License * http://opensource.org/licenses/MIT */ var config = {}; // Images configuration config.images = { path: '../images', url : '/images' }; // Set the following line to false if you have a webserver that serves you static resources or you have just put your images folder in public/. // Your images will be available to /dirname/ (where dirname is the name of your images folder). config.serve = true; // The image extensions to show config.exts = [ '.jpg', '.jpeg', '.bmp', '.png', '.gif' ]; // Sort images and folders config.sort = { mode: 'DESC', // ASC DESC by : 'lastModify' // name lastModify }; // Image served by Vasilij will be put in browser cache for 30 days config.maxAge = '2592000'; // Thumbnails configuration config.thumbs = { path : '../thumbs', url : '/thumbs', width : 500, cpu : 8 }; module.exports = config;
/* * Copyright (c) 2014 Giovanni Capuano <webmaster@giovannicapuano.net> * Released under the MIT License * http://opensource.org/licenses/MIT */ var config = {}; // Images configuration config.images = { path: '../images', url : '/images' }; // Set the following line to false if you have a webserver that serves you static resources or you have just put your images folder in public/. // Your images will be available to /dirname/ (where dirname is the name of your images folder). config.serve = true; // The image extensions to show config.exts = [ '.jpg', '.jpeg', '.bmp', '.png', '.gif' ]; // Sort images and folders config.sort = { mode: 'DESC', // ASC DESC by : 'lastModify' // name lastModify }; // Image served by Vasilij will be put in browser cache for 30 days config.maxAge = '2592000'; // Thumbnails configuration config.thumbs = { path : '../thumbs', url : '/thumbs', width : 250, cpu : 8 }; module.exports = config;
Set default thumbs width to 250
Set default thumbs width to 250
JavaScript
mit
RoxasShadow/Vasilij
--- +++ @@ -32,7 +32,7 @@ config.thumbs = { path : '../thumbs', url : '/thumbs', - width : 500, + width : 250, cpu : 8 };
685e7f437e4155c80814ca81f246a3571f85289f
spec/components/link.js
spec/components/link.js
import React, { PureComponent } from 'react'; import Link from '../../components/link'; class LinkTest extends PureComponent { handleClick = () => { console.log('Clicked on a link'); }; render () { return ( <article> <header> <h1>Links</h1> </header> <div className="component-spec"> <div className="preview"> <p><Link url="#">I'm a link</Link></p> <p><Link onClick={this.handleClick}>I'm a link</Link></p> </div> </div> </article> ); } } export default LinkTest;
import React, { PureComponent } from 'react'; import { Link, Heading1, Section } from '../../components/'; import { BrowserRouter as Router, Link as ReactRouterLink } from 'react-router-dom'; Link.use(ReactRouterLink); class LinkTest extends PureComponent { handleClick = () => { console.log('Clicked on a link'); }; render () { return ( <Router> <article> <Section color="neutral" dark> <Heading1>Links</Heading1> </Section> <div className="component-spec"> <div className="preview"> <p><Link to="http://www.facebook.com" target="_blank">I'm an external link</Link></p> <p><Link to="#" onClick={this.handleClick}>I'm an internal link</Link></p> </div> </div> </article> </Router> ); } } export default LinkTest;
Use the Link component from react-router in combination with our custom styled Link
Use the Link component from react-router in combination with our custom styled Link
JavaScript
mit
teamleadercrm/teamleader-ui
--- +++ @@ -1,5 +1,8 @@ import React, { PureComponent } from 'react'; -import Link from '../../components/link'; +import { Link, Heading1, Section } from '../../components/'; +import { BrowserRouter as Router, Link as ReactRouterLink } from 'react-router-dom'; + +Link.use(ReactRouterLink); class LinkTest extends PureComponent { handleClick = () => { @@ -8,17 +11,19 @@ render () { return ( - <article> - <header> - <h1>Links</h1> - </header> - <div className="component-spec"> - <div className="preview"> - <p><Link url="#">I'm a link</Link></p> - <p><Link onClick={this.handleClick}>I'm a link</Link></p> + <Router> + <article> + <Section color="neutral" dark> + <Heading1>Links</Heading1> + </Section> + <div className="component-spec"> + <div className="preview"> + <p><Link to="http://www.facebook.com" target="_blank">I'm an external link</Link></p> + <p><Link to="#" onClick={this.handleClick}>I'm an internal link</Link></p> + </div> </div> - </div> - </article> + </article> + </Router> ); } }
6bbed196b8b30180936e38e17bfddd3617752d31
__tests__/components/Thumbnail-test.js
__tests__/components/Thumbnail-test.js
import React from 'react'; import shallowRender from '../utils/shallowRender'; import Thumbnail from '../../src/components/Thumbnail'; jest.unmock('../../src/components/Thumbnail'); describe('Thumbnail Component', () => { it('should be a div HTML element', () => { const output = shallowRender(<Thumbnail />); expect(output.type).toBe('div'); }); it('should have a cssName of wrr-thumbnail', () => { const output = shallowRender(<Thumbnail />); expect(output.props.className).toBe('wrr-thumbnail'); }); });
import React from 'react'; import shallowRender from '../utils/shallowRender'; import Thumbnail from '../../src/components/Thumbnail'; jest.unmock('../../src/components/Thumbnail'); describe('Thumbnail Component', () => { it('should be a div HTML element', () => { const output = shallowRender(<Thumbnail />); expect(output.type).toBe('div'); }); it('should have a cssName of wrr-thumbnail', () => { const output = shallowRender(<Thumbnail />); expect(output.props.className).toBe('wrr-thumbnail'); }); it('should have a default color #000', () => { const expected = { color: '#000' }; const output = shallowRender(<Thumbnail />); expect(output.props.style).toEqual(expected); }); it('should properly set color to #fff when passed', () => { const expected = { color: '#fff' }; const output = shallowRender(<Thumbnail color={expected.color} />); expect(output.props.style).toEqual(expected); }); });
Update tests for Thumbnail component
Update tests for Thumbnail component
JavaScript
mit
LittleFurryBastards/webpack-react-redux,LittleFurryBastards/webpack-babel-react,LittleFurryBastards/webpack-babel-react,LittleFurryBastards/webpack-react-redux
--- +++ @@ -16,4 +16,18 @@ expect(output.props.className).toBe('wrr-thumbnail'); }); + + it('should have a default color #000', () => { + const expected = { color: '#000' }; + const output = shallowRender(<Thumbnail />); + + expect(output.props.style).toEqual(expected); + }); + + it('should properly set color to #fff when passed', () => { + const expected = { color: '#fff' }; + const output = shallowRender(<Thumbnail color={expected.color} />); + + expect(output.props.style).toEqual(expected); + }); });
d23a0c33a1db143c2b821dd307096d466db3c7af
src/frontend/lite/src/walletPath.js
src/frontend/lite/src/walletPath.js
import { app } from "electron"; const isDevelopment = process.env.NODE_ENV !== "production"; import os from "os"; import path from "path"; let walletPath = ""; if (process.type !== "renderer") { if (os.platform() === "linux") { walletPath = path.join( app.getPath("home"), isDevelopment ? ".gulden_dev" : ".gulden" ); } else { walletPath = app.getPath("userData"); if (isDevelopment) walletPath = walletPath + "_dev"; } } export default walletPath;
import { app } from "electron"; const isDevelopment = process.env.NODE_ENV !== "production"; import os from "os"; import path from "path"; let walletPath = ""; if (process.type !== "renderer") { if (os.platform() === "linux") { walletPath = path.join( app.getPath("home"), isDevelopment ? ".gulden_lite_dev" : ".gulden_lite" ); } else { walletPath = app.getPath("userData"); if (isDevelopment) walletPath = walletPath + "_dev"; } } export default walletPath;
Change wallet path for lite wallet
ELECTRON: Change wallet path for lite wallet
JavaScript
mit
nlgcoin/guldencoin-official,nlgcoin/guldencoin-official,nlgcoin/guldencoin-official,nlgcoin/guldencoin-official,nlgcoin/guldencoin-official,nlgcoin/guldencoin-official
--- +++ @@ -10,7 +10,7 @@ if (os.platform() === "linux") { walletPath = path.join( app.getPath("home"), - isDevelopment ? ".gulden_dev" : ".gulden" + isDevelopment ? ".gulden_lite_dev" : ".gulden_lite" ); } else { walletPath = app.getPath("userData");
2014d17c9c301508b0747327fc6a2a7b8dd538a3
src/main/web/florence/js/functions/_reset.js
src/main/web/florence/js/functions/_reset.js
function resetPage() { // Prevent default behaviour of all form submits throught Florence $(document).on('submit', 'form', function(e) { e.preventDefault(); console.log('Form submit stopped on: ', e); }); // Fix for modal form submits not being detected $(document).on('click', 'button', function() { var $closestForm = $(this).closest('form'); $closestForm.submit(function(e) { e.preventDefault(); }); }); // Stop anchors doing default behaviour // $(document).on('click', 'a', function(e) { // e.preventDefault(); // console.log('Anchor click stopped on: ', e); // }); // $(document).on('click', 'form', function(e) { // e.preventDefault(); // console.log('Form clicked'); // }); // $(document).on('click', 'button', function (e) { // e.preventDefault(); // console.log(e); // }); // $(document).on('submit', '#cancel-form', function(e) { // e.preventDefault(); // console.log(e); // }); }
function resetPage() { // Prevent default behaviour of all form submits throught Florence $(document).on('submit', 'form', function(e) { e.preventDefault(); }); // Fix for modal form submits not being detected $(document).on('click', 'button', function() { var $closestForm = $(this).closest('form'); $closestForm.submit(function(e) { e.preventDefault(); }); }); // Stop anchors doing default behaviour // $(document).on('click', 'a', function(e) { // e.preventDefault(); // console.log('Anchor click stopped on: ', e); // }); // $(document).on('click', 'form', function(e) { // e.preventDefault(); // console.log('Form clicked'); // }); // $(document).on('click', 'button', function (e) { // e.preventDefault(); // console.log(e); // }); // $(document).on('submit', '#cancel-form', function(e) { // e.preventDefault(); // console.log(e); // }); }
Remove form submit prevention logging
Remove form submit prevention logging
JavaScript
mit
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
--- +++ @@ -2,7 +2,6 @@ // Prevent default behaviour of all form submits throught Florence $(document).on('submit', 'form', function(e) { e.preventDefault(); - console.log('Form submit stopped on: ', e); }); // Fix for modal form submits not being detected
dc14852989ce28312ea93b1e2210f70f9928ee79
app/navigation/renderScene.js
app/navigation/renderScene.js
/* @flow */ import React from "react-native"; import routeMapper from "../routes/routeMapper"; import Colors from "../../Colors.json"; const { NavigationCard, StyleSheet, View } = React; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: Colors.lightGrey }, normal: { marginTop: 56 } }); const renderScene = function(navState: Object, onNavigation: Function): Function { return props => { const route = navState.get(navState.index); const { component: RouteComponent, passProps } = routeMapper(route); return ( <NavigationCard {...props}> <View style={[ styles.container, route.fullscreen ? null : styles.normal ]}> <RouteComponent {...passProps} style={styles.container} onNavigation={onNavigation} /> </View> </NavigationCard> ); }; }; export default renderScene;
/* @flow */ import React from "react-native"; import routeMapper from "../routes/routeMapper"; import Colors from "../../Colors.json"; const { NavigationCard, StyleSheet, View } = React; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: Colors.lightGrey }, normal: { marginTop: 56 } }); const renderScene = function(navState: Object, onNavigation: Function): Function { return props => { const route = props.sceneRecord.get("route"); // eslint-disable-line react/prop-types const { component: RouteComponent, passProps } = routeMapper(route); return ( <NavigationCard {...props}> <View style={[ styles.container, route.fullscreen ? null : styles.normal ]}> <RouteComponent {...passProps} style={styles.container} onNavigation={onNavigation} /> </View> </NavigationCard> ); }; }; export default renderScene;
Use sceneRecord.get to get current route
Use sceneRecord.get to get current route
JavaScript
unknown
scrollback/io.scrollback.neighborhoods,scrollback/io.scrollback.neighborhoods,wesley1001/io.scrollback.neighborhoods,wesley1001/io.scrollback.neighborhoods
--- +++ @@ -23,7 +23,8 @@ const renderScene = function(navState: Object, onNavigation: Function): Function { return props => { - const route = navState.get(navState.index); + const route = props.sceneRecord.get("route"); // eslint-disable-line react/prop-types + const { component: RouteComponent, passProps
d84468b7631cf9c08d1f9d185f59f36c79d16d68
app/static/js/lib/reserves.js
app/static/js/lib/reserves.js
import { fromPairs, isEmpty, head, last, max, mapObjIndexed, sortBy, toPairs, } from 'ramda' export function calculateReserves (cumulative, reserveData, mineral, column, series) { const reserves = getReserves(reserveData, mineral) if (!reserves) { // console.debug('No reserves!') return {} } const [reserveYear, reserveAmount] = last(sortBy(head, toPairs(reserves))) const cumulativeOnReserveYear = cumulative.data[reserveYear][column] return mapObjIndexed((row, year) => { return fromPairs([ ['Year', year], [series, max(1, reserveAmount - (row[column] - cumulativeOnReserveYear))] ]) }, cumulative.data) } export function getReserves (reserves, mineral) { return reserves.data && reserves.data[mineral] }
import { fromPairs, isEmpty, head, last, max, mapObjIndexed, sortBy, toPairs, } from 'ramda' export function calculateReserves (cumulative, reserveData, mineral, column, series) { const reserves = getReserves(reserveData, mineral) if (!reserves) { // console.debug('No reserves!') return {} } const [reserveYear, reserveAmount] = last(sortBy(head, toPairs(reserves))) const cumulativeOnReserveYear = cumulative.data[reserveYear][column] return mapObjIndexed((row, year) => { return fromPairs([ ['Year', year], [series, max(0, reserveAmount - (row[column] - cumulativeOnReserveYear))] ]) }, cumulative.data) } export function getReserves (reserves, mineral) { return reserves.data && reserves.data[mineral] }
Change calculateReserves minimum value to zero
Change calculateReserves minimum value to zero
JavaScript
mit
peterhil/ninhursag,peterhil/ninhursag,peterhil/ninhursag,peterhil/ninhursag
--- +++ @@ -23,7 +23,7 @@ return mapObjIndexed((row, year) => { return fromPairs([ ['Year', year], - [series, max(1, reserveAmount - (row[column] - cumulativeOnReserveYear))] + [series, max(0, reserveAmount - (row[column] - cumulativeOnReserveYear))] ]) }, cumulative.data) }
722184133a934315f1bd261bd4a16c54d5607be7
app/themes/base/containers.js
app/themes/base/containers.js
export default ({ borders, colors, radii, space }) => { const defaultStyles = { mx: 'auto', bg: colors.white, width: ['100%', '85%'], mb: `${space[6]}px`, }; const large = { ...defaultStyles, maxWidth: '1280px', }; const medium = { ...defaultStyles, maxWidth: '840px', }; const small = { ...defaultStyles, maxWidth: '600px', }; const bordered = { borderLeft: ['none', borders.default], borderRight: ['none', borders.default], borderTop: borders.default, borderBottom: borders.default, borderRadius: ['none', radii.default], }; return { large, largeBordered: { ...large, ...bordered, }, medium, mediumBordered: { ...medium, ...bordered, }, small, smallBordered: { ...small, ...bordered, }, }; };
export default ({ borders, colors, radii, space }) => { const defaultStyles = { mx: 'auto', bg: colors.white, width: ['100%', '85%'], mb: `${space[6]}px`, position: 'relative', }; const large = { ...defaultStyles, maxWidth: '1280px', }; const medium = { ...defaultStyles, maxWidth: '840px', }; const small = { ...defaultStyles, maxWidth: '600px', }; const bordered = { borderLeft: ['none', borders.default], borderRight: ['none', borders.default], borderTop: borders.default, borderBottom: borders.default, borderRadius: ['none', radii.default], }; return { large, largeBordered: { ...large, ...bordered, }, medium, mediumBordered: { ...medium, ...bordered, }, small, smallBordered: { ...small, ...bordered, }, }; };
Add relative position to default container styles
[WEB-1338] Add relative position to default container styles
JavaScript
bsd-2-clause
tidepool-org/blip,tidepool-org/blip,tidepool-org/blip
--- +++ @@ -4,6 +4,7 @@ bg: colors.white, width: ['100%', '85%'], mb: `${space[6]}px`, + position: 'relative', }; const large = {
940f3dce1f1aa7c885e66705c42df93810a308dd
lib/ticket-types.js
lib/ticket-types.js
'use strict'; function ticketTypes (args, callback) { var ticketTypes = [ {name: 'ninja', title: 'Ninja', tooltip: 'Select Ninja to create tickets for attendees under 13 or over 13.'}, {name: 'parent-guardian', title: 'Parent/Guardian', tooltip: 'Select Parent/Guardian to create tickets for parents/guardians of the attendees.'}, {name: 'mentor', title: 'Mentor', tooltip: 'Select Mentor to create tickets for Mentors.'}, {name: 'other', title: 'Other', tooltip: 'Select Other to create tickets for unlisted types e.g. laptops.'} ]; setImmediate(function () { return callback(null, ticketTypes); }); } module.exports = ticketTypes;
'use strict'; function ticketTypes (args, callback) { /* ninja is defined as a key in many areas, keep it for backward compatibility */ var ticketTypes = [ {name: 'ninja', title: 'Youth', tooltip: 'Select Youth to create tickets for attendees under 18.'}, {name: 'parent-guardian', title: 'Parent/Guardian', tooltip: 'Select Parent/Guardian to create tickets for parents/guardians of the attendees.'}, {name: 'mentor', title: 'Mentor', tooltip: 'Select Mentor to create tickets for Mentors.'}, {name: 'other', title: 'Other', tooltip: 'Select Other to create tickets for unlisted types e.g. laptops.'} ]; setImmediate(function () { return callback(null, ticketTypes); }); } module.exports = ticketTypes;
Rename ninja to youth to reduce confusion
Rename ninja to youth to reduce confusion
JavaScript
mit
CoderDojo/cp-events-service,CoderDojo/cp-events-service
--- +++ @@ -1,8 +1,9 @@ 'use strict'; function ticketTypes (args, callback) { + /* ninja is defined as a key in many areas, keep it for backward compatibility */ var ticketTypes = [ - {name: 'ninja', title: 'Ninja', tooltip: 'Select Ninja to create tickets for attendees under 13 or over 13.'}, + {name: 'ninja', title: 'Youth', tooltip: 'Select Youth to create tickets for attendees under 18.'}, {name: 'parent-guardian', title: 'Parent/Guardian', tooltip: 'Select Parent/Guardian to create tickets for parents/guardians of the attendees.'}, {name: 'mentor', title: 'Mentor', tooltip: 'Select Mentor to create tickets for Mentors.'}, {name: 'other', title: 'Other', tooltip: 'Select Other to create tickets for unlisted types e.g. laptops.'}
2984f42931b1030093f4329b51fc202063001eda
src/app/index.module.js
src/app/index.module.js
/* global malarkey:false, moment:false */ import { config } from './index.config'; import { routerConfig } from './index.route'; import { themeConfig } from './index.theme'; import { runBlock } from './index.run'; import { MainController } from './main/main.controller'; import { DetailsController } from './details/details.controller'; import { RetractableSearchbarDirective } from '../app/components/retractableSearchbar/retractableSearchbar.directive'; angular.module('generic-search-flow', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ngResource', 'ngRoute', 'ngMaterial', 'toastr', 'infinite-scroll']) .constant('malarkey', malarkey) .constant('moment', moment) .config(config) .config(routerConfig) .config(themeConfig) .run(runBlock) .controller('MainController', MainController) .controller('DetailsController', DetailsController) .directive('retractableSearchbar', RetractableSearchbarDirective)
/* global moment:false */ import { config } from './index.config'; import { routerConfig } from './index.route'; import { themeConfig } from './index.theme'; import { runBlock } from './index.run'; import { MainController } from './main/main.controller'; import { DetailsController } from './details/details.controller'; import { RetractableSearchbarDirective } from '../app/components/retractableSearchbar/retractableSearchbar.directive'; angular.module('generic-search-flow', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ngResource', 'ngRoute', 'ngMaterial', 'toastr']) .constant('moment', moment) .config(config) .config(routerConfig) .config(themeConfig) .run(runBlock) .controller('MainController', MainController) .controller('DetailsController', DetailsController) .directive('retractableSearchbar', RetractableSearchbarDirective)
FIX - Removed unused dependencies
FIX - Removed unused dependencies
JavaScript
mit
lucasdesenna/generic-search-flow,lucasdesenna/generic-search-flow
--- +++ @@ -1,4 +1,4 @@ -/* global malarkey:false, moment:false */ +/* global moment:false */ import { config } from './index.config'; import { routerConfig } from './index.route'; @@ -8,8 +8,7 @@ import { DetailsController } from './details/details.controller'; import { RetractableSearchbarDirective } from '../app/components/retractableSearchbar/retractableSearchbar.directive'; -angular.module('generic-search-flow', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ngResource', 'ngRoute', 'ngMaterial', 'toastr', 'infinite-scroll']) - .constant('malarkey', malarkey) +angular.module('generic-search-flow', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ngResource', 'ngRoute', 'ngMaterial', 'toastr']) .constant('moment', moment) .config(config) .config(routerConfig)
ad0ab578bfaa2f16ec7235f6943928859f65f01b
src/Store.js
src/Store.js
import AsyncStorage from '@react-native-community/async-storage'; import { persistStore, persistReducer } from 'redux-persist'; import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { createReactNavigationReduxMiddleware } from 'react-navigation-redux-helpers'; import reducers from './reducers'; // Create middleware and connect const appNavigatorMiddleware = createReactNavigationReduxMiddleware(state => state.nav, 'root'); const persistConfig = { keyPrefix: '', key: 'root', storage: AsyncStorage, blacklist: ['nav'], }; const persistedReducer = persistReducer(persistConfig, reducers); const store = createStore(persistedReducer, {}, applyMiddleware(thunk, appNavigatorMiddleware)); const persistedStore = persistStore(store); export { store, persistedStore };
import AsyncStorage from '@react-native-community/async-storage'; import { persistStore, persistReducer } from 'redux-persist'; import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { createReactNavigationReduxMiddleware } from 'react-navigation-redux-helpers'; import reducers from './reducers'; // Create middleware and connect const appNavigatorMiddleware = createReactNavigationReduxMiddleware(state => state.nav, 'root'); const persistConfig = { keyPrefix: '', key: 'root', storage: AsyncStorage, blacklist: ['nav', 'pages'], }; const persistedReducer = persistReducer(persistConfig, reducers); const store = createStore(persistedReducer, {}, applyMiddleware(thunk, appNavigatorMiddleware)); const persistedStore = persistStore(store); export { store, persistedStore };
Add blacklist pages store state
Add blacklist pages store state
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
--- +++ @@ -12,7 +12,7 @@ keyPrefix: '', key: 'root', storage: AsyncStorage, - blacklist: ['nav'], + blacklist: ['nav', 'pages'], }; const persistedReducer = persistReducer(persistConfig, reducers);
4ba2b6b0e60bbd7d101f61e228ec4191c608e288
src/index.js
src/index.js
'use strict'; /** * Make a web element pannable. */ module.exports = { init: (elem, containerElem) => { var container = containerElem ? containerElem : elem.parentElement; elem.addEventListener('mousemove', (e) => { e.preventDefault(); if (e && e.which === 1) { if (e.movementX !== 0) { container.scrollLeft -= e.movementX; } if (e.movementY !== 0) { container.scrollTop -= e.movementY; } } }); return elem; } };
'use strict'; /** * Limit execution of onReady function * to once over the given wait time. * * @function _throttle * @private * * @param {function} onReady * @param {function} onStandby * @param {number} wait * * @returns {function} */ const _throttle = (onReady, onStandby, wait) => { let time = Date.now(); return (e) => { onStandby(e); if ((time + wait - Date.now()) < 0) { onReady(e); time = Date.now(); } }; }; /** * Initialize element to be pannable * within the given contanerElement. * * @function init * @public * * @param {Object} elem * @param {Object} containerElem * * @returns {Object} */ const init = (elem, containerElem) => { const container = containerElem ? containerElem : elem.parentElement; let scrollLeft = 0; let scrollTop = 0; const handleMove = _throttle( (e) => { e.preventDefault(); requestAnimationFrame(() => { if (e && e.which === 1) { if (e.movementX !== 0) { container.scrollLeft -= scrollLeft; } if (e.movementY !== 0) { container.scrollTop -= scrollTop; } scrollLeft = 0; scrollTop = 0; } }); }, (e) => { if (e && e.which === 1) { if (e.movementX !== 0) { scrollLeft += e.movementX; } if (e.movementY !== 0) { scrollTop += e.movementY; } } }, 10 ); elem.addEventListener( 'mousemove', handleMove ); return elem; }; /** * Make a web element pannable. */ module.exports = { init };
Implement throttling on event listener
Implement throttling on event listener
JavaScript
mit
selcher/panner,selcher/panner
--- +++ @@ -1,29 +1,97 @@ 'use strict'; + +/** + * Limit execution of onReady function + * to once over the given wait time. + * + * @function _throttle + * @private + * + * @param {function} onReady + * @param {function} onStandby + * @param {number} wait + * + * @returns {function} + */ +const _throttle = (onReady, onStandby, wait) => { + let time = Date.now(); + + return (e) => { + onStandby(e); + + if ((time + wait - Date.now()) < 0) { + onReady(e); + time = Date.now(); + } + }; +}; + +/** + * Initialize element to be pannable + * within the given contanerElement. + * + * @function init + * @public + * + * @param {Object} elem + * @param {Object} containerElem + * + * @returns {Object} + */ +const init = (elem, containerElem) => { + const container = containerElem ? + containerElem : elem.parentElement; + + let scrollLeft = 0; + let scrollTop = 0; + + const handleMove = _throttle( + (e) => { + e.preventDefault(); + + requestAnimationFrame(() => { + if (e && e.which === 1) { + + if (e.movementX !== 0) { + container.scrollLeft -= scrollLeft; + } + + if (e.movementY !== 0) { + container.scrollTop -= scrollTop; + } + + scrollLeft = 0; + scrollTop = 0; + } + }); + }, + (e) => { + if (e && e.which === 1) { + + if (e.movementX !== 0) { + scrollLeft += e.movementX; + } + + if (e.movementY !== 0) { + scrollTop += e.movementY; + } + } + }, + 10 + ); + + elem.addEventListener( + 'mousemove', + handleMove + ); + + return elem; +}; /** * Make a web element pannable. */ module.exports = { - init: (elem, containerElem) => { - var container = containerElem ? - containerElem : elem.parentElement; - - elem.addEventListener('mousemove', (e) => { - e.preventDefault(); - - if (e && e.which === 1) { - - if (e.movementX !== 0) { - container.scrollLeft -= e.movementX; - } - - if (e.movementY !== 0) { - container.scrollTop -= e.movementY; - } - } - }); - - return elem; - } + init };
775cc483bbae71e5fd9793e9986e0348d2474d06
src/index.js
src/index.js
'use strict'; /* globals window, angular */ angular.module('vlui', [ 'LocalStorageModule', 'ui.select', ]) .constant('_', window._) // datalib, vegalite, vega .constant('dl', window.dl) .constant('vl', window.vl) .constant('vg', window.vg) // other libraries .constant('Blob', window.Blob) .constant('URL', window.URL) .constant('Drop', window.Drop) .constant('Heap', window.Heap) // constants .constant('consts', { addCount: true, // add count field to Dataset.dataschema debug: true, useUrl: true, logging: false, defaultConfigSet: 'large', appId: 'vlui', // embedded polestar and voyager with known data embeddedData: window.vguiData || undefined, priority: { bookmark: 0, popup: 0, vislist: 1000 }, myriaRest: 'http://ec2-52-1-38-182.compute-1.amazonaws.com:8753' });
'use strict'; /* globals window, angular */ angular.module('vlui', [ 'LocalStorageModule', 'ui.select', 'angular-google-analytics' ]) .constant('_', window._) // datalib, vegalite, vega .constant('dl', window.dl) .constant('vl', window.vl) .constant('vg', window.vg) // other libraries .constant('Blob', window.Blob) .constant('URL', window.URL) .constant('Drop', window.Drop) .constant('Heap', window.Heap) // constants .constant('consts', { addCount: true, // add count field to Dataset.dataschema debug: true, useUrl: true, logging: true, defaultConfigSet: 'large', appId: 'vlui', // embedded polestar and voyager with known data embeddedData: window.vguiData || undefined, priority: { bookmark: 0, popup: 0, vislist: 1000 }, myriaRest: 'http://ec2-52-1-38-182.compute-1.amazonaws.com:8753' }) .config(function (AnalyticsProvider) { AnalyticsProvider .setAccount(//{ tracker: 'UA-44428446-4', name: 'voyager', trackEvent: true }, { tracker: 'UA-38453955-1', name: 'test', trackEvent: true }); });
Add angular analytics as dependency
Add angular analytics as dependency
JavaScript
bsd-3-clause
vega/vega-lite-ui,uwdata/vega-lite-ui,uwdata/vega-lite-ui,vega/vega-lite-ui,vega/vega-lite-ui,uwdata/vega-lite-ui
--- +++ @@ -4,6 +4,7 @@ angular.module('vlui', [ 'LocalStorageModule', 'ui.select', + 'angular-google-analytics' ]) .constant('_', window._) // datalib, vegalite, vega @@ -20,7 +21,7 @@ addCount: true, // add count field to Dataset.dataschema debug: true, useUrl: true, - logging: false, + logging: true, defaultConfigSet: 'large', appId: 'vlui', // embedded polestar and voyager with known data @@ -31,4 +32,9 @@ vislist: 1000 }, myriaRest: 'http://ec2-52-1-38-182.compute-1.amazonaws.com:8753' + }) + .config(function (AnalyticsProvider) { + AnalyticsProvider + .setAccount(//{ tracker: 'UA-44428446-4', name: 'voyager', trackEvent: true }, + { tracker: 'UA-38453955-1', name: 'test', trackEvent: true }); });
e4da867c2422df1279ed0e13dcc3143af473aa6a
src/index.js
src/index.js
/* @flow */ import matches from 'matches-selector-ng'; const proto = global.Element && global.Element.prototype; const vendor = proto && proto.closest; export default function closest(element: HTMLElement, selector: string): ?HTMLElement { if (vendor) return vendor.call(element, selector); let parent = element; do { if (matches(parent, selector)) return parent; parent = parent.parentNode; } while (parent && parent !== global.document); return null; }
/* @flow */ import matches from 'matches-selector-ng'; const proto = global.Element && global.Element.prototype; const vendor = proto && proto.closest; export default function closest(element: HTMLElement, selector: string): HTMLElement | null { if (vendor) return vendor.call(element, selector); let parent = element; do { if (matches(parent, selector)) return parent; parent = parent.parentNode; } while (parent && parent !== global.document); return null; }
Make return type more specific.
Make return type more specific.
JavaScript
mit
AgentME/closest-ng
--- +++ @@ -5,7 +5,7 @@ const proto = global.Element && global.Element.prototype; const vendor = proto && proto.closest; -export default function closest(element: HTMLElement, selector: string): ?HTMLElement { +export default function closest(element: HTMLElement, selector: string): HTMLElement | null { if (vendor) return vendor.call(element, selector); let parent = element; do {
7235b162e7080fe287f83edd84b13a91a4aa0ab2
app/scripts/plugins/draw/draw.js
app/scripts/plugins/draw/draw.js
define(['backbone', 'backbone.marionette', 'communicator', 'leaflet', 'leaflet.draw'], function(Backbone, Marionette, Communicator, L, LeafletDraw) { return Marionette.Object.extend({ map: null, mapController: null, initialize: function(o) { var self = this; Communicator.mediator.on("map:ready", function(map) { self.map = map; self.initDraw(); }, this); }, initDraw: function() { // Leaflet map var map = this.map; var drawnItems = new L.FeatureGroup(); map.addLayer(drawnItems); var drawControl = new L.Control.Draw({ edit: { featureGroup: drawnItems } }); map.addControl(drawControl); map.on('draw:created', function (e) { var type = e.layerType, layer = e.layer; if (type === 'marker') { // Do marker specific actions } drawnItems.addLayer(layer); }); } }) });
define(['backbone', 'backbone.marionette', 'communicator', 'leaflet', 'leaflet.draw'], function(Backbone, Marionette, Communicator, L, LeafletDraw) { return Marionette.Object.extend({ map: null, mapController: null, initialize: function(o) { var self = this; Communicator.mediator.on("map:ready", function(map) { self.map = map; self.initDraw(); }, this); }, initDraw: function() { // Leaflet map var map = this.map; var drawnItems = new L.FeatureGroup(); map.addLayer(drawnItems); var drawControl = new L.Control.Draw({ draw: { rectangle: false, circle: false, }, edit: { featureGroup: drawnItems } }); map.addControl(drawControl); map.on('draw:created', function (e) { var type = e.layerType, layer = e.layer; if (type === 'marker') { // Do marker specific actions } drawnItems.addLayer(layer); }); } }) });
Remove circle and rectangle tools
Remove circle and rectangle tools
JavaScript
mit
TotalActiveMedia/erfgeoviewer,TotalActiveMedia/erfgeoviewer,TotalActiveMedia/erfgeoviewer
--- +++ @@ -24,6 +24,10 @@ map.addLayer(drawnItems); var drawControl = new L.Control.Draw({ + draw: { + rectangle: false, + circle: false, + }, edit: { featureGroup: drawnItems }
2b2aae763a3dc985a6bde7345a0798a7e0347423
projects/immersive-and-narrative/plugins/MediaEvents/src/MediaEvents.js
projects/immersive-and-narrative/plugins/MediaEvents/src/MediaEvents.js
var ForgePlugins = ForgePlugins || {}; ForgePlugins.MediaEvents = function() { this._video = null; }; ForgePlugins.MediaEvents.prototype = { boot: function() { this._setupVideo(); }, reset: function() { this._clearVideo(); this._setupVideo(); }, _setupVideo: function() { if(this.viewer.renderer.media !== null) { this._video = this.viewer.renderer.media.displayObject; this._video.onEnded.add(this._onEndedHandler, this); } else { if(this.viewer.renderer.onMediaReady.has(this._setupVideo, this) === false) { this.viewer.renderer.onMediaReady.addOnce(this._setupVideo, this); } } }, _clearVideo: function() { if(this._video !== null) { this._video.onEnded.remove(this._onEndedHandler, this); } this._video = null; }, _onEndedHandler: function() { this.plugin.events.onEnded.dispatch(); }, destroy: function() { this._clearVideo(); } };
var ForgePlugins = ForgePlugins || {}; ForgePlugins.MediaEvents = function() { this._video = null; }; ForgePlugins.MediaEvents.prototype = { boot: function() { this._setupVideo(); }, reset: function() { this._clearVideo(); this._setupVideo(); }, _setupVideo: function() { this._video = this.viewer.story.scene.media.displayObject; this._video.onEnded.add(this._onEndedHandler, this); }, _clearVideo: function() { if(this._video !== null) { this._video.onEnded.remove(this._onEndedHandler, this); } this._video = null; }, _onEndedHandler: function() { this.plugin.events.onEnded.dispatch(); }, destroy: function() { this._clearVideo(); } };
Fix MediaEvent plugin of immersive project for new scene media
Fix MediaEvent plugin of immersive project for new scene media
JavaScript
apache-2.0
gopro/forgejs-samples,gopro/forgejs-samples
--- +++ @@ -20,18 +20,8 @@ _setupVideo: function() { - if(this.viewer.renderer.media !== null) - { - this._video = this.viewer.renderer.media.displayObject; - this._video.onEnded.add(this._onEndedHandler, this); - } - else - { - if(this.viewer.renderer.onMediaReady.has(this._setupVideo, this) === false) - { - this.viewer.renderer.onMediaReady.addOnce(this._setupVideo, this); - } - } + this._video = this.viewer.story.scene.media.displayObject; + this._video.onEnded.add(this._onEndedHandler, this); }, _clearVideo: function()
aa7245ba61b8a9f4c0c50d1516b59e618caf3050
src/subtitulamos/resources/assets/js/rules.js
src/subtitulamos/resources/assets/js/rules.js
/** * This file is covered by the AGPLv3 license, which can be found at the LICENSE file in the root of this project. * @copyright 2020 subtitulamos.tv */ import "../css/rules.scss"; import { onDomReady } from "./utils"; onDomReady(() => { for (const $spoilerWrapper of document.querySelectorAll(".spoiler-wrapper")) { $spoilerWrapper.addEventListener("click", function () { const $spoiler = this.querySelector(".spoiler-content"); const $spoilerName = this.querySelector(".spoiler-name"); if ($spoilerName.innerHTML.includes("VER")) { $spoilerName.innerHTML = $spoilerName.innerHTML.replace("VER", "OCULTAR"); } else if ($spoilerName.innerHTML.includes("OCULTAR")) { $spoilerName.innerHTML = $spoilerName.innerHTML.replace("OCULTAR", "VER"); } if ($spoilerName.innerHTML.includes("MÁS")) { $spoilerName.innerHTML = $spoilerName.innerHTML.replace("MÁS", "MENOS"); } else if ($spoilerName.innerHTML.includes("MENOS")) { $spoilerName.innerHTML = $spoilerName.innerHTML.replace("MENOS", "MÁS"); } const $icon = this.querySelector(".spoiler-name i"); $icon.classList.toggle("fa-chevron-down"); $icon.classList.toggle("fa-chevron-up"); $spoiler.classList.toggle("expanded"); }); } });
/** * This file is covered by the AGPLv3 license, which can be found at the LICENSE file in the root of this project. * @copyright 2020 subtitulamos.tv */ import "../css/rules.scss"; import { get_all, onDomReady } from "./utils"; onDomReady(() => { for (const $spoilerName of get_all(".spoiler-name")) { $spoilerName.addEventListener("click", function () { const $spoilerWrapper = this.closest(".spoiler-wrapper"); const $spoiler = $spoilerWrapper.querySelector(".spoiler-content"); if ($spoilerName.innerHTML.includes("VER")) { $spoilerName.innerHTML = $spoilerName.innerHTML.replace("VER", "OCULTAR"); } else if ($spoilerName.innerHTML.includes("OCULTAR")) { $spoilerName.innerHTML = $spoilerName.innerHTML.replace("OCULTAR", "VER"); } if ($spoilerName.innerHTML.includes("MÁS")) { $spoilerName.innerHTML = $spoilerName.innerHTML.replace("MÁS", "MENOS"); } else if ($spoilerName.innerHTML.includes("MENOS")) { $spoilerName.innerHTML = $spoilerName.innerHTML.replace("MENOS", "MÁS"); } const $icon = this.querySelector(".spoiler-name i"); $icon.classList.toggle("fa-chevron-down"); $icon.classList.toggle("fa-chevron-up"); $spoiler.classList.toggle("expanded"); }); } });
Fix collapsing of rule explanations
Fix collapsing of rule explanations
JavaScript
agpl-3.0
subtitulamos/subtitulamos,subtitulamos/subtitulamos,subtitulamos/subtitulamos,subtitulamos/subtitulamos,subtitulamos/subtitulamos
--- +++ @@ -4,14 +4,14 @@ */ import "../css/rules.scss"; -import { onDomReady } from "./utils"; +import { get_all, onDomReady } from "./utils"; onDomReady(() => { - for (const $spoilerWrapper of document.querySelectorAll(".spoiler-wrapper")) { - $spoilerWrapper.addEventListener("click", function () { - const $spoiler = this.querySelector(".spoiler-content"); + for (const $spoilerName of get_all(".spoiler-name")) { + $spoilerName.addEventListener("click", function () { + const $spoilerWrapper = this.closest(".spoiler-wrapper"); + const $spoiler = $spoilerWrapper.querySelector(".spoiler-content"); - const $spoilerName = this.querySelector(".spoiler-name"); if ($spoilerName.innerHTML.includes("VER")) { $spoilerName.innerHTML = $spoilerName.innerHTML.replace("VER", "OCULTAR"); } else if ($spoilerName.innerHTML.includes("OCULTAR")) {
675065d9085e8c4dc7ee8214a7eade47d5041f51
src/utils.js
src/utils.js
const defaults = require('./defaults.js'); const parseBoolean = boolean => boolean === 'true'; const parseIntervals = (intervals) => { if (Array.isArray(intervals)) { return intervals .filter(i => !isNaN(i)) .map(parseFloat) .sort((a, b) => a - b); } const interval = parseFloat(intervals); return interval ? [interval] : defaults.intervals; }; const parseUnits = (units) => { if (units === 'kilometers' || units === 'miles') { return units; } return defaults.units; }; const parsers = { lng: parseFloat, lat: parseFloat, radius: parseFloat, cellSize: parseFloat, concavity: parseFloat, lengthThreshold: parseFloat, deintersect: parseBoolean, intervals: parseIntervals, units: parseUnits }; const parseQuery = query => Object.keys(parsers).reduce((acc, paramKey) => { if (query[paramKey]) { const parser = parsers[paramKey]; acc[paramKey] = parser(query[paramKey]); } return acc; }, defaults); module.exports = parseQuery;
const defaults = require('./defaults.js'); const parseBoolean = boolean => boolean === 'true'; const parseIntervals = (intervals) => { if (Array.isArray(intervals)) { return intervals .filter(i => !isNaN(i)) .map(parseFloat) .sort((a, b) => a - b); } const interval = parseFloat(intervals); return interval ? [interval] : defaults.intervals; }; const parseUnits = (units) => { if (units === 'kilometers' || units === 'miles') { return units; } return defaults.units; }; const parsers = { lng: parseFloat, lat: parseFloat, radius: parseFloat, cellSize: parseFloat, concavity: parseFloat, lengthThreshold: parseFloat, deintersect: parseBoolean, intervals: parseIntervals, units: parseUnits }; const parseQuery = query => Object.keys(parsers).reduce((acc, paramKey) => { if (query[paramKey]) { const parser = parsers[paramKey]; acc[paramKey] = parser(query[paramKey]); } return acc; }, Object.assign({}, defaults)); module.exports = parseQuery;
Clone `defaults` object to avoid member assignment
Clone `defaults` object to avoid member assignment Fixes urbica/galton#183
JavaScript
mit
urbica/galton,urbica/galton
--- +++ @@ -39,6 +39,6 @@ acc[paramKey] = parser(query[paramKey]); } return acc; - }, defaults); + }, Object.assign({}, defaults)); module.exports = parseQuery;
57125a8c83882e44b2108e7ecac9240dfd90c8cf
src/js/pebble-js-app.js
src/js/pebble-js-app.js
var initialized = false; Pebble.addEventListener("ready", function() { console.log("ready called!"); initialized = true; }); Pebble.addEventListener("showConfiguration", function() { console.log("showing configuration"); var shakeToCheat = 1; // get current setting from pebble Pebble.openURL('http://rawgithub.com/kesselborn/line-maze/SDK-2.0-with-shake-to-cheat-config/configuration.html?stc=' + shakeToCheat); }); Pebble.addEventListener("appmessage", function(e) { console.log("Received message: " + e.payload); }); Pebble.addEventListener("webviewclosed", function(e) { console.log("configuration closed"); // webview closed var options = JSON.parse(decodeURIComponent(e.response)); console.log("sending config to pebble"); Pebble.sendAppMessage( { "shake-to-cheat": options["shake-to-cheat"] }, function(e) { console.log("Successfully delivered message with transactionId=" + e.data.transactionId + " ... shake-to-cheat=" + options["shake-to-cheat"]); }, function(e) { console.log("Unable to deliver message with transactionId=" + e.data.transactionId + " Error is: " + e.error.message); } ); console.log("Options = " + JSON.stringify(options)); });
var initialized = false; Pebble.addEventListener("ready", function() { console.log("ready called!"); initialized = true; }); Pebble.addEventListener("showConfiguration", function() { console.log("showing configuration"); var shakeToCheat = localStorage.getItem("shake-to-cheat") || 1; Pebble.openURL('http://rawgithub.com/kesselborn/line-maze/SDK-2.0-with-shake-to-cheat-config/configuration.html?stc=' + shakeToCheat); }); Pebble.addEventListener("appmessage", function(e) { console.log("Received message: " + e.payload); }); Pebble.addEventListener("webviewclosed", function(e) { console.log("configuration closed"); // webview closed var options = JSON.parse(decodeURIComponent(e.response)); console.log("sending config to pebble"); Pebble.sendAppMessage( { "shake-to-cheat": options["shake-to-cheat"] }, function(e) { console.log("Successfully delivered message with transactionId=" + e.data.transactionId + " ... shake-to-cheat=" + options["shake-to-cheat"]); // only save when it worked to stay in sync with watch localStorage.setItem("shake-to-cheat", options["shake-to-cheat"]); }, function(e) { console.log("Unable to deliver message with transactionId=" + e.data.transactionId + " Error is: " + e.error.message); } ); console.log("Options = " + JSON.stringify(options)); });
Load and persist config on phone app
Load and persist config on phone app
JavaScript
mit
chasecolburn/line-maze,chasecolburn/line-maze,chasecolburn/line-maze
--- +++ @@ -7,7 +7,7 @@ Pebble.addEventListener("showConfiguration", function() { console.log("showing configuration"); - var shakeToCheat = 1; // get current setting from pebble + var shakeToCheat = localStorage.getItem("shake-to-cheat") || 1; Pebble.openURL('http://rawgithub.com/kesselborn/line-maze/SDK-2.0-with-shake-to-cheat-config/configuration.html?stc=' + shakeToCheat); }); @@ -25,6 +25,9 @@ function(e) { console.log("Successfully delivered message with transactionId=" + e.data.transactionId + " ... shake-to-cheat=" + options["shake-to-cheat"]); + + // only save when it worked to stay in sync with watch + localStorage.setItem("shake-to-cheat", options["shake-to-cheat"]); }, function(e) { console.log("Unable to deliver message with transactionId=" +
f74006ac42b9a1d75b2887130fd0046b7d05f268
client/components/admin-lte/Sidebar.js
client/components/admin-lte/Sidebar.js
import React from 'react'; import SideLink from '../common/SideLink'; import { Link } from 'react-router'; const Sidebar = (props) => { // eslint-disable-line no-unused-vars return ( <aside className="main-sidebar"> <section className="sidebar"> <div className="user-panel"> <div className="pull-left image"><img className="img-circle" src="https://placeholdit.imgix.net/~text?txtsize=15&txt=160%C3%97160&w=160&h=160" alt="User Image" /></div> <div className="pull-left info"> <p>Test user</p> <a> Online</a></div> </div> <ul className="sidebar-menu"> <li className="header">OPTIONS</li> <SideLink to="/">Home</SideLink> <SideLink to="/settings">Settings</SideLink> <li className="treeview"><a href="#"> Subscribers </a> <ul className="treeview-menu"> <li><Link to="/add-email">Add email</Link></li> <li><a href="#">Link in level 2</a></li> </ul> </li> </ul> </section> </aside> ); }; export default Sidebar;
import React from 'react'; import SideLink from '../common/SideLink'; import { Link } from 'react-router'; const Sidebar = (props) => { // eslint-disable-line no-unused-vars return ( <aside className="main-sidebar"> <section className="sidebar"> <div className="user-panel"> <div className="pull-left image"><img className="img-circle" src="https://placeholdit.imgix.net/~text?txtsize=15&txt=160%C3%97160&w=160&h=160" alt="User Image" /></div> <div className="pull-left info"> <p>Test user</p> <a> Online</a></div> </div> <ul className="sidebar-menu"> <li className="header">OPTIONS</li> <SideLink to="/">Home</SideLink> <SideLink to="/settings">Settings</SideLink> <li className="treeview"><a href="#"> Subscribers </a> <ul className="treeview-menu"> <li><Link to="/add-email">Add email</Link></li> <li><Link to="/import-subscribers">Import</Link></li> </ul> </li> </ul> </section> </aside> ); }; export default Sidebar;
Add a link to the import-subscribers page in the sidebar
Add a link to the import-subscribers page in the sidebar
JavaScript
bsd-3-clause
zhakkarn/Mail-for-Good,zhakkarn/Mail-for-Good,karuppiah7890/Mail-for-Good,karuppiah7890/Mail-for-Good,karuppiah7890/Mail-for-Good,zhakkarn/Mail-for-Good
--- +++ @@ -23,7 +23,7 @@ <li className="treeview"><a href="#"> Subscribers </a> <ul className="treeview-menu"> <li><Link to="/add-email">Add email</Link></li> - <li><a href="#">Link in level 2</a></li> + <li><Link to="/import-subscribers">Import</Link></li> </ul> </li> </ul>
3bfd0e3be920ac3e9b35ef9e906aeee47f34abe6
src/doors.js
src/doors.js
//TODO: Implement helper functions for: // open/close, lock/unlock, and other player and NPC interactions with doors.
//TODO: Implement helper functions for: // open/close, lock/unlock, and other player and NPC interactions with doors. 'use strict'; const CommandUtil = require('./command_util').CommandUtil; const util = require('util'); /* * Handy little util functions. */ const has = (collection, thing) => collection.indexOf(thing) !== -1; const findExit = (room, dir) => room.getExits() .filter(exit => has(exit.direction, dir)); const updateDestination = (player, dest, callback) => dest .getExits() .filter(exit => exit.location === player.getLocation()) .forEach(callback); exports.DoorUtil = { has, updateDestination, findExit, openOrClose }; function openOrClose(verb, args, player, players, rooms) { const isOpen = verb === 'open'; player.emit('action', 0); if (player.isInCombat()) { player.say('You are too busy for that right now.'); return; } args = args.toLowerCase().split(' '); if (!args) { return player.say("Which door do you want to " + verb + "?"); } const room = rooms.getAt(player.getLocation()); const dir = args[0]; const exits = findExit(room, dir); if (exits.length !== 1) { return player.say('Be more specific...'); } const exit = exits[0]; if (!exit.door) { return player.say('There is no door.'); } if (exit.door.open === isOpen) { const pastTense = isOpen ? 'opened' : 'closed'; return player.say('That door is already ' + pastTense +'.'); } const dest = rooms.getAt(exit.location); const srcTitle = room.getTitle('en'); const destTitle = dest.getTitle('en'); player.say('You ' + verb + ' the door to ' + destTitle + '.'); exit.door.open = isOpen; updateDestination(player, dest, exit => { exit.door.open = isOpen; const nounPhrase = isOpen ? 'swings open' : 'slams shut'; players.eachIf( p => p.getLocation() === exit.location, p => p.say('The door to ' + srcTitle + ' ' + nounPhrase + '.')); }); players.eachIf( p => CommandUtil.inSameRoom(p, player), p => p.say(player.getName() + ' ' + verb + 's the door to ' + dest + '.')); };
Refactor open and close function to be the same thing, exported to be called from the command files.
Refactor open and close function to be the same thing, exported to be called from the command files.
JavaScript
mit
seanohue/ranviermud,shawncplus/ranviermud,seanohue/ranviermud
--- +++ @@ -1,2 +1,83 @@ //TODO: Implement helper functions for: // open/close, lock/unlock, and other player and NPC interactions with doors. + +'use strict'; +const CommandUtil = require('./command_util').CommandUtil; +const util = require('util'); + +/* + * Handy little util functions. + */ +const has = (collection, thing) => collection.indexOf(thing) !== -1; + +const findExit = (room, dir) => room.getExits() + .filter(exit => has(exit.direction, dir)); + +const updateDestination = (player, dest, callback) => dest + .getExits() + .filter(exit => exit.location === player.getLocation()) + .forEach(callback); + +exports.DoorUtil = { + has, updateDestination, + findExit, openOrClose }; + +function openOrClose(verb, args, player, players, rooms) { + + const isOpen = verb === 'open'; + + player.emit('action', 0); + + if (player.isInCombat()) { + player.say('You are too busy for that right now.'); + return; + } + + args = args.toLowerCase().split(' '); + + if (!args) { + return player.say("Which door do you want to " + verb + "?"); + } + const room = rooms.getAt(player.getLocation()); + const dir = args[0]; + const exits = findExit(room, dir); + + if (exits.length !== 1) { + return player.say('Be more specific...'); + } + + const exit = exits[0]; + + if (!exit.door) { + return player.say('There is no door.'); + } + + if (exit.door.open === isOpen) { + const pastTense = isOpen ? 'opened' : 'closed'; + return player.say('That door is already ' + pastTense +'.'); + } + + const dest = rooms.getAt(exit.location); + + const srcTitle = room.getTitle('en'); + const destTitle = dest.getTitle('en'); + + player.say('You ' + verb + ' the door to ' + destTitle + '.'); + exit.door.open = isOpen; + + updateDestination(player, dest, + exit => { + exit.door.open = isOpen; + + const nounPhrase = isOpen ? 'swings open' : 'slams shut'; + players.eachIf( + p => p.getLocation() === exit.location, + p => p.say('The door to ' + srcTitle + ' ' + nounPhrase + '.')); + }); + + players.eachIf( + p => CommandUtil.inSameRoom(p, player), + p => p.say(player.getName() + ' ' + verb + 's the door to ' + dest + '.')); + + +};
2ef6613becea4df29aaf9aeff58d308686743084
app/js/app.js
app/js/app.js
var store = null; $(function() { $(document).on("dragstart", "img", false); $("#page-back").click(function() { utils.page(utils.page() - 1); }); $("#page-next").click(function() { utils.page(utils.page() + 1); }); $.getJSON("data.json").done(function(data) { if(data.length == 0) alert("No data.json, or data invalid."); store = data; window.router = new router(); router.init(); if(location.hash == "#" || location.hash == "") location.hash = "#index!1"; }); });
var store = null; $(function() { $(document).on("dragstart", "img", false); $("#page-back").click(function() { utils.page(utils.page() - 1); }); $("#page-next").click(function() { utils.page(utils.page() + 1); }); $(window).keydown(function(event) { if(event.keyCode == 39) { event.preventDefault(); utils.page(utils.page() + 1); } else if(event.keyCode == 8 || event.keyCode == 37) { event.preventDefault(); utils.page(utils.page() - 1); } }); $.getJSON("data.json").done(function(data) { if(data.length == 0) alert("No data.json, or data invalid."); store = data; window.router = new router(); router.init(); if(location.hash == "#" || location.hash == "") location.hash = "#index!1"; }); });
Allow using keyboard to move between pages as well
Allow using keyboard to move between pages as well
JavaScript
mit
bloopletech/mangos,bloopletech/videos,bloopletech/videos
--- +++ @@ -10,6 +10,17 @@ utils.page(utils.page() + 1); }); + $(window).keydown(function(event) { + if(event.keyCode == 39) { + event.preventDefault(); + utils.page(utils.page() + 1); + } + else if(event.keyCode == 8 || event.keyCode == 37) { + event.preventDefault(); + utils.page(utils.page() - 1); + } + }); + $.getJSON("data.json").done(function(data) { if(data.length == 0) alert("No data.json, or data invalid.");
b81ff5ecc2ccb982c136305f9df3fb3c0d72827c
libs/Mailer.js
libs/Mailer.js
// let messanger = require('./mailer/transport')(); module.exports = function(_db, messanger){ if(!SlickSources[_db]) return {start: () => false}; let _req = {db:SlickSources[_db]}, Mails = Models.Mails(_req), fetchMails = cb => { Mails.find({limit:100,sent:'0'}, function(e, recs){ if(!e){ cb(recs); }else{ console.error(e); } }) }, start = () => { fetchMails( dispatch ); }, dispatch = recs => { let run = function(){ if(recs.length){ sendMail(recs.pop()); }else setTimeout(start,100); }, sendMail = r => { r.to = `${r.receiver_name} <${r.receiver_email}>`; r.message = r.body; messanger.sendMail(r, function (e, info) { if (!e) { Mails.destroy({id:r.id}, function(err, res){ run(); }); } else{ Mails.update({id:r.id, sent:'1'}, function(){ run(); }); } }); }; run(); }; console.log('Registered Mailer for ', _db); return { start:start } };
// let messanger = require('./mailer/transport')(); module.exports = function(_db, messanger){ if(!SlickSources[_db]) return {start: () => false}; let _req = {db:SlickSources[_db]}, Mails = Models.Mails(_req), fetchMails = cb => { Mails.find({limit:100}, function(e, recs){ if(!e){ cb(recs); }else{ console.error(e); } }) }, start = () => { fetchMails( dispatch ); }, dispatch = recs => { let run = function(){ if(recs.length){ sendMail(recs.pop()); }else setTimeout(start,100); }, sendMail = r => { r.to = `${r.receiver_name} <${r.receiver_email}>`; r.message = r.body; messanger.sendMail(r, function (e, info) { if (!e) { Mails.destroy({id:r.id}, function(err, res){ run(); }); } // else{ // Mails.update({id:r.id, sent:'1'}, function(){ // run(); // }); // } }); }; run(); }; console.log('Registered Mailer for ', _db); return { start:start } };
Remove handling of failed send error
Remove handling of failed send error
JavaScript
mit
steveesamson/slicks-bee,steveesamson/slicks-bee
--- +++ @@ -9,10 +9,14 @@ Mails = Models.Mails(_req), fetchMails = cb => { - Mails.find({limit:100,sent:'0'}, function(e, recs){ + Mails.find({limit:100}, function(e, recs){ + if(!e){ + cb(recs); + }else{ + console.error(e); } @@ -46,12 +50,13 @@ run(); }); - } else{ + } + // else{ - Mails.update({id:r.id, sent:'1'}, function(){ - run(); - }); - } + // Mails.update({id:r.id, sent:'1'}, function(){ + // run(); + // }); + // } });
5c4c8f1b0b3557cde47b7ec4a2c553a3acca7a36
src/error.js
src/error.js
// // Error handling // export var onError export function catchFunctionErrors(delegate) { return onError ? function () { try { return delegate.apply(this, arguments); } catch (e) { onError && onError(e); throw e; } } : delegate; } export function deferError(error) { safeSetTimeout(function () { onError && onError(error); throw error; }, 0); } function safeSetTimeout(handler, timeout) { return setTimeout(catchFunctionErrors(handler), timeout); } export { safeSetTimeout as setTimeout }
// // Error handling // --- // // The default onError handler is to re-throw. export var onError = function (e) { throw(e); }; export function catchFunctionErrors(delegate) { return onError ? function () { try { return delegate.apply(this, arguments); } catch (e) { onError(e); } } : delegate; } export function deferError(error) { safeSetTimeout(function () { onError && onError(error); throw error; }, 0); } function safeSetTimeout(handler, timeout) { return setTimeout(catchFunctionErrors(handler), timeout); } export { safeSetTimeout as safeSetTimeout };
Change onError behaviour; export safeSetTimeout
Change onError behaviour; export safeSetTimeout
JavaScript
mit
knockout/tko.utils
--- +++ @@ -1,15 +1,16 @@ // // Error handling +// --- // -export var onError +// The default onError handler is to re-throw. +export var onError = function (e) { throw(e); }; export function catchFunctionErrors(delegate) { return onError ? function () { try { return delegate.apply(this, arguments); } catch (e) { - onError && onError(e); - throw e; + onError(e); } } : delegate; } @@ -26,4 +27,4 @@ return setTimeout(catchFunctionErrors(handler), timeout); } -export { safeSetTimeout as setTimeout } +export { safeSetTimeout as safeSetTimeout };
1dbec704daf75b7e48f6508fad00951ce1b562d4
app/assets/javascripts/renalware/components/tabs.js
app/assets/javascripts/renalware/components/tabs.js
function initTabs() { $(".sub-nav.with-tabs dl a").on("click", function(e) { e.preventDefault(); var anchor = e.target var dl = anchor.closest("dl"); var dd = anchor.closest("dd"); var idToDeactivate = $("dd.active a", dl).attr("href"); $("dd.active", dl).removeClass("active") $(dd).addClass("active"); var idToActivate = anchor.getAttribute("href"); $(idToDeactivate).hide(); $(idToActivate).show(); }) } $(function() { initTabs(); });
function initTabs() { $(".sub-nav.with-tabs dl a").on("click", function(e) { e.preventDefault(); var anchor = e.target var dl = $(anchor).closest("dl"); var dd = $(anchor).closest("dd"); var idToDeactivate = $("dd.active a", dl).attr("href"); $("dd.active", dl).removeClass("active") $(dd).addClass("active"); var idToActivate = anchor.getAttribute("href"); $(idToDeactivate).hide(); $(idToActivate).show(); }) } $(function() { initTabs(); });
Fix an IE11 js bug in tab toggling
Fix an IE11 js bug in tab toggling
JavaScript
mit
airslie/renalware-core,airslie/renalware-core,airslie/renalware-core,airslie/renalware-core
--- +++ @@ -2,8 +2,8 @@ $(".sub-nav.with-tabs dl a").on("click", function(e) { e.preventDefault(); var anchor = e.target - var dl = anchor.closest("dl"); - var dd = anchor.closest("dd"); + var dl = $(anchor).closest("dl"); + var dd = $(anchor).closest("dd"); var idToDeactivate = $("dd.active a", dl).attr("href"); $("dd.active", dl).removeClass("active") $(dd).addClass("active");
0287791b0c12f2f952d2289fd6b99a9ab5cb6203
dev/_/components/js/sourceCollectionView.js
dev/_/components/js/sourceCollectionView.js
AV.SourceCollectionView = Backbone.View.extend({ el: '#list_container', initialize: function() { this.listenTo(this.collection, 'all', this.render); console.log("Initialize View"); }, events: { "click #deleteButton": "delete", //"click #uploadButton": "upload", }, template: _.template( $("#list_template").html()), render: function () { this.$el.empty(); console.log("Rendered"); this.$el.html(this.template({sources: this.collection.models})); test(); }, delete: function(ev) { //ev is the mouse event. We receive the data-value which contains //the id. test("in delete in source collection"); var idToDelete = $(ev.target).data('value'); var sourceToRemove = this.collection.find(function (source) { return source.id == idToDelete;}); sourceToRemove.urlRoot = 'php/redirect.php/source/'; sourceToRemove.destroy(); }, upload: function(ev) { uploadModel = new AV.SourceModel({name: $("#upload").val(), data: $("#uploadContent").val()}); uploadModel.save(); }, });
AV.SourceCollectionView = Backbone.View.extend({ el: '#list_container', initialize: function() { this.listenTo(this.collection, 'all', this.render); console.log("Initialize View"); }, events: { "click #deleteButton": "delete", //"click #uploadButton": "upload", }, template: _.template( $("#list_template").html()), render: function () { this.$el.empty(); console.log("Rendered"); this.$el.html(this.template({sources: this.collection.models})); test(); }, delete: function(ev) { //ev is the mouse event. We receive the data-value which contains //the id. test("in delete in source collection"); var idToDelete = $(ev.target).data('value'); var sourceToRemove = this.collection.find(function (source) { return source.id == idToDelete;}); sourceToRemove.urlRoot = 'php/redirect.php/source/'; sourceToRemove.destroy(); } });
Remove upload view from sourcecollectionview
Remove upload view from sourcecollectionview
JavaScript
bsd-3-clause
Swarthmore/juxtaphor,Swarthmore/juxtaphor
--- +++ @@ -5,8 +5,8 @@ console.log("Initialize View"); }, events: { - "click #deleteButton": "delete", - //"click #uploadButton": "upload", + "click #deleteButton": "delete", + //"click #uploadButton": "upload", }, template: _.template( $("#list_template").html()), render: function () { @@ -25,12 +25,5 @@ sourceToRemove.urlRoot = 'php/redirect.php/source/'; sourceToRemove.destroy(); - }, - upload: function(ev) { - - uploadModel = new AV.SourceModel({name: $("#upload").val(), data: $("#uploadContent").val()}); - uploadModel.save(); - - }, - + } });
2d4f8b734a297942ba4ddc875359a165a68184b4
lib/form/index.js
lib/form/index.js
/** @jsx dom */ import dom from 'magic-virtual-element'; import formSerialize from 'form-serialize'; export const propTypes = { onSubmit: { type: 'function' }, transform: { type: 'function' } }; export function render({props}) { const {children, transform, onSubmit} = props; function handle(e) { e.preventDefault(); const el = e.target; if (el.checkValidity()) { const data = formSerialize(el, transform); if (onSubmit) { onSubmit(data, el); } } } return ( <form class={['Form', props.class]} novalidate onSubmit={handle}> {children} </form> ); }
/** @jsx dom */ import dom from 'magic-virtual-element'; import formSerialize from 'form-serialize'; export const propTypes = { onSubmit: { type: 'function' }, transform: { type: 'function' } }; export function render({props}) { const {children, transform, onSubmit} = props; function handle(e) { e.preventDefault(); const el = e.target; if (el.checkValidity()) { const data = formSerialize(el, transform); if (onSubmit) { onSubmit(data, el, e); } } } return ( <form class={['Form', props.class]} novalidate onSubmit={handle}> {children} </form> ); }
Return the submit event in callback
Return the submit event in callback
JavaScript
mit
kevva/deku-form
--- +++ @@ -23,7 +23,7 @@ const data = formSerialize(el, transform); if (onSubmit) { - onSubmit(data, el); + onSubmit(data, el, e); } } }
a4dcb20a78bf8e72f943ae24247a4330c68c56c9
src/index.js
src/index.js
(function () { module.exports = function (onCreate, onAppend) { var baseApp; return { /** * Array of properties to be copied from main app to sub app */ merged: ['view engine', 'views'], /** * Array of properties to be copied from main app to sub app locals */ locals: [], /** * Register the main express application, the source of merged/locals properties * * @param app */ create: function (app) { baseApp = app; onCreate && onCreate(app); onAppend && onAppend(app); return app; }, /** * Register a sub application, when the root is supplied the app is also bound to the main app. * * @param {string} [root] * @param app */ route: function(root, app) { if (arguments.length === 1) { app = root; root = null; } module.exports.merged.forEach(function (merged) { var baseAppValue = baseApp.get(merged); if (baseAppValue !== undefined) { app.set(merged, baseAppValue); } }); module.exports.locals.forEach(function (local) { app.locals[local] = baseApp.locals[local]; }); onAppend && onAppend(app); if (root > 1) { baseApp.use(root, app); } return app; } }; }; }());
(function () { module.exports = function (onCreate, onAppend) { var baseApp; return { /** * Array of properties to be copied from main app to sub app */ merged: ['view engine', 'views'], /** * Array of properties to be copied from main app to sub app locals */ locals: [], /** * Register the main express application, the source of merged/locals properties * * @param app */ create: function (app) { baseApp = app; onCreate && onCreate(app); onAppend && onAppend(app); return app; }, /** * Register a sub application, when the root is supplied the app is also bound to the main app. * * @param {string} [root] * @param app */ route: function(root, app) { if (arguments.length === 1) { app = root; root = null; } module.exports.merged.forEach(function (merged) { var baseAppValue = baseApp.get(merged); if (baseAppValue !== undefined) { app.set(merged, baseAppValue); } }); module.exports.locals.forEach(function (local) { app.locals[local] = baseApp.locals[local]; }); onAppend && onAppend(app, baseApp); if (root > 1) { baseApp.use(root, app); } return app; } }; }; }());
Include the baseApp when running onAppend function
Include the baseApp when running onAppend function
JavaScript
mit
steveukx/express-subapp
--- +++ @@ -51,7 +51,7 @@ app.locals[local] = baseApp.locals[local]; }); - onAppend && onAppend(app); + onAppend && onAppend(app, baseApp); if (root > 1) { baseApp.use(root, app);
7533d0283f658aaf5e93b017be5f96d021c1581e
src/index.js
src/index.js
var Laminate = {}; Laminate.Badge = require('./components/badge.js'); Laminate.Button = require('./components/button.js'); Laminate.Card = require('./components/card.js'); Laminate.Content = require('./components/content.js'); Laminate.Icon = require('./components/icon.js'); Laminate.Modal = require('./components/modal.js'); Laminate.TitleBar = require('./components/title-bar.js'); Laminate.Toggle = require('./components/toggle.js');
var Laminate = {}; Laminate.Badge = require('./components/badge'); Laminate.Button = require('./components/button'); Laminate.Card = require('./components/card'); Laminate.Content = require('./components/content'); Laminate.Icon = require('./components/icon'); Laminate.InputGroup = require('./components/input-group'); Laminate.Modal = require('./components/modal'); Laminate.TitleBar = require('./components/title-bar'); Laminate.Toggle = require('./components/toggle');
Remove the .js from requires.
Remove the .js from requires.
JavaScript
bsd-3-clause
joestump/laminate
--- +++ @@ -1,10 +1,11 @@ var Laminate = {}; -Laminate.Badge = require('./components/badge.js'); -Laminate.Button = require('./components/button.js'); -Laminate.Card = require('./components/card.js'); -Laminate.Content = require('./components/content.js'); -Laminate.Icon = require('./components/icon.js'); -Laminate.Modal = require('./components/modal.js'); -Laminate.TitleBar = require('./components/title-bar.js'); -Laminate.Toggle = require('./components/toggle.js'); +Laminate.Badge = require('./components/badge'); +Laminate.Button = require('./components/button'); +Laminate.Card = require('./components/card'); +Laminate.Content = require('./components/content'); +Laminate.Icon = require('./components/icon'); +Laminate.InputGroup = require('./components/input-group'); +Laminate.Modal = require('./components/modal'); +Laminate.TitleBar = require('./components/title-bar'); +Laminate.Toggle = require('./components/toggle');
184c92f89191ebcbe9135ec6f04bce0cb97f55cf
js/getData.js
js/getData.js
window.onload = initializeData() function initializeData() { var div = document.getElementById("right_now"); var date = new Date(); div.textContent = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate(); var text = div.textContent; }
window.onload = initializeData() function initializeData() { var right_now = document.getElementById("right_now"); var date = new Date(); right_now.textContent = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate(); var text = right_now.textContent; }
Rename div variable to right_now
Rename div variable to right_now
JavaScript
mit
mercysmart/cepatsembuh-iqbal,mercysmart/cepatsembuh-iqbal
--- +++ @@ -1,8 +1,8 @@ window.onload = initializeData() function initializeData() { - var div = document.getElementById("right_now"); + var right_now = document.getElementById("right_now"); var date = new Date(); - div.textContent = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate(); - var text = div.textContent; + right_now.textContent = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate(); + var text = right_now.textContent; }