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
079f1469cfd4daca8d9c900835ea557f94304a1e
app/assets/javascripts/pageflow/editor/views/change_theme_view.js
app/assets/javascripts/pageflow/editor/views/change_theme_view.js
pageflow.ChangeThemeView = Backbone.Marionette.ItemView.extend({ template: 'templates/change_theme', ui: { changeThemeButton: '.change_theme', labelText: 'label .name' }, events: { 'click .change_theme': function() { pageflow.ChangeThemeDialogView.open({ model: this.model, themes: this.options.themes }); } }, onRender: function() { this.ui.labelText.text(this.labelText()); }, labelText: function() { return this.options.label || this.labelPrefix() + ': ' + this.localizedThemeName(); }, labelPrefix: function() { return I18n.t('pageflow.editor.templates.change_theme.current_prefix'); }, localizedThemeName: function() { return I18n.t('pageflow.' + this.model.get('theme_name') + '_theme.name'); } });
pageflow.ChangeThemeView = Backbone.Marionette.ItemView.extend({ template: 'templates/change_theme', ui: { changeThemeButton: '.change_theme', labelText: 'label .name' }, events: { 'click .change_theme': function() { pageflow.ChangeThemeDialogView.open({ model: this.model, themes: this.options.themes }); } }, initialize: function(options) { this.listenTo(this.model, 'change:theme_name', this.render); }, onRender: function() { this.ui.labelText.text(this.labelText()); }, labelText: function() { return this.options.label || this.labelPrefix() + ': ' + this.localizedThemeName(); }, labelPrefix: function() { return I18n.t('pageflow.editor.templates.change_theme.current_prefix'); }, localizedThemeName: function() { return I18n.t('pageflow.' + this.model.get('theme_name') + '_theme.name'); } });
Update chosen theme in ChangeThemeView on theme change
Update chosen theme in ChangeThemeView on theme change
JavaScript
mit
codevise/pageflow,codevise/pageflow,tf/pageflow,tf/pageflow,tf/pageflow-dependabot-test,Modularfield/pageflow,Modularfield/pageflow,Modularfield/pageflow,tf/pageflow,tf/pageflow,codevise/pageflow,Modularfield/pageflow,codevise/pageflow,tf/pageflow-dependabot-test,tf/pageflow-dependabot-test,tf/pageflow-dependabot-test
--- +++ @@ -13,6 +13,10 @@ themes: this.options.themes }); } + }, + + initialize: function(options) { + this.listenTo(this.model, 'change:theme_name', this.render); }, onRender: function() {
98ce6706af142a0383449e4b734907741ce5a898
karma.conf.js
karma.conf.js
var path = require("path"); module.exports = function (config) { config.set({ logLevel: config.LOG_DEBUG, port: 3334, browsers: ["PhantomJS"], singleRun: true, frameworks: ["jasmine"], files: [ "src/**/*Tests.ts" ], preprocessors: { "src/**/*Tests.ts": ["webpack", "sourcemap"] }, reporters: ["progress"], webpack: require("./webpack.config.js"), webpackServer: { noInfo: true }, }); };
var path = require("path"); module.exports = function (config) { config.set({ logLevel: config.LOG_DEBUG, port: 3334, browsers: ["PhantomJS"], singleRun: true, frameworks: ["jasmine"], files: [ "src/**/*Tests.ts" ], mime: { "text/x-typescript": ["ts"] }, preprocessors: { "src/**/*Tests.ts": ["webpack", "sourcemap"] }, reporters: ["progress"], webpack: require("./webpack.config.js"), webpackServer: { noInfo: true }, }); };
Fix to get tests running again.
Fix to get tests running again.
JavaScript
apache-2.0
matthewrwilton/citibank-statement-to-sheets,matthewrwilton/citibank-statement-to-sheets,matthewrwilton/citibank-statement-to-sheets
--- +++ @@ -10,6 +10,9 @@ files: [ "src/**/*Tests.ts" ], + mime: { + "text/x-typescript": ["ts"] + }, preprocessors: { "src/**/*Tests.ts": ["webpack", "sourcemap"] },
bd0deb99380267ae9636791180cbe39eaf9ef8e5
app.js
app.js
(function() { var todolist = document.querySelector('#todolist'); var todolistView = new ToMvc.View( 'todolist', '#todolist' ); var todolistModel = new ToMvc.Model( 'todolist' ); var nrTodos = 0; function init() { document.querySelector('#add-todo button').addEventListener( 'click', addTodo, false); todolistModel.listenTo( 'todo:added', function( data ) { var key = nrTodos++; localStorage.setItem( nrTodos, data ); }); } function addTodo() { var text = window.prompt('enter event'); if (!text) return; var li = document.createElement('li'); li.textContent = text; todolist.appendChild(li); // Added todo must be send to Model todolistView.broadcast( 'todo:added', text); // Immediately ask for another todo to enter addTodo(); } // GO! init(); }());
( function() { var todolist = document.querySelector( '#todolist' ); var todolistView = new ToMvc.View( 'todolist', '#todolist' ); var todolistModel = new ToMvc.Model( 'todolist' ); // var todolistModel = function() { // this.name = 'todolist'; // } // todolistModel.prototype = new ToMvc.View; function init() { document.querySelector( '#add-todo button' ).addEventListener( 'click', addTodo, false ); // console.info( 'model', todolistModel ); // var currentTodos = todolistModel.getCurrentTodos(); var currentTodos = getCurrentTodos(); writeCurrentTodos( currentTodos ); todolistModel.listenTo( 'todo:added', function( data ) { var key = window.localStorage.length + 1; window.localStorage.setItem( key, data ); } ); } // model method // todolistModel.prototype.getCurrentTodos = function() { function getCurrentTodos() { var list = []; for ( var key in localStorage ) { list.push( window.localStorage.getItem( key ) ); } // TODO re-index keys because of deletions return list; } function writeCurrentTodos( list ) { list.forEach( function( item ) { writeTodo( item ); } ); } // view method function addTodo() { var text = window.prompt( 'enter event' ); if ( !text ) return; writeTodo( text ); // Added todo must be send to Model todolistView.broadcast( 'todo:added', text ); // Immediately ask for another todo to enter addTodo(); } // view method function writeTodo( text ) { var li = document.createElement( 'li' ); li.textContent = text; todolist.appendChild( li ); } // GO! init(); }() );
Add created todos to localStorage
Add created todos to localStorage
JavaScript
mit
ludder/tomvc
--- +++ @@ -1,35 +1,69 @@ -(function() { - var todolist = document.querySelector('#todolist'); - var todolistView = new ToMvc.View( 'todolist', '#todolist' ); +( function() { + var todolist = document.querySelector( '#todolist' ); + var todolistView = new ToMvc.View( 'todolist', '#todolist' ); var todolistModel = new ToMvc.Model( 'todolist' ); - var nrTodos = 0; + + + // var todolistModel = function() { + // this.name = 'todolist'; + // } + // todolistModel.prototype = new ToMvc.View; + function init() { - document.querySelector('#add-todo button').addEventListener( 'click', addTodo, false); + document.querySelector( '#add-todo button' ).addEventListener( 'click', addTodo, false ); + + // console.info( 'model', todolistModel ); + // var currentTodos = todolistModel.getCurrentTodos(); + var currentTodos = getCurrentTodos(); + writeCurrentTodos( currentTodos ); todolistModel.listenTo( 'todo:added', function( data ) { - var key = nrTodos++; - localStorage.setItem( nrTodos, data ); - }); + var key = window.localStorage.length + 1; + window.localStorage.setItem( key, data ); + } ); } + // model method + // todolistModel.prototype.getCurrentTodos = function() { + function getCurrentTodos() { + var list = []; + for ( var key in localStorage ) { + list.push( window.localStorage.getItem( key ) ); + } + // TODO re-index keys because of deletions + return list; + } + + function writeCurrentTodos( list ) { + list.forEach( function( item ) { + writeTodo( item ); + } ); + } + + // view method function addTodo() { - var text = window.prompt('enter event'); - if (!text) return; + var text = window.prompt( 'enter event' ); + if ( !text ) return; - var li = document.createElement('li'); - li.textContent = text; - todolist.appendChild(li); + writeTodo( text ); // Added todo must be send to Model - todolistView.broadcast( 'todo:added', text); + todolistView.broadcast( 'todo:added', text ); // Immediately ask for another todo to enter addTodo(); + } + + // view method + function writeTodo( text ) { + var li = document.createElement( 'li' ); + li.textContent = text; + todolist.appendChild( li ); } // GO! init(); -}()); +}() );
0c425775317ef58273184f031affafc2a6e61330
lib/middlewares.js
lib/middlewares.js
var twilio = require('twilio'); var _ = require('lodash'); var config = require('./config'); // Middleware to valid the request is coming from twilio function validRequest(req, res, next) { if (twilio.validateExpressRequest(req, config.twilio.token)) { next() } else { res.status(403).send('You are not Twilio!'); } } // Block non team member function teamMember(req, res, next) { var from = req.body.From; var member = _.find(config.team, { phone: from}); if (member) { req.teamMember = member; next(); } else { res.status(403).send('Limited to team member'); } } module.exports = { valid: validRequest, team: teamMember };
var twilio = require('twilio'); var _ = require('lodash'); var config = require('./config'); // Middleware to valid the request is coming from twilio function validRequest(req, res, next) { if (!twilio.validateExpressRequest(req, config.twilio.token)) { next() } else { res.status(403).send('You are not Twilio!'); } } // Block non team member function teamMember(req, res, next) { var from = req.body.From; var member = _.find(config.team, { phone: from}); if (member) { req.teamMember = member; next(); } else { res.status(403).send('Limited to team member'); } } module.exports = { valid: validRequest, team: teamMember };
Fix valid of twilio request
Fix valid of twilio request
JavaScript
apache-2.0
hart/betty,hart/betty,SamyPesse/betty,SamyPesse/betty,nelsonic/betty,nelsonic/betty
--- +++ @@ -5,7 +5,7 @@ // Middleware to valid the request is coming from twilio function validRequest(req, res, next) { - if (twilio.validateExpressRequest(req, config.twilio.token)) { + if (!twilio.validateExpressRequest(req, config.twilio.token)) { next() } else { res.status(403).send('You are not Twilio!');
d0a6efa2827627c67743eb0f248a981b69a0d68a
whenever.js
whenever.js
var Whenever = function(){ var callbacks = []; var ready = false; var args; return { ready: function(){ args = arguments; callbacks.forEach(function(callback){ callback.apply(this, args); }); ready = this; }, whenReady: function(callback){ if(ready){ callback.apply(this, args); }else{ callbacks.push(callback); } } } };
var Whenever = function(){ var callbacks = []; var ready = false; var args; return { get state(){ return { ready: ready, args: args, pendingCallbacks: callbacks.length }; }, ready: function(){ args = arguments; callbacks.forEach(function(callback){ callback.apply(this, args); }); callbacks = []; ready = true; }, whenReady: function(callback){ if(ready){ callback.apply(this, args); }else{ callbacks.push(callback); } } } };
Add state object and improve memory usage
Add state object and improve memory usage
JavaScript
mit
David-Mulder/whenever.js
--- +++ @@ -3,12 +3,20 @@ var ready = false; var args; return { + get state(){ + return { + ready: ready, + args: args, + pendingCallbacks: callbacks.length + }; + }, ready: function(){ args = arguments; callbacks.forEach(function(callback){ callback.apply(this, args); }); - ready = this; + callbacks = []; + ready = true; }, whenReady: function(callback){ if(ready){
3d24b99f496ad3707fb3fc6bc5136b44cf4a3a97
generators/karma-conf/templates/karma-coverage.conf.js
generators/karma-conf/templates/karma-coverage.conf.js
'use strict'; module.exports = function(config) { config.set({ frameworks: ['<%= testFramework %>', 'browserify'], files: [ 'src/**/*.js', 'test/**/*.js', { pattern: 'src/**/*.ts', included: false, watched: false }, { pattern: 'test/**/*.ts', included: false, watched: false }, { pattern: 'src/**/*.js.map', included: false, watched: true }, { pattern: 'test/**/*.js.map', included: false, watched: true } ], preprocessors: { 'src/**/*.js': ['browserify'], 'test/**/*.js': ['browserify'] }, browserify: { transform: ['browserify-istanbul'] }, browsers: [ 'Chrome' ], reporters: ['progress', 'coverage'], coverageReporter: { type: 'json', subdir: '.', file: 'coverage-final.json' }, singleRun: true }); };
'use strict'; module.exports = function(config) { config.set({ // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['<%= testFramework %>', 'browserify'], // list of files / patterns to load in the browser files: [ 'src/**/*.js', 'test/**/*.js', { pattern: 'src/**/*.ts', included: false, watched: false }, { pattern: 'test/**/*.ts', included: false, watched: false }, { pattern: 'src/**/*.js.map', included: false, watched: true }, { pattern: 'test/**/*.js.map', included: false, watched: true } ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'src/**/*.js': ['browserify'], 'test/**/*.js': ['browserify'] }, browserify: { transform: ['browserify-istanbul'] }, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: [ 'Chrome' ], // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage'], coverageReporter: { type: 'json', subdir: '.', file: 'coverage-final.json' }, // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true }); };
Update karma coverage file comments.
Update karma coverage file comments.
JavaScript
mit
yohangz/generator-typescript-npm-bower,yohangz/generator-typescript-npm-bower,yohangz/generator-typescript-npm-bower
--- +++ @@ -3,7 +3,11 @@ module.exports = function(config) { config.set({ + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['<%= testFramework %>', 'browserify'], + + // list of files / patterns to load in the browser files: [ 'src/**/*.js', 'test/**/*.js', @@ -12,23 +16,38 @@ { pattern: 'src/**/*.js.map', included: false, watched: true }, { pattern: 'test/**/*.js.map', included: false, watched: true } ], + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'src/**/*.js': ['browserify'], 'test/**/*.js': ['browserify'] }, + + browserify: { transform: ['browserify-istanbul'] }, + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: [ 'Chrome' ], + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage'], - coverageReporter: { - type: 'json', - subdir: '.', - file: 'coverage-final.json' - }, + + coverageReporter: { + type: 'json', + subdir: '.', + file: 'coverage-final.json' + }, + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits singleRun: true - }); };
d38a4d3011421fc8fe4681170401cb234426e78d
src/js/containers/App.js
src/js/containers/App.js
import React, { Component, PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import InvitationDialog from '../components/InvitationDialog'; import * as inviteActions from '../actions/invite'; import * as bootstrapUtils from 'react-bootstrap/lib/utils/bootstrapUtils'; import Button from 'react-bootstrap/lib/Button'; import Panel from 'react-bootstrap/lib/Panel'; bootstrapUtils.addStyle(Button, 'clear'); bootstrapUtils.bsSizes(['fab', 'fab-mini'], Button); bootstrapUtils.addStyle(Panel, 'clear'); let ConnectedInvitation = connect(state => { return { invitation: state.invite.received }; }, dispatch => { return bindActionCreators({respondToInvitation: inviteActions.answer}, dispatch); })(InvitationDialog); export default class Main extends Component { static contextTypes = { store: PropTypes.object }; render() { return ( <div className='fullScreen'> {/* this will render the child routes */} {this.props.children} <ConnectedInvitation /> </div> ); } }
import React, { Component, PropTypes } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import InvitationDialog from '../components/InvitationDialog'; import * as inviteActions from '../actions/invite'; import * as bootstrapUtils from 'react-bootstrap/lib/utils/bootstrapUtils'; import Button from 'react-bootstrap/lib/Button'; import Panel from 'react-bootstrap/lib/Panel'; bootstrapUtils.addStyle(Button, 'clear'); bootstrapUtils.bsSizes(['fab', 'fab-mini'], Button); bootstrapUtils.addStyle(Panel, 'clear'); let ConnectedInvitation = connect(state => { return { invitation: state.invite.received }; }, dispatch => { return bindActionCreators({respondToInvitation: inviteActions.answer}, dispatch); })(InvitationDialog); export default class Main extends Component { static contextTypes = { store: PropTypes.object }; render() { return ( <div className='fullScreen'> <a href="https://github.com/webcom-components/visio-sample"> <img style={{position: 'absolute', top: 0, left: 0, border: 0}} alt="Fork me on GitHub" src="https://s3.amazonaws.com/github/ribbons/forkme_left_orange_ff7600.png" /> </a> {/* this will render the child routes */} {this.props.children} <ConnectedInvitation /> </div> ); } }
Add "Fork me on GitHub" ribbon
chore(fork): Add "Fork me on GitHub" ribbon
JavaScript
mit
webcom-components/visio-sample,webcom-components/visio-sample,webcom-components/visio-sample
--- +++ @@ -25,9 +25,17 @@ store: PropTypes.object }; + render() { return ( <div className='fullScreen'> + <a href="https://github.com/webcom-components/visio-sample"> + <img + style={{position: 'absolute', top: 0, left: 0, border: 0}} + alt="Fork me on GitHub" + src="https://s3.amazonaws.com/github/ribbons/forkme_left_orange_ff7600.png" + /> + </a> {/* this will render the child routes */} {this.props.children} <ConnectedInvitation />
ba3ff79946cc25f8b3f5eebe3f544d0c8c233dfa
src/util/define-properties.js
src/util/define-properties.js
export default function (obj, props) { Object.keys(props).forEach(function (name) { const prop = props[name]; const descrptor = Object.getOwnPropertyDescriptor(obj, name); const isDinosaurBrowser = name !== 'arguments' && name !== 'caller' && 'value' in prop; const isConfigurable = !descrptor || descrptor.configurable; if (isConfigurable) { Object.defineProperty(obj, name, prop); } else if (isDinosaurBrowser) { obj[name] = prop.value; } }); }
export default function (obj, props) { Object.keys(props).forEach(function (name) { const prop = props[name]; const descriptor = Object.getOwnPropertyDescriptor(obj, name); const isDinosaurBrowser = name !== 'arguments' && name !== 'caller' && 'value' in prop; const isConfigurable = !descriptor || descriptor.configurable; const isWritable = !descriptor || descriptor.writable; if (isConfigurable) { Object.defineProperty(obj, name, prop); } else if (isDinosaurBrowser && isWritable) { obj[name] = prop.value; } }); }
Fix variable spelling error and ensure prop is writable before applying it.
Fix variable spelling error and ensure prop is writable before applying it.
JavaScript
mit
chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs
--- +++ @@ -1,13 +1,14 @@ export default function (obj, props) { Object.keys(props).forEach(function (name) { const prop = props[name]; - const descrptor = Object.getOwnPropertyDescriptor(obj, name); + const descriptor = Object.getOwnPropertyDescriptor(obj, name); const isDinosaurBrowser = name !== 'arguments' && name !== 'caller' && 'value' in prop; - const isConfigurable = !descrptor || descrptor.configurable; + const isConfigurable = !descriptor || descriptor.configurable; + const isWritable = !descriptor || descriptor.writable; if (isConfigurable) { Object.defineProperty(obj, name, prop); - } else if (isDinosaurBrowser) { + } else if (isDinosaurBrowser && isWritable) { obj[name] = prop.value; } });
28fd05ef69b975df9aec6f2e93d39ede4d2fb5f1
gulpfile.js
gulpfile.js
var gulp = require('gulp'), sass = require('gulp-sass'), cssmin = require('gulp-minify-css'), prefix = require('gulp-autoprefixer'), rename = require('gulp-rename'), header = require('gulp-header'), pkg = require('./package.json'), banner = [ '/*!', ' <%= pkg.name %> v<%= pkg.version %>', ' Written by <%= pkg.author.name %>', ' <%= pkg.author.url %>', ' <%= pkg.author.email %>', ' License: <%= pkg.license %>', '*/','' ].join('\n'); gulp.task('build', function() { return gulp.src('src/*.scss') .pipe( sass() ) .pipe( prefix('> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1') ) .pipe( header(banner, {pkg: pkg}) ) .pipe( gulp.dest('dist/') ) .pipe( cssmin() ) .pipe( rename({suffix: '.min'}) ) .pipe( gulp.dest('dist/') ); });
var gulp = require('gulp'), sass = require('gulp-sass'), cssmin = require('gulp-minify-css'), prefix = require('gulp-autoprefixer'), rename = require('gulp-rename'), header = require('gulp-header'), pkg = require('./package.json'), banner = [ '/*!', ' <%= pkg.name %> v<%= pkg.version %>', ' Written by <%= pkg.author.name %>', ' <%= pkg.author.url %>', ' <%= pkg.author.email %>', ' License: <%= pkg.license %>', '*/','' ].join('\n'); gulp.task('build', function() { return gulp.src('src/*.scss') .pipe( sass() ) .pipe( prefix('> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1') ) .pipe( header(banner, {pkg: pkg}) ) .pipe( gulp.dest('dist/') ) .pipe( cssmin() ) .pipe( rename({suffix: '.min'}) ) .pipe( gulp.dest('dist/') ); }); gulp.task('default',['build']);
Create default gulp task, that depends on build
Create default gulp task, that depends on build
JavaScript
mit
KolibriDev/Cress
--- +++ @@ -25,3 +25,5 @@ .pipe( rename({suffix: '.min'}) ) .pipe( gulp.dest('dist/') ); }); + +gulp.task('default',['build']);
3939f1697d5c8e1a50cf71a034aa0cd07e24cfee
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var runSequence = require('run-sequence'); var bs = require('browser-sync').create(); var del = require('del'); gulp.task('lint', function () { return gulp.src('app/js/**/*.js') .pipe($.eslint()) .pipe($.eslint.format()) .pipe($.eslint.failAfterError()); }); gulp.task('serve', function () { bs.init({ notify: false, port: 9000, open: true, server: { baseDir: ['app'] } }); gulp.watch([ 'app/**/*.html', 'app/js/**/*.js' ]).on('change', bs.reload); gulp.watch('app/js/**/*.js', ['lint']); }); gulp.task('clean', del.bind(null, ['dist'])); gulp.task('scripts', function () { return gulp.src('app/js/**/*.js') .pipe($.uglify()) .pipe(gulp.dest('dist/js')); }); gulp.task('html', function () { return gulp.src('app/**/*.html') .pipe($.htmlmin({ collapseWhitespace: true })) .pipe(gulp.dest('dist')); }); gulp.task('build', ['clean'], function (callback) { runSequence(['scripts', 'html'], callback); }); gulp.task('default', ['build']);
'use strict'; var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var runSequence = require('run-sequence'); var bs = require('browser-sync').create(); var del = require('del'); gulp.task('lint', function () { return gulp.src('app/js/**/*.js') .pipe($.eslint()) .pipe($.eslint.format()) .pipe($.eslint.failAfterError()); }); gulp.task('serve', function () { bs.init({ notify: false, port: 9000, open: true, server: { baseDir: ['app'] } }); gulp.watch([ 'app/**/*.html', 'app/js/**/*.js' ]).on('change', bs.reload); gulp.watch('app/js/**/*.js', ['lint']); }); gulp.task('clean', del.bind(null, ['dist'])); gulp.task('scripts', function () { return gulp.src('app/js/**/*.js') .pipe($.uglify()) .pipe(gulp.dest('dist/js')); }); gulp.task('html', function () { return gulp.src('app/**/*.html') .pipe($.htmlmin({ collapseWhitespace: true })) .pipe(gulp.dest('dist')); }); gulp.task('build', ['clean'], function (callback) { runSequence(['scripts', 'html'], callback); }); gulp.task('default', function (callback) { runSequence('lint', 'build', callback); });
Add lint to the default task
Add lint to the default task
JavaScript
mit
htanjo/gulp-boilerplate,htanjo/gulp-boilerplate
--- +++ @@ -49,4 +49,6 @@ runSequence(['scripts', 'html'], callback); }); -gulp.task('default', ['build']); +gulp.task('default', function (callback) { + runSequence('lint', 'build', callback); +});
b3136d3fb55977e2da0a8641e19d6b7b2ddc7e23
gulpfile.js
gulpfile.js
var gulp = require("gulp"), connect = require("gulp-connect"), babel = require("gulp-babel"); gulp.task("webserver", function () { connect.server(); }); gulp.task("babel", function () { return gulp.src("src/js/bpm-counter.js") .pipe(babel()) .pipe(gulp.dest("dist/")); }); gulp.task("default", ["webserver"]);
var gulp = require("gulp"), connect = require("gulp-connect"), babel = require("gulp-babel"); gulp.task("webserver", function () { connect.server(); }); gulp.task("babel", function () { return gulp.src("src/js/bpm-counter.js") .pipe(babel()) .pipe(gulp.dest("dist/")); }); gulp.task("default", ["babel", "webserver"]);
Add babel to the default task
Add babel to the default task
JavaScript
mit
khwang/plum,khwang/plum
--- +++ @@ -12,4 +12,4 @@ .pipe(gulp.dest("dist/")); }); -gulp.task("default", ["webserver"]); +gulp.task("default", ["babel", "webserver"]);
587ed71e7dd5a39e9cb550e619b6638da59933eb
lib/dowhen.js
lib/dowhen.js
var async = require('async'); var DoWhen = function(obj, ev) { var args, triggerCallbacks, objCallback, callbacks = []; triggerCallbacks = function() { for(var i = 0; i < callbacks.length; ++i) { var callback = callbacks.splice(i)[0]; async.nextTick(function() { callback.apply(callback, args); }); } }; this.on = function(obj, ev) { objCallback = function() { args = arguments; triggerCallbacks(); }; obj.on(ev, objCallback); }; this.on(obj, ev); this.off = function() { obj.removeCallback(objCallback); }; this.addCallback = function(callback) { callbacks.push(callback); if (typeof(args) != 'undefined') { triggerCallbacks(); } }; this.do = this.addCallback; this.removeCallback = function(callback) { var i = callbacks.indexOf(callback); if (i != -1) { callbacks.splice(i); return true; } else { return false; } }; }; module.exports = DoWhen;
var async = require('async'); var DoWhen = function(obj, ev) { var args, triggerCallbacks, objCallback, callbacks = []; triggerCallbacks = function() { if (callbacks.length > 0) { for(var i = 0; i < callbacks.length; ++i) { var callback = callbacks[i]; async.nextTick(function() { callback.apply(callback, args); }); } callbacks = []; } }; this.on = function(obj, ev) { objCallback = function() { args = arguments; triggerCallbacks(); }; obj.on(ev, objCallback); }; this.on(obj, ev); this.off = function() { obj.removeCallback(objCallback); }; this.addCallback = function(callback) { callbacks.push(callback); if (typeof(args) != 'undefined') { triggerCallbacks(); } }; this.do = this.addCallback; this.removeCallback = function(callback) { var i = callbacks.indexOf(callback); if (i != -1) { callbacks.splice(i, 1); return true; } else { return false; } }; }; module.exports = DoWhen;
Fix splice for removeCallback, and avoid using splice for triggerCallbacks
Fix splice for removeCallback, and avoid using splice for triggerCallbacks
JavaScript
bsd-2-clause
1stvamp/dowhen.js
--- +++ @@ -7,13 +7,16 @@ callbacks = []; triggerCallbacks = function() { - for(var i = 0; i < callbacks.length; ++i) { - var callback = callbacks.splice(i)[0]; - - async.nextTick(function() { - callback.apply(callback, args); - }); - } + if (callbacks.length > 0) { + for(var i = 0; i < callbacks.length; ++i) { + var callback = callbacks[i]; + + async.nextTick(function() { + callback.apply(callback, args); + }); + } + callbacks = []; + } }; this.on = function(obj, ev) { @@ -43,7 +46,7 @@ var i = callbacks.indexOf(callback); if (i != -1) { - callbacks.splice(i); + callbacks.splice(i, 1); return true; } else { return false;
8eaa78b65d74a276278a61d05381edfb0a407467
chrome/content/addressList.js
chrome/content/addressList.js
window.addEventListener('load', function() { // https://developer.mozilla.org/en/Code_snippets/Tabbed_browser var browser = window.opener.getBrowser(); var doc = window.opener.content.document; var c = doc.SimpleMap; Components.utils.reportError(c.addresses); // DEBUG var addressArray = c.addresses; var addrArrayLen = addressArray.length; for(i = 0; i < addrArrayLen; i++) { var addrList = document.getElementById("address-list"); addrList.appendItem(addressArray[i].toString()); } document.getElementById("show-map").addEventListener("oncommand", function() { var addr = document.getElementById("address-list").getSelectedItem(0).getAttribute("label"); var link = GoogleMap.getLinkToAddress(addr); gBrowser.selectedTab = gBrowser.addTab(link); },false); document.getElementById("show-directions").addEventListener("oncommand", function() { var addr = document.getElementById("address-list").getSelectedItem(0).getAttribute("label"); var link = GoogleMap.getLinkToAddressDirection(addr, c.getPreferences().getMyLocation()); gBrowser.selectedTab = gBrowser.addTab(link); }, false); }, false);
window.addEventListener('load', function() { // https://developer.mozilla.org/en/Code_snippets/Tabbed_browser var browser = window.opener.getBrowser(); var doc = window.opener.content.document; var c = doc.SimpleMap; Components.utils.reportError(c.addresses); // DEBUG var addressArray = c.addresses; var addrArrayLen = addressArray.length; for(i = 0; i < addrArrayLen; i++) { var addrList = document.getElementById("address-list"); addrList.appendItem(addressArray[i].toString()); } document.getElementById("show-map").addEventListener("command", function(e) { var addr = document.getElementById("address-list").getSelectedItem(0).getAttribute("label"); var link = GoogleMap.getLinkToAddress(addr); gBrowser.selectedTab = gBrowser.addTab(link); },false); document.getElementById("show-directions").addEventListener("command", function(e) { var addr = document.getElementById("address-list").getSelectedItem(0).getAttribute("label"); var link = GoogleMap.getLinkToAddressDirection(addr, c.getPreferences().getMyLocation()); gBrowser.selectedTab = gBrowser.addTab(link); }, false); }, false);
Change event listener to command
Change event listener to command
JavaScript
isc
chrslgn/cs3300-ramrod-map
--- +++ @@ -13,14 +13,14 @@ addrList.appendItem(addressArray[i].toString()); } - document.getElementById("show-map").addEventListener("oncommand", function() { + document.getElementById("show-map").addEventListener("command", function(e) { var addr = document.getElementById("address-list").getSelectedItem(0).getAttribute("label"); var link = GoogleMap.getLinkToAddress(addr); gBrowser.selectedTab = gBrowser.addTab(link); },false); - document.getElementById("show-directions").addEventListener("oncommand", function() { + document.getElementById("show-directions").addEventListener("command", function(e) { var addr = document.getElementById("address-list").getSelectedItem(0).getAttribute("label"); var link = GoogleMap.getLinkToAddressDirection(addr, c.getPreferences().getMyLocation());
1e744c94a6db22cb9a7b20ab2ec1f34308458964
spec/main-spec.js
spec/main-spec.js
'use babel' import * as _ from 'lodash' import * as path from 'path' describe('The Ispell provider for Atom Linter', () => { const lint = require('../lib/providers').provideLinter().lint beforeEach(() => { waitsForPromise(() => { return atom.packages.activatePackage('linter-spell') }) }) it('finds a spelling in "foo.txt"', () => { waitsForPromise(() => { return atom.workspace.open(path.join(__dirname, 'files', 'foo.txt')).then(editor => { return lint(editor).then(messages => { expect(_.some(messages, (message) => { return message.text.match(/^armour( ->|$)/) })).toBe(true) }) }) }) }) })
'use babel' import * as _ from 'lodash' import * as path from 'path' describe('The Ispell provider for Atom Linter', () => { const lint = require('../lib/providers').provideLinter().lint beforeEach(() => { waitsForPromise(() => { return atom.packages.activatePackage('linter-spell') }) }) it('finds a spelling in "foo.txt"', () => { waitsForPromise(() => { return atom.workspace.open(path.join(__dirname, 'files', 'foo.txt')).then(editor => { return lint(editor).then(messages => { expect(_.some(messages, (message) => { return message.excerpt.match(/^armour( ->|$)/) })).toBe(true) }) }) }) }) })
Upgrade specs to latest API
:arrow_up: Upgrade specs to latest API
JavaScript
mit
yitzchak/linter-hunspell,yitzchak/linter-hunspell
--- +++ @@ -16,7 +16,7 @@ waitsForPromise(() => { return atom.workspace.open(path.join(__dirname, 'files', 'foo.txt')).then(editor => { return lint(editor).then(messages => { - expect(_.some(messages, (message) => { return message.text.match(/^armour( ->|$)/) })).toBe(true) + expect(_.some(messages, (message) => { return message.excerpt.match(/^armour( ->|$)/) })).toBe(true) }) }) })
a6f6fa942486ec30ac459b5187a334604188f419
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var webpack = require('webpack-stream'); var client = { config: require('./config/webpack.prod.client.js'), in: './src/client/index.jsx' }, server = { config: require('./config/webpack.prod.server.js'), in: './src/server/index.js' }; gulp.task('bundle-client', function() { return gulp.src( client.in ) .pipe( webpack( client.config ) ) .pipe( gulp.dest('./app/') ) }); gulp.task('bundle-server', function() { return gulp.src( server.in ) .pipe( webpack( server.config ) ) .pipe( gulp.dest('./app/') ) }); gulp.task('bundle', ['bundle-client', 'bundle-server']);
var gulp = require('gulp'); var webpack = require('webpack'); var clientConfig = require('./config/webpack.prod.client.js') var serverConfig = require('./config/webpack.prod.server.js') gulp.task('bundle-client', function(done) { webpack( clientConfig ).run(onBundle(done)) }); gulp.task('bundle-server', function(done) { webpack( serverConfig ).run(onBundle(done)) }); gulp.task('bundle', ['bundle-client', 'bundle-server']); function onBundle(done) { return function(err, stats) { if (err) console.log('Error', err); else console.log(stats.toString()); done() } }
Refactor gulp task to bundle front/backend
Refactor gulp task to bundle front/backend
JavaScript
mit
AdamSalma/Lurka,AdamSalma/Lurka
--- +++ @@ -1,24 +1,25 @@ var gulp = require('gulp'); -var webpack = require('webpack-stream'); +var webpack = require('webpack'); -var client = { - config: require('./config/webpack.prod.client.js'), - in: './src/client/index.jsx' -}, server = { - config: require('./config/webpack.prod.server.js'), - in: './src/server/index.js' -}; +var clientConfig = require('./config/webpack.prod.client.js') +var serverConfig = require('./config/webpack.prod.server.js') -gulp.task('bundle-client', function() { - return gulp.src( client.in ) - .pipe( webpack( client.config ) ) - .pipe( gulp.dest('./app/') ) + +gulp.task('bundle-client', function(done) { + webpack( clientConfig ).run(onBundle(done)) }); -gulp.task('bundle-server', function() { - return gulp.src( server.in ) - .pipe( webpack( server.config ) ) - .pipe( gulp.dest('./app/') ) +gulp.task('bundle-server', function(done) { + webpack( serverConfig ).run(onBundle(done)) }); gulp.task('bundle', ['bundle-client', 'bundle-server']); + + +function onBundle(done) { + return function(err, stats) { + if (err) console.log('Error', err); + else console.log(stats.toString()); + done() + } +}
1a6b85141a7589ed4ebadefd75340d643d61a687
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'), browserify = require('browserify'), transform = require('vinyl-transform'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), jasmine = require('gulp-jasmine'); gulp.task('default', ['build', 'watch']); gulp.task('watch', function () { gulp.watch('./src/js/**/*.js', ['test']); }); gulp.task('build', function () { var browserified = transform(function (filename) { var b = browserify({ entries: filename, debug: true }); return b.bundle(); }); return gulp.src('./src/js/bowler.js') .pipe(browserified) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/js')); }); gulp.task('test', ['build'], function () { return gulp.src('./spec/**/*.js') .pipe(jasmine()); });
'use strict'; var gulp = require('gulp'), browserify = require('browserify'), transform = require('vinyl-transform'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), jasmine = require('gulp-jasmine'); gulp.task('default', ['build', 'watch']); gulp.task('watch', function () { gulp.watch('./src/js/**/*.js', ['test']); gulp.watch('./spec/**/*.js', ['test']); }); gulp.task('build', function () { var browserified = transform(function (filename) { var b = browserify({ entries: filename, debug: true }); return b.bundle(); }); return gulp.src('./src/js/bowler.js') .pipe(browserified) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/js')); }); gulp.task('test', ['build'], function () { return gulp.src('./spec/**/*.js') .pipe(jasmine()); });
Add watch of test files to gulp
Add watch of test files to gulp
JavaScript
mit
rowanoulton/bowler,rowanoulton/bowler
--- +++ @@ -11,6 +11,7 @@ gulp.task('watch', function () { gulp.watch('./src/js/**/*.js', ['test']); + gulp.watch('./spec/**/*.js', ['test']); }); gulp.task('build', function () {
f0742659c8af024a8d73bd2ea9b8fae52591b7d9
lib/knife/apply_rules.js
lib/knife/apply_rules.js
var lodash = require('lodash'); module.exports = { applyRules: function(rules, element, opts) { if (!rules) { return []; } return lodash.flatten(rules.map(function(rule) { return rule.lint.call(rule, element, opts); })); } };
var lodash = require('lodash'); module.exports = { applyRules: function(rules, element, opts) { if (!rules) { return []; } return lodash.flatten(rules.map(function(rule) { var issues = rule.lint.call(rule, element, opts); // apparently we can also get an issue directly, instead of an array of issues if (!Array.isArray(issues)) { issues.rule = rule.name; } else { issues.forEach(function (issue) { issue.rule = rule.name; }); } return issues; })); } };
Add rule name to issues for a better output
Add rule name to issues for a better output
JavaScript
isc
KrekkieD/htmllint,htmllint/htmllint,htmllint/htmllint,KrekkieD/htmllint
--- +++ @@ -7,7 +7,20 @@ } return lodash.flatten(rules.map(function(rule) { - return rule.lint.call(rule, element, opts); + var issues = rule.lint.call(rule, element, opts); + + // apparently we can also get an issue directly, instead of an array of issues + if (!Array.isArray(issues)) { + issues.rule = rule.name; + } + else { + issues.forEach(function (issue) { + issue.rule = rule.name; + }); + } + + return issues; })); + } };
2d1b2627997c7e0568b66fdbbde15a15d63fd67f
components/cors/controller.js
components/cors/controller.js
const Config = use('config'); const CORSController = { path: 'cors', permissions: {}, OPTIONS : [ function () { // @path: .* this.response.headers['Access-Control-Allow-Methods'] = Config.cors.methods.toString(); this.response.headers['Access-Control-Allow-Headers'] = Config.cors.headers.toString(); this.response.headers['Access-Control-Allow-Credentials'] = Config.cors.credentials.toString(); this.response.headers['Access-Control-Allow-Max-Age'] = Config.cors.maxAge.toString(); } ] }; module.exports = CORSController;
const Config = use('config'); const CORSController = { path: 'cors', permissions: {}, OPTIONS : [ function () { // @path: .* // @summary: Handle CORS OPTIONS request this.response.headers['Access-Control-Allow-Methods'] = Config.cors.methods.toString(); this.response.headers['Access-Control-Allow-Headers'] = Config.cors.headers.toString(); this.response.headers['Access-Control-Allow-Credentials'] = Config.cors.credentials.toString(); this.response.headers['Access-Control-Allow-Max-Age'] = Config.cors.maxAge.toString(); } ] }; module.exports = CORSController;
Add doc for CORS component
Add doc for CORS component
JavaScript
mit
yura-chaikovsky/dominion
--- +++ @@ -11,6 +11,7 @@ function () { // @path: .* + // @summary: Handle CORS OPTIONS request this.response.headers['Access-Control-Allow-Methods'] = Config.cors.methods.toString(); this.response.headers['Access-Control-Allow-Headers'] = Config.cors.headers.toString();
18ad9cc05ed8a0aaabc438e32b3ef086687622e4
src/bin/eslint.js
src/bin/eslint.js
import path from 'path'; import {CLIEngine, linter} from 'eslint'; import PackageJson from '../lib/package_json'; const project = PackageJson.load(); const baseConfig = linter.defaults(); const options = { baseConfig: Object.assign(baseConfig, { parser: 'babel-eslint', env: Object.assign(baseConfig.env, { es6: true, browser: true, node: true, jasmine: project.dependsOn(/jasmine/) }), ecmaFeatures: Object.assign(baseConfig.ecmaFeatures, { modules: true }), rules: Object.assign(baseConfig.rules, { strict: 0, quotes: [2, 'single'], 'no-process-exit': 0 }) }), ignorePath: path.resolve('.gitignore') }; const cli = new CLIEngine(options); const formatter = cli.getFormatter(); const report = cli.executeOnFiles(['.']); if (report.errorCount > 0) { process.stderr.write(formatter(report.results)); process.exit(1); }
import path from 'path'; import {CLIEngine, linter} from 'eslint'; import PackageJson from '../lib/package_json'; const project = PackageJson.load(); const baseConfig = linter.defaults(); const options = { baseConfig: Object.assign(baseConfig, { parser: 'babel-eslint', env: Object.assign(baseConfig.env, { es6: true, browser: true, node: true, jasmine: project.dependsOn(/jasmine/) }), ecmaFeatures: Object.assign(baseConfig.ecmaFeatures, { modules: true }), rules: Object.assign(baseConfig.rules, { strict: 0, quotes: [2, 'single', 'avoid-escape'], 'no-process-exit': 0 }) }), ignorePath: path.resolve('.gitignore') }; const cli = new CLIEngine(options); const formatter = cli.getFormatter(); const report = cli.executeOnFiles(['.']); if (report.errorCount > 0) { process.stderr.write(formatter(report.results)); process.exit(1); }
Allow double quotes to avoid escaping single quotes
Allow double quotes to avoid escaping single quotes
JavaScript
mit
vinsonchuong/eslint-defaults
--- +++ @@ -19,7 +19,7 @@ }), rules: Object.assign(baseConfig.rules, { strict: 0, - quotes: [2, 'single'], + quotes: [2, 'single', 'avoid-escape'], 'no-process-exit': 0 }) }),
88c77686a6eb10444037b98fb110ec129344e0dd
tests/integration/ParameterTableFixture.js
tests/integration/ParameterTableFixture.js
floatValue = /\d+.\d+/ ongoingDateRange = /partir du \d{1,2}\/\d{1,2}\/\d{4}/ dateRange = /Du \d{1,2}\/\d{1,2}\/\d{4} au \d{1,2}\/\d{1,2}\/\d{4}/ interruptionMessage = /ne figure plus dans la législation depuis le \d{1,2}\/\d{1,2}\/\d{4}/
floatValue = /\d+.\d+/ ongoingDateRange = /\d{2}\/\d{2}\/\d{4}/ dateRange = /\d{2}\/\d{2}\/\d{4}.+\d{2}\/\d{2}\/\d{4}/ interruptionMessage = /\d{2}\/\d{2}\/\d{4}/
Update integration tests for localised dates
Update integration tests for localised dates
JavaScript
agpl-3.0
openfisca/legislation-explorer
--- +++ @@ -1,4 +1,4 @@ floatValue = /\d+.\d+/ -ongoingDateRange = /partir du \d{1,2}\/\d{1,2}\/\d{4}/ -dateRange = /Du \d{1,2}\/\d{1,2}\/\d{4} au \d{1,2}\/\d{1,2}\/\d{4}/ -interruptionMessage = /ne figure plus dans la législation depuis le \d{1,2}\/\d{1,2}\/\d{4}/ +ongoingDateRange = /\d{2}\/\d{2}\/\d{4}/ +dateRange = /\d{2}\/\d{2}\/\d{4}.+\d{2}\/\d{2}\/\d{4}/ +interruptionMessage = /\d{2}\/\d{2}\/\d{4}/
1b73efa26e8778cf9755b407acc00d55494e4a16
tests/mocha/client/displayAListOfPlaces.js
tests/mocha/client/displayAListOfPlaces.js
if (!(typeof MochaWeb === 'undefined')){ MochaWeb.testOnly(function () { setTimeout(function (){ describe('The Route "/"', function () { it('Should have the title "Map"', function () { var title = document.title console.log(title) chai.assert.include(title, 'Map') }) }) describe('A list of places', function () { it('Should have a main section with the class map', function () { var map = $('main.map') chai.assert.ok(map.length > 0) }) it('Should contain map__places', function () { var placesList = $('main.map ul.map__places') chai.assert.ok(placesList.length > 0) }) it('should at least contain one place', function () { var places = $('ul.map__places li.place') chai.assert.ok(places.length > 0) }) }) describe('A place', function () { it('Should include a location', function () { var title = $('li.place .place__location').text() chai.assert.ok(title.length > 0) }) }) }, 1000) }) }
if (!(typeof MochaWeb === 'undefined')){ MochaWeb.testOnly(function () { Meteor.flush() describe('The Route "/"', function () { it('Should have the title "Map"', function () { var title = document.title chai.assert.include(title, 'Map') }) }) describe('A list of places', function () { it('Should have a main section with the class map', function () { var map = $('main.map') chai.assert.ok(map.length > 0) }) it('Should contain map__places', function () { var placesList = $('main.map ul.map__places') chai.assert.ok(placesList.length > 0) }) it('should at least contain one place', function () { var places = $('ul.map__places li.place') chai.assert.ok(places.length > 0) }) }) describe('A place', function () { it('Should include a location', function () { var title = $('li.place .place__location').text() chai.assert.ok(title.length > 0) }) }) }) }
Remove hack is was breaking the tests
Remove hack is was breaking the tests
JavaScript
mit
Kriegslustig/Bergbau-Graub-nden,Kriegslustig/Bergbau-Graub-nden,Kriegslustig/Bergbau-Graub-nden
--- +++ @@ -1,33 +1,31 @@ if (!(typeof MochaWeb === 'undefined')){ MochaWeb.testOnly(function () { - setTimeout(function (){ - describe('The Route "/"', function () { - it('Should have the title "Map"', function () { - var title = document.title - console.log(title) - chai.assert.include(title, 'Map') - }) + Meteor.flush() + describe('The Route "/"', function () { + it('Should have the title "Map"', function () { + var title = document.title + chai.assert.include(title, 'Map') }) - describe('A list of places', function () { - it('Should have a main section with the class map', function () { - var map = $('main.map') - chai.assert.ok(map.length > 0) - }) - it('Should contain map__places', function () { - var placesList = $('main.map ul.map__places') - chai.assert.ok(placesList.length > 0) - }) - it('should at least contain one place', function () { - var places = $('ul.map__places li.place') - chai.assert.ok(places.length > 0) - }) + }) + describe('A list of places', function () { + it('Should have a main section with the class map', function () { + var map = $('main.map') + chai.assert.ok(map.length > 0) }) - describe('A place', function () { - it('Should include a location', function () { - var title = $('li.place .place__location').text() - chai.assert.ok(title.length > 0) - }) + it('Should contain map__places', function () { + var placesList = $('main.map ul.map__places') + chai.assert.ok(placesList.length > 0) }) - }, 1000) + it('should at least contain one place', function () { + var places = $('ul.map__places li.place') + chai.assert.ok(places.length > 0) + }) + }) + describe('A place', function () { + it('Should include a location', function () { + var title = $('li.place .place__location').text() + chai.assert.ok(title.length > 0) + }) + }) }) }
073326ef326964f261bcdb2fe210493efaaf73fe
lib/communication/handler/index.js
lib/communication/handler/index.js
module.exports = { 'speedyfx:msg': require('./message'), 'speedyfx:prs': require('./presence'), 'speedyfx:rq': require('./request') };
module.exports = { 'speedy:msg': require('./message'), 'speedy:prs': require('./presence'), 'speedy:rq': require('./request') };
Modify namespace of message type
Modify namespace of message type
JavaScript
mit
johnsmith17th/SpeedyFx
--- +++ @@ -1,5 +1,5 @@ module.exports = { - 'speedyfx:msg': require('./message'), - 'speedyfx:prs': require('./presence'), - 'speedyfx:rq': require('./request') + 'speedy:msg': require('./message'), + 'speedy:prs': require('./presence'), + 'speedy:rq': require('./request') };
12ac4e2696d611956a9e6acfbe2ed2ebf7517c06
app/login/current-user.js
app/login/current-user.js
(function() { angular.module('notely.login') .service('CurrentUser', CurrentUser); CurrentUser['$inject'] = ['$window'] function CurrentUser($window) { var currentUser = JSON.parse($window.localStorage.getItem('currentUser')); this.set = function(user) { currentUser = user; $window.localStorage.setItem('currentUser', JSON.stringify(currentUser)); } this.get = function() { return currentUser || {}; } this.clear = function() { currentUser = undefined; $window.localStorage.removeItem('currentUser'); } } })();
angular.module('notely.login') .service('CurrentUser', ['$window', ($window) => { class CurrentUser { constructor() { this.currentUser = JSON.parse($window.localStorage.getItem('currentUser')); } set(user) { this.currentUser = user; $window.localStorage.setItem('currentUser', JSON.stringify(this.currentUser)); } get() { return this.currentUser || {}; } clear() { this.currentUser = undefined; $window.localStorage.removeItem('currentUser'); } } return new CurrentUser(); }]);
Make CurrentUser service use class syntax with inherited dependencies.
Make CurrentUser service use class syntax with inherited dependencies. This is one way to possibly alleviate concerns with having to tack `this` to the beginning of everything. Instead of using the class directly, DI an anonymous function, and declare/return the class inside of it.
JavaScript
mit
FretlessBecks/notely,FretlessBecks/notely
--- +++ @@ -1,23 +1,25 @@ -(function() { - angular.module('notely.login') - .service('CurrentUser', CurrentUser); +angular.module('notely.login') + .service('CurrentUser', ['$window', ($window) => { - CurrentUser['$inject'] = ['$window'] - function CurrentUser($window) { - var currentUser = JSON.parse($window.localStorage.getItem('currentUser')); - - this.set = function(user) { - currentUser = user; - $window.localStorage.setItem('currentUser', JSON.stringify(currentUser)); + class CurrentUser { + constructor() { + this.currentUser = JSON.parse($window.localStorage.getItem('currentUser')); } - this.get = function() { - return currentUser || {}; + set(user) { + this.currentUser = user; + $window.localStorage.setItem('currentUser', JSON.stringify(this.currentUser)); } - this.clear = function() { - currentUser = undefined; + get() { + return this.currentUser || {}; + } + + clear() { + this.currentUser = undefined; $window.localStorage.removeItem('currentUser'); } } -})(); + return new CurrentUser(); + +}]);
09f37253a32542839ef72174cdc14b2a61575d93
lib/ChunkedBlob.js
lib/ChunkedBlob.js
const rankSize = 16 function blobLength(b) { if (typeof b.byteLength !== 'undefined') return b.byteLength if (typeof b.size !== 'undefined') return b.size return b.length } export default class ChunkedBlob { constructor() { this.size = 0 this.ranks = [[]] } add(b) { this.size += blobLength(b) this.ranks[0].push(b) for (let i = 0; i < this.ranks.length; i++) { let rank = this.ranks[i] if (rank.length === rankSize) { this.ranks[i + 1] = this.ranks[i + 1] || [] this.ranks[i + 1].push(new Blob(rank)) this.ranks[i] = [] } } } toBlob() { let allRanks = [].concat(...this.ranks) return new Blob(allRanks) } }
const rankSize = 16 function blobLength(b) { if (typeof b.byteLength !== 'undefined') return b.byteLength if (typeof b.size !== 'undefined') return b.size return b.length } export default class ChunkedBlob { constructor() { this.size = 0 this.ranks = [] } add(b) { this.size += blobLength(b) this.ranks.push(b) } toBlob() { return new Blob(this.ranks) } }
Use one big array for all blobs instead of ranks.
Use one big array for all blobs instead of ranks.
JavaScript
bsd-3-clause
codebhendi/filepizza,hanford/filepizza,bradparks/filepizza_javascript_send_files_webrtc,jekrb/filepizza,codevlabs/filepizza,Ribeiro/filepizza,gramakri/filepizza,pquochoang/filepizza
--- +++ @@ -10,26 +10,16 @@ constructor() { this.size = 0 - this.ranks = [[]] + this.ranks = [] } add(b) { this.size += blobLength(b) - this.ranks[0].push(b) - - for (let i = 0; i < this.ranks.length; i++) { - let rank = this.ranks[i] - if (rank.length === rankSize) { - this.ranks[i + 1] = this.ranks[i + 1] || [] - this.ranks[i + 1].push(new Blob(rank)) - this.ranks[i] = [] - } - } + this.ranks.push(b) } toBlob() { - let allRanks = [].concat(...this.ranks) - return new Blob(allRanks) + return new Blob(this.ranks) } }
95046feb15b5450b4bc19fbf73a46cba5e7ab842
server/frontend/store/configureStore.js
server/frontend/store/configureStore.js
import { createStore, applyMiddleware } from 'redux'; import { reduxReactRouter } from 'redux-router'; import createHistory from 'history/lib/createBrowserHistory'; import routes from '../routes'; import thunkMiddleware from 'redux-thunk'; import createLogger from 'redux-logger'; import rootReducer from '../reducers'; const createStoreWithMiddleware = applyMiddleware( thunkMiddleware, reduxReactRouter({ routes, createHistory }), createLogger() )(createStore); export default function configureStore(initialState) { const store = createStoreWithMiddleware(rootReducer, initialState); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers'); store.replaceReducer(nextRootReducer); }); } return store; }
import { createStore, applyMiddleware, compose } from 'redux'; import { reduxReactRouter } from 'redux-router'; import thunk from 'redux-thunk'; import createHistory from 'history/lib/createBrowserHistory'; import routes from '../routes'; import createLogger from 'redux-logger'; import rootReducer from '../reducers'; const finalCreateStore = compose( applyMiddleware(thunk), applyMiddleware(createLogger()), reduxReactRouter({ routes, createHistory }) )(createStore); export default function configureStore(initialState) { const store = finalCreateStore(rootReducer, initialState); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextRootReducer = require('../reducers'); store.replaceReducer(nextRootReducer); }); } return store; }
Configure store creation to incorporate ReduxRouter
Configure store creation to incorporate ReduxRouter
JavaScript
mit
benjaminhoffman/Encompass,benjaminhoffman/Encompass,benjaminhoffman/Encompass
--- +++ @@ -1,20 +1,19 @@ -import { createStore, applyMiddleware } from 'redux'; +import { createStore, applyMiddleware, compose } from 'redux'; import { reduxReactRouter } from 'redux-router'; +import thunk from 'redux-thunk'; import createHistory from 'history/lib/createBrowserHistory'; import routes from '../routes'; -import thunkMiddleware from 'redux-thunk'; import createLogger from 'redux-logger'; import rootReducer from '../reducers'; - -const createStoreWithMiddleware = applyMiddleware( - thunkMiddleware, - reduxReactRouter({ routes, createHistory }), - createLogger() +const finalCreateStore = compose( + applyMiddleware(thunk), + applyMiddleware(createLogger()), + reduxReactRouter({ routes, createHistory }) )(createStore); export default function configureStore(initialState) { - const store = createStoreWithMiddleware(rootReducer, initialState); + const store = finalCreateStore(rootReducer, initialState); if (module.hot) { // Enable Webpack hot module replacement for reducers
d24fac89a787dcf182fc99630f32bc96df61cba2
app/controllers/trains.js
app/controllers/trains.js
import Ember from 'ember'; import $ from 'jquery'; export default Ember.Controller.extend({ transportApiSrv: Ember.inject.service('trasport-api'), searchLocation: null, destinations: null, selectedDestination: null, timetable: null, setInitialState () { const initialStation = this.get('model').stations[0]; this.set('searchLocation', initialStation.name); $('.departures-select').children().eq(1).attr('selected', 'selected'); this.setDestinationSelectList(initialStation.station_code); }, setDestinationSelectList (stationCode) { return this.get('transportApiSrv').getTrainSchedule({stationCode}) .then(response => { this.set('destinations', response.departures.all); Ember.run.later(() => { $('select').material_select(); }, 500); }); } });
import Ember from 'ember'; import $ from 'jquery'; export default Ember.Controller.extend({ transportApiSrv: Ember.inject.service('trasport-api'), searchLocation: null, destinations: null, selectedDestination: null, timetable: null, setInitialState () { const initialStation = this.get('model').stations[0]; this.set('searchLocation', initialStation.name); $('.departures-select').children().eq(1).attr('selected', 'selected'); this.setDestinationSelectList(initialStation.station_code); }, actions: { destinationSelected (destination) { let selectedService = this.get('destinations').filterBy('destination_name', destination); this.set('timetable', selectedService); }, departureSelected (departureStation) { const $selectEl = $('.station-select'); $selectEl.attr('disabled', 'disabled'); $('select').material_select(); this.set('timetable', null); this.setDestinationSelectList(departureStation).then(() => { $selectEl.removeAttr('disabled'); }); } }, setDestinationSelectList (stationCode) { return this.get('transportApiSrv').getTrainSchedule({stationCode}) .then(response => { this.set('destinations', response.departures.all); Ember.run.later(() => { $('select').material_select(); }, 500); }); } });
Set actions for select fields
feat: Set actions for select fields
JavaScript
mit
pe1te3son/transportme,pe1te3son/transportme
--- +++ @@ -16,6 +16,23 @@ this.setDestinationSelectList(initialStation.station_code); }, + actions: { + destinationSelected (destination) { + let selectedService = this.get('destinations').filterBy('destination_name', destination); + this.set('timetable', selectedService); + }, + departureSelected (departureStation) { + const $selectEl = $('.station-select'); + + $selectEl.attr('disabled', 'disabled'); + $('select').material_select(); + this.set('timetable', null); + this.setDestinationSelectList(departureStation).then(() => { + $selectEl.removeAttr('disabled'); + }); + } + }, + setDestinationSelectList (stationCode) { return this.get('transportApiSrv').getTrainSchedule({stationCode}) .then(response => {
a04731b805376dcbfcbafffc08e91698009b4cfc
lib/TokenClient.js
lib/TokenClient.js
import request from 'superagent'; import { Promise } from 'bluebird'; import { isValidToken } from './jwt'; export default class TokenClient { constructor(config) { this.user = config.user; this.password = config.password; this.routes = config.routes; this.token = config.token; } getValidToken() { return new Promise(this.tokenPromiseHandler.bind(this)); } tokenPromiseHandler(resolve, reject) { if (isValidToken(this.token)) { resolve(this.token); } else { this.requestToken(this.user, this.password, function(err, token) { if (err) { reject(err); } else { this.token = token; resolve(this.token); } }.bind(this)); } } requestToken(user, pass, callback) { request.post(this.routes.token) .send({ 'user' : user, 'password' : pass }) .end(function(err, result) { if (err) { callback(err); } else if (!isValidToken(result.body.token)) { if (result.serverError) { callback('Server error: '+ result.status ); } else { callback('Server returned invalid JWT token'); } } else { callback(null, result.body.token); } }); } }
import request from 'superagent'; import { Promise } from 'bluebird'; import { isValidToken } from './jwt'; export default class TokenClient { constructor(config) { this.user = config.user; this.password = config.password; this.routes = config.routes; this.token = config.token; } getValidToken() { return new Promise(this.tokenPromiseHandler.bind(this)); } tokenPromiseHandler(resolve, reject) { if (isValidToken(this.token)) { resolve(this.token); } else { this.requestToken(this.user, this.password, (err, token) => { if (err) { reject(err); } else { this.token = token; resolve(this.token); } }); } } requestToken(user, pass, callback) { request.post(this.routes.token) .send({ 'user' : user, 'password' : pass }) .end(function(err, result) { if (err) { callback(err); } else if (!isValidToken(result.body.token)) { if (result.serverError) { callback('Server error: '+ result.status ); } else { callback('Server returned invalid JWT token'); } } else { callback(null, result.body.token); } }); } }
Replace bind with fat arrow syntax
Replace bind with fat arrow syntax
JavaScript
mit
andrewk/biodome-client
--- +++ @@ -18,14 +18,14 @@ if (isValidToken(this.token)) { resolve(this.token); } else { - this.requestToken(this.user, this.password, function(err, token) { + this.requestToken(this.user, this.password, (err, token) => { if (err) { reject(err); } else { this.token = token; resolve(this.token); } - }.bind(this)); + }); } }
ca2e8dfa402e899fcb95256e3f24917d8fcd7f9d
lib/catch-links.js
lib/catch-links.js
module.exports = function (root, cb) { root.addEventListener('click', (ev) => { if (ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.defaultPrevented) { return true } let anchor = null for (let n = ev.target; n.parentNode; n = n.parentNode) { if (n.nodeName === 'A') { anchor = n break } } if (!anchor) return true let href = anchor.getAttribute('href') try { href = decodeURIComponent(href) } catch (e) { // Safely ignore error because href isn't URI-encoded. } if (href) { let isUrl let url try { url = new URL(href) isUrl = true } catch (e) { isUrl = false } if (isUrl && (url.host || url.protocol === 'magnet:')) { cb(href, true) } else if (href !== '#') { cb(href, false, anchor.anchor) } } ev.preventDefault() ev.stopPropagation() }) }
module.exports = function (root, cb) { root.addEventListener('click', (ev) => { if (ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.defaultPrevented) { return true } let anchor = null for (let n = ev.target; n.parentNode; n = n.parentNode) { if (n.nodeName === 'A') { anchor = n break } } if (!anchor) return true let href = anchor.getAttribute('href') if (href.startsWith('#')) { try { href = decodeURIComponent(href) } catch (e) { // Safely ignore error because href isn't URI-encoded. } } if (href) { let isUrl let url try { url = new URL(href) isUrl = true } catch (e) { isUrl = false } if (isUrl && (url.host || url.protocol === 'magnet:')) { cb(href, true) } else if (href !== '#') { cb(href, false, anchor.anchor) } } ev.preventDefault() ev.stopPropagation() }) }
Fix URI decode error breaking messages
Fix URI decode error breaking messages
JavaScript
agpl-3.0
ssbc/patchwork,ssbc/patchwork
--- +++ @@ -16,10 +16,12 @@ let href = anchor.getAttribute('href') - try { - href = decodeURIComponent(href) - } catch (e) { - // Safely ignore error because href isn't URI-encoded. + if (href.startsWith('#')) { + try { + href = decodeURIComponent(href) + } catch (e) { + // Safely ignore error because href isn't URI-encoded. + } } if (href) {
8d958f42d2de3dd0d5dbae778df32100092aa962
test/helpers/MockData.js
test/helpers/MockData.js
const CurrentData = { display_location: { full: 'Den' }, temp_f: 70 }; const ForecastData = { txt_forecast: { forecastday:[{ title: 'Monday', fcttext: 'Clear all day', }] }, simpleforecast: { forecastday:[{ conditions: 'Clear', high: { fahrenheit: 70, }, low: { fahrenheit: 32, } }] } }; const TenDay = { simpleforecast: { forecastday: [{ date: { weekday_short: 'Tue' }, high: { fahrenheit: 65 }, low: { fahrenheit: 28 } }, { date: { weekday_short: 'Wed' }, high: { fahrenheit: 58 }, low: { fahrenheit: 20 } }] } }; const SevenHour = [{ FCTTIME: { civil:"5:00PM" }, temp: { english: "42" } }] export default { CurrentData, ForecastData, TenDay, SevenHour };
const CurrentData = { display_location: { full: 'Den' }, temp_f: 70 }; const ForecastData = { txt_forecast: { forecastday:[{ title: 'Monday', fcttext: 'Clear all day', }] }, simpleforecast: { forecastday:[{ conditions: 'Clear', high: { fahrenheit: 70, }, low: { fahrenheit: 32, } }] } }; const TenDay = { simpleforecast: { forecastday: [{ date: { weekday_short: 'Tue' }, high: { fahrenheit: 65 }, low: { fahrenheit: 28 } }, { date: { weekday_short: 'Wed' }, high: { fahrenheit: 58 }, low: { fahrenheit: 20 } }] } }; const SevenHour = [{ FCTTIME: { civil:"5:00PM" }, temp: { english: "42" } }] const ResponseData = { error: { description: "No cities match your search query" } } export default { CurrentData, ForecastData, TenDay, SevenHour, ResponseData };
Test for error handling when location is not found.
Test for error handling when location is not found.
JavaScript
mit
thatPamIAm/weathrly,thatPamIAm/weathrly
--- +++ @@ -62,4 +62,11 @@ } }] -export default { CurrentData, ForecastData, TenDay, SevenHour }; + +const ResponseData = { + error: { + description: "No cities match your search query" + } +} + +export default { CurrentData, ForecastData, TenDay, SevenHour, ResponseData };
258666fc69af024c9aa5a51b7714f8647c77c537
test/integration/main.js
test/integration/main.js
var gpio = require('rpi-gpio'); var async = require('async'); var assert = require('assert'); var sinon = require('sinon'); var message = 'Please ensure that your Raspberry Pi is set up with with physical pins ' + '7 and 11 connected via a 1kΩ resistor (or similar) to make this test work' console.log(message) var writePin = 7 var readPin = 11 describe('rpi-gpio integration', function() { var readValue; var onChange = sinon.spy() before(function(done) { gpio.on('change', onChange); async.waterfall([ function(next) { gpio.setup(writePin, gpio.DIR_OUT, next) }, function(next) { gpio.setup(readPin, gpio.DIR_IN, gpio.EDGE_BOTH, next) }, function(next) { gpio.write(writePin, 1, next); }, function(next) { setTimeout(next, 100) }, function(next) { gpio.read(readPin, function(err, value) { readValue = value; next(); }); } ], function(err) { done(err) }); }); after(function(done) { gpio.destroy(done) }); it('should trigger the change listener', function() { sinon.assert.calledOnce(onChange) sinon.assert.calledWith(onChange, 11, true) }); it('should set the read pin on', function() { assert.equal(readValue, true) }); });
var gpio = require('../../rpi-gpio'); var async = require('async'); var assert = require('assert'); var sinon = require('sinon'); var message = 'Please ensure that your Raspberry Pi is set up with with physical pins ' + '7 and 11 connected via a 1kΩ resistor (or similar) to make this test work' console.log(message) var writePin = 7 var readPin = 11 describe('rpi-gpio integration', function() { var readValue; var onChange = sinon.spy() before(function(done) { gpio.on('change', onChange); async.waterfall([ function(next) { gpio.setup(writePin, gpio.DIR_OUT, next) }, function(next) { gpio.setup(readPin, gpio.DIR_IN, gpio.EDGE_BOTH, next) }, function(next) { gpio.write(writePin, 1, next); }, function(next) { setTimeout(next, 100) }, function(next) { gpio.read(readPin, function(err, value) { readValue = value; next(); }); } ], function(err) { done(err) }); }); after(function(done) { gpio.destroy(done) }); it('should trigger the change listener', function() { sinon.assert.calledOnce(onChange) sinon.assert.calledWith(onChange, 11, true) }); it('should set the read pin on', function() { assert.equal(readValue, true) }); });
Fix integration test path to module
Fix integration test path to module
JavaScript
mit
JamesBarwell/rpi-gpio.js
--- +++ @@ -1,4 +1,4 @@ -var gpio = require('rpi-gpio'); +var gpio = require('../../rpi-gpio'); var async = require('async'); var assert = require('assert'); var sinon = require('sinon');
9124af224228fd3bf3c41967f9bc6b2baa6f9e53
vendor/ember-component-attributes/index.js
vendor/ember-component-attributes/index.js
/* globals Ember */ (function() { const { Component, computed } = Ember; Component.reopen({ __HTML_ATTRIBUTES__: computed({ set: function(key, value) { let attributes = Object.keys(value); let customBindings = []; for (let i = 0; i < attributes.length; i++) { let attribute = attributes[i]; customBindings.push(`__HTML_ATTRIBUTES__.${attribute}:${attribute}`); } debugger this.attributeBindings = this.attributeBindings.concat(customBindings); return value; } }) }); })();
/* globals Ember */ (function() { const { Component, computed } = Ember; Component.reopen({ __HTML_ATTRIBUTES__: computed({ set: function(key, value) { let attributes = Object.keys(value); let customBindings = []; for (let i = 0; i < attributes.length; i++) { let attribute = attributes[i]; customBindings.push(`__HTML_ATTRIBUTES__.${attribute}:${attribute}`); } if (this.attributeBindings) { this.attributeBindings = this.attributeBindings.concat(customBindings); } else { this.attributeBindings = customBindings; } return value; } }) }); })();
Make work with and without pre-existing attributeBindings.
Make work with and without pre-existing attributeBindings. When a component has no attribute bindings, `this.attributeBindings` is undefined. This updates the computed setter to handle that scenario.
JavaScript
mit
mmun/ember-component-attributes,mmun/ember-component-attributes
--- +++ @@ -13,9 +13,11 @@ customBindings.push(`__HTML_ATTRIBUTES__.${attribute}:${attribute}`); } - debugger - - this.attributeBindings = this.attributeBindings.concat(customBindings); + if (this.attributeBindings) { + this.attributeBindings = this.attributeBindings.concat(customBindings); + } else { + this.attributeBindings = customBindings; + } return value; }
1991066ed6b2f8c93ae76034f30ed3c23ac2dca5
lib/yamb/proto/define.js
lib/yamb/proto/define.js
"use strict"; var utils = require('./../../utils'); function define(name, prop, priv) { var descriptor = {enumerable: true}; var getter = prop.get; var setter = prop.set; if (getter !== false) { if (!utils.is.fun(getter) && getter !== false) { getter = function() { return this[priv.symbl][name]; }; } descriptor.get = getter; } if (setter !== false) { if (!utils.is.fun(setter)) { setter = function(value) { if (value) { this[priv.symbl][name] = value; } return this; }; } descriptor.set = setter; } return descriptor; } module.exports = function(priv) { return function(name, prop) { return define(name, prop, priv); }; };
"use strict"; var utils = require('./../../utils'); function define(name, prop, priv) { var descriptor = {enumerable: true}; var getter = prop.get; var setter = prop.set; if (getter !== false) { if (!utils.is.fun(getter) && getter !== false) { getter = function() { return this[priv.symbl][name]; }; } descriptor.get = getter; } if (setter !== false) { if (!utils.is.fun(setter)) { setter = function(value) { if (value) { this[priv.symbl][name] = value; this[priv.flags][name] = this[priv.shado][name] !== value; } return this; }; } descriptor.set = setter; } return descriptor; } module.exports = function(priv) { return function(name, prop) { return define(name, prop, priv); }; };
Add updated flags for default setter
Add updated flags for default setter
JavaScript
mit
yamb/yamb
--- +++ @@ -23,6 +23,7 @@ setter = function(value) { if (value) { this[priv.symbl][name] = value; + this[priv.flags][name] = this[priv.shado][name] !== value; } return this;
9114f3e67a68a6fba193a1bfa09d411b805e3a94
lib/node_modules/@stdlib/string/remove-first/lib/index.js
lib/node_modules/@stdlib/string/remove-first/lib/index.js
'use strict'; /** * Remove the first character of a string. * * @module @stdlib/string/remove-first * * @example * var removeFirst = require( '@stdlib/string/remove-first' ); * * var out = removeFirst( 'last man standing' ); * // returns 'ast man standing' * * out = removeFirst( 'Hidden Treasures' ); * // returns 'hidden Treasures'; */ // MODULES // var removeFirst = require( './remove_first.js' ); // EXPORTS // module.exports = removeFirst;
'use strict'; /** * Remove the first character of a string. * * @module @stdlib/string/remove-first * * @example * var removeFirst = require( '@stdlib/string/remove-first' ); * * var out = removeFirst( 'last man standing' ); * // returns 'ast man standing' * * out = removeFirst( 'Hidden Treasures' ); * // returns 'idden Treasures'; */ // MODULES // var removeFirst = require( './remove_first.js' ); // EXPORTS // module.exports = removeFirst;
Fix return value in example code
Fix return value in example code
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
--- +++ @@ -12,7 +12,7 @@ * // returns 'ast man standing' * * out = removeFirst( 'Hidden Treasures' ); -* // returns 'hidden Treasures'; +* // returns 'idden Treasures'; */ // MODULES //
236eb48a65cef8928ce5ad8fdadee95124c67866
packages/flow-dev-tools/src/constants.js
packages/flow-dev-tools/src/constants.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import {resolve} from 'path'; const TOOL_ROOT = resolve(__dirname, "../"); const FLOW_ROOT = resolve(__dirname, "../../../"); export const defaultTestsDirName = "newtests"; // This is where we look for tests to run and where we put newly converted // tests export function getTestsDir(relative_to?: string): string { if (relative_to !== undefined) { return resolve(relative_to, defaultTestsDirName); } else { return resolve(FLOW_ROOT, defaultTestsDirName); } } export const binOptions: Array<string> = [ resolve(FLOW_ROOT, "bin/flow"), // Open source build resolve(FLOW_ROOT, "bin/flow.exe"), // Open source windows build resolve(FLOW_ROOT, "../buck-out/gen/flow/flow/flow"), // Buck ]; export const defaultFlowConfigName = "_flowconfig";
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ import {dirname, join, resolve} from 'path'; const FLOW_ROOT = resolve(__dirname, '../../../'); export const defaultTestsDirName = 'newtests'; // This is where we look for tests to run and where we put newly converted // tests export function getTestsDir(relative_to?: string): string { if (relative_to !== undefined) { return resolve(relative_to, defaultTestsDirName); } else { return dirname(require.resolve(join(defaultTestsDirName, 'package.json'))); } } export const binOptions: Array<string> = [ resolve(FLOW_ROOT, 'bin/flow'), // Open source build resolve(FLOW_ROOT, 'bin/flow.exe'), // Open source windows build resolve(FLOW_ROOT, '../buck-out/gen/flow/flow/flow'), // Buck ]; export const defaultFlowConfigName = '_flowconfig';
Allow workspaces outside of the workspace root
Allow workspaces outside of the workspace root Summary: As part of the workspace separation, and because our repo does not have an ideal layout (for example `react-native-github` consists of both product and tooling code, and is hard to move right now), I am in need of making workspaces outside of a workspace root work with Buck. This works with Yarn, assuming `$NODE_PATH` is used for correct resolutions, but did not work with Yarn's Buck Macros until this diff. ## How do the Yarn Buck Macros work? Up until this week we didn't have anyone left at the company who understands this infrastructure. Now that I am the owner, here is a high-level overview of how things work: * `yarn_workspace` creates a zip file of the workspace in `buck-out` (without `package.json` file). * `yarn_workspace_root` creates a zip file of the `package.json` files of the root and all workspaces, `yarn.lock`, and `node_modules` for the corresponding workspace. * `yarn_workspace_archive` merges the zip files for each workspace and the root to produce what is more or less the same as a Metronome package. * `yarn_workspace_binary` which ties together all of the above to run a JavaScript tool given an entry point. ## Why does it use zip files? The reason that this infrastructure uses zip files is because it was optimized for size and cache hits. In the past our `node_modules` folders were way too large and significantly slowed down buck builds. My end goal with the workspace separation is that product code will not use any of these rules at all (once the files are checked in), and that we should get rid of all the overhead and complexity of using zip files – either by using Metronome or by getting rid of the feature in the Yarn workspace rules. ## What does this diff do? With all this context in mind, this diff changes the layout of the zip files created by `yarn_workspace_root` and `yarn_workspace_archive` to align with the behavior of Metronome. Instead of using relative paths mirroring the source locations in the zip files, we now use package names. For example, instead of `workspace.zip/tools/metro/packages/metro-symbolicate` we now simply put this file into the root, like `workspace.zip/metro-symbolicate`. For namespaced packages, we now use `fb-tools/gen-rn-routes/` (package name) instead of `tools/gen-rn-routes/` (file system path). This will allow us to use workspaces outside of the workspace root without breaking out of the assigned output folder in `buck-out`. This also means that I had to update all callsites of `yarn_workspace_binary` to adjust the entry point to a package-relative path that can be resolved via node instead of a path generated from the source layout by Buck. NOTE: Arguably, this is how it should have been from the beginning. However, it requires the codebase to be well-organized with packages and without relative requires across the repo. We only reached this state earlier this year after our big cleanup, so the previous solution to mirror the source locations made the most sense up until now. Special thanks to davidaurelio for his patience and help over WhatsApp. Reviewed By: yungsters Differential Revision: D24359263 fbshipit-source-id: 40c4925ade1b8d87d2e65799bb059cda24c9a65b
JavaScript
mit
nmote/flow,nmote/flow,nmote/flow,nmote/flow,nmote/flow,nmote/flow,nmote/flow
--- +++ @@ -5,13 +5,13 @@ * LICENSE file in the root directory of this source tree. * * @flow + * @format */ -import {resolve} from 'path'; +import {dirname, join, resolve} from 'path'; -const TOOL_ROOT = resolve(__dirname, "../"); -const FLOW_ROOT = resolve(__dirname, "../../../"); -export const defaultTestsDirName = "newtests"; +const FLOW_ROOT = resolve(__dirname, '../../../'); +export const defaultTestsDirName = 'newtests'; // This is where we look for tests to run and where we put newly converted // tests @@ -19,14 +19,14 @@ if (relative_to !== undefined) { return resolve(relative_to, defaultTestsDirName); } else { - return resolve(FLOW_ROOT, defaultTestsDirName); + return dirname(require.resolve(join(defaultTestsDirName, 'package.json'))); } } export const binOptions: Array<string> = [ - resolve(FLOW_ROOT, "bin/flow"), // Open source build - resolve(FLOW_ROOT, "bin/flow.exe"), // Open source windows build - resolve(FLOW_ROOT, "../buck-out/gen/flow/flow/flow"), // Buck + resolve(FLOW_ROOT, 'bin/flow'), // Open source build + resolve(FLOW_ROOT, 'bin/flow.exe'), // Open source windows build + resolve(FLOW_ROOT, '../buck-out/gen/flow/flow/flow'), // Buck ]; -export const defaultFlowConfigName = "_flowconfig"; +export const defaultFlowConfigName = '_flowconfig';
68d37b8d80edef757b252205d69290a829bdf9e1
src/script/window/action/context-menu.js
src/script/window/action/context-menu.js
'use strict'; const remote = require('remote'); const Menu = remote.require('menu'); const MenuItem = remote.require('menu-item'); const slackWebview = appRequire('webview/slack-webview'); let popupOpenEvent; function initialise() { const menu = new Menu(); menu.append(new MenuItem({ label: 'Inspect element', click: inspectElement })); menu.append(new MenuItem({ accelerator: 'F12', label : 'Open devtools', click : openDevTools })); menu.append(new MenuItem({ type: 'separator' })); menu.append(new MenuItem({ accelerator: 'Ctrl+F12', label : 'Open webview devtools', click : slackWebview.openDevTools })); window.addEventListener('contextmenu', function (event) { event.preventDefault(); popupOpenEvent = event; menu.popup(remote.getCurrentWindow()); }, false); } function inspectElement() { const browserWindow = remote.getCurrentWindow(); browserWindow.inspectElement(popupOpenEvent.clientX, popupOpenEvent.clientY); } function openDevTools() { const browserWindow = remote.getCurrentWindow(); browserWindow.openDevTools(); } exports.initialise = initialise;
'use strict'; const remote = require('remote'); const Menu = remote.require('menu'); const MenuItem = remote.require('menu-item'); const slackWebview = appRequire('webview/slack-webview'); let popupOpenEvent; function initialise() { const menu = new Menu(); menu.append(new MenuItem({ label: 'Inspect element', click: inspectElement })); menu.append(new MenuItem({ label: 'Open devtools', click: openDevTools })); menu.append(new MenuItem({ type: 'separator' })); menu.append(new MenuItem({ label: 'Open webview devtools', click: slackWebview.openDevTools })); window.addEventListener('contextmenu', function (event) { event.preventDefault(); popupOpenEvent = event; menu.popup(remote.getCurrentWindow()); }, false); } function inspectElement() { const browserWindow = remote.getCurrentWindow(); browserWindow.inspectElement(popupOpenEvent.clientX, popupOpenEvent.clientY); } function openDevTools() { const browserWindow = remote.getCurrentWindow(); browserWindow.openDevTools(); } exports.initialise = initialise;
Remove context menu item accelerators, as they are not honoured.
Remove context menu item accelerators, as they are not honoured.
JavaScript
mit
pekim/slack-wrapped,pekim/slack-wrapped
--- +++ @@ -16,17 +16,15 @@ })); menu.append(new MenuItem({ - accelerator: 'F12', - label : 'Open devtools', - click : openDevTools + label: 'Open devtools', + click: openDevTools })); menu.append(new MenuItem({ type: 'separator' })); menu.append(new MenuItem({ - accelerator: 'Ctrl+F12', - label : 'Open webview devtools', - click : slackWebview.openDevTools + label: 'Open webview devtools', + click: slackWebview.openDevTools })); window.addEventListener('contextmenu', function (event) {
939d1502140150ae539c6c74dd4fe1b2eb613438
lib/jestUnexpected.js
lib/jestUnexpected.js
const unexpected = require('unexpected'); const baseExpect = unexpected.clone(); baseExpect.addAssertion( '<string> to jest match <string>', (expect, subject, value) => { expect.errorMode = 'bubble'; return expect(subject, 'to contain', value); } ); baseExpect.addAssertion( '<string> to jest match <regexp>', (expect, subject, value) => { expect.errorMode = 'bubble'; return expect(subject, 'to satisfy', value); } ); function withFlags(assertion, flags) { return flags.not ? `not ${assertion}` : assertion; } module.exports = function expect(subject) { const expect = baseExpect; const flags = { not: false }; const buildAssertion = assertion => { return value => { return expect(subject, withFlags(assertion, flags), value); }; }; return { toBe: buildAssertion('to be'), toEqual: buildAssertion('to equal'), toMatch: buildAssertion('to jest match'), get not() { flags.not = true; return this; } }; };
const unexpected = require('unexpected'); const baseExpect = unexpected.clone(); baseExpect.addAssertion( '<string> to jest match <string>', (expect, subject, value) => { expect.errorMode = 'bubble'; return expect(subject, 'to contain', value); } ); baseExpect.addAssertion( '<string> to jest match <regexp>', (expect, subject, value) => { expect.errorMode = 'bubble'; return expect(subject, 'to match', value); } ); function withFlags(assertion, flags) { return flags.not ? `not ${assertion}` : assertion; } module.exports = function expect(subject) { const expect = baseExpect; const flags = { not: false }; const buildAssertion = assertion => { return value => { return expect(subject, withFlags(assertion, flags), value); }; }; return { toBe: buildAssertion('to be'), toEqual: buildAssertion('to equal'), toMatch: buildAssertion('to jest match'), get not() { flags.not = true; return this; } }; };
Switch toMatch() to "to match" in the case of a regex on the RHS.
Switch toMatch() to "to match" in the case of a regex on the RHS.
JavaScript
bsd-3-clause
alexjeffburke/jest-unexpected
--- +++ @@ -13,7 +13,7 @@ '<string> to jest match <regexp>', (expect, subject, value) => { expect.errorMode = 'bubble'; - return expect(subject, 'to satisfy', value); + return expect(subject, 'to match', value); } );
58f635a28ceac0466ad3b928a5201c4443e60ff2
source/js/tests/config.js
source/js/tests/config.js
// Documentation available at https://theintern.github.io define({ proxyPort: 9010, proxyUrl: 'http://localhost:9010/', excludeInstrumentation: /^(?:bower_components|node_modules|public)\//, tunnel: 'NullTunnel', loaderOptions: { packages: [ { name: 'Wee', location: '/public/assets/js', main: 'script.min.js' } ] }, functionalSuites: [ ], suites: [ '/source/js/tests/unit/example' ], environments: [ { browserName: 'chrome' } ] });
// Documentation available at https://theintern.github.io define({ proxyPort: 9010, proxyUrl: 'http://localhost:9010/', excludeInstrumentation: /^(?:bower_components|node_modules|public)\//, tunnel: 'NullTunnel', loaderOptions: { packages: [ { name: 'Wee', location: 'public/assets/js', main: 'script.min.js' } ] }, functionalSuites: [ ], suites: [ 'source/js/tests/unit/example' ], environments: [ { browserName: 'chrome' } ] });
Update testing path to support new core /$root proxy route
Update testing path to support new core /$root proxy route
JavaScript
apache-2.0
weepower/wee,weepower/wee
--- +++ @@ -9,7 +9,7 @@ packages: [ { name: 'Wee', - location: '/public/assets/js', + location: 'public/assets/js', main: 'script.min.js' } ] @@ -18,7 +18,7 @@ ], suites: [ - '/source/js/tests/unit/example' + 'source/js/tests/unit/example' ], environments: [ {
b297f9bad36d7955d1841744301a37489aa528bf
addon/adapters/web-api.js
addon/adapters/web-api.js
import Ember from 'ember'; import DS from 'ember-data'; const VALIDATION_ERROR_STATUSES = [400, 422]; export default DS.RESTAdapter.extend({ namespace: 'api', isInvalid: function(status) { return VALIDATION_ERROR_STATUSES.indexOf(status) >= 0; }, // Override the parseErrorResponse method from RESTAdapter // so that we can munge the modelState into an errors collection. parseErrorResponse: function(responseText) { let json = this._super(responseText), strippedErrors = {}, jsonIsObject = json && (typeof json === 'object'); if (jsonIsObject && json.message) { delete json.message; } if (jsonIsObject && json.modelState) { Object.keys(json.modelState).forEach(key => { let newKey = key.substring(key.indexOf('.') + 1).camelize(); strippedErrors[newKey] = json.modelState[key]; }); json.errors = this.strippedErrors; delete json.modelState; } return json; } });
import Ember from 'ember'; import DS from 'ember-data'; const VALIDATION_ERROR_STATUSES = [400, 422]; export default DS.RESTAdapter.extend({ namespace: 'api', isInvalid: function(status) { return VALIDATION_ERROR_STATUSES.indexOf(status) >= 0; }, // Override the parseErrorResponse method from RESTAdapter // so that we can munge the modelState into an errors collection. // The source of the original method can be found at: // https://github.com/emberjs/data/blob/v2.1.0/packages/ember-data/lib/adapters/rest-adapter.js#L899 parseErrorResponse: function(responseText) { let json = this._super(responseText), strippedErrors = {}, jsonIsObject = json && (typeof json === 'object'); if (jsonIsObject && json.message) { delete json.message; } if (jsonIsObject && json.modelState) { Object.keys(json.modelState).forEach(key => { let newKey = key.substring(key.indexOf('.') + 1).camelize(); strippedErrors[newKey] = json.modelState[key]; }); json.errors = this.strippedErrors; delete json.modelState; } return json; } });
Update the comment with the URL to the source
Update the comment with the URL to the source
JavaScript
mit
CrshOverride/ember-web-api,CrshOverride/ember-web-api
--- +++ @@ -12,6 +12,8 @@ // Override the parseErrorResponse method from RESTAdapter // so that we can munge the modelState into an errors collection. + // The source of the original method can be found at: + // https://github.com/emberjs/data/blob/v2.1.0/packages/ember-data/lib/adapters/rest-adapter.js#L899 parseErrorResponse: function(responseText) { let json = this._super(responseText), strippedErrors = {},
a6bf1851c243ed51d8c17dc5b3d007fbee9a758b
addons/knobs/src/index.js
addons/knobs/src/index.js
import { window } from 'global'; import deprecate from 'util-deprecate'; import addons from '@storybook/addons'; import { vueHandler } from './vue'; import { reactHandler } from './react'; import { angularHandler } from './angular'; import { knob, text, boolean, number, color, object, array, date, manager } from './base'; export { knob, text, boolean, number, color, object, array, date }; deprecate( () => {}, 'Using @storybook/addon-knobs directly is discouraged, please use @storybook/addon-knobs/{{framework}}' ); // generic higher-order component decorator for all platforms - usage is discouraged // This file Should be removed with 4.0 release function wrapperKnobs(options) { const channel = addons.getChannel(); manager.setChannel(channel); if (options) channel.emit('addon:knobs:setOptions', options); switch (window.STORYBOOK_ENV) { case 'vue': { return vueHandler(channel, manager.knobStore); } case 'react': { return reactHandler(channel, manager.knobStore); } case 'angular': { return angularHandler(channel, manager.knobStore); } default: { return reactHandler(channel, manager.knobStore); } } } export function withKnobs(storyFn, context) { return wrapperKnobs()(storyFn)(context); } export function withKnobsOptions(options = {}) { return (storyFn, context) => wrapperKnobs(options)(storyFn)(context); }
import { window } from 'global'; import deprecate from 'util-deprecate'; import addons from '@storybook/addons'; import { vueHandler } from './vue'; import { reactHandler } from './react'; import { knob, text, boolean, number, color, object, array, date, manager } from './base'; export { knob, text, boolean, number, color, object, array, date }; deprecate( () => {}, 'Using @storybook/addon-knobs directly is discouraged, please use @storybook/addon-knobs/{{framework}}' ); // generic higher-order component decorator for all platforms - usage is discouraged // This file Should be removed with 4.0 release function wrapperKnobs(options) { const channel = addons.getChannel(); manager.setChannel(channel); if (options) channel.emit('addon:knobs:setOptions', options); switch (window.STORYBOOK_ENV) { case 'vue': { return vueHandler(channel, manager.knobStore); } case 'react': { return reactHandler(channel, manager.knobStore); } default: { return reactHandler(channel, manager.knobStore); } } } export function withKnobs(storyFn, context) { return wrapperKnobs()(storyFn)(context); } export function withKnobsOptions(options = {}) { return (storyFn, context) => wrapperKnobs(options)(storyFn)(context); }
REMOVE angular knobs from old-style import
REMOVE angular knobs from old-style import
JavaScript
mit
storybooks/storybook,storybooks/storybook,rhalff/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,rhalff/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,rhalff/storybook,rhalff/storybook,rhalff/storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,storybooks/storybook
--- +++ @@ -4,7 +4,6 @@ import { vueHandler } from './vue'; import { reactHandler } from './react'; -import { angularHandler } from './angular'; import { knob, text, boolean, number, color, object, array, date, manager } from './base'; @@ -30,9 +29,6 @@ case 'react': { return reactHandler(channel, manager.knobStore); } - case 'angular': { - return angularHandler(channel, manager.knobStore); - } default: { return reactHandler(channel, manager.knobStore); }
70e1ebb7559a7e131e72cef4e50a37e2c7792838
assets/js/document-nav.js
assets/js/document-nav.js
$(function() { var $documentNav = $('.document-nav'); if($documentNav.length) { var targets = [] , $window = $(window); $documentNav.find('a').each(function() { targets.push( $($(this).attr('href')) ) }); function setActive($current) { var $parent = $current.closest('li') , $parentParent = $parent.parent().closest('li'); $documentNav.find('.current, .active').removeClass('current active') $current.addClass('current') if($parentParent.length) { $parentParent.addClass('active') } else { $parent.addClass('active') } } // HASH change, update menu // ======================== $window.on('hashchange', function() { setTimeout(function() { setActive($documentNav.find('[href='+location.hash+']')) }, 1); }); // Scroll, update menu // =================== $window.on('scroll', function() { var scrollTop = $window.scrollTop(); $.each( targets, function($index, $el) { var sectionBottom = (targets[$index+1] && targets[$index+1].offset().top - 1) || $window.height() if ($el.length && scrollTop - sectionBottom < -48) { setActive($documentNav.find('[href=#'+$el.attr('id')+']')) return false; } }); }); } });
$(function() { var $documentNav = $('.document-nav'); if($documentNav.length) { var targets = [] , $window = $(window) , changeHash = false; $documentNav.find('a').each(function() { targets.push( $($(this).attr('href')) ) }); function setActive(hash) { var $current = $documentNav.find('[href='+hash+']') , $parent = $current.closest('li') , $parentParent = $parent.parent().closest('li'); $documentNav.find('.current, .active').removeClass('current active') $current.addClass('current') if($parentParent.length) { $parentParent.addClass('active') } else { $parent.addClass('active') } if(history.pushState) { history.pushState(null, null, hash); } else { location.hash = hash; } } // Scroll, update menu // =================== $window.on('scroll', function() { var scrollTop = $window.scrollTop(); console.log ('scroll', scrollTop); $.each( targets, function($index, $el) { var sectionBottom = (targets[$index+1] && targets[$index+1].offset().top - 1) || $window.height() if ($el.length && scrollTop - sectionBottom < -48) { setActive('#'+$el.attr('id')) return false; } }); }); } });
Fix scrollSpy bug preventing original scroll to happen if a hash is present
Fix scrollSpy bug preventing original scroll to happen if a hash is present
JavaScript
mit
pillars/bibliosoph
--- +++ @@ -5,14 +5,16 @@ if($documentNav.length) { var targets = [] - , $window = $(window); + , $window = $(window) + , changeHash = false; $documentNav.find('a').each(function() { targets.push( $($(this).attr('href')) ) }); - function setActive($current) { - var $parent = $current.closest('li') + function setActive(hash) { + var $current = $documentNav.find('[href='+hash+']') + , $parent = $current.closest('li') , $parentParent = $parent.parent().closest('li'); @@ -21,28 +23,29 @@ if($parentParent.length) { $parentParent.addClass('active') - } else { + } + else { $parent.addClass('active') } + + if(history.pushState) { + history.pushState(null, null, hash); + } + else { + location.hash = hash; + } } - - // HASH change, update menu - // ======================== - $window.on('hashchange', function() { - setTimeout(function() { - setActive($documentNav.find('[href='+location.hash+']')) - }, 1); - }); // Scroll, update menu // =================== $window.on('scroll', function() { var scrollTop = $window.scrollTop(); + console.log ('scroll', scrollTop); $.each( targets, function($index, $el) { var sectionBottom = (targets[$index+1] && targets[$index+1].offset().top - 1) || $window.height() if ($el.length && scrollTop - sectionBottom < -48) { - setActive($documentNav.find('[href=#'+$el.attr('id')+']')) + setActive('#'+$el.attr('id')) return false; } });
95b6e11a11d21dba2eef8ce8d426f1c866c289f9
app/assets/javascripts/representatives.js
app/assets/javascripts/representatives.js
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. function VoteStatsGraph(selector, options) { this.selector = selector; this.options = options; } VoteStatsGraph.prototype.render = function() { this.chart = new Highcharts.Chart({ chart: { renderTo: this.selector, type: 'spline', backgroundColor: null }, credits: { enabled: false }, title: { text: this.options.title }, subtitle: { text: this.options.subtitle }, xAxis: { type: 'datetime', dateTimeLabelFormats: { month: '%Y-%m', year: '%b' } }, yAxis: { title: { text: '' }, labels: false, }, tooltip: { formatter: function() { return '<b>'+ this.series.name +'</b><br/>'+ Highcharts.dateFormat('%Y-%m-%d', this.x); } }, series: this.options.series }); };
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. function VoteStatsGraph(selector, options) { this.selector = selector; this.options = options; } VoteStatsGraph.prototype.render = function() { this.chart = new Highcharts.Chart({ chart: { renderTo: this.selector, type: 'spline', backgroundColor: null }, credits: { enabled: false }, title: { text: this.options.title }, subtitle: { text: this.options.subtitle }, xAxis: { type: 'datetime', dateTimeLabelFormats: { month: '%Y-%m', year: '%b' } }, yAxis: { title: { text: '' }, labels: false, tickInterval: 1, }, tooltip: { formatter: function() { return '<b>'+ this.series.name +'</b><br/>'+ Highcharts.dateFormat('%Y-%m-%d', this.x); } }, series: this.options.series }); };
Remove empty lines in representative graph.
Remove empty lines in representative graph.
JavaScript
bsd-3-clause
holderdeord/hdo-site,holderdeord/hdo-site,holderdeord/hdo-site,holderdeord/hdo-site
--- +++ @@ -32,6 +32,7 @@ text: '' }, labels: false, + tickInterval: 1, }, tooltip: { formatter: function() {
3937af4c24411a6b34015f2c69f1df5fa5ab6475
packages/relay-compiler/RelayCompiler.js
packages/relay-compiler/RelayCompiler.js
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @providesModule RelayCompiler * @format */ 'use strict'; const GraphQLCompiler = require('GraphQLCompiler'); /** * For now, the `RelayCompiler` *is* the `GraphQLCompiler`, but we're creating * this aliasing module to provide for the possibility of divergence (as the * `RelayCompiler` becomes more specific, and the `GraphQLCompiler` becomes more * general). */ const RelayCompiler = GraphQLCompiler; module.exports = RelayCompiler;
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @providesModule RelayCompiler * @format */ 'use strict'; const {Compiler} = require('./graphql-compiler/GraphQLCompilerPublic'); /** * For now, the `RelayCompiler` *is* the `GraphQLCompiler`, but we're creating * this aliasing module to provide for the possibility of divergence (as the * `RelayCompiler` becomes more specific, and the `GraphQLCompiler` becomes more * general). */ const RelayCompiler = Compiler; module.exports = RelayCompiler;
Test importing from graphql-compiler package
Test importing from graphql-compiler package Reviewed By: leebyron Differential Revision: D5828011 fbshipit-source-id: 3c514c9b611f900234a22004bba1554436bf9df8
JavaScript
mit
kassens/relay,kassens/relay,facebook/relay,benjaminogles/relay,dbslone/relay,facebook/relay,zpao/relay,xuorig/relay,voideanvalue/relay,cpojer/relay,facebook/relay,dbslone/relay,benjaminogles/relay,josephsavona/relay,iamchenxin/relay,atxwebs/relay,wincent/relay,xuorig/relay,xuorig/relay,iamchenxin/relay,voideanvalue/relay,kassens/relay,atxwebs/relay,kassens/relay,yungsters/relay,voideanvalue/relay,atxwebs/relay,wincent/relay,yungsters/relay,iamchenxin/relay,zpao/relay,cpojer/relay,voideanvalue/relay,zpao/relay,apalm/relay,cpojer/relay,benjaminogles/relay,iamchenxin/relay,freiksenet/relay,voideanvalue/relay,facebook/relay,freiksenet/relay,apalm/relay,yungsters/relay,wincent/relay,kassens/relay,wincent/relay,facebook/relay,cpojer/relay,atxwebs/relay,wincent/relay,josephsavona/relay,xuorig/relay,josephsavona/relay,wincent/relay,voideanvalue/relay,kassens/relay,facebook/relay,apalm/relay,xuorig/relay,freiksenet/relay,xuorig/relay
--- +++ @@ -13,7 +13,7 @@ 'use strict'; -const GraphQLCompiler = require('GraphQLCompiler'); +const {Compiler} = require('./graphql-compiler/GraphQLCompilerPublic'); /** * For now, the `RelayCompiler` *is* the `GraphQLCompiler`, but we're creating @@ -21,6 +21,6 @@ * `RelayCompiler` becomes more specific, and the `GraphQLCompiler` becomes more * general). */ -const RelayCompiler = GraphQLCompiler; +const RelayCompiler = Compiler; module.exports = RelayCompiler;
b2e834f24e5e6dbe7cb0f3beb39253eb978704d9
notifications/helpers.js
notifications/helpers.js
import { createClient, } from 'redis'; import nconf from '../config'; let sub; let client; function redisConns() { sub = createClient(nconf.get('redis')); client = createClient(nconf.get('redis')); } export function fetchChannelList(redis, table) { console.log(`fetching channels for ${table}`); return new Promise((accept, reject) => { redis.keys(`${table}::*`, (err, values) => { if (!err) { const names = values.map(keyname => keyname.split('::')[1]); accept(names); } else { reject(err); } }); }); } export default function registerNotifications(slushbot, table, sendMessageToChannel) { if (!sub || !client) { redisConns(); } sub.on('message', (chan, msg) => { console.log(`notification on ${table}: ${msg}`); fetchChannelList(client, table) .then(channels => { console.log(`channel list: ${channels}`); channels.map(channel => { sendMessageToChannel(msg, channel, slushbot); }); }) .catch(err => console.err(err)); }); // Sub sub.subscribe(table); }
import { createClient, } from 'redis'; import nconf from '../config'; let sub; let client; function redisConns() { sub = createClient(nconf.get('redis')); client = createClient(nconf.get('redis')); } export function fetchChannelList(redis, table) { console.log(`fetching channels for ${table}`); return new Promise((accept, reject) => { redis.keys(`${table}::*`, (err, values) => { if (!err) { const names = values.map(keyname => keyname.split('::')[1]); accept(names); } else { reject(err); } }); }); } export default function registerNotifications(slushbot, table, sendMessageToChannel) { if (!sub || !client) { redisConns(); } sub.on('message', (chan, msg) => { if (chan === table) { console.log(`notification on ${chan}: ${msg}`); fetchChannelList(client, chan) .then(channels => { console.log(`channel list: ${channels}`); channels.map(channel => { sendMessageToChannel(msg, channel, slushbot); }); }) .catch(err => console.err(err)); } }); // Sub sub.subscribe(table); }
Fix the issue with posting all notifications even when you are subscribed to one
Fix the issue with posting all notifications even when you are subscribed to one
JavaScript
mit
rit-sse/slushbot,rit-sse/slushbot
--- +++ @@ -30,15 +30,17 @@ redisConns(); } sub.on('message', (chan, msg) => { - console.log(`notification on ${table}: ${msg}`); - fetchChannelList(client, table) - .then(channels => { - console.log(`channel list: ${channels}`); - channels.map(channel => { - sendMessageToChannel(msg, channel, slushbot); - }); - }) - .catch(err => console.err(err)); + if (chan === table) { + console.log(`notification on ${chan}: ${msg}`); + fetchChannelList(client, chan) + .then(channels => { + console.log(`channel list: ${channels}`); + channels.map(channel => { + sendMessageToChannel(msg, channel, slushbot); + }); + }) + .catch(err => console.err(err)); + } }); // Sub sub.subscribe(table);
6dd54b63ee36f46b490bcbfda97193d567386756
dev/_/components/js/visualizationView.js
dev/_/components/js/visualizationView.js
AV.VisualizationView = Backbone.View.extend({ el: '#visualization', // The rendering of the visualization will be slightly // different here, because there is no templating necessary: // The server gives back a page. render: function() { this.model.url = this.model.urlRoot + this.model.id + '/view?mode=heatmap&condensed=true'; var response = $.ajax({ url: this.model.url, type: "GET" }).done(_.bind(function(d) { //If the server returns an HTML document if (d[0] != 'R') { return d; } else { //Rendering setTimeout(function(){}, 1000); return this.render(); } }, this)); this.$el.attr('src', this.model.url).load(_.bind(function() { var iframe = this.$el.contents(); // iframe.find('.menubar').remove(); // iframe.find('.title-bar').remove(); }, this)); $('#basicModal').modal({ show: true }); } });
AV.VisualizationView = Backbone.View.extend({ el: '#visualization', initialize: function() { this.$el.load(_.bind(function(){ console.log("it did a reload"); console.log(this.$el.contents()[0].title); if (!(this.$el.contents()[0].title)) { console.log("RENDERING it says"); document.getElementById('visualization') .contentWindow .location .reload(true); } }, this)); }, // The rendering of the visualization will be slightly // different here, because there is no templating necessary: // The server gives back a page. render: function() { this.model.url = this.model.urlRoot + this.model.id + '/view?mode=heatmap&condensed=true'; var response = $.ajax({ url: this.model.url, type: "GET" }).done(_.bind(function(d) { //If the server returns an HTML document if (d[0] != 'R') { return d; } else { //Rendering setTimeout(function(){}, 1000); return this.render(); } }, this)); this.$el.attr('src', this.model.url).load(_.bind(function() { var iframe = this.$el.contents(); iframe.find('.menubar').remove(); // iframe.find('.title-bar').remove(); }, this)); $('#basicModal').modal({ show: true }); } });
Refresh iframe on "RENDERING" change
Refresh iframe on "RENDERING" change
JavaScript
bsd-3-clause
Swarthmore/juxtaphor,Swarthmore/juxtaphor
--- +++ @@ -1,5 +1,21 @@ AV.VisualizationView = Backbone.View.extend({ el: '#visualization', + + initialize: function() { + this.$el.load(_.bind(function(){ + console.log("it did a reload"); + console.log(this.$el.contents()[0].title); + if (!(this.$el.contents()[0].title)) { + console.log("RENDERING it says"); + document.getElementById('visualization') + .contentWindow + .location + .reload(true); + } + }, this)); + }, + + // The rendering of the visualization will be slightly // different here, because there is no templating necessary: // The server gives back a page. @@ -18,12 +34,10 @@ return this.render(); } }, this)); - - this.$el.attr('src', this.model.url).load(_.bind(function() { var iframe = this.$el.contents(); - // iframe.find('.menubar').remove(); - // iframe.find('.title-bar').remove(); + iframe.find('.menubar').remove(); +// iframe.find('.title-bar').remove(); }, this)); $('#basicModal').modal({
495701f1977ef5493497a8855cd9fcafb1ceaad5
src/clientDOMInterface.js
src/clientDOMInterface.js
var $ = require('jquery'); var _ = require('./utils.js'); // When passed to the template evaluator, // its render method will create actual DOM elements var DOMInterface = function() { return { createFragment: function() { return document.createDocumentFragment(); }, createDOMElement: function(tag, id, classes, attributes) { var elem = document.createElement(tag); if(id) elem.id = id; if(classes && classes.length) elem.className = classes.join(' '); // elem = $(elem); _.each(attributes, function(value, key) { // if(['checked', 'selected', 'disabled', 'readonly', 'multiple', 'defer', 'declare', 'noresize'].indexOf(key) != -1) { // } else { // elem.setAttribute(key, value); // } elem[key] = value; // elem.attr(key, value); }); return elem; }, createTextNode: function(text) { return document.createTextNode(text); } }; }; module.exports = DOMInterface;
var $ = require('jquery'); var _ = require('./utils.js'); // When passed to the template evaluator, // its render method will create actual DOM elements var DOMInterface = function() { return { createFragment: function() { return document.createDocumentFragment(); }, createDOMElement: function(tag, id, classes, attributes) { var elem = document.createElement(tag); if(id) elem.id = id; if(classes && classes.length) elem.className = classes.join(' '); // elem = $(elem); _.each(attributes, function(value, key) { // if(['checked', 'selected', 'disabled', 'readonly', 'multiple', 'defer', 'declare', 'noresize'].indexOf(key) != -1) { // } else { elem.setAttribute(key, value); // } // elem[key] = value; // elem.attr(key, value); }); return elem; }, createTextNode: function(text) { return document.createTextNode(text); } }; }; module.exports = DOMInterface;
Fix regression when setting custom attributes on DOM elements
Fix regression when setting custom attributes on DOM elements
JavaScript
mit
syntheticore/declaire
--- +++ @@ -18,9 +18,9 @@ _.each(attributes, function(value, key) { // if(['checked', 'selected', 'disabled', 'readonly', 'multiple', 'defer', 'declare', 'noresize'].indexOf(key) != -1) { // } else { - // elem.setAttribute(key, value); + elem.setAttribute(key, value); // } - elem[key] = value; + // elem[key] = value; // elem.attr(key, value); }); return elem;
7eaad2f4582da2f63cfe57e182d73f97abaebfca
src/components/table-view/checker.js
src/components/table-view/checker.js
import React from 'react' export default function Checker({ multiselect, checked, disabled, id, name, onChange }) { if (disabled) { return null } return ( <label className="ars-table-checker"> <span className="ars-hidden"> {checked ? 'Deselect' : 'Select'} {name} </span> <input type={multiselect ? 'checkbox' : 'radio'} onChange={onChange.bind(null, id)} checked={checked} /> </label> ) }
import React from 'react' export default function Checker({ multiselect, checked, disabled, id, name, onChange }) { if (disabled) { return null } return ( <label className="ars-table-checker"> <span className="ars-hidden"> {checked ? 'Deselect' : 'Select'} {name} </span> <input type={multiselect ? 'checkbox' : 'radio'} name="_ars_gallery_checker" onChange={onChange.bind(null, id)} checked={checked} /> </label> ) }
Use the same name on checkboxes to allow keyboard entry
Use the same name on checkboxes to allow keyboard entry
JavaScript
mit
vigetlabs/ars-arsenal,vigetlabs/ars-arsenal,vigetlabs/ars-arsenal
--- +++ @@ -20,6 +20,7 @@ <input type={multiselect ? 'checkbox' : 'radio'} + name="_ars_gallery_checker" onChange={onChange.bind(null, id)} checked={checked} />
5781e808241d4ac821e58832abee7b4847e54f1c
src/components/Restart.js
src/components/Restart.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import store from '../store.js'; import { restart } from '../actions/name-actions'; import { selectGender } from '../actions/gender-actions'; import MdBack from 'react-icons/lib/md/keyboard-arrow-left'; class Restart extends Component { constructor(props) { super(props); } restart() { store.dispatch(restart()); store.dispatch(selectGender(null)); localStorage.clear(); } render() { return ( <div className="navbar"> <a className="is-pulled-left" onClick={this.restart}><MdBack></MdBack> Byrja av nýggjum</a> </div> ); } } const mapStateToProps = function (store) { return { names: store.names, gender: store.gender }; } export default connect(mapStateToProps)(Restart);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import store from '../store.js'; import { restart } from '../actions/name-actions'; import { selectGender } from '../actions/gender-actions'; import MdBack from 'react-icons/lib/md/keyboard-arrow-left'; class Restart extends Component { constructor(props) { super(props); } restart() { store.dispatch(restart()); store.dispatch(selectGender(null)); localStorage.clear(); } render() { return ( <div className="navbar"> <a className="restart" onClick={this.restart}><MdBack></MdBack> Byrja av nýggjum</a> </div> ); } } const mapStateToProps = function (store) { return { names: store.names, gender: store.gender }; } export default connect(mapStateToProps)(Restart);
Add new class to restart
Add new class to restart
JavaScript
apache-2.0
johnbrowe/barnanavn,johnbrowe/barnanavn,johnbrowe/barnanavn
--- +++ @@ -20,7 +20,7 @@ render() { return ( <div className="navbar"> - <a className="is-pulled-left" onClick={this.restart}><MdBack></MdBack> Byrja av nýggjum</a> + <a className="restart" onClick={this.restart}><MdBack></MdBack> Byrja av nýggjum</a> </div> ); }
8e406d84dbc5c0da73428c1be5ce3915c12a59de
src/foam/nanos/auth/Relationships.js
src/foam/nanos/auth/Relationships.js
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ /* foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.Group', targetModel: 'foam.nanos.auth.Permission', forwardName: 'permissions', inverseName: 'groups', sourceProperty: { hidden: true }, targetProperty: { hidden: true } }); */ /* foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.User', targetModel: 'foam.nanos.auth.Group', forwardName: 'groups', inverseName: 'users', sourceProperty: { hidden: true }, targetProperty: { hidden: true } }); */ foam.RELATIONSHIP({ cardinality: '1:*', sourceModel: 'foam.nanos.auth.Group', targetModel: 'foam.nanos.auth.User', forwardName: 'users', inverseName: 'group', sourceProperty: { hidden: true }, targetProperty: { hidden: true } });
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ /* foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.Group', targetModel: 'foam.nanos.auth.Permission', forwardName: 'permissions', inverseName: 'groups', sourceProperty: { hidden: true }, targetProperty: { hidden: true } }); */ /* foam.RELATIONSHIP({ cardinality: '*:*', sourceModel: 'foam.nanos.auth.User', targetModel: 'foam.nanos.auth.Group', forwardName: 'groups', inverseName: 'users', sourceProperty: { hidden: true }, targetProperty: { hidden: true } }); */ foam.RELATIONSHIP({ cardinality: '1:*', sourceModel: 'foam.nanos.auth.Group', targetModel: 'foam.nanos.auth.User', forwardName: 'users', inverseName: 'group', sourceProperty: { hidden: true }, targetProperty: { hidden: false } });
Make group property in user visible.
Make group property in user visible.
JavaScript
apache-2.0
jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2
--- +++ @@ -47,6 +47,6 @@ hidden: true }, targetProperty: { - hidden: true + hidden: false } });
a5d22e50ef1c18a37c4b59d24f893677839ca5e1
lib/util/nullwritable.js
lib/util/nullwritable.js
/* * stompit.NullWritable * Copyright (c) 2014 Graham Daws <graham.daws@gmail.com> * MIT licensed */ var stream = require('stream'); var util = require('util'); function NullWritable(){ stream.Writable.call(this); this.bytesWritten = 0; } util.inherits(NullWritable, stream.Writable); NullWritable.prototype._write = function(chunk, encoding, callback){ this.bytesWritten += chunk.length; callback(); }; module.exports = NullWritable;
/* * stompit.NullWritable * Copyright (c) 2014 Graham Daws <graham.daws@gmail.com> * MIT licensed */ var stream = require('stream'); var util = require('util'); var crypto = require('crypto'); function NullWritable(hashAlgorithm){ stream.Writable.call(this); this.bytesWritten = 0; this._hash = crypto.createHash(hashAlgorithm || 'md5'); } util.inherits(NullWritable, stream.Writable); NullWritable.prototype._write = function(chunk, encoding, callback){ this.bytesWritten += chunk.length; this._hash.update(chunk); callback(); }; NullWritable.prototype.getBytesWritten = function(){ return this.bytesWritten; }; NullWritable.prototype.getHashDigest = function(encoding){ return this._hash.digest(encoding); }; module.exports = NullWritable;
Add hash digest calcuation to NullWritable
Add hash digest calcuation to NullWritable
JavaScript
mit
gdaws/node-stomp
--- +++ @@ -6,19 +6,28 @@ var stream = require('stream'); var util = require('util'); +var crypto = require('crypto'); -function NullWritable(){ - +function NullWritable(hashAlgorithm){ stream.Writable.call(this); - this.bytesWritten = 0; + this._hash = crypto.createHash(hashAlgorithm || 'md5'); } util.inherits(NullWritable, stream.Writable); NullWritable.prototype._write = function(chunk, encoding, callback){ this.bytesWritten += chunk.length; + this._hash.update(chunk); callback(); }; +NullWritable.prototype.getBytesWritten = function(){ + return this.bytesWritten; +}; + +NullWritable.prototype.getHashDigest = function(encoding){ + return this._hash.digest(encoding); +}; + module.exports = NullWritable;
e154bb8b1d231b80340baf56fbf5549eaffe7669
lib/utils/queryparams.js
lib/utils/queryparams.js
var querystring = require('querystring'); function isFunction(func) { return typeof func == 'function'; } module.exports = { stringify: function(object) { var converted = {}; for (var key in object) { if (isFunction(object[key].getTime)) { converted[key] = Math.round(object[key].getTime() / 1000); } else { converted[key] = object[key]; } } return querystring.stringify(converted); } };
var querystring = require('querystring'); function isFunction(func) { return typeof func === 'function'; } module.exports = { stringify: function(object) { var converted = {}; for (var key in object) { if (isFunction(object[key].getTime)) { converted[key] = Math.round(object[key].getTime() / 1000); } else { converted[key] = object[key]; } } return querystring.stringify(converted); } };
Use strict equals for function checking
Use strict equals for function checking
JavaScript
mit
delighted/delighted-node,callemall/delighted-node
--- +++ @@ -1,7 +1,7 @@ var querystring = require('querystring'); function isFunction(func) { - return typeof func == 'function'; + return typeof func === 'function'; } module.exports = {
63cea3de01e108c43815cac66f88ccde3d22f1a8
lang-ext.js
lang-ext.js
/** * Extend +destination+ with +source+ */ function extend(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; }; extend(Array.prototype, { /** * Performs the given function +f+ on each element in the array instance. * The function is given the index of the current object and the object * itself for each element in the array. */ each: function(f) { for (i = 0; i < this.length; i++) { f(i, this[i]); } } });
/** * Extend +destination+ with +source+ */ function extend(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; }; extend(Array.prototype, { /** * Performs the given function +f+ on each element in the array instance. * The function is given the index of the current object and the object * itself for each element in the array. */ each: function(f) { for (i = 0; i < this.length; i++) { f(i, this[i]); } }, /** * Constructs a new array by applying the given function to each element * of this array. */ map: function(f) { result = []; this.each(function(i,e) { result.push(f(i, e)); }); return result; }, /** * Applies the given function to each element in the array until a * match is made. Otherwise returns null. * */ contains: function(f) { for (i = 0; i < this.length; i++) { if (f(this[i])) return this[i]; } return null; } });
Add map() and contains() functions to Array class.
Add map() and contains() functions to Array class.
JavaScript
mit
Northern01/tuneup_js,MYOB-Technology/tuneup_js,Northern01/tuneup_js,misfitdavidl/tuneup_js,alexvollmer/tuneup_js,songxiang321/ios-monkey,MYOB-Technology/tuneup_js,alexvollmer/tuneup_js,giginet/tuneup_js,songxiang321/ios-monkey,Banno/tuneup_js,giginet/tuneup_js,misfitdavidl/tuneup_js,Banno/tuneup_js
--- +++ @@ -18,5 +18,28 @@ for (i = 0; i < this.length; i++) { f(i, this[i]); } + }, + + /** + * Constructs a new array by applying the given function to each element + * of this array. + */ + map: function(f) { + result = []; + this.each(function(i,e) { + result.push(f(i, e)); + }); + return result; + }, + + /** + * Applies the given function to each element in the array until a + * match is made. Otherwise returns null. + * */ + contains: function(f) { + for (i = 0; i < this.length; i++) { + if (f(this[i])) return this[i]; + } + return null; } });
b687c6d803bd7a026d68927e5ec16a7323814c8b
src/authentication/steps/install.js
src/authentication/steps/install.js
/** * Step 7 * Where installation are run (npm, bower) */ export default function () { this.npmInstall( this.options['social-networks'].split(',').map(service => `passport-${service.toLowerCase()}-token`), {save: true} ) };
/** * Step 7 * Where installation are run (npm, bower) */ const PASSPORT_DEPENDENCIES = { local: ['passport-local'], jwt: ['passport-jwt'], facebook: ['passport-facebook-token'], twitter: ['passport-twitter-token'], vkontakte: ['passport-vkontakte-token'], foursquare: ['passport-foursquare-token'], github: ['passport-github-token'], instagram: ['passport-instagram-token'], paypal: ['passport-paypal-token'], reddit: ['passport-reddit-token'], soundcloud: ['passport-soundcloud-token'], windowsLive: ['passport-windows-live-token'], twitch: ['passport-twitch-token'], yandex: ['passport-yandex-token'], amazon: ['passport-amazon-token'], googlePlus: ['passport-google-plus-token'], yahoo: ['passport-yahoo-token'] }; export default function () { let passportDependencies = Object.keys(PASSPORT_DEPENDENCIES).reduce((deps, strategy) => deps.concat(PASSPORT_DEPENDENCIES[strategy]), []); this.npmInstall(passportDependencies, {save: true}); };
Move passport dependencies to hash map
refactor(authentication): Move passport dependencies to hash map Add PASSPORT_DEPENDENCIES object that contains all passport strategies
JavaScript
mit
ghaiklor/generator-sails-rest-api,italoag/generator-sails-rest-api,ghaiklor/generator-sails-rest-api,tnunes/generator-trails,jaumard/generator-trails,italoag/generator-sails-rest-api,konstantinzolotarev/generator-trails
--- +++ @@ -3,9 +3,28 @@ * Where installation are run (npm, bower) */ +const PASSPORT_DEPENDENCIES = { + local: ['passport-local'], + jwt: ['passport-jwt'], + facebook: ['passport-facebook-token'], + twitter: ['passport-twitter-token'], + vkontakte: ['passport-vkontakte-token'], + foursquare: ['passport-foursquare-token'], + github: ['passport-github-token'], + instagram: ['passport-instagram-token'], + paypal: ['passport-paypal-token'], + reddit: ['passport-reddit-token'], + soundcloud: ['passport-soundcloud-token'], + windowsLive: ['passport-windows-live-token'], + twitch: ['passport-twitch-token'], + yandex: ['passport-yandex-token'], + amazon: ['passport-amazon-token'], + googlePlus: ['passport-google-plus-token'], + yahoo: ['passport-yahoo-token'] +}; + export default function () { - this.npmInstall( - this.options['social-networks'].split(',').map(service => `passport-${service.toLowerCase()}-token`), - {save: true} - ) + let passportDependencies = Object.keys(PASSPORT_DEPENDENCIES).reduce((deps, strategy) => deps.concat(PASSPORT_DEPENDENCIES[strategy]), []); + + this.npmInstall(passportDependencies, {save: true}); };
d9097a2a1296a690b942043e63ac4b42f0532229
loading-indicator.ios.js
loading-indicator.ios.js
var indicator = {} indicator.show = function() { var hud = MBProgressHUD.showHUDAddedToAnimated(this._getRootWindow(), true); hud.dimBackground = true; }; indicator.hide = function() { MBProgressHUD.hideHUDForViewAnimated(this._getRootWindow(), true); }; indicator._getRootWindow = function() { return UIApplication.sharedApplication().windows[0]; } module.exports = indicator;
var indicator = {} indicator.show = function() { MBProgressHUD.showHUDAddedToAnimated(this._getRootWindow(), true); }; indicator.hide = function() { MBProgressHUD.hideHUDForViewAnimated(this._getRootWindow(), true); }; indicator._getRootWindow = function() { return UIApplication.sharedApplication().windows[0]; } module.exports = indicator;
Remove dim background, it's a bit stark.
Remove dim background, it's a bit stark.
JavaScript
mit
pocketsmith/nativescript-loading-indicator,pocketsmith/nativescript-loading-indicator
--- +++ @@ -1,8 +1,7 @@ var indicator = {} indicator.show = function() { - var hud = MBProgressHUD.showHUDAddedToAnimated(this._getRootWindow(), true); - hud.dimBackground = true; + MBProgressHUD.showHUDAddedToAnimated(this._getRootWindow(), true); }; indicator.hide = function() {
c4660c920dcf68d502e279dc44a4dd1995f19a22
static/app/directives/dst_top_nav.js
static/app/directives/dst_top_nav.js
angular.module('genome.directive', []) .directive('dstTopNav', function() { return { controller: function($scope, $cookies, $rootScope, $location, SelfFactory) { $scope.user_first_name = $cookies.user_first_name; $scope.expand = false; // $scope.toggleNavList = function (ev) { // if (!(ev.type === 'mouseleave' && $scope.lastEventType === 'click')) { // $scope.expand = !$scope.expand; // } // $scope.lastEventType = ev.type; // }; $scope.onpoolpage = $location.$$path === '/pool' ? true : false; $scope.onselfpage = $location.$$path === '/self' ? true : false; $scope.getRelatives = function () { $scope.onpoolpage = true; $scope.onselfpage = false; $location.path('/pool'); }; $scope.getSelf = function () { $scope.onselfpage = true; $scope.onpoolpage = false; $location.path('/self'); }; }, templateUrl: '../static/app/directives/dst_top_nav.html' }; });
angular.module('genome.directive', []) .directive('dstTopNav', function() { return { controller: function($scope, $cookies, $rootScope, $location, SelfFactory) { $scope.user_first_name = $cookies.user_first_name; $scope.expand = false; $scope.onpoolpage = $location.$$path === '/pool' ? true : false; $scope.onselfpage = $location.$$path === '/self' ? true : false; $scope.getRelatives = function () { $scope.onpoolpage = true; $scope.onselfpage = false; $location.path('/pool'); }; $scope.getSelf = function () { $scope.onselfpage = true; $scope.onpoolpage = false; $location.path('/self'); }; }, templateUrl: '../static/app/directives/dst_top_nav.html' }; });
Remove mouseLeave functionality from top nav
Remove mouseLeave functionality from top nav
JavaScript
mit
ThunderousFigs/Genomes,ThunderousFigs/Genomes,ThunderousFigs/Genomes
--- +++ @@ -6,13 +6,6 @@ controller: function($scope, $cookies, $rootScope, $location, SelfFactory) { $scope.user_first_name = $cookies.user_first_name; $scope.expand = false; - - // $scope.toggleNavList = function (ev) { - // if (!(ev.type === 'mouseleave' && $scope.lastEventType === 'click')) { - // $scope.expand = !$scope.expand; - // } - // $scope.lastEventType = ev.type; - // }; $scope.onpoolpage = $location.$$path === '/pool' ? true : false; $scope.onselfpage = $location.$$path === '/self' ? true : false;
e70bc552af4ea37157a9e2f18cf9ad47eecd3e8c
Gruntfile.js
Gruntfile.js
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'Gruntfile.js', 'lib/*.js', 'test/*.js' ], options: { jshintrc: '.jshintrc' } }, tape: { options: { pretty: true, output: 'console' }, //files: ['test/**/*.js'] files: ['test/test.js'] }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint'] }, doxx: { all: { src: 'lib', target: 'docs', options: { title: 'LineRate Node.js REST API module', template: 'doxx.jade', readme: 'README.md' } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-doxx'); grunt.loadNpmTasks('grunt-tape'); grunt.registerTask('test', ['jshint', 'tape']); grunt.registerTask('default', ['jshint', 'tape', 'doxx']); };
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'Gruntfile.js', 'lib/*.js', 'test/*.js' ], options: { jshintrc: '.jshintrc' } }, tape: { options: { pretty: true, output: 'console' }, //files: ['test/**/*.js'] files: ['test/test.js'] }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint'] }, doxx: { all: { src: 'lib', target: 'docs', options: { title: 'LineRate Node.js REST API module', template: 'doxx.jade', readme: 'README.md' } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-doxx'); grunt.loadNpmTasks('grunt-tape'); grunt.registerTask('test', ['tape']); grunt.registerTask('jshint', ['jshint']); grunt.registerTask('default', ['jshint', 'tape', 'doxx']); };
Split out 'test' from 'jshint' subcommands in grunt
Split out 'test' from 'jshint' subcommands in grunt
JavaScript
mit
b225ccc/linerate_node_rest_api_module,b225ccc/linerate_node_rest_api_module
--- +++ @@ -44,7 +44,8 @@ grunt.loadNpmTasks('grunt-doxx'); grunt.loadNpmTasks('grunt-tape'); - grunt.registerTask('test', ['jshint', 'tape']); + grunt.registerTask('test', ['tape']); + grunt.registerTask('jshint', ['jshint']); grunt.registerTask('default', ['jshint', 'tape', 'doxx']); };
69d3a7503d50ccd000b34fbd7dd64255088507bc
example/migrations/2_deploy_contracts.js
example/migrations/2_deploy_contracts.js
module.exports = function(deployer) { deployer.deploy(ConvertLib); deployer.autolink(MetaCoin); deployer.deploy(MetaCoin); };
module.exports = function(deployer) { deployer.deploy(ConvertLib); deployer.autolink(); deployer.deploy(MetaCoin); };
Make example deploy a bit simpler.
Make example deploy a bit simpler.
JavaScript
mit
DigixGlobal/truffle,prashantpawar/truffle
--- +++ @@ -1,5 +1,5 @@ module.exports = function(deployer) { deployer.deploy(ConvertLib); - deployer.autolink(MetaCoin); + deployer.autolink(); deployer.deploy(MetaCoin); };
bcdd65f8c220249204df1e21b9d8c19fdbd94890
src/rules/property-no-unknown/index.js
src/rules/property-no-unknown/index.js
import { isString, isArray, isBoolean, } from "lodash" import { isStandardSyntaxProperty, isCustomProperty, report, ruleMessages, validateOptions, } from "../../utils" import { all as properties } from "known-css-properties" export const ruleName = "property-no-unknown" export const messages = ruleMessages(ruleName, { rejected: (property) => `Unexpected unknown property "${property}"`, }) const isPropertyIgnored = (prop, ignore) => { if (isArray(ignore)) { return ignore.indexOf(prop) > -1 } if (isString(ignore)) { return prop === ignore } return false } const isPropertyValid = (prop) => { return properties.indexOf(prop) > -1 } const validate = (result, options) => { return function (node) { const prop = node.prop if (!isStandardSyntaxProperty(prop)) { return } if (isCustomProperty(prop)) { return } if (isPropertyIgnored(prop, options.ignoreProperties)) { return } if (isPropertyValid(prop)) { return } report({ message: messages.rejected(node.prop), node, result, ruleName, }) } } export default function (enabled, options) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: enabled, possible: isBoolean, }, { actual: options, possible: { ignoreProperties: [isString], }, optional: true, }) if (!validOptions) { return } if (!enabled) { return } if (!options) { options = {} } root.walkDecls(validate(result, options)) } }
import { isString, isArray, } from "lodash" import { isStandardSyntaxProperty, isCustomProperty, report, ruleMessages, validateOptions, } from "../../utils" import { all as properties } from "known-css-properties" export const ruleName = "property-no-unknown" export const messages = ruleMessages(ruleName, { rejected: (property) => `Unexpected unknown property "${property}"`, }) export default function (actual, options) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual }, { actual: options, possible: { ignoreProperties: [isString], }, optional: true, }) if (!validOptions) { return } root.walkDecls(node => { const { prop } = node if (!isStandardSyntaxProperty(prop)) { return } if (isCustomProperty(prop)) { return } const ignoreProperties = options && options.ignoreProperties || [] if (isArray(ignoreProperties) && ignoreProperties.indexOf(prop) !== -1) { return } if (properties.indexOf(prop) !== -1) { return } report({ message: messages.rejected(node.prop), node, result, ruleName, }) }) } }
Fix rule to match the project standards
Fix rule to match the project standards
JavaScript
mit
stylelint/stylelint,hudochenkov/stylelint,stylelint/stylelint,heatwaveo8/stylelint,hudochenkov/stylelint,gucong3000/stylelint,heatwaveo8/stylelint,heatwaveo8/stylelint,gaidarenko/stylelint,stylelint/stylelint,hudochenkov/stylelint,gucong3000/stylelint,stylelint/stylelint,gaidarenko/stylelint,gaidarenko/stylelint,gucong3000/stylelint
--- +++ @@ -1,7 +1,6 @@ import { isString, isArray, - isBoolean, } from "lodash" import { isStandardSyntaxProperty, @@ -18,46 +17,9 @@ rejected: (property) => `Unexpected unknown property "${property}"`, }) -const isPropertyIgnored = (prop, ignore) => { - if (isArray(ignore)) { - return ignore.indexOf(prop) > -1 - } - - if (isString(ignore)) { - return prop === ignore - } - - return false -} - -const isPropertyValid = (prop) => { - return properties.indexOf(prop) > -1 -} - -const validate = (result, options) => { - return function (node) { - const prop = node.prop - - if (!isStandardSyntaxProperty(prop)) { return } - if (isCustomProperty(prop)) { return } - if (isPropertyIgnored(prop, options.ignoreProperties)) { return } - if (isPropertyValid(prop)) { return } - - report({ - message: messages.rejected(node.prop), - node, - result, - ruleName, - }) - } -} - -export default function (enabled, options) { +export default function (actual, options) { return (root, result) => { - const validOptions = validateOptions(result, ruleName, { - actual: enabled, - possible: isBoolean, - }, { + const validOptions = validateOptions(result, ruleName, { actual }, { actual: options, possible: { ignoreProperties: [isString], @@ -66,10 +28,24 @@ }) if (!validOptions) { return } - if (!enabled) { return } - if (!options) { options = {} } - root.walkDecls(validate(result, options)) + root.walkDecls(node => { + const { prop } = node + + if (!isStandardSyntaxProperty(prop)) { return } + if (isCustomProperty(prop)) { return } + + const ignoreProperties = options && options.ignoreProperties || [] + if (isArray(ignoreProperties) && ignoreProperties.indexOf(prop) !== -1) { return } + + if (properties.indexOf(prop) !== -1) { return } + + report({ + message: messages.rejected(node.prop), + node, + result, + ruleName, + }) + }) } } -
4f030e8ae4aadf0dbfc155cb763d2d947d70252d
app/containers/AssessmentEntry/AssessmentEntryColHeader.js
app/containers/AssessmentEntry/AssessmentEntryColHeader.js
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; const AssessmentEntryColHeaderView = ({ questions }) => { const values = Object.keys(questions); return ( <tr className="bg-info"> <td>UID</td> <td colSpan="2">Boundary Name</td> <td>Name</td> <td>Date of Visit</td> {values.map((id, i) => { return ( <td key={id} title={questions[id].question_text}> {i + 1} </td> ); })} <td>Save</td> </tr> ); }; AssessmentEntryColHeaderView.propTypes = { questions: PropTypes.object, }; const mapStateToProps = (state) => { return { questions: state.questions.questions, }; }; const AssessmentEntryColHeader = connect(mapStateToProps)(AssessmentEntryColHeaderView); export { AssessmentEntryColHeader };
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; const AssessmentEntryColHeaderView = ({ questions }) => { const values = Object.keys(questions); return ( <tr className="bg-info"> <td>ID</td> <td colSpan="2">Boundary Name</td> <td>Name</td> <td>Date of Visit</td> {values.map((id, i) => { return ( <td key={id} title={questions[id].question_text}> {i + 1} </td> ); })} <td>Save</td> </tr> ); }; AssessmentEntryColHeaderView.propTypes = { questions: PropTypes.object, }; const mapStateToProps = (state) => { return { questions: state.questions.questions, }; }; const AssessmentEntryColHeader = connect(mapStateToProps)(AssessmentEntryColHeaderView); export { AssessmentEntryColHeader };
Change the label UID to ID.
fix: Change the label UID to ID.
JavaScript
isc
klpdotorg/tada-frontend,klpdotorg/tada-frontend,klpdotorg/tada-frontend
--- +++ @@ -6,7 +6,7 @@ const values = Object.keys(questions); return ( <tr className="bg-info"> - <td>UID</td> + <td>ID</td> <td colSpan="2">Boundary Name</td> <td>Name</td> <td>Date of Visit</td>
92401a1125db1df5b48fb2fbaa80cc8719b0e047
client/components/forms/form-control.js
client/components/forms/form-control.js
import React, { Component, PropTypes } from 'react' import classnames from 'classnames' import { ControlButtons } from './' class FormControl extends Component { render () { const { componentClass: Component, className, style, submitted, ...props } = this.props const { $formRedux: { formInline, submitting, dirty }, $formGroup: { controlId, ...field } } = this.context const fieldProps = Object.assign({}, field) if (Component === 'input') { delete fieldProps.layout delete fieldProps.error delete fieldProps.touched delete fieldProps.valid } return ( <div> <Component {...props} {...fieldProps} id={controlId} className={classnames( 'form-control-input block lightestgray', Component, formInline ? 'inline-block' : '', className )} style={style} /> { formInline && <ControlButtons {...{ submitted, submitting, dirty, showCancel: false, formInline }} /> } </div> ) } } FormControl.contextTypes = { $formRedux: PropTypes.shape({ formInline: PropTypes.bool, submitting: PropTypes.bool, dirty: PropTypes.bool }), $formGroup: PropTypes.shape({ controlId: PropTypes.string }) } FormControl.propTypes = { submitted: PropTypes.bool.isRequired, componentClass: PropTypes.string.isRequired, style: PropTypes.object } FormControl.defaultProps = { componentClass: 'input', submitted: false } export default FormControl
import React, { Component, PropTypes } from 'react' import classnames from 'classnames' import { ControlButtons } from './' class FormControl extends Component { render () { const { componentClass: Component, className, style, submitted, ...props } = this.props const { $formRedux: { formInline, submitting, dirty }, $formGroup: { controlId, ...field } } = this.context const fieldProps = Object.assign({}, field) if (Component === 'input' || Component === 'textarea') { delete fieldProps.layout delete fieldProps.error delete fieldProps.touched delete fieldProps.valid } return ( <div> <Component {...props} {...fieldProps} id={controlId} className={classnames( 'form-control-input block lightestgray', Component, formInline ? 'inline-block' : '', className )} style={style} /> { formInline && <ControlButtons {...{ submitted, submitting, dirty, showCancel: false, formInline }} /> } </div> ) } } FormControl.contextTypes = { $formRedux: PropTypes.shape({ formInline: PropTypes.bool, submitting: PropTypes.bool, dirty: PropTypes.bool }), $formGroup: PropTypes.shape({ controlId: PropTypes.string }) } FormControl.propTypes = { submitted: PropTypes.bool.isRequired, componentClass: PropTypes.string.isRequired, style: PropTypes.object } FormControl.defaultProps = { componentClass: 'input', submitted: false } export default FormControl
Fix warning invalid props for textarea
Fix warning invalid props for textarea
JavaScript
agpl-3.0
nossas/bonde-client,nossas/bonde-client,nossas/bonde-client
--- +++ @@ -12,7 +12,7 @@ } = this.context const fieldProps = Object.assign({}, field) - if (Component === 'input') { + if (Component === 'input' || Component === 'textarea') { delete fieldProps.layout delete fieldProps.error delete fieldProps.touched
09ee3b4d8098e6e69d34e453cb48487129d591ff
gom/app/components/formUtil/formUtil.js
gom/app/components/formUtil/formUtil.js
'use strict'; function getDescProp(obj, prop) { var parts = prop.split('.'); while(parts.length) obj = obj[parts.shift()]; return obj; } angular.module('gomApp.formUtil', [ 'ngMaterial' ]) .directive('gomAsyncSave', [ '$mdToast', function($mdToast) { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attr, ngModelCtrl) { var targetId = attr.gomAsyncSave; element.on('blur', function(event) { if(ngModelCtrl.$pristine) return; // Hasn't changed ngModelCtrl.$validate(); // Run validator before check we're valid if(ngModelCtrl.$invalid) return; // Don't commit, is wrong getDescProp(scope,targetId).$save(function() { $mdToast.show($mdToast.simple() .content('Saved ' + ngModelCtrl.$name) .hideDelay(300) ); }); ngModelCtrl.$setPristine(); }); } }; }]);
'use strict'; function getDescProp(obj, prop) { var parts = prop.split('.'); while(parts.length) obj = obj[parts.shift()]; return obj; } angular.module('gomApp.formUtil', [ 'ngMaterial' ]) .directive('gomAsyncSave', [ '$mdToast', function($mdToast) { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attr, ngModelCtrl) { var targetId = attr.gomAsyncSave; element.on('blur', function(event) { if(ngModelCtrl.$pristine) return; // Hasn't changed ngModelCtrl.$validate(); // Run validator before check we're valid if(ngModelCtrl.$invalid) return; // Don't commit, is wrong var label = (attr.gomAsyncSaveLabel || ngModelCtrl.$name); getDescProp(scope,targetId).$save(function() { $mdToast.show($mdToast.simple() .content('Saved ' + label) .hideDelay(500) ); }); ngModelCtrl.$setPristine(); }); } }; }]);
Tweak time to display, allow for explict labelling.
Tweak time to display, allow for explict labelling.
JavaScript
bsd-2-clause
jhogg41/gm-o-matic,jhogg41/gm-o-matic,jhogg41/gm-o-matic
--- +++ @@ -22,10 +22,11 @@ if(ngModelCtrl.$pristine) return; // Hasn't changed ngModelCtrl.$validate(); // Run validator before check we're valid if(ngModelCtrl.$invalid) return; // Don't commit, is wrong + var label = (attr.gomAsyncSaveLabel || ngModelCtrl.$name); getDescProp(scope,targetId).$save(function() { $mdToast.show($mdToast.simple() - .content('Saved ' + ngModelCtrl.$name) - .hideDelay(300) + .content('Saved ' + label) + .hideDelay(500) ); }); ngModelCtrl.$setPristine();
d04fe29f5f079300a9f2a5c3cc35da47ad5ff097
app/renderer/containers/app.js
app/renderer/containers/app.js
const React = require('react') const { connect } = require('react-redux') const RequestsContainer = require('./requests') const SidebarContainer = require('./sidebar') const AppBar = require('material-ui/AppBar').default const App = ({ requests }) => <div className='app-container'> <SidebarContainer /> <main className='main-container'> <AppBar title='Proxy' /> <RequestsContainer requests={requests} /> </main> </div> App.propTypes = { requests: React.PropTypes.array.isRequired } const mapStateToProps = ({ requests }) => ({ requests }) module.exports = connect(mapStateToProps)(App)
const React = require('react') const { connect } = require('react-redux') const RequestsContainer = require('./requests') const SidebarContainer = require('./sidebar') const AppBar = require('material-ui/AppBar').default const titleStyle = { textAlign: 'center', height: '40px', lineHeight: '40px' } /* eslint-disable react/jsx-indent */ const App = ({ requests }) => <div className='app-container'> <SidebarContainer /> <main className='main-container'> <AppBar showMenuIconButton={false} titleStyle={titleStyle} title='Requests' /> <RequestsContainer requests={requests} /> </main> </div> App.propTypes = { requests: React.PropTypes.array.isRequired } const mapStateToProps = ({ requests }) => ({ requests }) module.exports = connect(mapStateToProps)(App) /* eslint-enable react/jsx-indent */
Change title text and center it.
Change title text and center it.
JavaScript
isc
niklasi/halland-proxy,niklasi/halland-proxy
--- +++ @@ -4,10 +4,16 @@ const SidebarContainer = require('./sidebar') const AppBar = require('material-ui/AppBar').default +const titleStyle = { + textAlign: 'center', + height: '40px', + lineHeight: '40px' +} +/* eslint-disable react/jsx-indent */ const App = ({ requests }) => <div className='app-container'> <SidebarContainer /> <main className='main-container'> - <AppBar title='Proxy' /> + <AppBar showMenuIconButton={false} titleStyle={titleStyle} title='Requests' /> <RequestsContainer requests={requests} /> </main> </div> @@ -19,3 +25,4 @@ const mapStateToProps = ({ requests }) => ({ requests }) module.exports = connect(mapStateToProps)(App) +/* eslint-enable react/jsx-indent */
ec242ddabc3867627ebb3b652e1f6a58a7732783
app/templates/tasks/scripts.js
app/templates/tasks/scripts.js
import gulp from 'gulp'; import gulpif from 'gulp-if'; import named from 'vinyl-named'; import webpack from 'webpack'; import gulpWebpack from 'webpack-stream'; import plumber from 'gulp-plumber'; import livereload from 'gulp-livereload'; import args from './lib/args'; gulp.task('scripts', (cb) => { return gulp.src('app/scripts/*.js') .pipe(plumber()) .pipe(named()) .pipe(gulpWebpack({ devtool: args.sourcemaps ? 'source-map': null, watch: args.watch, plugins: [ new webpack.DefinePlugin({ '__ENV__': JSON.stringify(args.production ? 'production' : 'development'), '__VENDOR__': JSON.stringify(args.vendor) }), ].concat(args.production ? [ new webpack.optimize.UglifyJsPlugin() ] : []), module: { preLoaders: [{ test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ }], loaders: [{ test: /\.js$/, loader: 'babel' }] }, eslint: { configFile: '.eslintrc' } })) .pipe(gulp.dest(`dist/${args.vendor}/scripts`)) .pipe(gulpif(args.watch, livereload())); });
import gulp from 'gulp'; import gulpif from 'gulp-if'; import named from 'vinyl-named'; import webpack from 'webpack'; import gulpWebpack from 'webpack-stream'; import plumber from 'gulp-plumber'; import livereload from 'gulp-livereload'; import args from './lib/args'; const ENV = args.production ? 'production' : 'development'; gulp.task('scripts', (cb) => { return gulp.src('app/scripts/*.js') .pipe(plumber()) .pipe(named()) .pipe(gulpWebpack({ devtool: args.sourcemaps ? 'source-map': null, watch: args.watch, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify(ENV) }, '__ENV__': JSON.stringify(ENV), '__VENDOR__': JSON.stringify(args.vendor) }), ].concat(args.production ? [ new webpack.optimize.UglifyJsPlugin() ] : []), module: { preLoaders: [{ test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ }], loaders: [{ test: /\.js$/, loader: 'babel' }] }, eslint: { configFile: '.eslintrc' } })) .pipe(gulp.dest(`dist/${args.vendor}/scripts`)) .pipe(gulpif(args.watch, livereload())); });
Add node env to script
Add node env to script - helps with optimising production code like react
JavaScript
mit
HaNdTriX/generator-chrome-extension-kickstart,HaNdTriX/generator-chrome-extension-kickstart
--- +++ @@ -6,6 +6,8 @@ import plumber from 'gulp-plumber'; import livereload from 'gulp-livereload'; import args from './lib/args'; + +const ENV = args.production ? 'production' : 'development'; gulp.task('scripts', (cb) => { return gulp.src('app/scripts/*.js') @@ -16,7 +18,10 @@ watch: args.watch, plugins: [ new webpack.DefinePlugin({ - '__ENV__': JSON.stringify(args.production ? 'production' : 'development'), + 'process.env': { + 'NODE_ENV': JSON.stringify(ENV) + }, + '__ENV__': JSON.stringify(ENV), '__VENDOR__': JSON.stringify(args.vendor) }), ].concat(args.production ? [
57266bd4bfb9a61f7efc106c4d2df47b432f9a7d
client/ember-cli-build.js
client/ember-cli-build.js
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var Funnel = require('broccoli-funnel'); module.exports = function(defaults) { var app = new EmberApp(defaults, { // Any other options }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. // app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.js'); // Included as separate file in index.html // app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.css'); // Included as separate file in index.html var extraAssets = new Funnel(app.bowerDirectory + '/semantic-ui', { srcDir: '/dist', include: ['**/*.*'], destDir: '/assets/semantic-ui' }); return app.toTree(extraAssets); };
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var Funnel = require('broccoli-funnel'); module.exports = function(defaults) { var app = new EmberApp(defaults, { // Any other options }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. // app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.js'); // Included as separate file in index.html // app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.css'); // Included as separate file in index.html var semanticUi = new Funnel(app.bowerDirectory + '/semantic-ui', { srcDir: '/dist', include: ['**/*.*'], destDir: '/assets/semantic-ui' }); var leaflet = new Funnel(app.bowerDirectory + '/leaflet', { srcDir: '/dist', include: ['**/*.*'], destDir: '/assets/leaflet' }); return app.toTree([semanticUi, leaflet]); };
Include leaflet lib + assets
Include leaflet lib + assets
JavaScript
mit
Turistforeningen/Hytteadmin,Turistforeningen/Hytteadmin
--- +++ @@ -25,12 +25,18 @@ // app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.js'); // Included as separate file in index.html // app.import(app.bowerDirectory + '/semantic-ui/dist/semantic.css'); // Included as separate file in index.html - var extraAssets = new Funnel(app.bowerDirectory + '/semantic-ui', { + var semanticUi = new Funnel(app.bowerDirectory + '/semantic-ui', { srcDir: '/dist', include: ['**/*.*'], destDir: '/assets/semantic-ui' }); - return app.toTree(extraAssets); + var leaflet = new Funnel(app.bowerDirectory + '/leaflet', { + srcDir: '/dist', + include: ['**/*.*'], + destDir: '/assets/leaflet' + }); + + return app.toTree([semanticUi, leaflet]); };
3244fcd522bd87e892732cbb67b97a26ae49d851
Twitter_FollowFly.user.js
Twitter_FollowFly.user.js
// ==UserScript== // @name Twitter Best // @namespace localhost // @description Get best tweets from profile // @include /^https://twitter\.com/[a-zA-Z0-9_]+$/ // @version 1 // @grant none // ==/UserScript== var l = document.createElement("a"); l.appendChild(document.createTextNode("View on FollowFly")); var username = window.location.pathname; l.href = "http://followfly.co/t" + username; document.querySelector(".ProfileHeaderCard-screenname").appendChild(l);
// ==UserScript== // @name Twitter - Add link to FollowFly from profile // @namespace localhost // @description Get best tweets from profile using FollowFly // @include /^https://twitter\.com/[a-zA-Z0-9_]+/?$/ // @version 1 // @grant none // ==/UserScript== var l = document.createElement("a"); l.appendChild(document.createTextNode("View on FollowFly")); var username = window.location.pathname; username = username.replace(/\/$/, ''); l.href = "http://followfly.co/t" + username; document.querySelector(".ProfileHeaderCard-screenname").appendChild(l);
Add support for URLs with trailing slash
TwitterFollowFly: Add support for URLs with trailing slash
JavaScript
cc0-1.0
Tailszefox/Userscripts
--- +++ @@ -1,8 +1,8 @@ // ==UserScript== -// @name Twitter Best +// @name Twitter - Add link to FollowFly from profile // @namespace localhost -// @description Get best tweets from profile -// @include /^https://twitter\.com/[a-zA-Z0-9_]+$/ +// @description Get best tweets from profile using FollowFly +// @include /^https://twitter\.com/[a-zA-Z0-9_]+/?$/ // @version 1 // @grant none // ==/UserScript== @@ -11,6 +11,7 @@ l.appendChild(document.createTextNode("View on FollowFly")); var username = window.location.pathname; +username = username.replace(/\/$/, ''); l.href = "http://followfly.co/t" + username; document.querySelector(".ProfileHeaderCard-screenname").appendChild(l);
c408f8fc7edef5e10b83b010c06d69df80c20442
tests/unit/services/multi-store-test.js
tests/unit/services/multi-store-test.js
import { moduleFor, test } from 'ember-qunit'; moduleFor('service:multi-store', 'Unit | Service | multi store', {}); test('it exists', function(assert) { let service = this.subject(); assert.ok(service); }); test('it starts empty', function(assert) { let service = this.subject(); assert.deepEqual([], service.get('storeNames')); assert.notOk(service.getStore('foo')); });
import { moduleFor, test } from 'ember-qunit'; moduleFor('service:multi-store', 'Unit | Service | multi store', {}); test('it exists', function(assert) { let service = this.subject(); assert.ok(service); }); test('it starts empty', function(assert) { let service = this.subject(); assert.deepEqual([], service.get('storeNames')); assert.notOk(service.isStoreRegistered('foo')); assert.notOk(service.getStore('foo')); assert.notOk(service.unregisterStore('foo')); }); test('it can register new stores', function(assert) { let service = this.subject(); assert.ok(service.registerStore('foo')); assert.deepEqual(['foo'], service.get('storeNames')); assert.ok(service.isStoreRegistered('foo')); assert.ok(service.getStore('foo')); }); test('it can unregister stores', function(assert) { let service = this.subject(); service.registerStore('foo'); assert.ok(service.unregisterStore('foo')); assert.deepEqual([], service.get('storeNames')); assert.notOk(service.isStoreRegistered('foo')); assert.notOk(service.getStore('foo')); });
Add in more unit tests.
Add in more unit tests.
JavaScript
mit
jonesetc/ember-cli-multi-store-service,jonesetc/ember-cli-multi-store-service
--- +++ @@ -10,5 +10,25 @@ test('it starts empty', function(assert) { let service = this.subject(); assert.deepEqual([], service.get('storeNames')); + assert.notOk(service.isStoreRegistered('foo')); + assert.notOk(service.getStore('foo')); + assert.notOk(service.unregisterStore('foo')); +}); + +test('it can register new stores', function(assert) { + let service = this.subject(); + assert.ok(service.registerStore('foo')); + assert.deepEqual(['foo'], service.get('storeNames')); + assert.ok(service.isStoreRegistered('foo')); + assert.ok(service.getStore('foo')); +}); + +test('it can unregister stores', function(assert) { + let service = this.subject(); + service.registerStore('foo'); + + assert.ok(service.unregisterStore('foo')); + assert.deepEqual([], service.get('storeNames')); + assert.notOk(service.isStoreRegistered('foo')); assert.notOk(service.getStore('foo')); });
cb4c27d7b90b1e525db8eef3b5f9b72a29efd6c1
client/js/controllers/index-controller.js
client/js/controllers/index-controller.js
"use strict"; var IndexController = function($scope, analytics, navigation, progressbar, search) { $scope.searchQuery = ""; $scope.search = function() { if ($scope.searchQuery.trim().length === 0) { navigation.toEntry("the-narrows"); } else { search.search($scope.searchQuery); } }; $scope.htmlReady(); }; IndexController.$inject = ["$scope", "analytics", "navigation", "progressbar", "search"];
"use strict"; var IndexController = function($scope, analytics, navigation, progressbar, search) { $scope.searchQuery = ""; progressbar.start(); $scope.search = function() { if ($scope.searchQuery.trim().length === 0) { navigation.toEntry("the-narrows"); } else { search.search($scope.searchQuery); } }; progressbar.complete(); $scope.htmlReady(); }; IndexController.$inject = ["$scope", "analytics", "navigation", "progressbar", "search"];
Add progress bar to / for consistency.
Add progress bar to / for consistency.
JavaScript
mit
zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io
--- +++ @@ -2,6 +2,7 @@ var IndexController = function($scope, analytics, navigation, progressbar, search) { $scope.searchQuery = ""; + progressbar.start(); $scope.search = function() { if ($scope.searchQuery.trim().length === 0) { navigation.toEntry("the-narrows"); @@ -10,6 +11,7 @@ } }; + progressbar.complete(); $scope.htmlReady(); };
5269da98660c34169b998fe1719eb86c7958cda1
fs/md5File.js
fs/md5File.js
"use strict"; var fs = require('fs'), crypto = require('crypto'); module.exports = function (file_path, callback){ var shasum = crypto.createHash('md5'); var s = fs.ReadStream(file_path); s.on('data', shasum.update.bind(shasum)); s.on('end', function() { callback(null, shasum.digest('hex')); }); }
"use strict"; const fs = require('fs'); const crypto = require('crypto'); module.exports = function md5File (file_path, cb) { if (typeof cb !== 'function') throw new TypeError('Argument cb must be a function') var output = crypto.createHash('md5') var input = fs.createReadStream(file_path) input.on('error', cb) output.once('readable', function () { cb(null, output.read().toString('hex')) }) input.pipe(output) }
Use crypto stream (prevent memory exhaustion on raspbian)
Use crypto stream (prevent memory exhaustion on raspbian)
JavaScript
mit
131/nyks
--- +++ @@ -1,14 +1,21 @@ "use strict"; -var fs = require('fs'), - crypto = require('crypto'); +const fs = require('fs'); +const crypto = require('crypto'); +module.exports = function md5File (file_path, cb) { + if (typeof cb !== 'function') + throw new TypeError('Argument cb must be a function') -module.exports = function (file_path, callback){ - var shasum = crypto.createHash('md5'); - var s = fs.ReadStream(file_path); - s.on('data', shasum.update.bind(shasum)); - s.on('end', function() { - callback(null, shasum.digest('hex')); - }); + var output = crypto.createHash('md5') + var input = fs.createReadStream(file_path) + + input.on('error', cb) + + output.once('readable', function () { + cb(null, output.read().toString('hex')) + }) + + input.pipe(output) } +
9947f637ca0b0b169d61ff9246bdc1e9d608ebc4
hxbot/Poll.js
hxbot/Poll.js
var PollModule = function () { }; PollModule.prototype.Message = function(message) { if(message.deletable) { message.delete(); } var keyword = "poll"; var pollIndex = message.content.indexOf(keyword); var questionmarkIndex = message.content.lastIndexOf("?"); var question = message.content.substring(pollIndex + keyword.length,questionmarkIndex+1).trim(); var options = message.content.substring(questionmarkIndex+1).trim().split(' '); if(question.length > 0 && options.length > 0) { message.channel.send(question).then(function (poll) { for (var i = 0; i < options.length; i++) { poll.react(options[i]); } }); } } module.exports = PollModule;
var PollModule = function () { }; PollModule.prototype.Message = function(message) { if(message.deletable) { message.delete(); } var keyword = "poll"; var pollIndex = message.content.indexOf(keyword); var questionmarkIndex = message.content.lastIndexOf("?"); var question = message.content.substring(pollIndex + keyword.length,questionmarkIndex+1).trim(); var options = message.content.substring(questionmarkIndex+1).trim().split(' ').map(s => s.replace(/[<>]/g, '')); if(question.length > 0 && options.length > 0) { message.channel.send(question).then(function (poll) { for (var i = 0; i < options.length; i++) { poll.react(options[i]); } }); } } module.exports = PollModule;
Fix custom emote parsing in polls
Fix custom emote parsing in polls
JavaScript
mit
HxxxxxS/DiscordBot,HxxxxxS/DiscordBot
--- +++ @@ -12,7 +12,7 @@ var questionmarkIndex = message.content.lastIndexOf("?"); var question = message.content.substring(pollIndex + keyword.length,questionmarkIndex+1).trim(); - var options = message.content.substring(questionmarkIndex+1).trim().split(' '); + var options = message.content.substring(questionmarkIndex+1).trim().split(' ').map(s => s.replace(/[<>]/g, '')); if(question.length > 0 && options.length > 0) {
5d4c7fbb46fa60cb02510eb3cab1238565c87b1d
src/ko.sortable-table.js
src/ko.sortable-table.js
ko.bindingHandlers.sortBy = { init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var asc = true; element.style.cursor = 'pointer'; element.onclick = function(){ var value = valueAccessor(); var data = value.array; var sortBy = value.sortBy; if((ko.isObservable(data) && !Array.isArray(data()))) throw "Incorrect argument for array. Array must be an observableArray"; asc = !asc; switch(true) { case typeof sortBy === "function": data.sort(sortBy); break; case Array.isArray(sortBy): var length = sortBy.length; data.sort(function(a,b){ var index = -1; while(++index < length) { var field = sortBy[index]; if(a[field] == b[field]) continue; return a[field] > b[field] ? 1 : -1; } }) break; case typeof sortBy === "string": data.sort(function(a,b){ return a[sortBy] > b[sortBy] ? 1 : a[sortBy] < b[sortBy] ? -1 : 0; }) break; default: throw "Incorrect argument for sortBy"; break; } }; } };
ko.bindingHandlers.sortBy = { init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var asc = true; element.style.cursor = 'pointer'; element.onclick = function(){ var value = valueAccessor(); var data = value.array; var sortBy = value.sortBy; if((ko.isObservable(data) && !Array.isArray(data()))) throw "Incorrect argument for array. Array must be an observableArray"; asc = !asc; switch(true) { case typeof sortBy === "function": data.sort(sortBy); break; case Array.isArray(sortBy): var length = sortBy.length; data.sort(function(a,b){ var index = -1; while(++index < length) { var field = sortBy[index]; if(a[field] == b[field]) continue; return a[field] > b[field] ? 1 : -1; } }); break; case typeof sortBy === "string": data.sort(function(a,b){ return a[sortBy] > b[sortBy] ? 1 : a[sortBy] < b[sortBy] ? -1 : 0; }); break; default: throw "Incorrect argument for sortBy"; } if(!asc) data.reverse(); }; } };
Fix for reverse sorting. Styling fixes
Fix for reverse sorting. Styling fixes
JavaScript
mit
RyanFrench/ko.sortable-table.js
--- +++ @@ -26,17 +26,18 @@ if(a[field] == b[field]) continue; return a[field] > b[field] ? 1 : -1; } - }) + }); break; case typeof sortBy === "string": data.sort(function(a,b){ return a[sortBy] > b[sortBy] ? 1 : a[sortBy] < b[sortBy] ? -1 : 0; - }) + }); break; default: throw "Incorrect argument for sortBy"; - break; } + + if(!asc) data.reverse(); }; } };
e050f4e1b2138de68ee1eaf6b71ea8285b2e1546
src/ms/symbol/isvalid.js
src/ms/symbol/isvalid.js
export default function isValid(extended) { var drawInstructions = JSON.stringify(this.drawInstructions).indexOf("null") == -1; if (extended) { return { drawInstructions: drawInstructions, icon: this.validIcon, mobility: this.metadata.mobility != undefined }; } else { return ( drawInstructions && this.validIcon && this.metadata.mobility != undefined ); } }
export default function isValid(extended) { var drawInstructions = JSON.stringify(this.drawInstructions).indexOf("null") == -1; if (extended) { return { affiliation: this.metadata.affiliation, dimension: this.metadata.dimension, dimensionUnknown: this.metadata.dimensionUnknown, drawInstructions: drawInstructions, icon: this.validIcon, mobility: this.metadata.mobility != undefined }; } else { return ( !( this.metadata.affiliation == "undefined" || (this.metadata.dimension == "undefined" && !this.metadata.controlMeasure) ) && drawInstructions && this.validIcon && this.metadata.mobility != undefined ); } }
Add check for affiliation and dimension to validation control
Add check for affiliation and dimension to validation control #203
JavaScript
mit
spatialillusions/milsymbol
--- +++ @@ -4,13 +4,23 @@ if (extended) { return { + affiliation: this.metadata.affiliation, + dimension: this.metadata.dimension, + dimensionUnknown: this.metadata.dimensionUnknown, drawInstructions: drawInstructions, icon: this.validIcon, mobility: this.metadata.mobility != undefined }; } else { return ( - drawInstructions && this.validIcon && this.metadata.mobility != undefined + !( + this.metadata.affiliation == "undefined" || + (this.metadata.dimension == "undefined" && + !this.metadata.controlMeasure) + ) && + drawInstructions && + this.validIcon && + this.metadata.mobility != undefined ); } }
af9244dadf0a21b55edca2634e114ebf79f10038
src/vdom.js
src/vdom.js
import vdom from 'skatejs-dom-diff/src/vdom/element'; export default vdom;
import vdom from 'skatejs-dom-diff/lib/vdom/element'; export default vdom;
Use lib instead of src for skatejs dom diff.
Use lib instead of src for skatejs dom diff.
JavaScript
mit
skatejs/kickflip,skatejs/kickflip
--- +++ @@ -1,2 +1,2 @@ -import vdom from 'skatejs-dom-diff/src/vdom/element'; +import vdom from 'skatejs-dom-diff/lib/vdom/element'; export default vdom;
a7b2005e731f9b82782a7c1e5a10958b974842db
scripts/release.js
scripts/release.js
var vow = require('vow'), vowNode = require('vow-node'), childProcess = require('child_process'), fs = require('fs'), exec = vowNode.promisify(childProcess.exec), readFile = vowNode.promisify(fs.readFile), writeFile = vowNode.promisify(fs.writeFile); version = process.argv.slice(2)[0] || 'patch'; exec('git pull') .then(() => exec('npm i')) .then(() => exec('npm run build')) .then(() => exec(`npm version ${version}`)) .then(() => vow.all([ readFile('package.json', 'utf8'), readFile(__dirname + '/distHeaderTmpl.txt', 'utf8'), readFile('dist/vidom.js'), readFile('dist/vidom.min.js') ])) .spread((packageContent, distHeaderTmpl, distContent, distMinContent) => { version = JSON.parse(packageContent).version; var distHeader = distHeaderTmpl.replace('${VERSION}', version); return vow.all([ writeFile('dist/vidom.js', distHeader + distContent), writeFile('dist/vidom.min.js', distHeader + distMinContent) ]); }) .then(() => exec('git push --follow-tags')) .then(() => exec('npm publish' + (version.includes('rc')? ' --tag next' : ''))) .then(() => { console.log(`version ${version} has just been released`); }) .done();
var vow = require('vow'), vowNode = require('vow-node'), childProcess = require('child_process'), fs = require('fs'), exec = vowNode.promisify(childProcess.exec), readFile = vowNode.promisify(fs.readFile), writeFile = vowNode.promisify(fs.writeFile); version = process.argv.slice(2)[0] || 'patch'; exec('git pull') .then(() => exec('npm ci')) .then(() => exec('npm run build')) .then(() => exec(`npm version ${version}`)) .then(() => vow.all([ readFile('package.json', 'utf8'), readFile(__dirname + '/distHeaderTmpl.txt', 'utf8'), readFile('dist/vidom.js'), readFile('dist/vidom.min.js') ])) .spread((packageContent, distHeaderTmpl, distContent, distMinContent) => { version = JSON.parse(packageContent).version; var distHeader = distHeaderTmpl.replace('${VERSION}', version); return vow.all([ writeFile('dist/vidom.js', distHeader + distContent), writeFile('dist/vidom.min.js', distHeader + distMinContent) ]); }) .then(() => exec('git push --follow-tags')) .then(() => exec('npm publish' + (version.includes('rc')? ' --tag next' : ''))) .then(() => { console.log(`version ${version} has just been released`); }) .done();
Use "npm ci" instead of "npm i"
Use "npm ci" instead of "npm i"
JavaScript
mit
dfilatov/vidom,dfilatov/vidom,dfilatov/vidom
--- +++ @@ -8,7 +8,7 @@ version = process.argv.slice(2)[0] || 'patch'; exec('git pull') - .then(() => exec('npm i')) + .then(() => exec('npm ci')) .then(() => exec('npm run build')) .then(() => exec(`npm version ${version}`)) .then(() => vow.all([
12730d88ead306ea569dd2152c34a9823883f5a5
app/assets/javascripts/express_admin/utility.js
app/assets/javascripts/express_admin/utility.js
$(function() { // toggle on/off switch $(document).on('click', '[data-toggle]', function() { targetHide = $(this).data('toggle-hide') targetShow = $(this).data('toggle-show') $('[data-toggle-name="' + targetHide + '"]').addClass('hide') $('[data-toggle-name="' + targetShow + '"]').removeClass('hide') }); // AJAX request utility AJAXRequest = function(url, method, data, success, error) { $.ajax({ url : url, type : method, data : data, dataType : 'JSON', cache : false, success : function(json) { success(json) }, error : function() { error() } }); } });
$(function() { // toggle on/off switch $(document).on('click', '[data-toggle]', function() { targetHide = $(this).data('toggle-hide') targetShow = $(this).data('toggle-show') $('[data-toggle-name="' + targetHide + '"]').addClass('hide') $('[data-toggle-name="' + targetShow + '"]').removeClass('hide') .find('input:text, textarea').first().focus() }); // AJAX request utility AJAXRequest = function(url, method, data, success, error) { $.ajax({ url : url, type : method, data : data, dataType : 'JSON', cache : false, success : function(json) { success(json) }, error : function() { error() } }); } });
Add autofocus on the first input text or textarea
Add autofocus on the first input text or textarea
JavaScript
mit
aelogica/express_admin,aelogica/express_admin,aelogica/express_admin,aelogica/express_admin
--- +++ @@ -6,6 +6,7 @@ targetShow = $(this).data('toggle-show') $('[data-toggle-name="' + targetHide + '"]').addClass('hide') $('[data-toggle-name="' + targetShow + '"]').removeClass('hide') + .find('input:text, textarea').first().focus() }); // AJAX request utility
78ef99ad5ac530063ec6de7416c04e1106b8f913
api/index.js
api/index.js
var userApi = require('./user'); var fableApi = require('./fable'); var mongoose = require('mongoose'); var credentials = require('./credentials'); module.exports = function(app){ const route = '/api'; // Connect to MongoDB console.log('Connecting to MongoLab as ' + credentials.username + '...'); var dbUrl = 'mongodb://'+credentials.username+':'+credentials.password+'@ds013918.mlab.com:13918/aesop-db' mongoose.connect(dbUrl); console.log('...connected!'); // Call API modules userApi(app); fableApi(app); app.get(route, function(req, res) { res.status(200).send('api data'); }) }
var userApi = require('./user'); var fableApi = require('./fable'); var mongoose = require('mongoose'); var credentials = require('./credentials'); module.exports = function(app){ const route = '/api'; // Connect to MongoDB console.log('Connecting to MongoLab as ' + credentials.username + '...'); var dbUrl = 'mongodb://' + (process.env.MONGO_USER || credentials.username) + ':' + (process.env.MONGO_PWD || credentials.password) + '@ds013918.mlab.com:13918/aesop-db' mongoose.connect(dbUrl); console.log('...connected!'); // Call API modules userApi(app); fableApi(app); app.get(route, function(req, res) { res.status(200).send('api data'); }) }
Add env variables for heroku deployment
Add env variables for heroku deployment
JavaScript
isc
RyanNHG/Aesop,RyanNHG/Aesop
--- +++ @@ -9,7 +9,7 @@ // Connect to MongoDB console.log('Connecting to MongoLab as ' + credentials.username + '...'); - var dbUrl = 'mongodb://'+credentials.username+':'+credentials.password+'@ds013918.mlab.com:13918/aesop-db' + var dbUrl = 'mongodb://' + (process.env.MONGO_USER || credentials.username) + ':' + (process.env.MONGO_PWD || credentials.password) + '@ds013918.mlab.com:13918/aesop-db' mongoose.connect(dbUrl); console.log('...connected!');
7aabb7730019229807dd350c290f9418a11a2d58
app/index.js
app/index.js
import 'babel-polyfill'; import React from 'react'; import moment from 'moment'; import { render } from 'react-dom'; import { hashHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import { syncHistoryWithStore } from 'react-router-redux'; import configureStore from 'app/utils/configureStore'; import Root from './Root'; moment.locale('nb-NO'); global.log = function log(self = this) { console.log(self); return this; }; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); const rootElement = document.getElementById('root'); render( <AppContainer> <Root {...{ store, history }} /> </AppContainer>, rootElement ); if (module.hot) { module.hot.accept('./Root', () => { render( <AppContainer> <Root {...{ store, history }} /> </AppContainer>, rootElement ); }); }
import 'babel-polyfill'; import React from 'react'; import moment from 'moment'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import { syncHistoryWithStore } from 'react-router-redux'; import configureStore from 'app/utils/configureStore'; import Root from './Root'; moment.locale('nb-NO'); global.log = function log(self = this) { console.log(self); return this; }; const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); const rootElement = document.getElementById('root'); render( <AppContainer> <Root {...{ store, history }} /> </AppContainer>, rootElement ); if (module.hot) { module.hot.accept('./Root', () => { render( <AppContainer> <Root {...{ store, history }} /> </AppContainer>, rootElement ); }); }
Switch from hashHistory to browserHistory
Switch from hashHistory to browserHistory
JavaScript
mit
webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp
--- +++ @@ -2,7 +2,7 @@ import React from 'react'; import moment from 'moment'; import { render } from 'react-dom'; -import { hashHistory } from 'react-router'; +import { browserHistory } from 'react-router'; import { AppContainer } from 'react-hot-loader'; import { syncHistoryWithStore } from 'react-router-redux'; import configureStore from 'app/utils/configureStore'; @@ -16,7 +16,7 @@ }; const store = configureStore(); -const history = syncHistoryWithStore(hashHistory, store); +const history = syncHistoryWithStore(browserHistory, store); const rootElement = document.getElementById('root');
0ed43edd2eabb8edda94fe6f91f271ed00d7096b
HigherOrderFunctions/repeat.js
HigherOrderFunctions/repeat.js
function repeat(operation, num) { if(num == 1 || num == 0){ return operation(); } return repeat(operation(), num-1); } // Do not remove the line below module.exports = repeat
function repeat(operation, num) { if(num <= 0){ return operation(); } return repeat(operation, --num); } // Do not remove the line below module.exports = repeat
Edit higher order function solution
Edit higher order function solution
JavaScript
mit
BrianLusina/JS-Snippets
--- +++ @@ -1,8 +1,8 @@ function repeat(operation, num) { - if(num == 1 || num == 0){ + if(num <= 0){ return operation(); } - return repeat(operation(), num-1); + return repeat(operation, --num); } // Do not remove the line below
229c325aae9c3aa2e255457eab838c4fbd4b6707
lib/modules/storage/utils/apply_modifier.js
lib/modules/storage/utils/apply_modifier.js
Astro.utils.storage.applyModifier = function(doc, modifier) { // Apply $set modifier. if (modifier.$set) { _.each(modifier.$set, function(fieldValue, fieldPattern) { Astro.utils.fields.setOne(doc, fieldPattern, fieldValue); }); } // Apply $push modifier. if (modifier.$push) { _.each(modifier.$push, function(pushValue, fieldPattern) { var fieldValue = Astro.utils.fields.getOne(doc, fieldPattern); // If field value is empty then set it to an empty array. if (fieldValue === null || fieldValue === undefined) { fieldValue = []; } // If field value is not an erray then throw exception. else if (!_.isArray(fieldValue)) { throw new Meteor.Error( 409, 'MinimongoError: Cannot apply $push modifier to non-array' ); } // Push a value. fieldValue.push(pushValue); Astro.utils.fields.setOne(doc, fieldPattern, fieldValue); }); } // Apply $inc modifier. if (modifier.$inc) { _.each(modifier.$inc, function(incValue, fieldPattern) { let fieldValue = Astro.utils.fields.getOne(doc, fieldPattern); fieldValue += incValue; Astro.utils.fields.setOne(doc, fieldPattern, fieldValue); }); } Astro.utils.fields.castNested(doc); return { $set: Astro.utils.storage.getModified(doc) }; };
Astro.utils.storage.applyModifier = function(doc, modifier) { // Use Minimongo "_modify" method to apply modifier. LocalCollection._modify(doc, modifier); // Cast values that was set using modifier. Astro.utils.fields.castNested(doc); // Get modified fields. let modified = Astro.utils.storage.getModified(doc); // Return modifier only if there were any changed. if (_.size(modified)) { return {$set: modified}; } };
Use Minimongo to perform modifications
Use Minimongo to perform modifications
JavaScript
mit
jagi/meteor-astronomy
--- +++ @@ -1,43 +1,15 @@ Astro.utils.storage.applyModifier = function(doc, modifier) { - // Apply $set modifier. - if (modifier.$set) { - _.each(modifier.$set, function(fieldValue, fieldPattern) { - Astro.utils.fields.setOne(doc, fieldPattern, fieldValue); - }); - } + // Use Minimongo "_modify" method to apply modifier. + LocalCollection._modify(doc, modifier); - // Apply $push modifier. - if (modifier.$push) { - _.each(modifier.$push, function(pushValue, fieldPattern) { - var fieldValue = Astro.utils.fields.getOne(doc, fieldPattern); - // If field value is empty then set it to an empty array. - if (fieldValue === null || fieldValue === undefined) { - fieldValue = []; - } - // If field value is not an erray then throw exception. - else if (!_.isArray(fieldValue)) { - throw new Meteor.Error( - 409, 'MinimongoError: Cannot apply $push modifier to non-array' - ); - } - // Push a value. - fieldValue.push(pushValue); - Astro.utils.fields.setOne(doc, fieldPattern, fieldValue); - }); - } - - // Apply $inc modifier. - if (modifier.$inc) { - _.each(modifier.$inc, function(incValue, fieldPattern) { - let fieldValue = Astro.utils.fields.getOne(doc, fieldPattern); - fieldValue += incValue; - Astro.utils.fields.setOne(doc, fieldPattern, fieldValue); - }); - } - + // Cast values that was set using modifier. Astro.utils.fields.castNested(doc); - return { - $set: Astro.utils.storage.getModified(doc) - }; + // Get modified fields. + let modified = Astro.utils.storage.getModified(doc); + + // Return modifier only if there were any changed. + if (_.size(modified)) { + return {$set: modified}; + } };
786ae0b1f0dea9da1894a33c4380f5838e2154e7
packages/redux-simple-auth/test/authenticators/credentials.spec.js
packages/redux-simple-auth/test/authenticators/credentials.spec.js
import createCredentialsAuthenticator from '../../src/authenticators/credentials' beforeEach(() => { fetch.resetMocks() }) it('fetches from given endpoint using default config', () => { fetch.mockResponse(JSON.stringify({ ok: true })) const credentials = createCredentialsAuthenticator({ endpoint: '/authenticate' }) const creds = { email: 'text@example.com', password: 'password' } credentials.authenticate(creds) expect(fetch).toHaveBeenCalledWith('/authenticate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(creds) }) }) it('resolves with returned data by default', async () => { fetch.mockResponse(JSON.stringify({ token: '12345' })) const credentials = createCredentialsAuthenticator({ endpoint: '/authenticate' }) const creds = { email: 'text@example.com', password: 'password' } const promise = credentials.authenticate(creds) await expect(promise).resolves.toEqual({ token: '12345' }) })
import createCredentialsAuthenticator from '../../src/authenticators/credentials' beforeEach(() => { fetch.resetMocks() }) it('fetches from given endpoint using default config', () => { fetch.mockResponse(JSON.stringify({ ok: true })) const credentials = createCredentialsAuthenticator({ endpoint: '/authenticate' }) const creds = { email: 'text@example.com', password: 'password' } credentials.authenticate(creds) expect(fetch).toHaveBeenCalledWith('/authenticate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(creds) }) }) it('resolves with returned data by default', async () => { fetch.mockResponse(JSON.stringify({ token: '12345' })) const credentials = createCredentialsAuthenticator({ endpoint: '/authenticate' }) const creds = { email: 'text@example.com', password: 'password' } const promise = credentials.authenticate(creds) await expect(promise).resolves.toEqual({ token: '12345' }) }) it('handles invalid responses', async () => { const error = { error: 'Wrong email or password' } fetch.mockResponse(JSON.stringify(error), { status: 401 }) const credentials = createCredentialsAuthenticator({ endpoint: '/authenticate' }) const promise = credentials.authenticate({ email: 'text@example.com', password: 'password' }) await expect(promise).rejects.toEqual(error) })
Add test to verify it handles errors correctly
Add test to verify it handles errors correctly
JavaScript
mit
jerelmiller/redux-simple-auth
--- +++ @@ -31,3 +31,18 @@ await expect(promise).resolves.toEqual({ token: '12345' }) }) + +it('handles invalid responses', async () => { + const error = { error: 'Wrong email or password' } + fetch.mockResponse(JSON.stringify(error), { status: 401 }) + const credentials = createCredentialsAuthenticator({ + endpoint: '/authenticate' + }) + + const promise = credentials.authenticate({ + email: 'text@example.com', + password: 'password' + }) + + await expect(promise).rejects.toEqual(error) +})
a101fc768cedc7ac9754006e5b7292bb7084ab54
Libraries/Core/setUpGlobals.js
Libraries/Core/setUpGlobals.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ 'use strict'; /** * Sets up global variables for React Native. * You can use this module directly, or just require InitializeCore. */ if (global.GLOBAL === undefined) { global.GLOBAL = global; } if (global.window === undefined) { // $FlowFixMe[cannot-write] global.window = global; } if (global.self === undefined) { // $FlowFixMe[cannot-write] global.self = global; } // Set up process global.process = global.process || {}; global.process.env = global.process.env || {}; if (!global.process.env.NODE_ENV) { global.process.env.NODE_ENV = __DEV__ ? 'development' : 'production'; }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ 'use strict'; /** * Sets up global variables for React Native. * You can use this module directly, or just require InitializeCore. */ if (global.window === undefined) { // $FlowFixMe[cannot-write] global.window = global; } if (global.self === undefined) { // $FlowFixMe[cannot-write] global.self = global; } // Set up process global.process = global.process || {}; global.process.env = global.process.env || {}; if (!global.process.env.NODE_ENV) { global.process.env.NODE_ENV = __DEV__ ? 'development' : 'production'; }
Remove unnecessary global variable named GLOBAL
Remove unnecessary global variable named GLOBAL Summary: We are defining an alias for the global variable in React Native called `GLOBAL`, which is not used at all at Facebook and it doesn't seem it's used externally either. This alias is not standard nor common in the JS ecosystem, so we can just remove it to reduce the pollution of the global scope. Changelog: [General][Removed] - Removed unnecessary global variable `GLOBAL`. Reviewed By: yungsters Differential Revision: D31472154 fbshipit-source-id: 127c3264848b638f85fb2e39e17ed2006372d2dd
JavaScript
mit
janicduplessis/react-native,javache/react-native,janicduplessis/react-native,facebook/react-native,facebook/react-native,facebook/react-native,javache/react-native,facebook/react-native,javache/react-native,janicduplessis/react-native,facebook/react-native,facebook/react-native,janicduplessis/react-native,facebook/react-native,facebook/react-native,javache/react-native,janicduplessis/react-native,javache/react-native,janicduplessis/react-native,javache/react-native,facebook/react-native,janicduplessis/react-native,javache/react-native,janicduplessis/react-native,javache/react-native,javache/react-native
--- +++ @@ -14,10 +14,6 @@ * Sets up global variables for React Native. * You can use this module directly, or just require InitializeCore. */ -if (global.GLOBAL === undefined) { - global.GLOBAL = global; -} - if (global.window === undefined) { // $FlowFixMe[cannot-write] global.window = global;
420bb9bcf135190223506693a6e3abef3ffa0c9b
src/main.js
src/main.js
/* global GuardianAPI, NYTAPI, DomUpdater */ function fillZero(num) { return num < 10 ? `0${num}` : num; } function formatGuardianDate(date) { return `${date.getFullYear()}-${fillZero(date.getMonth() + 1)}-${fillZero(date.getDate())}`; } function formatNYTDate(date) { return `${date.getFullYear()}${fillZero(date.getMonth() + 1)}${fillZero(date.getDate())}`; } function main() { const guardianContentNode = document.getElementById('GuardianContent'); const NYTContentNode = document.getElementById('NYTimesContent'); const today = new Date(Date.now()); console.log(today); // const yesterday = new Date(Date.now() - (8.64 * Math.pow(10, 7))); // console.log(yesterday); // const datesOfLastWeek = Array.from({ length: 6 }, (_, idx) => new Date(Date.now() - (idx +1) * (8.64 * Math.pow(10, 7)))) // // const vs = Array.from({length: 6}, (_, idx) => idx + 1); // console.log(vs); console.log(datesOfLastWeek); GuardianAPI.getArticles(formatGuardianDate(today)) .then(DomUpdater.buildArticleNodes) .then(DomUpdater.displayArticleNodes(guardianContentNode)); NYTAPI.getArticles(formatNYTDate(today)) .then(DomUpdater.buildArticleNodes) .then(DomUpdater.displayArticleNodes(NYTContentNode)); } main();
/* global GuardianAPI, NYTAPI, DomUpdater */ function main() { const today = new Date(Date.now()); console.log(today); const datesLastWeek = Array.from({ length: 7 }, (_, idx) => new Date(today - (idx + 1) * (8.64 * Math.pow(10, 7)))); console.log(datesLastWeek); const navDates = datesLastWeek.map(el => el.toDateString().slice(4, 10)); console.log(navDates); const guardianContentNode = document.getElementById('GuardianContent'); const NYTContentNode = document.getElementById('NYTimesContent'); GuardianAPI.getArticles(formatGuardianDate(today)) .then(DomUpdater.buildArticleNodes) .then(DomUpdater.displayArticleNodes(guardianContentNode)); NYTAPI.getArticles(formatNYTDate(today)) .then(DomUpdater.buildArticleNodes) .then(DomUpdater.displayArticleNodes(NYTContentNode)); } main(); function fillZero(num) { return num < 10 ? `0${num}` : num; } function formatGuardianDate(date) { return `${date.getFullYear()}-${fillZero(date.getMonth() + 1)}-${fillZero(date.getDate())}`; } function formatNYTDate(date) { return `${date.getFullYear()}${fillZero(date.getMonth() + 1)}${fillZero(date.getDate())}`; }
Add Array of responsive dates for navDates display
Add Array of responsive dates for navDates display
JavaScript
mit
Kata-Martagon/NewsAPI,Kata-Martagon/NewsAPI
--- +++ @@ -1,32 +1,18 @@ /* global GuardianAPI, NYTAPI, DomUpdater */ -function fillZero(num) { - return num < 10 ? `0${num}` : num; -} +function main() { + const today = new Date(Date.now()); + console.log(today); + + const datesLastWeek = Array.from({ length: 7 }, (_, idx) => new Date(today - (idx + 1) * (8.64 * Math.pow(10, 7)))); + console.log(datesLastWeek); + + const navDates = datesLastWeek.map(el => el.toDateString().slice(4, 10)); + console.log(navDates); -function formatGuardianDate(date) { - return `${date.getFullYear()}-${fillZero(date.getMonth() + 1)}-${fillZero(date.getDate())}`; -} - -function formatNYTDate(date) { - return `${date.getFullYear()}${fillZero(date.getMonth() + 1)}${fillZero(date.getDate())}`; -} - -function main() { const guardianContentNode = document.getElementById('GuardianContent'); const NYTContentNode = document.getElementById('NYTimesContent'); - - const today = new Date(Date.now()); - console.log(today); - // const yesterday = new Date(Date.now() - (8.64 * Math.pow(10, 7))); - // console.log(yesterday); - // - const datesOfLastWeek = Array.from({ length: 6 }, (_, idx) => new Date(Date.now() - (idx +1) * (8.64 * Math.pow(10, 7)))) - // - // const vs = Array.from({length: 6}, (_, idx) => idx + 1); - // console.log(vs); - console.log(datesOfLastWeek); GuardianAPI.getArticles(formatGuardianDate(today)) .then(DomUpdater.buildArticleNodes) @@ -37,5 +23,17 @@ .then(DomUpdater.displayArticleNodes(NYTContentNode)); } +main(); -main(); + +function fillZero(num) { + return num < 10 ? `0${num}` : num; +} + +function formatGuardianDate(date) { + return `${date.getFullYear()}-${fillZero(date.getMonth() + 1)}-${fillZero(date.getDate())}`; +} + +function formatNYTDate(date) { + return `${date.getFullYear()}${fillZero(date.getMonth() + 1)}${fillZero(date.getDate())}`; +}
7c4b65ea7f00ba206d9f79e61209af284c8f5864
scripts/js/020-components/05-feedback.js
scripts/js/020-components/05-feedback.js
var helpful_yes = document.querySelector( '.helpful_yes' ); var helpful_no = document.querySelector( '.helpful_no' ); var helpful_text = document.querySelector( '.helpful__question' ); function thanks(){ helpful_text.innerHTML = "Thanks for your response and helping us improve our content."; helpful_no.remove(); helpful_yes.remove(); } AddEvent( helpful_yes, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: yes', eventValue: 1 }); }); AddEvent( helpful_no, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: no', eventValue: 0 }); });
var helpful_yes = document.querySelector( '.helpful_yes' ); var helpful_no = document.querySelector( '.helpful_no' ); var helpful_text = document.querySelector( '.helpful__question' ); function thanks(){ helpful_text.innerHTML = "Thanks for your response and helping us improve our content."; helpful_no.remove(); helpful_yes.remove(); } AddEvent( helpful_yes, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: yes', eventValue: 1 }); }); AddEvent( helpful_no, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: no', eventValue: -1 }); });
Make a -1 value for "No"
Make a -1 value for "No"
JavaScript
mit
govau/service-manual
--- +++ @@ -28,6 +28,6 @@ eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: no', - eventValue: 0 + eventValue: -1 }); });
001dfa2fb926606369ba36b46448c1cda3d8f488
config/env/development.js
config/env/development.js
'use strict'; module.exports = { db: 'mongodb://localhost/codeaux-dev', app: { title: 'Codeaux - Development Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
'use strict'; module.exports = { db: 'mongodb://localhost/codeaux-dev', app: { title: 'Codeaux - Development Environment', description: 'Codeaux development stage' } };
Remove duplicates code and update app variable.
Remove duplicates code and update app variable.
JavaScript
mit
Codeaux/Codeaux,Codeaux/Codeaux,Codeaux/Codeaux
--- +++ @@ -1,43 +1,9 @@ 'use strict'; module.exports = { - db: 'mongodb://localhost/codeaux-dev', - app: { - title: 'Codeaux - Development Environment' - }, - facebook: { - clientID: process.env.FACEBOOK_ID || 'APP_ID', - clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', - callbackURL: '/auth/facebook/callback' - }, - twitter: { - clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', - clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', - callbackURL: '/auth/twitter/callback' - }, - google: { - clientID: process.env.GOOGLE_ID || 'APP_ID', - clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', - callbackURL: '/auth/google/callback' - }, - linkedin: { - clientID: process.env.LINKEDIN_ID || 'APP_ID', - clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', - callbackURL: '/auth/linkedin/callback' - }, - github: { - clientID: process.env.GITHUB_ID || 'APP_ID', - clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', - callbackURL: '/auth/github/callback' - }, - mailer: { - from: process.env.MAILER_FROM || 'MAILER_FROM', - options: { - service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', - auth: { - user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', - pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' - } - } - } + db: 'mongodb://localhost/codeaux-dev', + app: { + title: 'Codeaux - Development Environment', + description: 'Codeaux development stage' + } };
d89c55588196f8f58910d470652cc2388fc72f25
client/components/view-gist.js
client/components/view-gist.js
Template.viewGist.helpers({ description: function () { return JSON.parse(this.content).description }, files: function () { console.log(JSON.parse(this.content).files) const array = Object.keys(JSON.parse(this.content).files).map(filename => JSON.parse(this.content).files[filename]) return array } }) Template.viewGist.events({ 'submit form': function(event) { event.preventDefault() const updateContent = { files: {} } updateContent.files[this.filename] = { content: event.target.gist.value } const url = 'https://api.github.com/gists/' + this.gistId const opts = { method: 'PATCH', headers: { Authorization: 'token ' + Meteor.user().services.github.accessToken }, body: JSON.stringify(updateContent) } fetch(url, opts).then(res => console.log('success')) .catch(console.error) } })
Template.viewGist.helpers({ description: function () { return JSON.parse(this.content).description }, files: function () { return Object.keys(JSON.parse(this.content).files) .map(filename => Object.assign( JSON.parse(this.content).files[filename], { gistId: this._id } )) } }) Template.viewGist.events({ 'submit form': function(event) { event.preventDefault() const updateContent = { files: {} } updateContent.files[this.filename] = { content: event.target.gist.value } const url = 'https://api.github.com/gists/' + this.gistId const opts = { method: 'PATCH', headers: { Authorization: 'token ' + Meteor.user().services.github.accessToken }, body: JSON.stringify(updateContent) } fetch(url, opts).then(res => console.log('success')) .catch(console.error) } })
Fix updating to github gist
Fix updating to github gist
JavaScript
isc
caalberts/code-hangout,caalberts/code-hangout
--- +++ @@ -3,9 +3,11 @@ return JSON.parse(this.content).description }, files: function () { - console.log(JSON.parse(this.content).files) - const array = Object.keys(JSON.parse(this.content).files).map(filename => JSON.parse(this.content).files[filename]) - return array + return Object.keys(JSON.parse(this.content).files) + .map(filename => Object.assign( + JSON.parse(this.content).files[filename], + { gistId: this._id } + )) } })
f934e5201b6db5ee0eabf1b6f1613f70f2c1512e
page/templates/script.js
page/templates/script.js
'use strict'; angular.module('edge.app.controllers').controller('<%= controllerName %>Controller', function () { var <%= controllerName.toLowerCase() %> = this; <%= controllerName.toLowerCase() %>.info = '<%= appTitle %> &raquo; <%= _.capitalize(name) %>'; });
'use strict'; angular.module('edge.app.controllers').controller('<%= controllerName %>Controller', function () { var <%= controllerName.toLowerCase() %> = this; <%= controllerName.toLowerCase() %>.info = '<%= appTitle %> - <%= _.capitalize(name) %>'; });
Remove raquo so that it not necessary to sanitize html
Remove raquo so that it not necessary to sanitize html
JavaScript
mit
greaterweb/generator-edgeplate,greaterweb/generator-edgeplate
--- +++ @@ -2,5 +2,5 @@ angular.module('edge.app.controllers').controller('<%= controllerName %>Controller', function () { var <%= controllerName.toLowerCase() %> = this; - <%= controllerName.toLowerCase() %>.info = '<%= appTitle %> &raquo; <%= _.capitalize(name) %>'; + <%= controllerName.toLowerCase() %>.info = '<%= appTitle %> - <%= _.capitalize(name) %>'; });
e3b8893664e0f2cd9249b63d5660d5000d11b2e5
src/mean.js
src/mean.js
var mean = function (numArr) { if(!Object.prototype.toString.call(numArr) === "[object Array]"){ return false; } return numArr.reduce(function(previousVal, currentVal){return previousVal + currentVal;}) / numArr.length; }; anything.prototype.mean = mean;
var mean = function (numArr) { if(!Object.prototype.toString.call(numArr) === "[object Array]"){ return false; } return numArr.reduce(function(previousVal, currentVal){return previousVal + currentVal;}) / numArr.length; }; anything.prototype.mean = mean;
Remove extra space in indent
Remove extra space in indent
JavaScript
mit
dstrekelj/anything.js,developer787/anything.js,developer787/anything.js,developer787/anything.js,vekat/anything.js,awadYehya/anything.js,Rabrennie/anything.js,Sha-Grisha/anything.js,dstrekelj/anything.js,dstrekelj/anything.js,vekat/anything.js,awadYehya/anything.js,developer787/anything.js,vekat/anything.js,dstrekelj/anything.js,awadYehya/anything.js,Rabrennie/anything.js,awadYehya/anything.js,Rabrennie/anything.js,Sha-Grisha/anything.js,Sha-Grisha/anything.js,Rabrennie/anything.js,vekat/anything.js,Sha-Grisha/anything.js
--- +++ @@ -3,7 +3,7 @@ return false; } - return numArr.reduce(function(previousVal, currentVal){return previousVal + currentVal;}) / numArr.length; + return numArr.reduce(function(previousVal, currentVal){return previousVal + currentVal;}) / numArr.length; }; anything.prototype.mean = mean;
0b700b286a6bc29dd2d4d8e8403533c8cd846bf2
packages/accounts-twitter/twitter_server.js
packages/accounts-twitter/twitter_server.js
(function () { Accounts.oauth.registerService('twitter', 1, function(oauthBinding) { var identity = oauthBinding.get('https://api.twitter.com/1.1/account/verify_credentials.json').data; return { serviceData: { id: identity.id_str, screenName: identity.screen_name, accessToken: oauthBinding.accessToken, accessTokenSecret: oauthBinding.accessTokenSecret }, options: { profile: { name: identity.name } } }; }); }) ();
(function () { Accounts.oauth.registerService('twitter', 1, function(oauthBinding) { var identity = oauthBinding.get('https://api.twitter.com/1.1/account/verify_credentials.json').data; var serviceData = { id: identity.id_str, screenName: identity.screen_name, accessToken: oauthBinding.accessToken, accessTokenSecret: oauthBinding.accessTokenSecret }; // include helpful fields from twitter // https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials var whitelisted = ['profile_image_url', 'profile_image_url_https', 'lang']; var fields = _.pick(identity, whitelisted); _.extend(serviceData, fields); return { serviceData: serviceData, options: { profile: { name: identity.name } } }; }); }) ();
Include avatar and language in serviceData when user signs in to Twitter
Include avatar and language in serviceData when user signs in to Twitter
JavaScript
mit
h200863057/meteor,pandeysoni/meteor,LWHTarena/meteor,baiyunping333/meteor,esteedqueen/meteor,henrypan/meteor,evilemon/meteor,cherbst/meteor,Paulyoufu/meteor-1,guazipi/meteor,yiliaofan/meteor,HugoRLopes/meteor,jdivy/meteor,imanmafi/meteor,yonas/meteor-freebsd,queso/meteor,fashionsun/meteor,rabbyalone/meteor,deanius/meteor,TechplexEngineer/meteor,jirengu/meteor,pandeysoni/meteor,somallg/meteor,chiefninew/meteor,GrimDerp/meteor,akintoey/meteor,kencheung/meteor,yyx990803/meteor,namho102/meteor,johnthepink/meteor,rozzzly/meteor,mauricionr/meteor,meonkeys/meteor,Ken-Liu/meteor,jeblister/meteor,steedos/meteor,chmac/meteor,ljack/meteor,EduShareOntario/meteor,stevenliuit/meteor,ndarilek/meteor,devgrok/meteor,Urigo/meteor,dboyliao/meteor,h200863057/meteor,bhargav175/meteor,mubassirhayat/meteor,modulexcite/meteor,ndarilek/meteor,yanisIk/meteor,chengxiaole/meteor,jdivy/meteor,shrop/meteor,brdtrpp/meteor,daltonrenaldo/meteor,somallg/meteor,AlexR1712/meteor,namho102/meteor,TribeMedia/meteor,vjau/meteor,lassombra/meteor,aldeed/meteor,qscripter/meteor,modulexcite/meteor,judsonbsilva/meteor,papimomi/meteor,HugoRLopes/meteor,h200863057/meteor,justintung/meteor,brdtrpp/meteor,jg3526/meteor,colinligertwood/meteor,karlito40/meteor,jeblister/meteor,yanisIk/meteor,henrypan/meteor,shrop/meteor,mauricionr/meteor,fashionsun/meteor,DCKT/meteor,shmiko/meteor,vjau/meteor,chengxiaole/meteor,henrypan/meteor,newswim/meteor,Hansoft/meteor,SeanOceanHu/meteor,jagi/meteor,LWHTarena/meteor,jagi/meteor,imanmafi/meteor,jenalgit/meteor,williambr/meteor,dev-bobsong/meteor,cherbst/meteor,michielvanoeffelen/meteor,aramk/meteor,daslicht/meteor,sdeveloper/meteor,shrop/meteor,D1no/meteor,akintoey/meteor,eluck/meteor,karlito40/meteor,oceanzou123/meteor,mjmasn/meteor,luohuazju/meteor,namho102/meteor,aldeed/meteor,ericterpstra/meteor,youprofit/meteor,deanius/meteor,luohuazju/meteor,shmiko/meteor,yonas/meteor-freebsd,lieuwex/meteor,fashionsun/meteor,akintoey/meteor,deanius/meteor,lassombra/meteor,dboyliao/meteor,PatrickMcGuinness/meteor,Urigo/meteor,queso/meteor,daltonrenaldo/meteor,yinhe007/meteor,servel333/meteor,mauricionr/meteor,vacjaliu/meteor,servel333/meteor,cog-64/meteor,AlexR1712/meteor,nuvipannu/meteor,oceanzou123/meteor,ashwathgovind/meteor,brdtrpp/meteor,dboyliao/meteor,Eynaliyev/meteor,lpinto93/meteor,devgrok/meteor,JesseQin/meteor,ericterpstra/meteor,h200863057/meteor,Theviajerock/meteor,shmiko/meteor,somallg/meteor,lpinto93/meteor,arunoda/meteor,chmac/meteor,shadedprofit/meteor,steedos/meteor,dandv/meteor,baysao/meteor,eluck/meteor,sunny-g/meteor,iman-mafi/meteor,LWHTarena/meteor,msavin/meteor,SeanOceanHu/meteor,jdivy/meteor,dev-bobsong/meteor,jeblister/meteor,benstoltz/meteor,lassombra/meteor,ljack/meteor,neotim/meteor,wmkcc/meteor,brdtrpp/meteor,daslicht/meteor,4commerce-technologies-AG/meteor,dandv/meteor,mauricionr/meteor,michielvanoeffelen/meteor,JesseQin/meteor,youprofit/meteor,whip112/meteor,akintoey/meteor,mubassirhayat/meteor,bhargav175/meteor,ljack/meteor,arunoda/meteor,alphanso/meteor,jeblister/meteor,jg3526/meteor,chinasb/meteor,cbonami/meteor,sclausen/meteor,aleclarson/meteor,shmiko/meteor,alphanso/meteor,yonglehou/meteor,zdd910/meteor,youprofit/meteor,h200863057/meteor,servel333/meteor,aldeed/meteor,ljack/meteor,Profab/meteor,kencheung/meteor,GrimDerp/meteor,bhargav175/meteor,lorensr/meteor,ljack/meteor,namho102/meteor,oceanzou123/meteor,saisai/meteor,Paulyoufu/meteor-1,tdamsma/meteor,michielvanoeffelen/meteor,codingang/meteor,emmerge/meteor,meteor-velocity/meteor,jagi/meteor,papimomi/meteor,Jeremy017/meteor,skarekrow/meteor,elkingtonmcb/meteor,esteedqueen/meteor,lpinto93/meteor,alphanso/meteor,lieuwex/meteor,oceanzou123/meteor,yinhe007/meteor,justintung/meteor,lawrenceAIO/meteor,deanius/meteor,calvintychan/meteor,yiliaofan/meteor,codedogfish/meteor,Jonekee/meteor,lpinto93/meteor,yonglehou/meteor,yiliaofan/meteor,D1no/meteor,lieuwex/meteor,yalexx/meteor,iman-mafi/meteor,DCKT/meteor,EduShareOntario/meteor,yalexx/meteor,LWHTarena/meteor,HugoRLopes/meteor,dboyliao/meteor,ashwathgovind/meteor,juansgaitan/meteor,jrudio/meteor,DAB0mB/meteor,Quicksteve/meteor,vacjaliu/meteor,chmac/meteor,chengxiaole/meteor,lpinto93/meteor,mjmasn/meteor,SeanOceanHu/meteor,mirstan/meteor,lawrenceAIO/meteor,l0rd0fwar/meteor,GrimDerp/meteor,allanalexandre/meteor,shadedprofit/meteor,williambr/meteor,chasertech/meteor,meonkeys/meteor,udhayam/meteor,esteedqueen/meteor,HugoRLopes/meteor,sitexa/meteor,dandv/meteor,sclausen/meteor,PatrickMcGuinness/meteor,yalexx/meteor,joannekoong/meteor,brettle/meteor,vjau/meteor,vacjaliu/meteor,mirstan/meteor,AnthonyAstige/meteor,kidaa/meteor,oceanzou123/meteor,zdd910/meteor,JesseQin/meteor,yonas/meteor-freebsd,namho102/meteor,yonglehou/meteor,zdd910/meteor,daslicht/meteor,rabbyalone/meteor,calvintychan/meteor,wmkcc/meteor,kengchau/meteor,katopz/meteor,deanius/meteor,paul-barry-kenzan/meteor,DAB0mB/meteor,sunny-g/meteor,jg3526/meteor,chiefninew/meteor,emmerge/meteor,judsonbsilva/meteor,kidaa/meteor,chmac/meteor,jenalgit/meteor,newswim/meteor,Jeremy017/meteor,mubassirhayat/meteor,meonkeys/meteor,baysao/meteor,yanisIk/meteor,JesseQin/meteor,baiyunping333/meteor,Hansoft/meteor,meteor-velocity/meteor,rozzzly/meteor,Urigo/meteor,Eynaliyev/meteor,msavin/meteor,GrimDerp/meteor,Prithvi-A/meteor,aramk/meteor,EduShareOntario/meteor,karlito40/meteor,Ken-Liu/meteor,paul-barry-kenzan/meteor,meonkeys/meteor,alexbeletsky/meteor,shadedprofit/meteor,sdeveloper/meteor,lawrenceAIO/meteor,tdamsma/meteor,Ken-Liu/meteor,aramk/meteor,skarekrow/meteor,michielvanoeffelen/meteor,Eynaliyev/meteor,Jonekee/meteor,AnthonyAstige/meteor,emmerge/meteor,IveWong/meteor,cog-64/meteor,guazipi/meteor,zdd910/meteor,dboyliao/meteor,chiefninew/meteor,dboyliao/meteor,eluck/meteor,vacjaliu/meteor,DCKT/meteor,ljack/meteor,brettle/meteor,Urigo/meteor,brettle/meteor,yyx990803/meteor,benjamn/meteor,ericterpstra/meteor,chmac/meteor,michielvanoeffelen/meteor,juansgaitan/meteor,alexbeletsky/meteor,tdamsma/meteor,dfischer/meteor,codingang/meteor,sitexa/meteor,jirengu/meteor,IveWong/meteor,joannekoong/meteor,hristaki/meteor,steedos/meteor,sitexa/meteor,jrudio/meteor,daltonrenaldo/meteor,D1no/meteor,meonkeys/meteor,johnthepink/meteor,mjmasn/meteor,hristaki/meteor,mirstan/meteor,ndarilek/meteor,calvintychan/meteor,aleclarson/meteor,newswim/meteor,paul-barry-kenzan/meteor,guazipi/meteor,eluck/meteor,Eynaliyev/meteor,vjau/meteor,TechplexEngineer/meteor,yinhe007/meteor,shadedprofit/meteor,nuvipannu/meteor,williambr/meteor,jenalgit/meteor,kencheung/meteor,chmac/meteor,sclausen/meteor,4commerce-technologies-AG/meteor,Jeremy017/meteor,AnjirHossain/meteor,HugoRLopes/meteor,ashwathgovind/meteor,l0rd0fwar/meteor,baiyunping333/meteor,dfischer/meteor,pjump/meteor,planet-training/meteor,mubassirhayat/meteor,stevenliuit/meteor,cbonami/meteor,neotim/meteor,youprofit/meteor,dfischer/meteor,sitexa/meteor,luohuazju/meteor,l0rd0fwar/meteor,iman-mafi/meteor,imanmafi/meteor,aramk/meteor,ndarilek/meteor,fashionsun/meteor,esteedqueen/meteor,jenalgit/meteor,sclausen/meteor,vacjaliu/meteor,papimomi/meteor,h200863057/meteor,SeanOceanHu/meteor,Prithvi-A/meteor,PatrickMcGuinness/meteor,allanalexandre/meteor,allanalexandre/meteor,yyx990803/meteor,justintung/meteor,dfischer/meteor,Profab/meteor,kengchau/meteor,williambr/meteor,justintung/meteor,meonkeys/meteor,somallg/meteor,chiefninew/meteor,karlito40/meteor,chasertech/meteor,jagi/meteor,stevenliuit/meteor,jeblister/meteor,chinasb/meteor,modulexcite/meteor,iman-mafi/meteor,PatrickMcGuinness/meteor,kidaa/meteor,Quicksteve/meteor,wmkcc/meteor,HugoRLopes/meteor,henrypan/meteor,eluck/meteor,rozzzly/meteor,youprofit/meteor,aldeed/meteor,johnthepink/meteor,stevenliuit/meteor,qscripter/meteor,Hansoft/meteor,msavin/meteor,lorensr/meteor,somallg/meteor,kencheung/meteor,mubassirhayat/meteor,fashionsun/meteor,karlito40/meteor,Prithvi-A/meteor,dboyliao/meteor,kengchau/meteor,daslicht/meteor,colinligertwood/meteor,Paulyoufu/meteor-1,newswim/meteor,nuvipannu/meteor,lawrenceAIO/meteor,IveWong/meteor,udhayam/meteor,dev-bobsong/meteor,shrop/meteor,ashwathgovind/meteor,yonas/meteor-freebsd,neotim/meteor,lawrenceAIO/meteor,AnjirHossain/meteor,colinligertwood/meteor,planet-training/meteor,alphanso/meteor,yanisIk/meteor,elkingtonmcb/meteor,yanisIk/meteor,AlexR1712/meteor,lassombra/meteor,steedos/meteor,deanius/meteor,queso/meteor,DCKT/meteor,Prithvi-A/meteor,servel333/meteor,ljack/meteor,colinligertwood/meteor,chiefninew/meteor,vjau/meteor,DCKT/meteor,AlexR1712/meteor,AnjirHossain/meteor,IveWong/meteor,joannekoong/meteor,yiliaofan/meteor,papimomi/meteor,vacjaliu/meteor,udhayam/meteor,sdeveloper/meteor,judsonbsilva/meteor,dev-bobsong/meteor,TribeMedia/meteor,jg3526/meteor,Jeremy017/meteor,AnthonyAstige/meteor,juansgaitan/meteor,fashionsun/meteor,4commerce-technologies-AG/meteor,daltonrenaldo/meteor,hristaki/meteor,SeanOceanHu/meteor,justintung/meteor,codedogfish/meteor,sdeveloper/meteor,mirstan/meteor,ndarilek/meteor,yyx990803/meteor,lieuwex/meteor,daslicht/meteor,dandv/meteor,elkingtonmcb/meteor,msavin/meteor,aldeed/meteor,framewr/meteor,jenalgit/meteor,lorensr/meteor,TechplexEngineer/meteor,l0rd0fwar/meteor,codingang/meteor,brettle/meteor,colinligertwood/meteor,katopz/meteor,yiliaofan/meteor,modulexcite/meteor,ndarilek/meteor,4commerce-technologies-AG/meteor,Jonekee/meteor,Puena/meteor,cbonami/meteor,evilemon/meteor,pjump/meteor,paul-barry-kenzan/meteor,GrimDerp/meteor,mjmasn/meteor,SeanOceanHu/meteor,msavin/meteor,alexbeletsky/meteor,devgrok/meteor,mauricionr/meteor,brettle/meteor,qscripter/meteor,imanmafi/meteor,planet-training/meteor,johnthepink/meteor,joannekoong/meteor,cherbst/meteor,lorensr/meteor,Eynaliyev/meteor,AnjirHossain/meteor,Ken-Liu/meteor,AnthonyAstige/meteor,PatrickMcGuinness/meteor,cbonami/meteor,Paulyoufu/meteor-1,judsonbsilva/meteor,kengchau/meteor,chengxiaole/meteor,lassombra/meteor,henrypan/meteor,chmac/meteor,vjau/meteor,calvintychan/meteor,meonkeys/meteor,hristaki/meteor,wmkcc/meteor,qscripter/meteor,TribeMedia/meteor,imanmafi/meteor,elkingtonmcb/meteor,iman-mafi/meteor,sunny-g/meteor,tdamsma/meteor,jagi/meteor,Profab/meteor,iman-mafi/meteor,chinasb/meteor,rozzzly/meteor,yonglehou/meteor,papimomi/meteor,allanalexandre/meteor,TribeMedia/meteor,colinligertwood/meteor,benstoltz/meteor,pandeysoni/meteor,zdd910/meteor,Quicksteve/meteor,Paulyoufu/meteor-1,dandv/meteor,codingang/meteor,msavin/meteor,tdamsma/meteor,Profab/meteor,queso/meteor,Puena/meteor,michielvanoeffelen/meteor,saisai/meteor,yalexx/meteor,dev-bobsong/meteor,EduShareOntario/meteor,jg3526/meteor,Puena/meteor,AnthonyAstige/meteor,yyx990803/meteor,alexbeletsky/meteor,devgrok/meteor,pandeysoni/meteor,lpinto93/meteor,AnthonyAstige/meteor,zdd910/meteor,luohuazju/meteor,EduShareOntario/meteor,ashwathgovind/meteor,mjmasn/meteor,stevenliuit/meteor,udhayam/meteor,oceanzou123/meteor,daltonrenaldo/meteor,ericterpstra/meteor,lorensr/meteor,framewr/meteor,ndarilek/meteor,Jonekee/meteor,servel333/meteor,papimomi/meteor,jeblister/meteor,baiyunping333/meteor,DAB0mB/meteor,lorensr/meteor,alphanso/meteor,youprofit/meteor,Quicksteve/meteor,emmerge/meteor,yonas/meteor-freebsd,allanalexandre/meteor,codedogfish/meteor,skarekrow/meteor,shmiko/meteor,daslicht/meteor,benstoltz/meteor,sitexa/meteor,AnthonyAstige/meteor,Puena/meteor,baysao/meteor,skarekrow/meteor,Quicksteve/meteor,alphanso/meteor,devgrok/meteor,allanalexandre/meteor,bhargav175/meteor,jirengu/meteor,4commerce-technologies-AG/meteor,cog-64/meteor,Jonekee/meteor,neotim/meteor,baysao/meteor,Paulyoufu/meteor-1,dfischer/meteor,guazipi/meteor,modulexcite/meteor,arunoda/meteor,mauricionr/meteor,qscripter/meteor,Prithvi-A/meteor,shrop/meteor,iman-mafi/meteor,codedogfish/meteor,jdivy/meteor,yonglehou/meteor,HugoRLopes/meteor,zdd910/meteor,karlito40/meteor,skarekrow/meteor,cog-64/meteor,planet-training/meteor,stevenliuit/meteor,vjau/meteor,evilemon/meteor,Hansoft/meteor,sunny-g/meteor,eluck/meteor,sunny-g/meteor,evilemon/meteor,mauricionr/meteor,chiefninew/meteor,mubassirhayat/meteor,cbonami/meteor,dandv/meteor,alphanso/meteor,deanius/meteor,jg3526/meteor,somallg/meteor,guazipi/meteor,sitexa/meteor,shrop/meteor,cherbst/meteor,brettle/meteor,benjamn/meteor,chinasb/meteor,aramk/meteor,Hansoft/meteor,D1no/meteor,Paulyoufu/meteor-1,Eynaliyev/meteor,TribeMedia/meteor,dfischer/meteor,D1no/meteor,saisai/meteor,codedogfish/meteor,HugoRLopes/meteor,TechplexEngineer/meteor,daltonrenaldo/meteor,yalexx/meteor,D1no/meteor,framewr/meteor,sclausen/meteor,TechplexEngineer/meteor,yanisIk/meteor,PatrickMcGuinness/meteor,judsonbsilva/meteor,pandeysoni/meteor,cog-64/meteor,elkingtonmcb/meteor,evilemon/meteor,saisai/meteor,hristaki/meteor,IveWong/meteor,daltonrenaldo/meteor,Jeremy017/meteor,karlito40/meteor,johnthepink/meteor,ericterpstra/meteor,DAB0mB/meteor,johnthepink/meteor,joannekoong/meteor,D1no/meteor,aramk/meteor,daltonrenaldo/meteor,devgrok/meteor,newswim/meteor,paul-barry-kenzan/meteor,elkingtonmcb/meteor,lieuwex/meteor,saisai/meteor,planet-training/meteor,sunny-g/meteor,akintoey/meteor,TechplexEngineer/meteor,jirengu/meteor,williambr/meteor,pjump/meteor,yalexx/meteor,h200863057/meteor,whip112/meteor,eluck/meteor,rabbyalone/meteor,calvintychan/meteor,Hansoft/meteor,elkingtonmcb/meteor,LWHTarena/meteor,DAB0mB/meteor,jagi/meteor,cog-64/meteor,shadedprofit/meteor,queso/meteor,jg3526/meteor,jeblister/meteor,whip112/meteor,LWHTarena/meteor,whip112/meteor,Theviajerock/meteor,chengxiaole/meteor,namho102/meteor,codingang/meteor,servel333/meteor,qscripter/meteor,Ken-Liu/meteor,karlito40/meteor,sdeveloper/meteor,baiyunping333/meteor,mirstan/meteor,katopz/meteor,cherbst/meteor,l0rd0fwar/meteor,kengchau/meteor,benjamn/meteor,saisai/meteor,bhargav175/meteor,alexbeletsky/meteor,paul-barry-kenzan/meteor,ndarilek/meteor,codedogfish/meteor,AnjirHossain/meteor,arunoda/meteor,Puena/meteor,jdivy/meteor,Eynaliyev/meteor,udhayam/meteor,aldeed/meteor,ljack/meteor,lieuwex/meteor,jrudio/meteor,brdtrpp/meteor,baysao/meteor,aramk/meteor,kengchau/meteor,lorensr/meteor,Jonekee/meteor,aleclarson/meteor,queso/meteor,akintoey/meteor,yinhe007/meteor,msavin/meteor,allanalexandre/meteor,Hansoft/meteor,eluck/meteor,GrimDerp/meteor,justintung/meteor,rozzzly/meteor,Theviajerock/meteor,hristaki/meteor,DAB0mB/meteor,chasertech/meteor,pjump/meteor,SeanOceanHu/meteor,cbonami/meteor,AnjirHossain/meteor,l0rd0fwar/meteor,meteor-velocity/meteor,tdamsma/meteor,guazipi/meteor,somallg/meteor,nuvipannu/meteor,4commerce-technologies-AG/meteor,mirstan/meteor,guazipi/meteor,PatrickMcGuinness/meteor,framewr/meteor,lieuwex/meteor,IveWong/meteor,dev-bobsong/meteor,sdeveloper/meteor,hristaki/meteor,williambr/meteor,TribeMedia/meteor,esteedqueen/meteor,juansgaitan/meteor,JesseQin/meteor,chasertech/meteor,alexbeletsky/meteor,whip112/meteor,sclausen/meteor,alexbeletsky/meteor,calvintychan/meteor,dboyliao/meteor,oceanzou123/meteor,planet-training/meteor,TechplexEngineer/meteor,alexbeletsky/meteor,benjamn/meteor,kengchau/meteor,judsonbsilva/meteor,juansgaitan/meteor,brdtrpp/meteor,AlexR1712/meteor,saisai/meteor,codedogfish/meteor,neotim/meteor,benstoltz/meteor,ericterpstra/meteor,planet-training/meteor,mubassirhayat/meteor,l0rd0fwar/meteor,dandv/meteor,jrudio/meteor,LWHTarena/meteor,JesseQin/meteor,Prithvi-A/meteor,stevenliuit/meteor,shrop/meteor,henrypan/meteor,servel333/meteor,AlexR1712/meteor,katopz/meteor,modulexcite/meteor,qscripter/meteor,meteor-velocity/meteor,pandeysoni/meteor,namho102/meteor,devgrok/meteor,allanalexandre/meteor,Urigo/meteor,neotim/meteor,newswim/meteor,AnthonyAstige/meteor,framewr/meteor,queso/meteor,johnthepink/meteor,codingang/meteor,mjmasn/meteor,benstoltz/meteor,Profab/meteor,mirstan/meteor,GrimDerp/meteor,benjamn/meteor,ashwathgovind/meteor,tdamsma/meteor,baysao/meteor,Quicksteve/meteor,baiyunping333/meteor,vacjaliu/meteor,kencheung/meteor,chiefninew/meteor,skarekrow/meteor,AnjirHossain/meteor,Jeremy017/meteor,DAB0mB/meteor,Jonekee/meteor,rabbyalone/meteor,esteedqueen/meteor,yinhe007/meteor,pjump/meteor,katopz/meteor,yanisIk/meteor,nuvipannu/meteor,rabbyalone/meteor,chinasb/meteor,DCKT/meteor,benjamn/meteor,calvintychan/meteor,michielvanoeffelen/meteor,shadedprofit/meteor,cbonami/meteor,jenalgit/meteor,Theviajerock/meteor,daslicht/meteor,judsonbsilva/meteor,ashwathgovind/meteor,yiliaofan/meteor,codingang/meteor,chasertech/meteor,brettle/meteor,servel333/meteor,pjump/meteor,shmiko/meteor,papimomi/meteor,wmkcc/meteor,chasertech/meteor,nuvipannu/meteor,fashionsun/meteor,Prithvi-A/meteor,chinasb/meteor,jenalgit/meteor,4commerce-technologies-AG/meteor,Ken-Liu/meteor,Urigo/meteor,emmerge/meteor,meteor-velocity/meteor,kidaa/meteor,Puena/meteor,lassombra/meteor,emmerge/meteor,juansgaitan/meteor,joannekoong/meteor,Profab/meteor,baiyunping333/meteor,Jeremy017/meteor,luohuazju/meteor,cherbst/meteor,henrypan/meteor,rozzzly/meteor,yyx990803/meteor,D1no/meteor,steedos/meteor,rabbyalone/meteor,brdtrpp/meteor,williambr/meteor,dev-bobsong/meteor,kidaa/meteor,cog-64/meteor,sunny-g/meteor,planet-training/meteor,udhayam/meteor,evilemon/meteor,rozzzly/meteor,Theviajerock/meteor,jdivy/meteor,modulexcite/meteor,jagi/meteor,neotim/meteor,SeanOceanHu/meteor,justintung/meteor,yonas/meteor-freebsd,kencheung/meteor,kidaa/meteor,katopz/meteor,youprofit/meteor,arunoda/meteor,joannekoong/meteor,chinasb/meteor,sunny-g/meteor,mubassirhayat/meteor,kencheung/meteor,arunoda/meteor,somallg/meteor,yonglehou/meteor,bhargav175/meteor,EduShareOntario/meteor,shadedprofit/meteor,Theviajerock/meteor,chiefninew/meteor,nuvipannu/meteor,lpinto93/meteor,newswim/meteor,jirengu/meteor,skarekrow/meteor,yanisIk/meteor,chengxiaole/meteor,Eynaliyev/meteor,pjump/meteor,Profab/meteor,colinligertwood/meteor,Theviajerock/meteor,EduShareOntario/meteor,rabbyalone/meteor,jdivy/meteor,luohuazju/meteor,udhayam/meteor,steedos/meteor,bhargav175/meteor,IveWong/meteor,jirengu/meteor,aldeed/meteor,Quicksteve/meteor,chasertech/meteor,lawrenceAIO/meteor,benstoltz/meteor,yiliaofan/meteor,yinhe007/meteor,imanmafi/meteor,wmkcc/meteor,akintoey/meteor,jrudio/meteor,cherbst/meteor,imanmafi/meteor,esteedqueen/meteor,dfischer/meteor,sitexa/meteor,yalexx/meteor,chengxiaole/meteor,emmerge/meteor,lassombra/meteor,pandeysoni/meteor,evilemon/meteor,whip112/meteor,JesseQin/meteor,Puena/meteor,yonas/meteor-freebsd,meteor-velocity/meteor,Urigo/meteor,meteor-velocity/meteor,yonglehou/meteor,AlexR1712/meteor,TribeMedia/meteor,benstoltz/meteor,Ken-Liu/meteor,framewr/meteor,sdeveloper/meteor,kidaa/meteor,arunoda/meteor,wmkcc/meteor,whip112/meteor,ericterpstra/meteor,lawrenceAIO/meteor,framewr/meteor,luohuazju/meteor,jrudio/meteor,baysao/meteor,shmiko/meteor,brdtrpp/meteor,katopz/meteor,sclausen/meteor,steedos/meteor,mjmasn/meteor,yyx990803/meteor,yinhe007/meteor,jirengu/meteor,benjamn/meteor,juansgaitan/meteor,tdamsma/meteor,DCKT/meteor,paul-barry-kenzan/meteor
--- +++ @@ -3,13 +3,22 @@ Accounts.oauth.registerService('twitter', 1, function(oauthBinding) { var identity = oauthBinding.get('https://api.twitter.com/1.1/account/verify_credentials.json').data; - return { - serviceData: { + var serviceData = { id: identity.id_str, screenName: identity.screen_name, accessToken: oauthBinding.accessToken, accessTokenSecret: oauthBinding.accessTokenSecret - }, + }; + + // include helpful fields from twitter + // https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials + var whitelisted = ['profile_image_url', 'profile_image_url_https', 'lang']; + + var fields = _.pick(identity, whitelisted); + _.extend(serviceData, fields); + + return { + serviceData: serviceData, options: { profile: { name: identity.name
a4d7a5f9a19d56d51ba21702486e7f157da52785
Blog/src/js/components/login.react.js
Blog/src/js/components/login.react.js
import React from 'react'; export default class Login extends React.Component { render() { return ( <form> <div className="form-group"> <label htmlFor="username">{'Name'}</label> <input className="form-control" placeholder="Please, provide a User." type="text" /> </div> <div className="form-group"> <label htmlFor="password">{'Secret'}</label> <input className="form-control" placeholder="Also, don't forget the secret password." type="password" /> </div> <button type="submit" className="btn btn-default">{'Submit'}</button> </form> ); } }
import React from 'react'; export default class Login extends React.Component { static get displayName() { return 'Login'; } render() { return ( <form> <div className="form-group" > <label htmlFor="username" >{'Name'}</label> <input className="form-control" placeholder="Please, provide a User." type="text" /> </div> <div className="form-group" > <label htmlFor="password" >{'Secret'}</label> <input className="form-control" placeholder="Also, don't forget the secret password." type="password" /> </div> <button className="btn btn-default" type="submit" >{'Submit'}</button> </form> ); } }
Fix lint issues with Login component
Fix lint issues with Login component
JavaScript
mit
rcatlin/ryancatlin-info,rcatlin/ryancatlin-info,rcatlin/ryancatlin-info,rcatlin/ryancatlin-info
--- +++ @@ -1,26 +1,41 @@ import React from 'react'; export default class Login extends React.Component { + static get displayName() { + return 'Login'; + } + render() { return ( <form> - <div className="form-group"> - <label htmlFor="username">{'Name'}</label> + <div + className="form-group" + > + <label + htmlFor="username" + >{'Name'}</label> <input className="form-control" placeholder="Please, provide a User." type="text" /> </div> - <div className="form-group"> - <label htmlFor="password">{'Secret'}</label> + <div + className="form-group" + > + <label + htmlFor="password" + >{'Secret'}</label> <input className="form-control" placeholder="Also, don't forget the secret password." type="password" /> </div> - <button type="submit" className="btn btn-default">{'Submit'}</button> + <button + className="btn btn-default" + type="submit" + >{'Submit'}</button> </form> ); }
bac6c4e72db69dc7f7c6b79754046b8957779fed
tests/acceptance/build-info-test.js
tests/acceptance/build-info-test.js
import { test } from 'qunit'; import moduleForAcceptance from 'croodle/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | build info'); test('version is included as html meta tag', function(assert) { visit('/'); andThen(function() { assert.ok($('head meta[name="build-info"]').length === 1, 'tag exists'); assert.ok( $('head meta[name="build-info"]').attr('content').match(/^version=v\d[\d\.]+\d(-(alpha|beta|rc)\d)?(\+[\da-z]{8})?$/) !== null, 'format '.concat($('head meta[name="build-info"]').attr('content'), ' is correct') ); }); });
import { test } from 'qunit'; import moduleForAcceptance from 'croodle/tests/helpers/module-for-acceptance'; moduleForAcceptance('Acceptance | build info'); test('version is included as html meta tag', function(assert) { visit('/'); andThen(function() { assert.ok($('head meta[name="build-info"]').length === 1, 'tag exists'); assert.ok( $('head meta[name="build-info"]').attr('content').match(/^version=\d[\d\.]+\d(-(alpha|beta|rc)\d)?(\+[\da-z]{8})?$/) !== null, 'format '.concat($('head meta[name="build-info"]').attr('content'), ' is correct') ); }); });
Fix test after version in package.json has been corrected
Fix test after version in package.json has been corrected
JavaScript
mit
jelhan/croodle,jelhan/croodle,jelhan/croodle
--- +++ @@ -9,7 +9,7 @@ andThen(function() { assert.ok($('head meta[name="build-info"]').length === 1, 'tag exists'); assert.ok( - $('head meta[name="build-info"]').attr('content').match(/^version=v\d[\d\.]+\d(-(alpha|beta|rc)\d)?(\+[\da-z]{8})?$/) !== null, + $('head meta[name="build-info"]').attr('content').match(/^version=\d[\d\.]+\d(-(alpha|beta|rc)\d)?(\+[\da-z]{8})?$/) !== null, 'format '.concat($('head meta[name="build-info"]').attr('content'), ' is correct') ); });
39cc7b2b8521294d96d5d76b08773abe3739dd54
addon/adapters/web-api.js
addon/adapters/web-api.js
import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api', ajaxError: function(_, response) { return new DS.InvalidError(JSON.parse(response)); } });
import DS from 'ember-data'; const VALIDATION_ERROR_STATUSES = [400, 422]; export default DS.RESTAdapter.extend({ namespace: 'api', ajaxError: function(xhr, response) { let error = this._super(xhr); if(!error || VALIDATION_ERROR_STATUSES.indexOf(error.status) < 0) { return error; } return new DS.InvalidError(JSON.parse(response)); } });
Modify the adapter to only catch 400 and 422 responses as model validation errors
Modify the adapter to only catch 400 and 422 responses as model validation errors
JavaScript
mit
CrshOverride/ember-web-api,CrshOverride/ember-web-api
--- +++ @@ -1,9 +1,17 @@ import DS from 'ember-data'; + +const VALIDATION_ERROR_STATUSES = [400, 422]; export default DS.RESTAdapter.extend({ namespace: 'api', - ajaxError: function(_, response) { + ajaxError: function(xhr, response) { + let error = this._super(xhr); + + if(!error || VALIDATION_ERROR_STATUSES.indexOf(error.status) < 0) { + return error; + } + return new DS.InvalidError(JSON.parse(response)); } });
da648c56dc3098744d3316bfe5e38048c4c961b4
test/app.js
test/app.js
'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-drizzle:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({someAnswer: true}) .on('end', done); }); it('creates files', function () { assert.file([ 'dummyfile.txt' ]); }); });
/* eslint-env mocha */ 'use strict'; const path = require('path'); const assert = require('yeoman-assert'); const helpers = require('yeoman-test'); describe('generator-drizzle:app', () => { before(done => { helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({someAnswer: true}) .on('end', done); }); it('creates files', () => { assert.file([ 'dummyfile.txt' ]); }); });
Make stylistic changes to test file
Make stylistic changes to test file
JavaScript
mit
cloudfour/generator-drizzle
--- +++ @@ -1,16 +1,19 @@ +/* eslint-env mocha */ + 'use strict'; -var path = require('path'); -var assert = require('yeoman-assert'); -var helpers = require('yeoman-test'); -describe('generator-drizzle:app', function () { - before(function (done) { +const path = require('path'); +const assert = require('yeoman-assert'); +const helpers = require('yeoman-test'); + +describe('generator-drizzle:app', () => { + before(done => { helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({someAnswer: true}) .on('end', done); }); - it('creates files', function () { + it('creates files', () => { assert.file([ 'dummyfile.txt' ]);
84e170852786e21a990da636501e8ddaf459be6c
examples/simple.js
examples/simple.js
var injector = require('../'); var app = injector(); app.value('port', 8080); app.post('/greet/:name/:age', function(req, res) { res.write('hello ' + req.params.name + ' age ' + req.params.age); res.end(); }); app.listen(app.value('port'));
var injector = require('../'); var app = injector(); app.value('port', 8080); app.get('/greet/:name/:age', function(req, res) { res.write('hello ' + req.params.name + ' age ' + req.params.age); res.end(); }); app.listen(app.value('port'));
Switch sample to use a GET instead of POST handler
Switch sample to use a GET instead of POST handler
JavaScript
mit
itsananderson/molded
--- +++ @@ -4,7 +4,7 @@ app.value('port', 8080); -app.post('/greet/:name/:age', function(req, res) { +app.get('/greet/:name/:age', function(req, res) { res.write('hello ' + req.params.name + ' age ' + req.params.age); res.end();
312ce603a97e7befa5e666604c1dc18e0a767c1c
public/tutorial/index.js
public/tutorial/index.js
define( ["jquery"], function($) { function Tutorial(steps, content) { var _this = this; var currentIdx; function show(idx) { var step = steps[idx]; if (step.init) step.init.apply(_this); step.$content = $('[data-step="' + step.name + '"]', content); step.$content.dialog({ dialogClass: [].concat("tutorial-dialog", step.dialogClass || []).join(' '), maxWidth: 300, modal: false, resizable: false, position: step.position }); } function hide(idx) { var step = steps[idx]; if (step.destroy) step.destroy.apply(_this); step.$content.dialog('destroy'); } this.start = function() { currentIdx = 0; show(currentIdx); }; this.next = function() { if (currentIdx >= steps.length) return; hide(currentIdx); currentIdx++; if (currentIdx < steps.length) show(currentIdx); } this.end = function() { hide(currentIdx); currentIdx = steps.length; }; $('.tutorial-next', content).click(function () { _this.next(); return false; }); $('.tutorial-end', content).click(function () { _this.end(); return false; }); return this; }; return Tutorial; } );
define( ["jquery"], function($) { function Tutorial(steps, content) { var _this = this; var currentIdx; function show(idx) { var step = steps[idx]; if (step.init) step.init.apply(_this); step.$content = $('[data-step="' + step.name + '"]', content); step.$content.dialog({ dialogClass: [].concat("tutorial-dialog", step.dialogClass || []).join(' '), maxWidth: 300, modal: false, resizable: false, position: step.position }); step.resize = function resize() { step.$content.dialog("option", "position", step.position); }; $(window).on('resize', step.resize); } function hide(idx) { var step = steps[idx]; if (step.destroy) step.destroy.apply(_this); step.$content.dialog('destroy'); $(window).off('resize', step.resize); } this.start = function() { currentIdx = 0; show(currentIdx); }; this.next = function() { if (currentIdx >= steps.length) return; hide(currentIdx); currentIdx++; if (currentIdx < steps.length) show(currentIdx); } this.end = function() { hide(currentIdx); currentIdx = steps.length; }; $('.tutorial-next', content).click(function () { _this.next(); return false; }); $('.tutorial-end', content).click(function () { _this.end(); return false; }); return this; }; return Tutorial; } );
Reposition tooltips when window is resized
Reposition tooltips when window is resized
JavaScript
mpl-2.0
ekospinach/appmaker,uche40/appmaker,nirdeshdwa/appmaker,secretrobotron/appmaker,uche40/appmaker,valmzetvn/appmaker,lexoyo/appmaker,pcoughlin/appmaker,sheafferusa/appmaker,vaginessa/appmaker,lexoyo/appmaker,lexoyo/appmaker,vaginessa/appmaker,sheafferusa/appmaker,ekospinach/appmaker,ekospinach/appmaker,sheafferusa/appmaker,pcoughlin/appmaker,valmzetvn/appmaker,mozilla-appmaker/appmaker,nirdeshdwa/appmaker,pcoughlin/appmaker,vaginessa/appmaker,secretrobotron/appmaker,nirdeshdwa/appmaker,uche40/appmaker,mozilla-appmaker/appmaker,valmzetvn/appmaker,mozilla-appmaker/appmaker
--- +++ @@ -16,12 +16,17 @@ resizable: false, position: step.position }); + step.resize = function resize() { + step.$content.dialog("option", "position", step.position); + }; + $(window).on('resize', step.resize); } function hide(idx) { var step = steps[idx]; if (step.destroy) step.destroy.apply(_this); step.$content.dialog('destroy'); + $(window).off('resize', step.resize); } this.start = function() {
f19722e7d14b1de3594f3bdfb42e4509a8606c40
client/templates/projects/project_item.js
client/templates/projects/project_item.js
Template.projectItem.helpers({ canJoinProject: function(userId, projectId) { var projectOwnerOrMember = Projects.find({ $or: [{ 'owner.userId': userId, _id: projectId}, { members: { $elemMatch: { userId: userId } } } ] } ); return projectOwnerOrMember.count() === 0 && Meteor.userId(); } });
Template.projectItem.helpers({ canJoinProject: function(userId, projectId) { var projectOwnerOrMember = Projects.find({ $or: [{ 'owner.userId': userId, _id: projectId}, { members: { $elemMatch: { userId: userId } } } ] } ); return projectOwnerOrMember.count() === 0 && Meteor.userId(); } }); Template.projectItem.events({ 'click .join-button': function(e) { e.preventDefault(); var request = { user: { userId: Meteor.userId(), username: Meteor.user().username }, project: { name: this.name, projectId: this._id, ownerId: this.owner.userId } }; Meteor.call('addRequest', request, function (err, result) { if (err) { } else { Router.go('projectPage', this._id); } }); } });
Add click action to project item template when clicking Join
Add click action to project item template when clicking Join
JavaScript
mit
PUMATeam/puma,PUMATeam/puma
--- +++ @@ -20,3 +20,29 @@ return projectOwnerOrMember.count() === 0 && Meteor.userId(); } }); + +Template.projectItem.events({ + 'click .join-button': function(e) { + e.preventDefault(); + var request = { + user: { + userId: Meteor.userId(), + username: Meteor.user().username + }, + project: { + name: this.name, + projectId: this._id, + ownerId: this.owner.userId + } + }; + + Meteor.call('addRequest', request, function (err, result) { + if (err) { + + } else { + Router.go('projectPage', this._id); + } + }); + + } +});
30735514ce9ef7f9aff46c77ac417dbb5b79a4ec
src/gelato.js
src/gelato.js
'use strict'; if ($ === undefined) { throw 'Gelato requires jQuery as a dependency.' } else { window.jQuery = window.$ = $; } if (_ === undefined) { throw 'Gelato requires Lodash as a dependency.' } else { window._ = _; } if (Backbone === undefined) { throw 'Gelato requires Backbone as a dependency.' } else { window.Backbone = Backbone; } var Gelato = {}; Gelato._BUILD = '{!date!}'; Gelato._VERSION = '{!version!}'; Gelato.isLocalhost = function() { return location.hostname === 'localhost'; }; Gelato.isWebsite = function() { return location.protocol.indexOf('http') > -1; };
'use strict'; if ($ === undefined) { throw 'Gelato requires jQuery as a dependency.' } else { window.jQuery = window.$ = $; } if (_ === undefined) { throw 'Gelato requires Lodash as a dependency.' } else { window._ = _; } if (Backbone === undefined) { throw 'Gelato requires Backbone as a dependency.' } else { window.Backbone = Backbone; } var Gelato = {}; Gelato._BUILD = '{!date!}'; Gelato._VERSION = '{!version!}'; Gelato.isLocalhost = function() { return location.hostname === 'localhost'; }; Gelato.isWebsite = function() { return _.includes(location.protocol, 'http'); };
Use lodash includes when testing for http string.
Use lodash includes when testing for http string.
JavaScript
mit
mcfarljw/backbone-gelato,mcfarljw/gelato-framework,jernung/gelato,mcfarljw/gelato-framework,mcfarljw/backbone-gelato,jernung/gelato
--- +++ @@ -29,5 +29,5 @@ }; Gelato.isWebsite = function() { - return location.protocol.indexOf('http') > -1; + return _.includes(location.protocol, 'http'); };
a3d113f35e6f4d429fb9a0c65dc23375dba0b38b
frontend/src/scenes/SplashScreen/index.js
frontend/src/scenes/SplashScreen/index.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Button, Container, Input } from 'rebass'; import { actions } from '../../redux/players'; import HomeLayout from './components/HomeLayout'; class SplashScreen extends Component { play = e => { if (this._username !== undefined) { this.props.chooseUsername(this._username); } }; render() { return ( <HomeLayout> <Container> <Input name="username" label="Username" placeholder="Username" hideLabel onChange={e => (this._username = e.target.value)} /> <Button backgroundColor="primary" color="white" big onClick={this.play}> PLAY NOW! </Button> </Container> </HomeLayout> ); } } const mapStateToProps = state => ({}); const mapDispatchToProps = { chooseUsername: actions.chooseUsername, }; export default connect(mapStateToProps, mapDispatchToProps)(SplashScreen);
// @flow import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Container } from 'rebass'; import { actions } from '../../redux/players'; import { InputGroup, Button, Classes, Intent } from '@blueprintjs/core'; import HomeLayout from './components/HomeLayout'; class SplashScreen extends Component { _username = ''; play = e => { e.preventDefault(); if (this._username !== undefined) { this.props.chooseUsername(this._username); } }; render() { return ( <HomeLayout> <Container> <form onSubmit={this.play}> <InputGroup placeholder="Username" onChange={e => (this._username = e.target.value)} rightElement={this.renderSubmit()} /> </form> </Container> </HomeLayout> ); } renderSubmit = () => ( <Button className={Classes.MINIMAL} onClick={this.play} intent={Intent.PRIMARY} rightIconName="arrow-right" /> ); } const mapDispatchToProps = { chooseUsername: actions.chooseUsername, }; export default connect(null, mapDispatchToProps)(SplashScreen);
Change username input to use blueprint
Change username input to use blueprint
JavaScript
mit
luxons/seven-wonders,luxons/seven-wonders,luxons/seven-wonders
--- +++ @@ -1,12 +1,17 @@ +// @flow import React, { Component } from 'react'; import { connect } from 'react-redux'; -import { Button, Container, Input } from 'rebass'; +import { Container } from 'rebass'; import { actions } from '../../redux/players'; +import { InputGroup, Button, Classes, Intent } from '@blueprintjs/core'; import HomeLayout from './components/HomeLayout'; class SplashScreen extends Component { + _username = ''; + play = e => { + e.preventDefault(); if (this._username !== undefined) { this.props.chooseUsername(this._username); } @@ -16,26 +21,25 @@ return ( <HomeLayout> <Container> - <Input - name="username" - label="Username" - placeholder="Username" - hideLabel - onChange={e => (this._username = e.target.value)} - /> - <Button backgroundColor="primary" color="white" big onClick={this.play}> - PLAY NOW! - </Button> + <form onSubmit={this.play}> + <InputGroup + placeholder="Username" + onChange={e => (this._username = e.target.value)} + rightElement={this.renderSubmit()} + /> + </form> </Container> </HomeLayout> ); } + + renderSubmit = () => ( + <Button className={Classes.MINIMAL} onClick={this.play} intent={Intent.PRIMARY} rightIconName="arrow-right" /> + ); } - -const mapStateToProps = state => ({}); const mapDispatchToProps = { chooseUsername: actions.chooseUsername, }; -export default connect(mapStateToProps, mapDispatchToProps)(SplashScreen); +export default connect(null, mapDispatchToProps)(SplashScreen);
a872d24aff37f907d8c22b39b968c8121ed5213b
clipboard.js
clipboard.js
var clipboard = {}; clipboard.copy = (function() { var _intercept = false; var _data; // Map from data type (e.g. "text/html") to value. document.addEventListener("copy", function(e){ if (_intercept) { for (key in _data) { e.clipboardData.setData(key, _data[key]); } e.preventDefault(); } }); return function(data) { _intercept = true; _data = (typeof data === "string" ? {"text/plain": data} : data); document.execCommand("copy"); _intercept = false; }; }()); clipboard.paste = (function() { var _intercept = false; var _resolve; var _dataType; document.addEventListener("paste", function(e) { if (_intercept) { _intercept = false; e.preventDefault(); _resolve(e.clipboardData.getData(_dataType)); } }); return function(dataType) { return new Promise(function(resolve, reject) { _intercept = true; // Race condition? _resolve = resolve; _dataType = dataType || "text/plain"; document.execCommand("paste"); }); }; }());
var clipboard = {}; clipboard.copy = (function() { var _intercept = false; var _data; // Map from data type (e.g. "text/html") to value. document.addEventListener("copy", function(e){ if (_intercept) { for (var key in _data) { e.clipboardData.setData(key, _data[key]); } e.preventDefault(); } }); return function(data) { _intercept = true; _data = (typeof data === "string" ? {"text/plain": data} : data); document.execCommand("copy"); _intercept = false; }; }()); clipboard.paste = (function() { var _intercept = false; var _resolve; var _dataType; document.addEventListener("paste", function(e) { if (_intercept) { _intercept = false; e.preventDefault(); _resolve(e.clipboardData.getData(_dataType)); } }); return function(dataType) { return new Promise(function(resolve, reject) { _intercept = true; // Race condition? _resolve = resolve; _dataType = dataType || "text/plain"; document.execCommand("paste"); }); }; }());
Add missing `var` declaration for "use strict";
Add missing `var` declaration for "use strict";
JavaScript
mit
Coolaxer/clipboard.js,Zimbra/clipboard.js,Zimbra/clipboard.js,Coolaxer/clipboard.js
--- +++ @@ -6,7 +6,7 @@ document.addEventListener("copy", function(e){ if (_intercept) { - for (key in _data) { + for (var key in _data) { e.clipboardData.setData(key, _data[key]); } e.preventDefault();
d2911a29a82bd2b053fd09c7909012fc091ddd4a
book.js
book.js
module.exports = { "root": "./protocol-spec" }; // Only add piwik if we're building on the CI and deploying if (process.env.CI) { module.exports["plugins"] = ["piwik", "mermaid-gb3"]; module.exports["pluginsConfig"] = { "piwik": { "URL": "apps.nonpolynomial.com/p/", "siteId": 7, "phpPath": "js/", "jsPath": "js/" } }; }
module.exports = { "root": "./protocol-spec" }; module.exports["plugins"] = ["mermaid-gb3"]; // Only add piwik if we're building on the CI and deploying if (process.env.CI) { module.exports["plugins"].push("piwik"); module.exports["pluginsConfig"] = { "piwik": { "URL": "apps.nonpolynomial.com/p/", "siteId": 7, "phpPath": "js/", "jsPath": "js/" } }; }
Fix mermaid plugin config inclusion
Fix mermaid plugin config inclusion Config changed a lot while adding piwik
JavaScript
bsd-3-clause
metafetish/buttplug
--- +++ @@ -1,8 +1,9 @@ module.exports = { "root": "./protocol-spec" }; +module.exports["plugins"] = ["mermaid-gb3"]; // Only add piwik if we're building on the CI and deploying if (process.env.CI) { - module.exports["plugins"] = ["piwik", "mermaid-gb3"]; + module.exports["plugins"].push("piwik"); module.exports["pluginsConfig"] = { "piwik": { "URL": "apps.nonpolynomial.com/p/",
45945d92e124f9e91ad3afdcfac068e2126e692b
src/config.js
src/config.js
let dotAnsel = `${process.env.HOME}/.ansel`; if (process.env.ANSEL_DEV_MODE) dotAnsel = `${process.env.INIT_CWD}/dot-ansel`; export default { characters: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZéè', acceptedRawFormats: [ 'raf', 'cr2', 'arw', 'dng' ], acceptedImgFormats: [ 'png', 'jpg', 'jpeg', 'tif', 'tiff' ], watchedFormats: /([\$\#\w\d]+)-([\$\#\w\dèé]+)-(\d+)\.(JPEG|JPG|PNG|PPM)/i, dotAnsel, dbFile: `${dotAnsel}/db.sqlite3`, settings: `${dotAnsel}/settings.json`, thumbsPath: `${dotAnsel}/thumbs`, thumbs250Path: `${dotAnsel}/thumbs-250`, tmp: '/tmp/ansel', concurrency: 5 };
let dotAnsel = `${process.env.HOME}/.ansel`; if (process.env.ANSEL_DEV_MODE) dotAnsel = `${process.env.INIT_CWD}/dot-ansel`; export default { characters: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZéè', acceptedRawFormats: [ 'raf', 'cr2', 'arw', 'dng' ], acceptedImgFormats: [ 'png', 'jpg', 'jpeg', 'tif', 'tiff' ], watchedFormats: /([\$\#\w\d]+)-([\$\#\w\dèé]+)-(\d+)\.(JPEG|JPG|PNG|PPM)/i, dotAnsel, dbFile: `${dotAnsel}/db.sqlite3`, settings: `${dotAnsel}/settings.json`, thumbsPath: `${dotAnsel}/thumbs`, thumbs250Path: `${dotAnsel}/thumbs-250`, tmp: '/tmp/ansel', concurrency: 3 };
Reduce concurrency level to 3 for accomodating acient thinkpad
Reduce concurrency level to 3 for accomodating acient thinkpad
JavaScript
mit
m0g/ansel,m0g/ansel,m0g/ansel,m0g/ansel
--- +++ @@ -14,5 +14,5 @@ thumbsPath: `${dotAnsel}/thumbs`, thumbs250Path: `${dotAnsel}/thumbs-250`, tmp: '/tmp/ansel', - concurrency: 5 + concurrency: 3 };
6296624a9f5e95aeec68e6c7afe6b1c70496773a
src/main.js
src/main.js
'use babel' import {transform} from 'babel-core' import Path from 'path' export const compiler = true export const minifier = false export function process(contents, {fileName, relativePath}, {config, state}) { const beginning = contents.substr(0, 11) if (beginning !== '"use babel"' && beginning !== "'use babel'") { return contents } const transpiled = transform(contents, Object.assign({}, config.babel, { filename: fileName, filenameRelative: relativePath, sourceRoot: Path.join('sources', Path.dirname(relativePath)), sourceMaps: true, highlightCode: false })) state.sourceMap = transpiled.map return transpiled.code }
'use babel' import {transform} from 'babel-core' import Path from 'path' export const compiler = true export const minifier = false export function process(contents, {rootDirectory, filePath, config}) { const beginning = contents.substr(0, 11) if (beginning !== '"use babel"' && beginning !== "'use babel'") { return null } const fileName = Path.dirname(filePath) const relativePath = Path.relative(rootDirectory, filePath) const transpiled = transform(contents, Object.assign({}, config.babel, { filename: fileName, filenameRelative: relativePath, sourceRoot: rootDirectory, sourceMaps: true, highlightCode: false })) return { contents: transpiled.code, sourceMap: transpiled.map } }
Upgrade package to latest ucompiler API
:arrow_up: Upgrade package to latest ucompiler API
JavaScript
mit
steelbrain/ucompiler-plugin-babel
--- +++ @@ -5,19 +5,23 @@ export const compiler = true export const minifier = false -export function process(contents, {fileName, relativePath}, {config, state}) { +export function process(contents, {rootDirectory, filePath, config}) { const beginning = contents.substr(0, 11) if (beginning !== '"use babel"' && beginning !== "'use babel'") { - return contents + return null } + const fileName = Path.dirname(filePath) + const relativePath = Path.relative(rootDirectory, filePath) const transpiled = transform(contents, Object.assign({}, config.babel, { filename: fileName, filenameRelative: relativePath, - sourceRoot: Path.join('sources', Path.dirname(relativePath)), + sourceRoot: rootDirectory, sourceMaps: true, highlightCode: false })) - state.sourceMap = transpiled.map - return transpiled.code + return { + contents: transpiled.code, + sourceMap: transpiled.map + } }
ed9365d506c30a93a2550b0765ac7c2e57a565d1
src/option.js
src/option.js
module.exports = { Some: (value) => Object({ value, hasValue: true }), None: Object() }
module.exports = { Some: (value) => ({ value, hasValue: true }), None: {}, }
Use object literal syntax instead of Object constructor
Use object literal syntax instead of Object constructor
JavaScript
apache-2.0
leonardiwagner/z,z-pattern-matching/z,leonardiwagner/npm-z
--- +++ @@ -1,4 +1,4 @@ module.exports = { - Some: (value) => Object({ value, hasValue: true }), - None: Object() + Some: (value) => ({ value, hasValue: true }), + None: {}, }