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
007bd9cd36f3d2069f5681245f4c80d28c3e0841
packages/core/database/lib/lifecycles.js
packages/core/database/lib/lifecycles.js
'use strict'; const createLifecyclesManager = db => { let subscribers = []; const lifecycleManager = { subscribe(subscriber) { // TODO: verify subscriber subscribers.push(subscriber); return () => { subscribers.splice(subscribers.indexOf(subscriber), 1); }; }, createEvent(action, uid, properties) { const model = db.metadata.get(uid); return { action, model, ...properties, }; }, async run(action, uid, properties) { for (const subscriber of subscribers) { if (typeof subscriber === 'function') { const event = this.createEvent(action, uid, properties); return await subscriber(event); } const hasAction = action in subscriber; const hasModel = !subscriber.models || subscriber.models.includes(uid); if (hasAction && hasModel) { const event = this.createEvent(action, uid, properties); await subscriber[action](event); } } }, clear() { subscribers = []; }, }; return lifecycleManager; }; module.exports = { createLifecyclesManager, };
'use strict'; const createLifecyclesManager = db => { let subscribers = []; const lifecycleManager = { subscribe(subscriber) { // TODO: verify subscriber subscribers.push(subscriber); return () => { subscribers.splice(subscribers.indexOf(subscriber), 1); }; }, createEvent(action, uid, properties) { const model = db.metadata.get(uid); return { action, model, ...properties, }; }, async run(action, uid, properties) { for (const subscriber of subscribers) { if (typeof subscriber === 'function') { const event = this.createEvent(action, uid, properties); await subscriber(event); continue; } const hasAction = action in subscriber; const hasModel = !subscriber.models || subscriber.models.includes(uid); if (hasAction && hasModel) { const event = this.createEvent(action, uid, properties); await subscriber[action](event); } } }, clear() { subscribers = []; }, }; return lifecycleManager; }; module.exports = { createLifecyclesManager, };
Fix return in for loop instead of continue
Fix return in for loop instead of continue
JavaScript
mit
wistityhq/strapi,wistityhq/strapi
--- +++ @@ -27,7 +27,8 @@ for (const subscriber of subscribers) { if (typeof subscriber === 'function') { const event = this.createEvent(action, uid, properties); - return await subscriber(event); + await subscriber(event); + continue; } const hasAction = action in subscriber;
3789c3c739f450188cdb50ffd25fe3099f8b458c
react/components/UI/LoadingIndicator/index.js
react/components/UI/LoadingIndicator/index.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { space, width, height } from 'styled-system'; import { preset } from 'react/styles/functions'; import Text from 'react/components/UI/Text'; const Container = styled.div` box-sizing: border-box; display: flex; flex: 1; align-items: center; justify-content: center; user-select: none; ${space} ${preset(width, { width: '100%' })} ${preset(height, { height: '100%' })} `; export default class LoadingIndicator extends Component { static propTypes = { frames: PropTypes.arrayOf(PropTypes.string), interval: PropTypes.number, } static defaultProps = { frames: [ '·', '··', '···', ], interval: 175, } state = { cursor: 0, } componentDidMount() { this.interval = setInterval(() => { this.setState(({ cursor }) => ({ cursor: cursor + 1 })); }, this.props.interval); } componentWillUnmount() { clearInterval(this.interval); } render() { const { cursor } = this.state; const { frames, ...rest } = this.props; return ( <Container {...rest}> <Text f={7} color="gray.base"> {frames[cursor % frames.length]} </Text> </Container> ); } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { space, width, height } from 'styled-system'; import { preset } from 'react/styles/functions'; import Text from 'react/components/UI/Text'; const Container = styled.div` box-sizing: border-box; display: flex; flex: 1; align-items: center; justify-content: center; user-select: none; ${space} ${preset(width, { width: '100%' })} ${preset(height, { height: '100%' })} `; export default class LoadingIndicator extends Component { static propTypes = { frames: PropTypes.arrayOf(PropTypes.string), interval: PropTypes.number, f: PropTypes.number, color: PropTypes.string, } static defaultProps = { frames: [ '·', '··', '···', ], interval: 175, f: 7, color: 'gray.base', } state = { cursor: 0, } componentDidMount() { this.interval = setInterval(() => { this.setState(({ cursor }) => ({ cursor: cursor + 1 })); }, this.props.interval); } componentWillUnmount() { clearInterval(this.interval); } render() { const { cursor } = this.state; const { frames, f, color, ...rest } = this.props; return ( <Container {...rest}> <Text f={f} color={color}> {frames[cursor % frames.length]} </Text> </Container> ); } }
Support color/font size in loading indicator
Support color/font size in loading indicator
JavaScript
mit
aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell
--- +++ @@ -14,7 +14,6 @@ align-items: center; justify-content: center; user-select: none; - ${space} ${preset(width, { width: '100%' })} ${preset(height, { height: '100%' })} @@ -24,6 +23,8 @@ static propTypes = { frames: PropTypes.arrayOf(PropTypes.string), interval: PropTypes.number, + f: PropTypes.number, + color: PropTypes.string, } static defaultProps = { @@ -33,6 +34,8 @@ '···', ], interval: 175, + f: 7, + color: 'gray.base', } state = { @@ -51,11 +54,13 @@ render() { const { cursor } = this.state; - const { frames, ...rest } = this.props; + const { + frames, f, color, ...rest + } = this.props; return ( <Container {...rest}> - <Text f={7} color="gray.base"> + <Text f={f} color={color}> {frames[cursor % frames.length]} </Text> </Container>
753c56b41f2d7564dd660995d24606f17b0ffbbd
assets/src/stories-editor/helpers/test/addAMPExtraProps.js
assets/src/stories-editor/helpers/test/addAMPExtraProps.js
/** * Internal dependencies */ import { addAMPExtraProps } from '../'; describe( 'addAMPExtraProps', () => { it( 'does not modify non-child blocks', () => { const props = addAMPExtraProps( {}, { name: 'foo/bar' }, {} ); expect( props ).toStrictEqual( {} ); } ); it( 'generates a unique ID', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, {} ); expect( props ).toHaveProperty( 'id' ); } ); it( 'uses the existing anchor attribute as the ID', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { anchor: 'foo' } ); expect( props ).toStrictEqual( { id: 'foo' } ); } ); it( 'adds a font family attribute', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { ampFontFamily: 'Roboto' } ); expect( props ).toMatchObject( { 'data-font-family': 'Roboto' } ); } ); it( 'adds inline CSS for rotation', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { rotationAngle: 90.54321 } ); expect( props ).toMatchObject( { style: { transform: 'rotate(90deg)' } } ); } ); } );
/** * Internal dependencies */ import { addAMPExtraProps } from '../'; describe( 'addAMPExtraProps', () => { it( 'does not modify non-child blocks', () => { const props = addAMPExtraProps( {}, { name: 'foo/bar' }, {} ); expect( props ).toStrictEqual( {} ); } ); it( 'adds a font family attribute', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { ampFontFamily: 'Roboto' } ); expect( props ).toMatchObject( { 'data-font-family': 'Roboto' } ); } ); it( 'adds inline CSS for rotation', () => { const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { rotationAngle: 90.54321 } ); expect( props ).toMatchObject( { style: { transform: 'rotate(90deg)' } } ); } ); } );
Remove tests that are not relevant anymore.
Remove tests that are not relevant anymore.
JavaScript
apache-2.0
ampproject/amp-toolbox-php,ampproject/amp-toolbox-php
--- +++ @@ -8,18 +8,6 @@ const props = addAMPExtraProps( {}, { name: 'foo/bar' }, {} ); expect( props ).toStrictEqual( {} ); - } ); - - it( 'generates a unique ID', () => { - const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, {} ); - - expect( props ).toHaveProperty( 'id' ); - } ); - - it( 'uses the existing anchor attribute as the ID', () => { - const props = addAMPExtraProps( {}, { name: 'amp/amp-story-text' }, { anchor: 'foo' } ); - - expect( props ).toStrictEqual( { id: 'foo' } ); } ); it( 'adds a font family attribute', () => {
0a77c621aed25a004b0347bf8adfdf1888dc554f
app-frontend/src/app/components/channelHistogram/channelHistogram.controller.js
app-frontend/src/app/components/channelHistogram/channelHistogram.controller.js
export default class ChannelHistogramController { constructor() { 'ngInject'; } $onInit() { this.histOptions = { chart: { type: 'lineChart', showLegend: false, showXAxis: false, showYAxis: false, margin: { top: 0, right: 0, bottom: 0, left: 0 }, xAxis: { showLabel: false }, yAxis: { showLabel: false } } }; if (this.data) { this.histData = Array.from(this.data); } } $onChanges(changesObj) { if ('data' in changesObj && changesObj.data.currentValue) { this.histData = Array.from(changesObj.data.currentValue); } } }
export default class ChannelHistogramController { constructor() { 'ngInject'; } $onInit() { this.histOptions = { chart: { type: 'lineChart', showLegend: false, showXAxis: false, showYAxis: false, interactive: false, margin: { top: 0, right: 0, bottom: 0, left: 0 }, xAxis: { showLabel: false }, yAxis: { showLabel: false } } }; if (this.data) { this.histData = Array.from(this.data); } } $onChanges(changesObj) { if ('data' in changesObj && changesObj.data.currentValue) { this.histData = Array.from(changesObj.data.currentValue); } } }
Remove interactivity from cc histogram
Remove interactivity from cc histogram
JavaScript
apache-2.0
azavea/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,aaronxsu/raster-foundry,aaronxsu/raster-foundry,raster-foundry/raster-foundry,raster-foundry/raster-foundry,aaronxsu/raster-foundry,aaronxsu/raster-foundry,azavea/raster-foundry,azavea/raster-foundry,raster-foundry/raster-foundry
--- +++ @@ -10,6 +10,7 @@ showLegend: false, showXAxis: false, showYAxis: false, + interactive: false, margin: { top: 0, right: 0,
f3d1753ded9f0ecf6c88252db1efa652e2ab632f
app/App.js
app/App.js
import React, { PropTypes } from 'react'; import { Link, IndexLink } from 'react-router'; import { Login } from 'auth'; import { ErrorHandler } from 'error'; import { rendered } from 'lib/fetchData'; export default class App extends React.Component { static propTypes = { children: PropTypes.object, }; componentDidMount() { rendered(); } render() { return ( <div id="main-view"> <IndexLink to="/">About</IndexLink> {' '} <Link to="/todos">Todos</Link> <hr /> <Login /> <hr /> <ErrorHandler> {this.props.children} </ErrorHandler> </div> ); } }
import React, { PropTypes } from 'react'; import { Link, IndexLink } from 'react-router'; import { Login } from 'auth'; import { ErrorHandler } from 'error'; import { rendered } from 'lib/fetchData'; export default class App extends React.Component { static propTypes = { children: PropTypes.object, }; componentDidMount() { /* This is one of the most important lines of the app, * it is where we start triggering loading of data * on the client-side */ rendered(); } render() { return ( <div id="main-view"> <IndexLink to="/">About</IndexLink> {' '} <Link to="/todos">Todos</Link> <hr /> <Login /> <hr /> <ErrorHandler> {this.props.children} </ErrorHandler> </div> ); } }
Add comment as to how important the call to render() is
Add comment as to how important the call to render() is
JavaScript
mit
terribleplan/isomorphic-redux-plus,isogon/isomorphic-redux-plus
--- +++ @@ -11,6 +11,10 @@ }; componentDidMount() { + /* This is one of the most important lines of the app, + * it is where we start triggering loading of data + * on the client-side + */ rendered(); }
ffeca8d1b1e312864f75e859babbc3a5abb53d8f
web/gulpfile.babel.js
web/gulpfile.babel.js
import bg from 'gulp-bg'; import eslint from 'gulp-eslint'; import gulp from 'gulp'; import runSequence from 'run-sequence'; import webpackBuild from './webpack/build'; const runEslint = () => { return gulp.src([ 'gulpfile.babel.js', 'src/**/*.js', 'webpack/*.js' // '!**/__tests__/*.*' ]) .pipe(eslint()) .pipe(eslint.format()); }; // Always use Gulp only in development gulp.task('set-dev-environment', () => { process.env.NODE_ENV = 'development'; // eslint-disable-line no-undef }); gulp.task('build', webpackBuild); gulp.task('eslint', () => { return runEslint(); }); gulp.task('eslint-ci', () => { // Exit process with an error code (1) on lint error for CI build. return runEslint().pipe(eslint.failAfterError()); }); gulp.task('test', (done) => { runSequence('eslint-ci', 'build', done); }); gulp.task('server-hot', bg('node', './webpack/server')); gulp.task('server', ['set-dev-environment', 'server-hot'], bg('./node_modules/.bin/nodemon', './src/server')); gulp.task('default', ['server']);
import bg from 'gulp-bg'; import eslint from 'gulp-eslint'; import gulp from 'gulp'; import runSequence from 'run-sequence'; import webpackBuild from './webpack/build'; import os from 'os'; const runEslint = () => { return gulp.src([ 'gulpfile.babel.js', 'src/**/*.js', 'webpack/*.js' // '!**/__tests__/*.*' ]) .pipe(eslint()) .pipe(eslint.format()); }; // Always use Gulp only in development gulp.task('set-dev-environment', () => { process.env.NODE_ENV = 'development'; // eslint-disable-line no-undef }); gulp.task('build', webpackBuild); gulp.task('eslint', () => { return runEslint(); }); gulp.task('eslint-ci', () => { // Exit process with an error code (1) on lint error for CI build. return runEslint().pipe(eslint.failAfterError()); }); gulp.task('test', (done) => { runSequence('eslint-ci', 'build', done); }); gulp.task('server-hot', bg('node', './webpack/server')); gulp.task('server', ['set-dev-environment', 'server-hot'], bg( os.type() == 'Windows_NT' ? '.\\node_modules\\.bin\\nodemon.cmd' : './node_modules/.bin/nodemon', './src/server')); gulp.task('default', ['server']);
Fix gulp nodemon commang for windows environments
Fix gulp nodemon commang for windows environments original fix by @mannro
JavaScript
mit
Brainfock/este
--- +++ @@ -3,6 +3,7 @@ import gulp from 'gulp'; import runSequence from 'run-sequence'; import webpackBuild from './webpack/build'; +import os from 'os'; const runEslint = () => { return gulp.src([ @@ -37,6 +38,7 @@ gulp.task('server-hot', bg('node', './webpack/server')); -gulp.task('server', ['set-dev-environment', 'server-hot'], bg('./node_modules/.bin/nodemon', './src/server')); +gulp.task('server', ['set-dev-environment', 'server-hot'], bg( + os.type() == 'Windows_NT' ? '.\\node_modules\\.bin\\nodemon.cmd' : './node_modules/.bin/nodemon', './src/server')); gulp.task('default', ['server']);
981d520b780cbe87d05bca2448d6495ee15650aa
js/console-notes.js
js/console-notes.js
/** * Handles writting the notes to the browser console in synchronization with the reveal.js */ var ConsoleNotes = (function() { function log(event) { // event.previousSlide, event.currentSlide, event.indexh, event.indexv var notes = event.currentSlide.querySelector(".notes"); if (notes) { console.info(notes.innerHTML.replace(/\n\s+/g, "\n")); } } // Fires when reveal.js has loaded all (synchronous) dependencies and is ready to start navigating Reveal.addEventListener("ready", log); // Fires when slide is changed Reveal.addEventListener("slidechanged", log); })();
/** * Handles writting the notes to the browser console in synchronization with the reveal.js */ var ConsoleNotes = (function() { function log(event) { // event.previousSlide, event.currentSlide, event.indexh, event.indexv var notes = event.currentSlide.querySelector(".notes"); if (notes) { console.info(notes.innerHTML.replace(/\n\s+/g, "\n")); } } // Fires when reveal.js has loaded all (synchronous) dependencies and is ready to start navigating //Reveal.addEventListener("ready", log); // Fires when slide is changed Reveal.addEventListener("slidechanged", log); })();
Remove load event handler for browser console speaker notes plugin
Remove load event handler for browser console speaker notes plugin
JavaScript
mit
itkoren/revealular,itkoren/revealular
--- +++ @@ -13,7 +13,7 @@ } // Fires when reveal.js has loaded all (synchronous) dependencies and is ready to start navigating - Reveal.addEventListener("ready", log); + //Reveal.addEventListener("ready", log); // Fires when slide is changed Reveal.addEventListener("slidechanged", log);
cd3230171aa42b3eb574da1d06c0488face95001
tests/dummy/app/snippets/config-bootstrap-v4.js
tests/dummy/app/snippets/config-bootstrap-v4.js
const ENV = { // ... "ember-validated-form": { label: { submit: "Go for it!" }, css: { // bootstrap classes group: "form-group", radio: "radio", control: "form-control", label: "col-form-label", help: "small form-text text-danger", hint: "small form-text text-muted", checkbox: "checkbox", button: "btn btn-default", submit: "btn btn-primary", loading: "loading", valid: "is-valid", invalid: "is-invalid" } } // ... };
const ENV = { // ... "ember-validated-form": { label: { submit: "Go for it!" }, css: { // bootstrap classes group: "form-group", radio: "radio", control: "form-control", label: "col-form-label", help: "small form-text text-danger", hint: "small form-text text-muted", checkbox: "checkbox", button: "btn btn-default", submit: "btn btn-primary", loading: "loading", valid: "is-valid", error: "is-invalid" } } // ... };
Update bootstrap 4 config error class
Update bootstrap 4 config error class The error class used in `error`, not `invalid`.
JavaScript
mit
adfinis-sygroup/ember-validated-form,adfinis-sygroup/ember-validated-form,adfinis-sygroup/ember-validated-form
--- +++ @@ -17,7 +17,7 @@ submit: "btn btn-primary", loading: "loading", valid: "is-valid", - invalid: "is-invalid" + error: "is-invalid" } } // ...
66ce8257b0164f8618b53d2fbe15bda4fa73fb33
src/prototype/off.js
src/prototype/off.js
define([ 'jquery', 'var/eventStorage', 'prototype/var/EmojioneArea' ], function($, eventStorage, EmojioneArea) { EmojioneArea.prototype.off = function(events, handler) { if (events) { var id = this.id; $.each(events.toLowerCase().replace(/_/g, '.').split(' '), function(i, event) { if (eventStorage[id][event] && !/^@/.test(event)) { if (handler) { $.each(eventStorage[id][event], function(j, fn) { if (fn === handler) { eventStorage[id][event] = eventStorage[id][event].splice(j, 1); } }); } else { eventStorage[id][event] = []; } } }); } return this; }; });
define([ 'jquery', 'var/eventStorage', 'prototype/var/EmojioneArea' ], function($, eventStorage, EmojioneArea) { EmojioneArea.prototype.off = function(events, handler) { if (events) { var id = this.id; $.each(events.toLowerCase().replace(/_/g, '.').split(' '), function(i, event) { if (eventStorage[id][event] && !/^@/.test(event)) { if (handler) { $.each(eventStorage[id][event], function(j, fn) { if (fn === handler) { eventStorage[id][event].splice(j, 1); } }); } else { eventStorage[id][event] = []; } } }); } return this; }; });
Fix typo which causes memory leak.
Fix typo which causes memory leak.
JavaScript
mit
mervick/emojionearea
--- +++ @@ -12,7 +12,7 @@ if (handler) { $.each(eventStorage[id][event], function(j, fn) { if (fn === handler) { - eventStorage[id][event] = eventStorage[id][event].splice(j, 1); + eventStorage[id][event].splice(j, 1); } }); } else {
45255860bc78e5a90d7f6b3938c213628d8d6609
lib/bin.js
lib/bin.js
#!/usr/bin/env node var argv = require('argv'); var polyjuice = require('./polyjuice'); var options = [ { name: 'jshint', type: 'string', description: 'Defines the source file for jshint', example: '\'polyjuice --jshint .jshintrc\'' }, { name: 'jscs', type: 'string', description: 'Defines the source file for jscs', example: '\'polyjuice --jscs .jscsrc\'' } ]; var src = argv.option(options).run(); var output = {}; if (src.options.jshint && src.options.jscs) { output = polyjuice.to.eslint(src.options.jshint, src.options.jscs); } else if (src.options.jshint) { output = polyjuice.from.jshint(src.options.jshint); } else if (src.options.jscs) { output = polyjuice.from.jscs(src.options.jscs); } console.log(JSON.stringify(output, null, 2));
#!/usr/bin/env node var argv = require('argv'); var polyjuice = require('./polyjuice'); var options = [ { name: 'jshint', type: 'string', description: 'Defines the source file for jshint', example: '\'polyjuice --jshint=.jshintrc\'' }, { name: 'jscs', type: 'string', description: 'Defines the source file for jscs', example: '\'polyjuice --jscs=.jscsrc\'' } ]; var src = argv.option(options).run(); var output = {}; if (src.options.jshint && src.options.jscs) { output = polyjuice.to.eslint(src.options.jshint, src.options.jscs); } else if (src.options.jshint) { output = polyjuice.from.jshint(src.options.jshint); } else if (src.options.jscs) { output = polyjuice.from.jscs(src.options.jscs); } console.log(JSON.stringify(output, null, 2));
Fix --help examples to include '='
Fix --help examples to include '=' Fixes #9
JavaScript
mit
brenolf/polyjuice
--- +++ @@ -8,13 +8,13 @@ name: 'jshint', type: 'string', description: 'Defines the source file for jshint', - example: '\'polyjuice --jshint .jshintrc\'' + example: '\'polyjuice --jshint=.jshintrc\'' }, { name: 'jscs', type: 'string', description: 'Defines the source file for jscs', - example: '\'polyjuice --jscs .jscsrc\'' + example: '\'polyjuice --jscs=.jscsrc\'' } ];
07059d2cc11db8cdddedc82de931c2c80d4faff4
lib/cli.js
lib/cli.js
'use strict'; const _ = require('lodash'); const updateNotifier = require('update-notifier'); /** * Expose a CLI with given actions as subcommands * @param {Array} actions Array of subclasses of Action * @param {Object} pkg The package.json contents * @returns {Array} */ module.exports = function (actions, pkg) { updateNotifier({pkg}).notify(); const yargs = require('yargs').usage('$0 <cmd> [args]'); _.each(actions, Action => (new Action()).register(yargs)); return yargs .help('h') .version() .alias('h', 'help') .alias('v', 'version') .argv; };
'use strict'; const _ = require('lodash'); const updateNotifier = require('update-notifier'); /** * Expose a CLI with given actions as subcommands * @param {Array} actions Array of subclasses of Action * @param {Object} pkg The package.json contents * @returns {Array} */ module.exports = function (actions, pkg) { updateNotifier({pkg}).notify(); const yargs = require('yargs').usage('$0 <cmd> [args]'); _.each(actions, Action => (new Action()).register(yargs)); return yargs .help('h') .version() .alias('h', 'help') .argv; };
Fix error caused by aliasing "v" to "version" on yargs
Fix error caused by aliasing "v" to "version" on yargs
JavaScript
mit
launchdeckio/shipment
--- +++ @@ -21,6 +21,5 @@ .help('h') .version() .alias('h', 'help') - .alias('v', 'version') .argv; };
0785140b62ddd655c4f472a157022b2c5a11164d
lib/git.js
lib/git.js
const spawn = require("./spawn"); module.exports = function(workDir, isDebug){ function git() { var len = arguments.length; var args = new Array(len); for (var i = 0; i < len; i++) { args[i] = arguments[i]; } return spawn('git', args, { cwd: workDir, verbose: isDebug }); } return function pullFetchRebasePush(forkedRepoUrl, sourceRepoUrl, forkedDefaultBranch, sourceDefaultBranch) { return git('init') .then(() => git('remote', 'add', 'origin', forkedRepoUrl)) .then(() => git('pull', 'origin', forkedDefaultBranch)) .then(() => git('remote', 'add', 'upstream', sourceRepoUrl)) .then(() => git('fetch', 'upstream')) .then(() => git('checkout', 'origin/' + forkedDefaultBranch)) .then(() => git('merge', 'upstream/' + sourceDefaultBranch)) .then(() => git('push', 'origin', 'HEAD:' + forkedDefaultBranch, '--force')) .catch((err) => console.log(err)); } }
const spawn = require("./spawn"); module.exports = function(workDir, isDebug){ function git() { var len = arguments.length; var args = new Array(len); for (var i = 0; i < len; i++) { args[i] = arguments[i]; } return spawn('git', args, { cwd: workDir, verbose: isDebug }); } return function pullFetchRebasePush(forkedRepoUrl, sourceRepoUrl, forkedDefaultBranch, sourceDefaultBranch) { return git('init') .then(() => git('remote', 'add', 'origin', forkedRepoUrl)) .then(() => git('pull', 'origin', forkedDefaultBranch)) .then(() => git('remote', 'add', 'upstream', sourceRepoUrl)) .then(() => git('fetch', 'upstream')) .then(() => git('checkout', 'origin/' + forkedDefaultBranch)) .then(() => git('merge', 'upstream/' + sourceDefaultBranch)) .then(() => git('push', 'origin', 'HEAD:' + forkedDefaultBranch)) .catch((err) => console.log(err)); } }
Remove force as it may overwrite somthing unwanted.
Remove force as it may overwrite somthing unwanted.
JavaScript
bsd-3-clause
NoahDragon/update-forked-repo
--- +++ @@ -23,7 +23,7 @@ .then(() => git('fetch', 'upstream')) .then(() => git('checkout', 'origin/' + forkedDefaultBranch)) .then(() => git('merge', 'upstream/' + sourceDefaultBranch)) - .then(() => git('push', 'origin', 'HEAD:' + forkedDefaultBranch, '--force')) + .then(() => git('push', 'origin', 'HEAD:' + forkedDefaultBranch)) .catch((err) => console.log(err)); } }
554d3977a180989956124761c4178fc01f69ed78
lib/client/hooks.js
lib/client/hooks.js
Router.hooks = { dataNotFound: function (pause) { var data = this.data(); var tmpl; if (data === null || typeof data === 'undefined') { tmpl = this.lookupProperty('notFoundTemplate'); if (tmpl) { this.render(tmpl); this.renderRegions(); pause(); } } }, loading: function (pause) { var self = this; var tmpl; if (!this.ready()) { tmpl = this.lookupProperty('loadingTemplate'); if (tmpl) { this.render(tmpl); this.renderRegions(); pause(); } } } };
Router.hooks = { dataNotFound: function (pause) { var data = this.data(); var tmpl; if (!this.ready()) return; if (data === null || typeof data === 'undefined') { tmpl = this.lookupProperty('notFoundTemplate'); if (tmpl) { this.render(tmpl); this.renderRegions(); pause(); } } }, loading: function (pause) { var self = this; var tmpl; if (!this.ready()) { tmpl = this.lookupProperty('loadingTemplate'); if (tmpl) { this.render(tmpl); this.renderRegions(); pause(); } } } };
Make dataNotFoundHook return if data not ready.
Make dataNotFoundHook return if data not ready.
JavaScript
mit
firdausramlan/iron-router,Aaron1992/iron-router,TechplexEngineer/iron-router,abhiaiyer91/iron-router,tianzhihen/iron-router,ecuanaso/iron-router,DanielDornhardt/iron-router-2,Aaron1992/iron-router,jg3526/iron-router,assets1975/iron-router,leoetlino/iron-router,TechplexEngineer/iron-router,Sombressoul/iron-router,appoets/iron-router,firdausramlan/iron-router,tianzhihen/iron-router,DanielDornhardt/iron-router-2,Hyparman/iron-router,Sombressoul/iron-router,iron-meteor/iron-router,sean-stanley/iron-router,snamoah/iron-router,assets1975/iron-router,sean-stanley/iron-router,iron-meteor/iron-router,abhiaiyer91/iron-router,jg3526/iron-router,appoets/iron-router,snamoah/iron-router,Hyparman/iron-router,ecuanaso/iron-router
--- +++ @@ -2,6 +2,9 @@ dataNotFound: function (pause) { var data = this.data(); var tmpl; + + if (!this.ready()) + return; if (data === null || typeof data === 'undefined') { tmpl = this.lookupProperty('notFoundTemplate');
37b8b0c2a0c887b942653eaa832c5c4d15e3b205
test/Client.connect.js
test/Client.connect.js
var Client = require('../index').Client; var Transport = require('./mock/Transport'); var OutgoingFrameStream = require('./mock/OutgoingFrameStream'); var assert = require('assert'); describe('Client.connect', function() { var client, transport, framesOut, framesIn; beforeEach(function() { transport = new Transport(); framesOut = new OutgoingFrameStream(); client = new Client(transport, { outgoingFrameStream: framesOut }); }); it('should send a CONNECT frame and include accept-version header', function(done) { client.connect(); assert(framesOut._frames[0]); var frame = framesOut._frames[0]; assert.equal(frame.command, 'CONNECT'); assert('accept-version' in frame.headers); assert.equal(frame._finished, true); assert.equal(frame._body.length, 0); done(); }); });
var Client = require('../index').Client; var Transport = require('./mock/Transport'); var OutgoingFrameStream = require('./mock/OutgoingFrameStream'); var assert = require('assert'); describe('Client.connect', function() { var client, transport, framesOut, framesIn; beforeEach(function() { transport = new Transport(); framesOut = new OutgoingFrameStream(); client = new Client(transport, { outgoingFrameStream: framesOut }); }); it('should send a CONNECT frame and include accept-version header', function(done) { client.connect(); assert(framesOut._frames[0]); var frame = framesOut._frames[0]; assert.equal(frame.command, 'CONNECT'); assert('accept-version' in frame.headers); assert.equal(frame._finished, true); assert.equal(frame._body.length, 0); done(); }); it('should parse the heart-beat header and call setHeartbeat', function(done) { client.connect({ 'heart-beat': '1,2' }); var heartbeat = client.getHeartbeat(); assert.equal(heartbeat[0], 1); assert.equal(heartbeat[1], 2); assert.equal(framesOut._frames[0].headers['heart-beat'], '1,2'); done(); }); });
Test for heart-beat header handling
Test for heart-beat header handling
JavaScript
mit
gdaws/node-stomp
--- +++ @@ -35,4 +35,19 @@ done(); }); + it('should parse the heart-beat header and call setHeartbeat', function(done) { + + client.connect({ + 'heart-beat': '1,2' + }); + + var heartbeat = client.getHeartbeat(); + + assert.equal(heartbeat[0], 1); + assert.equal(heartbeat[1], 2); + + assert.equal(framesOut._frames[0].headers['heart-beat'], '1,2'); + + done(); + }); });
fa6f1f516775a84db71769b07f11fd23d5b39f7e
addon/helpers/-ui-component-class.js
addon/helpers/-ui-component-class.js
import Ember from 'ember'; export default Ember.Helper.helper(function ([prefix, ...classNames]) { var classString = ''; classNames.forEach(function(name) { if (!name) return; var trimmedName = name.replace(/\s/g, ''); if (trimmedName === '') return; if (trimmedName === ':component') { classString += `${prefix} `; } else { classString += `${prefix}${trimmedName} `; } }); return classString; });
import Ember from 'ember'; const FONT_SIZE_PATTERN = /font-size/; export default Ember.Helper.helper(function ([prefix, ...classNames]) { return classNames.reduce(function(string, name) { if (!name) return string; let trimmedName = name.replace(/\s/g, ''); if (trimmedName === '') return string; switch (true) { case (trimmedName === ':component'): return string += `${prefix} `; case (FONT_SIZE_PATTERN.test(trimmedName)): return string += `${trimmedName} `; default: return string += `${prefix}${trimmedName} `; } }, ''); });
Whitelist font-size classes from prefixing
Whitelist font-size classes from prefixing
JavaScript
mit
prototypal-io/untitled-ui,prototypal-io/untitled-ui,prototypal-io/ui-base-theme,prototypal-io/ui-base-theme
--- +++ @@ -1,20 +1,21 @@ import Ember from 'ember'; +const FONT_SIZE_PATTERN = /font-size/; + export default Ember.Helper.helper(function ([prefix, ...classNames]) { - var classString = ''; + return classNames.reduce(function(string, name) { + if (!name) return string; - classNames.forEach(function(name) { - if (!name) return; + let trimmedName = name.replace(/\s/g, ''); + if (trimmedName === '') return string; - var trimmedName = name.replace(/\s/g, ''); - if (trimmedName === '') return; - - if (trimmedName === ':component') { - classString += `${prefix} `; - } else { - classString += `${prefix}${trimmedName} `; + switch (true) { + case (trimmedName === ':component'): + return string += `${prefix} `; + case (FONT_SIZE_PATTERN.test(trimmedName)): + return string += `${trimmedName} `; + default: + return string += `${prefix}${trimmedName} `; } - }); - - return classString; + }, ''); });
f0aad1536f204a108876fea8bbda7aa8ba102749
server/mappings/windowslive.js
server/mappings/windowslive.js
module.exports = profile => { return { uid: profile.username || profile.id, mail: profile.emails && profile.emails[0] && profile.emails[0].value, cn: profile.displayName, displayName: profile.displayName, givenName: profile.name.familyName, sn: profile.name.givenName } }
module.exports = profile => { return { uid: profile.username || profile.id, mail: profile.emails && profile.emails[0] && profile.emails[0].value, cn: profile.displayName, displayName: profile.displayName, givenName: profile.name.givenName, sn: profile.name.familyName } }
Fix typo in windows live mapping
Fix typo in windows live mapping
JavaScript
apache-2.0
GluuFederation/gluu-passport,GluuFederation/gluu-passport
--- +++ @@ -4,7 +4,7 @@ mail: profile.emails && profile.emails[0] && profile.emails[0].value, cn: profile.displayName, displayName: profile.displayName, - givenName: profile.name.familyName, - sn: profile.name.givenName + givenName: profile.name.givenName, + sn: profile.name.familyName } }
3617df199a77a9758b391615ec12e6ab0ae6362e
content.js
content.js
// Obtain ALL anchors on the page. var links = document.links; // The previous/next urls if they exist. var prev = findHref("prev"); var next = findHref("next"); /** * Find the href for a given name. * @param {String} The name of the anchor to search for. * @return {String} The href for a given tag, otherwise an empty string. */ function findHref(name) { for (var index = 0; index < links.length; ++index) { // The complete anchor HTML element (<a>). var anchor = links[index]; // Not all anchors have text, rels or classes defined. var rel = (anchor.rel !== undefined) ? anchor.rel : ''; var text = (anchor.text !== undefined) ? anchor.text.toLowerCase() : ''; var class_name = (anchor.className !== undefined) ? anchor.className : ''; if (rel.indexOf(name) > -1 || text.indexOf(name) > -1 || class_name.indexOf(name) > -1) { return anchor.href; } } } // Go to the next/previous pages using the arrow keys. document.addEventListener('keydown', function(event) { if(event.keyCode == 37) { if (prev) chrome.extension.sendMessage({redirect: prev}); } else if(event.keyCode == 39) { if (next) chrome.extension.sendMessage({redirect: next}); } });
// Obtain ALL anchors on the page. var links = document.links; // The previous/next urls if they exist. var prev = findHref("prev"); var next = findHref("next"); /** * Find the href for a given name. * @param {String} name - The name of the anchor to search for. * @return {String} The href for a given tag, otherwise an empty string. */ function findHref(name) { for (var index = 0; index < links.length; ++index) { // The complete anchor HTML element (<a>). var anchor = links[index]; // Does the name exist in the anchor? if (isNameInAnchor(name, anchor.rel) || isNameInAnchor(name, anchor.text.toLowerCase()) || isNameInAnchor(name, anchor.className)) { return anchor.href } } } /** * Does the word exist in a given element? * @param {String} name - The name to search for. * @param {String} element - The element to search in. * @return {Boolean} True if the name exists in the element, otherwise false. */ function isNameInAnchor(name, element) { if (element !== undefined && element.indexOf(name) > -1) return true; else return false } // Go to the next/previous pages using the arrow keys. document.addEventListener('keydown', function(event) { if(event.keyCode == 37) { if (prev) chrome.extension.sendMessage({redirect: prev}); } else if(event.keyCode == 39) { if (next) chrome.extension.sendMessage({redirect: next}); } });
Refactor repeated checking to a helper method.
Refactor repeated checking to a helper method.
JavaScript
mit
jawrainey/leftyrighty
--- +++ @@ -7,21 +7,32 @@ /** * Find the href for a given name. - * @param {String} The name of the anchor to search for. + * @param {String} name - The name of the anchor to search for. * @return {String} The href for a given tag, otherwise an empty string. */ function findHref(name) { for (var index = 0; index < links.length; ++index) { // The complete anchor HTML element (<a>). var anchor = links[index]; - // Not all anchors have text, rels or classes defined. - var rel = (anchor.rel !== undefined) ? anchor.rel : ''; - var text = (anchor.text !== undefined) ? anchor.text.toLowerCase() : ''; - var class_name = (anchor.className !== undefined) ? anchor.className : ''; - if (rel.indexOf(name) > -1 || text.indexOf(name) > -1 || class_name.indexOf(name) > -1) { - return anchor.href; + // Does the name exist in the anchor? + if (isNameInAnchor(name, anchor.rel) || + isNameInAnchor(name, anchor.text.toLowerCase()) || + isNameInAnchor(name, anchor.className)) + { + return anchor.href } } +} + +/** + * Does the word exist in a given element? + * @param {String} name - The name to search for. + * @param {String} element - The element to search in. + * @return {Boolean} True if the name exists in the element, otherwise false. + */ +function isNameInAnchor(name, element) { + if (element !== undefined && element.indexOf(name) > -1) return true; + else return false } // Go to the next/previous pages using the arrow keys.
394ccb91c645cab13fbd2681cfdac3dd3bbaa602
app/contentModule.js
app/contentModule.js
app.module("ContentModule", function(ContentModule, app){ ContentModule.listTemplate = "<div>List</div>"; ContentModule.showTemplate = "<div>Show <%= id %></div>"; ContentModule.ListView = Marionette.ItemView.extend({ template: _.template(ContentModule.listTemplate), className: 'content list' }); ContentModule.ShowView = Marionette.ItemView.extend({ template: _.template(ContentModule.showTemplate), className: 'content show' }); ContentModule.Controller = Marionette.Controller.extend({ displayList: function() { app.content.show(new ContentModule.ListView()); }, displayShow: function(id) { app.content.show(new ContentModule.ShowView({ model: new Backbone.Model({id: id}) })); } }); ContentModule.addInitializer(function() { ContentModule.controller = new ContentModule.Controller(); }); ContentModule.Router = Marionette.AppRouter.extend({ appRoutes: { "list": "displayList", "show/:id": "displayShow" } }); ContentModule.addInitializer(function() { new ContentModule.Router({ controller: ContentModule.controller }) }); });
app.module("ContentModule", function(ContentModule, app){ ContentModule.itemTemplate = "Item"; ContentModule.listTemplate = "<div>List</div><ul></ul>"; ContentModule.showTemplate = "<div>Show <%= id %></div>"; ContentModule.ItemView = Marionette.ItemView.extend({ template: _.template(ContentModule.itemTemplate), tagName: 'li', }); ContentModule.ListView = Marionette.CompositeView.extend({ template: _.template(ContentModule.listTemplate), className: 'content list', itemView: ContentModule.ItemView, itemViewContainer: 'ul' }); ContentModule.ShowView = Marionette.ItemView.extend({ template: _.template(ContentModule.showTemplate), className: 'content show' }); ContentModule.Controller = Marionette.Controller.extend({ displayList: function() { app.content.show(new ContentModule.ListView({ collection: new Backbone.Collection([{1:1},{2:2},{3:3}]) })); }, displayShow: function(id) { app.content.show(new ContentModule.ShowView({ model: new Backbone.Model({id: id}) })); } }); ContentModule.addInitializer(function() { ContentModule.controller = new ContentModule.Controller(); }); ContentModule.Router = Marionette.AppRouter.extend({ appRoutes: { "list": "displayList", "show/:id": "displayShow" } }); ContentModule.addInitializer(function() { new ContentModule.Router({ controller: ContentModule.controller }) }); });
Change list view to be a composite view
Change list view to be a composite view
JavaScript
mit
Gerg/marionette-boilerplate
--- +++ @@ -1,10 +1,18 @@ app.module("ContentModule", function(ContentModule, app){ - ContentModule.listTemplate = "<div>List</div>"; + ContentModule.itemTemplate = "Item"; + ContentModule.listTemplate = "<div>List</div><ul></ul>"; ContentModule.showTemplate = "<div>Show <%= id %></div>"; - ContentModule.ListView = Marionette.ItemView.extend({ + ContentModule.ItemView = Marionette.ItemView.extend({ + template: _.template(ContentModule.itemTemplate), + tagName: 'li', + }); + + ContentModule.ListView = Marionette.CompositeView.extend({ template: _.template(ContentModule.listTemplate), - className: 'content list' + className: 'content list', + itemView: ContentModule.ItemView, + itemViewContainer: 'ul' }); ContentModule.ShowView = Marionette.ItemView.extend({ @@ -14,7 +22,9 @@ ContentModule.Controller = Marionette.Controller.extend({ displayList: function() { - app.content.show(new ContentModule.ListView()); + app.content.show(new ContentModule.ListView({ + collection: new Backbone.Collection([{1:1},{2:2},{3:3}]) + })); }, displayShow: function(id) {
e7fba0907c173ee96a277f3d75e894e886f38c5b
markovChain.js
markovChain.js
'use strict'; function randomIntFromInterval(min,max){return Math.floor(Math.random()*(max-min+1)+min);}; var markovGenerator = { order: 2, table:{}, load:function(text){ text = text.toLowerCase(); //text.replace(/[^a-z ]/, ''); for (var i = this.settings.order; i < text.length; i++){ var entry = text.slice(i-this.order, i); if(Array.isArray(this.table[entry])){ this.table[entry].push(text.charAt(i)); }else{ this.table[entry] = [text.charAt(i)]; } } }, generate:function(length, start){ if(length == undefined){ throw 'tooFewArguments'; } if(start == undefined){ var possibleKeys = Object.keys(this.table); start = possibleKeys[randomIntFromInterval(0, possibleKeys.length)]; } var text = start; while(text.length < length){ var key = text.slice(text.length-this.order, text.length); var possibilities = this.table[key]; var letter = possibilities[randomIntFromInterval(0, possibilities.length-1)]; text += letter; } return text; } }
'use strict'; function randomIntFromInterval(min,max){return Math.floor(Math.random()*(max-min+1)+min);}; var markovGenerator = { order: 2, table:{}, load:function(text){ text = text.toLowerCase(); //text.replace(/[^a-z ]/, ''); for (var i = this.order; i < text.length; i++){ var entry = text.slice(i-this.order, i); if(Array.isArray(this.table[entry])){ this.table[entry].push(text.charAt(i)); }else{ this.table[entry] = [text.charAt(i)]; } } }, generate:function(length, start){ if(length == undefined){ throw 'tooFewArguments'; } if(start == undefined){ var possibleKeys = Object.keys(this.table); start = possibleKeys[randomIntFromInterval(0, possibleKeys.length)]; } var text = start; while(text.length < length){ var key = text.slice(text.length-this.order, text.length); var possibilities = this.table[key]; var letter = possibilities[randomIntFromInterval(0, possibilities.length-1)]; text += letter; } return text; } }
Fix for a wrongly named variable introduced when cleaning up
Fix for a wrongly named variable introduced when cleaning up
JavaScript
bsd-3-clause
Albertoni/JavascriptMarkovChain,Albertoni/JavascriptMarkovChain
--- +++ @@ -9,7 +9,7 @@ text = text.toLowerCase(); //text.replace(/[^a-z ]/, ''); - for (var i = this.settings.order; i < text.length; i++){ + for (var i = this.order; i < text.length; i++){ var entry = text.slice(i-this.order, i); if(Array.isArray(this.table[entry])){ this.table[entry].push(text.charAt(i));
1a8061be07063cb673b603ada0e2742e0b3cfa0c
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ connect: { server: { options: { port: 8000, useAvailablePort: true, hostname: '*', keepalive: true } } }, uglify: { dist: { files: { 'dist/angular-local-storage.min.min.js': ['src/angular-local-storage.min.js'] } } } }); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask('start_server', ['connect:server']); grunt.registerTask('dist', ['uglify:dist']); };
module.exports = function(grunt) { grunt.initConfig({ connect: { server: { options: { port: 8000, useAvailablePort: true, hostname: '*', keepalive: true } } }, uglify: { dist: { files: { 'dist/angular-local-storage.min.js': ['src/angular-local-storage.js'] } } } }); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask('start_server', ['connect:server']); grunt.registerTask('dist', ['uglify:dist']); };
Change config uglify task grunt
Change config uglify task grunt
JavaScript
mit
krescruz/angular-local-storage
--- +++ @@ -14,7 +14,7 @@ uglify: { dist: { files: { - 'dist/angular-local-storage.min.min.js': ['src/angular-local-storage.min.js'] + 'dist/angular-local-storage.min.js': ['src/angular-local-storage.js'] } } }
a40f8e8464462e96cf78314098122bef99b2479f
client/src/components/ArticleCard.js
client/src/components/ArticleCard.js
import React from 'react' import {Link} from 'react-router-dom' function setArticleUrl(title) { var sanitizedTitle = title.replace(/%/g, "[percent]") debugger return encodeURIComponent(sanitizedTitle) } const ArticleCard = ({channel, article}) => { return ( <Link to={`/newsfeed/${channel.source_id}/${setArticleUrl(article.title)}`} className="article-link"> <div className="card"> <h3>{article.title}</h3> <img src={article.urlToImage} className="image" alt=""/> </div> </Link> ) } export default ArticleCard
import React from 'react' import {Link} from 'react-router-dom' const ArticleCard = ({channel, article, setArticleUrl}) => { return ( <Link to={`/newsfeed/${channel.source_id}/${setArticleUrl(article.title)}`} className="article-link"> <div className="card"> <h3>{article.title}</h3> <img src={article.urlToImage} className="image" alt=""/> </div> </Link> ) } export default ArticleCard
Move setUrl functoin to parent
Move setUrl functoin to parent
JavaScript
mit
kevinladkins/newsfeed,kevinladkins/newsfeed,kevinladkins/newsfeed
--- +++ @@ -1,13 +1,9 @@ import React from 'react' import {Link} from 'react-router-dom' -function setArticleUrl(title) { - var sanitizedTitle = title.replace(/%/g, "[percent]") - debugger - return encodeURIComponent(sanitizedTitle) -} -const ArticleCard = ({channel, article}) => { + +const ArticleCard = ({channel, article, setArticleUrl}) => { return ( <Link to={`/newsfeed/${channel.source_id}/${setArticleUrl(article.title)}`} className="article-link"> <div className="card">
cb839f6dd5000d1acfb62332344cf4d36e4df676
config/http-get-param-interceptor.js
config/http-get-param-interceptor.js
'use strict'; angular.module('gc.ngHttpGetParamInterceptor', [ 'gc.utils' ]).factory('httpGetParamInterceptor', [ 'utils', function httpGetParamInterceptor(utils) { return { request: function(config) { // Manually build query params using custom logic because Angular and // Rails do not handle nested query parameters in the same way if (config.params) { config.url = config.url + '?' + utils.param(config.params); delete config.params; } return config; } }; } ]);
'use strict'; angular.module('gc.ngHttpGetParamInterceptor', [ 'gc.utils' ]).factory('httpGetParamInterceptor', [ 'utils', function httpGetParamInterceptor(utils) { function deleteUndefinedValues(obj) { _.keys(obj).forEach(function(key) { if (_.isUndefined(obj[key])) { delete obj[key]; } else if (_.isObject(obj[key])) { deleteUndefinedValues(obj[key]); } }); } return { request: function(config) { // Manually build query params using custom logic because Angular and // Rails do not handle nested query parameters in the same way if (config.params) { deleteUndefinedValues(config.params); config.url = config.url + '?' + utils.param(config.params); delete config.params; } return config; } }; } ]);
Revert "Revert "delete undefined properties from http config params""
Revert "Revert "delete undefined properties from http config params"" This reverts commit f2875d45257f892607df8a460b253cd35fb0900a.
JavaScript
mit
gocardless-ng/ng-gc-base-app-service
--- +++ @@ -5,11 +5,23 @@ ]).factory('httpGetParamInterceptor', [ 'utils', function httpGetParamInterceptor(utils) { + + function deleteUndefinedValues(obj) { + _.keys(obj).forEach(function(key) { + if (_.isUndefined(obj[key])) { + delete obj[key]; + } else if (_.isObject(obj[key])) { + deleteUndefinedValues(obj[key]); + } + }); + } + return { request: function(config) { // Manually build query params using custom logic because Angular and // Rails do not handle nested query parameters in the same way if (config.params) { + deleteUndefinedValues(config.params); config.url = config.url + '?' + utils.param(config.params); delete config.params; }
08b96b29e385b58fb09e8c5bc197c17492f1c9d4
examples/test-runner/mocha-controls.js
examples/test-runner/mocha-controls.js
"use strict"; var exampleTests = require('../example-tests'); function Controls(mochaRunner) { this._mochaRunner = mochaRunner; } Controls.prototype = { connectButtons: function(passingButtonId, failingButtonId, manyButtonId) { function connect(id, fn) { document.getElementById(id).addEventListener('click', fn); } connect(passingButtonId, this._postPassingTest.bind(this)); connect(failingButtonId, this._postFailingTest.bind(this)); connect(manyButtonId, this._postManyTests.bind(this)); }, _postPassingTest: function() { this._postTestSourceCode(exampleTests.simplePassingTestCode); }, _postFailingTest: function() { this._postTestSourceCode(exampleTests.simplePassingTestCode); }, _postManyTests: function() { this._postTestSourceCode([ exampleTests.simplePassingTestCode, exampleTests.simplePassingTestCode, exampleTests.simplePassingTestCode, exampleTests.simpleFailingTestCode, exampleTests.simpleFailingTestCode, exampleTests.simplePassingTestCode ].join('\n')); }, _postTestSourceCode: function(sourceCode) { this._mochaRunner.send(sourceCode); } }; module.exports = Controls;
"use strict"; var exampleTests = require('../example-tests'); function Controls(mochaRunner) { this._mochaRunner = mochaRunner; } Controls.prototype = { connectButtons: function(passingButtonId, failingButtonId, manyButtonId) { function connect(id, fn) { document.getElementById(id).addEventListener('click', fn); } connect(passingButtonId, this._postPassingTest.bind(this)); connect(failingButtonId, this._postFailingTest.bind(this)); connect(manyButtonId, this._postManyTests.bind(this)); }, _postPassingTest: function() { this._postTestSourceCode(exampleTests.simplePassingTestCode); }, _postFailingTest: function() { this._postTestSourceCode(exampleTests.simpleFailingTestCode); }, _postManyTests: function() { this._postTestSourceCode([ exampleTests.simplePassingTestCode, exampleTests.simplePassingTestCode, exampleTests.simplePassingTestCode, exampleTests.simpleFailingTestCode, exampleTests.simpleFailingTestCode, exampleTests.simplePassingTestCode ].join('\n')); }, _postTestSourceCode: function(sourceCode) { this._mochaRunner.send(sourceCode); } }; module.exports = Controls;
Use the proper test code.
Use the proper test code.
JavaScript
mit
tddbin/tddbin-frontend,tddbin/tddbin-frontend,tddbin/tddbin-frontend
--- +++ @@ -19,7 +19,7 @@ this._postTestSourceCode(exampleTests.simplePassingTestCode); }, _postFailingTest: function() { - this._postTestSourceCode(exampleTests.simplePassingTestCode); + this._postTestSourceCode(exampleTests.simpleFailingTestCode); }, _postManyTests: function() { this._postTestSourceCode([
d804e831b659c5ad23b398df1f7d9198026d32d6
src/main/webapp/components/BuildSnapshotContainer.js
src/main/webapp/components/BuildSnapshotContainer.js
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { const SOURCE = '/builders'; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE) .then(res => res.json()) .then(json => setData(json)) .catch(setData([])); }, []); return ( <div> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> ); } );
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { const NUMBER = 2; const OFFSET = 3; const SOURCE = `/builders/number=${NUMBER}/offset=${OFFSET}`; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE) .then(res => res.json()) .then(json => setData(json)) .catch(setData([])); }, []); return ( <div> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> ); } );
Update fetch source, add parameters
Update fetch source, add parameters
JavaScript
apache-2.0
googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020
--- +++ @@ -9,7 +9,11 @@ */ export const BuildSnapshotContainer = React.memo((props) => { - const SOURCE = '/builders'; + const NUMBER = 2; + const OFFSET = 3; + + const SOURCE = `/builders/number=${NUMBER}/offset=${OFFSET}`; + const [data, setData] = React.useState([]); /**
bb0c2f4f9f7a227820308f0802c062520b0f6a00
stockflux-launcher/src/app-shortcuts/AppShortcuts.js
stockflux-launcher/src/app-shortcuts/AppShortcuts.js
import React, { useEffect, useState } from 'react'; import { OpenfinApiHelpers } from 'stockflux-core'; import Components from 'stockflux-components'; import './AppShortcuts.css'; export default () => { const [apps, setApps] = useState([]); useEffect(() => { const options = { method: 'GET' }; OpenfinApiHelpers.getCurrentWindow() .then(window => window.getOptions()) .then(options => options.customData.apiBaseUrl) .then(baseUrl => fetch(`${baseUrl}/apps/v1`, options)) .then(response => response.json()) .then(results => { console.log('results', results); setApps(results); }) .catch(console.error); }, []); return ( <div className="app-shortcuts"> {apps .filter( app => app.customConfig !== undefined && app.customConfig.showInLauncher ) .map(app => { /* Get the appropriate shortcut button by taking a part of stocklux appId (e.g. "news", "watchlist", "chart"), capitalizing the first letter and appending "Shortcut" at the end */ const AppShortcut = Components[ app.appId .split('stockflux-')[1] .charAt(0) .toUpperCase() + app.appId.slice(11) + 'Shortcut' ]; return <AppShortcut key={app.appId} app={app} />; })} </div> ); };
import React, { useEffect, useState } from 'react'; import { OpenfinApiHelpers } from 'stockflux-core'; import Components from 'stockflux-components'; import './AppShortcuts.css'; export default () => { const [apps, setApps] = useState([]); useEffect(() => { const options = { method: 'GET' }; OpenfinApiHelpers.getCurrentWindow() .then(window => window.getOptions()) .then(options => options.customData.apiBaseUrl) .then(baseUrl => fetch(`${baseUrl}/apps/v1`, options)) .then(response => response.json()) .then(results => setApps(results)) .catch(console.error); }, []); return ( <div className="app-shortcuts"> {apps .filter( app => app.customConfig !== undefined && app.customConfig.showInLauncher ) .map(app => { /* Get the appropriate shortcut button by taking a part of stocklux appId (e.g. "news", "watchlist", "chart"), capitalizing the first letter and appending "Shortcut" at the end */ const AppShortcut = Components[ app.appId .split('stockflux-')[1] .charAt(0) .toUpperCase() + app.appId.slice(11) + 'Shortcut' ]; return <AppShortcut key={app.appId} app={app} />; })} </div> ); };
Rename stockflux-search to stockflux-launcher in package.json and remove console.log
Rename stockflux-search to stockflux-launcher in package.json and remove console.log
JavaScript
mit
owennw/OpenFinD3FC,owennw/OpenFinD3FC,ScottLogic/bitflux-openfin,ScottLogic/StockFlux,ScottLogic/StockFlux,ScottLogic/bitflux-openfin
--- +++ @@ -16,10 +16,7 @@ .then(options => options.customData.apiBaseUrl) .then(baseUrl => fetch(`${baseUrl}/apps/v1`, options)) .then(response => response.json()) - .then(results => { - console.log('results', results); - setApps(results); - }) + .then(results => setApps(results)) .catch(console.error); }, []);
7e019de783a757fdeb5fc5babb05b297defb6b46
src/client/es6/controller/cart-blog-create.js
src/client/es6/controller/cart-blog-create.js
import CartBlogEditorCtrl from './base/cart-blog-editor.js'; class CartBlogCreateCtrl extends CartBlogEditorCtrl { constructor(...args) { super(...args); this.logInit('CartBlogCreateCtrl'); this.init(); } init() { this.apiService.postDefaultCategory().then( (category) => { this.category = category; this.post.category = category.uuid; }, (error) => this.msgService.error(error) ); this.tags = []; this.attachments = []; this.post = { driveId: null, title: '', created: new Date(), updated: new Date(), category: null, tags: [], attachments: [], isPublic: this.apiService.postDefaultPrivacy() } } //noinspection ES6Validation async save() { try { //noinspection ES6Validation let post = await this.apiService.postUpsert(this.post); this.msgService.info('Post saved: ', post); } catch (e) { this.msgService.error('Error when creating post: ', e.data.error.message); } } } CartBlogCreateCtrl.$inject = [...CartBlogEditorCtrl.$inject]; export default CartBlogCreateCtrl;
import CartBlogEditorCtrl from './base/cart-blog-editor.js'; class CartBlogCreateCtrl extends CartBlogEditorCtrl { constructor(...args) { super(...args); this.logInit('CartBlogCreateCtrl'); this.init(); } init() { this.apiService.postDefaultCategory().then( (category) => { this.category = category; this.post.category = category.uuid; }, (error) => this.msgService.error(error) ); this.tags = []; this.attachments = []; this.post = { uuid: undefined, // have to be "undefined" to make stongloop server recognize this property shall apply defaultFn driveId: null, title: '', created: new Date(), updated: new Date(), category: null, tags: [], attachments: [], isPublic: this.apiService.postDefaultPrivacy() } } //noinspection ES6Validation async save() { try { //noinspection ES6Validation let post = await this.apiService.postUpsert(this.post); this.msgService.info('Post saved: ', post); } catch (e) { this.msgService.error('Error when creating post: ', e.data.error.message); } } } CartBlogCreateCtrl.$inject = [...CartBlogEditorCtrl.$inject]; export default CartBlogCreateCtrl;
Remove uuid in constructor, since strong loop server will see null as value provided, there won't be any defaultFn called. Otherwise you can give uuid "undefined", it's OK.
Remove uuid in constructor, since strong loop server will see null as value provided, there won't be any defaultFn called. Otherwise you can give uuid "undefined", it's OK.
JavaScript
mit
agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart
--- +++ @@ -19,6 +19,7 @@ this.tags = []; this.attachments = []; this.post = { + uuid: undefined, // have to be "undefined" to make stongloop server recognize this property shall apply defaultFn driveId: null, title: '', created: new Date(),
e6fd0e7eb621d549d231b9435ed3f7974f368f10
notifications/content.js
notifications/content.js
var baseUrl = process.env.BASE_URI || "localdocker:4000"; module.exports = { approveFeed: function(message, recipient, group) { return "<p>" + message["user"]["userName"] + " has approved the feed for their " + message["election"].date.substring(0,10) + " " + message["election"].election_type + " election for publication. It was approved by" + message["user"]["userName"] + " (" + message["user"]["email"] + ").</p>" + "<p><a href='https://" + baseUrl + "/#/feeds/" + message[":public-id"] + "'>Go to the Data Dashboard</a></p>"; }, processedFeed: function(message, recipient, group) { return "<p>" + recipient.givenName + ",</p>" + "<p>The data you provided for " + group.description + "'s election is available for you to review on the VIP Data Dashboard.</p>" + "<p>Please click the link below to review your feed.</p>" + "<p><a href='https://" + baseUrl + "/#/feeds/" + message[":public-id"] + "'>Go to the Data Dashboard</a></p>" + "<p>If you have any questions, please contact <a href='mailto:vip@democracy.works'>vip@democracy.works</a>.</p>" + "<p>Thank you!</p>"; }, errorDuringProcessing: function(message) { return 'It looks like a feed failed during processing. Here\'s the information we got: \ \nMessage we got: ' + JSON.stringify(message); } }
var baseUrl = process.env.BASE_URI || "localdocker:4000"; module.exports = { approveFeed: function(message, recipient, group) { return "<p>" + message["user"]["userName"] + " has approved the feed for their " + message["election"].date.substring(0,10) + " " + message["election"].election_type + " election for publication. It was approved by " + message["user"]["userName"] + " (" + message["user"]["email"] + ").</p>" + "<p><a href='https://" + baseUrl + "/#/feeds/" + message[":public-id"] + "'>Go to the Data Dashboard</a></p>"; }, processedFeed: function(message, recipient, group) { return "<p>" + recipient.givenName + ",</p>" + "<p>The data you provided for " + group.description + "'s election is available for you to review on the VIP Data Dashboard.</p>" + "<p>Please click the link below to review your feed.</p>" + "<p><a href='https://" + baseUrl + "/#/feeds/" + message[":public-id"] + "'>Go to the Data Dashboard</a></p>" + "<p>If you have any questions, please contact <a href='mailto:vip@democracy.works'>vip@democracy.works</a>.</p>" + "<p>Thank you!</p>"; }, errorDuringProcessing: function(message) { return 'It looks like a feed failed during processing. Here\'s the information we got: \ \nMessage we got: ' + JSON.stringify(message); } }
Add missing space in email template.
[CS] Add missing space in email template.
JavaScript
bsd-3-clause
votinginfoproject/Metis,votinginfoproject/Metis,votinginfoproject/Metis
--- +++ @@ -3,7 +3,7 @@ module.exports = { approveFeed: function(message, recipient, group) { return "<p>" + message["user"]["userName"] + " has approved the feed for their " + message["election"].date.substring(0,10) + " " + - message["election"].election_type + " election for publication. It was approved by" + message["user"]["userName"] + " (" + + message["election"].election_type + " election for publication. It was approved by " + message["user"]["userName"] + " (" + message["user"]["email"] + ").</p>" + "<p><a href='https://" + baseUrl + "/#/feeds/" + message[":public-id"] + "'>Go to the Data Dashboard</a></p>"; },
ee12708d43ff22bc9d9c9ea5a36011ee66fdd69a
tasks/autoprefixer.js
tasks/autoprefixer.js
/* * grunt-autoprefixer * * * Copyright (c) 2013 Dmitry Nikitenko * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { var autoprefixer = require('autoprefixer'); grunt.registerMultiTask('autoprefixer', 'Parse CSS and add prefixed properties and values by Can I Use database for actual browsers.', function () { var options = this.options(), compiler = autoprefixer(options.browsers); // Iterate over all specified file groups. this.files.forEach(function (f) { // Concat specified files. var src = f.src.filter(function (filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function (filepath) { // Read file source. return grunt.file.read(filepath); } ).join(''); // Write the destination file. grunt.file.write(f.dest, compiler.compile(src)); // Print a success message. grunt.log.writeln('File "' + f.dest + '" created.'); }); }); };
/* * grunt-autoprefixer * * * Copyright (c) 2013 Dmitry Nikitenko * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { var autoprefixer = require('autoprefixer'); grunt.registerMultiTask('autoprefixer', 'Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website.', function () { var options = this.options(), compiler = autoprefixer(options.browsers); // Iterate over all specified file groups. this.files.forEach(function (f) { // Concat specified files. var src = f.src.filter(function (filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function (filepath) { // Read file source. return grunt.file.read(filepath); } ).join(''); // Write the destination file. grunt.file.write(f.dest, compiler.compile(src)); // Print a success message. grunt.log.writeln('File "' + f.dest + '" created.'); }); }); };
Update the description of the task.
Update the description of the task.
JavaScript
mit
nqdy666/grunt-autoprefixer,nDmitry/grunt-autoprefixer,yuhualingfeng/grunt-autoprefixer
--- +++ @@ -12,7 +12,7 @@ var autoprefixer = require('autoprefixer'); - grunt.registerMultiTask('autoprefixer', 'Parse CSS and add prefixed properties and values by Can I Use database for actual browsers.', function () { + grunt.registerMultiTask('autoprefixer', 'Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website.', function () { var options = this.options(), compiler = autoprefixer(options.browsers);
7645de616768d37c3589609d347e1566be48634a
plugins/index.js
plugins/index.js
'use strict'; let telegram = require( './telegram.js' ); let urlchecker = require( './urlchecker.js' ); let github = require( './github.js' ); let rss = require( './rss.js' ); let dagensmix = require( './dagensmix.js' ); let pushbullet = require( './pushbullet.js' ); let httpcat = require( './httpcat.js' ); module.exports.telegram = telegram; module.exports.urlchecker = urlchecker; module.exports.github = github; module.exports.rss = rss; module.exports.dagensmix = dagensmix; module.exports.pushbullet = pushbullet; module.exports.httpcat = httpcat;
'use strict'; let telegram = require( './telegram.js' ); let urlchecker = require( './urlchecker.js' ); let github = require( './github.js' ); let rss = require( './rss.js' ); let dagensmix = require( './dagensmix.js' ); // let pushbullet = require( './pushbullet.js' ); let httpcat = require( './httpcat.js' ); module.exports.telegram = telegram; module.exports.urlchecker = urlchecker; module.exports.github = github; module.exports.rss = rss; module.exports.dagensmix = dagensmix; // module.exports.pushbullet = pushbullet; module.exports.httpcat = httpcat;
Disable pushbullet because we don't use it anymore :D
Disable pushbullet because we don't use it anymore :D
JavaScript
mit
kokarn/KokBot
--- +++ @@ -5,7 +5,7 @@ let github = require( './github.js' ); let rss = require( './rss.js' ); let dagensmix = require( './dagensmix.js' ); -let pushbullet = require( './pushbullet.js' ); +// let pushbullet = require( './pushbullet.js' ); let httpcat = require( './httpcat.js' ); module.exports.telegram = telegram; @@ -13,5 +13,5 @@ module.exports.github = github; module.exports.rss = rss; module.exports.dagensmix = dagensmix; -module.exports.pushbullet = pushbullet; +// module.exports.pushbullet = pushbullet; module.exports.httpcat = httpcat;
a5440e93f7550b2c107ffbf831a616938d90cbe7
desktop/reactified/client/src/App.js
desktop/reactified/client/src/App.js
import React, { Component } from 'react'; import { Route, BrowserRouter as Router } from 'react-router-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import injectTapEventPlugin from 'react-tap-event-plugin'; import { blue500 } from 'material-ui/styles/colors'; import Sidebar from './Sidebar/Sidebar'; import FAB from './FAB/FAB'; import TaskList from './Task/TaskList'; import IdeaList from './Idea/IdeaList'; import Settings from './Settings/Settings'; import About from './About/About'; import './App.css'; injectTapEventPlugin(); class App extends Component { render() { const muiTheme = getMuiTheme({ palette: { primary1Color: blue500, }, }); return ( <Router> <MuiThemeProvider muiTheme={muiTheme}> <div className="App"> <Sidebar /> <FAB /> <Route path="/tasks" component={TaskList} /> <Route path="/ideas" component={IdeaList} /> <Route path="/settings" component={Settings} /> <Route path="/about" component={About} /> </div> </MuiThemeProvider> </Router> ); } } export default App;
import React, { Component } from 'react'; import { Redirect, Route, BrowserRouter as Router } from 'react-router-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import injectTapEventPlugin from 'react-tap-event-plugin'; import { blue500 } from 'material-ui/styles/colors'; import Sidebar from './Sidebar/Sidebar'; import FAB from './FAB/FAB'; import TaskList from './Task/TaskList'; import IdeaList from './Idea/IdeaList'; import Settings from './Settings/Settings'; import About from './About/About'; import './App.css'; injectTapEventPlugin(); class App extends Component { render() { const muiTheme = getMuiTheme({ palette: { primary1Color: blue500, }, }); return ( <Router> <MuiThemeProvider muiTheme={muiTheme}> <div className="App"> <Sidebar /> <FAB /> <Redirect from="/" to="tasks" /> <Route path="/tasks" component={TaskList} /> <Route path="/ideas" component={IdeaList} /> <Route path="/settings" component={Settings} /> <Route path="/about" component={About} /> </div> </MuiThemeProvider> </Router> ); } } export default App;
Add default route from / to /tasks
Add default route from / to /tasks
JavaScript
mit
mkermani144/wanna,mkermani144/wanna
--- +++ @@ -1,6 +1,6 @@ import React, { Component } from 'react'; -import { Route, BrowserRouter as Router } from 'react-router-dom'; +import { Redirect, Route, BrowserRouter as Router } from 'react-router-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; @@ -32,6 +32,7 @@ <div className="App"> <Sidebar /> <FAB /> + <Redirect from="/" to="tasks" /> <Route path="/tasks" component={TaskList} /> <Route path="/ideas" component={IdeaList} /> <Route path="/settings" component={Settings} />
0369aa8e1381c1d98f7049268f6275342017b9e0
src/components/with-drag-and-drop/item-target/item-target.js
src/components/with-drag-and-drop/item-target/item-target.js
import React from 'react'; import ReactDOM from 'react-dom'; const ItemTarget = { hover(props, monitor, component) { const dragIndex = monitor.getItem().index; const hoverIndex = props.index; // Don't replace items with themselves if (dragIndex === hoverIndex) { console.log(1); return; } // Determine rectangle on screen const hoverBoundingRect = ReactDOM.findDOMNode(component).getBoundingClientRect(); // Get vertical middle const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2; // Determine mouse position const clientOffset = monitor.getClientOffset(); // Get pixels to the top const hoverClientY = clientOffset.y - hoverBoundingRect.top; // Only perform the move when the mouse has crossed half of the items height // When dragging downwards, only move when the cursor is below 50% // When dragging upwards, only move when the cursor is above 50% // Dragging downwards if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) { console.log(2); return; } // Dragging upwards if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) { console.log(3); return; } // Time to actually perform the action props.moveItem(dragIndex, hoverIndex); // Note: we're mutating the monitor item here! // Generally it's better to avoid mutations, // but it's good here for the sake of performance // to avoid expensive index searches. monitor.getItem().index = hoverIndex; } }; export default ItemTarget;
import ReactDOM from 'react-dom'; const ItemTarget = { hover(props, monitor, component) { const dragIndex = monitor.getItem().index; const hoverIndex = props.index; // Don't replace items with themselves if (dragIndex === hoverIndex) { return; } // Determine rectangle on screen const hoverBoundingRect = ReactDOM.findDOMNode(component).getBoundingClientRect(); // Get vertical middle const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2; // Determine mouse position const clientOffset = monitor.getClientOffset(); // Get pixels to the top const hoverClientY = clientOffset.y - hoverBoundingRect.top; // Only perform the move when the mouse has crossed half of the items height // When dragging downwards, only move when the cursor is below 50% // When dragging upwards, only move when the cursor is above 50% // Dragging downwards if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) { return; } // Dragging upwards if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) { return; } // Time to actually perform the action props.moveItem(dragIndex, hoverIndex); // Note: we're mutating the monitor item here! // Generally it's better to avoid mutations, // but it's good here for the sake of performance // to avoid expensive index searches. monitor.getItem().index = hoverIndex; } }; export default ItemTarget;
Remove unused var and console statements
Remove unused var and console statements
JavaScript
apache-2.0
Sage/carbon,Sage/carbon,Sage/carbon
--- +++ @@ -1,4 +1,3 @@ -import React from 'react'; import ReactDOM from 'react-dom'; const ItemTarget = { @@ -8,7 +7,6 @@ // Don't replace items with themselves if (dragIndex === hoverIndex) { - console.log(1); return; } @@ -30,13 +28,11 @@ // Dragging downwards if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) { - console.log(2); return; } // Dragging upwards if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) { - console.log(3); return; }
042737ff4aad71ec237b8565e59a1fb988c1b7f3
lib/node_modules/@stdlib/random/base/improved-ziggurat/lib/ratio_array.js
lib/node_modules/@stdlib/random/base/improved-ziggurat/lib/ratio_array.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // /** * Returns an array containing the ratio of each pair of consecutive elements in order: `X[ i+1 ] / X[ i ]`. * * @private * @param {NumberArray} X - input array * @returns {NumberArray} ratio array * * @example * var R = ratioArray( [ 1, 2, 5 ] ); * // returns [ 0.5, 0.4 ] */ function ratioArray( X ) { var R = new Array( X.length-1 ); var i; for ( i = 0; i < R.length; i++ ) { R[ i ] = X[ i+1 ] / X[ i ]; } return R; } // EXPORTS // module.exports = ratioArray;
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MAIN // /** * Returns an array containing the ratio of each pair of consecutive elements in order: `X[ i+1 ] / X[ i ]`. * * @private * @param {NumberArray} X - input array * @returns {NumberArray} ratio array * * @example * var R = ratioArray( [ 1.0, 2.0, 5.0 ] ); * // returns [ 2.0, 2.5 ] */ function ratioArray( X ) { var R; var i; R = []; for ( i = 0; i < X.length-1; i++ ) { R.push( X[ i+1 ] / X[ i ] ); } return R; } // EXPORTS // module.exports = ratioArray;
Fix example and dynamically resize array
Fix example and dynamically resize array
JavaScript
apache-2.0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
--- +++ @@ -28,14 +28,16 @@ * @returns {NumberArray} ratio array * * @example -* var R = ratioArray( [ 1, 2, 5 ] ); -* // returns [ 0.5, 0.4 ] +* var R = ratioArray( [ 1.0, 2.0, 5.0 ] ); +* // returns [ 2.0, 2.5 ] */ function ratioArray( X ) { - var R = new Array( X.length-1 ); + var R; var i; - for ( i = 0; i < R.length; i++ ) { - R[ i ] = X[ i+1 ] / X[ i ]; + + R = []; + for ( i = 0; i < X.length-1; i++ ) { + R.push( X[ i+1 ] / X[ i ] ); } return R; }
0ff964092fda25483633ce0fd4494b1bdf0858b0
public/js/app.js
public/js/app.js
$(".up-button").mousedown(function(){ $.get("/movecam/moveUp"); }).mouseup(function(){ $.get("/movecam/moveStop"); }); $(".left-button").mousedown(function(){ $.get("/movecam/moveLeft"); }).mouseup(function(){ $.get("/movecam/moveStop"); }); $(".right-button").mousedown(function(){ $.get("/movecam/moveRight"); }).mouseup(function(){ $.get("/movecam/moveStop"); }); $(".down-button").mousedown(function(){ $.get("/movecam/moveDown"); }).mouseup(function(){ $.get("/movecam/moveStop"); }); $(".zoom-tele").mousedown(function(){ $.get("/movecam/zoomTeleStd"); }).mouseup(function(){ $.get("/movecam/zoomStop"); }); $(".zoom-wide").mousedown(function(){ $.get("/movecam/zoomWideStd"); }).mouseup(function(){ $.get("/movecam/zoomStop"); });
$(".up-button").bind("mousedown touchstart", function(){ $.get("/movecam/moveUp"); }).bind("mouseup touchend", function(){ $.get("/movecam/moveStop"); }); $(".left-button").bind("mousedown touchstart", function(){ $.get("/movecam/moveLeft"); }).bind("mouseup touchend", function(){ $.get("/movecam/moveStop"); }); $(".right-button").bind("mousedown touchstart", function(){ $.get("/movecam/moveRight"); }).bind("mouseup touchend", function(){ $.get("/movecam/moveStop"); }); $(".down-button").bind("mousedown touchstart", function(){ $.get("/movecam/moveDown"); }).bind("mouseup touchend", function(){ $.get("/movecam/moveStop"); }); $(".zoom-tele").bind("mousedown touchstart", function(){ $.get("/movecam/zoomTeleStd"); }).bind("mouseup touchend", function(){ $.get("/movecam/zoomStop"); }); $(".zoom-wide").bind("mousedown touchstart", function(){ $.get("/movecam/zoomWideStd"); }).bind("mouseup touchend", function(){ $.get("/movecam/zoomStop"); });
Enable touch use with jQuery element.
Enable touch use with jQuery element.
JavaScript
mit
qrila/khvidcontrol,qrila/khvidcontrol
--- +++ @@ -1,35 +1,35 @@ -$(".up-button").mousedown(function(){ +$(".up-button").bind("mousedown touchstart", function(){ $.get("/movecam/moveUp"); -}).mouseup(function(){ +}).bind("mouseup touchend", function(){ $.get("/movecam/moveStop"); }); -$(".left-button").mousedown(function(){ +$(".left-button").bind("mousedown touchstart", function(){ $.get("/movecam/moveLeft"); -}).mouseup(function(){ +}).bind("mouseup touchend", function(){ $.get("/movecam/moveStop"); }); -$(".right-button").mousedown(function(){ +$(".right-button").bind("mousedown touchstart", function(){ $.get("/movecam/moveRight"); -}).mouseup(function(){ +}).bind("mouseup touchend", function(){ $.get("/movecam/moveStop"); }); -$(".down-button").mousedown(function(){ +$(".down-button").bind("mousedown touchstart", function(){ $.get("/movecam/moveDown"); -}).mouseup(function(){ +}).bind("mouseup touchend", function(){ $.get("/movecam/moveStop"); }); -$(".zoom-tele").mousedown(function(){ +$(".zoom-tele").bind("mousedown touchstart", function(){ $.get("/movecam/zoomTeleStd"); -}).mouseup(function(){ +}).bind("mouseup touchend", function(){ $.get("/movecam/zoomStop"); }); -$(".zoom-wide").mousedown(function(){ +$(".zoom-wide").bind("mousedown touchstart", function(){ $.get("/movecam/zoomWideStd"); -}).mouseup(function(){ +}).bind("mouseup touchend", function(){ $.get("/movecam/zoomStop"); });
f336097b6a75ac819d934dbc0db0f6901c4ad464
randombytes.js
randombytes.js
var assert = require('nanoassert') var randombytes = (function () { var QUOTA = 65536 // limit for QuotaExceededException var crypto = typeof window !== 'undefined' ? (window.crypto || window.msCrypto) : null function windowBytes (out, n) { for (var i = 0; i < n; i += QUOTA) { crypto.getRandomValues(out.subarray(i, i + Math.min(n - i, QUOTA))) } } function nodeBytes (out, n) { out.set(crypto.randomBytes(n)) } function noImpl () { throw new Error('No secure random number generator available') } if (crypto && crypto.getRandomValues) { return windowBytes } else if (typeof require !== 'undefined') { // Node.js. crypto = require('cry' + 'pto'); if (crypto && crypto.randomBytes) { return nodeBytes } } return noImpl })() Object.defineProperty(module.exports, 'randombytes', { value: randombytes }) module.exports.randombytes_buf = function (out) { assert(out, 'out must be given') randombytes(out, out.length) }
var assert = require('nanoassert') var randombytes = (function () { var QUOTA = 65536 // limit for QuotaExceededException var crypto = typeof global !== 'undefined' ? crypto = (global.crypto || global.msCrypto) : null function browserBytes (out, n) { for (var i = 0; i < n; i += QUOTA) { crypto.getRandomValues(out.subarray(i, i + Math.min(n - i, QUOTA))) } } function nodeBytes (out, n) { out.set(crypto.randomBytes(n)) } function noImpl () { throw new Error('No secure random number generator available') } if (crypto && crypto.getRandomValues) { return browserBytes } else if (typeof require !== 'undefined') { // Node.js. crypto = require('cry' + 'pto'); if (crypto && crypto.randomBytes) { return nodeBytes } } return noImpl })() Object.defineProperty(module.exports, 'randombytes', { value: randombytes }) module.exports.randombytes_buf = function (out) { assert(out, 'out must be given') randombytes(out, out.length) }
Fix bug with undefined window in web workers
Fix bug with undefined window in web workers Fixes #8
JavaScript
mit
sodium-friends/sodium-javascript
--- +++ @@ -1,9 +1,9 @@ var assert = require('nanoassert') var randombytes = (function () { var QUOTA = 65536 // limit for QuotaExceededException - var crypto = typeof window !== 'undefined' ? (window.crypto || window.msCrypto) : null + var crypto = typeof global !== 'undefined' ? crypto = (global.crypto || global.msCrypto) : null - function windowBytes (out, n) { + function browserBytes (out, n) { for (var i = 0; i < n; i += QUOTA) { crypto.getRandomValues(out.subarray(i, i + Math.min(n - i, QUOTA))) } @@ -18,7 +18,7 @@ } if (crypto && crypto.getRandomValues) { - return windowBytes + return browserBytes } else if (typeof require !== 'undefined') { // Node.js. crypto = require('cry' + 'pto');
d14f4976cba654e91753d4f290c339fd11891c88
frontend/common/directives/competition-infos/competitionInfos.controller.js
frontend/common/directives/competition-infos/competitionInfos.controller.js
'use strict'; angular.module('konehuone.competitionInfos') .controller('CompetitionInfosCtrl', function ($scope, lodash, apiService) { var _ = lodash; // # Variables $scope.uiClosed = { jj1: true, jj2: true, rc: true }; $scope.compData = {}; $scope.igImages = []; // # Functions $scope.init = function() { apiService.getCompetitionData().then( function success(compData) { _.extend($scope.compData, compData); } ); apiService.getLatestIgImages().then( function success(igImages) { $scope.igImages = igImages; } ); }; });
'use strict'; angular.module('konehuone.competitionInfos') .controller('CompetitionInfosCtrl', function ($scope, lodash, apiService) { var _ = lodash; // # Variables $scope.uiClosed = { jj1: false, jj2: false, rc: false }; $scope.compData = {}; $scope.igImages = []; // # Functions $scope.init = function() { apiService.getCompetitionData().then( function success(compData) { _.extend($scope.compData, compData); } ); apiService.getLatestIgImages().then( function success(igImages) { $scope.igImages = igImages; } ); }; });
Set comp info boxes opened as default
Set comp info boxes opened as default
JavaScript
mit
miro/konehuone,miro/konehuone
--- +++ @@ -7,9 +7,9 @@ // # Variables $scope.uiClosed = { - jj1: true, - jj2: true, - rc: true + jj1: false, + jj2: false, + rc: false }; $scope.compData = {}; $scope.igImages = [];
446458ad0ea88c40f6b0ebffe083c509a4fddb0c
resources/titleManager.js
resources/titleManager.js
/* * Title module displaying title tag based on current view */ var EngineJS_titleManager = { content: {}, titleDefault: "", titleSuffix: "", init: function(content, titleDefault, titleSuffix) { this.content = content; this.titleDefault = titleDefault; this.titleSuffix = titleSuffix; }, change: function(view) { var contentPageKey = view.replace(/\//g, '-'); var title = this.content[contentPageKey]; if(title === undefined) { title = this.titleDefault; } else { title + ' - ' + this.titleSuffix; } document.title = title; } };
/* * Title module displaying title tag based on current view */ var EngineJS_titleManager = { content: {}, titleDefault: "", titleSuffix: "", init: function(content, titleDefault, titleSuffix) { this.content = content; this.titleDefault = titleDefault; this.titleSuffix = titleSuffix; }, change: function(view) { var contentPageKey = view.replace(/\//g, '-'); var title = this.content[contentPageKey]; if(title === undefined) { title = this.titleDefault; } else { title += ' - ' + this.titleSuffix; } document.title = title; } };
Fix typo from previous commit
Fix typo from previous commit
JavaScript
mit
enginejs/libs
--- +++ @@ -17,7 +17,7 @@ if(title === undefined) { title = this.titleDefault; } else { - title + ' - ' + this.titleSuffix; + title += ' - ' + this.titleSuffix; } document.title = title;
b2e9a173ccf695fceed5a2689e0b7dfce4d5f810
package.js
package.js
Package.describe({ summary: "Ravelry OAuth flow", name: "amschrader:ravelry", git: "git@github.com:amschrader/meteor-ravelry.git", version: "0.1.0" }); Package.onTest(function(api) { api.use('tinytest'); api.use('amschrader:ravelry'); api.addFiles('ravelry-tests.js'); }); Package.on_use(function(api) { api.use('http@1.0.8', ['client', 'server']); api.use('templating@1.0.9', 'client'); api.use('oauth1@1.1.2', ['client', 'server']); api.use('oauth@1.1.2', ['client', 'server']); api.use('random@1.0.1', 'client'); api.use('underscore@1.0.1', 'server'); api.use('service-configuration@1.0.2', ['client', 'server']); api.export && api.export('Ravelry'); api.add_files([ 'ravelry-configure.html', 'ravelry-configure.js' ],'client'); api.add_files('ravelry-server.js', 'server'); api.add_files('ravelry-client.js', 'client'); });
Package.describe({ summary: "Ravelry OAuth flow", name: "amschrader:ravelry", git: "https://github.com/amschrader/meteor-ravelry.git", version: "0.1.2" }); Package.onTest(function(api) { api.use('tinytest'); api.use('amschrader:ravelry'); api.addFiles('ravelry-tests.js'); }); Package.onUse(function(api) { api.use('http@1.0.8', ['client', 'server']); api.use('templating@1.0.9', 'client'); api.use('oauth1@1.1.2', ['client', 'server']); api.use('oauth@1.1.2', ['client', 'server']); api.use('random@1.0.1', 'client'); api.use('underscore@1.0.1', 'server'); api.use('service-configuration@1.0.2', ['client', 'server']); api.export && api.export('Ravelry'); api.add_files([ 'ravelry-configure.html', 'ravelry-configure.js' ],'client'); api.addFiles('ravelry-server.js', 'server'); api.addFiles('ravelry-client.js', 'client'); });
Update git url, formatting nits
Update git url, formatting nits
JavaScript
mit
amschrader/meteor-ravelry
--- +++ @@ -1,8 +1,8 @@ Package.describe({ summary: "Ravelry OAuth flow", name: "amschrader:ravelry", - git: "git@github.com:amschrader/meteor-ravelry.git", - version: "0.1.0" + git: "https://github.com/amschrader/meteor-ravelry.git", + version: "0.1.2" }); Package.onTest(function(api) { @@ -11,7 +11,7 @@ api.addFiles('ravelry-tests.js'); }); -Package.on_use(function(api) { +Package.onUse(function(api) { api.use('http@1.0.8', ['client', 'server']); api.use('templating@1.0.9', 'client'); api.use('oauth1@1.1.2', ['client', 'server']); @@ -27,6 +27,6 @@ 'ravelry-configure.js' ],'client'); - api.add_files('ravelry-server.js', 'server'); - api.add_files('ravelry-client.js', 'client'); + api.addFiles('ravelry-server.js', 'server'); + api.addFiles('ravelry-client.js', 'client'); });
56e32f674d211ab1d94afd97660c0c28a82a621f
step_definitions/lib/navigation/link/index.js
step_definitions/lib/navigation/link/index.js
module.exports = { validateAnchorText: validateAnchorText, click: click, }; /** * * @param {WebdriverIO} browser Instance of web driver * @param {String} anchorText The anchor text to target by */ function click (browser, anchorText) { return browser.click('a=' + anchorText); } /** * Sets the client's location to the provided URL * @param {String} anchorText The visible text to select */ function validateAnchorText (anchorText) { if (!anchorText) { throw new Error('Missing anchor text'); } }
var interaction = require('../../interaction'); module.exports = { validateAnchorText: validateAnchorText, click: click, }; /** * Clicks an anchor element with the given anchor text * @param {WebdriverIO} browser Instance of web driver * @param {String} anchorText The anchor text to target by */ function click (browser, anchorText) { return interaction.clickElement(browser, 'a=' + anchorText); } /** * Sets the client's location to the provided URL * @param {String} anchorText The visible text to select */ function validateAnchorText (anchorText) { if (!anchorText) { throw new Error('Missing anchor text'); } }
Refactor click link to use click element method
Refactor click link to use click element method
JavaScript
mit
sudokrew/krewcumber,sudokrew/krewcumber
--- +++ @@ -1,15 +1,17 @@ +var interaction = require('../../interaction'); + module.exports = { validateAnchorText: validateAnchorText, click: click, }; /** - * + * Clicks an anchor element with the given anchor text * @param {WebdriverIO} browser Instance of web driver * @param {String} anchorText The anchor text to target by */ function click (browser, anchorText) { - return browser.click('a=' + anchorText); + return interaction.clickElement(browser, 'a=' + anchorText); } /**
2d311ac85665a5edef7a4aab7c8efaac43426201
lab10/public/js/l10.js
lab10/public/js/l10.js
/** * Created by curtis on 3/28/16. */ angular.module('clusterApp', []) .controller('MainCtrl', [ '$scope', '$http', function($scope, $http) { var completed = 0, timesToQuery = 100, pids = []; $scope.cluster = []; $scope.busy = false; $scope.getMyPIDs = function() { $scope.busy = true; for (var i = 0; i < timesToQuery; i++) { $http.get('/pid').success(function(data) { //console.log("getAll", data); pids.push(data); completed++; if (completed % timesToQuery == 0) { $scope.cluster = angular.copy(pids); $scope.busy = false; } }); } }; $scope.clearPIDs = function() { completed = 0; pids = []; $scope.cluster = []; }; } ]);
/** * Created by curtis on 3/28/16. */ angular.module('clusterApp', []) .controller('MainCtrl', [ '$scope', '$http', function($scope, $http) { var completed = 0, timesToQuery = 100; $scope.cluster = []; $scope.busy = false; $scope.getMyPIDs = function() { $scope.busy = true; for (var i = 0; i < timesToQuery; i++) { $http.get('/pid').success(function(data) { //console.log("getAll", data); completed++; $scope.cluster.push(data); if (completed % timesToQuery == 0) { $scope.busy = false; } }); } }; $scope.clearPIDs = function() { completed = 0; $scope.cluster = []; }; } ]);
Clean up the lab10 code a bit.
Clean up the lab10 code a bit.
JavaScript
mit
chocklymon/CS360,chocklymon/CS360,chocklymon/CS360,chocklymon/CS360
--- +++ @@ -7,8 +7,7 @@ '$http', function($scope, $http) { var completed = 0, - timesToQuery = 100, - pids = []; + timesToQuery = 100; $scope.cluster = []; $scope.busy = false; @@ -17,10 +16,9 @@ for (var i = 0; i < timesToQuery; i++) { $http.get('/pid').success(function(data) { //console.log("getAll", data); - pids.push(data); completed++; + $scope.cluster.push(data); if (completed % timesToQuery == 0) { - $scope.cluster = angular.copy(pids); $scope.busy = false; } }); @@ -28,7 +26,6 @@ }; $scope.clearPIDs = function() { completed = 0; - pids = []; $scope.cluster = []; }; }
1890cfca8065635ced6755524d468614dead23f5
src/services/GetCharityData.js
src/services/GetCharityData.js
class GetCharityData { getData(){ var CHARITY_DATA = [ {amount: '41,234', month: 'January', year: '2015', name: 'Charity:Water', description: 'Cool description that was so hard to come up with. Hence I ended up writing some random text that dosent make much text' ,imageSource: 'https://s3.amazonaws.com/moveit-multunus/charity_resources/March2015/GiveIndia_education_march_2015.png'}, {amount: '41,234', month: 'February', year: '2015', name: 'Charity:Water', description: 'Cooler description hat was so hard to come up with. Hence I ended up writing some random text that dosent make much text',imageSource: 'https://s3.amazonaws.com/moveit-multunus/charity_resources/April2015/charity_water+Apr+2015.png'}, {amount: '21,234', month: 'March', year: '2015', name: 'Charity:Water', description: 'Coolest description hat was so hard to come up with. Hence I ended up writing some random text that dosent make much text',imageSource: 'https://s3.amazonaws.com/moveit-multunus/charity_resources/April2015/charity_water+Apr+2015.png'} ]; return CHARITY_DATA ; } } export default new GetCharityData();
class GetCharityData { getData(){ var CHARITY_DATA_ARRAY = []; var spreadsheetID = "1f1tFr7y62QS7IRWOC2nNR5HWsTO99Bna3d0Xv1PTPiY"; var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json"; fetch(url).then((response) => response.json()) .then((responseText) => { entry = responseText.feed.entry; entry.forEach(function(element){ CHARITY_DATA_ARRAY.push({amount: element.gsx$charityamount.$t, month: element.gsx$month.$t, year: element.gsx$year.$t, name: element.gsx$charityname.$t, description: element.gsx$charitydesc.$t, imageSource: element.gsx$charityimage.$t }); }); }) .catch((error) => { console.warn(error); }); return CHARITY_DATA_ARRAY; } } export default new GetCharityData();
Implement service to fetch charity data from spreadsheet
Implement service to fetch charity data from spreadsheet https://trello.com/c/wjthoHP0/28-user-sbat-view-the-charity-contributions-done-per-month-by-the-company
JavaScript
mit
multunus/moveit-mobile,multunus/moveit-mobile,multunus/moveit-mobile
--- +++ @@ -1,12 +1,19 @@ class GetCharityData { - getData(){ - var CHARITY_DATA = [ - {amount: '41,234', month: 'January', year: '2015', name: 'Charity:Water', description: 'Cool description that was so hard to come up with. Hence I ended up writing some random text that dosent make much text' ,imageSource: 'https://s3.amazonaws.com/moveit-multunus/charity_resources/March2015/GiveIndia_education_march_2015.png'}, - {amount: '41,234', month: 'February', year: '2015', name: 'Charity:Water', description: 'Cooler description hat was so hard to come up with. Hence I ended up writing some random text that dosent make much text',imageSource: 'https://s3.amazonaws.com/moveit-multunus/charity_resources/April2015/charity_water+Apr+2015.png'}, - {amount: '21,234', month: 'March', year: '2015', name: 'Charity:Water', description: 'Coolest description hat was so hard to come up with. Hence I ended up writing some random text that dosent make much text',imageSource: 'https://s3.amazonaws.com/moveit-multunus/charity_resources/April2015/charity_water+Apr+2015.png'} - ]; - return CHARITY_DATA ; - } + getData(){ + var CHARITY_DATA_ARRAY = []; + var spreadsheetID = "1f1tFr7y62QS7IRWOC2nNR5HWsTO99Bna3d0Xv1PTPiY"; + var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json"; + fetch(url).then((response) => response.json()) + .then((responseText) => { + entry = responseText.feed.entry; + entry.forEach(function(element){ + CHARITY_DATA_ARRAY.push({amount: element.gsx$charityamount.$t, month: element.gsx$month.$t, year: element.gsx$year.$t, name: element.gsx$charityname.$t, description: element.gsx$charitydesc.$t, imageSource: element.gsx$charityimage.$t }); + }); + }) + .catch((error) => { + console.warn(error); + }); + return CHARITY_DATA_ARRAY; + } } - export default new GetCharityData();
ad44e79d9f69feea484f72c44c55853f144fb6b8
lib/get-youtube-url.js
lib/get-youtube-url.js
const Request = require('sdk/request').Request; const qs = require('sdk/querystring'); const baseURL = 'http://www.youtube.com/get_video_info'; module.exports = getYouTubeUrl; function getYouTubeUrl(videoId, cb) { Request({ url: baseURL + '?' + qs.stringify({video_id: videoId}), onComplete: function (resp) { const streamParams = qs.parse(resp.text)['url_encoded_fmt_stream_map'].split(',')[0]; cb(null, qs.parse(streamParams).url); } }).get(); }
const Request = require('sdk/request').Request; const qs = require('sdk/querystring'); const baseURL = 'https://www.youtube.com/get_video_info'; module.exports = getYouTubeUrl; function getYouTubeUrl(videoId, cb) { Request({ url: baseURL + '?' + qs.stringify({video_id: videoId}), onComplete: function (resp) { const streamParams = qs.parse(resp.text)['url_encoded_fmt_stream_map'].split(',')[0]; cb(null, qs.parse(streamParams).url); } }).get(); }
Convert YouTube link to HTTPS
Convert YouTube link to HTTPS
JavaScript
mpl-2.0
meandavejustice/min-vid,meandavejustice/min-vid,meandavejustice/min-vid
--- +++ @@ -1,7 +1,7 @@ const Request = require('sdk/request').Request; const qs = require('sdk/querystring'); -const baseURL = 'http://www.youtube.com/get_video_info'; +const baseURL = 'https://www.youtube.com/get_video_info'; module.exports = getYouTubeUrl;
74aa179b5e16f5456a7529326820aba1a97bbb1e
server/middleware/auth.js
server/middleware/auth.js
const session = require('express-session'); const RedisStore = require('connect-redis')(session); const redisClient = require('redis').createClient(); module.exports.verify = (req, res, next) => { if (req.isAuthenticated()) { return next(); } res.redirect('/login'); }; module.exports.profileRedirect = (req, res, next) => { if ( req.isAuthenticated()) { res.redirect('/profile'); } return next(); }; module.exports.session = session({ store: new RedisStore({ client: redisClient, host: 'localhost', port: 6379 }), secret: 'more laughter, more love, more life', resave: false, saveUninitialized: false });
const session = require('express-session'); const RedisStore = require('connect-redis')(session); const redisClient = require('redis').createClient(process.env.REDIS_URL) || require('redis').createClient; module.exports.verify = (req, res, next) => { if (req.isAuthenticated()) { return next(); } res.redirect('/login'); }; module.exports.profileRedirect = (req, res, next) => { if ( req.isAuthenticated()) { res.redirect('/profile'); } return next(); }; module.exports.session = session({ store: new RedisStore({ client: redisClient, host: 'localhost', port: 6379 }), secret: 'more laughter, more love, more life', resave: false, saveUninitialized: false });
Add REDIS_URL to createClient as an argument
Add REDIS_URL to createClient as an argument
JavaScript
mit
FuriousFridges/FuriousFridges,FuriousFridges/FuriousFridges
--- +++ @@ -1,6 +1,6 @@ const session = require('express-session'); const RedisStore = require('connect-redis')(session); -const redisClient = require('redis').createClient(); +const redisClient = require('redis').createClient(process.env.REDIS_URL) || require('redis').createClient; module.exports.verify = (req, res, next) => { if (req.isAuthenticated()) {
9960f49700f7793c93295240481ef1fcb7080a93
troposphere/static/js/stores/HelpLinkStore.js
troposphere/static/js/stores/HelpLinkStore.js
import Dispatcher from "dispatchers/Dispatcher"; import BaseStore from "stores/BaseStore"; import HelpLinkCollection from "collections/HelpLinkCollection"; var HelpLinkStore = BaseStore.extend({ collection: HelpLinkCollection, queryParams: { page_size: 100 }, }); var store = new HelpLinkStore(); Dispatcher.register(function(dispatch) { var options = dispatch.action.options || options; if (!options.silent) { store.emitChange(); } return true; }); export default store;
import _ from "underscore"; import Dispatcher from "dispatchers/Dispatcher"; import BaseStore from "stores/BaseStore"; import HelpLinkCollection from "collections/HelpLinkCollection"; var HelpLinkStore = BaseStore.extend({ collection: HelpLinkCollection, queryParams: { page_size: 100 }, }); var store = new HelpLinkStore(); Dispatcher.register(function(dispatch) { var options = dispatch.action.options || options; if (_.has(options, "silent") && !options.silent) { store.emitChange(); } return true; }); export default store;
Fix error when updateImageAttributes dispatched
Fix error when updateImageAttributes dispatched An uncaught error has been occurring when an image creator saves any changes to image attributes: ``` Uncaught TypeError: Cannot read property 'silent' of undefined ``` It turns out that the HelpLinkStore is performing check for an option, `option.silent`, to determine if an `emitChange()` call should be made. Unfortunately, this "check" is done in a manner that generates the above uncaught type error. The fix was to use the `_.has(obj, "propName")` call. This could be replaced with an expression like `obj && obj.hasOwnProperty("prop")`, but here we opt for `underscore` since it is already available - we could also move to `lodash`.
JavaScript
apache-2.0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
--- +++ @@ -1,3 +1,4 @@ +import _ from "underscore"; import Dispatcher from "dispatchers/Dispatcher"; import BaseStore from "stores/BaseStore"; import HelpLinkCollection from "collections/HelpLinkCollection"; @@ -16,7 +17,7 @@ Dispatcher.register(function(dispatch) { var options = dispatch.action.options || options; - if (!options.silent) { + if (_.has(options, "silent") && !options.silent) { store.emitChange(); }
0393c02cf549c8ee3bc09278153208702ec2b25a
lib/app/store/geoip.js
lib/app/store/geoip.js
module.exports = function geoip (ip) { return (state, emitter) => { state.geoip = { ip: ip, isLoading: false } emitter.on('geoip:fetch', () => { if (state.geoip.isLoading) return state.geoip.isLoading = true window.fetch('//api.ipify.org?format=json') .then(body => body.json()) .then(resp => window.fetch(`//freegeoip.net/json/${resp.ip}`)) .then(body => body.json()) .then(data => { Object.assign(state.geoip, data, { isLoading: false, precision: 'city' }) emitter.emit('render') }, err => { state.geoip.isLoading = false emitter.emit('error', err) }) }) emitter.on('geoip:getPosition', () => { state.geoip.isLoading = true emitter.emit('render') navigator.geolocation.getCurrentPosition(position => { state.geoip.latitude = position.coords.latitude state.geoip.longitude = position.coords.longitude state.geoip.precision = 'exact' state.geoip.isLoading = false emitter.emit('render') }, err => emitter.emit('error', err)) }) } }
module.exports = function geoip (ip) { return (state, emitter) => { state.geoip = { ip: ip, isLoading: false } emitter.on('geoip:fetch', () => { if (state.geoip.isLoading) return state.geoip.isLoading = true window.fetch('https://freegeoip.net/json/').then(body => { return body.json().then(data => { Object.assign(state.geoip, data, { isLoading: false, precision: 'city' }) emitter.emit('render') }) }).catch(err => { state.geoip.isLoading = false emitter.emit('error', err) }) }) emitter.on('geoip:getPosition', () => { state.geoip.isLoading = true emitter.emit('render') navigator.geolocation.getCurrentPosition(position => { state.geoip.latitude = position.coords.latitude state.geoip.longitude = position.coords.longitude state.geoip.precision = 'exact' state.geoip.isLoading = false emitter.emit('render') }, err => emitter.emit('error', err)) }) } }
Remove use of ipify.org service
Remove use of ipify.org service
JavaScript
apache-2.0
CIVIS-project/BRFApp
--- +++ @@ -9,20 +9,18 @@ if (state.geoip.isLoading) return state.geoip.isLoading = true - window.fetch('//api.ipify.org?format=json') - .then(body => body.json()) - .then(resp => window.fetch(`//freegeoip.net/json/${resp.ip}`)) - .then(body => body.json()) - .then(data => { + window.fetch('https://freegeoip.net/json/').then(body => { + return body.json().then(data => { Object.assign(state.geoip, data, { isLoading: false, precision: 'city' }) emitter.emit('render') - }, err => { - state.geoip.isLoading = false - emitter.emit('error', err) }) + }).catch(err => { + state.geoip.isLoading = false + emitter.emit('error', err) + }) }) emitter.on('geoip:getPosition', () => {
d34142022ccee2c72cf99430bba1ad3446061294
public/js/script.js
public/js/script.js
//Client-side JS goes here. (function () { var locale = APP.intl.locale, baseUrl = 'http://yui.yahooapis.com/combo?platform/intl/0.1.2/Intl.min.js&platform/intl/0.1.2/locale-data/jsonp/', comboUrl = baseUrl + locale + '.js'; yepnope({ test : !!window.Intl, nope : comboUrl callback: init }); function init () { // Initialize application here } })();
//Client-side JS goes here. (function () { var locale = APP.intl.locale, // TODO: expose these URLs through Express State instead baseUrl = 'http://yui.yahooapis.com/combo?platform/intl/0.1.2/Intl.min.js&platform/intl/0.1.2/locale-data/jsonp/', comboUrl = baseUrl + locale + '.js', intlMessageFormatUrl = '/node_modules/intl-messageformat/build/intl-messageformat.complete.min.js'; yepnope([{ test : !!window.Intl, nope : comboUrl }, intlMessageFormatUrl, { complete: init }]); function init () { // Initialize application here } })();
Load in `intl-messageformat` after Intl
Load in `intl-messageformat` after Intl
JavaScript
bsd-3-clause
okuryu/formatjs-site,ericf/formatjs-site,ericf/formatjs-site
--- +++ @@ -1,14 +1,17 @@ //Client-side JS goes here. (function () { var locale = APP.intl.locale, - baseUrl = 'http://yui.yahooapis.com/combo?platform/intl/0.1.2/Intl.min.js&platform/intl/0.1.2/locale-data/jsonp/', - comboUrl = baseUrl + locale + '.js'; + // TODO: expose these URLs through Express State instead + baseUrl = 'http://yui.yahooapis.com/combo?platform/intl/0.1.2/Intl.min.js&platform/intl/0.1.2/locale-data/jsonp/', + comboUrl = baseUrl + locale + '.js', + intlMessageFormatUrl = '/node_modules/intl-messageformat/build/intl-messageformat.complete.min.js'; - yepnope({ + yepnope([{ test : !!window.Intl, nope : comboUrl - callback: init - }); + }, intlMessageFormatUrl, { + complete: init + }]); function init () { // Initialize application here
6f7ef8765f1919c1ad9471d031bd3d6cb1f6937f
lib/middleware/cors.js
lib/middleware/cors.js
/** * Adds CORS headers to the response * * ####Example: * * app.all('/api*', keystone.middleware.cors); * * @param {app.request} req * @param {app.response} res * @param {function} next * @api public */ // The exported function returns a closure that retains // a reference to the keystone instance, so it can be // passed as middeware to the express app. module.exports = function (keystone) { return function cors (req, res, next) { var origin = keystone.get('cors allow origin'); if (origin) { res.header('Access-Control-Allow-Origin', origin === true ? '*' : origin); } if (keystone.get('cors allow methods') !== false) { res.header('Access-Control-Allow-Methods', keystone.get('cors allow methods') || 'GET,PUT,POST,DELETE'); } if (keystone.get('cors allow headers') !== false) { res.header('Access-Control-Allow-Headers', keystone.get('cors allow headers') || 'Content-Type, Authorization'); } next(); }; };
/** * Adds CORS headers to the response * * ####Example: * * app.all('/api*', keystone.middleware.cors); * * @param {app.request} req * @param {app.response} res * @param {function} next * @api public */ // The exported function returns a closure that retains // a reference to the keystone instance, so it can be // passed as middeware to the express app. module.exports = function (keystone) { return function cors (req, res, next) { var origin = keystone.get('cors allow origin'); if (origin) { res.header('Access-Control-Allow-Origin', origin === true ? '*' : origin); } if (keystone.get('cors allow methods') !== false) { res.header('Access-Control-Allow-Methods', keystone.get('cors allow methods') || 'GET,PUT,POST,DELETE,OPTIONS'); } if (keystone.get('cors allow headers') !== false) { res.header('Access-Control-Allow-Headers', keystone.get('cors allow headers') || 'Content-Type, Authorization'); } next(); }; };
Add OPTIONS to CORS allowed methods
Add OPTIONS to CORS allowed methods
JavaScript
mit
creynders/keystone,creynders/keystone
--- +++ @@ -24,7 +24,7 @@ } if (keystone.get('cors allow methods') !== false) { - res.header('Access-Control-Allow-Methods', keystone.get('cors allow methods') || 'GET,PUT,POST,DELETE'); + res.header('Access-Control-Allow-Methods', keystone.get('cors allow methods') || 'GET,PUT,POST,DELETE,OPTIONS'); } if (keystone.get('cors allow headers') !== false) { res.header('Access-Control-Allow-Headers', keystone.get('cors allow headers') || 'Content-Type, Authorization');
53db1031477a5f159feeb90dfb30a51a83093840
components/layout/layout-panel-header.directive.js
components/layout/layout-panel-header.directive.js
export default ['config', 'Core', function (config, Core) { return { template: require('components/layout/partials/panel-header.directive.html'), transclude: { 'extraButtons': '?extraButtons', 'extraTitle': '?extraTitle' }, scope: { panelName: "@", panelTitle: "=panelTitle" }, controller: function ($scope) { $scope.closePanel = Core.closePanel; } }; }]
export default ['config', 'Core', function (config, Core) { return { template: require('components/layout/partials/panel-header.directive.html'), transclude: { 'extraButtons': '?extraButtons', 'extraTitle': '?extraTitle' }, scope: { panelName: "@", panelTitle: "=panelTitle" }, controller: ['$scope', function ($scope) { $scope.closePanel = Core.closePanel; }] }; }]
Fix incorrect injection of $scope for minification
Fix incorrect injection of $scope for minification
JavaScript
mit
hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng
--- +++ @@ -9,8 +9,8 @@ panelName: "@", panelTitle: "=panelTitle" }, - controller: function ($scope) { + controller: ['$scope', function ($scope) { $scope.closePanel = Core.closePanel; - } + }] }; }]
84e900f20bc6738ca5f71d9346254a5f8322f5eb
examples/node-browser/tracer-init.js
examples/node-browser/tracer-init.js
/* * Copyright 2015-2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; import opentracing from 'opentracing'; import hawkularAPM from '../../index'; function init() { opentracing.initGlobalTracer(new hawkularAPM.APMTracer({ recorder: new hawkularAPM.HttpRecorder('http://localhost:8080', 'jdoe', 'password'), // recorder: new hawkularAPM.ConsoleRecorder(), sampler: new hawkularAPM.AlwaysSample(), })); } module.exports = { init };
/* * Copyright 2015-2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; import opentracing from 'opentracing'; import hawkularAPM from '../../index'; function init() { opentracing.initGlobalTracer(new hawkularAPM.APMTracer({ recorder: new hawkularAPM.HttpRecorder('http://localhost:8080', 'jdoe', 'password'), // recorder: new hawkularAPM.ConsoleRecorder(), sampler: new hawkularAPM.AlwaysSample(), deploymentMetaData: new hawkularAPM.DeploymentMetaData('node-browser-service'), })); } module.exports = { init };
Add deployment meta data to example app
Add deployment meta data to example app
JavaScript
apache-2.0
hawkular/hawkular-apm-opentracing-javascript
--- +++ @@ -25,6 +25,7 @@ recorder: new hawkularAPM.HttpRecorder('http://localhost:8080', 'jdoe', 'password'), // recorder: new hawkularAPM.ConsoleRecorder(), sampler: new hawkularAPM.AlwaysSample(), + deploymentMetaData: new hawkularAPM.DeploymentMetaData('node-browser-service'), })); }
523cdd46d039ad2a581a08f6da6438e7c72df472
bi-platform-v2-plugin/cdf/js/components/simpleautocomplete.js
bi-platform-v2-plugin/cdf/js/components/simpleautocomplete.js
var SimpleAutoCompleteComponent = BaseComponent.extend({ ph: undefined, completionCallback: undefined, update: function() { this.ph = $("#" + this.htmlObject).empty(); this.input = $("<input type='text'>").appendTo(this.ph); this.query = new Query(this.queryDefinition); var myself = this; this.input.autocomplete({ source:function(term,callback){return myself.triggerQuery(term,callback);} }); }, handleQuery: function(callback) { var myself = this; return function(values) { if(typeof myself.postFetch == "function") { var changedValues = myself.postFetch(values); values = changedValues || values; }; var results = values.resultset.map(function(e){return e[0];}); callback(results); } }, triggerQuery: function(term,callback){ var params = $.extend([],this.parameters); params.push([this.termParam,term]); if(term.length >= this.minTextLength) { this.query.fetchData(params,this.handleQuery(callback)); } else { callback([]); } } })
var SimpleAutoCompleteComponent = BaseComponent.extend({ ph: undefined, completionCallback: undefined, update: function() { var myself = this; this.ph = $("#" + this.htmlObject).empty(); this.input = $("<input type='text'>").appendTo(this.ph); this.query = new Query(this.queryDefinition); var myself = this; this.input.autocomplete({ source:function(obj,callback){return myself.triggerQuery(obj.term,callback);} }); this.input.change(function(){ Dashboards.processChange(myself.name); }).keyup(function(event){ if (event.keyCode == 13) { Dashboards.processChange(myself.name); } }); }, handleQuery: function(callback) { var myself = this; return function(values) { if(typeof myself.postFetch == "function") { var changedValues = myself.postFetch(values); values = changedValues || values; }; var results = values.resultset.map(function(e){return e[0];}); callback(results); } }, triggerQuery: function(term,callback){ var params = $.extend([],this.parameters); if (params.length) { params[0][1] = "'" + term+ "'"; } if(term.length >= this.minTextLength) { this.query.fetchData(params,this.handleQuery(callback)); } else { callback([]); } }, getValue: function() { return this.input.val(); } })
Fix some bugs with simple autocomplete
Fix some bugs with simple autocomplete
JavaScript
mpl-2.0
Tiger66639/cdf,pamval/cdf,krivera-pentaho/cdf,davidmsantos90/cdf,diogofscmariano/cdf,eliofreitas/cdf,jvelasques/cdf,Aliaksandr-Kastenka/cdf,pedrofvteixeira/cdf,pamval/cdf,jvelasques/cdf,diogofscmariano/cdf,diogofscmariano/cdf,Tiger66639/cdf,e-cuellar/cdf,afrjorge/cdf,afrjorge/cdf,webdetails/cdf,eliofreitas/cdf,scottyaslan/cdf,davidmsantos90/cdf,carlosrusso/cdf,Tiger66639/cdf,plagoa/cdf,akhayrutdinov/cdf,pamval/cdf,akhayrutdinov/cdf,pedrofvteixeira/cdf,webdetails/cdf,e-cuellar/cdf,bytekast/cdf,bytekast/cdf,scottyaslan/cdf,eliofreitas/cdf,plagoa/cdf,webdetails/cdf,plagoa/cdf,miguelleite/cdf,akhayrutdinov/cdf,carlosrusso/cdf,carlosrusso/cdf,pedrofvteixeira/cdf,gcnonato/cdf,bytekast/cdf,dcleao/cdf,gcnonato/cdf,krivera-pentaho/cdf,gcnonato/cdf,dcleao/cdf,dcleao/cdf,e-cuellar/cdf,davidmsantos90/cdf,jvelasques/cdf,miguelleite/cdf,Aliaksandr-Kastenka/cdf,scottyaslan/cdf,krivera-pentaho/cdf,afrjorge/cdf,Aliaksandr-Kastenka/cdf,miguelleite/cdf
--- +++ @@ -5,12 +5,20 @@ completionCallback: undefined, update: function() { + var myself = this; this.ph = $("#" + this.htmlObject).empty(); this.input = $("<input type='text'>").appendTo(this.ph); this.query = new Query(this.queryDefinition); var myself = this; this.input.autocomplete({ - source:function(term,callback){return myself.triggerQuery(term,callback);} + source:function(obj,callback){return myself.triggerQuery(obj.term,callback);} + }); + this.input.change(function(){ + Dashboards.processChange(myself.name); + }).keyup(function(event){ + if (event.keyCode == 13) { + Dashboards.processChange(myself.name); + } }); }, @@ -28,12 +36,17 @@ triggerQuery: function(term,callback){ var params = $.extend([],this.parameters); - params.push([this.termParam,term]); + if (params.length) { + params[0][1] = "'" + term+ "'"; + } if(term.length >= this.minTextLength) { this.query.fetchData(params,this.handleQuery(callback)); } else { callback([]); } + }, + getValue: function() { + return this.input.val(); } })
77cd76c4e97c2cdc895e0fba1f1207f4c6c7623d
lib/transport/index.js
lib/transport/index.js
'use strict'; var EventEmitter = require('events').EventEmitter; var AbstractTransport = require('./abstract_transport.js'); var NetTransport = require('./net_transport.js'); var TlsTransport = require('./tls_transport.js'); function TransportProvider() { this._transports = {}; } TransportProvider.prototype.registerTransport = function(protocol, transport) { // NOTE: if we only cared about internal modules, 'instanceof' would work, but // since we're "duck typing" transports to avoid circular dependencies, we have to // verify the transport prototype differently. for(var member in AbstractTransport.prototype) { if (AbstractTransport.prototype.hasOwnProperty(member)) if (typeof AbstractTransport.prototype[member] != typeof transport[member]) { throw new Error('transport should implement the \'' + member + '\' method.'); } } if (!(transport instanceof EventEmitter)) { throw new Error('transport should inherit from EventEmitter') } this._transports[protocol] = transport; }; TransportProvider.prototype.getTransportFor = function(protocol) { if (!this._transports.hasOwnProperty(protocol)) throw new Error('invalid protocol: ', protocol); return this._transports[protocol]; }; module.exports = function() { var provider = new TransportProvider(); // pre-register our "known" transports provider.registerTransport("amqp", new NetTransport()); provider.registerTransport("amqps", new TlsTransport()); return provider; };
'use strict'; var EventEmitter = require('events').EventEmitter; var AbstractTransport = require('./abstract_transport.js'); var NetTransport = require('./net_transport.js'); var TlsTransport = require('./tls_transport.js'); function TransportProvider() { this._transports = {}; } TransportProvider.prototype.registerTransport = function(protocol, transport) { // NOTE: if we only cared about internal modules, 'instanceof' would work, but // since we're "duck typing" transports to avoid circular dependencies, we have to // verify the transport prototype differently. for(var member in AbstractTransport.prototype) { if (AbstractTransport.prototype.hasOwnProperty(member)) if (typeof AbstractTransport.prototype[member] !== typeof transport[member]) { throw new Error('transport should implement the \'' + member + '\' method.'); } } if (!(transport instanceof EventEmitter)) { throw new Error('transport should inherit from EventEmitter'); } this._transports[protocol] = transport; }; TransportProvider.prototype.getTransportFor = function(protocol) { if (!this._transports.hasOwnProperty(protocol)) throw new Error('invalid protocol: ', protocol); return this._transports[protocol]; }; module.exports = function() { var provider = new TransportProvider(); // pre-register our "known" transports provider.registerTransport("amqp", new NetTransport()); provider.registerTransport("amqps", new TlsTransport()); return provider; };
Fix jshint errors in transport
Fix jshint errors in transport
JavaScript
mit
noodlefrenzy/node-amqp10
--- +++ @@ -16,14 +16,14 @@ for(var member in AbstractTransport.prototype) { if (AbstractTransport.prototype.hasOwnProperty(member)) - if (typeof AbstractTransport.prototype[member] != typeof transport[member]) { + if (typeof AbstractTransport.prototype[member] !== typeof transport[member]) { throw new Error('transport should implement the \'' + member + '\' method.'); } } if (!(transport instanceof EventEmitter)) { - throw new Error('transport should inherit from EventEmitter') + throw new Error('transport should inherit from EventEmitter'); } this._transports[protocol] = transport;
f60c3859905ed939366800d3adf71ec7e1da3a4b
eloquent_js/chapter12/ch12_ex03.js
eloquent_js/chapter12/ch12_ex03.js
function skipSpace(string) { let toRemove = string.match(/^(?:\s|#.*)*/); return string.slice(toRemove[0].length); }
function skipSpace(string) { let match = string.match(/^(\s+|#.*)*/); return string.slice(match[0].length); }
Add chapter 12, exercise 3
Add chapter 12, exercise 3
JavaScript
mit
bewuethr/ctci
--- +++ @@ -1,4 +1,4 @@ function skipSpace(string) { - let toRemove = string.match(/^(?:\s|#.*)*/); - return string.slice(toRemove[0].length); + let match = string.match(/^(\s+|#.*)*/); + return string.slice(match[0].length); }
f98cf367c1d9fa9ca2516ab0d2dead2b80f7848a
test/test-issue-85.js
test/test-issue-85.js
var common = require("./common") , odbc = require("../") , db = new odbc.Database() , assert = require("assert") , util = require('util') , count = 0 ; var sql = (common.dialect == 'sqlite' || common.dialect =='mysql') ? 'select cast(-1 as signed) as test;' : 'select cast(-1 as int) as test;' ; db.open(common.connectionString, function(err) { console.error(err || "Connected") if (!err) { db.query(sql, function (err, results, more) { assert.equal(err, null); assert.equal(results[0].test, -1); db.close(function(err) { console.log(err || "Closed") }) }) } });
var common = require("./common") , odbc = require("../") , db = new odbc.Database() , assert = require("assert") , util = require('util') , count = 0 ; var sql = (common.dialect == 'sqlite' || common.dialect =='mysql') ? 'select cast(-1 as signed) as test, cast(-2147483648 as signed) as test2, cast(2147483647 as signed) as test3;' : 'select cast(-1 as int) as test, cast(-2147483648 as int) as test2, cast(2147483647 as int) as test3;' ; db.open(common.connectionString, function(err) { console.error(err || "Connected") if (!err) { db.query(sql, function (err, results, more) { console.log(results); assert.equal(err, null); assert.equal(results[0].test, -1); assert.equal(results[0].test2, -2147483648); assert.equal(results[0].test3, 2147483647); db.close(function(err) { console.log(err || "Closed") }) }) } });
Update test to include min and max of integer range
Update test to include min and max of integer range
JavaScript
mit
jbaxter0810/node-odbc,gmahomarf/node-odbc,dfbaskin/node-odbc,bzuillsmith/node-odbc,Papercloud/node-odbc,bustta/node-odbc,gmahomarf/node-odbc,Papercloud/node-odbc,bzuillsmith/node-odbc,wankdanker/node-odbc,wankdanker/node-odbc,jbaxter0810/node-odbc,gmahomarf/node-odbc,dfbaskin/node-odbc,bustta/node-odbc,Papercloud/node-odbc,bustta/node-odbc,bustta/node-odbc,gmahomarf/node-odbc,dfbaskin/node-odbc,wankdanker/node-odbc,Papercloud/node-odbc,jbaxter0810/node-odbc,wankdanker/node-odbc,bzuillsmith/node-odbc,bzuillsmith/node-odbc,dfbaskin/node-odbc,jbaxter0810/node-odbc
--- +++ @@ -7,8 +7,8 @@ ; var sql = (common.dialect == 'sqlite' || common.dialect =='mysql') - ? 'select cast(-1 as signed) as test;' - : 'select cast(-1 as int) as test;' + ? 'select cast(-1 as signed) as test, cast(-2147483648 as signed) as test2, cast(2147483647 as signed) as test3;' + : 'select cast(-1 as int) as test, cast(-2147483648 as int) as test2, cast(2147483647 as int) as test3;' ; db.open(common.connectionString, function(err) { @@ -16,8 +16,12 @@ if (!err) { db.query(sql, function (err, results, more) { + console.log(results); + assert.equal(err, null); assert.equal(results[0].test, -1); + assert.equal(results[0].test2, -2147483648); + assert.equal(results[0].test3, 2147483647); db.close(function(err) { console.log(err || "Closed") }) })
32912d1ef7ede8ffc7722a15fa7eeba0751319a0
example/app/models/post.js
example/app/models/post.js
module.exports = function () { this.string('name', { required: true, minLength: 5 }); this.string('title', { required: true, minLength: 5 }); this.string('content'); this.timestamps(); this.filter('all', { map: function (doc) { if (doc.resource === 'Post') { var x = doc._id; doc._id = doc._id.split('/').slice(1).join('/'); emit(x, doc); } } }); this.before('save', function (obj) { obj.id = obj.title; return true; }); };
module.exports = function () { this.string('name', { required: true, minLength: 5 }); this.string('title', { required: true, minLength: 5 }); this.string('content'); this.timestamps(); this.filter('all', { map: function (doc) { if (doc.resource === 'Post') { emit(doc._id, doc); } } }); this.before('save', function (obj) { obj.id = obj.title; return true; }); };
Change view based on fixes in resourceful
Change view based on fixes in resourceful
JavaScript
mit
pksunkara/bullet
--- +++ @@ -17,9 +17,7 @@ this.filter('all', { map: function (doc) { if (doc.resource === 'Post') { - var x = doc._id; - doc._id = doc._id.split('/').slice(1).join('/'); - emit(x, doc); + emit(doc._id, doc); } } });
92254b47944a101e37444aa4aea7f2ddb840cf38
waltz-ng/client/extensions/extensions.js
waltz-ng/client/extensions/extensions.js
// extensions initialisation import {registerComponents} from '../common/module-utils'; import {dynamicSections, dynamicSectionsByKind} from "../dynamic-section/dynamic-section-definitions"; import dbChangeInitiativeBrowser from './components/change-initiative/change-initiative-browser/db-change-initiative-browser'; import dbChangeInitiativeSection from './components/change-initiative/change-initiative-section/db-change-initiative-section'; export const init = (module) => { registerComponents(module, [ dbChangeInitiativeBrowser, dbChangeInitiativeSection ]); _overrideChangeInitiativeSection(); }; function _overrideChangeInitiativeSection() { dynamicSections.dbChangeInitiativesSection = { componentId: 'db-change-initiative-section', name: 'Change Initiatives', icon: 'paper-plane-o', id: 10000 }; dynamicSectionsByKind["APPLICATION"] = [ dynamicSections.measurableRatingAppSection, dynamicSections.entityNamedNotesSection, dynamicSections.bookmarksSection, dynamicSections.involvedPeopleSection, dynamicSections.dbChangeInitiativesSection, //overridden dynamicSections.flowDiagramsSection, dynamicSections.dataFlowSection, dynamicSections.technologySection, dynamicSections.appCostsSection, dynamicSections.entityStatisticSection, dynamicSections.surveySection, dynamicSections.changeLogSection ]; }
// extensions initialisation import _ from "lodash"; import {registerComponents} from '../common/module-utils'; import {dynamicSections, dynamicSectionsByKind} from "../dynamic-section/dynamic-section-definitions"; import dbChangeInitiativeBrowser from './components/change-initiative/change-initiative-browser/db-change-initiative-browser'; import dbChangeInitiativeSection from './components/change-initiative/change-initiative-section/db-change-initiative-section'; export const init = (module) => { registerComponents(module, [ dbChangeInitiativeBrowser, dbChangeInitiativeSection ]); overrideApplicationDynamicSections(); }; function overrideApplicationDynamicSections() { dynamicSections.dbChangeInitiativesSection = { componentId: 'db-change-initiative-section', name: 'Change Initiatives', icon: 'paper-plane-o', id: 10000 }; dynamicSectionsByKind["APPLICATION"] = _.map( dynamicSectionsByKind["APPLICATION"], ds => ds.id === dynamicSections.changeInitiativeSection.id ? dynamicSections.dbChangeInitiativesSection : ds ); }
Fix change initiative section - Override GH section with DB specific one
Fix change initiative section - Override GH section with DB specific one CTCTOWALTZ-706
JavaScript
apache-2.0
davidwatkins73/waltz-dev,kamransaleem/waltz,khartec/waltz,rovats/waltz,rovats/waltz,rovats/waltz,khartec/waltz,kamransaleem/waltz,khartec/waltz,rovats/waltz,davidwatkins73/waltz-dev,kamransaleem/waltz,kamransaleem/waltz,khartec/waltz,davidwatkins73/waltz-dev,davidwatkins73/waltz-dev
--- +++ @@ -1,5 +1,6 @@ // extensions initialisation +import _ from "lodash"; import {registerComponents} from '../common/module-utils'; import {dynamicSections, dynamicSectionsByKind} from "../dynamic-section/dynamic-section-definitions"; @@ -13,11 +14,11 @@ dbChangeInitiativeSection ]); - _overrideChangeInitiativeSection(); + overrideApplicationDynamicSections(); }; -function _overrideChangeInitiativeSection() { +function overrideApplicationDynamicSections() { dynamicSections.dbChangeInitiativesSection = { componentId: 'db-change-initiative-section', name: 'Change Initiatives', @@ -25,18 +26,10 @@ id: 10000 }; - dynamicSectionsByKind["APPLICATION"] = [ - dynamicSections.measurableRatingAppSection, - dynamicSections.entityNamedNotesSection, - dynamicSections.bookmarksSection, - dynamicSections.involvedPeopleSection, - dynamicSections.dbChangeInitiativesSection, //overridden - dynamicSections.flowDiagramsSection, - dynamicSections.dataFlowSection, - dynamicSections.technologySection, - dynamicSections.appCostsSection, - dynamicSections.entityStatisticSection, - dynamicSections.surveySection, - dynamicSections.changeLogSection - ]; + dynamicSectionsByKind["APPLICATION"] = _.map( + dynamicSectionsByKind["APPLICATION"], + ds => ds.id === dynamicSections.changeInitiativeSection.id + ? dynamicSections.dbChangeInitiativesSection + : ds + ); }
8a779ce56482ab429172aa05c49d36d500bfea16
public/backbone-marionette/js/router.js
public/backbone-marionette/js/router.js
/*global BackboneWizard, Backbone*/ BackboneWizard.Routers = BackboneWizard.Routers || {}; (function () { 'use strict'; BackboneWizard.Routers.WizardRouter = Backbone.Router.extend({ routes: { '': 'index', 'verify': 'showVerify', 'payment': 'showPayment', 'success': 'showSuccess' }, index: function () { BackboneWizard.Controllers.WizardController.index(); }, showVerify: function () { BackboneWizard.Controllers.WizardController.showVerify(); }, showPayment: function () { BackboneWizard.Controllers.WizardController.showPayment(); }, showSuccess: function () { BackboneWizard.Controllers.WizardController.showSuccess(); } }); })();
/*global BackboneWizard, Marionette*/ BackboneWizard.Routers = BackboneWizard.Routers || {}; (function () { 'use strict'; BackboneWizard.Routers.WizardRouter = Marionette.AppRouter.extend({ appRoutes: { '': 'index', 'verify': 'showVerify', 'payment': 'showPayment', 'success': 'showSuccess' } }); })();
Use Marionette.AppRouter for the Router.
Use Marionette.AppRouter for the Router.
JavaScript
mit
jonkemp/wizard-mvc
--- +++ @@ -1,32 +1,16 @@ -/*global BackboneWizard, Backbone*/ +/*global BackboneWizard, Marionette*/ BackboneWizard.Routers = BackboneWizard.Routers || {}; (function () { 'use strict'; - BackboneWizard.Routers.WizardRouter = Backbone.Router.extend({ - routes: { + BackboneWizard.Routers.WizardRouter = Marionette.AppRouter.extend({ + appRoutes: { '': 'index', 'verify': 'showVerify', 'payment': 'showPayment', 'success': 'showSuccess' - }, - - index: function () { - BackboneWizard.Controllers.WizardController.index(); - }, - - showVerify: function () { - BackboneWizard.Controllers.WizardController.showVerify(); - }, - - showPayment: function () { - BackboneWizard.Controllers.WizardController.showPayment(); - }, - - showSuccess: function () { - BackboneWizard.Controllers.WizardController.showSuccess(); } });
8ca18ff251f2f44b93ebb9050931c542628fc8d1
app/assets/javascripts/representativeSelector.js
app/assets/javascripts/representativeSelector.js
var HDO = HDO || {}; (function (H, $) { H.representativeSelector = { init: function (opts) { var districtSelect, representativeSelect, representatives, selectedRepresentatives; districtSelect = opts.districtSelect; representativeSelect = opts.representativeSelect; representatives = districtSelect.data('representatives'); function useRepresentativesFrom(district) { representativeSelect.html('<option/>'); if (district === '') { selectedRepresentatives = representatives; } else { selectedRepresentatives = $(representatives).filter(function () { return district === this.district; }); } $.each(selectedRepresentatives, function () { representativeSelect.append($("<option />").val(this.slug).text(this.name)); }); representativeSelect.trigger('liszt:updated'); // chosen } districtSelect.change(function (e) { useRepresentativesFrom($(this).val()); if (opts.selectedRepresentative !== '') { representativeSelect.val(opts.selectedRepresentative).change(); } }); if (opts.selectedDistrict !== '') { districtSelect.val(opts.selectedDistrict).change(); } representativeSelect.chosen({}); districtSelect.chosen({}); } }; }(HDO, window.jQuery));
var HDO = HDO || {}; (function (H, $) { H.representativeSelector = { init: function (opts) { var districtSelect, representativeSelect, representatives, selectedRepresentatives; districtSelect = opts.districtSelect; representativeSelect = opts.representativeSelect; representatives = districtSelect.data('representatives'); function useRepresentativesFrom(district) { representativeSelect.html('<option/>'); if (district === '') { selectedRepresentatives = representatives; } else { selectedRepresentatives = $(representatives).filter(function () { return district === this.district; }); } $.each(selectedRepresentatives, function () { representativeSelect.append($("<option />").val(this.slug).text(this.name)); }); representativeSelect.trigger('liszt:updated'); // chosen } districtSelect.change(function (e) { useRepresentativesFrom($(this).val()); if (opts.selectedRepresentative !== '') { representativeSelect.val(opts.selectedRepresentative).change(); } }); if (opts.selectedDistrict !== '') { districtSelect.val(opts.selectedDistrict).change(); } representativeSelect.chosen({search_contains: true}); districtSelect.chosen({disable_search: true}); } }; }(HDO, window.jQuery));
Disable district search + use contains filter for representatives.
Disable district search + use contains filter for representatives.
JavaScript
bsd-3-clause
holderdeord/hdo-site,holderdeord/hdo-site,holderdeord/hdo-site,holderdeord/hdo-site
--- +++ @@ -39,9 +39,8 @@ districtSelect.val(opts.selectedDistrict).change(); } - representativeSelect.chosen({}); - districtSelect.chosen({}); - + representativeSelect.chosen({search_contains: true}); + districtSelect.chosen({disable_search: true}); } }; }(HDO, window.jQuery));
728693fbf3fbad513fec2d1bee6aeabe4e5caf91
frontend/src/components/ViewActivities/activityday.js
frontend/src/components/ViewActivities/activityday.js
import React from 'react'; import Accordion from 'react-bootstrap/Accordion'; import Card from 'react-bootstrap/Card'; import Activity from './activity'; import * as activityFns from './activityfns'; import * as utils from '../Utils/utils.js' class ActivityDay extends React.Component { /** @inheritdoc */ constructor(props) { super(props); this.state = { date: props.date, activities: Array.from(props.activities).sort(activityFns.compareActivities) }; } /** @inheritdoc */ render() { let date = new Date(this.props.date); let id = date.getTime(); return ( <Card> <Accordion.Toggle as={Card.Header} eventKey="0" align="center" > {utils.timestampToDateFormatted(date.getTime())} </Accordion.Toggle> <Accordion.Collapse eventKey="0"> <Card.Body> {this.state.activities.map((activity, index) => ( <Activity activity={activity} key={index + id}/> ))} </Card.Body> </Accordion.Collapse> </Card> ); } } export default ActivityDay;
import React from 'react'; import Accordion from 'react-bootstrap/Accordion'; import Card from 'react-bootstrap/Card'; import Activity from './activity'; import * as activityFns from './activityfns'; import * as utils from '../Utils/utils.js' class ActivityDay extends React.Component { /** @inheritdoc */ constructor(props) { super(props); } /** @inheritdoc */ render() { const sortedActivities = Array.from(this.props.activities) .sort(activityFns.compareActivities); let date = new Date(this.props.date); let id = date.getTime(); return ( <Card> <Accordion.Toggle as={Card.Header} eventKey="0" align="center" > {utils.timestampToDateFormatted(date.getTime())} </Accordion.Toggle> <Accordion.Collapse eventKey="0"> <Card.Body> {sortedActivities.map((activity, index) => ( <Activity activity={activity} key={index + id}/> ))} </Card.Body> </Accordion.Collapse> </Card> ); } } export default ActivityDay;
Remove state variable where it can be removed.
Remove state variable where it can be removed.
JavaScript
apache-2.0
googleinterns/SLURP,googleinterns/SLURP,googleinterns/SLURP
--- +++ @@ -9,14 +9,12 @@ /** @inheritdoc */ constructor(props) { super(props); - this.state = { - date: props.date, - activities: Array.from(props.activities).sort(activityFns.compareActivities) - }; } /** @inheritdoc */ render() { + const sortedActivities = Array.from(this.props.activities) + .sort(activityFns.compareActivities); let date = new Date(this.props.date); let id = date.getTime(); return ( @@ -26,7 +24,7 @@ </Accordion.Toggle> <Accordion.Collapse eventKey="0"> <Card.Body> - {this.state.activities.map((activity, index) => ( + {sortedActivities.map((activity, index) => ( <Activity activity={activity} key={index + id}/> ))} </Card.Body>
1649c411366e12bc338b3486b82b0d109f97d6f0
src/modules/unit/components/UnitsOnMap.js
src/modules/unit/components/UnitsOnMap.js
import React from 'react'; import isEmpty from 'lodash/isEmpty'; import SingleUnitOnMap from './SingleUnitOnMap'; import {sortByCondition} from '../helpers'; export const UnitsOnMap = ({units, selectedUnitId, openUnit}) => { let unitsInOrder = units.slice(); // Draw things in condition order unitsInOrder = sortByCondition(unitsInOrder).reverse(); if(!isEmpty(unitsInOrder) && selectedUnitId) { const index = unitsInOrder.findIndex((unit) => unit.id === selectedUnitId); const selectedUnit = unitsInOrder[index]; unitsInOrder.push(selectedUnit); } return( <div className="units-on-map"> { !isEmpty(unitsInOrder) && unitsInOrder.map( (unit, index) => <SingleUnitOnMap isSelected={unit.id === selectedUnitId} unit={unit} key={`${index}:${unit.id}`} openUnit={openUnit} /> ) } </div> ); }; export default UnitsOnMap;
import React from 'react'; import isEmpty from 'lodash/isEmpty'; import SingleUnitOnMap from './SingleUnitOnMap'; import {sortByCondition} from '../helpers'; export const UnitsOnMap = ({units, selectedUnitId, openUnit}) => { let unitsInOrder = units.slice(); // Draw things in condition order unitsInOrder = sortByCondition(unitsInOrder).reverse(); if(!isEmpty(unitsInOrder) && selectedUnitId) { const index = unitsInOrder.findIndex((unit) => unit.id === selectedUnitId); const selectedUnit = unitsInOrder[index]; //FIXME: This fails if url parameter unitId does not exist unitsInOrder.push(selectedUnit); } return( <div className="units-on-map"> { !isEmpty(unitsInOrder) && unitsInOrder.map( (unit, index) => <SingleUnitOnMap isSelected={unit.id === selectedUnitId} unit={unit} key={`${index}:${unit.id}`} openUnit={openUnit} /> ) } </div> ); }; export default UnitsOnMap;
Add comment to fix a bug
Add comment to fix a bug
JavaScript
mit
nordsoftware/outdoors-sports-map,nordsoftware/outdoors-sports-map,nordsoftware/outdoors-sports-map
--- +++ @@ -11,7 +11,7 @@ if(!isEmpty(unitsInOrder) && selectedUnitId) { const index = unitsInOrder.findIndex((unit) => unit.id === selectedUnitId); - const selectedUnit = unitsInOrder[index]; + const selectedUnit = unitsInOrder[index]; //FIXME: This fails if url parameter unitId does not exist unitsInOrder.push(selectedUnit); }
d6090f49d653d76a65696e3c5fe8417c673c398a
auto-bind.js
auto-bind.js
'use strict'; var copy = require('es5-ext/object/copy') , map = require('es5-ext/object/map') , callable = require('es5-ext/object/valid-callable') , validValue = require('es5-ext/object/valid-value') , bind = Function.prototype.bind, defineProperty = Object.defineProperty , hasOwnProperty = Object.prototype.hasOwnProperty , define; define = function (name, desc, bindTo) { var value = validValue(desc) && callable(desc.value), dgs; dgs = copy(desc); delete dgs.writable; delete dgs.value; dgs.get = function () { if (hasOwnProperty.call(this, name)) return value; desc.value = bind.call(value, (bindTo == null) ? this : this[bindTo]); defineProperty(this, name, desc); return this[name]; }; return dgs; }; module.exports = function (props/*, bindTo*/) { var bindTo = arguments[1]; return map(props, function (desc, name) { return define(name, desc, bindTo); }); };
'use strict'; var copy = require('es5-ext/object/copy') , ensureCallable = require('es5-ext/object/valid-callable') , map = require('es5-ext/object/map') , callable = require('es5-ext/object/valid-callable') , validValue = require('es5-ext/object/valid-value') , bind = Function.prototype.bind, defineProperty = Object.defineProperty , hasOwnProperty = Object.prototype.hasOwnProperty , define; define = function (name, desc, resolveContext) { var value = validValue(desc) && callable(desc.value), dgs; dgs = copy(desc); delete dgs.writable; delete dgs.value; dgs.get = function () { if (hasOwnProperty.call(this, name)) return value; desc.value = bind.call(value, resolveContext ? resolveContext(this) : this); defineProperty(this, name, desc); return this[name]; }; return dgs; }; module.exports = function (props/*, options*/) { var options = Object(arguments[1]) , resolveContext; if (options.resolveContext != null) resolveContext = ensureCallable(options.resolveContext); return map(props, function (desc, name) { return define(name, desc, resolveContext); }); };
Reconfigure bindTo support into options.resolveContext
Reconfigure bindTo support into options.resolveContext
JavaScript
isc
medikoo/d
--- +++ @@ -1,31 +1,32 @@ 'use strict'; -var copy = require('es5-ext/object/copy') - , map = require('es5-ext/object/map') - , callable = require('es5-ext/object/valid-callable') - , validValue = require('es5-ext/object/valid-value') +var copy = require('es5-ext/object/copy') + , ensureCallable = require('es5-ext/object/valid-callable') + , map = require('es5-ext/object/map') + , callable = require('es5-ext/object/valid-callable') + , validValue = require('es5-ext/object/valid-value') , bind = Function.prototype.bind, defineProperty = Object.defineProperty , hasOwnProperty = Object.prototype.hasOwnProperty , define; -define = function (name, desc, bindTo) { +define = function (name, desc, resolveContext) { var value = validValue(desc) && callable(desc.value), dgs; dgs = copy(desc); delete dgs.writable; delete dgs.value; dgs.get = function () { if (hasOwnProperty.call(this, name)) return value; - desc.value = bind.call(value, (bindTo == null) ? this : this[bindTo]); + desc.value = bind.call(value, resolveContext ? resolveContext(this) : this); defineProperty(this, name, desc); return this[name]; }; return dgs; }; -module.exports = function (props/*, bindTo*/) { - var bindTo = arguments[1]; - return map(props, function (desc, name) { - return define(name, desc, bindTo); - }); +module.exports = function (props/*, options*/) { + var options = Object(arguments[1]) + , resolveContext; + if (options.resolveContext != null) resolveContext = ensureCallable(options.resolveContext); + return map(props, function (desc, name) { return define(name, desc, resolveContext); }); };
79e5bd95684823ee41af1d35474cb29a627328d2
example/index.js
example/index.js
var express = require('express'), app = express(), kaching = require('kaching'); app.set('views', __dirname); app.set('view engine', 'jade'); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.session({ secret: 'secret' })); app.use(kaching.initialize()); app.get('/', function(req, res) { res.render('index'); }); app.get('/kaching/paypal', function(req, res, next) { next(); }, kaching.create('paypal')); app.listen(3000);
var express = require('express'), app = express(), PaypalStrategy = require('kaching-paypal'), kaching = require('kaching'); app.set('views', __dirname); app.set('view engine', 'jade'); /** * Test account: kaching@gmail.com * Password: kachingtest */ kaching.use(new PaypalStrategy({ 'client_id': 'AVNKWRCWeT5AB6KEzKD28qyLwAl5rGi8vt3jtWpZtx--ybYDUjFivZd3EP9-', 'client_secret': 'EAiZrRC51hz6ixu7On34zHnAFYB6jgZfVoBoz15aWei3nvM1MSDidZaT1GF0' })); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(express.session({ secret: 'secret' })); app.use(kaching.initialize()); app.get('/', function(req, res) { res.render('index'); }); app.get('/kaching/paypal', function(req, res, next) { // Construct payment detail in `req.payment` req.payment = { // Payment amount, with optional details amount:{ total:'7.47', currency:'USD', details: { shipping: '1.00', subtotal: '6.00', tax: '0.47' } }, // Item list, optional item_list: { items: [ { name: 'Product', price: '3', quantity: '2', currency: 'USD' } ] }, // Payment transaction description description:'Kaching paypal test transaction' }; // Proceed to next step next(); }, kaching.create('paypal', { // Redirect URL is required for paypal payment. redirect_urls: { return_url: 'http://localhost:3000/kaching/paypal/return', cancel_url: 'http://localhost:3000/kaching/paypal/cancel' } })); app.get('/session', function(req, res) { res.json(req.session); }); app.listen(3000);
Use paypal strategy for testing.
Use paypal strategy for testing.
JavaScript
mit
gregwym/kaching
--- +++ @@ -1,9 +1,19 @@ var express = require('express'), app = express(), + PaypalStrategy = require('kaching-paypal'), kaching = require('kaching'); app.set('views', __dirname); app.set('view engine', 'jade'); + +/** + * Test account: kaching@gmail.com + * Password: kachingtest + */ +kaching.use(new PaypalStrategy({ + 'client_id': 'AVNKWRCWeT5AB6KEzKD28qyLwAl5rGi8vt3jtWpZtx--ybYDUjFivZd3EP9-', + 'client_secret': 'EAiZrRC51hz6ixu7On34zHnAFYB6jgZfVoBoz15aWei3nvM1MSDidZaT1GF0' +})); app.use(express.logger('dev')); app.use(express.bodyParser()); @@ -17,7 +27,39 @@ }); app.get('/kaching/paypal', function(req, res, next) { + // Construct payment detail in `req.payment` + req.payment = { + // Payment amount, with optional details + amount:{ + total:'7.47', + currency:'USD', + details: { + shipping: '1.00', + subtotal: '6.00', + tax: '0.47' + } + }, + // Item list, optional + item_list: { + items: [ + { name: 'Product', price: '3', quantity: '2', currency: 'USD' } + ] + }, + // Payment transaction description + description:'Kaching paypal test transaction' + }; + // Proceed to next step next(); -}, kaching.create('paypal')); +}, kaching.create('paypal', { + // Redirect URL is required for paypal payment. + redirect_urls: { + return_url: 'http://localhost:3000/kaching/paypal/return', + cancel_url: 'http://localhost:3000/kaching/paypal/cancel' + } +})); + +app.get('/session', function(req, res) { + res.json(req.session); +}); app.listen(3000);
d769d4b6df913d6b4e32e1e4b44d4f69d9f926ca
bin/cli.js
bin/cli.js
var program = require('commander'); program .description('Generate random documents, numbers, names, address, etc.') .version('0.0.1') .option('-f, --cpf', 'Select CPF') .option('-j, --cnpj', 'Select CNPJ') .option('-n, --name [gender]', 'Select Name') .option('-c, --creditCard <type>', 'Select Credit Card. Types: maestro, dinersclub, laser, jcb, unionpay, discover, mastercard, amex, visa') .option('-q, --quantity <number>', 'Quantity of generate data', parseInt) .option('-m, --mask', 'Add mask to') .option('-v, --validate <document>', 'Validate document') .option('-C, --clipboard', 'Copy text to clipboard') .parse(process.argv); module.exports = program;
var program = require('commander'); program .description('Generate random documents, numbers, names, address, etc.') .version('0.0.1') .option('-f, --cpf', 'Select CPF') .option('-j, --cnpj', 'Select CNPJ') .option('-c, --creditCard <type>', 'Select Credit Card. Types: maestro, dinersclub, laser, jcb, unionpay, discover, mastercard, amex, visa') .option('-q, --quantity <number>', 'Quantity of generate data', parseInt) .option('-m, --mask', 'Add mask to') .option('-v, --validate <document>', 'Validate document') .option('-C, --clipboard', 'Copy text to clipboard') .parse(process.argv); module.exports = program;
Remove --name feature as it's not working at the moment
Remove --name feature as it's not working at the moment
JavaScript
mit
lvendrame/dev-util-cli,lagden/dev-util-cli
--- +++ @@ -5,7 +5,6 @@ .version('0.0.1') .option('-f, --cpf', 'Select CPF') .option('-j, --cnpj', 'Select CNPJ') - .option('-n, --name [gender]', 'Select Name') .option('-c, --creditCard <type>', 'Select Credit Card. Types: maestro, dinersclub, laser, jcb, unionpay, discover, mastercard, amex, visa') .option('-q, --quantity <number>', 'Quantity of generate data', parseInt) .option('-m, --mask', 'Add mask to')
c553b7303421701a87f84d506643e88dafab7798
client/app/pages/admin/outdated-queries/index.js
client/app/pages/admin/outdated-queries/index.js
import moment from 'moment'; import { Paginator } from '@/lib/pagination'; import template from './outdated-queries.html'; function OutdatedQueriesCtrl($scope, $http, $timeout) { $scope.autoUpdate = true; this.queries = new Paginator([], { itemsPerPage: 50 }); const refresh = () => { if ($scope.autoUpdate) { $scope.refresh_time = moment().add(1, 'minutes'); $http.get('/api/admin/queries/outdated').success((data) => { this.queries.updateRows(data.queries); $scope.updatedAt = data.updated_at * 1000.0; }); } const timer = $timeout(refresh, 59 * 1000); $scope.$on('$destroy', () => { if (timer) { $timeout.cancel(timer); } }); }; refresh(); } export default function init(ngModule) { ngModule.component('outdatedQueriesPage', { template, controller: OutdatedQueriesCtrl, }); return { '/admin/queries/outdated': { template: '<outdated-queries-page></outdated-queries-page>', title: 'Outdated Queries', }, }; }
import moment from 'moment'; import { Paginator } from '@/lib/pagination'; import template from './outdated-queries.html'; function OutdatedQueriesCtrl($scope, $http, $timeout) { $scope.autoUpdate = true; this.queries = new Paginator([], { itemsPerPage: 50 }); const refresh = () => { if ($scope.autoUpdate) { $scope.refresh_time = moment().add(1, 'minutes'); $http.get('/api/admin/queries/outdated').success((data) => { this.queries.updateRows(data.queries); $scope.updatedAt = data.updated_at * 1000.0; }); } const timer = $timeout(refresh, 59 * 1000); $scope.$on('$destroy', () => { if (timer) { $timeout.cancel(timer); } }); }; refresh(); } export default function init(ngModule) { ngModule.component('outdatedQueriesPage', { template, controller: OutdatedQueriesCtrl, }); return { '/admin/queries/outdated': { template: '<outdated-queries-page></outdated-queries-page>', title: 'Outdated Queries', }, }; }
Test line end carriages redo.
Test line end carriages redo.
JavaScript
bsd-2-clause
moritz9/redash,moritz9/redash,moritz9/redash,moritz9/redash
--- +++ @@ -1,4 +1,3 @@ - import moment from 'moment'; import { Paginator } from '@/lib/pagination';
764061b8b87ff137633089f17f14e954f995cd8d
bin/cli.js
bin/cli.js
var program = require('commander'); var pkg = require('../package.json'); program .version(pkg.version) .description('Gitter bot for evaluating expressions') .usage('<room-name>') .parse(process.argv); if (!program.args[0]) { throw new Error('You must supply room'); }
var program = require('commander'); var pkg = require('../package.json'); program .version(pkg.version) .description('Gitter bot for evaluating expressions') .usage('[options] <room-name>') .option('-k, --key', 'Override API key by default') .parse(process.argv);
Add option for override default API key
Add option for override default API key
JavaScript
mit
ghaiklor/uwcua-vii
--- +++ @@ -4,9 +4,6 @@ program .version(pkg.version) .description('Gitter bot for evaluating expressions') - .usage('<room-name>') + .usage('[options] <room-name>') + .option('-k, --key', 'Override API key by default') .parse(process.argv); - -if (!program.args[0]) { - throw new Error('You must supply room'); -}
8102b934e3aa9386d2dd68acb7cb5985c68684b8
test/promises-tests.js
test/promises-tests.js
var path = require('path'); var fs = require('fs'); global.adapter = require('./adapter-a'); describe('promises-tests', function () { var testsDir = path.join(path.dirname(require.resolve('promises-aplus-tests/lib/programmaticRunner.js')), 'tests'); var testFileNames = fs.readdirSync(testsDir); testFileNames.forEach(function (testFileName) { if (path.extname(testFileName) === ".js") { var testFilePath = path.join(testsDir, testFileName); require(testFilePath); } }); });
var tests = require('promises-aplus-tests'); var adapter = require('./adapter-a'); tests.mocha(adapter);
Use newer system for programatic runner
Use newer system for programatic runner
JavaScript
mit
nodegit/promise,slang800/promise,then/promise,vigetlabs/promise,taylorhakes/promise,JoshuaWise/jellypromise,implausible/promise,ljharb/promise,npmcomponent/then-promise,astorije/promise,Bacra/promise,cpojer/promise
--- +++ @@ -1,16 +1,4 @@ -var path = require('path'); -var fs = require('fs'); +var tests = require('promises-aplus-tests'); +var adapter = require('./adapter-a'); -global.adapter = require('./adapter-a'); - -describe('promises-tests', function () { - var testsDir = path.join(path.dirname(require.resolve('promises-aplus-tests/lib/programmaticRunner.js')), 'tests'); - var testFileNames = fs.readdirSync(testsDir); - - testFileNames.forEach(function (testFileName) { - if (path.extname(testFileName) === ".js") { - var testFilePath = path.join(testsDir, testFileName); - require(testFilePath); - } - }); -}); +tests.mocha(adapter);
ec3d29cdb3231abc1bed89d5fc5a02f29addb392
examples/todo/webpack.config.js
examples/todo/webpack.config.js
var path = require('path'); module.exports = { entry: path.resolve(__dirname, 'lib', 'client.js'), output: { filename: 'app.js', path: path.resolve(__dirname, 'lib'), }, };
var path = require('path'); module.exports = { entry: [ 'babel-core/polyfill', path.resolve(__dirname, 'lib', 'client.js'), ], output: { filename: 'app.js', path: path.resolve(__dirname, 'lib'), }, };
Load babel-core/polyfill in the example (thanks to @DylanSale)
Load babel-core/polyfill in the example (thanks to @DylanSale)
JavaScript
bsd-2-clause
AndriyShepitsen/react-relay-cbi,denvned/isomorphic-relay-router
--- +++ @@ -1,7 +1,10 @@ var path = require('path'); module.exports = { - entry: path.resolve(__dirname, 'lib', 'client.js'), + entry: [ + 'babel-core/polyfill', + path.resolve(__dirname, 'lib', 'client.js'), + ], output: { filename: 'app.js', path: path.resolve(__dirname, 'lib'),
9e4798c05b4b8bbb90b448121e606263afe1aced
server/hueRoutes.js
server/hueRoutes.js
const Debug = require('debug')('iot-home:server:hue') var HueServer = {} function HueRoutes (server, middleware) { server.get('/hue/bridges', middleware.findBridge) server.get('/hue/lights', middleware.findAllLights) server.get('/hue/light/:light', middleware.getState) server.get('/hue/light/:light/on', middleware.on) server.get('/hue/light/:light/off', middleware.off) server.put('/hue/light/:light/set', middleware.setHue) server.get('/hue/users', middleware.getAllUsers) server.get('/hue/user/:username', middleware.getUser) server.post('/hue/user', middleware.newUser) server.del('/hue/user', middleware.deleteUser) server.get('/hue/config', middleware.displayConfiguration) } HueServer.init = (API, middleware) => { Debug('Initializing Hue API Routes') return new HueRoutes(API, middleware) } module.exports = HueServer
const Debug = require('debug')('iot-home:server:hue') var HueServer = {} function HueRoutes (server, middleware) { server.get('/hue/bridges', middleware.findBridge) server.get('/hue/lights', middleware.findAllLights) server.get('/hue/lights/:light', middleware.getState) server.get('/hue/lights/:light/on', middleware.on) server.get('/hue/lights/:light/off', middleware.off) server.put('/hue/lights/:light/set', middleware.setHue) server.get('/hue/users', middleware.getAllUsers) server.get('/hue/users/:username', middleware.getUser) server.post('/hue/users', middleware.newUser) server.del('/hue/users', middleware.deleteUser) server.get('/hue/config', middleware.displayConfiguration) } HueServer.init = (API, middleware) => { Debug('Initializing Hue API Routes') return new HueRoutes(API, middleware) } module.exports = HueServer
Make routes follow JSON API standards
Make routes follow JSON API standards
JavaScript
mit
harlanj/iot-home,theworkflow/iot-home
--- +++ @@ -5,14 +5,14 @@ function HueRoutes (server, middleware) { server.get('/hue/bridges', middleware.findBridge) server.get('/hue/lights', middleware.findAllLights) - server.get('/hue/light/:light', middleware.getState) - server.get('/hue/light/:light/on', middleware.on) - server.get('/hue/light/:light/off', middleware.off) - server.put('/hue/light/:light/set', middleware.setHue) + server.get('/hue/lights/:light', middleware.getState) + server.get('/hue/lights/:light/on', middleware.on) + server.get('/hue/lights/:light/off', middleware.off) + server.put('/hue/lights/:light/set', middleware.setHue) server.get('/hue/users', middleware.getAllUsers) - server.get('/hue/user/:username', middleware.getUser) - server.post('/hue/user', middleware.newUser) - server.del('/hue/user', middleware.deleteUser) + server.get('/hue/users/:username', middleware.getUser) + server.post('/hue/users', middleware.newUser) + server.del('/hue/users', middleware.deleteUser) server.get('/hue/config', middleware.displayConfiguration) }
d6e9f814bde9c63af95ec9220c768ab477b2dc5a
app/assets/javascripts/routes/sign_in_route.js
app/assets/javascripts/routes/sign_in_route.js
HB.SignInRoute = Ember.Route.extend({ beforeModel: function() { if (this.get('currentUser.isSignedIn')) { this.transitionTo('dashboard'); } } });
HB.SignInRoute = Ember.Route.extend({ beforeModel: function() { if (this.get('currentUser.isSignedIn')) { this.transitionTo('dashboard'); } }, setupController: function(controller, model) { controller.set('username', ''); controller.set('password', ''); controller.set('errorMessage', ''); } });
Reset login form on setupController
Reset login form on setupController
JavaScript
apache-2.0
saintsantos/hummingbird,MiLk/hummingbird,sidaga/hummingbird,jcoady9/hummingbird,sidaga/hummingbird,wlads/hummingbird,jcoady9/hummingbird,erengy/hummingbird,erengy/hummingbird,synthtech/hummingbird,hummingbird-me/hummingbird,vevix/hummingbird,MiLk/hummingbird,Snitzle/hummingbird,saintsantos/hummingbird,paladique/hummingbird,NuckChorris/hummingbird,hummingbird-me/hummingbird,paladique/hummingbird,xhocquet/hummingbird,NuckChorris/hummingbird,Snitzle/hummingbird,jcoady9/hummingbird,erengy/hummingbird,sidaga/hummingbird,vevix/hummingbird,paladique/hummingbird,xhocquet/hummingbird,astraldragon/hummingbird,xhocquet/hummingbird,astraldragon/hummingbird,cybrox/hummingbird,Snitzle/hummingbird,saintsantos/hummingbird,NuckChorris/hummingbird,synthtech/hummingbird,qgustavor/hummingbird,vevix/hummingbird,sidaga/hummingbird,paladique/hummingbird,NuckChorris/hummingbird,jcoady9/hummingbird,erengy/hummingbird,qgustavor/hummingbird,xhocquet/hummingbird,qgustavor/hummingbird,astraldragon/hummingbird,wlads/hummingbird,wlads/hummingbird,MiLk/hummingbird,qgustavor/hummingbird,vevix/hummingbird,xhocquet/hummingbird,Snitzle/hummingbird,MiLk/hummingbird,xhocquet/hummingbird,wlads/hummingbird,xhocquet/hummingbird,astraldragon/hummingbird,saintsantos/hummingbird
--- +++ @@ -3,5 +3,10 @@ if (this.get('currentUser.isSignedIn')) { this.transitionTo('dashboard'); } + }, + setupController: function(controller, model) { + controller.set('username', ''); + controller.set('password', ''); + controller.set('errorMessage', ''); } });
b5e62cd5dfaef3a3c9266e1ce6581830957c60dd
app/pages/browser-warning/BrowserWarning.spec.js
app/pages/browser-warning/BrowserWarning.spec.js
import React from 'react'; import BrowserWarning from './BrowserWarning'; import { shallowWithIntl } from 'utils/testUtils'; describe('pages/browser-warning/BrowserWarning', () => { function getWrapper() { return shallowWithIntl(<BrowserWarning />); } test('renders a browser warning div', () => { const div = getWrapper().find('div'); expect(div.length).toBe(1); }); test('renders a browser warning paragraph', () => { const p = getWrapper().find('p'); expect(p.length).toBe(3); }); test('renders all specified browser links', () => { const a = getWrapper().find('a'); expect(a.length).toBe(9); }); });
import React from 'react'; import BrowserWarning from './BrowserWarning'; import { shallowWithIntl } from '../../utils/testUtils'; describe('pages/browser-warning/BrowserWarning', () => { function getWrapper() { return shallowWithIntl(<BrowserWarning />); } test('renders a browser warning div', () => { const div = getWrapper().find('div'); expect(div.length).toBe(1); }); test('renders a browser warning paragraph', () => { const p = getWrapper().find('p'); expect(p.length).toBe(3); }); test('renders all specified browser links', () => { const a = getWrapper().find('a'); expect(a.length).toBe(9); }); });
Change import paths to relative for files in ./app/pages/browser-warning/ folder
Change import paths to relative for files in ./app/pages/browser-warning/ folder
JavaScript
mit
fastmonkeys/respa-ui
--- +++ @@ -1,7 +1,7 @@ import React from 'react'; import BrowserWarning from './BrowserWarning'; -import { shallowWithIntl } from 'utils/testUtils'; +import { shallowWithIntl } from '../../utils/testUtils'; describe('pages/browser-warning/BrowserWarning', () => { function getWrapper() {
0813ec552b2bbf3e3b781b0a4ccb81d142a8adb1
blueprints/ember-cli-table-pagination/index.js
blueprints/ember-cli-table-pagination/index.js
/*jshint node:true*/ module.exports = { description: 'install the addon'// , // locals: function(options) { // // Return custom template variables here. // return { // foo: options.entity.options.foo // }; // } // afterInstall: function(options) { // // Perform extra work here. // } // normalizeEntityName() { // // this prevents an error when the entityName is // // not specified (since that doesn't actually matter // // to us // } };
/*jshint node:true*/ module.exports = { description: 'install the addon', // locals: function(options) { // // Return custom template variables here. // return { // foo: options.entity.options.foo // }; // } // afterInstall: function(options) { // // Perform extra work here. // } normalizeEntityName() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us } };
Revert "try changing the blueprint"
Revert "try changing the blueprint" This reverts commit 9f6815ed2ef27ef7898fe5f2f444d2b5af1e816a.
JavaScript
mit
jking6884/ember-cli-table-pagination,gte451f/ember-cli-table-pagination,jking6884/ember-cli-table-pagination,gte451f/ember-cli-table-pagination
--- +++ @@ -1,6 +1,6 @@ /*jshint node:true*/ module.exports = { - description: 'install the addon'// , + description: 'install the addon', // locals: function(options) { // // Return custom template variables here. @@ -12,9 +12,9 @@ // afterInstall: function(options) { // // Perform extra work here. // } - // normalizeEntityName() { - // // this prevents an error when the entityName is - // // not specified (since that doesn't actually matter - // // to us - // } + normalizeEntityName() { + // this prevents an error when the entityName is + // not specified (since that doesn't actually matter + // to us + } };
c63270920685755f00bf4df93734d5e4753ea798
data/panel.js
data/panel.js
let selectElm = document.getElementById("switchy-panel-select"); selectElm.onchange = function() { self.port.emit("changeProfile", selectElm.value); } let buttons = [ 'add', 'manager', 'settings', 'about' ]; for (let i = 0; i < buttons.length; ++i) { createButton(buttons[i]); } function createButton(name) { let button = document.getElementById('switchy-panel-' + name + '-button'); button.onclick = function() { self.port.emit(name); } } self.port.on("show", function(data) { let elm = document.getElementById("switchy-current-profile"); elm.innerHTML = ''; elm.appendChild(document.createTextNode(data.currentProfile)); selectElm.innerHTML = ''; for (let i = 0; i < data.profileNames.length; ++i) { if (data.profileNames[i] == data.currentProfile) { continue; } let opt = document.createElement('option'); opt.appendChild(document.createTextNode(data.profileNames[i])); opt.setAttribute('value', data.profileNames[i]); selectElm.appendChild(opt); } });
let selectElm = document.getElementById("switchy-panel-select"); let buttons = [ 'add', 'manager', 'settings', 'about' ]; for (let i = 0; i < buttons.length; ++i) { createButton(buttons[i]); } function createButton(name) { let button = document.getElementById('switchy-panel-' + name + '-button'); button.onclick = function() { self.port.emit(name); } } self.port.on("show", function(data) { let elm = document.getElementById("switchy-current-profile"); elm.innerHTML = ''; elm.appendChild(document.createTextNode(data.currentProfile)); selectElm.innerHTML = ''; for (let i = 0; i < data.profileNames.length; ++i) { if (data.profileNames[i] == data.currentProfile) { continue; } let opt = document.createElement('option'); opt.appendChild(document.createTextNode(data.profileNames[i])); opt.setAttribute('value', data.profileNames[i]); opt.onclick = function() { self.port.emit("changeProfile", selectElm.value); } selectElm.appendChild(opt); } });
Select profile with 1 element in the select
Select profile with 1 element in the select
JavaScript
mpl-2.0
bakulf/switchy
--- +++ @@ -1,7 +1,4 @@ let selectElm = document.getElementById("switchy-panel-select"); -selectElm.onchange = function() { - self.port.emit("changeProfile", selectElm.value); -} let buttons = [ 'add', 'manager', 'settings', 'about' ]; for (let i = 0; i < buttons.length; ++i) { @@ -30,6 +27,9 @@ let opt = document.createElement('option'); opt.appendChild(document.createTextNode(data.profileNames[i])); opt.setAttribute('value', data.profileNames[i]); + opt.onclick = function() { + self.port.emit("changeProfile", selectElm.value); + } selectElm.appendChild(opt); } });
9186287a7e1881eb051fada1d782e4118804c2af
simpyapp/static/sim.js
simpyapp/static/sim.js
$(document).ready(function() { init(); $.ajaxSetup({ crossDomain: false, // obviates need for sameOrigin test beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type)) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); }); function init() { $('#compare').click(function() { $.ajax({ url: '/compare/', type: 'post', data: { doc1: $('#doc1').val(), doc2: $('#doc2').val(), }, success: function(data){ $('#result').html(data); }, }); }); } function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }
$(document).ready(function() { init(); }); function init() { $('#compare').click(function() { $.ajax({ url: '/compare/', type: 'post', data: { doc1: $('#doc1').val(), doc2: $('#doc2').val(), }, success: function(data){ $('#result').html(data); }, }); }); } // csrf $.ajaxSetup({ crossDomain: false, // obviates need for sameOrigin test beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type)) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }
Clean up csrf helper functions
Clean up csrf helper functions
JavaScript
mit
initrc/simpy,initrc/simpy
--- +++ @@ -1,13 +1,5 @@ $(document).ready(function() { init(); - $.ajaxSetup({ - crossDomain: false, // obviates need for sameOrigin test - beforeSend: function(xhr, settings) { - if (!csrfSafeMethod(settings.type)) { - xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); - } - } - }); }); function init() { @@ -26,13 +18,28 @@ }); } +// csrf +$.ajaxSetup({ + crossDomain: false, // obviates need for sameOrigin test + beforeSend: function(xhr, settings) { + if (!csrfSafeMethod(settings.type)) { + xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); + } + } +}); + +function csrfSafeMethod(method) { + // these HTTP methods do not require CSRF protection + return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); +} + function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); - // Does this cookie string begin with the name we want? + // does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; @@ -41,8 +48,3 @@ } return cookieValue; } - -function csrfSafeMethod(method) { - // these HTTP methods do not require CSRF protection - return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); -}
b6d910a90dfec796752c91b21014073f02618b01
js/containers/makeSortable.js
js/containers/makeSortable.js
'use strict'; var React = require('react'); var Sortable = require('../views/Sortable'); var {deepPureRenderMixin} = require('../react-utils'); // We skip the first column to keep 'samples' on the left. function makeSortable(Component) { return React.createClass({ displayName: 'SpreadsheetSortable', mixins: [deepPureRenderMixin], render() { var {onClick, onReorder, children, ...otherProps} = this.props, [first, ...rest] = React.Children.toArray(children); return ( <Component {...otherProps}> {first} <Sortable onClick={onClick} onReorder={order => onReorder([first.props.actionKey, ...order])}> {rest} </Sortable> </Component>); } }); } module.exports = makeSortable;
'use strict'; var React = require('react'); var Sortable = require('../views/Sortable'); var {deepPureRenderMixin} = require('../react-utils'); // We skip the first column to keep 'samples' on the left. function makeSortable(Component) { return React.createClass({ displayName: 'SpreadsheetSortable', mixins: [deepPureRenderMixin], render() { var {onClick, onReorder, children, ...otherProps} = this.props, [first, ...rest] = React.Children.toArray(children); return ( <Component {...otherProps}> <div onClick={onClick}> {first} </div> <Sortable onClick={onClick} onReorder={order => onReorder([first.props.actionKey, ...order])}> {rest} </Sortable> </Component>); } }); } module.exports = makeSortable;
Enable tooltip freeze on samples.
Enable tooltip freeze on samples.
JavaScript
apache-2.0
ucscXena/ucsc-xena-client,acthp/ucsc-xena-client,ucscXena/ucsc-xena-client,ucscXena/ucsc-xena-client,acthp/ucsc-xena-client,ucscXena/ucsc-xena-client,acthp/ucsc-xena-client,ucscXena/ucsc-xena-client
--- +++ @@ -13,7 +13,9 @@ [first, ...rest] = React.Children.toArray(children); return ( <Component {...otherProps}> - {first} + <div onClick={onClick}> + {first} + </div> <Sortable onClick={onClick} onReorder={order => onReorder([first.props.actionKey, ...order])}> {rest} </Sortable>
0098c64ebf6ecddabd6516901b986b86be3e6620
js/src/common/extend/Model.js
js/src/common/extend/Model.js
export default class Routes { type; attributes = []; hasOnes = []; hasManys = []; constructor(type, model = null) { this.type = type; this.model = model; } attribute(name) { this.attributes.push(name); return this; } hasOne(type) { this.hasOnes.push(type); return this; } hasMany(type) { this.hasManys.push(type); return this; } extend(app, extension) { if (this.model) { app.store.models[this.type] = this.model; } const model = app.store.models[this.type]; this.attributes.forEach((name) => (model.prototype[name] = model.attribute(name))); this.hasOnes.forEach((name) => (model.prototype[name] = model.hasOne(name))); this.hasManys.forEach((name) => (model.prototype[name] = model.hasMany(name))); } }
export default class Model { type; attributes = []; hasOnes = []; hasManys = []; constructor(type, model = null) { this.type = type; this.model = model; } attribute(name) { this.attributes.push(name); return this; } hasOne(type) { this.hasOnes.push(type); return this; } hasMany(type) { this.hasManys.push(type); return this; } extend(app, extension) { if (this.model) { app.store.models[this.type] = this.model; } const model = app.store.models[this.type]; this.attributes.forEach((name) => (model.prototype[name] = model.attribute(name))); this.hasOnes.forEach((name) => (model.prototype[name] = model.hasOne(name))); this.hasManys.forEach((name) => (model.prototype[name] = model.hasMany(name))); } }
Fix an irrelevant export name :P
Fix an irrelevant export name :P
JavaScript
mit
flarum/core,flarum/core,flarum/core
--- +++ @@ -1,4 +1,4 @@ -export default class Routes { +export default class Model { type; attributes = []; hasOnes = [];
b91aee96a7e3ecb45e1b70e7bb54c1c4e32547a5
src/exports.js
src/exports.js
var Game = require('./game'); var GameArtist = require('./artists/gameartist'); var EventDispatcher = require('./eventdispatcher'); var utils = require('./utils'); var EventLogger = require('./eventLogger'); var PlaybackDispatcher = require('./playbackdispatcher'); var Landmine = window.Landmine || {}; Landmine.start = function(options) { utils.requireOptions(options, 'canvas'); var eventDispatcher = options.eventDispatcher || new EventDispatcher(options.canvas); var game = new Game({ canvas: options.canvas, eventDispatcher: eventDispatcher }); //jshint unused:false var gameArtist = new GameArtist({ canvas: options.canvas, game: game }); var eventLogger = new EventLogger({ eventDispatcher: eventDispatcher }); Landmine.events = eventLogger; game.start(); }; Landmine.playback = function(options) { utils.requireOptions(options, 'canvas', 'events'); var vcr = new PlaybackDispatcher({ events: options.events }); options.eventDispatcher = vcr; Landmine.start(options); vcr.start(); }; window.Landmine = Landmine;
var Game = require('./game'); var GameArtist = require('./artists/gameartist'); var EventDispatcher = require('./eventdispatcher'); var utils = require('./utils'); var EventLogger = require('./eventlogger'); var PlaybackDispatcher = require('./playbackdispatcher'); var Landmine = window.Landmine || {}; Landmine.start = function(options) { utils.requireOptions(options, 'canvas'); var eventDispatcher = options.eventDispatcher || new EventDispatcher(options.canvas); var game = new Game({ canvas: options.canvas, eventDispatcher: eventDispatcher }); //jshint unused:false var gameArtist = new GameArtist({ canvas: options.canvas, game: game }); var eventLogger = new EventLogger({ eventDispatcher: eventDispatcher }); Landmine.events = eventLogger; game.start(); }; Landmine.playback = function(options) { utils.requireOptions(options, 'canvas', 'events'); var vcr = new PlaybackDispatcher({ events: options.events }); options.eventDispatcher = vcr; Landmine.start(options); vcr.start(); }; window.Landmine = Landmine;
Fix typo in requrie that breaks on case-sensitive FS
Fix typo in requrie that breaks on case-sensitive FS
JavaScript
mit
akatakritos/Landmine.js
--- +++ @@ -2,7 +2,7 @@ var GameArtist = require('./artists/gameartist'); var EventDispatcher = require('./eventdispatcher'); var utils = require('./utils'); -var EventLogger = require('./eventLogger'); +var EventLogger = require('./eventlogger'); var PlaybackDispatcher = require('./playbackdispatcher'); var Landmine = window.Landmine || {};
a1ed0a17b3604cd150ed653c1beb4f21d725034c
src/globals.js
src/globals.js
var base = require('jsio.base'); GLOBAL.Class = base.Class; GLOBAL.merge = base.merge; GLOBAL.bind = base.bind; // catch SIGTERM and SIGINT so `exit` events properly trigger on the process // object (e.g. killing child processes) process.on('SIGTERM', function () { process.exit(1); }); process.on('SIGINT', function () { process.exit(2); }); if (process.env.DEVKIT_TRACE) { trace = function devkitTrace () { console.log.apply(console, arguments); }; process.env.BLUEBIRD_DEBUG = 1; } else { trace = function () {}; } Promise = require('bluebird');
var base = require('jsio.base'); GLOBAL.Class = base.Class; GLOBAL.merge = base.merge; GLOBAL.bind = base.bind; // catch SIGTERM and SIGINT so `exit` events properly trigger on the process // object (e.g. killing child processes) process.on('SIGTERM', function () { process.exit(1); }); process.on('SIGINT', function () { process.exit(2); }); if (process.env.DEVKIT_TRACE) { trace = function devkitTrace () { console.log.apply(console, arguments); }; process.env.BLUEBIRD_DEBUG = 1; } else { trace = function () {}; } Promise = require('bluebird'); /** * Show devkit trace information */ var version = require(__dirname + '/../package.json').version; trace('--------------------------------------------------------------------------------'); trace('------------------------- GAME CLOSURE DEVKIT TRACE ----------------------------'); trace('--------------------------------------------------------------------------------'); trace(' VERSION =>', version, '\n\n');
Print devkit header and version info when tracing
Print devkit header and version info when tracing
JavaScript
mpl-2.0
gameclosure/devkit,gameclosure/devkit,gameclosure/devkit
--- +++ @@ -25,3 +25,13 @@ } Promise = require('bluebird'); + +/** + * Show devkit trace information + */ +var version = require(__dirname + '/../package.json').version; +trace('--------------------------------------------------------------------------------'); +trace('------------------------- GAME CLOSURE DEVKIT TRACE ----------------------------'); +trace('--------------------------------------------------------------------------------'); +trace(' VERSION =>', version, '\n\n'); +
5305aea90d10ba8c89422ccae0d75a8b22baa806
src/lib/run.js
src/lib/run.js
const path = require('path'); const babelOptions = { presets: ['es2015', 'stage-0'], plugins: ['transform-decorators-legacy', 'transform-runtime'] }; exports.module = function runModule(modulePath) { /* eslint-disable lines-around-comment, global-require */ const packageJson = require(path.resolve('package.json')); require('register-module')({ name: packageJson.name, path: path.resolve('src'), main: packageJson.main || 'index.js' }); require('babel-register')(babelOptions); require(modulePath); /* eslint-enable lines-around-comment, global-require */ }; exports.stdin = function runStdin() { /* eslint-disable lines-around-comment, no-var */ var code = ''; /* eslint-enable lines-around-comment, no-var */ process.stdin.setEncoding('utf8'); process.stdin.on('readable', () => { const data = process.stdin.read(); if (data) { code += data; } else { /* eslint-disable lines-around-comment, global-require, no-underscore-dangle */ const compiled = require('babel-core').transform(code, babelOptions); require('babel-register')(babelOptions); module._compile(compiled.code, 'stdin'); /* eslint-enable lines-around-comment, global-require, no-underscore-dangle */ } }); };
const path = require('path'); const babelOptions = { presets: ['es2015', 'stage-0'], plugins: ['transform-decorators-legacy', 'transform-runtime'] }; exports.module = function runModule(modulePath) { /* eslint-disable lines-around-comment, global-require */ const packageJson = require(path.resolve('package.json')); require('register-module')({ name: packageJson.name, path: path.resolve('src'), main: packageJson.main ? packageJson.main.replace('src/', '') : 'index.js' }); require('babel-register')(babelOptions); require(modulePath); /* eslint-enable lines-around-comment, global-require */ }; exports.stdin = function runStdin() { /* eslint-disable lines-around-comment, no-var */ var code = ''; /* eslint-enable lines-around-comment, no-var */ process.stdin.setEncoding('utf8'); process.stdin.on('readable', () => { const data = process.stdin.read(); if (data) { code += data; } else { /* eslint-disable lines-around-comment, global-require, no-underscore-dangle */ const compiled = require('babel-core').transform(code, babelOptions); require('babel-register')(babelOptions); module._compile(compiled.code, 'stdin'); /* eslint-enable lines-around-comment, global-require, no-underscore-dangle */ } }); };
Remove src/ from package.json in development
Remove src/ from package.json in development
JavaScript
mit
vinsonchuong/dist-es6
--- +++ @@ -11,7 +11,9 @@ require('register-module')({ name: packageJson.name, path: path.resolve('src'), - main: packageJson.main || 'index.js' + main: packageJson.main ? + packageJson.main.replace('src/', '') : + 'index.js' }); require('babel-register')(babelOptions); require(modulePath);
96e2badfc4d6a3bbdabe220cdbb6dd3851a6b6fc
src/global/style/utils.js
src/global/style/utils.js
//@flow export function baseAdjust(n: number): string { return ` padding-top: calc(${n}em / 16) !important; margin-bottom: calc(-${n}em / 16) !important; `; }
//@flow import { css } from "styled-components"; export const baseAdjust = (n: number) => css` padding-top: calc(${n}em / 16) !important; margin-bottom: calc(-${n}em / 16) !important; `;
Edit baseAdjust to ()=> and include css`` in styled components output
Edit baseAdjust to ()=> and include css`` in styled components output
JavaScript
mit
slightly-askew/portfolio-2017,slightly-askew/portfolio-2017
--- +++ @@ -1,8 +1,8 @@ //@flow -export function baseAdjust(n: number): string { - return ` - padding-top: calc(${n}em / 16) !important; - margin-bottom: calc(-${n}em / 16) !important; - `; -} +import { css } from "styled-components"; + +export const baseAdjust = (n: number) => css` + padding-top: calc(${n}em / 16) !important; + margin-bottom: calc(-${n}em / 16) !important; +`;
b9805279764f6fa4c3a50a4e3b9dbca7a40156c0
addon/instance-initializers/body-class.js
addon/instance-initializers/body-class.js
import Ember from 'ember'; export function initialize(instance) { const config = instance.container.lookupFactory('config:environment'); // Default to true when not set let _includeRouteName = true; if (config['ember-body-class'] && config['ember-body-class'].includeRouteName === false) { _includeRouteName = false; } Ember.Route.reopen({ classNames: [], bodyClasses: [], // Backwards compatibility addClasses: Ember.on('activate', function() { const $body = Ember.$('body'); ['bodyClasses', 'classNames'].forEach((classes) => { this.get(classes).forEach(function(klass) { $body.addClass(klass); }); }); if (_includeRouteName) { let routeName = this.get('routeName').split('.').get('lastObject'); $body.addClass(routeName); } }), removeClasses: Ember.on('deactivate', function() { const $body = Ember.$('body'); ['bodyClasses', 'classNames'].forEach((classes) => { this.get(classes).forEach(function(klass) { $body.removeClass(klass); }); }); if (_includeRouteName) { let routeName = this.get('routeName').split('.').get('lastObject'); $body.removeClass(routeName); } }), }); } export default { name: 'body-class', initialize: initialize };
import Ember from 'ember'; export function initialize(instance) { var config; if (instance.resolveRegistration) { // Ember 2.1+ // http://emberjs.com/blog/2015/08/16/ember-2-1-beta-released.html#toc_registry-and-container-reform config = instance.resolveRegistration('config:environment'); } else { config = instance.container.lookupFactory('config:environment'); } // Default to true when not set let _includeRouteName = true; if (config['ember-body-class'] && config['ember-body-class'].includeRouteName === false) { _includeRouteName = false; } Ember.Route.reopen({ classNames: [], bodyClasses: [], // Backwards compatibility _getRouteName() { const nameParts = this.get('routeName').split('.'); return nameParts[nameParts.length - 1]; }, addClasses: Ember.on('activate', function() { const $body = Ember.$('body'); ['bodyClasses', 'classNames'].forEach((classes) => { this.get(classes).forEach(function(klass) { $body.addClass(klass); }); }); if (_includeRouteName) { $body.addClass(this._getRouteName()); } }), removeClasses: Ember.on('deactivate', function() { const $body = Ember.$('body'); ['bodyClasses', 'classNames'].forEach((classes) => { this.get(classes).forEach(function(klass) { $body.removeClass(klass); }); }); if (_includeRouteName) { $body.removeClass(this._getRouteName()); } }), }); } export default { name: 'body-class', initialize: initialize };
Use updated registry in Ember 2.1
Use updated registry in Ember 2.1
JavaScript
mit
AddJam/ember-body-class,AddJam/ember-body-class
--- +++ @@ -1,7 +1,14 @@ import Ember from 'ember'; export function initialize(instance) { - const config = instance.container.lookupFactory('config:environment'); + var config; + if (instance.resolveRegistration) { + // Ember 2.1+ + // http://emberjs.com/blog/2015/08/16/ember-2-1-beta-released.html#toc_registry-and-container-reform + config = instance.resolveRegistration('config:environment'); + } else { + config = instance.container.lookupFactory('config:environment'); + } // Default to true when not set let _includeRouteName = true; @@ -13,6 +20,11 @@ classNames: [], bodyClasses: [], // Backwards compatibility + _getRouteName() { + const nameParts = this.get('routeName').split('.'); + return nameParts[nameParts.length - 1]; + }, + addClasses: Ember.on('activate', function() { const $body = Ember.$('body'); ['bodyClasses', 'classNames'].forEach((classes) => { @@ -22,8 +34,7 @@ }); if (_includeRouteName) { - let routeName = this.get('routeName').split('.').get('lastObject'); - $body.addClass(routeName); + $body.addClass(this._getRouteName()); } }), @@ -36,8 +47,7 @@ }); if (_includeRouteName) { - let routeName = this.get('routeName').split('.').get('lastObject'); - $body.removeClass(routeName); + $body.removeClass(this._getRouteName()); } }), });
8767bd64bad5313a86dca9b44c227e1b688a9d81
webpack-prod.config.js
webpack-prod.config.js
var config = module.exports = require("./webpack.config.js"); var webpack = require('webpack'); var _ = require('lodash'); config = _.merge(config, { externals : { "react" : "React" } }); var StringReplacePlugin = require("string-replace-webpack-plugin"); config.module.loaders.push({ test: /index.html$/, loader: StringReplacePlugin.replace({ replacements: [ { pattern: /<!-- externals to be replaced by webpack StringReplacePlugin -->/ig, replacement: function (match, p1, offset, string) { return '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react-with-addons.js"></script>'; } } ]}) } ); var definePlugin = new webpack.DefinePlugin({ __PRODUCTION__ : true }); config.plugins.push( new StringReplacePlugin(), definePlugin )
var config = module.exports = require("./webpack.config.js"); var webpack = require('webpack'); var _ = require('lodash'); config = _.merge(config, { externals : { "react" : "React", "react-dom" : "ReactDOM" } }); var StringReplacePlugin = require("string-replace-webpack-plugin"); config.module.loaders.push({ test: /index.html$/, loader: StringReplacePlugin.replace({ replacements: [ { pattern: /<!-- externals to be replaced by webpack StringReplacePlugin -->/ig, replacement: function (match, p1, offset, string) { return '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-with-addons.js"></script><script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.js"></script>'; } } ]}) } ); var definePlugin = new webpack.DefinePlugin({ __PRODUCTION__ : true }); config.plugins.push( new StringReplacePlugin(), definePlugin )
Update production build for react-0.14
Update production build for react-0.14
JavaScript
mit
payalabs/scalajs-react-bridge-example,payalabs/scalajs-react-bridge-example
--- +++ @@ -4,7 +4,8 @@ config = _.merge(config, { externals : { - "react" : "React" + "react" : "React", + "react-dom" : "ReactDOM" } }); @@ -18,7 +19,7 @@ { pattern: /<!-- externals to be replaced by webpack StringReplacePlugin -->/ig, replacement: function (match, p1, offset, string) { - return '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react-with-addons.js"></script>'; + return '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-with-addons.js"></script><script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.js"></script>'; } } ]})
5408013ea3ade16bd810f418d1e6e6cea992a841
db/config.js
db/config.js
//For Heroku Deployment var URI = require('urijs'); var config = URI.parse(process.env.DATABASE_URL); module.exports = config; // module.exports = { // database: 'sonder', // user: 'postgres', // //password: 'postgres', // port: 32769, // host: '192.168.99.100' // };
//For Heroku Deployment var URI = require('urijs'); var config = URI.parse(process.env.DATABASE_URL); config['ssl'] = true; module.exports = config; // module.exports = { // database: 'sonder', // user: 'postgres', // //password: 'postgres', // port: 32769, // host: '192.168.99.100' // };
Enforce SSL connection to Postgres
Enforce SSL connection to Postgres
JavaScript
mit
MapReactor/SonderServer,aarontrank/SonderServer,aarontrank/SonderServer,MapReactor/SonderServer
--- +++ @@ -1,6 +1,7 @@ //For Heroku Deployment var URI = require('urijs'); var config = URI.parse(process.env.DATABASE_URL); +config['ssl'] = true; module.exports = config; // module.exports = {
485f1e8443bee8dd5f7116112f98717edbc49a08
examples/ably.js
examples/ably.js
'use strict'; require.config({ paths: { Ably: '/ably.min' } }); define(['Ably'], function(Ably) { var ably = new Ably(); return ably; });
'use strict'; require.config({ paths: { Ably: '/ably.min' } }); /* global define */ define(['Ably'], function(Ably) { var ably = new Ably(); return ably; });
Allow "define" in examples (no-undef)
Allow "define" in examples (no-undef)
JavaScript
mit
vgno/ably
--- +++ @@ -6,6 +6,7 @@ } }); +/* global define */ define(['Ably'], function(Ably) { var ably = new Ably(); return ably;
e5a8b77baea9eca2a44fb043dcff28e73177f8a6
src/js/models.js
src/js/models.js
var Pomodoro = Backbone.Model.extend({ defaults: { isStarted: false, duration: 25 * 60, remainingSeconds: null }, initialize: function() { this.listenTo(this, 'finished', this.finish); }, start: function(duration){ if (duration) { this.set('duration', duration); } this.set('isStarted', true); this.set('remainingSeconds', this.get('duration')); var that = this; this._interval = setInterval(function(){ that.set('remainingSeconds', that.get('remainingSeconds') - 1); var remainingSeconds = that.get('remainingSeconds'); that.trigger('countedDown', remainingSeconds); if (remainingSeconds === 0){ that.trigger('finished'); } }, 1000); }, finish: function() { clearInterval(this._interval); this.stop(); }, stop: function() { this.set('isStarted', false); this.set('remainingSeconds', null); }, onChange: function(callback) { this.listenTo(this, 'countedDown', callback); }, onFinish: function(callback) { this.listenTo(this, 'finished', callback); } }); module.exports = Pomodoro;
var Pomodoro = Backbone.Model.extend({ defaults: { isStarted: false, duration: 25 * 60, remainingSeconds: null }, initialize: function() { this.listenTo(this, 'finished', this.finish); }, start: function(duration){ if (duration) { this.set('duration', duration); } this.set('isStarted', true); this.set('remainingSeconds', this.get('duration')); this.trigger('countedDown', this.get('remainingSeconds')); var that = this; clearInterval(this._interval); this._interval = setInterval(function(){ that.set('remainingSeconds', that.get('remainingSeconds') - 1); var remainingSeconds = that.get('remainingSeconds'); that.trigger('countedDown', remainingSeconds); if (remainingSeconds <= 0){ that.trigger('finished'); } }, 1000); }, finish: function() { clearInterval(this._interval); this.stop(); }, stop: function() { this.set('isStarted', false); this.set('remainingSeconds', null); }, onChange: function(callback) { this.listenTo(this, 'countedDown', callback); }, onFinish: function(callback) { this.listenTo(this, 'finished', callback); } }); module.exports = Pomodoro;
Fix bug when starting pmdr multiple times
Fix bug when starting pmdr multiple times
JavaScript
mit
namlook/pmdr
--- +++ @@ -18,13 +18,15 @@ this.set('isStarted', true); this.set('remainingSeconds', this.get('duration')); + this.trigger('countedDown', this.get('remainingSeconds')); var that = this; + clearInterval(this._interval); this._interval = setInterval(function(){ that.set('remainingSeconds', that.get('remainingSeconds') - 1); var remainingSeconds = that.get('remainingSeconds'); that.trigger('countedDown', remainingSeconds); - if (remainingSeconds === 0){ + if (remainingSeconds <= 0){ that.trigger('finished'); } }, 1000);
8552314ec2908bd82723ba50d406c48d4a0a6b59
devServer.js
devServer.js
/* eslint no-var: 0, func-names: 0 , no-console: 0 */ /** * Development Server * - See https://github.com/gaearon/react-transform-boilerplate */ var path = require('path'); var express = require('express'); var webpack = require('webpack'); var config = require('./webpack.config.dev'); var app = express(); var compiler = webpack(config); app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath, })); app.use(require('webpack-hot-middleware')(compiler)); app.get('*', function (req, res) { res.sendFile(path.join(__dirname, 'src/index.html')); }); app.listen(3000, 'localhost', function (err) { if (err) { console.log(err); return; } console.log(process.env.NODE_ENV); console.log('Listening at http://localhost:3000'); });
/* eslint no-var: 0, func-names: 0 , no-console: 0 */ /** * Development Server * - See https://github.com/gaearon/react-transform-boilerplate */ var path = require('path'); var express = require('express'); var webpack = require('webpack'); var config = require('./webpack.config.dev'); var app = express(); var compiler = webpack(config); var PORT = process.env.PORT || 3000; app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath, })); app.use(require('webpack-hot-middleware')(compiler)); app.get('*', function (req, res) { res.sendFile(path.join(__dirname, 'src/index.html')); }); app.listen(PORT, 'localhost', function (err) { if (err) { console.log(err); return; } console.log('Listening at http://localhost:' + PORT); });
Read dev server port from env if its there
[cleanup] Read dev server port from env if its there
JavaScript
mit
jackp/finance-tracker,jackp/finance-tracker
--- +++ @@ -13,6 +13,8 @@ var app = express(); var compiler = webpack(config); +var PORT = process.env.PORT || 3000; + app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath, @@ -24,11 +26,11 @@ res.sendFile(path.join(__dirname, 'src/index.html')); }); -app.listen(3000, 'localhost', function (err) { +app.listen(PORT, 'localhost', function (err) { if (err) { console.log(err); return; } - console.log(process.env.NODE_ENV); - console.log('Listening at http://localhost:3000'); + + console.log('Listening at http://localhost:' + PORT); });
a73841eb0191f1585affb4228e05af6e2e503291
shallowEqualImmutable.js
shallowEqualImmutable.js
var Immutable = require('immutable'); var is = Immutable.is.bind(Immutable), getKeys = Object.keys.bind(Object); function shallowEqualImmutable(objA, objB) { if (is(objA, objB)) { return true; } var keysA = getKeys(objA), keysB = getKeys(objB), keysAlength = keysA.length, keysBlength = keysB.length if(keysAlength !== keysBlength) { return false; } // Test for A's keys different from B. for(var i = 0; i < keysAlength; i++) { if (!objB.hasOwnProperty(keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]]) ) { return false; } } // Now we dont need to test for B's keys missing from A, // because if length's is same and prev check success - objB hasn't more keys return true; } module.exports = shallowEqualImmutable;
var Immutable = require('immutable'); var is = Immutable.is.bind(Immutable); function shallowEqualImmutable(objA, objB) { if (objA === objB || is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } module.exports = shallowEqualImmutable;
Make more similar to original version
Make more similar to original version
JavaScript
mit
steffenmllr/react-immutable-render-mixin,jurassix/react-immutable-render-mixin
--- +++ @@ -1,30 +1,32 @@ var Immutable = require('immutable'); -var is = Immutable.is.bind(Immutable), - getKeys = Object.keys.bind(Object); +var is = Immutable.is.bind(Immutable); function shallowEqualImmutable(objA, objB) { - if (is(objA, objB)) { + if (objA === objB || is(objA, objB)) { return true; } - var keysA = getKeys(objA), - keysB = getKeys(objB), - keysAlength = keysA.length, - keysBlength = keysB.length - - if(keysAlength !== keysBlength) { + + if (typeof objA !== 'object' || objA === null || + typeof objB !== 'object' || objB === null) { return false; } + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) { + return false; + } + // Test for A's keys different from B. - for(var i = 0; i < keysAlength; i++) { - if (!objB.hasOwnProperty(keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]]) ) { + var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB); + for (var i = 0; i < keysA.length; i++) { + if (!bHasOwnProperty(keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } - - // Now we dont need to test for B's keys missing from A, - // because if length's is same and prev check success - objB hasn't more keys + return true; }
926caeb0c32c3130945b2e5ba0753a989b5f1035
app/components/select-year/component.js
app/components/select-year/component.js
import Ember from 'ember'; function range(start, end) { return Array(end-start).join(0).split(0).map((val, id) => id + start); } export default Ember.Component.extend({ years: range(new Date().getFullYear(), new Date().getFullYear() + 6) });
import Ember from 'ember'; function range(start, end) { return new Array(end-start).join(0).split(0).map((val, id) => id + start); } export default Ember.Component.extend({ years: range(new Date().getFullYear(), new Date().getFullYear() + 6) });
Use new for Array construction
Use new for Array construction Fixes issue with jshint.
JavaScript
mit
blakepettersson/dashboard.aptible.com,blakepettersson/dashboard.aptible.com,aptible/dashboard.aptible.com,chasballew/dashboard.aptible.com,chasballew/dashboard.aptible.com,aptible/dashboard.aptible.com,aptible/dashboard.aptible.com,blakepettersson/dashboard.aptible.com,chasballew/dashboard.aptible.com
--- +++ @@ -1,7 +1,7 @@ import Ember from 'ember'; function range(start, end) { - return Array(end-start).join(0).split(0).map((val, id) => id + start); + return new Array(end-start).join(0).split(0).map((val, id) => id + start); } export default Ember.Component.extend({ years: range(new Date().getFullYear(), new Date().getFullYear() + 6)
15cb0b67e0850945fc3c505e902b9984c67e4923
src/components/Menu.js
src/components/Menu.js
import React from 'react'; import { Link } from 'react-router'; import './Menu.css'; import User from './User'; import language from '../language/language'; const menuLanguage = language.components.menu; let Menu = React.createClass ({ getInitialState() { return { showUser: false }; }, toggleUser() { if (!this.state.showUser) { this.setState({showUser : true}); } else { this.setState({showUser : false}); } }, render() { const { user } = this.props; let userElement; userElement = ( <User user={user} /> ); return ( <div> <ul> <li className="Menu__item"> <Link to="recent-tracks"> {menuLanguage.recentTracks} </Link> </li> <li className="Menu__item"> <Link to="top-artists"> {menuLanguage.topArtists} </Link> </li> <li className="Menu__item"> <Link to="#0" onClick={this.toggleUser}> {menuLanguage.userInfo} </Link> </li> </ul> {this.state.showUser ? userElement : null} </div> ); } }); export default Menu;
import React from 'react'; import { Link } from 'react-router'; import './Menu.css'; import User from './User'; import language from '../language/language'; const menuLanguage = language.components.menu; let Menu = React.createClass ({ getInitialState() { return { showUser: false }; }, toggleUser() { if (!this.state.showUser) { this.setState({showUser : true}); } else { this.setState({showUser : false}); } }, render() { const { user } = this.props; let userElement; userElement = ( <User user={user} /> ); return ( <div> <ul> <li className="Menu__item"> <Link to="recent-tracks"> {menuLanguage.recentTracks} </Link> </li> <li className="Menu__item"> <Link to="top-artists"> {menuLanguage.topArtists} </Link> </li> <li className="Menu__item"> <Link id="toggleUser" onClick={this.toggleUser}> {menuLanguage.userInfo} </Link> </li> </ul> {this.state.showUser ? userElement : null} </div> ); } }); export default Menu;
Add id the link where the toggleUser is bind
Add id the link where the toggleUser is bind
JavaScript
bsd-3-clause
jeromelachaud/Last.fm-Activities-React,jeromelachaud/Last.fm-Activities-React
--- +++ @@ -54,7 +54,7 @@ <li className="Menu__item"> <Link - to="#0" + id="toggleUser" onClick={this.toggleUser}> {menuLanguage.userInfo} </Link>
f76fe4e96d4c637c10d11e80a73c280c28113550
src/minipanel.js
src/minipanel.js
MiniPanel = function (game, text, x, y) { Phaser.Group.call(this, game); text = "TESTING" var style = { font: "25px Arial", align: "center" }; this.label = game.add.text(x, y, text, style) this.label.anchor.setTo(0.5) var middle = this.game.add.tileSprite(x, y, this.label.width-50, 50, 'sprites', 'best-word-frame-middle'); middle.anchor.setTo(0.5) this.add(middle) var left = this.create(x+1-middle.width/2, y, 'sprites', 'best-word-frame-left') left.anchor.setTo(1, 0.5) var right = this.create(x-1+middle.width/2, y, 'sprites', 'best-word-frame-right') right.anchor.setTo(0, 0.5) this.add(this.label) } MiniPanel.prototype = Object.create(Phaser.Group.prototype) MiniPanel.prototype.constructor = MiniPanel MiniPanel.prototype.remove = function() { this.game.add.tween(this).to({alpha: 0}, 3000, Phaser.Easing.Quadratic.In, true); } MiniPanel.prototype.update = function(text) { }
MiniPanel = function (game, text, x, y) { Phaser.Group.call(this, game); var style = { font: "25px Arial", align: "center" }; this.label = game.add.text(x, y, text, style) this.label.anchor.setTo(0.5) var middle = this.game.add.tileSprite(x, y, this.label.width-50, 50, 'sprites', 'best-word-frame-middle'); middle.anchor.setTo(0.5) this.add(middle) var left = this.create(x+1-middle.width/2, y, 'sprites', 'best-word-frame-left') left.anchor.setTo(1, 0.5) var right = this.create(x-1+middle.width/2, y, 'sprites', 'best-word-frame-right') right.anchor.setTo(0, 0.5) this.add(this.label) } MiniPanel.prototype = Object.create(Phaser.Group.prototype) MiniPanel.prototype.constructor = MiniPanel MiniPanel.prototype.remove = function() { this.game.add.tween(this).to({alpha: 0}, 3000, Phaser.Easing.Quadratic.In, true); } MiniPanel.prototype.update = function(text) { }
Remove "Testing" as best word every time
Remove "Testing" as best word every time Signed-off-by: Reicher <d5b86a7882b5bcb4262a5e66c6cf4ed497795bc7@gmail.com>
JavaScript
mit
Reicher/Lettris,Reicher/Lettris
--- +++ @@ -1,7 +1,5 @@ MiniPanel = function (game, text, x, y) { Phaser.Group.call(this, game); - - text = "TESTING" var style = { font: "25px Arial", align: "center" }; this.label = game.add.text(x, y, text, style)
8de3db905a598cc1fea5476eaa8ba7109f0ef6be
src/App.js
src/App.js
import React from 'react'; import './App.css'; import Clock from './Clock.js'; function App() { return ( <div className="App"> <Clock></Clock> {/* If you add a Weatherclock launcher to your home screen on an iPhone, the page opened will not be in a web-browser (or at least look like it's not). So we add a reload button of our own here. */} {/* FIXME: Should be "onClick" not "onclick, then read console messages for further inspiration" */} <button type="button" onclick="location.reload();">Update forecast FIXME: Handler doesnt work</button> <p>Weather forecast from <a href="yr.no">yr.no</a>, delivered by the <a href="http://met.no/English/">Norwegian Meteorological Institute</a> and the <a href="http://www.nrk.no/">NRK</a>.</p> <p>Imagine a share-on-Facebook button here</p> <p> <a href="https://github.com/walles/weatherclock">Source code on GitHub</a> </p> </div> ); } export default App;
import React from 'react'; import './App.css'; import Clock from './Clock.js'; function App() { return ( <div className="App"> <Clock></Clock> {/* If you add a Weatherclock launcher to your home screen on an iPhone, the page opened will not be in a web-browser (or at least look like it's not). So we add a reload button of our own here. */} {/* FIXME: Should be "onClick" not "onclick, then read console messages for further inspiration" */} <button type="button" onclick="location.reload();">Update forecast FIXME: Handler doesnt work</button> <p>Weather forecast from <a href="yr.no">yr.no</a>, delivered by the <a href="http://met.no/English/">Norwegian Meteorological Institute</a> and the <a href="http://www.nrk.no/">NRK</a>.</p> <p>Imagine a share-on-Facebook button here</p> <p> <a href="https://github.com/walles/weatherclock">Source code on GitHub</a> </p> </div> ); } export default App;
Add missing whitespace around link
Add missing whitespace around link
JavaScript
mit
walles/weatherclock,walles/weatherclock,walles/weatherclock,walles/weatherclock
--- +++ @@ -17,9 +17,9 @@ {/* FIXME: Should be "onClick" not "onclick, then read console messages for further inspiration" */} <button type="button" onclick="location.reload();">Update forecast FIXME: Handler doesnt work</button> - <p>Weather forecast from <a href="yr.no">yr.no</a>, delivered by the - <a href="http://met.no/English/">Norwegian Meteorological Institute</a> - and the <a href="http://www.nrk.no/">NRK</a>.</p> + <p>Weather forecast from <a href="yr.no">yr.no</a>, delivered by + the <a href="http://met.no/English/">Norwegian Meteorological + Institute</a> and the <a href="http://www.nrk.no/">NRK</a>.</p> <p>Imagine a share-on-Facebook button here</p>
652d9409708510ddcfdf3c73c92205345ef3710c
generators/needle/needle-client-base.js
generators/needle/needle-client-base.js
const needleBase = require('./needle-base'); module.exports = class extends needleBase { addStyle(style, comment, filePath, needle) { const styleBlock = this.mergeStyleAndComment(style, comment); this.addBlockContentToFile(filePath, styleBlock, needle); } mergeStyleAndComment(style, comment) { let styleBlock = ''; if (comment) { styleBlock += '/* ==========================================================================\n'; styleBlock += `${comment}\n`; styleBlock += '========================================================================== */\n'; } styleBlock += `${style}\n`; return styleBlock; } };
const needleBase = require('./needle-base'); module.exports = class extends needleBase { addStyle(style, comment, filePath, needle) { const styleBlock = this.mergeStyleAndComment(style, comment); const rewriteFileModel = this.generateFileModel(filePath, needle, styleBlock); this.addBlockContentToFile(rewriteFileModel, 'Style not added to JHipster app.\n'); } mergeStyleAndComment(style, comment) { let styleBlock = ''; if (comment) { styleBlock += '/* ==========================================================================\n'; styleBlock += `${comment}\n`; styleBlock += '========================================================================== */\n'; } styleBlock += `${style}\n`; return styleBlock; } };
Use needleNase API in clientBase
Use needleNase API in clientBase
JavaScript
apache-2.0
gmarziou/generator-jhipster,pascalgrimaud/generator-jhipster,mosoft521/generator-jhipster,wmarques/generator-jhipster,pascalgrimaud/generator-jhipster,mosoft521/generator-jhipster,gmarziou/generator-jhipster,jhipster/generator-jhipster,atomfrede/generator-jhipster,liseri/generator-jhipster,vivekmore/generator-jhipster,mosoft521/generator-jhipster,sendilkumarn/generator-jhipster,atomfrede/generator-jhipster,vivekmore/generator-jhipster,ctamisier/generator-jhipster,dynamicguy/generator-jhipster,sendilkumarn/generator-jhipster,ruddell/generator-jhipster,vivekmore/generator-jhipster,cbornet/generator-jhipster,hdurix/generator-jhipster,atomfrede/generator-jhipster,duderoot/generator-jhipster,duderoot/generator-jhipster,atomfrede/generator-jhipster,mraible/generator-jhipster,jhipster/generator-jhipster,ctamisier/generator-jhipster,mraible/generator-jhipster,wmarques/generator-jhipster,mosoft521/generator-jhipster,vivekmore/generator-jhipster,vivekmore/generator-jhipster,duderoot/generator-jhipster,hdurix/generator-jhipster,ruddell/generator-jhipster,hdurix/generator-jhipster,ctamisier/generator-jhipster,mraible/generator-jhipster,mosoft521/generator-jhipster,sendilkumarn/generator-jhipster,cbornet/generator-jhipster,ruddell/generator-jhipster,liseri/generator-jhipster,ctamisier/generator-jhipster,pascalgrimaud/generator-jhipster,mraible/generator-jhipster,hdurix/generator-jhipster,cbornet/generator-jhipster,liseri/generator-jhipster,ruddell/generator-jhipster,sendilkumarn/generator-jhipster,ruddell/generator-jhipster,mraible/generator-jhipster,sendilkumarn/generator-jhipster,wmarques/generator-jhipster,PierreBesson/generator-jhipster,liseri/generator-jhipster,hdurix/generator-jhipster,gmarziou/generator-jhipster,dynamicguy/generator-jhipster,cbornet/generator-jhipster,pascalgrimaud/generator-jhipster,dynamicguy/generator-jhipster,gmarziou/generator-jhipster,duderoot/generator-jhipster,atomfrede/generator-jhipster,liseri/generator-jhipster,wmarques/generator-jhipster,jhipster/generator-jhipster,wmarques/generator-jhipster,PierreBesson/generator-jhipster,PierreBesson/generator-jhipster,gmarziou/generator-jhipster,jhipster/generator-jhipster,dynamicguy/generator-jhipster,cbornet/generator-jhipster,ctamisier/generator-jhipster,duderoot/generator-jhipster,jhipster/generator-jhipster,PierreBesson/generator-jhipster,PierreBesson/generator-jhipster,pascalgrimaud/generator-jhipster
--- +++ @@ -3,7 +3,9 @@ module.exports = class extends needleBase { addStyle(style, comment, filePath, needle) { const styleBlock = this.mergeStyleAndComment(style, comment); - this.addBlockContentToFile(filePath, styleBlock, needle); + const rewriteFileModel = this.generateFileModel(filePath, needle, styleBlock); + + this.addBlockContentToFile(rewriteFileModel, 'Style not added to JHipster app.\n'); } mergeStyleAndComment(style, comment) {
30d333b4b38cc94b4cfad7d98b113cd949a3d248
gulp/tasks/assets.js
gulp/tasks/assets.js
import gulp from 'gulp'; import plumber from 'gulp-plumber'; import filter from 'gulp-filter'; import changed from 'gulp-changed'; import imagemin from 'gulp-imagemin'; import { plumberConfig, imageminConfig } from '../config'; export const assets = () => { const imageFilter = filter('**/*.{jpg,gif,svg,png}', { restore: true }); gulp.src([ '**/*.*', '!**/_*.*' ], { cwd: 'source/static/assets' }) .pipe(plumber(plumberConfig)) .pipe(changed('dest/assets')) // Minify images .pipe(imageFilter) .pipe(changed('dest/assets')) .pipe(imagemin(imageminConfig.images)) .pipe(imageFilter.restore) // Copy other files .pipe(gulp.dest('dest/assets')); }; export const staticFiles = () => gulp.src('**/{*,.*}', { cwd: 'source/static/public' }) .pipe(plumber(plumberConfig)) .pipe(gulp.dest('dest'));
import gulp from 'gulp'; import plumber from 'gulp-plumber'; import filter from 'gulp-filter'; import changed from 'gulp-changed'; import imagemin from 'gulp-imagemin'; import { plumberConfig, imageminConfig } from '../config'; export const assets = () => { const imageFilter = filter('**/*.{jpg,gif,svg,png}', { restore: true }); return gulp.src([ '**/*.*', '!**/_*.*' ], { cwd: 'source/static/assets' }) .pipe(plumber(plumberConfig)) .pipe(changed('dest/assets')) // Minify images .pipe(imageFilter) .pipe(changed('dest/assets')) .pipe(imagemin(imageminConfig.images)) .pipe(imageFilter.restore) // Copy other files .pipe(gulp.dest('dest/assets')); }; export const staticFiles = () => gulp.src('**/{*,.*}', { cwd: 'source/static/public' }) .pipe(plumber(plumberConfig)) .pipe(gulp.dest('dest'));
Add return for async task cmpletition
Add return for async task cmpletition
JavaScript
mit
Zoxon/gulp-front,Zoxon/gulp-front,bkzhn/gulp-front,bkzhn/gulp-front
--- +++ @@ -8,7 +8,7 @@ export const assets = () => { const imageFilter = filter('**/*.{jpg,gif,svg,png}', { restore: true }); - gulp.src([ '**/*.*', '!**/_*.*' ], { cwd: 'source/static/assets' }) + return gulp.src([ '**/*.*', '!**/_*.*' ], { cwd: 'source/static/assets' }) .pipe(plumber(plumberConfig)) .pipe(changed('dest/assets'))
f2b9463ee744299caaae1f936003e53ae0e826a6
tasks/style.js
tasks/style.js
/*eslint-disable no-alert, no-console */ import gulp from 'gulp'; import gulpLoadPlugins from 'gulp-load-plugins'; import * as paths from './paths'; const $ = gulpLoadPlugins(); gulp.task('compile:styles', () => { const AUTOPREFIXER_BROWSERS = [ 'ie >= 10', 'ie_mob >= 10', 'ff >= 30', 'chrome >= 34', 'safari >= 7', 'opera >= 23', 'ios >= 7', 'android >= 4.4', 'bb >= 10' ]; return gulp.src(paths.SRC_STYLE) .pipe($.plumber({ errorHandler: (err) => { console.log(err); this.emit('end'); } })) .pipe($.changed(paths.BUILD_DIR, {extension: '.css'})) .pipe($.sass().on('error', $.sass.logError)) .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS)) .pipe(gulp.dest(paths.TMP_DIR)) });
/*eslint-disable no-alert, no-console */ import gulp from 'gulp'; import gulpLoadPlugins from 'gulp-load-plugins'; import * as paths from './paths'; const $ = gulpLoadPlugins(); gulp.task('compile:styles', () => { // See https://github.com/ai/browserslist for more details on how to set // browser versions const AUTOPREFIXER_BROWSERS = ['last 2 versions'] return gulp.src(paths.SRC_STYLE) .pipe($.plumber({ errorHandler: (err) => { console.log(err); this.emit('end'); } })) .pipe($.changed(paths.BUILD_DIR, {extension: '.css'})) .pipe($.sass().on('error', $.sass.logError)) .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS)) .pipe(gulp.dest(paths.TMP_DIR)) });
Simplify browser version selection for autoprefixer
Simplify browser version selection for autoprefixer
JavaScript
unlicense
gsong/es6-jspm-gulp-starter,gsong/es6-jspm-gulp-starter
--- +++ @@ -9,17 +9,9 @@ gulp.task('compile:styles', () => { - const AUTOPREFIXER_BROWSERS = [ - 'ie >= 10', - 'ie_mob >= 10', - 'ff >= 30', - 'chrome >= 34', - 'safari >= 7', - 'opera >= 23', - 'ios >= 7', - 'android >= 4.4', - 'bb >= 10' - ]; + // See https://github.com/ai/browserslist for more details on how to set + // browser versions + const AUTOPREFIXER_BROWSERS = ['last 2 versions'] return gulp.src(paths.SRC_STYLE) .pipe($.plumber({
bbae0e095d80a174275d9d20bd23728f6d9b5f5b
test/buster.js
test/buster.js
exports["Buster terminal tests"] = { environment: "node", tests: ["test/**/*.js"] };
exports["Buster terminal tests"] = { environment: "node", tests: ["**/*.js"] };
Update configuration file according to new API
Update configuration file according to new API
JavaScript
bsd-3-clause
busterjs/ansi-grid,busterjs/ansi-colorizer
--- +++ @@ -1,4 +1,4 @@ exports["Buster terminal tests"] = { environment: "node", - tests: ["test/**/*.js"] + tests: ["**/*.js"] };
e3859a6937aa4848c9940f7e6bbecfa35bd845bc
src/cli.js
src/cli.js
#!/usr/bin/env node var _ = require('lodash') var yargs = require('yargs') var installer = require('./installer') var pkg = require('../package.json') var argv = yargs .version(pkg.version) .usage(pkg.description + '\n\nUsage: $0 --src <inputdir> --dest <outputdir>') .option('src', { describe: 'Directory that contains your built Electron app (e.g. with `electron-packager`)', demand: true }) .option('dest', { describe: 'Directory that will contain the resulting Windows installer', demand: true }) .option('config', { describe: 'JSON file that contains the metadata for your application', config: true }) .example('$0 --src dist/app/ --dest dist/installer/', 'use metadata from `dist/app/`') .example('$0 --src dist/app/ --dest dist/installer/ --config config.json', 'use metadata from `config.json`') .wrap(null) .argv console.log('Creating package (this may take a while)') var options = _.omit(argv, ['$0', '_', 'version']) installer(options, function (err) { if (err) { console.error(err, err.stack) process.exit(1) } console.log('Successfully created package at ' + argv.dest) })
#!/usr/bin/env node var _ = require('lodash') var yargs = require('yargs') var installer = require('./installer') var pkg = require('../package.json') var argv = yargs .version(pkg.version) .usage(pkg.description + '\n\nUsage: $0 --src <inputdir> --dest <outputdir>') .option('src', { describe: 'Directory that contains your built Electron app (e.g. with `electron-packager`)', demand: true }) .option('dest', { describe: 'Directory that will contain the resulting Windows installer', demand: true }) .option('config', { describe: 'JSON file that contains the metadata for your application', config: true }) .example('$0 --src dist/app/ --dest dist/installer/', 'use metadata from `dist/app/`') .example('$0 --src dist/app/ --dest dist/installer/ --config config.json', 'use metadata from `config.json`') .wrap(null) .argv console.log('Creating package (this may take a while)') var options = _.omit(argv, ['$0', '_', 'version']) installer(options) .then(() => console.log(`Successfully created package at ${argv.dest}`)) .catch(err => { console.error(err, err.stack) process.exit(1) })
Use promise installer when using CLI
Use promise installer when using CLI
JavaScript
mit
unindented/electron-installer-windows,unindented/electron-installer-windows
--- +++ @@ -29,11 +29,10 @@ console.log('Creating package (this may take a while)') var options = _.omit(argv, ['$0', '_', 'version']) -installer(options, function (err) { - if (err) { + +installer(options) + .then(() => console.log(`Successfully created package at ${argv.dest}`)) + .catch(err => { console.error(err, err.stack) process.exit(1) - } - - console.log('Successfully created package at ' + argv.dest) -}) + })
a7c81ff7bb40623991cbec24777f7f2fae31a2d8
plugins/async-await.js
plugins/async-await.js
module.exports = function (babel) { var t = babel.types; return { visitor: { Function: function (path) { var node = path.node; if (! node.async) { return; } node.async = false; node.body = t.blockStatement([ t.expressionStatement(t.stringLiteral("use strict")), t.returnStatement( t.callExpression( t.memberExpression( t.identifier("Promise"), t.identifier("asyncApply"), false ), [ t.functionExpression( null, // anonymous node.params.slice(0), node.body ), t.thisExpression(), t.identifier("arguments") ] ) ) ]); }, AwaitExpression: function (path) { var node = path.node; path.replaceWith(t.callExpression( t.memberExpression( t.identifier("Promise"), t.identifier(node.all ? "awaitAll" : "await"), false ), [node.argument] )); } } }; };
"use strict"; module.exports = function (babel) { const t = babel.types; return { visitor: { Function: { exit: function (path) { const node = path.node; if (! node.async) { return; } // The original function becomes a non-async function that // returns a Promise. node.async = false; const innerFn = t.functionExpression( null, // anonymous node.params.slice(0), node.body ); if (this.opts.useNativeAsyncAwait) { // The inner function called by Promise.asyncApply should be // async if we have native async/await support. innerFn.async = true; } // Calling the async function with Promise.asyncApply is // important to ensure that the part before the first await // expression runs synchronously in its own Fiber, even when // there is native support for async/await. node.body = t.blockStatement([ t.expressionStatement(t.stringLiteral("use strict")), t.returnStatement( t.callExpression( t.memberExpression( t.identifier("Promise"), t.identifier("asyncApply"), false ), [ innerFn, t.thisExpression(), t.identifier("arguments") ] ) ) ]); } }, AwaitExpression: function (path) { if (this.opts.useNativeAsyncAwait) { // No need to transform await expressions if we have native // support for them. return; } const node = path.node; path.replaceWith(t.callExpression( t.memberExpression( t.identifier("Promise"), t.identifier(node.all ? "awaitAll" : "await"), false ), [node.argument] )); } } }; };
Enable native async/await in Node 8.
Enable native async/await in Node 8.
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
--- +++ @@ -1,41 +1,64 @@ +"use strict"; + module.exports = function (babel) { - var t = babel.types; + const t = babel.types; return { visitor: { - Function: function (path) { - var node = path.node; - if (! node.async) { + Function: { + exit: function (path) { + const node = path.node; + if (! node.async) { + return; + } + + // The original function becomes a non-async function that + // returns a Promise. + node.async = false; + + const innerFn = t.functionExpression( + null, // anonymous + node.params.slice(0), + node.body + ); + + if (this.opts.useNativeAsyncAwait) { + // The inner function called by Promise.asyncApply should be + // async if we have native async/await support. + innerFn.async = true; + } + + // Calling the async function with Promise.asyncApply is + // important to ensure that the part before the first await + // expression runs synchronously in its own Fiber, even when + // there is native support for async/await. + node.body = t.blockStatement([ + t.expressionStatement(t.stringLiteral("use strict")), + t.returnStatement( + t.callExpression( + t.memberExpression( + t.identifier("Promise"), + t.identifier("asyncApply"), + false + ), [ + innerFn, + t.thisExpression(), + t.identifier("arguments") + ] + ) + ) + ]); + } + }, + + AwaitExpression: function (path) { + if (this.opts.useNativeAsyncAwait) { + // No need to transform await expressions if we have native + // support for them. return; } - node.async = false; - - node.body = t.blockStatement([ - t.expressionStatement(t.stringLiteral("use strict")), - t.returnStatement( - t.callExpression( - t.memberExpression( - t.identifier("Promise"), - t.identifier("asyncApply"), - false - ), - [ - t.functionExpression( - null, // anonymous - node.params.slice(0), - node.body - ), - t.thisExpression(), - t.identifier("arguments") - ] - ) - ) - ]); - }, - - AwaitExpression: function (path) { - var node = path.node; + const node = path.node; path.replaceWith(t.callExpression( t.memberExpression( t.identifier("Promise"),
abd2538246f0e1f38a110efa84d973dfa6118b86
lib/collections/checkID.js
lib/collections/checkID.js
Meteor.methods({ checkHKID: function (hkid) { var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/; var matchArray = hkid.match(hkidPat); if(matchArray == null){throw new Meteor.Error('invalid', 'The HKID entered is invalid')} else { var checkSum = 0; var charPart = matchArray[1]; var numPart = matchArray[2]; var checkDigit = matchArray[3]; if (charPart.length == 2) { checkSum += 9 * (charPart.charAt(0).charCodeAt(0) - 55); checkSum += 8 * (charPart.charAt(1).charCodeAt(0) - 55); } else { checkSum += 8 * (charPart.charCodeAt(0)-55); checkSum += 324; } for (var i = 0, j = 7; i < numPart.length; i++, j--){ checkSum += j * numPart.charAt(i); } var remaining = checkSum % 11; var checkNumber = 11 - remaining; if(checkDigit == checkNumber) {} else {throw new Meteor.Error('invalid', 'The HKID entered is invalid')} return(hkid) }} });
Meteor.methods({ checkHKID: function (hkid) { var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/; // HKID format = 1 or 2 letters followed by 6 numbers and 1 checksum digit. var matchArray = hkid.match(hkidPat); if(matchArray == null){idError()} var checkSum = 0; var charPart = matchArray[1]; var numPart = matchArray[2]; var checkDigit = matchArray[3]; if (charPart.length == 2) { checkSum += 9 * (charPart.charAt(0).charCodeAt(0) - 55); checkSum += 8 * (charPart.charAt(1).charCodeAt(0) - 55); } else { checkSum += 8 * (charPart.charCodeAt(0)-55); checkSum += 324; } for (var i = 0, j = 7; i < numPart.length; i++, j--){ checkSum += j * numPart.charAt(i); } var remaining = checkSum % 11; var checkNumber = 11 - remaining; if(checkDigit == checkNumber) {return("valid")} function idError () { throw new Meteor.Error('invalid', 'The HKID entered is invalid') } } });
Clean up HKID verification code
Clean up HKID verification code
JavaScript
agpl-3.0
gazhayes/Popvote-HK,gazhayes/Popvote-HK
--- +++ @@ -1,27 +1,30 @@ Meteor.methods({ checkHKID: function (hkid) { - var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/; + var hkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/; // HKID format = 1 or 2 letters followed by 6 numbers and 1 checksum digit. var matchArray = hkid.match(hkidPat); - if(matchArray == null){throw new Meteor.Error('invalid', 'The HKID entered is invalid')} else { - var checkSum = 0; - var charPart = matchArray[1]; - var numPart = matchArray[2]; - var checkDigit = matchArray[3]; - if (charPart.length == 2) { - checkSum += 9 * (charPart.charAt(0).charCodeAt(0) - 55); - checkSum += 8 * (charPart.charAt(1).charCodeAt(0) - 55); - } else { + if(matchArray == null){idError()} + var checkSum = 0; + var charPart = matchArray[1]; + var numPart = matchArray[2]; + var checkDigit = matchArray[3]; + if (charPart.length == 2) { + checkSum += 9 * (charPart.charAt(0).charCodeAt(0) - 55); + checkSum += 8 * (charPart.charAt(1).charCodeAt(0) - 55); + } + else { checkSum += 8 * (charPart.charCodeAt(0)-55); checkSum += 324; - } - for (var i = 0, j = 7; i < numPart.length; i++, j--){ + } + for (var i = 0, j = 7; i < numPart.length; i++, j--){ checkSum += j * numPart.charAt(i); } + var remaining = checkSum % 11; + var checkNumber = 11 - remaining; + if(checkDigit == checkNumber) {return("valid")} + function idError () { + throw new Meteor.Error('invalid', 'The HKID entered is invalid') + } - var remaining = checkSum % 11; - var checkNumber = 11 - remaining; - if(checkDigit == checkNumber) {} else {throw new Meteor.Error('invalid', 'The HKID entered is invalid')} - return(hkid) - }} + } });
af64cda5c55b48be439bce1457016248a28d2d82
Gruntfile.js
Gruntfile.js
/*jshint camelcase:false */ module.exports = function (grunt) { // Load all grunt tasks require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ release: { options: { bump: true, //default: true file: 'package.json', //default: package.json add: true, //default: true commit: true, //default: true tag: true, //default: true push: true, //default: true pushTags: true, //default: true npm: true, //default: true tagName: 'v<%= version %>', //default: '<%= version %>' commitMessage: 'releasing v<%= version %>', //default: 'release <%= version %>' tagMessage: 'v<%= version %>' //default: 'Version <%= version %>' } }, jshint: { options: { jshintrc: true, }, lib: ['lib/**/*.js'], }, watch: { spec: { files: [ 'lib/**/*.js', 'test/**/*.js', ], tasks: ['mochaTest:spec'], }, }, mochaTest: { options: { reporter: 'spec', }, spec: { src: ['test/spec/*.js'] } }, }); // Default task. grunt.registerTask('default', []); };
/*jshint camelcase:false */ module.exports = function (grunt) { // Load all grunt tasks require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ release: { options: { bump: true, //default: true file: 'package.json', //default: package.json add: true, //default: true commit: true, //default: true tag: true, //default: true push: true, //default: true pushTags: true, //default: true npm: true, //default: true tagName: 'v<%= version %>', //default: '<%= version %>' commitMessage: 'releasing v<%= version %>', //default: 'release <%= version %>' tagMessage: 'v<%= version %>' //default: 'Version <%= version %>' } }, jshint: { options: { jshintrc: true, }, lib: ['lib/**/*.js'], }, watch: { spec: { files: [ 'lib/**/*.js', 'test/**/*.js', ], tasks: ['mochaTest:spec'], }, unit: { files: [ 'lib/**/*.js', 'test/**/*.js', ], tasks: ['mochaTest:unit'], }, }, mochaTest: { options: { reporter: 'spec', }, spec: { src: ['test/spec/*.js'] }, unit: { src: ['test/unit/*.js'] } }, }); // Default task. grunt.registerTask('default', []); };
Create unit watcher grunt task
Create unit watcher grunt task
JavaScript
mit
thanpolas/kansas-metrics
--- +++ @@ -35,6 +35,13 @@ ], tasks: ['mochaTest:spec'], }, + unit: { + files: [ + 'lib/**/*.js', + 'test/**/*.js', + ], + tasks: ['mochaTest:unit'], + }, }, mochaTest: { options: { @@ -42,6 +49,9 @@ }, spec: { src: ['test/spec/*.js'] + }, + unit: { + src: ['test/unit/*.js'] } }, });
c4cd0f33a0d83d83f32016088ada70bb4401458e
Gruntfile.js
Gruntfile.js
/*jshint node:true */ "use strict"; var fs = require("fs"), async = require("async"); module.exports = function(grunt) { var nwDir = grunt.option("nwdir") || "./bin/node-webkit-v0.5.0-win-ia32/"; grunt.loadNpmTasks("grunt-contrib-compress"); grunt.loadNpmTasks("grunt-mkdir"); grunt.loadNpmTasks("grunt-shell"); grunt.loadTasks("./build/"); grunt.initConfig({ mkdir : { bin : { options : { create : [ "bin" ] } } }, compress : { tristis : { src : [ "src/*", "package.json" ], options : { mode : "zip", archive : "./bin/tristis.nw" } } }, shell : { launch : { command : "nw.exe ../../", options : { execOptions : { cwd : nwDir } } }, debug : { command : "nw.exe ../../ --debug", options : { execOptions : { cwd : nwDir } } } } }); grunt.registerTask("default", [ "shell:launch" ]); grunt.registerTask("debug", [ "shell:debug" ]); grunt.registerTask("release", [ "mkdir", "compress", "package" ]); };
/*jshint node:true */ "use strict"; module.exports = function(grunt) { var nwDir = grunt.option("nwdir") || "./bin/node-webkit-v0.5.1-win-ia32/"; grunt.loadNpmTasks("grunt-contrib-compress"); grunt.loadNpmTasks("grunt-mkdir"); grunt.loadNpmTasks("grunt-shell"); grunt.loadTasks("./build/"); grunt.initConfig({ mkdir : { bin : { options : { create : [ "bin" ] } } }, compress : { tristis : { src : [ "src/*", "package.json" ], options : { mode : "zip", archive : "./bin/tristis.nw" } } }, shell : { launch : { command : "nw.exe ../../", options : { execOptions : { cwd : nwDir } } }, debug : { command : "nw.exe ../../ --debug", options : { execOptions : { cwd : nwDir } } } } }); grunt.registerTask("default", [ "shell:launch" ]); grunt.registerTask("debug", [ "shell:debug" ]); grunt.registerTask("release", [ "mkdir", "compress", "package" ]); };
Clean up & node-webkit version bump
Clean up & node-webkit version bump
JavaScript
mit
tivac/falco,tivac/falco
--- +++ @@ -1,12 +1,9 @@ /*jshint node:true */ "use strict"; -var fs = require("fs"), - async = require("async"); - module.exports = function(grunt) { - var nwDir = grunt.option("nwdir") || "./bin/node-webkit-v0.5.0-win-ia32/"; + var nwDir = grunt.option("nwdir") || "./bin/node-webkit-v0.5.1-win-ia32/"; grunt.loadNpmTasks("grunt-contrib-compress"); grunt.loadNpmTasks("grunt-mkdir");
ef5f7fef4b715561983945604118bc27bb257d28
Gruntfile.js
Gruntfile.js
'use strict'; module.exports = function(grunt) { // Load all tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ pck: grunt.file.readJSON('package.json'), clean: { all: ['typebase.css'] }, watch: { less: { files: ['src/{,*/}*.less'], tasks: ['less:dev'] } }, less: { dev: { files: { "typebase.css": "src/typebase.less" } } }, sass: { dev: { files: { "typebase-sass.css": "src/typebase.sass" } } } }); grunt.registerTask('dev', [ 'watch' ]); grunt.registerTask('default', [ 'clean', 'less', ]); };
'use strict'; module.exports = function(grunt) { // Load all tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ pck: grunt.file.readJSON('package.json'), clean: { all: ['typebase.css'] }, watch: { less: { files: ['src/{,*/}*.less'], tasks: ['less:dev'] } }, less: { dev: { files: { "typebase.css": "src/typebase.less" } } }, sass: { dev: { files: { "typebase-sass.css": "src/typebase.sass" } } }, stylus: { dev: { files: { "typebase-stylus.css":"src/typebase.stylus" } } } }); grunt.registerTask('dev', [ 'watch' ]); grunt.registerTask('default', [ 'clean', 'less', ]); };
Add a grunt task to translipe stylus
Add a grunt task to translipe stylus
JavaScript
mit
devinhunt/typebase.css,devinhunt/typebase.css,aoimedia/typebase.css,Calinou/typebase.css,Calinou/typebase.css,aoimedia/typebase.css
--- +++ @@ -32,6 +32,14 @@ "typebase-sass.css": "src/typebase.sass" } } + }, + + stylus: { + dev: { + files: { + "typebase-stylus.css":"src/typebase.stylus" + } + } } });
c3fe78a28501479a475de075ebdb707821255e83
karma.conf.js
karma.conf.js
module.exports = function(karma) { const rollupConfig = require("./rollup.config")[0]; karma.set({ frameworks: ["mocha", "chai", "chai-dom", "sinon-chai"], files: [ { pattern: "src/**/!(cli|webpack).js", included: false }, "spec/**/*.spec.js" ], preprocessors: { "src/**/!(cli).js": ["rollup"], "spec/**/*.spec.js": ["rollup"] }, client: { captureConsole: true, mocha: { reporter: "html" // view on http://localhost:9876/debug.html } }, reporters: ["mocha"], browsers: ["ChromeHeadlessNoSandbox"], customLaunchers: { ChromeHeadlessNoSandbox: { base: "ChromeHeadless", flags: ["--no-sandbox"] } }, rollupPreprocessor: { output: rollupConfig.output, plugins: rollupConfig.plugins, external: undefined } }); };
module.exports = function(karma) { const rollupConfig = require("./rollup.config")[0]; karma.set({ frameworks: ["mocha", "chai", "chai-dom", "sinon-chai"], files: [ { pattern: "src/**/!(cli|webpack).js", included: false }, "spec/**/*.spec.js" ], preprocessors: { "src/**/!(cli|tasks|utils).js": ["rollup"], "spec/**/*.spec.js": ["rollup"] }, client: { captureConsole: true, mocha: { reporter: "html" // view on http://localhost:9876/debug.html } }, reporters: ["mocha"], browsers: ["ChromeHeadlessNoSandbox"], customLaunchers: { ChromeHeadlessNoSandbox: { base: "ChromeHeadless", flags: ["--no-sandbox"] } }, rollupPreprocessor: { output: rollupConfig.output, plugins: rollupConfig.plugins, external: undefined } }); };
Fix Karma trying to compile files that should not be compiled
Fix Karma trying to compile files that should not be compiled Perhaps we need another strategy here. Basically only 'frontend' files need to be compiled.
JavaScript
mit
kabisa/maji,kabisa/maji,kabisa/maji
--- +++ @@ -10,7 +10,7 @@ ], preprocessors: { - "src/**/!(cli).js": ["rollup"], + "src/**/!(cli|tasks|utils).js": ["rollup"], "spec/**/*.spec.js": ["rollup"] },
5e167fb98b87c1f21ef6787dda245560fbc786f6
lib/config.js
lib/config.js
/** * Configuration library * * On start-up: * - load a configuration file * - validate the configuration * - populate configuration secrets from environment variables * * On configuration: * - register authenticators */ 'use strict'; module.exports = { _safeGetEnvString: safeGetEnvString, load, populateEnvironmentVariables, }; /** * Module dependencies. */ const { check, mapValuesDeep } = require('./utils'); const { flow } = require('lodash'); const read = require('read-data'); /** * Assemble a configuration * * @return {Object} */ function load() { return flow(read.sync, populateEnvironmentVariables)('character.yml'); } /** * Populate configuration secrets with values from environment variables * * @param {Object} config * @return {Object} Configuration populated with values from environment variables */ function populateEnvironmentVariables(config) { return mapValuesDeep(config, safeGetEnvString); } /** * Read an environment variable and throw if it is undefined (in production) * * @param {string} name Environment variable name * @return {string} Value of the environment variable */ function safeGetEnvString(name) { if (typeof name === 'string' && name.startsWith('$')) { const variable = name.substring(1, name.length); // using soft assert so that Character can continue in limited mode with an invalid config if ( check( process.env[variable], `Missing environment variable \`${variable}\``, ) ) { return process.env[variable].trim(); } else { return undefined; } } else { return name; } }
'use strict'; module.exports = { _safeGetEnvString: safeGetEnvString, load, populateEnvironmentVariables, }; /** * Module dependencies. */ const { check, mapValuesDeep } = require('./utils'); const { flow } = require('lodash'); const read = require('read-data'); /** * Assemble a configuration * * @return {Object} */ function load() { return flow(read.sync, populateEnvironmentVariables)('character.yml'); } /** * Populate configuration secrets with values from environment variables * * @param {Object} config * @return {Object} Configuration populated with values from environment variables */ function populateEnvironmentVariables(config) { return mapValuesDeep(config, safeGetEnvString); } /** * Read an environment variable and throw if it is undefined (in production) * * @param {string} name Environment variable name * @return {string} Value of the environment variable */ function safeGetEnvString(name) { if (typeof name === 'string' && name.startsWith('$')) { const variable = name.substring(1, name.length); // using soft assert so that Character can continue in limited mode with an invalid config if ( check( process.env[variable], `Missing environment variable \`${variable}\``, ) ) { return process.env[variable].trim(); } else { return undefined; } } else { return name; } }
Remove old and incorrect workflow docs
Remove old and incorrect workflow docs
JavaScript
mit
HiFaraz/identity-desk
--- +++ @@ -1,15 +1,3 @@ -/** - * Configuration library - * - * On start-up: - * - load a configuration file - * - validate the configuration - * - populate configuration secrets from environment variables - * - * On configuration: - * - register authenticators - */ - 'use strict'; module.exports = {